rookery-agent 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (508) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +367 -0
  3. package/docs/migration.md +88 -0
  4. package/package.json +39 -0
  5. package/packages/cli/dist/commands/chat.d.ts +52 -0
  6. package/packages/cli/dist/commands/chat.d.ts.map +1 -0
  7. package/packages/cli/dist/commands/chat.js +107 -0
  8. package/packages/cli/dist/commands/chat.js.map +1 -0
  9. package/packages/cli/dist/commands/config.d.ts +12 -0
  10. package/packages/cli/dist/commands/config.d.ts.map +1 -0
  11. package/packages/cli/dist/commands/config.js +156 -0
  12. package/packages/cli/dist/commands/config.js.map +1 -0
  13. package/packages/cli/dist/commands/doctor.d.ts +12 -0
  14. package/packages/cli/dist/commands/doctor.d.ts.map +1 -0
  15. package/packages/cli/dist/commands/doctor.js +137 -0
  16. package/packages/cli/dist/commands/doctor.js.map +1 -0
  17. package/packages/cli/dist/commands/memory.d.ts +34 -0
  18. package/packages/cli/dist/commands/memory.d.ts.map +1 -0
  19. package/packages/cli/dist/commands/memory.js +133 -0
  20. package/packages/cli/dist/commands/memory.js.map +1 -0
  21. package/packages/cli/dist/commands/org.d.ts +93 -0
  22. package/packages/cli/dist/commands/org.d.ts.map +1 -0
  23. package/packages/cli/dist/commands/org.js +389 -0
  24. package/packages/cli/dist/commands/org.js.map +1 -0
  25. package/packages/cli/dist/commands/serve.d.ts +13 -0
  26. package/packages/cli/dist/commands/serve.d.ts.map +1 -0
  27. package/packages/cli/dist/commands/serve.js +100 -0
  28. package/packages/cli/dist/commands/serve.js.map +1 -0
  29. package/packages/cli/dist/commands/sessions.d.ts +18 -0
  30. package/packages/cli/dist/commands/sessions.d.ts.map +1 -0
  31. package/packages/cli/dist/commands/sessions.js +88 -0
  32. package/packages/cli/dist/commands/sessions.js.map +1 -0
  33. package/packages/cli/dist/commands/shared.d.ts +59 -0
  34. package/packages/cli/dist/commands/shared.d.ts.map +1 -0
  35. package/packages/cli/dist/commands/shared.js +230 -0
  36. package/packages/cli/dist/commands/shared.js.map +1 -0
  37. package/packages/cli/dist/commands/tasks.d.ts +62 -0
  38. package/packages/cli/dist/commands/tasks.d.ts.map +1 -0
  39. package/packages/cli/dist/commands/tasks.js +262 -0
  40. package/packages/cli/dist/commands/tasks.js.map +1 -0
  41. package/packages/cli/dist/commands/tools.d.ts +8 -0
  42. package/packages/cli/dist/commands/tools.d.ts.map +1 -0
  43. package/packages/cli/dist/commands/tools.js +65 -0
  44. package/packages/cli/dist/commands/tools.js.map +1 -0
  45. package/packages/cli/dist/index.d.ts +15 -0
  46. package/packages/cli/dist/index.d.ts.map +1 -0
  47. package/packages/cli/dist/index.js +513 -0
  48. package/packages/cli/dist/index.js.map +1 -0
  49. package/packages/cli/dist/repl.d.ts +29 -0
  50. package/packages/cli/dist/repl.d.ts.map +1 -0
  51. package/packages/cli/dist/repl.js +634 -0
  52. package/packages/cli/dist/repl.js.map +1 -0
  53. package/packages/cli/dist/tui/App.d.ts +51 -0
  54. package/packages/cli/dist/tui/App.d.ts.map +1 -0
  55. package/packages/cli/dist/tui/App.js +461 -0
  56. package/packages/cli/dist/tui/App.js.map +1 -0
  57. package/packages/cli/dist/tui/commands.d.ts +34 -0
  58. package/packages/cli/dist/tui/commands.d.ts.map +1 -0
  59. package/packages/cli/dist/tui/commands.js +367 -0
  60. package/packages/cli/dist/tui/commands.js.map +1 -0
  61. package/packages/cli/dist/tui/components/ActivityLine.d.ts +16 -0
  62. package/packages/cli/dist/tui/components/ActivityLine.d.ts.map +1 -0
  63. package/packages/cli/dist/tui/components/ActivityLine.js +7 -0
  64. package/packages/cli/dist/tui/components/ActivityLine.js.map +1 -0
  65. package/packages/cli/dist/tui/components/AssignmentsView.d.ts +31 -0
  66. package/packages/cli/dist/tui/components/AssignmentsView.d.ts.map +1 -0
  67. package/packages/cli/dist/tui/components/AssignmentsView.js +79 -0
  68. package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -0
  69. package/packages/cli/dist/tui/components/Banner.d.ts +18 -0
  70. package/packages/cli/dist/tui/components/Banner.d.ts.map +1 -0
  71. package/packages/cli/dist/tui/components/Banner.js +16 -0
  72. package/packages/cli/dist/tui/components/Banner.js.map +1 -0
  73. package/packages/cli/dist/tui/components/CodeBlock.d.ts +19 -0
  74. package/packages/cli/dist/tui/components/CodeBlock.d.ts.map +1 -0
  75. package/packages/cli/dist/tui/components/CodeBlock.js +21 -0
  76. package/packages/cli/dist/tui/components/CodeBlock.js.map +1 -0
  77. package/packages/cli/dist/tui/components/InputBox.d.ts +25 -0
  78. package/packages/cli/dist/tui/components/InputBox.d.ts.map +1 -0
  79. package/packages/cli/dist/tui/components/InputBox.js +35 -0
  80. package/packages/cli/dist/tui/components/InputBox.js.map +1 -0
  81. package/packages/cli/dist/tui/components/Markdown.d.ts +74 -0
  82. package/packages/cli/dist/tui/components/Markdown.d.ts.map +1 -0
  83. package/packages/cli/dist/tui/components/Markdown.js +293 -0
  84. package/packages/cli/dist/tui/components/Markdown.js.map +1 -0
  85. package/packages/cli/dist/tui/components/Message.d.ts +29 -0
  86. package/packages/cli/dist/tui/components/Message.d.ts.map +1 -0
  87. package/packages/cli/dist/tui/components/Message.js +28 -0
  88. package/packages/cli/dist/tui/components/Message.js.map +1 -0
  89. package/packages/cli/dist/tui/components/Scrollback.d.ts +23 -0
  90. package/packages/cli/dist/tui/components/Scrollback.d.ts.map +1 -0
  91. package/packages/cli/dist/tui/components/Scrollback.js +36 -0
  92. package/packages/cli/dist/tui/components/Scrollback.js.map +1 -0
  93. package/packages/cli/dist/tui/components/SlashPalette.d.ts +17 -0
  94. package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -0
  95. package/packages/cli/dist/tui/components/SlashPalette.js +19 -0
  96. package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -0
  97. package/packages/cli/dist/tui/components/StatusLine.d.ts +61 -0
  98. package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -0
  99. package/packages/cli/dist/tui/components/StatusLine.js +55 -0
  100. package/packages/cli/dist/tui/components/StatusLine.js.map +1 -0
  101. package/packages/cli/dist/tui/components/ToolGroup.d.ts +33 -0
  102. package/packages/cli/dist/tui/components/ToolGroup.d.ts.map +1 -0
  103. package/packages/cli/dist/tui/components/ToolGroup.js +52 -0
  104. package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -0
  105. package/packages/cli/dist/tui/components/Wordmark.d.ts +35 -0
  106. package/packages/cli/dist/tui/components/Wordmark.d.ts.map +1 -0
  107. package/packages/cli/dist/tui/components/Wordmark.js +81 -0
  108. package/packages/cli/dist/tui/components/Wordmark.js.map +1 -0
  109. package/packages/cli/dist/tui/highlight.d.ts +29 -0
  110. package/packages/cli/dist/tui/highlight.d.ts.map +1 -0
  111. package/packages/cli/dist/tui/highlight.js +137 -0
  112. package/packages/cli/dist/tui/highlight.js.map +1 -0
  113. package/packages/cli/dist/tui/hooks/useColumns.d.ts +20 -0
  114. package/packages/cli/dist/tui/hooks/useColumns.d.ts.map +1 -0
  115. package/packages/cli/dist/tui/hooks/useColumns.js +38 -0
  116. package/packages/cli/dist/tui/hooks/useColumns.js.map +1 -0
  117. package/packages/cli/dist/tui/hooks/useHistory.d.ts +21 -0
  118. package/packages/cli/dist/tui/hooks/useHistory.d.ts.map +1 -0
  119. package/packages/cli/dist/tui/hooks/useHistory.js +57 -0
  120. package/packages/cli/dist/tui/hooks/useHistory.js.map +1 -0
  121. package/packages/cli/dist/tui/hooks/useSlash.d.ts +38 -0
  122. package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -0
  123. package/packages/cli/dist/tui/hooks/useSlash.js +89 -0
  124. package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -0
  125. package/packages/cli/dist/tui/hooks/useTurn.d.ts +75 -0
  126. package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -0
  127. package/packages/cli/dist/tui/hooks/useTurn.js +396 -0
  128. package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -0
  129. package/packages/cli/dist/tui/theme.d.ts +126 -0
  130. package/packages/cli/dist/tui/theme.d.ts.map +1 -0
  131. package/packages/cli/dist/tui/theme.js +127 -0
  132. package/packages/cli/dist/tui/theme.js.map +1 -0
  133. package/packages/cli/dist/tui/types.d.ts +205 -0
  134. package/packages/cli/dist/tui/types.d.ts.map +1 -0
  135. package/packages/cli/dist/tui/types.js +55 -0
  136. package/packages/cli/dist/tui/types.js.map +1 -0
  137. package/packages/cli/dist/ui/render.d.ts +74 -0
  138. package/packages/cli/dist/ui/render.d.ts.map +1 -0
  139. package/packages/cli/dist/ui/render.js +349 -0
  140. package/packages/cli/dist/ui/render.js.map +1 -0
  141. package/packages/cli/dist/ui/speech.d.ts +42 -0
  142. package/packages/cli/dist/ui/speech.d.ts.map +1 -0
  143. package/packages/cli/dist/ui/speech.js +257 -0
  144. package/packages/cli/dist/ui/speech.js.map +1 -0
  145. package/packages/cli/dist/ui/spinner.d.ts +17 -0
  146. package/packages/cli/dist/ui/spinner.d.ts.map +1 -0
  147. package/packages/cli/dist/ui/spinner.js +61 -0
  148. package/packages/cli/dist/ui/spinner.js.map +1 -0
  149. package/packages/cli/dist/ui/theme.d.ts +54 -0
  150. package/packages/cli/dist/ui/theme.d.ts.map +1 -0
  151. package/packages/cli/dist/ui/theme.js +74 -0
  152. package/packages/cli/dist/ui/theme.js.map +1 -0
  153. package/packages/cli/package.json +1 -0
  154. package/packages/core/dist/agents/legacy-persona.d.ts +4 -0
  155. package/packages/core/dist/agents/legacy-persona.d.ts.map +1 -0
  156. package/packages/core/dist/agents/legacy-persona.js +39 -0
  157. package/packages/core/dist/agents/legacy-persona.js.map +1 -0
  158. package/packages/core/dist/agents/orchestrator.d.ts +24 -0
  159. package/packages/core/dist/agents/orchestrator.d.ts.map +1 -0
  160. package/packages/core/dist/agents/orchestrator.js +88 -0
  161. package/packages/core/dist/agents/orchestrator.js.map +1 -0
  162. package/packages/core/dist/agents/persona.d.ts +56 -0
  163. package/packages/core/dist/agents/persona.d.ts.map +1 -0
  164. package/packages/core/dist/agents/persona.js +153 -0
  165. package/packages/core/dist/agents/persona.js.map +1 -0
  166. package/packages/core/dist/agents/roles.d.ts +21 -0
  167. package/packages/core/dist/agents/roles.d.ts.map +1 -0
  168. package/packages/core/dist/agents/roles.js +81 -0
  169. package/packages/core/dist/agents/roles.js.map +1 -0
  170. package/packages/core/dist/agents/team.d.ts +105 -0
  171. package/packages/core/dist/agents/team.d.ts.map +1 -0
  172. package/packages/core/dist/agents/team.js +623 -0
  173. package/packages/core/dist/agents/team.js.map +1 -0
  174. package/packages/core/dist/computer/keys.d.ts +12 -0
  175. package/packages/core/dist/computer/keys.d.ts.map +1 -0
  176. package/packages/core/dist/computer/keys.js +56 -0
  177. package/packages/core/dist/computer/keys.js.map +1 -0
  178. package/packages/core/dist/computer/mcp-server.d.ts +11 -0
  179. package/packages/core/dist/computer/mcp-server.d.ts.map +1 -0
  180. package/packages/core/dist/computer/mcp-server.js +228 -0
  181. package/packages/core/dist/computer/mcp-server.js.map +1 -0
  182. package/packages/core/dist/computer/powershell.d.ts +13 -0
  183. package/packages/core/dist/computer/powershell.d.ts.map +1 -0
  184. package/packages/core/dist/computer/powershell.js +359 -0
  185. package/packages/core/dist/computer/powershell.js.map +1 -0
  186. package/packages/core/dist/computer/tools.d.ts +43 -0
  187. package/packages/core/dist/computer/tools.d.ts.map +1 -0
  188. package/packages/core/dist/computer/tools.js +260 -0
  189. package/packages/core/dist/computer/tools.js.map +1 -0
  190. package/packages/core/dist/config.d.ts +32 -0
  191. package/packages/core/dist/config.d.ts.map +1 -0
  192. package/packages/core/dist/config.js +329 -0
  193. package/packages/core/dist/config.js.map +1 -0
  194. package/packages/core/dist/cron/parse.d.ts +52 -0
  195. package/packages/core/dist/cron/parse.d.ts.map +1 -0
  196. package/packages/core/dist/cron/parse.js +277 -0
  197. package/packages/core/dist/cron/parse.js.map +1 -0
  198. package/packages/core/dist/cron/scheduler.d.ts +102 -0
  199. package/packages/core/dist/cron/scheduler.d.ts.map +1 -0
  200. package/packages/core/dist/cron/scheduler.js +334 -0
  201. package/packages/core/dist/cron/scheduler.js.map +1 -0
  202. package/packages/core/dist/cron/script.d.ts +9 -0
  203. package/packages/core/dist/cron/script.d.ts.map +1 -0
  204. package/packages/core/dist/cron/script.js +113 -0
  205. package/packages/core/dist/cron/script.js.map +1 -0
  206. package/packages/core/dist/cron/store.d.ts +77 -0
  207. package/packages/core/dist/cron/store.d.ts.map +1 -0
  208. package/packages/core/dist/cron/store.js +229 -0
  209. package/packages/core/dist/cron/store.js.map +1 -0
  210. package/packages/core/dist/gateway/policy.d.ts +113 -0
  211. package/packages/core/dist/gateway/policy.d.ts.map +1 -0
  212. package/packages/core/dist/gateway/policy.js +373 -0
  213. package/packages/core/dist/gateway/policy.js.map +1 -0
  214. package/packages/core/dist/index.d.ts +45 -0
  215. package/packages/core/dist/index.d.ts.map +1 -0
  216. package/packages/core/dist/index.js +52 -0
  217. package/packages/core/dist/index.js.map +1 -0
  218. package/packages/core/dist/logger.d.ts +21 -0
  219. package/packages/core/dist/logger.d.ts.map +1 -0
  220. package/packages/core/dist/logger.js +61 -0
  221. package/packages/core/dist/logger.js.map +1 -0
  222. package/packages/core/dist/memory/db.d.ts +12 -0
  223. package/packages/core/dist/memory/db.d.ts.map +1 -0
  224. package/packages/core/dist/memory/db.js +414 -0
  225. package/packages/core/dist/memory/db.js.map +1 -0
  226. package/packages/core/dist/memory/extractor.d.ts +35 -0
  227. package/packages/core/dist/memory/extractor.d.ts.map +1 -0
  228. package/packages/core/dist/memory/extractor.js +159 -0
  229. package/packages/core/dist/memory/extractor.js.map +1 -0
  230. package/packages/core/dist/memory/gate.d.ts +68 -0
  231. package/packages/core/dist/memory/gate.d.ts.map +1 -0
  232. package/packages/core/dist/memory/gate.js +163 -0
  233. package/packages/core/dist/memory/gate.js.map +1 -0
  234. package/packages/core/dist/memory/recall.d.ts +61 -0
  235. package/packages/core/dist/memory/recall.d.ts.map +1 -0
  236. package/packages/core/dist/memory/recall.js +342 -0
  237. package/packages/core/dist/memory/recall.js.map +1 -0
  238. package/packages/core/dist/memory/sleep.d.ts +105 -0
  239. package/packages/core/dist/memory/sleep.d.ts.map +1 -0
  240. package/packages/core/dist/memory/sleep.js +888 -0
  241. package/packages/core/dist/memory/sleep.js.map +1 -0
  242. package/packages/core/dist/memory/store.d.ts +263 -0
  243. package/packages/core/dist/memory/store.d.ts.map +1 -0
  244. package/packages/core/dist/memory/store.js +999 -0
  245. package/packages/core/dist/memory/store.js.map +1 -0
  246. package/packages/core/dist/migration-cron.d.ts +37 -0
  247. package/packages/core/dist/migration-cron.d.ts.map +1 -0
  248. package/packages/core/dist/migration-cron.js +257 -0
  249. package/packages/core/dist/migration-cron.js.map +1 -0
  250. package/packages/core/dist/migration-scripts.d.ts +15 -0
  251. package/packages/core/dist/migration-scripts.d.ts.map +1 -0
  252. package/packages/core/dist/migration-scripts.js +97 -0
  253. package/packages/core/dist/migration-scripts.js.map +1 -0
  254. package/packages/core/dist/migration.d.ts +33 -0
  255. package/packages/core/dist/migration.d.ts.map +1 -0
  256. package/packages/core/dist/migration.js +296 -0
  257. package/packages/core/dist/migration.js.map +1 -0
  258. package/packages/core/dist/org/bridge.d.ts +42 -0
  259. package/packages/core/dist/org/bridge.d.ts.map +1 -0
  260. package/packages/core/dist/org/bridge.js +139 -0
  261. package/packages/core/dist/org/bridge.js.map +1 -0
  262. package/packages/core/dist/org/controller.d.ts +118 -0
  263. package/packages/core/dist/org/controller.d.ts.map +1 -0
  264. package/packages/core/dist/org/controller.js +1431 -0
  265. package/packages/core/dist/org/controller.js.map +1 -0
  266. package/packages/core/dist/org/mcp-bridge.d.ts +11 -0
  267. package/packages/core/dist/org/mcp-bridge.d.ts.map +1 -0
  268. package/packages/core/dist/org/mcp-bridge.js +148 -0
  269. package/packages/core/dist/org/mcp-bridge.js.map +1 -0
  270. package/packages/core/dist/org/planner.d.ts +60 -0
  271. package/packages/core/dist/org/planner.d.ts.map +1 -0
  272. package/packages/core/dist/org/planner.js +175 -0
  273. package/packages/core/dist/org/planner.js.map +1 -0
  274. package/packages/core/dist/org/ponytail.d.ts +24 -0
  275. package/packages/core/dist/org/ponytail.d.ts.map +1 -0
  276. package/packages/core/dist/org/ponytail.js +53 -0
  277. package/packages/core/dist/org/ponytail.js.map +1 -0
  278. package/packages/core/dist/org/project-mcp.d.ts +32 -0
  279. package/packages/core/dist/org/project-mcp.d.ts.map +1 -0
  280. package/packages/core/dist/org/project-mcp.js +53 -0
  281. package/packages/core/dist/org/project-mcp.js.map +1 -0
  282. package/packages/core/dist/org/prompts.d.ts +71 -0
  283. package/packages/core/dist/org/prompts.d.ts.map +1 -0
  284. package/packages/core/dist/org/prompts.js +268 -0
  285. package/packages/core/dist/org/prompts.js.map +1 -0
  286. package/packages/core/dist/org/store.d.ts +176 -0
  287. package/packages/core/dist/org/store.d.ts.map +1 -0
  288. package/packages/core/dist/org/store.js +594 -0
  289. package/packages/core/dist/org/store.js.map +1 -0
  290. package/packages/core/dist/org/tools.d.ts +22 -0
  291. package/packages/core/dist/org/tools.d.ts.map +1 -0
  292. package/packages/core/dist/org/tools.js +578 -0
  293. package/packages/core/dist/org/tools.js.map +1 -0
  294. package/packages/core/dist/profile.d.ts +16 -0
  295. package/packages/core/dist/profile.d.ts.map +1 -0
  296. package/packages/core/dist/profile.js +176 -0
  297. package/packages/core/dist/profile.js.map +1 -0
  298. package/packages/core/dist/providers/catalogue.d.ts +6 -0
  299. package/packages/core/dist/providers/catalogue.d.ts.map +1 -0
  300. package/packages/core/dist/providers/catalogue.js +104 -0
  301. package/packages/core/dist/providers/catalogue.js.map +1 -0
  302. package/packages/core/dist/providers/claude-code.d.ts +10 -0
  303. package/packages/core/dist/providers/claude-code.d.ts.map +1 -0
  304. package/packages/core/dist/providers/claude-code.js +321 -0
  305. package/packages/core/dist/providers/claude-code.js.map +1 -0
  306. package/packages/core/dist/providers/codex.d.ts +10 -0
  307. package/packages/core/dist/providers/codex.d.ts.map +1 -0
  308. package/packages/core/dist/providers/codex.js +375 -0
  309. package/packages/core/dist/providers/codex.js.map +1 -0
  310. package/packages/core/dist/providers/process.d.ts +48 -0
  311. package/packages/core/dist/providers/process.d.ts.map +1 -0
  312. package/packages/core/dist/providers/process.js +165 -0
  313. package/packages/core/dist/providers/process.js.map +1 -0
  314. package/packages/core/dist/providers/quota.d.ts +13 -0
  315. package/packages/core/dist/providers/quota.d.ts.map +1 -0
  316. package/packages/core/dist/providers/quota.js +231 -0
  317. package/packages/core/dist/providers/quota.js.map +1 -0
  318. package/packages/core/dist/providers/registry.d.ts +27 -0
  319. package/packages/core/dist/providers/registry.d.ts.map +1 -0
  320. package/packages/core/dist/providers/registry.js +64 -0
  321. package/packages/core/dist/providers/registry.js.map +1 -0
  322. package/packages/core/dist/runtime.d.ts +149 -0
  323. package/packages/core/dist/runtime.d.ts.map +1 -0
  324. package/packages/core/dist/runtime.js +778 -0
  325. package/packages/core/dist/runtime.js.map +1 -0
  326. package/packages/core/dist/skills/import.d.ts +41 -0
  327. package/packages/core/dist/skills/import.d.ts.map +1 -0
  328. package/packages/core/dist/skills/import.js +129 -0
  329. package/packages/core/dist/skills/import.js.map +1 -0
  330. package/packages/core/dist/skills/store.d.ts +57 -0
  331. package/packages/core/dist/skills/store.d.ts.map +1 -0
  332. package/packages/core/dist/skills/store.js +126 -0
  333. package/packages/core/dist/skills/store.js.map +1 -0
  334. package/packages/core/dist/tools/browser.d.ts +20 -0
  335. package/packages/core/dist/tools/browser.d.ts.map +1 -0
  336. package/packages/core/dist/tools/browser.js +72 -0
  337. package/packages/core/dist/tools/browser.js.map +1 -0
  338. package/packages/core/dist/tools/catalog.d.ts +67 -0
  339. package/packages/core/dist/tools/catalog.d.ts.map +1 -0
  340. package/packages/core/dist/tools/catalog.js +233 -0
  341. package/packages/core/dist/tools/catalog.js.map +1 -0
  342. package/packages/core/dist/tools/hub.d.ts +68 -0
  343. package/packages/core/dist/tools/hub.d.ts.map +1 -0
  344. package/packages/core/dist/tools/hub.js +213 -0
  345. package/packages/core/dist/tools/hub.js.map +1 -0
  346. package/packages/core/dist/types.d.ts +1031 -0
  347. package/packages/core/dist/types.d.ts.map +1 -0
  348. package/packages/core/dist/types.js +22 -0
  349. package/packages/core/dist/types.js.map +1 -0
  350. package/packages/core/dist/util/queue.d.ts +25 -0
  351. package/packages/core/dist/util/queue.d.ts.map +1 -0
  352. package/packages/core/dist/util/queue.js +64 -0
  353. package/packages/core/dist/util/queue.js.map +1 -0
  354. package/packages/core/package.json +1 -0
  355. package/packages/server/dist/auth.d.ts +12 -0
  356. package/packages/server/dist/auth.d.ts.map +1 -0
  357. package/packages/server/dist/auth.js +61 -0
  358. package/packages/server/dist/auth.js.map +1 -0
  359. package/packages/server/dist/context.d.ts +29 -0
  360. package/packages/server/dist/context.d.ts.map +1 -0
  361. package/packages/server/dist/context.js +46 -0
  362. package/packages/server/dist/context.js.map +1 -0
  363. package/packages/server/dist/env.d.ts +8 -0
  364. package/packages/server/dist/env.d.ts.map +1 -0
  365. package/packages/server/dist/env.js +36 -0
  366. package/packages/server/dist/env.js.map +1 -0
  367. package/packages/server/dist/gateways/push.d.ts +22 -0
  368. package/packages/server/dist/gateways/push.d.ts.map +1 -0
  369. package/packages/server/dist/gateways/push.js +267 -0
  370. package/packages/server/dist/gateways/push.js.map +1 -0
  371. package/packages/server/dist/gateways/telegram-api.d.ts +82 -0
  372. package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -0
  373. package/packages/server/dist/gateways/telegram-api.js +168 -0
  374. package/packages/server/dist/gateways/telegram-api.js.map +1 -0
  375. package/packages/server/dist/gateways/telegram.d.ts +32 -0
  376. package/packages/server/dist/gateways/telegram.d.ts.map +1 -0
  377. package/packages/server/dist/gateways/telegram.js +583 -0
  378. package/packages/server/dist/gateways/telegram.js.map +1 -0
  379. package/packages/server/dist/index.d.ts +12 -0
  380. package/packages/server/dist/index.d.ts.map +1 -0
  381. package/packages/server/dist/index.js +12 -0
  382. package/packages/server/dist/index.js.map +1 -0
  383. package/packages/server/dist/main.d.ts +2 -0
  384. package/packages/server/dist/main.d.ts.map +1 -0
  385. package/packages/server/dist/main.js +74 -0
  386. package/packages/server/dist/main.js.map +1 -0
  387. package/packages/server/dist/routes/agents.d.ts +5 -0
  388. package/packages/server/dist/routes/agents.d.ts.map +1 -0
  389. package/packages/server/dist/routes/agents.js +6 -0
  390. package/packages/server/dist/routes/agents.js.map +1 -0
  391. package/packages/server/dist/routes/chat.d.ts +10 -0
  392. package/packages/server/dist/routes/chat.d.ts.map +1 -0
  393. package/packages/server/dist/routes/chat.js +36 -0
  394. package/packages/server/dist/routes/chat.js.map +1 -0
  395. package/packages/server/dist/routes/config.d.ts +4 -0
  396. package/packages/server/dist/routes/config.d.ts.map +1 -0
  397. package/packages/server/dist/routes/config.js +58 -0
  398. package/packages/server/dist/routes/config.js.map +1 -0
  399. package/packages/server/dist/routes/cron.d.ts +10 -0
  400. package/packages/server/dist/routes/cron.d.ts.map +1 -0
  401. package/packages/server/dist/routes/cron.js +128 -0
  402. package/packages/server/dist/routes/cron.js.map +1 -0
  403. package/packages/server/dist/routes/gateways.d.ts +10 -0
  404. package/packages/server/dist/routes/gateways.d.ts.map +1 -0
  405. package/packages/server/dist/routes/gateways.js +32 -0
  406. package/packages/server/dist/routes/gateways.js.map +1 -0
  407. package/packages/server/dist/routes/health.d.ts +8 -0
  408. package/packages/server/dist/routes/health.d.ts.map +1 -0
  409. package/packages/server/dist/routes/health.js +12 -0
  410. package/packages/server/dist/routes/health.js.map +1 -0
  411. package/packages/server/dist/routes/memories.d.ts +11 -0
  412. package/packages/server/dist/routes/memories.d.ts.map +1 -0
  413. package/packages/server/dist/routes/memories.js +134 -0
  414. package/packages/server/dist/routes/memories.js.map +1 -0
  415. package/packages/server/dist/routes/org.d.ts +13 -0
  416. package/packages/server/dist/routes/org.d.ts.map +1 -0
  417. package/packages/server/dist/routes/org.js +316 -0
  418. package/packages/server/dist/routes/org.js.map +1 -0
  419. package/packages/server/dist/routes/profile.d.ts +4 -0
  420. package/packages/server/dist/routes/profile.d.ts.map +1 -0
  421. package/packages/server/dist/routes/profile.js +51 -0
  422. package/packages/server/dist/routes/profile.js.map +1 -0
  423. package/packages/server/dist/routes/providers.d.ts +9 -0
  424. package/packages/server/dist/routes/providers.d.ts.map +1 -0
  425. package/packages/server/dist/routes/providers.js +41 -0
  426. package/packages/server/dist/routes/providers.js.map +1 -0
  427. package/packages/server/dist/routes/sessions.d.ts +9 -0
  428. package/packages/server/dist/routes/sessions.d.ts.map +1 -0
  429. package/packages/server/dist/routes/sessions.js +72 -0
  430. package/packages/server/dist/routes/sessions.js.map +1 -0
  431. package/packages/server/dist/routes/sleep.d.ts +12 -0
  432. package/packages/server/dist/routes/sleep.d.ts.map +1 -0
  433. package/packages/server/dist/routes/sleep.js +70 -0
  434. package/packages/server/dist/routes/sleep.js.map +1 -0
  435. package/packages/server/dist/routes/stats.d.ts +17 -0
  436. package/packages/server/dist/routes/stats.d.ts.map +1 -0
  437. package/packages/server/dist/routes/stats.js +57 -0
  438. package/packages/server/dist/routes/stats.js.map +1 -0
  439. package/packages/server/dist/routes/team.d.ts +11 -0
  440. package/packages/server/dist/routes/team.d.ts.map +1 -0
  441. package/packages/server/dist/routes/team.js +36 -0
  442. package/packages/server/dist/routes/team.js.map +1 -0
  443. package/packages/server/dist/routes/tools.d.ts +10 -0
  444. package/packages/server/dist/routes/tools.d.ts.map +1 -0
  445. package/packages/server/dist/routes/tools.js +128 -0
  446. package/packages/server/dist/routes/tools.js.map +1 -0
  447. package/packages/server/dist/routes/tts.d.ts +12 -0
  448. package/packages/server/dist/routes/tts.d.ts.map +1 -0
  449. package/packages/server/dist/routes/tts.js +38 -0
  450. package/packages/server/dist/routes/tts.js.map +1 -0
  451. package/packages/server/dist/routes/ws.d.ts +13 -0
  452. package/packages/server/dist/routes/ws.d.ts.map +1 -0
  453. package/packages/server/dist/routes/ws.js +96 -0
  454. package/packages/server/dist/routes/ws.js.map +1 -0
  455. package/packages/server/dist/schemas.d.ts +981 -0
  456. package/packages/server/dist/schemas.d.ts.map +1 -0
  457. package/packages/server/dist/schemas.js +339 -0
  458. package/packages/server/dist/schemas.js.map +1 -0
  459. package/packages/server/dist/server.d.ts +20 -0
  460. package/packages/server/dist/server.d.ts.map +1 -0
  461. package/packages/server/dist/server.js +234 -0
  462. package/packages/server/dist/server.js.map +1 -0
  463. package/packages/server/dist/services/stream.d.ts +77 -0
  464. package/packages/server/dist/services/stream.d.ts.map +1 -0
  465. package/packages/server/dist/services/stream.js +84 -0
  466. package/packages/server/dist/services/stream.js.map +1 -0
  467. package/packages/server/dist/services/tts.d.ts +53 -0
  468. package/packages/server/dist/services/tts.d.ts.map +1 -0
  469. package/packages/server/dist/services/tts.js +281 -0
  470. package/packages/server/dist/services/tts.js.map +1 -0
  471. package/packages/server/dist/services/voice-keys.d.ts +26 -0
  472. package/packages/server/dist/services/voice-keys.d.ts.map +1 -0
  473. package/packages/server/dist/services/voice-keys.js +51 -0
  474. package/packages/server/dist/services/voice-keys.js.map +1 -0
  475. package/packages/server/dist/static.d.ts +12 -0
  476. package/packages/server/dist/static.d.ts.map +1 -0
  477. package/packages/server/dist/static.js +63 -0
  478. package/packages/server/dist/static.js.map +1 -0
  479. package/packages/server/package.json +1 -0
  480. package/packages/web/dist/apple-touch-icon.png +0 -0
  481. package/packages/web/dist/assets/3d-force-graph-BPZmoydi.js +1163 -0
  482. package/packages/web/dist/assets/bricolage-grotesque-latin-ext-wght-normal-CcLUaPy7.woff2 +0 -0
  483. package/packages/web/dist/assets/bricolage-grotesque-latin-wght-normal-DLoelf7F.woff2 +0 -0
  484. package/packages/web/dist/assets/bricolage-grotesque-vietnamese-wght-normal-BUzh504Q.woff2 +0 -0
  485. package/packages/web/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  486. package/packages/web/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  487. package/packages/web/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  488. package/packages/web/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  489. package/packages/web/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  490. package/packages/web/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  491. package/packages/web/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  492. package/packages/web/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  493. package/packages/web/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  494. package/packages/web/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  495. package/packages/web/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  496. package/packages/web/dist/assets/index-IBSTzK7-.js +1255 -0
  497. package/packages/web/dist/assets/index-qUXUui7W.css +1 -0
  498. package/packages/web/dist/assets/three-spritetext-B9ZIW7c-.js +4 -0
  499. package/packages/web/dist/assets/three.module-cmFfBtHS.js +4228 -0
  500. package/packages/web/dist/favicon.ico +0 -0
  501. package/packages/web/dist/favicon.svg +2 -0
  502. package/packages/web/dist/index.html +28 -0
  503. package/packages/web/dist/logo-light.svg +2 -0
  504. package/packages/web/dist/logo.svg +2 -0
  505. package/packages/web/dist/mark-light.svg +2 -0
  506. package/packages/web/dist/mark.svg +2 -0
  507. package/packages/web/package.json +1 -0
  508. package/scripts/rookery.mjs +183 -0
@@ -0,0 +1,1163 @@
1
+ import{C as Du,R as em,M as st,T as nr,V as de,P as jh,a as z,b as bt,B as Eo,c as yn,S as qh,d as Dt,e as tm,f as Rc,L as Cx,G as nm,g as rm,h as im,i as Mx,Q as Px,j as sm,k as Bx,l as Fx,w as Y,H as wt,m as Xh,N as Ki,n as Ga,o as tf,p as Kh,F as Dx,q as Lx,y as Ac,r as Fe,s as V,t as Yn,u as Ti,v as Rt,x as Ye,z as Qt,A as tt,D as yt,E as li,I as sr,J as io,W as nu,K as Pn,O as Si,U as Ox,X as om,Y as Ux,Z as Yh,_ as am,$ as Ix,a0 as kx,a1 as Gx,a2 as Vx,a3 as $x,a4 as zx,a5 as Wx,a6 as Hx,a7 as Yi,a8 as Pt,a9 as Ur,aa as rr,ab as gt,ac as qe,ad as mt,ae as Qh,af as Co,ag as Mo,ah as Dn,ai as Ln,aj as pn,ak as Po,al as Bo,am as Zh,an as um,ao as lm,ap as or,aq as Jh,ar as ed,as as Lu,at as cm,au as ar,av as yo,aw as jx,ax as qx,ay as Br,az as ci,aA as Qn,aB as Cr,aC as ns,aD as Xx,aE as td,aF as nd,aG as ru,aH as rs,aI as le,aJ as gs,aK as rd,aL as nf,aM as Ou,aN as bo,aO as Kx,aP as iu,aQ as Uu,aR as xo,aS as Iu,aT as Ir,aU as Nc,aV as is,aW as hm,aX as zt,aY as dm,aZ as su,a_ as ss,a$ as fm,b0 as Fo,b1 as id,b2 as pm,b3 as gm,b4 as rf,b5 as os,b6 as sf,b7 as mm,b8 as _m,b9 as ym,ba as bm,bb as xm,bc as vm,bd as Tm,be as Sm,bf as wm,bg as Rm,bh as Am,bi as Nm,bj as Em,bk as Cm,bl as Mm,bm as Pm,bn as Bm,bo as Fm,bp as Yx,bq as Qx,br as Zx,bs as Dm,bt as ur,bu as Wi,bv as Hi,bw as ji,bx as Zn,by as Lm,bz as Om,bA as Um,bB as Im,bC as km,bD as Gm,bE as Vm,bF as $m,bG as sd,bH as Va,bI as $a,bJ as za,bK as Wa,bL as of,bM as af,bN as uf,bO as lf,bP as Ec,bQ as Cc,bR as Mc,bS as Pc,bT as Bc,bU as ou,bV as Fc,bW as Dc,bX as Lc,bY as Oc,bZ as Uc,b_ as Ic,b$ as kc,c0 as Gc,c1 as Vc,c2 as $c,c3 as zc,c4 as Wc,c5 as Hc,c6 as jc,c7 as qc,c8 as Xc,c9 as Kc,ca as Yc,cb as Qc,cc as Zc,cd as au,ce as Jc,cf as ku,cg as Jx,ch as ev,ci as tv,cj as nv,ck as rv,cl as iv,cm as sv,cn as ov,co as av,cp as uv,cq as lv,cr as Gu,cs as od,ct as cv,cu as hv,cv as dv,cw as uu,cx as fv,cy as pv,cz as gv,cA as mv,cB as _v,cC as yv,cD as bv,cE as xv,cF as vv,cG as Tv,cH as Sv,cI as wv,cJ as Rv,cK as Av,cL as Nv,cM as Ev,cN as zm,cO as Wm,cP as Cv,cQ as Mv,cR as Pv,cS as lu,cT as Bv,cU as Fv,cV as Hm,cW as jm,cX as Dv,cY as Lv,cZ as Ov,c_ as Uv,c$ as ad,d0 as qm,d1 as Iv,d2 as kv,d3 as Gv,d4 as cu,d5 as hu,d6 as ll,d7 as cl,d8 as Vv,d9 as $v,da as zv,db as Wv,dc as cf,dd as Hv,de as hf,df as jv,dg as qv,dh as Xm,di as Xv,dj as Kv}from"./three.module-cmFfBtHS.js";import{g as Yv,o as Qv,m as Zv,a as Jv,_ as rn}from"./index-IBSTzK7-.js";const Qi=new jh,Jn=new de,Km=new z,hl=new de,Ha=new de,du=new z,eh=new z,Ym=new bt,Qm=new z,Zm=new z;let pt=null,Nn=null;const er=[],kr={NONE:-1,PAN:0,ROTATE:1};class e0 extends Du{constructor(e,t,n=null){super(t,n),this.objects=e,this.recursive=!0,this.transformGroup=!1,this.rotateSpeed=1,this.raycaster=new em,this.mouseButtons={LEFT:st.PAN,MIDDLE:st.PAN,RIGHT:st.ROTATE},this.touches={ONE:nr.PAN},this._onPointerMove=t0.bind(this),this._onPointerDown=n0.bind(this),this._onPointerCancel=r0.bind(this),this._onContextMenu=i0.bind(this),n!==null&&this.connect(n)}connect(e){super.connect(e),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerCancel),this.domElement.addEventListener("pointerleave",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerCancel),this.domElement.removeEventListener("pointerleave",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="",this.domElement.style.cursor=""}dispose(){this.disconnect()}_updatePointer(e){const t=this.domElement.getBoundingClientRect();Jn.x=(e.clientX-t.left)/t.width*2-1,Jn.y=-(e.clientY-t.top)/t.height*2+1}_updateState(e){let t;if(e.pointerType==="touch")t=this.touches.ONE;else switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=null}switch(t){case st.PAN:case nr.PAN:this.state=kr.PAN;break;case st.ROTATE:case nr.ROTATE:this.state=kr.ROTATE;break;default:this.state=kr.NONE}}}function t0(r){const e=this.object,t=this.domElement,n=this.raycaster;if(this.enabled!==!1){if(this._updatePointer(r),n.setFromCamera(Jn,e),pt)this.state===kr.PAN?n.ray.intersectPlane(Qi,du)&&(pt.position.copy(du.sub(Km).applyMatrix4(Ym)),this.dispatchEvent({type:"drag",object:pt})):this.state===kr.ROTATE&&(hl.subVectors(Jn,Ha).multiplyScalar(this.rotateSpeed),pt.rotateOnWorldAxis(Qm,hl.x),pt.rotateOnWorldAxis(Zm.normalize(),-hl.y),this.dispatchEvent({type:"drag",object:pt})),Ha.copy(Jn);else if(r.pointerType==="mouse"||r.pointerType==="pen")if(er.length=0,n.setFromCamera(Jn,e),n.intersectObjects(this.objects,this.recursive,er),er.length>0){const i=er[0].object;Qi.setFromNormalAndCoplanarPoint(e.getWorldDirection(Qi.normal),eh.setFromMatrixPosition(i.matrixWorld)),Nn!==i&&Nn!==null&&(this.dispatchEvent({type:"hoveroff",object:Nn}),t.style.cursor="auto",Nn=null),Nn!==i&&(this.dispatchEvent({type:"hoveron",object:i}),t.style.cursor="pointer",Nn=i)}else Nn!==null&&(this.dispatchEvent({type:"hoveroff",object:Nn}),t.style.cursor="auto",Nn=null);Ha.copy(Jn)}}function n0(r){const e=this.object,t=this.domElement,n=this.raycaster;this.enabled!==!1&&(this._updatePointer(r),this._updateState(r),er.length=0,n.setFromCamera(Jn,e),n.intersectObjects(this.objects,this.recursive,er),er.length>0&&(this.transformGroup===!0?pt=Jm(er[0].object):pt=er[0].object,Qi.setFromNormalAndCoplanarPoint(e.getWorldDirection(Qi.normal),eh.setFromMatrixPosition(pt.matrixWorld)),n.ray.intersectPlane(Qi,du)&&(this.state===kr.PAN?(Ym.copy(pt.parent.matrixWorld).invert(),Km.copy(du).sub(eh.setFromMatrixPosition(pt.matrixWorld)),t.style.cursor="move",this.dispatchEvent({type:"dragstart",object:pt})):this.state===kr.ROTATE&&(Qm.set(0,1,0).applyQuaternion(e.quaternion).normalize(),Zm.set(1,0,0).applyQuaternion(e.quaternion).normalize(),t.style.cursor="move",this.dispatchEvent({type:"dragstart",object:pt})))),Ha.copy(Jn))}function r0(){this.enabled!==!1&&(pt&&(this.dispatchEvent({type:"dragend",object:pt}),pt=null),this.domElement.style.cursor=Nn?"pointer":"auto",this.state=kr.NONE)}function i0(r){this.enabled!==!1&&r.preventDefault()}function Jm(r,e=null){return r.isGroup&&(e=r),r.parent===null?e:Jm(r.parent,e)}function s0(r,e,t){var n,i=1;r==null&&(r=0),e==null&&(e=0),t==null&&(t=0);function s(){var o,a=n.length,u,l=0,c=0,h=0;for(o=0;o<a;++o)u=n[o],l+=u.x||0,c+=u.y||0,h+=u.z||0;for(l=(l/a-r)*i,c=(c/a-e)*i,h=(h/a-t)*i,o=0;o<a;++o)u=n[o],l&&(u.x-=l),c&&(u.y-=c),h&&(u.z-=h)}return s.initialize=function(o){n=o},s.x=function(o){return arguments.length?(r=+o,s):r},s.y=function(o){return arguments.length?(e=+o,s):e},s.z=function(o){return arguments.length?(t=+o,s):t},s.strength=function(o){return arguments.length?(i=+o,s):i},s}function o0(r){const e=+this._x.call(null,r);return e_(this.cover(e),e,r)}function e_(r,e,t){if(isNaN(e))return r;var n,i=r._root,s={data:t},o=r._x0,a=r._x1,u,l,c,h,d;if(!i)return r._root=s,r;for(;i.length;)if((c=e>=(u=(o+a)/2))?o=u:a=u,n=i,!(i=i[h=+c]))return n[h]=s,r;if(l=+r._x.call(null,i.data),e===l)return s.next=i,n?n[h]=s:r._root=s,r;do n=n?n[h]=new Array(2):r._root=new Array(2),(c=e>=(u=(o+a)/2))?o=u:a=u;while((h=+c)==(d=+(l>=u)));return n[d]=i,n[h]=s,r}function a0(r){Array.isArray(r)||(r=Array.from(r));const e=r.length,t=new Float64Array(e);let n=1/0,i=-1/0;for(let s=0,o;s<e;++s)isNaN(o=+this._x.call(null,r[s]))||(t[s]=o,o<n&&(n=o),o>i&&(i=o));if(n>i)return this;this.cover(n).cover(i);for(let s=0;s<e;++s)e_(this,t[s],r[s]);return this}function u0(r){if(isNaN(r=+r))return this;var e=this._x0,t=this._x1;if(isNaN(e))t=(e=Math.floor(r))+1;else{for(var n=t-e||1,i=this._root,s,o;e>r||r>=t;)switch(o=+(r<e),s=new Array(2),s[o]=i,i=s,n*=2,o){case 0:t=e+n;break;case 1:e=t-n;break}this._root&&this._root.length&&(this._root=i)}return this._x0=e,this._x1=t,this}function l0(){var r=[];return this.visit(function(e){if(!e.length)do r.push(e.data);while(e=e.next)}),r}function c0(r){return arguments.length?this.cover(+r[0][0]).cover(+r[1][0]):isNaN(this._x0)?void 0:[[this._x0],[this._x1]]}function lr(r,e,t){this.node=r,this.x0=e,this.x1=t}function h0(r,e){var t,n=this._x0,i,s,o=this._x1,a=[],u=this._root,l,c;for(u&&a.push(new lr(u,n,o)),e==null?e=1/0:(n=r-e,o=r+e);l=a.pop();)if(!(!(u=l.node)||(i=l.x0)>o||(s=l.x1)<n))if(u.length){var h=(i+s)/2;a.push(new lr(u[1],h,s),new lr(u[0],i,h)),(c=+(r>=h))&&(l=a[a.length-1],a[a.length-1]=a[a.length-1-c],a[a.length-1-c]=l)}else{var d=Math.abs(r-+this._x.call(null,u.data));d<e&&(e=d,n=r-d,o=r+d,t=u.data)}return t}function d0(r){if(isNaN(u=+this._x.call(null,r)))return this;var e,t=this._root,n,i,s,o=this._x0,a=this._x1,u,l,c,h,d;if(!t)return this;if(t.length)for(;;){if((c=u>=(l=(o+a)/2))?o=l:a=l,e=t,!(t=t[h=+c]))return this;if(!t.length)break;e[h+1&1]&&(n=e,d=h)}for(;t.data!==r;)if(i=t,!(t=t.next))return this;return(s=t.next)&&delete t.next,i?(s?i.next=s:delete i.next,this):e?(s?e[h]=s:delete e[h],(t=e[0]||e[1])&&t===(e[1]||e[0])&&!t.length&&(n?n[d]=t:this._root=t),this):(this._root=s,this)}function f0(r){for(var e=0,t=r.length;e<t;++e)this.remove(r[e]);return this}function p0(){return this._root}function g0(){var r=0;return this.visit(function(e){if(!e.length)do++r;while(e=e.next)}),r}function m0(r){var e=[],t,n=this._root,i,s,o;for(n&&e.push(new lr(n,this._x0,this._x1));t=e.pop();)if(!r(n=t.node,s=t.x0,o=t.x1)&&n.length){var a=(s+o)/2;(i=n[1])&&e.push(new lr(i,a,o)),(i=n[0])&&e.push(new lr(i,s,a))}return this}function _0(r){var e=[],t=[],n;for(this._root&&e.push(new lr(this._root,this._x0,this._x1));n=e.pop();){var i=n.node;if(i.length){var s,o=n.x0,a=n.x1,u=(o+a)/2;(s=i[0])&&e.push(new lr(s,o,u)),(s=i[1])&&e.push(new lr(s,u,a))}t.push(n)}for(;n=t.pop();)r(n.node,n.x0,n.x1);return this}function y0(r){return r[0]}function b0(r){return arguments.length?(this._x=r,this):this._x}function t_(r,e){var t=new ud(e??y0,NaN,NaN);return r==null?t:t.addAll(r)}function ud(r,e,t){this._x=r,this._x0=e,this._x1=t,this._root=void 0}function df(r){for(var e={data:r.data},t=e;r=r.next;)t=t.next={data:r.data};return e}var Lt=t_.prototype=ud.prototype;Lt.copy=function(){var r=new ud(this._x,this._x0,this._x1),e=this._root,t,n;if(!e)return r;if(!e.length)return r._root=df(e),r;for(t=[{source:e,target:r._root=new Array(2)}];e=t.pop();)for(var i=0;i<2;++i)(n=e.source[i])&&(n.length?t.push({source:n,target:e.target[i]=new Array(2)}):e.target[i]=df(n));return r};Lt.add=o0;Lt.addAll=a0;Lt.cover=u0;Lt.data=l0;Lt.extent=c0;Lt.find=h0;Lt.remove=d0;Lt.removeAll=f0;Lt.root=p0;Lt.size=g0;Lt.visit=m0;Lt.visitAfter=_0;Lt.x=b0;function x0(r){const e=+this._x.call(null,r),t=+this._y.call(null,r);return n_(this.cover(e,t),e,t,r)}function n_(r,e,t,n){if(isNaN(e)||isNaN(t))return r;var i,s=r._root,o={data:n},a=r._x0,u=r._y0,l=r._x1,c=r._y1,h,d,f,p,g,_,m,y;if(!s)return r._root=o,r;for(;s.length;)if((g=e>=(h=(a+l)/2))?a=h:l=h,(_=t>=(d=(u+c)/2))?u=d:c=d,i=s,!(s=s[m=_<<1|g]))return i[m]=o,r;if(f=+r._x.call(null,s.data),p=+r._y.call(null,s.data),e===f&&t===p)return o.next=s,i?i[m]=o:r._root=o,r;do i=i?i[m]=new Array(4):r._root=new Array(4),(g=e>=(h=(a+l)/2))?a=h:l=h,(_=t>=(d=(u+c)/2))?u=d:c=d;while((m=_<<1|g)===(y=(p>=d)<<1|f>=h));return i[y]=s,i[m]=o,r}function v0(r){var e,t,n=r.length,i,s,o=new Array(n),a=new Array(n),u=1/0,l=1/0,c=-1/0,h=-1/0;for(t=0;t<n;++t)isNaN(i=+this._x.call(null,e=r[t]))||isNaN(s=+this._y.call(null,e))||(o[t]=i,a[t]=s,i<u&&(u=i),i>c&&(c=i),s<l&&(l=s),s>h&&(h=s));if(u>c||l>h)return this;for(this.cover(u,l).cover(c,h),t=0;t<n;++t)n_(this,o[t],a[t],r[t]);return this}function T0(r,e){if(isNaN(r=+r)||isNaN(e=+e))return this;var t=this._x0,n=this._y0,i=this._x1,s=this._y1;if(isNaN(t))i=(t=Math.floor(r))+1,s=(n=Math.floor(e))+1;else{for(var o=i-t||1,a=this._root,u,l;t>r||r>=i||n>e||e>=s;)switch(l=(e<n)<<1|r<t,u=new Array(4),u[l]=a,a=u,o*=2,l){case 0:i=t+o,s=n+o;break;case 1:t=i-o,s=n+o;break;case 2:i=t+o,n=s-o;break;case 3:t=i-o,n=s-o;break}this._root&&this._root.length&&(this._root=a)}return this._x0=t,this._y0=n,this._x1=i,this._y1=s,this}function S0(){var r=[];return this.visit(function(e){if(!e.length)do r.push(e.data);while(e=e.next)}),r}function w0(r){return arguments.length?this.cover(+r[0][0],+r[0][1]).cover(+r[1][0],+r[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function St(r,e,t,n,i){this.node=r,this.x0=e,this.y0=t,this.x1=n,this.y1=i}function R0(r,e,t){var n,i=this._x0,s=this._y0,o,a,u,l,c=this._x1,h=this._y1,d=[],f=this._root,p,g;for(f&&d.push(new St(f,i,s,c,h)),t==null?t=1/0:(i=r-t,s=e-t,c=r+t,h=e+t,t*=t);p=d.pop();)if(!(!(f=p.node)||(o=p.x0)>c||(a=p.y0)>h||(u=p.x1)<i||(l=p.y1)<s))if(f.length){var _=(o+u)/2,m=(a+l)/2;d.push(new St(f[3],_,m,u,l),new St(f[2],o,m,_,l),new St(f[1],_,a,u,m),new St(f[0],o,a,_,m)),(g=(e>=m)<<1|r>=_)&&(p=d[d.length-1],d[d.length-1]=d[d.length-1-g],d[d.length-1-g]=p)}else{var y=r-+this._x.call(null,f.data),b=e-+this._y.call(null,f.data),T=y*y+b*b;if(T<t){var x=Math.sqrt(t=T);i=r-x,s=e-x,c=r+x,h=e+x,n=f.data}}return n}function A0(r){if(isNaN(c=+this._x.call(null,r))||isNaN(h=+this._y.call(null,r)))return this;var e,t=this._root,n,i,s,o=this._x0,a=this._y0,u=this._x1,l=this._y1,c,h,d,f,p,g,_,m;if(!t)return this;if(t.length)for(;;){if((p=c>=(d=(o+u)/2))?o=d:u=d,(g=h>=(f=(a+l)/2))?a=f:l=f,e=t,!(t=t[_=g<<1|p]))return this;if(!t.length)break;(e[_+1&3]||e[_+2&3]||e[_+3&3])&&(n=e,m=_)}for(;t.data!==r;)if(i=t,!(t=t.next))return this;return(s=t.next)&&delete t.next,i?(s?i.next=s:delete i.next,this):e?(s?e[_]=s:delete e[_],(t=e[0]||e[1]||e[2]||e[3])&&t===(e[3]||e[2]||e[1]||e[0])&&!t.length&&(n?n[m]=t:this._root=t),this):(this._root=s,this)}function N0(r){for(var e=0,t=r.length;e<t;++e)this.remove(r[e]);return this}function E0(){return this._root}function C0(){var r=0;return this.visit(function(e){if(!e.length)do++r;while(e=e.next)}),r}function M0(r){var e=[],t,n=this._root,i,s,o,a,u;for(n&&e.push(new St(n,this._x0,this._y0,this._x1,this._y1));t=e.pop();)if(!r(n=t.node,s=t.x0,o=t.y0,a=t.x1,u=t.y1)&&n.length){var l=(s+a)/2,c=(o+u)/2;(i=n[3])&&e.push(new St(i,l,c,a,u)),(i=n[2])&&e.push(new St(i,s,c,l,u)),(i=n[1])&&e.push(new St(i,l,o,a,c)),(i=n[0])&&e.push(new St(i,s,o,l,c))}return this}function P0(r){var e=[],t=[],n;for(this._root&&e.push(new St(this._root,this._x0,this._y0,this._x1,this._y1));n=e.pop();){var i=n.node;if(i.length){var s,o=n.x0,a=n.y0,u=n.x1,l=n.y1,c=(o+u)/2,h=(a+l)/2;(s=i[0])&&e.push(new St(s,o,a,c,h)),(s=i[1])&&e.push(new St(s,c,a,u,h)),(s=i[2])&&e.push(new St(s,o,h,c,l)),(s=i[3])&&e.push(new St(s,c,h,u,l))}t.push(n)}for(;n=t.pop();)r(n.node,n.x0,n.y0,n.x1,n.y1);return this}function B0(r){return r[0]}function F0(r){return arguments.length?(this._x=r,this):this._x}function D0(r){return r[1]}function L0(r){return arguments.length?(this._y=r,this):this._y}function r_(r,e,t){var n=new ld(e??B0,t??D0,NaN,NaN,NaN,NaN);return r==null?n:n.addAll(r)}function ld(r,e,t,n,i,s){this._x=r,this._y=e,this._x0=t,this._y0=n,this._x1=i,this._y1=s,this._root=void 0}function ff(r){for(var e={data:r.data},t=e;r=r.next;)t=t.next={data:r.data};return e}var At=r_.prototype=ld.prototype;At.copy=function(){var r=new ld(this._x,this._y,this._x0,this._y0,this._x1,this._y1),e=this._root,t,n;if(!e)return r;if(!e.length)return r._root=ff(e),r;for(t=[{source:e,target:r._root=new Array(4)}];e=t.pop();)for(var i=0;i<4;++i)(n=e.source[i])&&(n.length?t.push({source:n,target:e.target[i]=new Array(4)}):e.target[i]=ff(n));return r};At.add=x0;At.addAll=v0;At.cover=T0;At.data=S0;At.extent=w0;At.find=R0;At.remove=A0;At.removeAll=N0;At.root=E0;At.size=C0;At.visit=M0;At.visitAfter=P0;At.x=F0;At.y=L0;function O0(r){const e=+this._x.call(null,r),t=+this._y.call(null,r),n=+this._z.call(null,r);return i_(this.cover(e,t,n),e,t,n,r)}function i_(r,e,t,n,i){if(isNaN(e)||isNaN(t)||isNaN(n))return r;var s,o=r._root,a={data:i},u=r._x0,l=r._y0,c=r._z0,h=r._x1,d=r._y1,f=r._z1,p,g,_,m,y,b,T,x,v,w,R;if(!o)return r._root=a,r;for(;o.length;)if((T=e>=(p=(u+h)/2))?u=p:h=p,(x=t>=(g=(l+d)/2))?l=g:d=g,(v=n>=(_=(c+f)/2))?c=_:f=_,s=o,!(o=o[w=v<<2|x<<1|T]))return s[w]=a,r;if(m=+r._x.call(null,o.data),y=+r._y.call(null,o.data),b=+r._z.call(null,o.data),e===m&&t===y&&n===b)return a.next=o,s?s[w]=a:r._root=a,r;do s=s?s[w]=new Array(8):r._root=new Array(8),(T=e>=(p=(u+h)/2))?u=p:h=p,(x=t>=(g=(l+d)/2))?l=g:d=g,(v=n>=(_=(c+f)/2))?c=_:f=_;while((w=v<<2|x<<1|T)===(R=(b>=_)<<2|(y>=g)<<1|m>=p));return s[R]=o,s[w]=a,r}function U0(r){Array.isArray(r)||(r=Array.from(r));const e=r.length,t=new Float64Array(e),n=new Float64Array(e),i=new Float64Array(e);let s=1/0,o=1/0,a=1/0,u=-1/0,l=-1/0,c=-1/0;for(let h=0,d,f,p,g;h<e;++h)isNaN(f=+this._x.call(null,d=r[h]))||isNaN(p=+this._y.call(null,d))||isNaN(g=+this._z.call(null,d))||(t[h]=f,n[h]=p,i[h]=g,f<s&&(s=f),f>u&&(u=f),p<o&&(o=p),p>l&&(l=p),g<a&&(a=g),g>c&&(c=g));if(s>u||o>l||a>c)return this;this.cover(s,o,a).cover(u,l,c);for(let h=0;h<e;++h)i_(this,t[h],n[h],i[h],r[h]);return this}function I0(r,e,t){if(isNaN(r=+r)||isNaN(e=+e)||isNaN(t=+t))return this;var n=this._x0,i=this._y0,s=this._z0,o=this._x1,a=this._y1,u=this._z1;if(isNaN(n))o=(n=Math.floor(r))+1,a=(i=Math.floor(e))+1,u=(s=Math.floor(t))+1;else{for(var l=o-n||1,c=this._root,h,d;n>r||r>=o||i>e||e>=a||s>t||t>=u;)switch(d=(t<s)<<2|(e<i)<<1|r<n,h=new Array(8),h[d]=c,c=h,l*=2,d){case 0:o=n+l,a=i+l,u=s+l;break;case 1:n=o-l,a=i+l,u=s+l;break;case 2:o=n+l,i=a-l,u=s+l;break;case 3:n=o-l,i=a-l,u=s+l;break;case 4:o=n+l,a=i+l,s=u-l;break;case 5:n=o-l,a=i+l,s=u-l;break;case 6:o=n+l,i=a-l,s=u-l;break;case 7:n=o-l,i=a-l,s=u-l;break}this._root&&this._root.length&&(this._root=c)}return this._x0=n,this._y0=i,this._z0=s,this._x1=o,this._y1=a,this._z1=u,this}function k0(){var r=[];return this.visit(function(e){if(!e.length)do r.push(e.data);while(e=e.next)}),r}function G0(r){return arguments.length?this.cover(+r[0][0],+r[0][1],+r[0][2]).cover(+r[1][0],+r[1][1],+r[1][2]):isNaN(this._x0)?void 0:[[this._x0,this._y0,this._z0],[this._x1,this._y1,this._z1]]}function Re(r,e,t,n,i,s,o){this.node=r,this.x0=e,this.y0=t,this.z0=n,this.x1=i,this.y1=s,this.z1=o}function V0(r,e,t,n){var i,s=this._x0,o=this._y0,a=this._z0,u,l,c,h,d,f,p=this._x1,g=this._y1,_=this._z1,m=[],y=this._root,b,T;for(y&&m.push(new Re(y,s,o,a,p,g,_)),n==null?n=1/0:(s=r-n,o=e-n,a=t-n,p=r+n,g=e+n,_=t+n,n*=n);b=m.pop();)if(!(!(y=b.node)||(u=b.x0)>p||(l=b.y0)>g||(c=b.z0)>_||(h=b.x1)<s||(d=b.y1)<o||(f=b.z1)<a))if(y.length){var x=(u+h)/2,v=(l+d)/2,w=(c+f)/2;m.push(new Re(y[7],x,v,w,h,d,f),new Re(y[6],u,v,w,x,d,f),new Re(y[5],x,l,w,h,v,f),new Re(y[4],u,l,w,x,v,f),new Re(y[3],x,v,c,h,d,w),new Re(y[2],u,v,c,x,d,w),new Re(y[1],x,l,c,h,v,w),new Re(y[0],u,l,c,x,v,w)),(T=(t>=w)<<2|(e>=v)<<1|r>=x)&&(b=m[m.length-1],m[m.length-1]=m[m.length-1-T],m[m.length-1-T]=b)}else{var R=r-+this._x.call(null,y.data),F=e-+this._y.call(null,y.data),M=t-+this._z.call(null,y.data),O=R*R+F*F+M*M;if(O<n){var U=Math.sqrt(n=O);s=r-U,o=e-U,a=t-U,p=r+U,g=e+U,_=t+U,i=y.data}}return i}const $0=(r,e,t,n,i,s)=>Math.sqrt((r-n)**2+(e-i)**2+(t-s)**2);function z0(r,e,t,n){const i=[],s=r-n,o=e-n,a=t-n,u=r+n,l=e+n,c=t+n;return this.visit((h,d,f,p,g,_,m)=>{if(!h.length)do{const y=h.data;$0(r,e,t,this._x(y),this._y(y),this._z(y))<=n&&i.push(y)}while(h=h.next);return d>u||f>l||p>c||g<s||_<o||m<a}),i}function W0(r){if(isNaN(d=+this._x.call(null,r))||isNaN(f=+this._y.call(null,r))||isNaN(p=+this._z.call(null,r)))return this;var e,t=this._root,n,i,s,o=this._x0,a=this._y0,u=this._z0,l=this._x1,c=this._y1,h=this._z1,d,f,p,g,_,m,y,b,T,x,v;if(!t)return this;if(t.length)for(;;){if((y=d>=(g=(o+l)/2))?o=g:l=g,(b=f>=(_=(a+c)/2))?a=_:c=_,(T=p>=(m=(u+h)/2))?u=m:h=m,e=t,!(t=t[x=T<<2|b<<1|y]))return this;if(!t.length)break;(e[x+1&7]||e[x+2&7]||e[x+3&7]||e[x+4&7]||e[x+5&7]||e[x+6&7]||e[x+7&7])&&(n=e,v=x)}for(;t.data!==r;)if(i=t,!(t=t.next))return this;return(s=t.next)&&delete t.next,i?(s?i.next=s:delete i.next,this):e?(s?e[x]=s:delete e[x],(t=e[0]||e[1]||e[2]||e[3]||e[4]||e[5]||e[6]||e[7])&&t===(e[7]||e[6]||e[5]||e[4]||e[3]||e[2]||e[1]||e[0])&&!t.length&&(n?n[v]=t:this._root=t),this):(this._root=s,this)}function H0(r){for(var e=0,t=r.length;e<t;++e)this.remove(r[e]);return this}function j0(){return this._root}function q0(){var r=0;return this.visit(function(e){if(!e.length)do++r;while(e=e.next)}),r}function X0(r){var e=[],t,n=this._root,i,s,o,a,u,l,c;for(n&&e.push(new Re(n,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));t=e.pop();)if(!r(n=t.node,s=t.x0,o=t.y0,a=t.z0,u=t.x1,l=t.y1,c=t.z1)&&n.length){var h=(s+u)/2,d=(o+l)/2,f=(a+c)/2;(i=n[7])&&e.push(new Re(i,h,d,f,u,l,c)),(i=n[6])&&e.push(new Re(i,s,d,f,h,l,c)),(i=n[5])&&e.push(new Re(i,h,o,f,u,d,c)),(i=n[4])&&e.push(new Re(i,s,o,f,h,d,c)),(i=n[3])&&e.push(new Re(i,h,d,a,u,l,f)),(i=n[2])&&e.push(new Re(i,s,d,a,h,l,f)),(i=n[1])&&e.push(new Re(i,h,o,a,u,d,f)),(i=n[0])&&e.push(new Re(i,s,o,a,h,d,f))}return this}function K0(r){var e=[],t=[],n;for(this._root&&e.push(new Re(this._root,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));n=e.pop();){var i=n.node;if(i.length){var s,o=n.x0,a=n.y0,u=n.z0,l=n.x1,c=n.y1,h=n.z1,d=(o+l)/2,f=(a+c)/2,p=(u+h)/2;(s=i[0])&&e.push(new Re(s,o,a,u,d,f,p)),(s=i[1])&&e.push(new Re(s,d,a,u,l,f,p)),(s=i[2])&&e.push(new Re(s,o,f,u,d,c,p)),(s=i[3])&&e.push(new Re(s,d,f,u,l,c,p)),(s=i[4])&&e.push(new Re(s,o,a,p,d,f,h)),(s=i[5])&&e.push(new Re(s,d,a,p,l,f,h)),(s=i[6])&&e.push(new Re(s,o,f,p,d,c,h)),(s=i[7])&&e.push(new Re(s,d,f,p,l,c,h))}t.push(n)}for(;n=t.pop();)r(n.node,n.x0,n.y0,n.z0,n.x1,n.y1,n.z1);return this}function Y0(r){return r[0]}function Q0(r){return arguments.length?(this._x=r,this):this._x}function Z0(r){return r[1]}function J0(r){return arguments.length?(this._y=r,this):this._y}function eT(r){return r[2]}function tT(r){return arguments.length?(this._z=r,this):this._z}function s_(r,e,t,n){var i=new cd(e??Y0,t??Z0,n??eT,NaN,NaN,NaN,NaN,NaN,NaN);return r==null?i:i.addAll(r)}function cd(r,e,t,n,i,s,o,a,u){this._x=r,this._y=e,this._z=t,this._x0=n,this._y0=i,this._z0=s,this._x1=o,this._y1=a,this._z1=u,this._root=void 0}function pf(r){for(var e={data:r.data},t=e;r=r.next;)t=t.next={data:r.data};return e}var at=s_.prototype=cd.prototype;at.copy=function(){var r=new cd(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),e=this._root,t,n;if(!e)return r;if(!e.length)return r._root=pf(e),r;for(t=[{source:e,target:r._root=new Array(8)}];e=t.pop();)for(var i=0;i<8;++i)(n=e.source[i])&&(n.length?t.push({source:n,target:e.target[i]=new Array(8)}):e.target[i]=pf(n));return r};at.add=O0;at.addAll=U0;at.cover=I0;at.data=k0;at.extent=G0;at.find=V0;at.findAllWithinRadius=z0;at.remove=W0;at.removeAll=H0;at.root=j0;at.size=q0;at.visit=X0;at.visitAfter=K0;at.x=Q0;at.y=J0;at.z=tT;function ir(r){return function(){return r}}function Kn(r){return(r()-.5)*1e-6}function nT(r){return r.index}function gf(r,e){var t=r.get(e);if(!t)throw new Error("node not found: "+e);return t}function rT(r){var e=nT,t=d,n,i=ir(30),s,o,a,u,l,c,h=1;r==null&&(r=[]);function d(m){return 1/Math.min(u[m.source.index],u[m.target.index])}function f(m){for(var y=0,b=r.length;y<h;++y)for(var T=0,x,v,w,R=0,F=0,M=0,O,U;T<b;++T)x=r[T],v=x.source,w=x.target,R=w.x+w.vx-v.x-v.vx||Kn(c),a>1&&(F=w.y+w.vy-v.y-v.vy||Kn(c)),a>2&&(M=w.z+w.vz-v.z-v.vz||Kn(c)),O=Math.sqrt(R*R+F*F+M*M),O=(O-s[T])/O*m*n[T],R*=O,F*=O,M*=O,w.vx-=R*(U=l[T]),a>1&&(w.vy-=F*U),a>2&&(w.vz-=M*U),v.vx+=R*(U=1-U),a>1&&(v.vy+=F*U),a>2&&(v.vz+=M*U)}function p(){if(o){var m,y=o.length,b=r.length,T=new Map(o.map((v,w)=>[e(v,w,o),v])),x;for(m=0,u=new Array(y);m<b;++m)x=r[m],x.index=m,typeof x.source!="object"&&(x.source=gf(T,x.source)),typeof x.target!="object"&&(x.target=gf(T,x.target)),u[x.source.index]=(u[x.source.index]||0)+1,u[x.target.index]=(u[x.target.index]||0)+1;for(m=0,l=new Array(b);m<b;++m)x=r[m],l[m]=u[x.source.index]/(u[x.source.index]+u[x.target.index]);n=new Array(b),g(),s=new Array(b),_()}}function g(){if(o)for(var m=0,y=r.length;m<y;++m)n[m]=+t(r[m],m,r)}function _(){if(o)for(var m=0,y=r.length;m<y;++m)s[m]=+i(r[m],m,r)}return f.initialize=function(m,...y){o=m,c=y.find(b=>typeof b=="function")||Math.random,a=y.find(b=>[1,2,3].includes(b))||2,p()},f.links=function(m){return arguments.length?(r=m,p(),f):r},f.id=function(m){return arguments.length?(e=m,f):e},f.iterations=function(m){return arguments.length?(h=+m,f):h},f.strength=function(m){return arguments.length?(t=typeof m=="function"?m:ir(+m),g(),f):t},f.distance=function(m){return arguments.length?(i=typeof m=="function"?m:ir(+m),_(),f):i},f}var iT={value:()=>{}};function o_(){for(var r=0,e=arguments.length,t={},n;r<e;++r){if(!(n=arguments[r]+"")||n in t||/[\s.]/.test(n))throw new Error("illegal type: "+n);t[n]=[]}return new ja(t)}function ja(r){this._=r}function sT(r,e){return r.trim().split(/^|\s+/).map(function(t){var n="",i=t.indexOf(".");if(i>=0&&(n=t.slice(i+1),t=t.slice(0,i)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}})}ja.prototype=o_.prototype={constructor:ja,on:function(r,e){var t=this._,n=sT(r+"",t),i,s=-1,o=n.length;if(arguments.length<2){for(;++s<o;)if((i=(r=n[s]).type)&&(i=oT(t[i],r.name)))return i;return}if(e!=null&&typeof e!="function")throw new Error("invalid callback: "+e);for(;++s<o;)if(i=(r=n[s]).type)t[i]=mf(t[i],r.name,e);else if(e==null)for(i in t)t[i]=mf(t[i],r.name,null);return this},copy:function(){var r={},e=this._;for(var t in e)r[t]=e[t].slice();return new ja(r)},call:function(r,e){if((i=arguments.length-2)>0)for(var t=new Array(i),n=0,i,s;n<i;++n)t[n]=arguments[n+2];if(!this._.hasOwnProperty(r))throw new Error("unknown type: "+r);for(s=this._[r],n=0,i=s.length;n<i;++n)s[n].value.apply(e,t)},apply:function(r,e,t){if(!this._.hasOwnProperty(r))throw new Error("unknown type: "+r);for(var n=this._[r],i=0,s=n.length;i<s;++i)n[i].value.apply(e,t)}};function oT(r,e){for(var t=0,n=r.length,i;t<n;++t)if((i=r[t]).name===e)return i.value}function mf(r,e,t){for(var n=0,i=r.length;n<i;++n)if(r[n].name===e){r[n]=iT,r=r.slice(0,n).concat(r.slice(n+1));break}return t!=null&&r.push({name:e,value:t}),r}var as=0,Ys=0,As=0,a_=1e3,fu,Qs,pu=0,gi=0,Vu=0,vo=typeof performance=="object"&&performance.now?performance:Date,u_=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(r){setTimeout(r,17)};function l_(){return gi||(u_(aT),gi=vo.now()+Vu)}function aT(){gi=0}function th(){this._call=this._time=this._next=null}th.prototype=c_.prototype={constructor:th,restart:function(r,e,t){if(typeof r!="function")throw new TypeError("callback is not a function");t=(t==null?l_():+t)+(e==null?0:+e),!this._next&&Qs!==this&&(Qs?Qs._next=this:fu=this,Qs=this),this._call=r,this._time=t,nh()},stop:function(){this._call&&(this._call=null,this._time=1/0,nh())}};function c_(r,e,t){var n=new th;return n.restart(r,e,t),n}function uT(){l_(),++as;for(var r=fu,e;r;)(e=gi-r._time)>=0&&r._call.call(void 0,e),r=r._next;--as}function _f(){gi=(pu=vo.now())+Vu,as=Ys=0;try{uT()}finally{as=0,cT(),gi=0}}function lT(){var r=vo.now(),e=r-pu;e>a_&&(Vu-=e,pu=r)}function cT(){for(var r,e=fu,t,n=1/0;e;)e._call?(n>e._time&&(n=e._time),r=e,e=e._next):(t=e._next,e._next=null,e=r?r._next=t:fu=t);Qs=r,nh(n)}function nh(r){if(!as){Ys&&(Ys=clearTimeout(Ys));var e=r-gi;e>24?(r<1/0&&(Ys=setTimeout(_f,r-vo.now()-Vu)),As&&(As=clearInterval(As))):(As||(pu=vo.now(),As=setInterval(lT,a_)),as=1,u_(_f))}}const hT=1664525,dT=1013904223,yf=4294967296;function fT(){let r=1;return()=>(r=(hT*r+dT)%yf)/yf}var bf=3;function dl(r){return r.x}function xf(r){return r.y}function pT(r){return r.z}var gT=10,mT=Math.PI*(3-Math.sqrt(5)),_T=Math.PI*20/(9+Math.sqrt(221));function yT(r,e){e=e||2;var t=Math.min(bf,Math.max(1,Math.round(e))),n,i=1,s=.001,o=1-Math.pow(s,1/300),a=0,u=.6,l=new Map,c=c_(f),h=o_("tick","end"),d=fT();r==null&&(r=[]);function f(){p(),h.call("tick",n),i<s&&(c.stop(),h.call("end",n))}function p(m){var y,b=r.length,T;m===void 0&&(m=1);for(var x=0;x<m;++x)for(i+=(a-i)*o,l.forEach(function(v){v(i)}),y=0;y<b;++y)T=r[y],T.fx==null?T.x+=T.vx*=u:(T.x=T.fx,T.vx=0),t>1&&(T.fy==null?T.y+=T.vy*=u:(T.y=T.fy,T.vy=0)),t>2&&(T.fz==null?T.z+=T.vz*=u:(T.z=T.fz,T.vz=0));return n}function g(){for(var m=0,y=r.length,b;m<y;++m){if(b=r[m],b.index=m,b.fx!=null&&(b.x=b.fx),b.fy!=null&&(b.y=b.fy),b.fz!=null&&(b.z=b.fz),isNaN(b.x)||t>1&&isNaN(b.y)||t>2&&isNaN(b.z)){var T=gT*(t>2?Math.cbrt(.5+m):t>1?Math.sqrt(.5+m):m),x=m*mT,v=m*_T;t===1?b.x=T:t===2?(b.x=T*Math.cos(x),b.y=T*Math.sin(x)):(b.x=T*Math.sin(x)*Math.cos(v),b.y=T*Math.cos(x),b.z=T*Math.sin(x)*Math.sin(v))}(isNaN(b.vx)||t>1&&isNaN(b.vy)||t>2&&isNaN(b.vz))&&(b.vx=0,t>1&&(b.vy=0),t>2&&(b.vz=0))}}function _(m){return m.initialize&&m.initialize(r,d,t),m}return g(),n={tick:p,restart:function(){return c.restart(f),n},stop:function(){return c.stop(),n},numDimensions:function(m){return arguments.length?(t=Math.min(bf,Math.max(1,Math.round(m))),l.forEach(_),n):t},nodes:function(m){return arguments.length?(r=m,g(),l.forEach(_),n):r},alpha:function(m){return arguments.length?(i=+m,n):i},alphaMin:function(m){return arguments.length?(s=+m,n):s},alphaDecay:function(m){return arguments.length?(o=+m,n):+o},alphaTarget:function(m){return arguments.length?(a=+m,n):a},velocityDecay:function(m){return arguments.length?(u=1-m,n):1-u},randomSource:function(m){return arguments.length?(d=m,l.forEach(_),n):d},force:function(m,y){return arguments.length>1?(y==null?l.delete(m):l.set(m,_(y)),n):l.get(m)},find:function(){var m=Array.prototype.slice.call(arguments),y=m.shift()||0,b=(t>1?m.shift():null)||0,T=(t>2?m.shift():null)||0,x=m.shift()||1/0,v=0,w=r.length,R,F,M,O,U,X;for(x*=x,v=0;v<w;++v)U=r[v],R=y-U.x,F=b-(U.y||0),M=T-(U.z||0),O=R*R+F*F+M*M,O<x&&(X=U,x=O);return X},on:function(m,y){return arguments.length>1?(h.on(m,y),n):h.on(m)}}}function bT(){var r,e,t,n,i,s=ir(-30),o,a=1,u=1/0,l=.81;function c(p){var g,_=r.length,m=(e===1?t_(r,dl):e===2?r_(r,dl,xf):e===3?s_(r,dl,xf,pT):null).visitAfter(d);for(i=p,g=0;g<_;++g)t=r[g],m.visit(f)}function h(){if(r){var p,g=r.length,_;for(o=new Array(g),p=0;p<g;++p)_=r[p],o[_.index]=+s(_,p,r)}}function d(p){var g=0,_,m,y=0,b,T,x,v,w=p.length;if(w){for(b=T=x=v=0;v<w;++v)(_=p[v])&&(m=Math.abs(_.value))&&(g+=_.value,y+=m,b+=m*(_.x||0),T+=m*(_.y||0),x+=m*(_.z||0));g*=Math.sqrt(4/w),p.x=b/y,e>1&&(p.y=T/y),e>2&&(p.z=x/y)}else{_=p,_.x=_.data.x,e>1&&(_.y=_.data.y),e>2&&(_.z=_.data.z);do g+=o[_.data.index];while(_=_.next)}p.value=g}function f(p,g,_,m,y){if(!p.value)return!0;var b=[_,m,y][e-1],T=p.x-t.x,x=e>1?p.y-t.y:0,v=e>2?p.z-t.z:0,w=b-g,R=T*T+x*x+v*v;if(w*w/l<R)return R<u&&(T===0&&(T=Kn(n),R+=T*T),e>1&&x===0&&(x=Kn(n),R+=x*x),e>2&&v===0&&(v=Kn(n),R+=v*v),R<a&&(R=Math.sqrt(a*R)),t.vx+=T*p.value*i/R,e>1&&(t.vy+=x*p.value*i/R),e>2&&(t.vz+=v*p.value*i/R)),!0;if(p.length||R>=u)return;(p.data!==t||p.next)&&(T===0&&(T=Kn(n),R+=T*T),e>1&&x===0&&(x=Kn(n),R+=x*x),e>2&&v===0&&(v=Kn(n),R+=v*v),R<a&&(R=Math.sqrt(a*R)));do p.data!==t&&(w=o[p.data.index]*i/R,t.vx+=T*w,e>1&&(t.vy+=x*w),e>2&&(t.vz+=v*w));while(p=p.next)}return c.initialize=function(p,...g){r=p,n=g.find(_=>typeof _=="function")||Math.random,e=g.find(_=>[1,2,3].includes(_))||2,h()},c.strength=function(p){return arguments.length?(s=typeof p=="function"?p:ir(+p),h(),c):s},c.distanceMin=function(p){return arguments.length?(a=p*p,c):Math.sqrt(a)},c.distanceMax=function(p){return arguments.length?(u=p*p,c):Math.sqrt(u)},c.theta=function(p){return arguments.length?(l=p*p,c):Math.sqrt(l)},c}function xT(r,e,t,n){var i,s,o=ir(.1),a,u;typeof r!="function"&&(r=ir(+r)),e==null&&(e=0),t==null&&(t=0),n==null&&(n=0);function l(h){for(var d=0,f=i.length;d<f;++d){var p=i[d],g=p.x-e||1e-6,_=(p.y||0)-t||1e-6,m=(p.z||0)-n||1e-6,y=Math.sqrt(g*g+_*_+m*m),b=(u[d]-y)*a[d]*h/y;p.vx+=g*b,s>1&&(p.vy+=_*b),s>2&&(p.vz+=m*b)}}function c(){if(i){var h,d=i.length;for(a=new Array(d),u=new Array(d),h=0;h<d;++h)u[h]=+r(i[h],h,i),a[h]=isNaN(u[h])?0:+o(i[h],h,i)}}return l.initialize=function(h,...d){i=h,s=d.find(f=>[1,2,3].includes(f))||2,c()},l.strength=function(h){return arguments.length?(o=typeof h=="function"?h:ir(+h),c(),l):o},l.radius=function(h){return arguments.length?(r=typeof h=="function"?h:ir(+h),c(),l):r},l.x=function(h){return arguments.length?(e=+h,l):e},l.y=function(h){return arguments.length?(t=+h,l):t},l.z=function(h){return arguments.length?(n=+h,l):n},l}function vT(r){ST(r);const e=TT(r);return r.on=e.on,r.off=e.off,r.fire=e.fire,r}function TT(r){let e=Object.create(null);return{on:function(t,n,i){if(typeof n!="function")throw new Error("callback is expected to be a function");let s=e[t];return s||(s=e[t]=[]),s.push({callback:n,ctx:i}),r},off:function(t,n){if(typeof t>"u")return e=Object.create(null),r;if(e[t])if(typeof n!="function")delete e[t];else{const o=e[t];for(let a=0;a<o.length;++a)o[a].callback===n&&o.splice(a,1)}return r},fire:function(t){const n=e[t];if(!n)return r;let i;arguments.length>1&&(i=Array.prototype.slice.call(arguments,1));for(let s=0;s<n.length;++s){const o=n[s];o.callback.apply(o.ctx,i)}return r}}}function ST(r){if(!r)throw new Error("Eventify cannot use falsy object as events subject");const e=["on","fire","off"];for(let t=0;t<e.length;++t)if(r.hasOwnProperty(e[t]))throw new Error("Subject cannot be eventified, since it already has property '"+e[t]+"'")}function wT(r){if(r=r||{},"uniqueLinkId"in r&&(console.warn("ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\nUse `multigraph` option instead\n",`
2
+ `,`Note: there is also change in default behavior: From now on each graph
3
+ is considered to be not a multigraph by default (each edge is unique).`),r.multigraph=r.uniqueLinkId),r.multigraph===void 0&&(r.multigraph=!1),typeof Map!="function")throw new Error("ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph");var e=new Map,t=new Map,n={},i=0,s=r.multigraph?T:b,o=[],a=L,u=L,l=L,c=L,h={version:20,addNode:g,addLink:y,removeLink:R,removeNode:m,getNode:_,getNodeCount:x,getLinkCount:v,getEdgeCount:v,getLinksCount:v,getNodesCount:x,getLinks:w,forEachNode:ce,forEachLinkedNode:oe,forEachLink:X,beginUpdate:l,endUpdate:c,clear:U,hasLink:M,hasNode:_,getLink:M,getLinkById:O};return vT(h),d(),h;function d(){var k=h.on;h.on=j;function j(){return h.beginUpdate=l=G,h.endUpdate=c=Z,a=f,u=p,h.on=k,k.apply(h,arguments)}}function f(k,j){o.push({link:k,changeType:j})}function p(k,j){o.push({node:k,changeType:j})}function g(k,j){if(k===void 0)throw new Error("Invalid node identifier");l();var ae=_(k);return ae?(ae.data=j,u(ae,"update")):(ae=new RT(k,j),u(ae,"add")),e.set(k,ae),c(),ae}function _(k){return e.get(k)}function m(k){var j=_(k);if(!j)return!1;l();var ae=j.links;return ae&&(ae.forEach(F),j.links=null),e.delete(k),u(j,"remove"),c(),!0}function y(k,j,ae){l();var Ne=_(k)||g(k),B=_(j)||g(j),I=s(k,j,ae),J=t.has(I.id);return t.set(I.id,I),vf(Ne,I),k!==j&&vf(B,I),a(I,J?"update":"add"),c(),I}function b(k,j,ae){var Ne=zo(k,j),B=t.get(Ne);return B?(B.data=ae,B):new Tf(k,j,ae,Ne)}function T(k,j,ae){var Ne=zo(k,j),B=n.hasOwnProperty(Ne);if(B||M(k,j)){B||(n[Ne]=0);var I="@"+ ++n[Ne];Ne=zo(k+I,j+I)}return new Tf(k,j,ae,Ne)}function x(){return e.size}function v(){return t.size}function w(k){var j=_(k);return j?j.links:null}function R(k,j){return j!==void 0&&(k=M(k,j)),F(k)}function F(k){if(!k||!t.get(k.id))return!1;l(),t.delete(k.id);var j=_(k.fromId),ae=_(k.toId);return j&&j.links.delete(k),ae&&ae.links.delete(k),a(k,"remove"),c(),!0}function M(k,j){if(!(k===void 0||j===void 0))return t.get(zo(k,j))}function O(k){if(k!==void 0)return t.get(k)}function U(){l(),ce(function(k){m(k.id)}),c()}function X(k){if(typeof k=="function")for(var j=t.values(),ae=j.next();!ae.done;){if(k(ae.value))return!0;ae=j.next()}}function oe(k,j,ae){var Ne=_(k);if(Ne&&Ne.links&&typeof j=="function")return ae?ue(Ne.links,k,j):H(Ne.links,k,j)}function H(k,j,ae){for(var Ne,B=k.values(),I=B.next();!I.done;){var J=I.value,ye=J.fromId===j?J.toId:J.fromId;if(Ne=ae(e.get(ye),J),Ne)return!0;I=B.next()}}function ue(k,j,ae){for(var Ne,B=k.values(),I=B.next();!I.done;){var J=I.value;if(J.fromId===j&&(Ne=ae(e.get(J.toId),J),Ne))return!0;I=B.next()}}function L(){}function G(){i+=1}function Z(){i-=1,i===0&&o.length>0&&(h.fire("changed",o),o.length=0)}function ce(k){if(typeof k!="function")throw new Error("Function is expected to iterate over graph nodes. You passed "+k);for(var j=e.values(),ae=j.next();!ae.done;){if(k(ae.value))return!0;ae=j.next()}}}function RT(r,e){this.id=r,this.links=null,this.data=e}function vf(r,e){r.links?r.links.add(e):r.links=new Set([e])}function Tf(r,e,t,n){this.fromId=r,this.toId=e,this.data=t,this.id=n}function zo(r,e){return r.toString()+"👉 "+e.toString()}var Wo={exports:{}},Ci={exports:{}},fl,Sf;function h_(){return Sf||(Sf=1,fl=function(e){return e===0?"x":e===1?"y":e===2?"z":"c"+(e+1)}),fl}var pl,wf;function ms(){if(wf)return pl;wf=1;const r=h_();return pl=function(t){return n;function n(i,s){let o=s&&s.indent||0,a=s&&s.join!==void 0?s.join:`
4
+ `,u=Array(o+1).join(" "),l=[];for(let c=0;c<t;++c){let h=r(c),d=c===0?"":u;l.push(d+i.replace(/{var}/g,h))}return l.join(a)}},pl}var Rf;function AT(){if(Rf)return Ci.exports;Rf=1;const r=ms();Ci.exports=e,Ci.exports.generateCreateBodyFunctionBody=t,Ci.exports.getVectorCode=i,Ci.exports.getBodyCode=n;function e(s,o){let a=t(s,o),{Body:u}=new Function(a)();return u}function t(s,o){return`
5
+ ${i(s,o)}
6
+ ${n(s)}
7
+ return {Body: Body, Vector: Vector};
8
+ `}function n(s){let o=r(s),a=o("{var}",{join:", "});return`
9
+ function Body(${a}) {
10
+ this.isPinned = false;
11
+ this.pos = new Vector(${a});
12
+ this.force = new Vector();
13
+ this.velocity = new Vector();
14
+ this.mass = 1;
15
+
16
+ this.springCount = 0;
17
+ this.springLength = 0;
18
+ }
19
+
20
+ Body.prototype.reset = function() {
21
+ this.force.reset();
22
+ this.springCount = 0;
23
+ this.springLength = 0;
24
+ }
25
+
26
+ Body.prototype.setPosition = function (${a}) {
27
+ ${o("this.pos.{var} = {var} || 0;",{indent:2})}
28
+ };`}function i(s,o){let a=r(s),u="";return o&&(u=`${a(`
29
+ var v{var};
30
+ Object.defineProperty(this, '{var}', {
31
+ set: function(v) {
32
+ if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');
33
+ v{var} = v;
34
+ },
35
+ get: function() { return v{var}; }
36
+ });`)}`),`function Vector(${a("{var}",{join:", "})}) {
37
+ ${u}
38
+ if (typeof arguments[0] === 'object') {
39
+ // could be another vector
40
+ let v = arguments[0];
41
+ ${a('if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");',{indent:4})}
42
+ ${a("this.{var} = v.{var};",{indent:4})}
43
+ } else {
44
+ ${a('this.{var} = typeof {var} === "number" ? {var} : 0;',{indent:4})}
45
+ }
46
+ }
47
+
48
+ Vector.prototype.reset = function () {
49
+ ${a("this.{var} = ",{join:""})}0;
50
+ };`}return Ci.exports}var Vn={exports:{}},Af;function NT(){if(Af)return Vn.exports;Af=1;const r=ms(),e=h_();Vn.exports=t,Vn.exports.generateQuadTreeFunctionBody=n,Vn.exports.getInsertStackCode=u,Vn.exports.getQuadNodeCode=a,Vn.exports.isSamePosition=i,Vn.exports.getChildBodyCode=o,Vn.exports.setChildBodyCode=s;function t(l){let c=n(l);return new Function(c)()}function n(l){let c=r(l),h=Math.pow(2,l);return`
51
+ ${u()}
52
+ ${a(l)}
53
+ ${i(l)}
54
+ ${o(l)}
55
+ ${s(l)}
56
+
57
+ function createQuadTree(options, random) {
58
+ options = options || {};
59
+ options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;
60
+ options.theta = typeof options.theta === 'number' ? options.theta : 0.8;
61
+
62
+ var gravity = options.gravity;
63
+ var updateQueue = [];
64
+ var insertStack = new InsertStack();
65
+ var theta = options.theta;
66
+
67
+ var nodesCache = [];
68
+ var currentInCache = 0;
69
+ var root = newNode();
70
+
71
+ return {
72
+ insertBodies: insertBodies,
73
+
74
+ /**
75
+ * Gets root node if it is present
76
+ */
77
+ getRoot: function() {
78
+ return root;
79
+ },
80
+
81
+ updateBodyForce: update,
82
+
83
+ options: function(newOptions) {
84
+ if (newOptions) {
85
+ if (typeof newOptions.gravity === 'number') {
86
+ gravity = newOptions.gravity;
87
+ }
88
+ if (typeof newOptions.theta === 'number') {
89
+ theta = newOptions.theta;
90
+ }
91
+
92
+ return this;
93
+ }
94
+
95
+ return {
96
+ gravity: gravity,
97
+ theta: theta
98
+ };
99
+ }
100
+ };
101
+
102
+ function newNode() {
103
+ // To avoid pressure on GC we reuse nodes.
104
+ var node = nodesCache[currentInCache];
105
+ if (node) {
106
+ ${g(" node.")}
107
+ node.body = null;
108
+ node.mass = ${c("node.mass_{var} = ",{join:""})}0;
109
+ ${c("node.min_{var} = node.max_{var} = ",{join:""})}0;
110
+ } else {
111
+ node = new QuadNode();
112
+ nodesCache[currentInCache] = node;
113
+ }
114
+
115
+ ++currentInCache;
116
+ return node;
117
+ }
118
+
119
+ function update(sourceBody) {
120
+ var queue = updateQueue;
121
+ var v;
122
+ ${c("var d{var};",{indent:4})}
123
+ var r;
124
+ ${c("var f{var} = 0;",{indent:4})}
125
+ var queueLength = 1;
126
+ var shiftIdx = 0;
127
+ var pushIdx = 1;
128
+
129
+ queue[0] = root;
130
+
131
+ while (queueLength) {
132
+ var node = queue[shiftIdx];
133
+ var body = node.body;
134
+
135
+ queueLength -= 1;
136
+ shiftIdx += 1;
137
+ var differentBody = (body !== sourceBody);
138
+ if (body && differentBody) {
139
+ // If the current node is a leaf node (and it is not source body),
140
+ // calculate the force exerted by the current node on body, and add this
141
+ // amount to body's net force.
142
+ ${c("d{var} = body.pos.{var} - sourceBody.pos.{var};",{indent:8})}
143
+ r = Math.sqrt(${c("d{var} * d{var}",{join:" + "})});
144
+
145
+ if (r === 0) {
146
+ // Poor man's protection against zero distance.
147
+ ${c("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}
148
+ r = Math.sqrt(${c("d{var} * d{var}",{join:" + "})});
149
+ }
150
+
151
+ // This is standard gravitation force calculation but we divide
152
+ // by r^3 to save two operations when normalizing force vector.
153
+ v = gravity * body.mass * sourceBody.mass / (r * r * r);
154
+ ${c("f{var} += v * d{var};",{indent:8})}
155
+ } else if (differentBody) {
156
+ // Otherwise, calculate the ratio s / r, where s is the width of the region
157
+ // represented by the internal node, and r is the distance between the body
158
+ // and the node's center-of-mass
159
+ ${c("d{var} = node.mass_{var} / node.mass - sourceBody.pos.{var};",{indent:8})}
160
+ r = Math.sqrt(${c("d{var} * d{var}",{join:" + "})});
161
+
162
+ if (r === 0) {
163
+ // Sorry about code duplication. I don't want to create many functions
164
+ // right away. Just want to see performance first.
165
+ ${c("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}
166
+ r = Math.sqrt(${c("d{var} * d{var}",{join:" + "})});
167
+ }
168
+ // If s / r < θ, treat this internal node as a single body, and calculate the
169
+ // force it exerts on sourceBody, and add this amount to sourceBody's net force.
170
+ if ((node.max_${e(0)} - node.min_${e(0)}) / r < theta) {
171
+ // in the if statement above we consider node's width only
172
+ // because the region was made into square during tree creation.
173
+ // Thus there is no difference between using width or height.
174
+ v = gravity * node.mass * sourceBody.mass / (r * r * r);
175
+ ${c("f{var} += v * d{var};",{indent:10})}
176
+ } else {
177
+ // Otherwise, run the procedure recursively on each of the current node's children.
178
+
179
+ // I intentionally unfolded this loop, to save several CPU cycles.
180
+ ${p()}
181
+ }
182
+ }
183
+ }
184
+
185
+ ${c("sourceBody.force.{var} += f{var};",{indent:4})}
186
+ }
187
+
188
+ function insertBodies(bodies) {
189
+ ${c("var {var}min = Number.MAX_VALUE;",{indent:4})}
190
+ ${c("var {var}max = Number.MIN_VALUE;",{indent:4})}
191
+ var i = bodies.length;
192
+
193
+ // To reduce quad tree depth we are looking for exact bounding box of all particles.
194
+ while (i--) {
195
+ var pos = bodies[i].pos;
196
+ ${c("if (pos.{var} < {var}min) {var}min = pos.{var};",{indent:6})}
197
+ ${c("if (pos.{var} > {var}max) {var}max = pos.{var};",{indent:6})}
198
+ }
199
+
200
+ // Makes the bounds square.
201
+ var maxSideLength = -Infinity;
202
+ ${c("if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;",{indent:4})}
203
+
204
+ currentInCache = 0;
205
+ root = newNode();
206
+ ${c("root.min_{var} = {var}min;",{indent:4})}
207
+ ${c("root.max_{var} = {var}min + maxSideLength;",{indent:4})}
208
+
209
+ i = bodies.length - 1;
210
+ if (i >= 0) {
211
+ root.body = bodies[i];
212
+ }
213
+ while (i--) {
214
+ insert(bodies[i], root);
215
+ }
216
+ }
217
+
218
+ function insert(newBody) {
219
+ insertStack.reset();
220
+ insertStack.push(root, newBody);
221
+
222
+ while (!insertStack.isEmpty()) {
223
+ var stackItem = insertStack.pop();
224
+ var node = stackItem.node;
225
+ var body = stackItem.body;
226
+
227
+ if (!node.body) {
228
+ // This is internal node. Update the total mass of the node and center-of-mass.
229
+ ${c("var {var} = body.pos.{var};",{indent:8})}
230
+ node.mass += body.mass;
231
+ ${c("node.mass_{var} += body.mass * {var};",{indent:8})}
232
+
233
+ // Recursively insert the body in the appropriate quadrant.
234
+ // But first find the appropriate quadrant.
235
+ var quadIdx = 0; // Assume we are in the 0's quad.
236
+ ${c("var min_{var} = node.min_{var};",{indent:8})}
237
+ ${c("var max_{var} = (min_{var} + node.max_{var}) / 2;",{indent:8})}
238
+
239
+ ${f(8)}
240
+
241
+ var child = getChild(node, quadIdx);
242
+
243
+ if (!child) {
244
+ // The node is internal but this quadrant is not taken. Add
245
+ // subnode to it.
246
+ child = newNode();
247
+ ${c("child.min_{var} = min_{var};",{indent:10})}
248
+ ${c("child.max_{var} = max_{var};",{indent:10})}
249
+ child.body = body;
250
+
251
+ setChild(node, quadIdx, child);
252
+ } else {
253
+ // continue searching in this quadrant.
254
+ insertStack.push(child, body);
255
+ }
256
+ } else {
257
+ // We are trying to add to the leaf node.
258
+ // We have to convert current leaf into internal node
259
+ // and continue adding two nodes.
260
+ var oldBody = node.body;
261
+ node.body = null; // internal nodes do not cary bodies
262
+
263
+ if (isSamePosition(oldBody.pos, body.pos)) {
264
+ // Prevent infinite subdivision by bumping one node
265
+ // anywhere in this quadrant
266
+ var retriesCount = 3;
267
+ do {
268
+ var offset = random.nextDouble();
269
+ ${c("var d{var} = (node.max_{var} - node.min_{var}) * offset;",{indent:12})}
270
+
271
+ ${c("oldBody.pos.{var} = node.min_{var} + d{var};",{indent:12})}
272
+ retriesCount -= 1;
273
+ // Make sure we don't bump it out of the box. If we do, next iteration should fix it
274
+ } while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));
275
+
276
+ if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {
277
+ // This is very bad, we ran out of precision.
278
+ // if we do not return from the method we'll get into
279
+ // infinite loop here. So we sacrifice correctness of layout, and keep the app running
280
+ // Next layout iteration should get larger bounding box in the first step and fix this
281
+ return;
282
+ }
283
+ }
284
+ // Next iteration should subdivide node further.
285
+ insertStack.push(node, oldBody);
286
+ insertStack.push(node, body);
287
+ }
288
+ }
289
+ }
290
+ }
291
+ return createQuadTree;
292
+
293
+ `;function f(_){let m=[],y=Array(_+1).join(" ");for(let b=0;b<l;++b)m.push(y+`if (${e(b)} > max_${e(b)}) {`),m.push(y+` quadIdx = quadIdx + ${Math.pow(2,b)};`),m.push(y+` min_${e(b)} = max_${e(b)};`),m.push(y+` max_${e(b)} = node.max_${e(b)};`),m.push(y+"}");return m.join(`
294
+ `)}function p(){let _=Array(11).join(" "),m=[];for(let y=0;y<h;++y)m.push(_+`if (node.quad${y}) {`),m.push(_+` queue[pushIdx] = node.quad${y};`),m.push(_+" queueLength += 1;"),m.push(_+" pushIdx += 1;"),m.push(_+"}");return m.join(`
295
+ `)}function g(_){let m=[];for(let y=0;y<h;++y)m.push(`${_}quad${y} = null;`);return m.join(`
296
+ `)}}function i(l){let c=r(l);return`
297
+ function isSamePosition(point1, point2) {
298
+ ${c("var d{var} = Math.abs(point1.{var} - point2.{var});",{indent:2})}
299
+
300
+ return ${c("d{var} < 1e-8",{join:" && "})};
301
+ }
302
+ `}function s(l){var c=Math.pow(2,l);return`
303
+ function setChild(node, idx, child) {
304
+ ${h()}
305
+ }`;function h(){let d=[];for(let f=0;f<c;++f){let p=f===0?" ":" else ";d.push(`${p}if (idx === ${f}) node.quad${f} = child;`)}return d.join(`
306
+ `)}}function o(l){return`function getChild(node, idx) {
307
+ ${c()}
308
+ return null;
309
+ }`;function c(){let h=[],d=Math.pow(2,l);for(let f=0;f<d;++f)h.push(` if (idx === ${f}) return node.quad${f};`);return h.join(`
310
+ `)}}function a(l){let c=r(l),h=Math.pow(2,l);var d=`
311
+ function QuadNode() {
312
+ // body stored inside this node. In quad tree only leaf nodes (by construction)
313
+ // contain bodies:
314
+ this.body = null;
315
+
316
+ // Child nodes are stored in quads. Each quad is presented by number:
317
+ // 0 | 1
318
+ // -----
319
+ // 2 | 3
320
+ ${f(" this.")}
321
+
322
+ // Total mass of current node
323
+ this.mass = 0;
324
+
325
+ // Center of mass coordinates
326
+ ${c("this.mass_{var} = 0;",{indent:2})}
327
+
328
+ // bounding box coordinates
329
+ ${c("this.min_{var} = 0;",{indent:2})}
330
+ ${c("this.max_{var} = 0;",{indent:2})}
331
+ }
332
+ `;return d;function f(p){let g=[];for(let _=0;_<h;++_)g.push(`${p}quad${_} = null;`);return g.join(`
333
+ `)}}function u(){return`
334
+ /**
335
+ * Our implementation of QuadTree is non-recursive to avoid GC hit
336
+ * This data structure represent stack of elements
337
+ * which we are trying to insert into quad tree.
338
+ */
339
+ function InsertStack () {
340
+ this.stack = [];
341
+ this.popIdx = 0;
342
+ }
343
+
344
+ InsertStack.prototype = {
345
+ isEmpty: function() {
346
+ return this.popIdx === 0;
347
+ },
348
+ push: function (node, body) {
349
+ var item = this.stack[this.popIdx];
350
+ if (!item) {
351
+ // we are trying to avoid memory pressure: create new element
352
+ // only when absolutely necessary
353
+ this.stack[this.popIdx] = new InsertStackElement(node, body);
354
+ } else {
355
+ item.node = node;
356
+ item.body = body;
357
+ }
358
+ ++this.popIdx;
359
+ },
360
+ pop: function () {
361
+ if (this.popIdx > 0) {
362
+ return this.stack[--this.popIdx];
363
+ }
364
+ },
365
+ reset: function () {
366
+ this.popIdx = 0;
367
+ }
368
+ };
369
+
370
+ function InsertStackElement(node, body) {
371
+ this.node = node; // QuadTree node
372
+ this.body = body; // physical body which needs to be inserted to node
373
+ }
374
+ `}return Vn.exports}var Ho={exports:{}},Nf;function ET(){if(Nf)return Ho.exports;Nf=1,Ho.exports=e,Ho.exports.generateFunctionBody=t;const r=ms();function e(n){let i=t(n);return new Function("bodies","settings","random",i)}function t(n){let i=r(n);return`
375
+ var boundingBox = {
376
+ ${i("min_{var}: 0, max_{var}: 0,",{indent:4})}
377
+ };
378
+
379
+ return {
380
+ box: boundingBox,
381
+
382
+ update: updateBoundingBox,
383
+
384
+ reset: resetBoundingBox,
385
+
386
+ getBestNewPosition: function (neighbors) {
387
+ var ${i("base_{var} = 0",{join:", "})};
388
+
389
+ if (neighbors.length) {
390
+ for (var i = 0; i < neighbors.length; ++i) {
391
+ let neighborPos = neighbors[i].pos;
392
+ ${i("base_{var} += neighborPos.{var};",{indent:10})}
393
+ }
394
+
395
+ ${i("base_{var} /= neighbors.length;",{indent:8})}
396
+ } else {
397
+ ${i("base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;",{indent:8})}
398
+ }
399
+
400
+ var springLength = settings.springLength;
401
+ return {
402
+ ${i("{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,",{indent:8})}
403
+ };
404
+ }
405
+ };
406
+
407
+ function updateBoundingBox() {
408
+ var i = bodies.length;
409
+ if (i === 0) return; // No bodies - no borders.
410
+
411
+ ${i("var max_{var} = -Infinity;",{indent:4})}
412
+ ${i("var min_{var} = Infinity;",{indent:4})}
413
+
414
+ while(i--) {
415
+ // this is O(n), it could be done faster with quadtree, if we check the root node bounds
416
+ var bodyPos = bodies[i].pos;
417
+ ${i("if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};",{indent:6})}
418
+ ${i("if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};",{indent:6})}
419
+ }
420
+
421
+ ${i("boundingBox.min_{var} = min_{var};",{indent:4})}
422
+ ${i("boundingBox.max_{var} = max_{var};",{indent:4})}
423
+ }
424
+
425
+ function resetBoundingBox() {
426
+ ${i("boundingBox.min_{var} = boundingBox.max_{var} = 0;",{indent:4})}
427
+ }
428
+ `}return Ho.exports}var jo={exports:{}},Ef;function CT(){if(Ef)return jo.exports;Ef=1;const r=ms();jo.exports=e,jo.exports.generateCreateDragForceFunctionBody=t;function e(n){let i=t(n);return new Function("options",i)}function t(n){return`
429
+ if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');
430
+
431
+ return {
432
+ update: function(body) {
433
+ ${r(n)("body.force.{var} -= options.dragCoefficient * body.velocity.{var};",{indent:6})}
434
+ }
435
+ };
436
+ `}return jo.exports}var qo={exports:{}},Cf;function MT(){if(Cf)return qo.exports;Cf=1;const r=ms();qo.exports=e,qo.exports.generateCreateSpringForceFunctionBody=t;function e(n){let i=t(n);return new Function("options","random",i)}function t(n){let i=r(n);return`
437
+ if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');
438
+ if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');
439
+
440
+ return {
441
+ /**
442
+ * Updates forces acting on a spring
443
+ */
444
+ update: function (spring) {
445
+ var body1 = spring.from;
446
+ var body2 = spring.to;
447
+ var length = spring.length < 0 ? options.springLength : spring.length;
448
+ ${i("var d{var} = body2.pos.{var} - body1.pos.{var};",{indent:6})}
449
+ var r = Math.sqrt(${i("d{var} * d{var}",{join:" + "})});
450
+
451
+ if (r === 0) {
452
+ ${i("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:8})}
453
+ r = Math.sqrt(${i("d{var} * d{var}",{join:" + "})});
454
+ }
455
+
456
+ var d = r - length;
457
+ var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;
458
+
459
+ ${i("body1.force.{var} += coefficient * d{var}",{indent:6})};
460
+ body1.springCount += 1;
461
+ body1.springLength += r;
462
+
463
+ ${i("body2.force.{var} -= coefficient * d{var}",{indent:6})};
464
+ body2.springCount += 1;
465
+ body2.springLength += r;
466
+ }
467
+ };
468
+ `}return qo.exports}var Xo={exports:{}},Mf;function PT(){if(Mf)return Xo.exports;Mf=1;const r=ms();Xo.exports=e,Xo.exports.generateIntegratorFunctionBody=t;function e(n){let i=t(n);return new Function("bodies","timeStep","adaptiveTimeStepWeight",i)}function t(n){let i=r(n);return`
469
+ var length = bodies.length;
470
+ if (length === 0) return 0;
471
+
472
+ ${i("var d{var} = 0, t{var} = 0;",{indent:2})}
473
+
474
+ for (var i = 0; i < length; ++i) {
475
+ var body = bodies[i];
476
+ if (body.isPinned) continue;
477
+
478
+ if (adaptiveTimeStepWeight && body.springCount) {
479
+ timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);
480
+ }
481
+
482
+ var coeff = timeStep / body.mass;
483
+
484
+ ${i("body.velocity.{var} += coeff * body.force.{var};",{indent:4})}
485
+ ${i("var v{var} = body.velocity.{var};",{indent:4})}
486
+ var v = Math.sqrt(${i("v{var} * v{var}",{join:" + "})});
487
+
488
+ if (v > 1) {
489
+ // We normalize it so that we move within timeStep range.
490
+ // for the case when v <= 1 - we let velocity to fade out.
491
+ ${i("body.velocity.{var} = v{var} / v;",{indent:6})}
492
+ }
493
+
494
+ ${i("d{var} = timeStep * body.velocity.{var};",{indent:4})}
495
+
496
+ ${i("body.pos.{var} += d{var};",{indent:4})}
497
+
498
+ ${i("t{var} += Math.abs(d{var});",{indent:4})}
499
+ }
500
+
501
+ return (${i("t{var} * t{var}",{join:" + "})})/length;
502
+ `}return Xo.exports}var gl,Pf;function BT(){if(Pf)return gl;Pf=1,gl=r;function r(e,t,n,i){this.from=e,this.to=t,this.length=n,this.coefficient=i}return gl}var ml,Bf;function FT(){if(Bf)return ml;Bf=1,ml=r;function r(e,t){var n;if(e||(e={}),t){for(n in t)if(t.hasOwnProperty(n)){var i=e.hasOwnProperty(n),s=typeof t[n],o=!i||typeof e[n]!==s;o?e[n]=t[n]:s==="object"&&(e[n]=r(e[n],t[n]))}}return e}return ml}var _l,Ff;function d_(){if(Ff)return _l;Ff=1;function r(n){t(n);const i=e(n);return n.on=i.on,n.off=i.off,n.fire=i.fire,n}function e(n){let i=Object.create(null);return{on:function(s,o,a){if(typeof o!="function")throw new Error("callback is expected to be a function");let u=i[s];return u||(u=i[s]=[]),u.push({callback:o,ctx:a}),n},off:function(s,o){if(typeof s>"u")return i=Object.create(null),n;if(i[s])if(typeof o!="function")delete i[s];else{const a=i[s];for(let u=0;u<a.length;++u)a[u].callback===o&&a.splice(u,1)}return n},fire:function(s){const o=i[s];if(!o)return n;let a;arguments.length>1&&(a=Array.prototype.slice.call(arguments,1));for(let u=0;u<o.length;++u){const l=o[u];l.callback.apply(l.ctx,a)}return n}}}function t(n){if(!n)throw new Error("Eventify cannot use falsy object as events subject");const i=["on","fire","off"];for(let s=0;s<i.length;++s)if(n.hasOwnProperty(i[s]))throw new Error("Subject cannot be eventified, since it already has property '"+i[s]+"'")}return _l=r,_l}var Ns={exports:{}},Df;function DT(){if(Df)return Ns.exports;Df=1,Ns.exports=r,Ns.exports.random=r,Ns.exports.randomIterator=a;function r(u){var l=typeof u=="number"?u:+new Date;return new e(l)}function e(u){this.seed=u}e.prototype.next=o,e.prototype.nextDouble=s,e.prototype.uniform=s,e.prototype.gaussian=t,e.prototype.random=s;function t(){var u,l,c;do l=this.nextDouble()*2-1,c=this.nextDouble()*2-1,u=l*l+c*c;while(u>=1||u===0);return l*Math.sqrt(-2*Math.log(u)/u)}e.prototype.levy=n;function n(){var u=1.5,l=Math.pow(i(1+u)*Math.sin(Math.PI*u/2)/(i((1+u)/2)*u*Math.pow(2,(u-1)/2)),1/u);return this.gaussian()*l/Math.pow(Math.abs(this.gaussian()),1/u)}function i(u){return Math.sqrt(2*Math.PI/u)*Math.pow(1/Math.E*(u+1/(12*u-1/(10*u))),u)}function s(){var u=this.seed;return u=u+2127912214+(u<<12)&4294967295,u=(u^3345072700^u>>>19)&4294967295,u=u+374761393+(u<<5)&4294967295,u=(u+3550635116^u<<9)&4294967295,u=u+4251993797+(u<<3)&4294967295,u=(u^3042594569^u>>>16)&4294967295,this.seed=u,(u&268435455)/268435456}function o(u){return Math.floor(this.nextDouble()*u)}function a(u,l){var c=l||r();if(typeof c.next!="function")throw new Error("customRandom does not match expected API: next() function is missing");return{forEach:d,shuffle:h};function h(){var f,p,g;for(f=u.length-1;f>0;--f)p=c.next(f+1),g=u[p],u[p]=u[f],u[f]=g;return u}function d(f){var p,g,_;for(p=u.length-1;p>0;--p)g=c.next(p+1),_=u[g],u[g]=u[p],u[p]=_,f(_);u.length&&f(u[0])}}return Ns.exports}var yl,Lf;function Of(){if(Lf)return yl;Lf=1,yl=a;var r=AT(),e=NT(),t=ET(),n=CT(),i=MT(),s=PT(),o={};function a(c){var h=BT(),d=FT(),f=d_();if(c){if(c.springCoeff!==void 0)throw new Error("springCoeff was renamed to springCoefficient");if(c.dragCoeff!==void 0)throw new Error("dragCoeff was renamed to dragCoefficient")}c=d(c,{springLength:10,springCoefficient:.8,gravity:-12,theta:.8,dragCoefficient:.9,timeStep:.5,adaptiveTimeStepWeight:0,dimensions:2,debug:!1});var p=o[c.dimensions];if(!p){var g=c.dimensions;p={Body:r(g,c.debug),createQuadTree:e(g),createBounds:t(g),createDragForce:n(g),createSpringForce:i(g),integrate:s(g)},o[g]=p}var _=p.Body,m=p.createQuadTree,y=p.createBounds,b=p.createDragForce,T=p.createSpringForce,x=p.integrate,v=B=>new _(B),w=DT().random(42),R=[],F=[],M=m(c,w),O=y(R,c,w),U=T(c,w),X=b(c),oe=0,H=[],ue=new Map,L=0;ce("nbody",ae),ce("spring",Ne);var G={bodies:R,quadTree:M,springs:F,settings:c,addForce:ce,removeForce:k,getForces:j,step:function(){for(var B=0;B<H.length;++B)H[B](L);var I=x(R,c.timeStep,c.adaptiveTimeStepWeight);return L+=1,I},addBody:function(B){if(!B)throw new Error("Body is required");return R.push(B),B},addBodyAt:function(B){if(!B)throw new Error("Body position is required");var I=v(B);return R.push(I),I},removeBody:function(B){if(B){var I=R.indexOf(B);if(!(I<0))return R.splice(I,1),R.length===0&&O.reset(),!0}},addSpring:function(B,I,J,ye){if(!B||!I)throw new Error("Cannot add null spring to force simulator");typeof J!="number"&&(J=-1);var Ge=new h(B,I,J,ye>=0?ye:-1);return F.push(Ge),Ge},getTotalMovement:function(){return oe},removeSpring:function(B){if(B){var I=F.indexOf(B);if(I>-1)return F.splice(I,1),!0}},getBestNewBodyPosition:function(B){return O.getBestNewPosition(B)},getBBox:Z,getBoundingBox:Z,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(B){return B!==void 0?(c.gravity=B,M.options({gravity:B}),this):c.gravity},theta:function(B){return B!==void 0?(c.theta=B,M.options({theta:B}),this):c.theta},random:w};return u(c,G),f(G),G;function Z(){return O.update(),O.box}function ce(B,I){if(ue.has(B))throw new Error("Force "+B+" is already added");ue.set(B,I),H.push(I)}function k(B){var I=H.indexOf(ue.get(B));I<0||(H.splice(I,1),ue.delete(B))}function j(){return ue}function ae(){if(R.length!==0){M.insertBodies(R);for(var B=R.length;B--;){var I=R[B];I.isPinned||(I.reset(),M.updateBodyForce(I),X.update(I))}}}function Ne(){for(var B=F.length;B--;)U.update(F[B])}}function u(c,h){for(var d in c)l(c,h,d)}function l(c,h,d){if(c.hasOwnProperty(d)&&typeof h[d]!="function"){var f=Number.isFinite(c[d]);f?h[d]=function(p){if(p!==void 0){if(!Number.isFinite(p))throw new Error("Value of "+d+" should be a valid number.");return c[d]=p,h}return c[d]}:h[d]=function(p){return p!==void 0?(c[d]=p,h):c[d]}}}return yl}var Uf;function LT(){if(Uf)return Wo.exports;Uf=1,Wo.exports=e,Wo.exports.simulator=Of();var r=d_();function e(n,i){if(!n)throw new Error("Graph structure cannot be undefined");var s=i&&i.createSimulator||Of(),o=s(i);if(Array.isArray(i))throw new Error("Physics settings is expected to be an object");var a=n.version>19?ue:H;i&&typeof i.nodeMass=="function"&&(a=i.nodeMass);var u=new Map,l={},c=0,h=o.settings.springTransform||t;v(),b();var d=!1,f={step:function(){if(c===0)return p(!0),!0;var L=o.step();f.lastMove=L,f.fire("step");var G=L/c,Z=G<=.01;return p(Z),Z},getNodePosition:function(L){return oe(L).pos},setNodePosition:function(L){var G=oe(L);G.setPosition.apply(G,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(L){var G=l[L];if(G)return{from:G.from.pos,to:G.to.pos}},getGraphRect:function(){return o.getBBox()},forEachBody:g,pinNode:function(L,G){var Z=oe(L.id);Z.isPinned=!!G},isNodePinned:function(L){return oe(L.id).isPinned},dispose:function(){n.off("changed",x),f.fire("disposed")},getBody:y,getSpring:m,getForceVectorLength:_,simulator:o,graph:n,lastMove:0};return r(f),f;function p(L){d!==L&&(d=L,T(L))}function g(L){u.forEach(L)}function _(){var L=0,G=0;return g(function(Z){L+=Math.abs(Z.force.x),G+=Math.abs(Z.force.y)}),Math.sqrt(L*L+G*G)}function m(L,G){var Z;if(G===void 0)typeof L!="object"?Z=L:Z=L.id;else{var ce=n.hasLink(L,G);if(!ce)return;Z=ce.id}return l[Z]}function y(L){return u.get(L)}function b(){n.on("changed",x)}function T(L){f.fire("stable",L)}function x(L){for(var G=0;G<L.length;++G){var Z=L[G];Z.changeType==="add"?(Z.node&&w(Z.node.id),Z.link&&F(Z.link)):Z.changeType==="remove"&&(Z.node&&R(Z.node),Z.link&&M(Z.link))}c=n.getNodesCount()}function v(){c=0,n.forEachNode(function(L){w(L.id),c+=1}),n.forEachLink(F)}function w(L){var G=u.get(L);if(!G){var Z=n.getNode(L);if(!Z)throw new Error("initBody() was called with unknown node id");var ce=Z.position;if(!ce){var k=O(Z);ce=o.getBestNewBodyPosition(k)}G=o.addBodyAt(ce),G.id=L,u.set(L,G),U(L),X(Z)&&(G.isPinned=!0)}}function R(L){var G=L.id,Z=u.get(G);Z&&(u.delete(G),o.removeBody(Z))}function F(L){U(L.fromId),U(L.toId);var G=u.get(L.fromId),Z=u.get(L.toId),ce=o.addSpring(G,Z,L.length);h(L,ce),l[L.id]=ce}function M(L){var G=l[L.id];if(G){var Z=n.getNode(L.fromId),ce=n.getNode(L.toId);Z&&U(Z.id),ce&&U(ce.id),delete l[L.id],o.removeSpring(G)}}function O(L){var G=[];if(!L.links)return G;for(var Z=Math.min(L.links.length,2),ce=0;ce<Z;++ce){var k=L.links[ce],j=k.fromId!==L.id?u.get(k.fromId):u.get(k.toId);j&&j.pos&&G.push(j)}return G}function U(L){var G=u.get(L);if(G.mass=a(L),Number.isNaN(G.mass))throw new Error("Node mass should be a number")}function X(L){return L&&(L.isPinned||L.data&&L.data.isPinned)}function oe(L){var G=u.get(L);return G||(w(L),G=u.get(L)),G}function H(L){var G=n.getLinks(L);return G?1+G.length/3:1}function ue(L){var G=n.getLinks(L);return G?1+G.size/3:1}}function t(){}return Wo.exports}var OT=LT();const UT=Yv(OT);function rh(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var IT=typeof global=="object"&&global&&global.Object===Object&&global,kT=typeof self=="object"&&self&&self.Object===Object&&self,f_=IT||kT||Function("return this")(),bl=function(){return f_.Date.now()},GT=/\s/;function VT(r){for(var e=r.length;e--&&GT.test(r.charAt(e)););return e}var $T=/^\s+/;function zT(r){return r&&r.slice(0,VT(r)+1).replace($T,"")}var gu=f_.Symbol,p_=Object.prototype,WT=p_.hasOwnProperty,HT=p_.toString,Es=gu?gu.toStringTag:void 0;function jT(r){var e=WT.call(r,Es),t=r[Es];try{r[Es]=void 0;var n=!0}catch{}var i=HT.call(r);return n&&(e?r[Es]=t:delete r[Es]),i}var qT=Object.prototype,XT=qT.toString;function KT(r){return XT.call(r)}var YT="[object Null]",QT="[object Undefined]",If=gu?gu.toStringTag:void 0;function ZT(r){return r==null?r===void 0?QT:YT:If&&If in Object(r)?jT(r):KT(r)}function JT(r){return r!=null&&typeof r=="object"}var eS="[object Symbol]";function tS(r){return typeof r=="symbol"||JT(r)&&ZT(r)==eS}var kf=NaN,nS=/^[-+]0x[0-9a-f]+$/i,rS=/^0b[01]+$/i,iS=/^0o[0-7]+$/i,sS=parseInt;function Gf(r){if(typeof r=="number")return r;if(tS(r))return kf;if(rh(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=rh(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=zT(r);var t=rS.test(r);return t||iS.test(r)?sS(r.slice(2),t?2:8):nS.test(r)?kf:+r}var oS="Expected a function",aS=Math.max,uS=Math.min;function lS(r,e,t){var n,i,s,o,a,u,l=0,c=!1,h=!1,d=!0;if(typeof r!="function")throw new TypeError(oS);e=Gf(e)||0,rh(t)&&(c=!!t.leading,h="maxWait"in t,s=h?aS(Gf(t.maxWait)||0,e):s,d="trailing"in t?!!t.trailing:d);function f(v){var w=n,R=i;return n=i=void 0,l=v,o=r.apply(R,w),o}function p(v){return l=v,a=setTimeout(m,e),c?f(v):o}function g(v){var w=v-u,R=v-l,F=e-w;return h?uS(F,s-R):F}function _(v){var w=v-u,R=v-l;return u===void 0||w>=e||w<0||h&&R>=s}function m(){var v=bl();if(_(v))return y(v);a=setTimeout(m,g(v))}function y(v){return a=void 0,d&&n?f(v):(n=i=void 0,o)}function b(){a!==void 0&&clearTimeout(a),l=0,n=u=i=a=void 0}function T(){return a===void 0?o:y(bl())}function x(){var v=bl(),w=_(v);if(n=arguments,i=this,u=v,w){if(a===void 0)return p(u);if(h)return clearTimeout(a),a=setTimeout(m,e),f(u)}return a===void 0&&(a=setTimeout(m,e)),o}return x.cancel=b,x.flush=T,x}function Vf(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function cS(r){if(Array.isArray(r))return r}function hS(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function dS(r,e,t){return Object.defineProperty(r,"prototype",{writable:!1}),r}function fS(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n,i,s,o,a=[],u=!0,l=!1;try{if(s=(t=t.call(r)).next,e!==0)for(;!(u=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,i=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw i}}return a}}function pS(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
503
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gS(r,e){return cS(r)||fS(r,e)||mS(r,e)||pS()}function mS(r,e){if(r){if(typeof r=="string")return Vf(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Vf(r,e):void 0}}var _S=dS(function r(e,t){var n=t.default,i=n===void 0?null:n,s=t.triggerUpdate,o=s===void 0?!0:s,a=t.onChange,u=a===void 0?function(l,c){}:a;hS(this,r),this.name=e,this.defaultVal=i,this.triggerUpdate=o,this.onChange=u});function $u(r){var e=r.stateInit,t=e===void 0?function(){return{}}:e,n=r.props,i=n===void 0?{}:n,s=r.methods,o=s===void 0?{}:s,a=r.aliases,u=a===void 0?{}:a,l=r.init,c=l===void 0?function(){}:l,h=r.update,d=h===void 0?function(){}:h,f=Object.keys(i).map(function(p){return new _S(p,i[p])});return function p(){for(var g=arguments.length,_=new Array(g),m=0;m<g;m++)_[m]=arguments[m];var y=!!(this instanceof p&&this.constructor),b=y?_.shift():void 0,T=_[0],x=T===void 0?{}:T,v=Object.assign({},t instanceof Function?t(x):t,{initialised:!1}),w={};function R(O){return F(O,x),M(),R}var F=function(U,X){c.call(R,U,v,X),v.initialised=!0},M=lS(function(){v.initialised&&(d.call(R,v,w),w={})},1);return f.forEach(function(O){R[O.name]=U(O);function U(X){var oe=X.name,H=X.triggerUpdate,ue=H===void 0?!1:H,L=X.onChange,G=L===void 0?function(k,j){}:L,Z=X.defaultVal,ce=Z===void 0?null:Z;return function(k){var j=v[oe];if(!arguments.length)return j;var ae=k===void 0?ce:k;return v[oe]=ae,G.call(R,ae,v,j),!w.hasOwnProperty(oe)&&(w[oe]=j),ue&&M(),R}}}),Object.keys(o).forEach(function(O){R[O]=function(){for(var U,X=arguments.length,oe=new Array(X),H=0;H<X;H++)oe[H]=arguments[H];return(U=o[O]).call.apply(U,[R,v].concat(oe))}}),Object.entries(u).forEach(function(O){var U=gS(O,2),X=U[0],oe=U[1];return R[X]=R[oe]}),R.resetProps=function(){return f.forEach(function(O){R[O.name](O.defaultVal)}),R},R.resetProps(),v._rerender=M,y&&b&&R(b),R}}var pe=(function(r){return typeof r=="function"?r:typeof r=="string"?function(e){return e[r]}:function(e){return r}});function ih(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function yS(r){if(Array.isArray(r))return r}function bS(r){if(Array.isArray(r))return ih(r)}function g_(r,e,t){if(typeof r=="function"?r===e:r.has(e))return arguments.length<3?e:t;throw new TypeError("Private element is not present on this object")}function xS(r,e){if(e.has(r))throw new TypeError("Cannot initialize the same private elements twice on an object")}function vS(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function lt(r,e){return r.get(g_(r,e))}function Mi(r,e,t){xS(r,e),e.set(r,t)}function Ko(r,e,t){return r.set(g_(r,e),t),t}function TS(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,PS(n.key),n)}}function SS(r,e,t){return e&&TS(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}function wS(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function RS(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n,i,s,o,a=[],u=!0,l=!1;try{if(s=(t=t.call(r)).next,e!==0)for(;!(u=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,i=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw i}}return a}}function AS(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
504
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function NS(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
505
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ES(r,e){return yS(r)||RS(r,e)||m_(r,e)||AS()}function CS(r){return bS(r)||wS(r)||m_(r)||NS()}function MS(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(r)}function PS(r){var e=MS(r,"string");return typeof e=="symbol"?e:e+""}function m_(r,e){if(r){if(typeof r=="string")return ih(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?ih(r,e):void 0}}var Pi=new WeakMap,Cs=new WeakMap,Bi=new WeakMap,xl=new WeakMap,vl=new WeakMap,Tl=new WeakMap,BS=(function(){function r(){vS(this,r),Mi(this,Pi,new Map),Mi(this,Cs,new Map),Mi(this,Bi,function(e){return e}),Mi(this,xl,function(){return{}}),Mi(this,vl,function(){}),Mi(this,Tl,function(){})}return SS(r,[{key:"getObj",value:function(t){return lt(Pi,this).get(lt(Bi,this).call(this,t))}},{key:"getData",value:function(t){return lt(Cs,this).get(t)}},{key:"entries",value:function(){return CS(lt(Cs,this).entries()).map(function(t){var n=ES(t,2),i=n[0],s=n[1];return[s,i]})}},{key:"id",value:function(t){return Ko(Bi,this,pe(t)),this}},{key:"onCreateObj",value:function(t){return Ko(xl,this,t),this}},{key:"onUpdateObj",value:function(t){return Ko(vl,this,t),this}},{key:"onRemoveObj",value:function(t){return Ko(Tl,this,t),this}},{key:"digest",value:function(t){var n=this;t.filter(function(s){return!lt(Pi,n).has(lt(Bi,n).call(n,s))}).forEach(function(s){var o=lt(xl,n).call(n,s);lt(Pi,n).set(lt(Bi,n).call(n,s),o),lt(Cs,n).set(o,s)});var i=new Map(t.map(function(s){return[lt(Bi,n).call(n,s),s]}));return lt(Pi,this).forEach(function(s,o){i.has(o)?lt(vl,n).call(n,s,i.get(o)):(lt(Tl,n).call(n,s,o),lt(Pi,n).delete(o),lt(Cs,n).delete(s))}),this}},{key:"clear",value:function(){return this.digest([]),this}}])})();function FS(r){for(var e=r.length/6|0,t=new Array(e),n=0;n<e;)t[n]="#"+r.slice(n*6,++n*6);return t}const DS=FS("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");function mu(r){"@babel/helpers - typeof";return mu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},mu(r)}var LS=/^\s+/,OS=/\s+$/;function ee(r,e){if(r=r||"",e=e||{},r instanceof ee)return r;if(!(this instanceof ee))return new ee(r,e);var t=US(r);this._originalInput=r,this._r=t.r,this._g=t.g,this._b=t.b,this._a=t.a,this._roundA=Math.round(100*this._a)/100,this._format=e.format||t.format,this._gradientType=e.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=t.ok}ee.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(e.r*299+e.g*587+e.b*114)/1e3},getLuminance:function(){var e=this.toRgb(),t,n,i,s,o,a;return t=e.r/255,n=e.g/255,i=e.b/255,t<=.03928?s=t/12.92:s=Math.pow((t+.055)/1.055,2.4),n<=.03928?o=n/12.92:o=Math.pow((n+.055)/1.055,2.4),i<=.03928?a=i/12.92:a=Math.pow((i+.055)/1.055,2.4),.2126*s+.7152*o+.0722*a},setAlpha:function(e){return this._a=__(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=zf(this._r,this._g,this._b);return{h:e.h*360,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=zf(this._r,this._g,this._b),t=Math.round(e.h*360),n=Math.round(e.s*100),i=Math.round(e.v*100);return this._a==1?"hsv("+t+", "+n+"%, "+i+"%)":"hsva("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHsl:function(){var e=$f(this._r,this._g,this._b);return{h:e.h*360,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=$f(this._r,this._g,this._b),t=Math.round(e.h*360),n=Math.round(e.s*100),i=Math.round(e.l*100);return this._a==1?"hsl("+t+", "+n+"%, "+i+"%)":"hsla("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHex:function(e){return Wf(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return VS(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return this._a==1?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(Oe(this._r,255)*100)+"%",g:Math.round(Oe(this._g,255)*100)+"%",b:Math.round(Oe(this._b,255)*100)+"%",a:this._a}},toPercentageRgbString:function(){return this._a==1?"rgb("+Math.round(Oe(this._r,255)*100)+"%, "+Math.round(Oe(this._g,255)*100)+"%, "+Math.round(Oe(this._b,255)*100)+"%)":"rgba("+Math.round(Oe(this._r,255)*100)+"%, "+Math.round(Oe(this._g,255)*100)+"%, "+Math.round(Oe(this._b,255)*100)+"%, "+this._roundA+")"},toName:function(){return this._a===0?"transparent":this._a<1?!1:JS[Wf(this._r,this._g,this._b,!0)]||!1},toFilter:function(e){var t="#"+Hf(this._r,this._g,this._b,this._a),n=t,i=this._gradientType?"GradientType = 1, ":"";if(e){var s=ee(e);n="#"+Hf(s._r,s._g,s._b,s._a)}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,i=this._a<1&&this._a>=0,s=!t&&i&&(e==="hex"||e==="hex6"||e==="hex3"||e==="hex4"||e==="hex8"||e==="name");return s?e==="name"&&this._a===0?this.toName():this.toRgbString():(e==="rgb"&&(n=this.toRgbString()),e==="prgb"&&(n=this.toPercentageRgbString()),(e==="hex"||e==="hex6")&&(n=this.toHexString()),e==="hex3"&&(n=this.toHexString(!0)),e==="hex4"&&(n=this.toHex8String(!0)),e==="hex8"&&(n=this.toHex8String()),e==="name"&&(n=this.toName()),e==="hsl"&&(n=this.toHslString()),e==="hsv"&&(n=this.toHsvString()),n||this.toHexString())},clone:function(){return ee(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(HS,arguments)},brighten:function(){return this._applyModification(jS,arguments)},darken:function(){return this._applyModification(qS,arguments)},desaturate:function(){return this._applyModification($S,arguments)},saturate:function(){return this._applyModification(zS,arguments)},greyscale:function(){return this._applyModification(WS,arguments)},spin:function(){return this._applyModification(XS,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(QS,arguments)},complement:function(){return this._applyCombination(KS,arguments)},monochromatic:function(){return this._applyCombination(ZS,arguments)},splitcomplement:function(){return this._applyCombination(YS,arguments)},triad:function(){return this._applyCombination(jf,[3])},tetrad:function(){return this._applyCombination(jf,[4])}};ee.fromRatio=function(r,e){if(mu(r)=="object"){var t={};for(var n in r)r.hasOwnProperty(n)&&(n==="a"?t[n]=r[n]:t[n]=Zs(r[n]));r=t}return ee(r,e)};function US(r){var e={r:0,g:0,b:0},t=1,n=null,i=null,s=null,o=!1,a=!1;return typeof r=="string"&&(r=rw(r)),mu(r)=="object"&&($n(r.r)&&$n(r.g)&&$n(r.b)?(e=IS(r.r,r.g,r.b),o=!0,a=String(r.r).substr(-1)==="%"?"prgb":"rgb"):$n(r.h)&&$n(r.s)&&$n(r.v)?(n=Zs(r.s),i=Zs(r.v),e=GS(r.h,n,i),o=!0,a="hsv"):$n(r.h)&&$n(r.s)&&$n(r.l)&&(n=Zs(r.s),s=Zs(r.l),e=kS(r.h,n,s),o=!0,a="hsl"),r.hasOwnProperty("a")&&(t=r.a)),t=__(t),{ok:o,format:r.format||a,r:Math.min(255,Math.max(e.r,0)),g:Math.min(255,Math.max(e.g,0)),b:Math.min(255,Math.max(e.b,0)),a:t}}function IS(r,e,t){return{r:Oe(r,255)*255,g:Oe(e,255)*255,b:Oe(t,255)*255}}function $f(r,e,t){r=Oe(r,255),e=Oe(e,255),t=Oe(t,255);var n=Math.max(r,e,t),i=Math.min(r,e,t),s,o,a=(n+i)/2;if(n==i)s=o=0;else{var u=n-i;switch(o=a>.5?u/(2-n-i):u/(n+i),n){case r:s=(e-t)/u+(e<t?6:0);break;case e:s=(t-r)/u+2;break;case t:s=(r-e)/u+4;break}s/=6}return{h:s,s:o,l:a}}function kS(r,e,t){var n,i,s;r=Oe(r,360),e=Oe(e,100),t=Oe(t,100);function o(l,c,h){return h<0&&(h+=1),h>1&&(h-=1),h<1/6?l+(c-l)*6*h:h<1/2?c:h<2/3?l+(c-l)*(2/3-h)*6:l}if(e===0)n=i=s=t;else{var a=t<.5?t*(1+e):t+e-t*e,u=2*t-a;n=o(u,a,r+1/3),i=o(u,a,r),s=o(u,a,r-1/3)}return{r:n*255,g:i*255,b:s*255}}function zf(r,e,t){r=Oe(r,255),e=Oe(e,255),t=Oe(t,255);var n=Math.max(r,e,t),i=Math.min(r,e,t),s,o,a=n,u=n-i;if(o=n===0?0:u/n,n==i)s=0;else{switch(n){case r:s=(e-t)/u+(e<t?6:0);break;case e:s=(t-r)/u+2;break;case t:s=(r-e)/u+4;break}s/=6}return{h:s,s:o,v:a}}function GS(r,e,t){r=Oe(r,360)*6,e=Oe(e,100),t=Oe(t,100);var n=Math.floor(r),i=r-n,s=t*(1-e),o=t*(1-i*e),a=t*(1-(1-i)*e),u=n%6,l=[t,o,s,s,a,t][u],c=[a,t,t,o,s,s][u],h=[s,s,a,t,t,o][u];return{r:l*255,g:c*255,b:h*255}}function Wf(r,e,t,n){var i=[gn(Math.round(r).toString(16)),gn(Math.round(e).toString(16)),gn(Math.round(t).toString(16))];return n&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join("")}function VS(r,e,t,n,i){var s=[gn(Math.round(r).toString(16)),gn(Math.round(e).toString(16)),gn(Math.round(t).toString(16)),gn(y_(n))];return i&&s[0].charAt(0)==s[0].charAt(1)&&s[1].charAt(0)==s[1].charAt(1)&&s[2].charAt(0)==s[2].charAt(1)&&s[3].charAt(0)==s[3].charAt(1)?s[0].charAt(0)+s[1].charAt(0)+s[2].charAt(0)+s[3].charAt(0):s.join("")}function Hf(r,e,t,n){var i=[gn(y_(n)),gn(Math.round(r).toString(16)),gn(Math.round(e).toString(16)),gn(Math.round(t).toString(16))];return i.join("")}ee.equals=function(r,e){return!r||!e?!1:ee(r).toRgbString()==ee(e).toRgbString()};ee.random=function(){return ee.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})};function $S(r,e){e=e===0?0:e||10;var t=ee(r).toHsl();return t.s-=e/100,t.s=zu(t.s),ee(t)}function zS(r,e){e=e===0?0:e||10;var t=ee(r).toHsl();return t.s+=e/100,t.s=zu(t.s),ee(t)}function WS(r){return ee(r).desaturate(100)}function HS(r,e){e=e===0?0:e||10;var t=ee(r).toHsl();return t.l+=e/100,t.l=zu(t.l),ee(t)}function jS(r,e){e=e===0?0:e||10;var t=ee(r).toRgb();return t.r=Math.max(0,Math.min(255,t.r-Math.round(255*-(e/100)))),t.g=Math.max(0,Math.min(255,t.g-Math.round(255*-(e/100)))),t.b=Math.max(0,Math.min(255,t.b-Math.round(255*-(e/100)))),ee(t)}function qS(r,e){e=e===0?0:e||10;var t=ee(r).toHsl();return t.l-=e/100,t.l=zu(t.l),ee(t)}function XS(r,e){var t=ee(r).toHsl(),n=(t.h+e)%360;return t.h=n<0?360+n:n,ee(t)}function KS(r){var e=ee(r).toHsl();return e.h=(e.h+180)%360,ee(e)}function jf(r,e){if(isNaN(e)||e<=0)throw new Error("Argument to polyad must be a positive number");for(var t=ee(r).toHsl(),n=[ee(r)],i=360/e,s=1;s<e;s++)n.push(ee({h:(t.h+s*i)%360,s:t.s,l:t.l}));return n}function YS(r){var e=ee(r).toHsl(),t=e.h;return[ee(r),ee({h:(t+72)%360,s:e.s,l:e.l}),ee({h:(t+216)%360,s:e.s,l:e.l})]}function QS(r,e,t){e=e||6,t=t||30;var n=ee(r).toHsl(),i=360/t,s=[ee(r)];for(n.h=(n.h-(i*e>>1)+720)%360;--e;)n.h=(n.h+i)%360,s.push(ee(n));return s}function ZS(r,e){e=e||6;for(var t=ee(r).toHsv(),n=t.h,i=t.s,s=t.v,o=[],a=1/e;e--;)o.push(ee({h:n,s:i,v:s})),s=(s+a)%1;return o}ee.mix=function(r,e,t){t=t===0?0:t||50;var n=ee(r).toRgb(),i=ee(e).toRgb(),s=t/100,o={r:(i.r-n.r)*s+n.r,g:(i.g-n.g)*s+n.g,b:(i.b-n.b)*s+n.b,a:(i.a-n.a)*s+n.a};return ee(o)};ee.readability=function(r,e){var t=ee(r),n=ee(e);return(Math.max(t.getLuminance(),n.getLuminance())+.05)/(Math.min(t.getLuminance(),n.getLuminance())+.05)};ee.isReadable=function(r,e,t){var n=ee.readability(r,e),i,s;switch(s=!1,i=iw(t),i.level+i.size){case"AAsmall":case"AAAlarge":s=n>=4.5;break;case"AAlarge":s=n>=3;break;case"AAAsmall":s=n>=7;break}return s};ee.mostReadable=function(r,e,t){var n=null,i=0,s,o,a,u;t=t||{},o=t.includeFallbackColors,a=t.level,u=t.size;for(var l=0;l<e.length;l++)s=ee.readability(r,e[l]),s>i&&(i=s,n=ee(e[l]));return ee.isReadable(r,n,{level:a,size:u})||!o?n:(t.includeFallbackColors=!1,ee.mostReadable(r,["#fff","#000"],t))};var sh=ee.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},JS=ee.hexNames=ew(sh);function ew(r){var e={};for(var t in r)r.hasOwnProperty(t)&&(e[r[t]]=t);return e}function __(r){return r=parseFloat(r),(isNaN(r)||r<0||r>1)&&(r=1),r}function Oe(r,e){tw(r)&&(r="100%");var t=nw(r);return r=Math.min(e,Math.max(0,parseFloat(r))),t&&(r=parseInt(r*e,10)/100),Math.abs(r-e)<1e-6?1:r%e/parseFloat(e)}function zu(r){return Math.min(1,Math.max(0,r))}function Vt(r){return parseInt(r,16)}function tw(r){return typeof r=="string"&&r.indexOf(".")!=-1&&parseFloat(r)===1}function nw(r){return typeof r=="string"&&r.indexOf("%")!=-1}function gn(r){return r.length==1?"0"+r:""+r}function Zs(r){return r<=1&&(r=r*100+"%"),r}function y_(r){return Math.round(parseFloat(r)*255).toString(16)}function qf(r){return Vt(r)/255}var ln=(function(){var r="[-\\+]?\\d+%?",e="[-\\+]?\\d*\\.\\d+%?",t="(?:"+e+")|(?:"+r+")",n="[\\s|\\(]+("+t+")[,|\\s]+("+t+")[,|\\s]+("+t+")\\s*\\)?",i="[\\s|\\(]+("+t+")[,|\\s]+("+t+")[,|\\s]+("+t+")[,|\\s]+("+t+")\\s*\\)?";return{CSS_UNIT:new RegExp(t),rgb:new RegExp("rgb"+n),rgba:new RegExp("rgba"+i),hsl:new RegExp("hsl"+n),hsla:new RegExp("hsla"+i),hsv:new RegExp("hsv"+n),hsva:new RegExp("hsva"+i),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}})();function $n(r){return!!ln.CSS_UNIT.exec(r)}function rw(r){r=r.replace(LS,"").replace(OS,"").toLowerCase();var e=!1;if(sh[r])r=sh[r],e=!0;else if(r=="transparent")return{r:0,g:0,b:0,a:0,format:"name"};var t;return(t=ln.rgb.exec(r))?{r:t[1],g:t[2],b:t[3]}:(t=ln.rgba.exec(r))?{r:t[1],g:t[2],b:t[3],a:t[4]}:(t=ln.hsl.exec(r))?{h:t[1],s:t[2],l:t[3]}:(t=ln.hsla.exec(r))?{h:t[1],s:t[2],l:t[3],a:t[4]}:(t=ln.hsv.exec(r))?{h:t[1],s:t[2],v:t[3]}:(t=ln.hsva.exec(r))?{h:t[1],s:t[2],v:t[3],a:t[4]}:(t=ln.hex8.exec(r))?{r:Vt(t[1]),g:Vt(t[2]),b:Vt(t[3]),a:qf(t[4]),format:e?"name":"hex8"}:(t=ln.hex6.exec(r))?{r:Vt(t[1]),g:Vt(t[2]),b:Vt(t[3]),format:e?"name":"hex"}:(t=ln.hex4.exec(r))?{r:Vt(t[1]+""+t[1]),g:Vt(t[2]+""+t[2]),b:Vt(t[3]+""+t[3]),a:qf(t[4]+""+t[4]),format:e?"name":"hex8"}:(t=ln.hex3.exec(r))?{r:Vt(t[1]+""+t[1]),g:Vt(t[2]+""+t[2]),b:Vt(t[3]+""+t[3]),format:e?"name":"hex"}:!1}function iw(r){var e,t;return r=r||{level:"AA",size:"small"},e=(r.level||"AA").toUpperCase(),t=(r.size||"small").toLowerCase(),e!=="AA"&&e!=="AAA"&&(e="AA"),t!=="small"&&t!=="large"&&(t="small"),{level:e,size:t}}function oh(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function sw(r){if(Array.isArray(r))return r}function ow(r){if(Array.isArray(r))return oh(r)}function b_(r,e,t){if(typeof r=="function"?r===e:r.has(e))return arguments.length<3?e:t;throw new TypeError("Private element is not present on this object")}function aw(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function x_(r,e,t){return e=us(e),gw(r,hd()?Reflect.construct(e,t||[],us(r).constructor):e.apply(r,t))}function uw(r,e){if(e.has(r))throw new TypeError("Cannot initialize the same private elements twice on an object")}function v_(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function Sl(r,e){return r.get(b_(r,e))}function Xf(r,e,t){uw(r,e),e.set(r,t)}function Kf(r,e,t){return r.set(b_(r,e),t),t}function T_(r,e,t){if(hd())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(r.bind.apply(r,n));return i}function lw(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,R_(n.key),n)}}function S_(r,e,t){return e&&lw(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}function Wu(r,e,t){return(e=R_(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function ah(){return ah=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(r,e,t){var n=mw(r,e);if(n){var i=Object.getOwnPropertyDescriptor(n,e);return i.get?i.get.call(arguments.length<3?r:t):i.value}},ah.apply(null,arguments)}function us(r){return us=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},us(r)}function w_(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&uh(r,e)}function hd(){try{var r=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(hd=function(){return!!r})()}function cw(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function hw(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n,i,s,o,a=[],u=!0,l=!1;try{if(s=(t=t.call(r)).next,e!==0)for(;!(u=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,i=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw i}}return a}}function dw(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
506
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function fw(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
507
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Yf(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function pw(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Yf(Object(t),!0).forEach(function(n){Wu(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Yf(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function gw(r,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return aw(r)}function uh(r,e){return uh=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},uh(r,e)}function so(r,e){return sw(r)||hw(r,e)||A_(r,e)||dw()}function mw(r,e){for(;!{}.hasOwnProperty.call(r,e)&&(r=us(r))!==null;);return r}function wl(r,e,t,n){var i=ah(us(r.prototype),e,t);return typeof i=="function"?function(s){return i.apply(t,s)}:i}function cn(r){return ow(r)||cw(r)||A_(r)||fw()}function _w(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function R_(r){var e=_w(r,"string");return typeof e=="symbol"?e:e+""}function lh(r){"@babel/helpers - typeof";return lh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lh(r)}function A_(r,e){if(r){if(typeof r=="string")return oh(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?oh(r,e):void 0}}var N_=function(e){e instanceof Array?e.forEach(N_):(e.map&&e.map.dispose(),e.dispose())},dd=function(e){e.geometry&&e.geometry.dispose(),e.material&&N_(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(dd)},Qf=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),dd(t)}},Rl=new WeakMap,Yo=new WeakMap,Ms=(function(r){function e(t){var n,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=i.dataBindAttr,o=s===void 0?"__data":s,a=i.objBindAttr,u=a===void 0?"__threeObj":a;return v_(this,e),n=x_(this,e),Wu(n,"scene",void 0),Xf(n,Rl,void 0),Xf(n,Yo,void 0),n.scene=t,Kf(Rl,n,o),Kf(Yo,n,u),n.onRemoveObj(function(){}),n}return w_(e,r),S_(e,[{key:"onCreateObj",value:function(n){var i=this;return wl(e,"onCreateObj",this)([function(s){var o=n(s);return s[Sl(Yo,i)]=o,o[Sl(Rl,i)]=s,i.scene.add(o),o}]),this}},{key:"onRemoveObj",value:function(n){var i=this;return wl(e,"onRemoveObj",this)([function(s,o){var a=wl(e,"getData",i)([s]);n(s,o),i.scene.remove(s),dd(s),delete a[Sl(Yo,i)]}]),this}}])})(BS),Ps=function(e){return isNaN(e)?parseInt(ee(e).toHex(),16):e},Al=function(e){return isNaN(e)?ee(e).getAlpha():1},yw=Qv(DS);function Zf(r,e,t){!e||typeof t!="string"||r.filter(function(n){return!n[t]}).forEach(function(n){n[t]=yw(e(n))})}function bw(r,e){var t=r.nodes,n=r.links,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=i.nodeFilter,o=s===void 0?function(){return!0}:s,a=i.onLoopError,u=a===void 0?function(f){throw"Invalid DAG structure! Found cycle in node path: ".concat(f.join(" -> "),".")}:a,l={};t.forEach(function(f){return l[e(f)]={data:f,out:[],depth:-1,skip:!o(f)}}),n.forEach(function(f){var p=f.source,g=f.target,_=T(p),m=T(g);if(!l.hasOwnProperty(_))throw"Missing source node with id: ".concat(_);if(!l.hasOwnProperty(m))throw"Missing target node with id: ".concat(m);var y=l[_],b=l[m];y.out.push(b);function T(x){return lh(x)==="object"?e(x):x}});var c=[];d(Object.values(l));var h=Object.assign.apply(Object,[{}].concat(cn(Object.entries(l).filter(function(f){var p=so(f,2),g=p[1];return!g.skip}).map(function(f){var p=so(f,2),g=p[0],_=p[1];return Wu({},g,_.depth)}))));return h;function d(f){for(var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,_=function(){var T=f[m];if(p.indexOf(T)!==-1){var x=[].concat(cn(p.slice(p.indexOf(T))),[T]).map(function(v){return e(v.data)});return c.some(function(v){return v.length===x.length&&v.every(function(w,R){return w===x[R]})})||(c.push(x),u(x)),1}g>T.depth&&(T.depth=g,d(T.out,[].concat(cn(p),[T]),g+(T.skip?0:1)))},m=0,y=f.length;m<y;m++)_()}}var se=window.THREE?window.THREE:{Group:nm,Mesh:yn,MeshLambertMaterial:tm,Color:Dt,BufferGeometry:Eo,BufferAttribute:Rc,Matrix4:bt,Vector3:z,SphereGeometry:qh,CylinderGeometry:rm,TubeGeometry:Fx,ConeGeometry:Bx,Line:Cx,LineBasicMaterial:sm,QuadraticBezierCurve3:Px,CubicBezierCurve3:Mx,Box3:im},Jf={graph:wT,forcelayout:UT},xw=2,Nl=new se.BufferGeometry().setAttribute?"setAttribute":"addAttribute",Qo=new se.BufferGeometry().applyMatrix4?"applyMatrix4":"applyMatrix",vw=$u({props:{jsonUrl:{onChange:function(e,t){var n=this;e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(function(i){return i.json()}).then(function(i){t.fetchingJson=!1,t.onFinishLoading(i),n.graphData(i)}))},triggerUpdate:!1},graphData:{default:{nodes:[],links:[]},onChange:function(e,t){t.engineRunning=!1}},numDimensions:{default:3,onChange:function(e,t){var n=t.d3ForceLayout.force("charge");n&&n.strength(e>2?-60:-30),e<3&&i(t.graphData.nodes,"z"),e<2&&i(t.graphData.nodes,"y");function i(s,o){s.forEach(function(a){delete a[o],delete a["v".concat(o)]})}}},dagMode:{onChange:function(e,t){!e&&t.forceEngine==="d3"&&(t.graphData.nodes||[]).forEach(function(n){return n.fx=n.fy=n.fz=void 0})}},dagLevelDistance:{},dagNodeFilter:{default:function(e){return!0}},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:"id"},nodeVal:{default:"val"},nodeResolution:{default:8},nodeColor:{default:"color"},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:"source"},linkTarget:{default:"target"},linkVisibility:{default:!0},linkColor:{default:"color"},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleOffset:{default:0,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},linkDirectionalParticleThreeObject:{},forceEngine:{default:"d3"},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:function(){},triggerUpdate:!1},onFinishLoading:{default:function(){},triggerUpdate:!1},onUpdate:{default:function(){},triggerUpdate:!1},onFinishUpdate:{default:function(){},triggerUpdate:!1},onEngineTick:{default:function(){},triggerUpdate:!1},onEngineStop:{default:function(){},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return n===void 0?e.d3ForceLayout.force(t):(e.d3ForceLayout.force(t,n),this)},d3ReheatSimulation:function(e){return e.d3ForceLayout.alpha(1),this.resetCountdown(),this},resetCountdown:function(e){return e.cntTicks=0,e.startTickTime=new Date,e.engineRunning=!0,this},tickFrame:function(e){var t=e.forceEngine!=="ngraph";return e.engineRunning&&n(),i(),s(),this;function n(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||t&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin?(e.engineRunning=!1,e.onEngineStop()):(e.layout[t?"tick":"step"](),e.onEngineTick());var o=pe(e.nodeThreeObjectExtend);e.nodeDataMapper.entries().forEach(function(d){var f=so(d,2),p=f[0],g=f[1];if(g){var _=t?p:e.layout.getNodePosition(p[e.nodeId]),m=o(p);(!e.nodePositionUpdate||!e.nodePositionUpdate(m?g.children[0]:g,{x:_.x,y:_.y,z:_.z},p)||m)&&(g.position.x=_.x,g.position.y=_.y||0,g.position.z=_.z||0)}});var a=pe(e.linkWidth),u=pe(e.linkCurvature),l=pe(e.linkCurveRotation),c=pe(e.linkThreeObjectExtend);e.linkDataMapper.entries().forEach(function(d){var f=so(d,2),p=f[0],g=f[1];if(g){var _=t?p:e.layout.getLinkPosition(e.layout.graph.getLink(p.source,p.target).id),m=_[t?"source":"from"],y=_[t?"target":"to"];if(!(!m||!y||!m.hasOwnProperty("x")||!y.hasOwnProperty("x"))){h(p);var b=c(p);if(!(e.linkPositionUpdate&&e.linkPositionUpdate(b?g.children[1]:g,{start:{x:m.x,y:m.y,z:m.z},end:{x:y.x,y:y.y,z:y.z}},p)&&!b)){var T=30,x=p.__curve,v=g.children.length?g.children[0]:g;if(v.type==="Line"){if(x){var R=x.getPoints(T);v.geometry.getAttribute("position").array.length!==R.length*3&&v.geometry[Nl]("position",new se.BufferAttribute(new Float32Array(R.length*3),3)),v.geometry.setFromPoints(R)}else{var w=v.geometry.getAttribute("position");(!w||!w.array||w.array.length!==6)&&v.geometry[Nl]("position",w=new se.BufferAttribute(new Float32Array(6),3)),w.array[0]=m.x,w.array[1]=m.y||0,w.array[2]=m.z||0,w.array[3]=y.x,w.array[4]=y.y||0,w.array[5]=y.z||0,w.needsUpdate=!0}v.geometry.computeBoundingSphere()}else if(v.type==="Mesh")if(x){v.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(v.position.set(0,0,0),v.rotation.set(0,0,0),v.scale.set(1,1,1));var H=Math.ceil(a(p)*10)/10,ue=H/2,L=new se.TubeGeometry(x,T,ue,e.linkResolution,!1);v.geometry.dispose(),v.geometry=L}else{if(!v.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var F=Math.ceil(a(p)*10)/10,M=F/2,O=new se.CylinderGeometry(M,M,1,e.linkResolution,1,!1);O[Qo](new se.Matrix4().makeTranslation(0,1/2,0)),O[Qo](new se.Matrix4().makeRotationX(Math.PI/2)),v.geometry.dispose(),v.geometry=O}var U=new se.Vector3(m.x,m.y||0,m.z||0),X=new se.Vector3(y.x,y.y||0,y.z||0),oe=U.distanceTo(X);v.position.x=U.x,v.position.y=U.y,v.position.z=U.z,v.scale.z=oe,v.parent.localToWorld(X),v.lookAt(X)}}}}});function h(d){var f=t?d:e.layout.getLinkPosition(e.layout.graph.getLink(d.source,d.target).id),p=f[t?"source":"from"],g=f[t?"target":"to"];if(!(!p||!g||!p.hasOwnProperty("x")||!g.hasOwnProperty("x"))){var _=u(d);if(!_)d.__curve=null;else{var m=new se.Vector3(p.x,p.y||0,p.z||0),y=new se.Vector3(g.x,g.y||0,g.z||0),b=m.distanceTo(y),T,x=l(d);if(b>0){var v=g.x-p.x,w=g.y-p.y||0,R=new se.Vector3().subVectors(y,m),F=R.clone().multiplyScalar(_).cross(v!==0||w!==0?new se.Vector3(0,0,1):new se.Vector3(0,1,0)).applyAxisAngle(R.normalize(),x).add(new se.Vector3().addVectors(m,y).divideScalar(2));T=new se.QuadraticBezierCurve3(m,F,y)}else{var M=_*70,O=-x,U=O+Math.PI/2;T=new se.CubicBezierCurve3(m,new se.Vector3(M*Math.cos(U),M*Math.sin(U),0).add(m),new se.Vector3(M*Math.cos(O),M*Math.sin(O),0).add(m),y)}d.__curve=T}}}}function i(){var o=pe(e.linkDirectionalArrowRelPos),a=pe(e.linkDirectionalArrowLength),u=pe(e.nodeVal);e.arrowDataMapper.entries().forEach(function(l){var c=so(l,2),h=c[0],d=c[1];if(d){var f=t?h:e.layout.getLinkPosition(e.layout.graph.getLink(h.source,h.target).id),p=f[t?"source":"from"],g=f[t?"target":"to"];if(!(!p||!g||!p.hasOwnProperty("x")||!g.hasOwnProperty("x"))){var _=Math.cbrt(Math.max(0,u(p)||1))*e.nodeRelSize,m=Math.cbrt(Math.max(0,u(g)||1))*e.nodeRelSize,y=a(h),b=o(h),T=h.__curve?function(M){return h.__curve.getPoint(M)}:function(M){var O=function(X,oe,H,ue){return oe[X]+(H[X]-oe[X])*ue||0};return{x:O("x",p,g,M),y:O("y",p,g,M),z:O("z",p,g,M)}},x=h.__curve?h.__curve.getLength():Math.sqrt(["x","y","z"].map(function(M){return Math.pow((g[M]||0)-(p[M]||0),2)}).reduce(function(M,O){return M+O},0)),v=_+y+(x-_-m-y)*b,w=T(v/x),R=T((v-y)/x);["x","y","z"].forEach(function(M){return d.position[M]=R[M]});var F=T_(se.Vector3,cn(["x","y","z"].map(function(M){return w[M]})));d.parent.localToWorld(F),d.lookAt(F)}}})}function s(){var o=pe(e.linkDirectionalParticleSpeed),a=pe(e.linkDirectionalParticleOffset);e.graphData.links.forEach(function(u){var l=e.particlesDataMapper.getObj(u),c=l&&l.children,h=u.__singleHopPhotonsObj&&u.__singleHopPhotonsObj.children;if(!((!h||!h.length)&&(!c||!c.length))){var d=t?u:e.layout.getLinkPosition(e.layout.graph.getLink(u.source,u.target).id),f=d[t?"source":"from"],p=d[t?"target":"to"];if(!(!f||!p||!f.hasOwnProperty("x")||!p.hasOwnProperty("x"))){var g=o(u),_=Math.abs(a(u)),m=u.__curve?function(b){return u.__curve.getPoint(b)}:function(b){var T=function(v,w,R,F){return w[v]+(R[v]-w[v])*F||0};return{x:T("x",f,p,b),y:T("y",f,p,b),z:T("z",f,p,b)}},y=[].concat(cn(c||[]),cn(h||[]));y.forEach(function(b,T){var x=b.parent.__linkThreeObjType==="singleHopPhotons";if(b.hasOwnProperty("__progressRatio")||(b.__progressRatio=x?g<0?1:0:(T+_)/c.length),b.__progressRatio+=g,b.__progressRatio>=1||b.__progressRatio<0)if(!x)b.__progressRatio=b.__progressRatio%1,b.__progressRatio<0&&b.__progressRatio++;else{b.parent.remove(b),Qf(b);return}var v=b.__progressRatio,w=m(v);b.geometry.type!=="SphereGeometry"&&b.lookAt(w.x,w.y,w.z),["x","y","z"].forEach(function(R){return b.position[R]=w[R]})})}}})}},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new se.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var i=pe(e.linkDirectionalParticleThreeObject)(t);if(i&&e.linkDirectionalParticleThreeObject===i&&(i=i.clone()),!i){var s=pe(e.linkDirectionalParticleWidth),o=Math.ceil(s(t)*10)/10/2,a=e.linkDirectionalParticleResolution,u=new se.SphereGeometry(o,a,a),l=pe(e.linkColor),c=pe(e.linkDirectionalParticleColor),h=c(t)||l(t)||"#f0f0f0",d=new se.Color(Ps(h)),f=e.linkOpacity*3,p=new se.MeshLambertMaterial({color:d,transparent:!0,opacity:f});i=new se.Mesh(u,p)}t.__singleHopPhotonsObj.add(i)}return this},getGraphBbox:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){return!0};if(!e.initialised)return null;var n=(function i(s){var o=[];if(s.geometry){s.geometry.computeBoundingBox();var a=new se.Box3;a.copy(s.geometry.boundingBox).applyMatrix4(s.matrixWorld),o.push(a)}return o.concat.apply(o,cn((s.children||[]).filter(function(u){return!u.hasOwnProperty("__graphObjType")||u.__graphObjType==="node"&&t(u.__data)}).map(i)))})(e.graphScene);return n.length?Object.assign.apply(Object,cn(["x","y","z"].map(function(i){return Wu({},i,[Zv(n,function(s){return s.min[i]}),Jv(n,function(s){return s.max[i]})])}))):null}},stateInit:function(){return{d3ForceLayout:yT().force("link",rT()).force("charge",bT()).force("center",s0()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new Ms(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new Ms(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new Ms(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new Ms(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(I){return I.some(function(J){return t.hasOwnProperty(J)})};if(e.engineRunning=!1,typeof e.onUpdate=="function"&&e.onUpdate(),e.nodeAutoColorBy!==null&&n(["nodeAutoColorBy","graphData","nodeColor"])&&Zf(e.graphData.nodes,pe(e.nodeAutoColorBy),e.nodeColor),e.linkAutoColorBy!==null&&n(["linkAutoColorBy","graphData","linkColor"])&&Zf(e.graphData.links,pe(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var i=pe(e.nodeThreeObject),s=pe(e.nodeThreeObjectExtend),o=pe(e.nodeVal),a=pe(e.nodeColor),u=pe(e.nodeVisibility),l={},c={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj(function(B){var I=i(B),J=s(B);I&&e.nodeThreeObject===I&&(I=I.clone());var ye;return I&&!J?ye=I:(ye=new se.Mesh,ye.__graphDefaultObj=!0,I&&J&&ye.add(I)),ye.__graphObjType="node",ye}).onUpdateObj(function(B,I){if(B.__graphDefaultObj){var J=o(I)||1,ye=Math.cbrt(J)*e.nodeRelSize,Ge=e.nodeResolution;(!B.geometry.type.match(/^Sphere(Buffer)?Geometry$/)||B.geometry.parameters.radius!==ye||B.geometry.parameters.widthSegments!==Ge)&&(l.hasOwnProperty(J)||(l[J]=new se.SphereGeometry(ye,Ge,Ge)),B.geometry.dispose(),B.geometry=l[J]);var $e=a(I),ze=new se.Color(Ps($e||"#ffffaa")),bn=e.nodeOpacity*Al($e);(B.material.type!=="MeshLambertMaterial"||!B.material.color.equals(ze)||B.material.opacity!==bn)&&(c.hasOwnProperty($e)||(c[$e]=new se.MeshLambertMaterial({color:ze,transparent:!0,opacity:bn})),B.material.dispose(),B.material=c[$e])}}).digest(e.graphData.nodes.filter(u))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject"])){var h=pe(e.linkThreeObject),d=pe(e.linkThreeObjectExtend),f=pe(e.linkMaterial),p=pe(e.linkVisibility),g=pe(e.linkColor),_=pe(e.linkWidth),m={},y={},b={},T=e.graphData.links.filter(p);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(function(B){var I=B.__data&&B.__data.__singleHopPhotonsObj;I&&(I.parent.remove(I),Qf(I),delete B.__data.__singleHopPhotonsObj)}).onCreateObj(function(B){var I=h(B),J=d(B);I&&e.linkThreeObject===I&&(I=I.clone());var ye;if(!I||J){var Ge=!!_(B);if(Ge)ye=new se.Mesh;else{var $e=new se.BufferGeometry;$e[Nl]("position",new se.BufferAttribute(new Float32Array(6),3)),ye=new se.Line($e)}}var ze;return I?J?(ze=new se.Group,ze.__graphDefaultObj=!0,ze.add(ye),ze.add(I)):ze=I:(ze=ye,ze.__graphDefaultObj=!0),ze.renderOrder=10,ze.__graphObjType="link",ze}).onUpdateObj(function(B,I){if(B.__graphDefaultObj){var J=B.children.length?B.children[0]:B,ye=Math.ceil(_(I)*10)/10,Ge=!!ye;if(Ge){var $e=ye/2,ze=e.linkResolution;if(!J.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||J.geometry.parameters.radiusTop!==$e||J.geometry.parameters.radialSegments!==ze){if(!m.hasOwnProperty(ye)){var bn=new se.CylinderGeometry($e,$e,1,ze,1,!1);bn[Qo](new se.Matrix4().makeTranslation(0,1/2,0)),bn[Qo](new se.Matrix4().makeRotationX(Math.PI/2)),m[ye]=bn}J.geometry.dispose(),J.geometry=m[ye]}}var Yr=f(I);if(Yr)J.material=Yr;else{var mr=g(I),ws=new se.Color(Ps(mr||"#f0f0f0")),Ei=e.linkOpacity*Al(mr),_r=Ge?"MeshLambertMaterial":"LineBasicMaterial";if(J.material.type!==_r||!J.material.color.equals(ws)||J.material.opacity!==Ei){var Rs=Ge?y:b;Rs.hasOwnProperty(mr)||(Rs[mr]=new se[_r]({color:ws,transparent:Ei<1,opacity:Ei,depthWrite:Ei>=1})),J.material.dispose(),J.material=Rs[mr]}}}}).digest(T),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var x=pe(e.linkDirectionalArrowLength),v=pe(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var B=new se.Mesh(void 0,new se.MeshLambertMaterial({transparent:!0}));return B.__linkThreeObjType="arrow",B}).onUpdateObj(function(B,I){var J=x(I),ye=e.linkDirectionalArrowResolution;if(!B.geometry.type.match(/^Cone(Buffer)?Geometry$/)||B.geometry.parameters.height!==J||B.geometry.parameters.radialSegments!==ye){var Ge=new se.ConeGeometry(J*.25,J,ye);Ge.translate(0,J/2,0),Ge.rotateX(Math.PI/2),B.geometry.dispose(),B.geometry=Ge}var $e=v(I)||g(I)||"#f0f0f0";B.material.color=new se.Color(Ps($e)),B.material.opacity=e.linkOpacity*3*Al($e)}).digest(T.filter(x))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var w=pe(e.linkDirectionalParticles),R=pe(e.linkDirectionalParticleWidth),F=pe(e.linkDirectionalParticleColor),M=pe(e.linkDirectionalParticleThreeObject),O={},U={};e.particlesDataMapper.onCreateObj(function(){var B=new se.Group;return B.__linkThreeObjType="photons",B.__photonDataMapper=new Ms(B),B}).onUpdateObj(function(B,I){var J=!!B.children.length&&B.children[0],ye=M(I),Ge,$e;if(ye)Ge=ye.geometry,$e=ye.material;else{var ze=Math.ceil(R(I)*10)/10/2,bn=e.linkDirectionalParticleResolution;J&&J.geometry.parameters.radius===ze&&J.geometry.parameters.widthSegments===bn?Ge=J.geometry:(U.hasOwnProperty(ze)||(U[ze]=new se.SphereGeometry(ze,bn,bn)),Ge=U[ze]);var Yr=F(I)||g(I)||"#f0f0f0",mr=new se.Color(Ps(Yr)),ws=e.linkOpacity*3;J&&J.material.color.equals(mr)&&J.material.opacity===ws?$e=J.material:(O.hasOwnProperty(Yr)||(O[Yr]=new se.MeshLambertMaterial({color:mr,transparent:!0,opacity:ws})),$e=O[Yr])}J&&(J.geometry!==Ge&&J.geometry.dispose(),J.material!==$e&&J.material.dispose());var Ei=Math.round(Math.abs(w(I)));B.__photonDataMapper.id(function(_r){return _r.idx}).onCreateObj(function(){return new se.Mesh(Ge,$e)}).onUpdateObj(function(_r){_r.geometry=Ge,_r.material=$e}).digest(cn(new Array(Ei)).map(function(_r,Rs){return{idx:Rs}}))}).digest(T.filter(w))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach(function(B){B.source=B[e.linkSource],B.target=B[e.linkTarget]});var X=e.forceEngine!=="ngraph",oe;if(X){(oe=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var H=e.d3ForceLayout.force("link");H&&H.id(function(B){return B[e.nodeId]}).links(e.graphData.links);var ue=e.dagMode&&bw(e.graphData,function(B){return B[e.nodeId]},{nodeFilter:e.dagNodeFilter,onLoopError:e.onDagError||void 0}),L=Math.max.apply(Math,cn(Object.values(ue||[]))),G=e.dagLevelDistance||e.graphData.nodes.length/(L||1)*xw*(["radialin","radialout"].indexOf(e.dagMode)!==-1?.7:1);if(["lr","rl","td","bu","zin","zout"].includes(t.dagMode)){var Z=["lr","rl"].includes(t.dagMode)?"fx":["td","bu"].includes(t.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(B){return delete B[Z]})}if(["lr","rl","td","bu","zin","zout"].includes(e.dagMode)){var ce=["rl","td","zout"].includes(e.dagMode),k=function(I){return(ue[I[e.nodeId]]-L/2)*G*(ce?-1:1)},j=["lr","rl"].includes(e.dagMode)?"fx":["td","bu"].includes(e.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(B){return B[j]=k(B)})}e.d3ForceLayout.force("dagRadial",["radialin","radialout"].indexOf(e.dagMode)!==-1?xT(function(B){var I=ue[B[e.nodeId]]||-1;return(e.dagMode==="radialin"?L-I:I)*G}).strength(function(B){return e.dagNodeFilter(B)?1:0}):null)}else{var ae=Jf.graph();e.graphData.nodes.forEach(function(B){ae.addNode(B[e.nodeId])}),e.graphData.links.forEach(function(B){ae.addLink(B.source,B.target)}),oe=Jf.forcelayout(ae,pw({dimensions:e.numDimensions},e.ngraphPhysics)),oe.graph=ae}for(var Ne=0;Ne<e.warmupTicks&&!(X&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin);Ne++)oe[X?"tick":"step"]();e.layout=oe,this.resetCountdown()}e.engineRunning=!0,e.onFinishUpdate()}});function Tw(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Object,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=(function(i){function s(){var o;v_(this,s);for(var a=arguments.length,u=new Array(a),l=0;l<a;l++)u[l]=arguments[l];return o=x_(this,s,[].concat(u)),o.__kapsuleInstance=T_(r,[].concat(cn(t?[o]:[]),u)),o}return w_(s,i),S_(s)})(e);return Object.keys(r()).forEach(function(i){return n.prototype[i]=function(){var s,o=(s=this.__kapsuleInstance)[i].apply(s,arguments);return o===this.__kapsuleInstance?this:o}}),n}var Sw=window.THREE?window.THREE:{Group:nm},E_=Tw(vw,Sw.Group,!0);/**
508
+ * @license
509
+ * Copyright 2010-2026 Three.js Authors
510
+ * SPDX-License-Identifier: MIT
511
+ */const ww=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","bumpScale","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dashOffset","dashSize","dispersion","displacementBias","displacementMap","displacementScale","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","envMapRotation","gapSize","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThickness","iridescenceThicknessMap","lightMap","lightMapIntensity","linewidth","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","reflectivity","retroreflectivity","rotation","roughness","roughnessMap","scale","sheen","sheenColor","sheenColorMap","sheenRoughness","sheenRoughnessMap","shininess","size","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","steps","thickness","transmission","transmissionMap"],ep=new WeakMap,tp=new WeakMap,np=new WeakMap,rp=new WeakMap;class Rw{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=ww,this.renderId=0}firstInitialization(e){return this.renderObjects.has(e)===!1?(this.getRenderObjectData(e),!0):!1}hasDynamicInstancing(e){return e.isInstancedMesh===!0&&(e.instanceMatrix.usage===rs||e.instanceColor!==null&&e.instanceColor.usage===rs)}needsVelocity(e){const t=e.getMRT();return t!==null&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(t===void 0){const{geometry:n,object:i}=e;if(t={geometryId:n.id,geometryVersion:this.getGeometryData(n)._version,materialVersion:this.getMaterialData(e.material)._version,worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),i.isInstancedMesh===!0&&(t.instanceMatrixVersion=i.instanceMatrix.version,t.instanceColorVersion=i.instanceColor!==null?i.instanceColor.version:null,t.morphTextureVersion=i.morphTexture!==null?i.morphTexture.version:null),i.isBatchedMesh===!0&&(t.matricesTextureVersion=i._matricesTexture.version,t.colorsTextureVersion=i._colorsTexture!==null?i._colorsTexture.version:null,t.indirectTextureVersion=i._indirectTexture.version),e.bundle!==null&&(t.version=e.bundle.version),e.material.transmission>0){const{width:a,height:u}=e.context;t.bufferWidth=a,t.bufferHeight=u}const{environmentIntensity:s,environmentRotation:o}=e.scene;t.environmentIntensity=s,t.environmentRotation=o.clone(),t.lights=this.getLightsData(e.lightsNode.getBuiltinLights(),[]),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const i=e[n];t[n]={id:i.isInterleavedBufferAttribute?i.data.uuid:i.id,version:i.isInterleavedBufferAttribute?i.data.version:i.version}}return t}containsNode(e){const t=e.material;for(const n in t)if(t[n]&&t[n].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getGeometryData(e){let t=np.get(e);return t===void 0&&(t={_renderId:-1,_version:0,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},e.addEventListener("dispose",()=>{t._version++}),np.set(e,t)),t}getTextureData(e){let t=rp.get(e);if(t===void 0){t={_version:0};const n=()=>{t._version++};e.renderTarget!==null?e.renderTarget.addEventListener("dispose",n):e.addEventListener("dispose",n),rp.set(e,t)}return t}getMaterialData(e){let t=tp.get(e);if(t===void 0){t={_renderId:-1,_version:0};for(const n of this.refreshUniforms){const i=e[n];i!==void 0&&(i===null?t[n]=null:typeof i=="object"&&i.clone!==void 0?i.isTexture===!0?t[n]={id:i.id,version:0,cacheVersion:this.getTextureData(i)._version}:t[n]=i.clone():t[n]=i)}tp.set(e,t)}return t}equals(e,t,n){const{object:i,material:s,geometry:o}=e,a=this.getRenderObjectData(e);if(a.worldMatrix.equals(i.matrixWorld)!==!0)return a.worldMatrix.copy(i.matrixWorld),!1;const u=this.getMaterialData(e.material);if(u._renderId!==n){u._renderId=n;let h=!1;for(const d in u){const f=u[d],p=s[d];if(d!=="_renderId"&&d!=="_version")if(f===null||p===null||p===void 0)f!==(p===void 0?null:p)&&(p==null?u[d]=null:p.isTexture===!0?u[d]={id:p.id,version:p.version,cacheVersion:this.getTextureData(p)._version}:typeof p=="object"&&p.clone!==void 0?u[d]=p.clone():u[d]=p,h=!0);else if(f.equals!==void 0)f.equals(p)===!1&&(f.copy(p),h=!0);else if(p.isTexture===!0){const g=this.getTextureData(p);(f.id!==p.id||f.version!==p.version||f.cacheVersion!==g._version)&&(f.id=p.id,f.version=p.version,f.cacheVersion=g._version,h=!0)}else f!==p&&(u[d]=p,h=!0)}h===!0&&u._version++}if(a.materialVersion!==u._version)return a.materialVersion=u._version,!1;if(u.transmission>0){const{width:h,height:d}=e.context;if(a.bufferWidth!==h||a.bufferHeight!==d)return a.bufferWidth=h,a.bufferHeight=d,!1}if(a.geometryId!==o.id)return a.geometryId=o.id,a.geometryVersion=this.getGeometryData(o)._version,!1;const l=this.getGeometryData(e.geometry);if(l._renderId!==n){l._renderId=n;let h=!1;const d=o.attributes,f=l.attributes;let p=0,g=0;for(const b in d)p++;for(const b in f){g++;const T=f[b],x=d[b];if(x===void 0){delete f[b],h=!0;continue}const v=x.isInterleavedBufferAttribute?x.data.uuid:x.id,w=x.isInterleavedBufferAttribute?x.data.version:x.version;(T.id!==v||T.version!==w)&&(T.id=v,T.version=w,h=!0)}g!==p&&(l.attributes=this.getAttributesData(d),h=!0);const _=o.index,m=_?_.id:null,y=_?_.version:null;(l.indexId!==m||l.indexVersion!==y)&&(l.indexId=m,l.indexVersion=y,h=!0),(l.drawRange.start!==o.drawRange.start||l.drawRange.count!==o.drawRange.count)&&(l.drawRange.start=o.drawRange.start,l.drawRange.count=o.drawRange.count,h=!0),h===!0&&l._version++}if(a.geometryVersion!==l._version)return a.geometryVersion=l._version,!1;if(a.morphTargetInfluences){let h=!1;for(let d=0;d<a.morphTargetInfluences.length;d++)a.morphTargetInfluences[d]!==i.morphTargetInfluences[d]&&(a.morphTargetInfluences[d]=i.morphTargetInfluences[d],h=!0);if(h)return!1}if(i.isInstancedMesh===!0){const h=i.instanceColor!==null?i.instanceColor.version:null,d=i.morphTexture!==null?i.morphTexture.version:null;if(a.instanceMatrixVersion!==i.instanceMatrix.version||a.instanceColorVersion!==h||a.morphTextureVersion!==d)return a.instanceMatrixVersion=i.instanceMatrix.version,a.instanceColorVersion=h,a.morphTextureVersion=d,!1}if(i.isBatchedMesh===!0){const h=i._colorsTexture!==null?i._colorsTexture.version:null;if(a.matricesTextureVersion!==i._matricesTexture.version||a.colorsTextureVersion!==h||a.indirectTextureVersion!==i._indirectTexture.version)return a.matricesTextureVersion=i._matricesTexture.version,a.colorsTextureVersion=h,a.indirectTextureVersion=i._indirectTexture.version,!1}if(a.lights)for(let h=0;h<t.length;h++){const d=a.lights[h],f=t[h];if(d.map!==f.map||d.cacheVersion!==f.cacheVersion||d.shadowMapWidth!==f.shadowMapWidth||d.shadowMapHeight!==f.shadowMapHeight)return d.map=f.map,d.cacheVersion=f.cacheVersion,d.shadowMapWidth=f.shadowMapWidth,d.shadowMapHeight=f.shadowMapHeight,!1}const c=e.scene;return c.environment!==null&&s.envMap===null&&(a.environmentIntensity!==c.environmentIntensity||a.environmentRotation.equals(c.environmentRotation)===!1)?(a.environmentIntensity=c.environmentIntensity,a.environmentRotation.copy(c.environmentRotation),!1):a.center&&a.center.equals(i.center)===!1?(a.center.copy(i.center),!1):(e.bundle!==null&&(a.version=e.bundle.version),!0)}getLightsData(e,t){t.length=0;for(const n of e){let i=null;n.isSpotLight===!0&&n.map!==null&&(i={map:n.map.version,cacheVersion:this.getTextureData(n.map)._version}),n.castShadow===!0&&n.shadow!==void 0&&(i===null&&(i={}),i.shadowMapWidth=n.shadow.mapSize.width,i.shadowMapHeight=n.shadow.mapSize.height),i!==null&&t.push(i)}return t}getLights(e,t){let n=ep.get(e);return n===void 0&&(n={renderId:-1,lightsData:[]},ep.set(e,n)),n.renderId===t||(n.renderId=t,this.getLightsData(e.getBuiltinLights(),n.lightsData)),n.lightsData}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.hasDynamicInstancing(e.object)||this.firstInitialization(e)||this.needsVelocity(t.renderer))return Yn.FULL;const{renderId:n}=t;let i=Yn.NONE;this.renderId!==n&&(this.renderId=n,i=Yn.SHARED);const s=e.object.static===!0,o=e.bundle!==null&&e.bundle.static===!0&&this.getRenderObjectData(e).version===e.bundle.version;if(s||o)return i;const a=this.getLights(e.lightsNode,n);return this.equals(e,a,n)===!1&&(i=Yn.FULL),i}}const Aw=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];function Nw(r){const e=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return r.split(`
512
+ `).map(t=>{const n=t.match(e);if(!n)return null;const i=n[1]||n[2]||"",s=n[3].split("?")[0],o=parseInt(n[4],10),a=parseInt(n[5],10),u=s.split("/").pop();return{fn:i,file:u,line:o,column:a}}).filter(t=>t&&!Aw.some(n=>n.test(t.file)))}class Ft{constructor(e=null){this.isStackTrace=!0,this.stack=Nw(e||new Error().stack)}getLocation(){if(this.stack.length===0)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(this.stack.length===0)return e;const t=this.stack.map(n=>{const i=`${n.file}:${n.line}:${n.column}`;return n.fn?` at ${n.fn} (${i})`:` at ${i}`}).join(`
513
+ `);return`${e}
514
+ ${t}`}}function fd(r,e=0){let t=3735928559^e,n=1103547991^e;if(Array.isArray(r))for(let i=0,s;i<r.length;i++)s=r[i],t=Math.imul(t^s,2654435761),n=Math.imul(n^s,1597334677);else for(let i=0,s;i<r.length;i++)s=r.charCodeAt(i),t=Math.imul(t^s,2654435761),n=Math.imul(n^s,1597334677);return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&n)+(t>>>0)}const wi=r=>fd(r),Do=r=>fd(r),oo=(...r)=>fd(r),Ew=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),ip=new WeakMap;function pd(r){return Ew.get(r)}function _u(r){if(r==null)return null;const e=typeof r;return r.isNode===!0?"node":e==="number"?"float":e==="boolean"?"bool":e==="string"?"string":e==="function"?"shader":r.isVector2===!0?"vec2":r.isVector3===!0?"vec3":r.isVector4===!0?"vec4":r.isMatrix2===!0?"mat2":r.isMatrix3===!0?"mat3":r.isMatrix4===!0?"mat4":r.isColor===!0?"color":r instanceof ArrayBuffer?"ArrayBuffer":null}function C_(r){if(r.isDepthTexture===!0)return"float";const e=r.format;let t;e===Co||e===Mo||e===Dn||e===Ln||e===Qh?t=1:e===pn||e===Po?t=2:e===Bo||e===Zh?t=3:t=4;let n;if(r.type===qe?n="uint":r.type===gt?n="int":n="float",t===1)return n;let i=pd(t);return n!=="float"&&(i=n[0]+i),i}function gd(r,...e){const t=r?r.slice(-4):void 0;return e.length===1&&(t==="vec2"?e=[e[0],e[0]]:t==="vec3"?e=[e[0],e[0],e[0]]:t==="vec4"&&(e=[e[0],e[0],e[0],e[0]])),r==="color"?new Dt(...e):t==="vec2"?new de(...e):t==="vec3"?new z(...e):t==="vec4"?new tt(...e):t==="mat2"?new Hm(...e):t==="mat3"?new gs(...e):t==="mat4"?new bt(...e):r==="bool"?e[0]||!1:r==="float"||r==="int"||r==="uint"?e[0]||0:r==="string"?e[0]||"":r==="ArrayBuffer"?Mw(e[0]):null}function M_(r){let e=ip.get(r);return e===void 0&&(e={},ip.set(r,e)),e}function Cw(r){let e="";const t=new Uint8Array(r);for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Mw(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer}function P_(r){return r[0]!==void 0&&r[0]!==null&&(r[0].isNode||Object.getPrototypeOf(r[0])!==Object.prototype)}const Bs={VERTEX:"vertex"},ie={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Wt={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},Pw=["fragment","vertex"],El=["setup","analyze","generate"],Cl=[...Pw,"compute"],_s=["x","y","z","w"],Bw={analyze:"setup",generate:"analyze"};let Fw=0;class te extends Lu{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=ie.NONE,this.updateBeforeType=ie.NONE,this.updateAfterType=ie.NONE,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=Fw++,this.stackTrace=null,te.captureStackTrace===!0&&(this.stackTrace=new Ft)}set needsUpdate(e){e===!0&&this.version++}get uuid(){return this._uuid===null&&(this._uuid=lu.generateUUID()),this._uuid}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,ie.FRAME)}onRenderUpdate(e){return this.onUpdate(e,ie.RENDER)}onObjectUpdate(e){return this.onUpdate(e,ie.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const n of Object.getOwnPropertyNames(this)){const i=this[n];if(!(n.startsWith("_")===!0||e.has(i))){if(Array.isArray(i)===!0)for(let s=0;s<i.length;s++){const o=i[s];o&&o.isNode===!0&&t.push({property:n,index:s,childNode:o})}else if(i&&i.isNode===!0)t.push({property:n,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(const s in i){if(s.startsWith("_")===!0)continue;const o=i[s];o&&o.isNode===!0&&t.push({property:n,index:s,childNode:o})}}}return t}getCacheKey(e=!1,t=null){if(e=e||this.version!==this._cacheKeyVersion,e===!0||this._cacheKey===null){t===null&&(t=new Set);const n=[];for(const{property:i,childNode:s}of this._getChildren(t))n.push(wi(i.slice(0,-4)),s.getCacheKey(e,t));this._cacheKey=oo(Do(n),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e,t=null){const n=e.getDataFromNode(this);let i;return t!==null?(n.typeFromOutput=n.typeFromOutput||{},i=n.typeFromOutput[t],i===void 0&&(i=this.generateNodeType(e,t),n.typeFromOutput[t]=i)):(i=n.type,i===void 0&&(i=this.generateNodeType(e),n.type=i)),i}generateNodeType(e,t=null){const n=e.getNodeProperties(this);return n.outputNode?n.outputNode.getNodeType(e,t):this.nodeType}getShared(e){const t=this.getHash(e),n=e.getNodeFromHash(t);let i=null;if(n&&n!==this)i=n;else if(e.context.overrideNodes){const s=e.context.overrideNodes.get(this);if(s){const o=e.getDataFromNode(this);o.isOverwritten!==!0?(o.isOverwritten=!0,i=s(e).overrideNode(this,null),o.sharedNode=i):i=o.sharedNode}}return i||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let n=0;for(const i of this.getChildren())t["node"+n++]=i;return t.outputNode||null}analyze(e,t=null){const n=e.increaseUsage(this);if(this.parents===!0){const i=e.getDataFromNode(this,"any");i.stages=i.stages||{},i.stages[e.shaderStage]=i.stages[e.shaderStage]||[],i.stages[e.shaderStage].push(t)}if(n===1){const i=e.getNodeProperties(this);for(const s of Object.values(i))s&&s.isNode===!0&&s.build(e,this)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&n.isNode===!0)return n.build(e,t)}updateBefore(){Y("Abstract function.")}updateAfter(){Y("Abstract function.")}update(){Y("Abstract function.")}before(e){return this._beforeNodes===null&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);if(this._beforeNodes!==null){const u=this._beforeNodes;this._beforeNodes=null;for(const l of u)l.build(e,t);this._beforeNodes=u}const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const s=Bw[e.buildStage];if(s&&i.buildStages[s]!==!0){const u=e.getBuildStage();e.setBuildStage(s),this.build(e),e.setBuildStage(u)}e.addChain(this);let o=null;const a=e.getBuildStage();if(a==="setup"){e.addNode(this),this.updateReference(e);const u=e.getNodeProperties(this);if(u.initialized!==!0){u.initialized=!0,u.outputNode=this.setup(e)||u.outputNode||null;for(const l of Object.values(u))if(l&&l.isNode===!0){if(l.parents===!0){const c=e.getNodeProperties(l);c.parents=c.parents||[],c.parents.push(this)}l.build(e)}e.addSequentialNode(this)}o=u.outputNode}else if(a==="analyze")this.analyze(e,t);else if(a==="generate"){if(this.generate.length<2){const l=this.getNodeType(e),c=e.getDataFromNode(this);o=c.snippet,o===void 0?c.generated===void 0?(c.generated=!0,o=this.generate(e)||"",c.snippet=o):(Y("Node: Recursion detected.",this),o="/* Recursion detected. */"):c.flowCodes!==void 0&&e.context.nodeBlock!==void 0&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),o=e.format(o,l,t)}else o=this.generate(e,t)||"";o===""&&t!==null&&t!=="void"&&t!=="OutputType"&&(V(`TSL: Invalid generated code, expected a "${t}".`),o=e.generateConst(t))}return e.removeChain(this),o}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:i,index:s,childNode:o}of t)s!==void 0?(n[i]===void 0&&(n[i]=Number.isInteger(s)?[]:{}),n[i][s]=o.toJSON(e.meta).uuid):n[i]=o.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(e.inputNodes!==void 0){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const i=[];for(const s of e.inputNodes[n])i.push(t[s]);this[n]=i}else if(typeof e.inputNodes[n]=="object"){const i={};for(const s in e.inputNodes[n]){const o=e.inputNodes[n][s];i[s]=t[o]}this[n]=i}else{const i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){const{uuid:t,type:n}=this,i=e===void 0||typeof e=="string";i&&(e={textures:{},images:{},nodes:{}});let s=e.nodes[t];s===void 0&&(s={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},i!==!0&&(e.nodes[s.uuid]=s),this.serialize(s),delete s.meta);function o(a){const u=[];for(const l in a){const c=a[l];delete c.metadata,u.push(c)}return u}if(i){const a=o(e.textures),u=o(e.images),l=o(e.nodes);a.length>0&&(s.textures=a),u.length>0&&(s.images=u),l.length>0&&(s.nodes=l)}return s}}te.captureStackTrace=!1;class Lo extends te{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e),n=this.node.build(e),i=this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint");return`${n}[ ${i} ]`}}class B_ extends te{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const i of this.convertTo.split("|"))(n===null||e.getTypeLength(t)===e.getTypeLength(i))&&(n=i);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,i=this.getNodeType(e),s=n.build(e,i);return e.format(s,i,t)}}class ut extends te{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if(e.getBuildStage()==="generate"){const i=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(s.propertyName!==void 0)return e.format(s.propertyName,i,t);if(i!=="void"&&t!=="void"&&this.hasDependencies(e)){const o=super.build(e,i),a=e.getVarFromNode(this,null,i),u=e.getPropertyName(a);return e.addLineFlowCode(`${u} = ${o}`,this),s.snippet=o,s.propertyName=u,e.format(s.propertyName,i,t)}}return super.build(e,t)}}class Dw extends ut{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return this.nodeType!==null?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0))}generate(e,t){const n=this.getNodeType(e),i=e.getTypeLength(n),s=this.nodes,o=e.getComponentType(n),a=[];let u=0;for(const c of s){if(u>=i){V(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`,this.stackTrace);break}let h=c.getNodeType(e),d=e.getTypeLength(h),f;if(u+d>i&&(V(`TSL: Length of '${n}()' data exceeds maximum length of output type.`,this.stackTrace),d=i-u,h=e.getTypeFromLength(d)),u+=d,f=c.build(e,h),e.getComponentType(h)!==o){const g=e.getTypeFromLength(d,o);f=e.format(f,h,g)}a.push(f)}const l=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(l,n,t)}}const Lw=_s.join("");class Ow extends te{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(_s.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const n=this.node,i=e.getTypeLength(n.getNodeType(e));let s=null;if(i>1){let o=null;this.getVectorLength()>=i&&(o=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const u=n.build(e,o);this.components.length===i&&this.components===Lw.slice(0,this.components.length)?s=e.format(u,o,t):s=e.format(`${u}.${this.components}`,this.getNodeType(e),t)}else s=n.build(e,t);return s}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class Uw extends ut{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:i}=this,s=this.getNodeType(e),o=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(n.length,o),u=i.build(e,a),l=t.build(e,s),c=e.getTypeLength(s),h=[];for(let d=0;d<c;d++){const f=_s[d];f===n[0]?(h.push(u),d+=n.length-1):h.push(l+"."+f)}return`${e.getType(s)}( ${h.join(", ")} )`}}class Iw extends ut{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:n}=this,i=this.getNodeType(e),s=n.build(e),o=e.getVarFromNode(this),a=e.getPropertyName(o);e.addLineFlowCode(a+" = "+s,this);const u=e.getTypeLength(i),l=[];let c=0;for(let h=0;h<u;h++){const d=_s[h];d===t[c]?(l.push("1.0 - "+(a+"."+d)),c++):l.push(a+"."+d)}return`${e.getType(i)}( ${l.join(", ")} )`}}class md extends te{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}generateNodeType(){return this.nodeType===null?_u(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=_u(this.value),e.nodeType=this.nodeType,e.valueType==="ArrayBuffer"&&(e.value=Cw(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?gd(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){Y("Abstract function.")}}const sp=/float|u?int/;class Gn extends md{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const n=this.getNodeType(e);return sp.test(n)&&sp.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}}class kw extends te{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return this.structNode.isMemberNode&&this.structNode.hasMember(e)===!1?!1:this.structNode.getMemberType(e,this.property)!=="void"}generateNodeType(e){return this.hasMember(e)===!1?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(this.hasMember(e)===!1)return"float";const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}generate(e){if(this.hasMember(e)===!1){Y(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const n=this.getNodeType(e);return e.generateConst(n)}return this.structNode.build(e)+"."+this.property}}let mi=null;const ch=new Map;function E(r,e){if(ch.has(r)){Y(`TSL: Redefinition of method chaining '${r}'.`);return}if(typeof e!="function")throw new Error(`THREE.TSL: Node element ${r} is not a function`);ch.set(r,e),r!=="assign"&&(te.prototype[r]=function(...t){return this.isStackNode?this.addToStack(e(...t)):e(this,...t)},te.prototype[r+"Assign"]=function(...t){return this.isStackNode?this.assign(t[0],e(...t)):this.assign(e(this,...t))})}const Gw=r=>r.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),op=r=>Gw(r).split("").sort().join("");te.prototype.assign=function(...r){if(this.isStackNode!==!0)return mi!==null?mi.assign(this,...r):V("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Ft),this;{const e=ch.get("assign");return this.addToStack(e(...r))}};te.prototype.toVarIntent=function(){return this};te.prototype.get=function(r){return new kw(this,r)};const ao={};function Zo(r,e,t){ao[r]=ao[e]=ao[t]={get(){this._cache=this._cache||{};let o=this._cache[r];return o===void 0&&(o=new Ow(this,r),this._cache[r]=o),o},set(o){this[r].assign(K(o))}};const n=r.toUpperCase(),i=e.toUpperCase(),s=t.toUpperCase();te.prototype["set"+n]=te.prototype["set"+i]=te.prototype["set"+s]=function(o){const a=op(r);return new Uw(this,a,K(o))},te.prototype["flip"+n]=te.prototype["flip"+i]=te.prototype["flip"+s]=function(){const o=op(r);return new Iw(this,o)}}const xn=["x","y","z","w"],vn=["r","g","b","a"],Tn=["s","t","p","q"];for(let r=0;r<4;r++){let e=xn[r],t=vn[r],n=Tn[r];Zo(e,t,n);for(let i=0;i<4;i++){e=xn[r]+xn[i],t=vn[r]+vn[i],n=Tn[r]+Tn[i],Zo(e,t,n);for(let s=0;s<4;s++){e=xn[r]+xn[i]+xn[s],t=vn[r]+vn[i]+vn[s],n=Tn[r]+Tn[i]+Tn[s],Zo(e,t,n);for(let o=0;o<4;o++)e=xn[r]+xn[i]+xn[s]+xn[o],t=vn[r]+vn[i]+vn[s]+vn[o],n=Tn[r]+Tn[i]+Tn[s]+Tn[o],Zo(e,t,n)}}}for(let r=0;r<32;r++)ao[r]={get(){this._cache=this._cache||{};let e=this._cache[r];return e===void 0&&(e=new Lo(this,new Gn(r,"uint")),this._cache[r]=e),e},set(e){this[r].assign(K(e))}};Object.defineProperties(te.prototype,ao);const Vw=function(r,e=null){const t=_u(r);return t==="node"?r:e===null&&(t==="float"||t==="boolean")||t&&t!=="shader"&&t!=="string"?K(hh(r,e)):t==="shader"?r.isFn?r:P(r):r},$w=function(r,e=null){for(const t in r)r[t]=K(r[t],e);return r},zw=function(r,e=null){const t=r.length;for(let n=0;n<t;n++)r[n]=K(r[n],e);return r},F_=function(r,e=null,t=null,n=null){function i(c){return n!==null?(c=K(Object.assign(c,n)),n.intent===!0&&(c=c.toVarIntent())):c=K(c),c}let s,o=e,a,u;function l(c){let h;return o?h=/[a-z]/i.test(o)?o+"()":o:h=r.type,a!==void 0&&c.length<a?(V(`TSL: "${h}" parameter length is less than minimum required.`,new Ft),c.concat(new Array(a-c.length).fill(0))):u!==void 0&&c.length>u?(V(`TSL: "${h}" parameter length exceeds limit.`,new Ft),c.slice(0,u)):c}return e===null?s=(...c)=>i(new r(...Zi(l(c)))):t!==null?(t=K(t),s=(...c)=>i(new r(e,...Zi(l(c)),t))):s=(...c)=>i(new r(e,...Zi(l(c)))),s.setParameterLength=(...c)=>(c.length===1?a=u=c[0]:c.length===2&&([a,u]=c),s),s.setName=c=>(o=c,s),s},Ww=function(r,...e){return new r(...Zi(e))};class Hw extends te{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:n}=this,i=e.getNodeProperties(t),s=e.getClosestSubBuild(t.subBuilds)||"",o=s||"default";if(i[o])return i[o];const a=e.subBuildFn,u=e.fnCall;e.subBuildFn=s,e.fnCall=this;let l=null;if(t.layout){if(n){const d=t.layout.inputs;if(P_(n)){const f=n;for(let p=0;p<d.length;p++){const g=f[p];g&&g.isNode&&g.build(e)}}else{const f=n[0];for(const p of d){const g=f[p.name];g&&g.isNode&&g.build(e)}}}const c=e.buildFunctionNode(t);e.addInclude(c);const h=n?jw(n):null;l=c.call(h)}else{const c=new Proxy(e,{get:(g,_,m)=>{let y;return Symbol.iterator===_?y=function*(){yield void 0}:y=Reflect.get(g,_,m),y}}),h=n?qw(n):null,d=Array.isArray(n)?n.length>0:n!==null,f=t.jsFunc,p=d||f.length>1?f(h,c):f(c);l=K(p)}return e.subBuildFn=a,e.fnCall=u,t.once&&(i[o]=l),l}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),n=e.getSubBuildOutput(this);return t[n]=t[n]||this.setupOutput(e),t[n].subBuild=e.getClosestSubBuild(this),t[n]}build(e,t=null){let n=null;const i=e.getBuildStage(),s=e.getNodeProperties(this),o=e.getSubBuildOutput(this),a=this.getOutputNode(e),u=e.fnCall;if(e.fnCall=this,i==="setup"){const l=e.getSubBuildProperty("initialized",this);if(s[l]!==!0&&(s[l]=!0,s[o]=this.getOutputNode(e),s[o].build(e),this.shaderNode.subBuilds))for(const c of e.chaining){const h=e.getDataFromNode(c,"any");h.subBuilds=h.subBuilds||new Set;for(const d of this.shaderNode.subBuilds)h.subBuilds.add(d)}n=s[o]}else i==="analyze"?a.build(e,t):i==="generate"&&(n=a.build(e,t)||"");return e.fnCall=u,n}}function jw(r){let e;return xd(r),P_(r)?e=[...r]:e=r[0],e}function qw(r){let e=0;return xd(r),new Proxy(r,{get:(t,n,i)=>{let s;if(n==="length")return s=r.length,s;if(Symbol.iterator===n)s=function*(){for(const o of r)yield K(o)};else{if(r.length>0)if(Object.getPrototypeOf(r[0])===Object.prototype){const o=r[0];o[n]===void 0?s=o[e++]:s=Reflect.get(o,n,i)}else r[0]instanceof te&&(r[n]===void 0?s=r[e++]:s=Reflect.get(r,n,i));else s=Reflect.get(t,n,i);s=K(s)}return s}})}class Xw extends te{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Hw(this,e)}setup(){return this.call()}}const Kw=[!1,!0],Yw=[0,1,2,3],Qw=[-1,-2],D_=[.5,1.5,1/3,1e-6,1e6,Math.PI,Math.PI*2,1/Math.PI,2/Math.PI,1/(Math.PI*2),Math.PI/2],_d=new Map;for(const r of Kw)_d.set(r,new Gn(r));const yd=new Map;for(const r of Yw)yd.set(r,new Gn(r,"uint"));const bd=new Map([...yd].map(r=>new Gn(r.value,"int")));for(const r of Qw)bd.set(r,new Gn(r,"int"));const Hu=new Map([...bd].map(r=>new Gn(r.value)));for(const r of D_)Hu.set(r,new Gn(r));for(const r of D_)Hu.set(-r,new Gn(-r));const ju={bool:_d,uint:yd,ints:bd,float:Hu},ap=new Map([..._d,...Hu]),hh=(r,e)=>ap.has(r)?ap.get(r):r.isNode===!0?r:new Gn(r,e),Ze=function(r,e=null){return(...t)=>{for(const i of t)if(i===void 0)return V(`TSL: Invalid parameter for the type "${r}".`,new Ft),new Gn(0,r);if((t.length===0||!["bool","float","int","uint"].includes(r)&&t.every(i=>{const s=typeof i;return s!=="object"&&s!=="function"}))&&(t=[gd(r,...t)]),t.length===1&&e!==null&&e.has(t[0]))return Jo(e.get(t[0]));if(t.length===1){const i=hh(t[0],r);return i.nodeType===r?Jo(i):Jo(new B_(i,r))}const n=t.map(i=>hh(i));return Jo(new Dw(n,r))}};function dh(r){return r&&r.isNode&&r.traverse(e=>{e.isConstNode&&(r=e.value)}),!!r}const Zw=r=>r!=null?r.nodeType||r.convertTo||(typeof r=="string"?r:null):null;function Js(r,e){return new Xw(r,e)}const K=(r,e=null)=>Vw(r,e),Jo=(r,e=null)=>K(r,e).toVarIntent(),xd=(r,e=null)=>new $w(r,e),Zi=(r,e=null)=>new zw(r,e),ke=(r,e=null,t=null,n=null)=>new F_(r,e,t,n),$=(r,...e)=>new Ww(r,...e),W=(r,e=null,t=null,n={})=>new F_(r,e,t,{...n,intent:!0});let Jw=0;class eR extends te{constructor(e,t=null){super();let n=null;t!==null&&(typeof t=="object"?n=t.return:(typeof t=="string"?n=t:V("TSL: Invalid layout type.",new Ft),t=null)),this.shaderNode=new Js(e,n),t!==null&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if(typeof e.inputs!="object"){const n={name:"fn"+Jw++,type:t,inputs:[]};for(const i in e)i!=="return"&&n.inputs.push({name:i,type:e[i]});e=n}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return this.shaderNode.nodeType==="void"&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return V('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function P(r,e=null){const t=new eR(r,e);return new Proxy(()=>{},{apply(n,i,s){return t.call(...s)},get(n,i,s){return Reflect.get(t,i,s)},set(n,i,s,o){return Reflect.set(t,i,s,o)}})}const yu=r=>{mi=r},L_=()=>mi,Me=(...r)=>mi.If(...r);function tR(r){return mi&&mi.addToStack(r),r}E("toStack",tR);const nR=new Ze("color"),N=new Ze("float",ju.float),Ae=new Ze("int",ju.ints),He=new Ze("uint",ju.uint),Oo=new Ze("bool",ju.bool),re=new Ze("vec2"),Ht=new Ze("ivec2"),rR=new Ze("uvec2"),iR=new Ze("bvec2"),D=new Ze("vec3"),sR=new Ze("ivec3"),oR=new Ze("uvec3"),aR=new Ze("bvec3"),q=new Ze("vec4"),uR=new Ze("ivec4"),lR=new Ze("uvec4"),cR=new Ze("bvec4"),vd=new Ze("mat2"),nt=new Ze("mat3"),Gr=new Ze("mat4");E("toColor",nR);E("toFloat",N);E("toInt",Ae);E("toUint",He);E("toBool",Oo);E("toVec2",re);E("toIVec2",Ht);E("toUVec2",rR);E("toBVec2",iR);E("toVec3",D);E("toIVec3",sR);E("toUVec3",oR);E("toBVec3",aR);E("toVec4",q);E("toIVec4",uR);E("toUVec4",lR);E("toBVec4",cR);E("toMat2",vd);E("toMat3",nt);E("toMat4",Gr);const hR=ke(Lo).setParameterLength(2),dR=(r,e)=>new B_(K(r),e);E("element",hR);E("convert",dR);class _e extends te{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1,i=null){super(e),this.name=t,this.varying=n,this.placeholderNode=K(i),this.isPropertyNode=!0,this.global=!0}getNodeType(e){const t=super.getNodeType(e);return t==="output"?e.getOutputType():t}customCacheKey(){return wi(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;if(this.varying===!0)t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0;else if(t=e.getVarFromNode(this,this.name),this.placeholderNode!==null&&e.hasWriteUsage(this)===!1){const n=this.placeholderNode.build(e,this.getNodeType(e));e.addLineFlowCode(`${e.getPropertyName(t)} = ${n}`,this)}return e.getPropertyName(t)}}const Wr=(r,e,t=null)=>new _e(r,e,!1,t),Ri=(r,e,t=null)=>new _e(r,e,!0,t),xe=$(_e,"vec4","DiffuseColor"),zi=$(_e,"vec3","DiffuseContribution"),up=$(_e,"vec3","EmissiveColor"),hn=$(_e,"float","Roughness"),hi=$(_e,"float","Metalness"),fh=$(_e,"float","Clearcoat"),uo=$(_e,"float","ClearcoatRoughness"),$t=$(_e,"vec3","Sheen"),si=$(_e,"float","SheenRoughness"),Td=$(_e,"float","Iridescence"),ph=$(_e,"float","IridescenceIOR"),gh=$(_e,"float","IridescenceThickness"),mh=$(_e,"float","AlphaT"),ni=$(_e,"float","Anisotropy"),qa=$(_e,"vec3","AnisotropyT"),Ji=$(_e,"vec3","AnisotropyB"),En=$(_e,"color","SpecularColor"),Mr=$(_e,"color","SpecularColorBlended"),Xn=$(_e,"float","SpecularF90"),_h=$(_e,"float","Shininess"),lo=$(_e,"output","Output"),es=$(_e,"float","dashSize"),bu=$(_e,"float","gapSize"),Xa=$(_e,"float","IOR"),yh=$(_e,"float","Transmission"),O_=$(_e,"float","Thickness"),U_=$(_e,"float","AttenuationDistance"),I_=$(_e,"color","AttenuationColor"),k_=$(_e,"float","Dispersion"),xu=$(_e,"float","Retroreflectivity"),lp=$(_e,"float","AmbientOcclusion",!1,1);class G_ extends te{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1,i=null){super("string"),this.name=e,this.shared=t,this.order=n,this.updateType=i,this.isUniformGroup=!0}update(){this.needsUpdate=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const fR=(r,e=1,t=null)=>new G_(r,!1,e,t),Sd=(r,e=0,t=null)=>new G_(r,!0,e,t);ie.FRAME;const Q=Sd("render",0,ie.RENDER),pR=fR("object",1,ie.OBJECT);class Uo extends md{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=pR}setName(e){return this.name=e,this}label(e){return Y('TSL: "label()" has been deprecated. Use "setName()" instead.',new Ft),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}getSharedNode(e){const t=this.getUniformHash(e);let n=e.getNodeFromHash(t);return n===void 0&&(e.setHashNode(this,t),n=this),n}onUpdate(e,t){return e=e.bind(this),super.onUpdate(n=>{const i=e(n,this);i!==void 0&&(this.value=i)},t)}getInputType(e){let t=super.getInputType(e);return t==="bool"&&(t="uint"),t}generate(e,t){const n=this.getNodeType(e),i=this.getSharedNode(e),s=i.getInputType(e),o=e.getUniformFromNode(i,s,e.shaderStage,this.name||e.context.nodeName),a=e.getPropertyName(o);e.context.nodeName!==void 0&&delete e.context.nodeName;let u=a;if(n==="bool"){const l=e.getDataFromNode(this);let c=l.propertyName;if(c===void 0){const h=e.getVarFromNode(this,null,"bool");c=e.getPropertyName(h),l.propertyName=c,u=e.format(a,s,n),e.addLineFlowCode(`${c} = ${u}`,this)}u=c}return e.format(u,n,t)}}const ne=(r,e)=>{const t=Zw(e||r);if(t===r&&(r=gd(t)),r&&r.isNode===!0){let n=r.value;r.traverse(i=>{i.isConstNode===!0&&(n=i.value)}),r=n}return new Uo(r,t)};class cp extends ut{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getArrayCount(){return this.count}generateNodeType(e){return this.nodeType===null?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return this.nodeType===null?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const bh=(...r)=>{let e;if(r.length===1){const t=r[0].map(n=>K(n));e=new cp(null,t.length,t)}else{const t=r[0],n=r[1];e=new cp(t,n)}return e};E("toArray",(r,e)=>bh(Array(e).fill(r)));class gR extends ut{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(e,t){return t!=="void"?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(e.isAvailable("swizzleAssign")===!1&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return _s.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,i=t.getScope(),s=e.getDataFromNode(i);s.assign=!0;const o=e.getNodeProperties(this);o.sourceNode=n,o.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:i}=e.getNodeProperties(this),s=this.needsSplitAssign(e),o=n.build(e),a=n.getNodeType(e),u=i.build(e,a),l=i.getNodeType(e),c=e.getDataFromNode(this);let h;if(c.initialized===!0)t!=="void"&&(h=o);else if(s){const d=e.getVarFromNode(this,null,a),f=e.getPropertyName(d);e.addLineFlowCode(`${f} = ${u}`,this);const p=n.node,_=p.node.context({assign:!0}).build(e);for(let m=0;m<p.components.length;m++){const y=p.components[m];e.addLineFlowCode(`${_}.${y} = ${f}[ ${m} ]`,this)}t!=="void"&&(h=o)}else h=`${o} = ${u}`,(t==="void"||l==="void")&&(e.addLineFlowCode(h,this),t!=="void"&&(h=o));return c.initialized=!0,e.format(h,a,t)}}const mR=ke(gR).setParameterLength(2);E("assign",mR);class _R extends ut{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}generateNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],n=this.functionNode,i=n.getInputs(e),s=this.parameters,o=(u,l)=>{const c=l.type,h=c==="pointer";let d;return h?d="&"+u.build(e):d=u.build(e,c),d};if(Array.isArray(s)){if(s.length>i.length)V("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),s.length=i.length;else if(s.length<i.length)for(V("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");s.length<i.length;)s.push(N(0));for(let u=0;u<s.length;u++)t.push(o(s[u],i[u]))}else for(const u of i){const l=s[u.name];l!==void 0?t.push(o(l,u)):(V(`TSL: Input '${u.name}' not found in 'Fn()'.`),t.push(o(N(0),u)))}return`${n.build(e,"property")}( ${t.join(", ")} )`}}const yR=(r,...e)=>(e=e.length>1||e[0]&&e[0].isNode===!0?Zi(e):xd(e[0]),new _R(K(r),e));E("call",yR);const bR={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Ie extends ut{static get type(){return"OperatorNode"}constructor(e,t,n,...i){if(super(),i.length>0){let s=new Ie(e,t,n);for(let o=0;o<i.length-1;o++)s=new Ie(e,s,i[o]);t=s,n=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=n,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(bR[this.op],t)}generateNodeType(e,t=null){const n=this.op,i=this.aNode,s=this.bNode,o=i.getNodeType(e),a=s?s.getNodeType(e):null;if(o==="void"||a==="void")return t||"void";if(n==="%")return o;if(n==="~"||n==="&"||n==="|"||n==="^"||n===">>"||n==="<<")return e.getIntegerType(o);if(n==="&&"||n==="||"||n==="^^")return"bool";if(n==="!"){const u=e.getTypeLength(o);return u>1?`bvec${u}`:"bool"}else if(n==="=="||n==="!="||n==="<"||n===">"||n==="<="||n===">="){const u=Math.max(e.getTypeLength(o),e.getTypeLength(a));return u>1?`bvec${u}`:"bool"}else{if(e.isMatrix(o)){if(a==="float")return o;if(e.isVector(a))return e.getVectorFromMatrix(o);if(e.isMatrix(a))return o}else if(e.isMatrix(a)){if(o==="float")return a;if(e.isVector(o))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(o)?a:o}}generate(e,t){const n=this.op,{aNode:i,bNode:s}=this,o=this.getNodeType(e,t);let a=null,u=null;o!=="void"?(a=i.getNodeType(e),u=s?s.getNodeType(e):null,n==="<"||n===">"||n==="<="||n===">="||n==="=="||n==="!="?e.isVector(a)?u=a:e.isVector(u)?a=u:a!==u&&(a=u="float"):n===">>"||n==="<<"?(a=o,u=e.changeComponentType(u,"uint")):n==="%"?(a=o,u=e.isInteger(a)&&e.isInteger(u)?u:a):e.isMatrix(a)?u==="float"?u="float":e.isVector(u)?u=e.getVectorFromMatrix(a):e.isMatrix(u)||(a=u=o):e.isMatrix(u)?a==="float"?a="float":e.isVector(a)?a=e.getVectorFromMatrix(u):a=u=o:a=u=o):a=u=o;const l=i.build(e,a),c=s?s.build(e,u):null,h=e.getFunctionOperator(n);if(t!=="void"){const d=e.renderer.coordinateSystem===nu;if(n==="=="||n==="!="||n==="<"||n===">"||n==="<="||n===">=")return d?e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${c} )`,o,t):e.format(`( ${l} ${n} ${c} )`,o,t):e.format(`( ${l} ${n} ${c} )`,o,t);if(n==="%")return e.isInteger(u)?e.format(`( ${l} % ${c} )`,o,t):e.format(`${this.getOperatorMethod(e,o)}( ${l}, ${c} )`,o,t);if(n==="!")return d&&e.isVector(a)?e.format(`not( ${l} )`,t):e.format(`( ${n} ${l} )`,a,t);if(n==="~")return e.format(`( ${n} ${l} )`,a,t);if(h)return e.format(`${h}( ${l}, ${c} )`,o,t);if(e.isMatrix(a)&&u==="float")return e.format(`( ${c} ${n} ${l} )`,o,t);if(a==="float"&&e.isMatrix(u))return e.format(`${l} ${n} ${c}`,o,t);{let f=`( ${l} ${n} ${c} )`;return!d&&o==="bool"&&e.isVector(a)&&e.isVector(u)&&(f=`all${f}`),e.format(f,o,t)}}else if(a!=="void")return h?e.format(`${h}( ${l}, ${c} )`,o,t):e.isMatrix(a)&&u==="float"?e.format(`${c} ${n} ${l}`,o,t):e.format(`${l} ${n} ${c}`,o,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const jt=W(Ie,"+").setParameterLength(2,1/0).setName("add"),Et=W(Ie,"-").setParameterLength(2,1/0).setName("sub"),he=W(Ie,"*").setParameterLength(2,1/0).setName("mul"),On=W(Ie,"/").setParameterLength(2,1/0).setName("div"),V_=W(Ie,"%").setParameterLength(2).setName("mod"),xR=W(Ie,"==").setParameterLength(2).setName("equal"),vR=W(Ie,"!=").setParameterLength(2).setName("notEqual"),TR=W(Ie,"<").setParameterLength(2).setName("lessThan"),SR=W(Ie,">").setParameterLength(2).setName("greaterThan"),wR=W(Ie,"<=").setParameterLength(2).setName("lessThanEqual"),RR=W(Ie,">=").setParameterLength(2).setName("greaterThanEqual"),AR=W(Ie,"&&").setParameterLength(2,1/0).setName("and"),NR=W(Ie,"||").setParameterLength(2,1/0).setName("or"),ER=W(Ie,"!").setParameterLength(1).setName("not"),CR=W(Ie,"^^").setParameterLength(2).setName("xor"),MR=W(Ie,"&").setParameterLength(2).setName("bitAnd"),PR=W(Ie,"~").setParameterLength(1).setName("bitNot"),BR=W(Ie,"|").setParameterLength(2).setName("bitOr"),FR=W(Ie,"^").setParameterLength(2).setName("bitXor"),DR=W(Ie,"<<").setParameterLength(2).setName("shiftLeft"),LR=W(Ie,">>").setParameterLength(2).setName("shiftRight"),OR=P(([r])=>(r.addAssign(1),r)),UR=P(([r])=>(r.subAssign(1),r)),IR=P(([r])=>{const e=Ae(r).toConst();return r.addAssign(1),e}),kR=P(([r])=>{const e=Ae(r).toConst();return r.subAssign(1),e});E("add",jt);E("sub",Et);E("mul",he);E("div",On);E("mod",V_);E("equal",xR);E("notEqual",vR);E("lessThan",TR);E("greaterThan",SR);E("lessThanEqual",wR);E("greaterThanEqual",RR);E("and",AR);E("or",NR);E("not",ER);E("xor",CR);E("bitAnd",MR);E("bitNot",PR);E("bitOr",BR);E("bitXor",FR);E("shiftLeft",DR);E("shiftRight",LR);E("incrementBefore",OR);E("decrementBefore",UR);E("increment",IR);E("decrement",kR);class A extends ut{static get type(){return"MathNode"}constructor(e,t,n=null,i=null){if(super(),(e===A.MAX||e===A.MIN)&&arguments.length>3){let s=new A(e,t,n);for(let o=3;o<arguments.length-1;o++)s=new A(e,s,arguments[o]);t=s,n=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=n,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,s=e.isMatrix(t)?0:e.getTypeLength(t),o=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(i)?0:e.getTypeLength(i);return s>o&&s>a?t:o>a?n:a>s?i:t}generateNodeType(e){const t=this.method;return t===A.LENGTH||t===A.DISTANCE||t===A.DOT||t===A.DETERMINANT?"float":t===A.CROSS?"vec3":t===A.ALL||t===A.ANY?"bool":t===A.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:n,method:i}=this;let s=null;if(i===A.ONE_MINUS)s=Et(1,t);else if(i===A.RECIPROCAL)s=On(1,t);else if(i===A.DIFFERENCE)s=Ct(Et(t,n));else if(i===A.TRANSFORM_DIRECTION){let o,a;e.isMatrix(t.getNodeType(e))?(o=t,a=n):(o=n,a=t),s=tn(he(o,q(D(a),0)).xyz)}return s!==null?s:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let i=this.method;const s=this.getNodeType(e),o=this.getInputType(e),a=this.aNode,u=this.bNode,l=this.cNode,c=e.renderer.coordinateSystem;if(i===A.NEGATE)return e.format("( - "+a.build(e,o)+" )",s,t);{const h=[];return i===A.CROSS?h.push(a.build(e,s),u.build(e,s)):c===nu&&i===A.STEP?h.push(a.build(e,e.getTypeLength(a.getNodeType(e))===1?"float":o),u.build(e,o)):c===nu&&(i===A.MIN||i===A.MAX)?h.push(a.build(e,o),u.build(e,e.getTypeLength(u.getNodeType(e))===1?e.getComponentType(o):o)):i===A.REFRACT?h.push(a.build(e,o),u.build(e,o),l.build(e,"float")):i===A.MIX?h.push(a.build(e,o),u.build(e,o),l.build(e,e.getTypeLength(l.getNodeType(e))===1?"float":o)):(c===bo&&i===A.ATAN&&u!==null&&(i="atan2"),e.shaderStage!=="fragment"&&(i===A.DFDX||i===A.DFDY)&&(V(`TSL: '${i}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),i="/*"+i+"*/"),h.push(a.build(e,o)),u!==null&&h.push(u.build(e,o)),l!==null&&h.push(l.build(e,o))),e.format(`${e.getMethod(i,s)}( ${h.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}A.ALL="all";A.ANY="any";A.RADIANS="radians";A.DEGREES="degrees";A.EXP="exp";A.EXP2="exp2";A.LOG="log";A.LOG2="log2";A.SQRT="sqrt";A.INVERSE_SQRT="inversesqrt";A.FLOOR="floor";A.CEIL="ceil";A.NORMALIZE="normalize";A.FRACT="fract";A.SIN="sin";A.SINH="sinh";A.COS="cos";A.COSH="cosh";A.TAN="tan";A.TANH="tanh";A.ASIN="asin";A.ASINH="asinh";A.ACOS="acos";A.ACOSH="acosh";A.ATAN="atan";A.ATANH="atanh";A.ABS="abs";A.SIGN="sign";A.LENGTH="length";A.NEGATE="negate";A.ONE_MINUS="oneMinus";A.DFDX="dFdx";A.DFDY="dFdy";A.ROUND="round";A.RECIPROCAL="reciprocal";A.TRUNC="trunc";A.FWIDTH="fwidth";A.TRANSPOSE="transpose";A.DETERMINANT="determinant";A.INVERSE="inverse";A.EQUALS="equals";A.MIN="min";A.MAX="max";A.STEP="step";A.REFLECT="reflect";A.DISTANCE="distance";A.DIFFERENCE="difference";A.DOT="dot";A.CROSS="cross";A.POW="pow";A.TRANSFORM_DIRECTION="transformDirection";A.MIX="mix";A.CLAMP="clamp";A.REFRACT="refract";A.SMOOTHSTEP="smoothstep";A.FACEFORWARD="faceforward";const $_=N(1e-6),GR=N(Math.PI),VR=W(A,A.ALL).setParameterLength(1),$R=W(A,A.ANY).setParameterLength(1),zR=W(A,A.RADIANS).setParameterLength(1),WR=W(A,A.DEGREES).setParameterLength(1),wd=W(A,A.EXP).setParameterLength(1),To=W(A,A.EXP2).setParameterLength(1),Rd=W(A,A.LOG).setParameterLength(1),cr=W(A,A.LOG2).setParameterLength(1),hr=W(A,A.SQRT).setParameterLength(1),HR=W(A,A.INVERSE_SQRT).setParameterLength(1),di=W(A,A.FLOOR).setParameterLength(1),Ad=W(A,A.CEIL).setParameterLength(1),tn=W(A,A.NORMALIZE).setParameterLength(1),fr=W(A,A.FRACT).setParameterLength(1),Tt=W(A,A.SIN).setParameterLength(1),jR=W(A,A.SINH).setParameterLength(1),dn=W(A,A.COS).setParameterLength(1),qR=W(A,A.COSH).setParameterLength(1),XR=W(A,A.TAN).setParameterLength(1),KR=W(A,A.TANH).setParameterLength(1),YR=W(A,A.ASIN).setParameterLength(1),QR=W(A,A.ASINH).setParameterLength(1),z_=W(A,A.ACOS).setParameterLength(1),ZR=W(A,A.ACOSH).setParameterLength(1),JR=W(A,A.ATAN).setParameterLength(1,2),eA=W(A,A.ATANH).setParameterLength(1),Ct=W(A,A.ABS).setParameterLength(1),W_=W(A,A.SIGN).setParameterLength(1),dr=W(A,A.LENGTH).setParameterLength(1),tA=W(A,A.NEGATE).setParameterLength(1),nA=W(A,A.ONE_MINUS).setParameterLength(1),H_=W(A,A.DFDX).setParameterLength(1),j_=W(A,A.DFDY).setParameterLength(1),rA=W(A,A.ROUND).setParameterLength(1),iA=W(A,A.RECIPROCAL).setParameterLength(1),sA=W(A,A.TRUNC).setParameterLength(1),q_=W(A,A.FWIDTH).setParameterLength(1),oA=W(A,A.TRANSPOSE).setParameterLength(1),aA=W(A,A.DETERMINANT).setParameterLength(1),uA=W(A,A.INVERSE).setParameterLength(1),_i=W(A,A.MIN).setParameterLength(2,1/0),ot=W(A,A.MAX).setParameterLength(2,1/0),So=W(A,A.STEP).setParameterLength(2),lA=W(A,A.REFLECT).setParameterLength(2),cA=W(A,A.DISTANCE).setParameterLength(2),hA=W(A,A.DIFFERENCE).setParameterLength(2),yi=W(A,A.DOT).setParameterLength(2),Vr=W(A,A.CROSS).setParameterLength(2),qu=W(A,A.POW).setParameterLength(2),X_=r=>he(r,r),dA=r=>he(r,r,r),Nd=r=>he(r,r,r,r),fA=W(A,A.TRANSFORM_DIRECTION).setParameterLength(2),pA=(r,e)=>tn(he(e,q(D(r),0)).xyz),gA=(r,e)=>tn(q(D(r),0).mul(e).xyz),mA=r=>he(W_(r),qu(Ct(r),1/3)),_A=r=>yi(r,r),Se=W(A,A.MIX).setParameterLength(3),$r=(r,e=0,t=1)=>new A(A.CLAMP,K(r),K(e),K(t)),Ed=r=>$r(r),K_=W(A,A.REFRACT).setParameterLength(3),Un=W(A,A.SMOOTHSTEP).setParameterLength(3),yA=W(A,A.FACEFORWARD).setParameterLength(3),bA=P(([r])=>{const n=43758.5453,i=yi(r.xy,re(12.9898,78.233)),s=V_(i,GR);return fr(Tt(s).mul(n))}),xA=(r,e,t)=>Se(e,t,r),vA=(r,e,t)=>Un(e,t,r),TA=(r,e)=>So(e,r);E("all",VR);E("any",$R);E("radians",zR);E("degrees",WR);E("exp",wd);E("exp2",To);E("log",Rd);E("log2",cr);E("sqrt",hr);E("inverseSqrt",HR);E("floor",di);E("ceil",Ad);E("normalize",tn);E("fract",fr);E("sin",Tt);E("sinh",jR);E("cos",dn);E("cosh",qR);E("tan",XR);E("tanh",KR);E("asin",YR);E("asinh",QR);E("acos",z_);E("acosh",ZR);E("atan",JR);E("atanh",eA);E("abs",Ct);E("sign",W_);E("length",dr);E("lengthSq",_A);E("negate",tA);E("oneMinus",nA);E("dFdx",H_);E("dFdy",j_);E("round",rA);E("reciprocal",iA);E("trunc",sA);E("fwidth",q_);E("min",_i);E("max",ot);E("step",TA);E("reflect",lA);E("distance",cA);E("dot",yi);E("cross",Vr);E("pow",qu);E("pow2",X_);E("pow3",dA);E("pow4",Nd);E("transformDirection",fA);E("transformNormalByViewMatrix",pA);E("transformNormalByInverseViewMatrix",gA);E("mix",xA);E("clamp",$r);E("refract",K_);E("smoothstep",vA);E("faceForward",yA);E("difference",hA);E("saturate",Ed);E("cbrt",mA);E("transpose",oA);E("determinant",aA);E("inverse",uA);E("rand",bA);class SA extends te{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}generateNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(t===void 0)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(n!==null){const s=n.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(i))return s}return i}setup(e){const t=this.condNode,n=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,s=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=s,i!==null&&(e.getDataFromNode(i).parentNodeBlock=s);const o=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=o?n:n.context({nodeBlock:n}),a.elseNode=i?o?i:i.context({nodeBlock:i}):null}generate(e,t){const n=this.getNodeType(e),i=e.getDataFromNode(this);if(i.nodeProperty!==void 0)return i.nodeProperty;const{condNode:s,ifNode:o,elseNode:a}=e.getNodeProperties(this),u=e.currentFunctionNode,l=t!=="void",c=l?Wr(n).build(e):"";i.nodeProperty=c;const h=s.build(e,"bool");if(e.context.uniformFlow&&a!==null){const p=o.build(e,n),g=a.build(e,n),_=e.getTernary(h,p,g);return e.format(_,n,t)}e.addFlowCode(`
515
+ ${e.tab}if ( ${h} ) {
516
+
517
+ `).addFlowTab();let f=o.build(e,n);if(f&&(l?f=c+" = "+f+";":(f="return "+f+";",u===null&&(Y("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),f="// "+f))),e.removeFlowTab().addFlowCode(e.tab+" "+f+`
518
+
519
+ `+e.tab+"}"),a!==null){e.addFlowCode(` else {
520
+
521
+ `).addFlowTab();let p=a.build(e,n);p&&(l?p=c+" = "+p+";":(p="return "+p+";",u===null&&(Y("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),p="// "+p))),e.removeFlowTab().addFlowCode(e.tab+" "+p+`
522
+
523
+ `+e.tab+`}
524
+
525
+ `)}else e.addFlowCode(`
526
+
527
+ `);return e.format(c,n,t)}}const Zt=ke(SA).setParameterLength(2,3);E("select",Zt);class Cd extends te{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{t.isContextNode===!0&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){if(e.increaseUsage(this)===1){const n=e.addContext(this.value);this.node.build(e,this),e.setContext(n)}}setup(e){const t=e.addContext(this.value),n=this.node.build(e);return e.setContext(t),n}generate(e,t){const n=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(n),i}}const pr=(r=null,e={})=>{let t=r;return(t===null||t.isNode!==!0)&&(e=t||e,t=null),new Cd(t,e)},wA=r=>pr(r,{uniformFlow:!0}),Y_=(r,e)=>pr(r,{nodeName:e});function RA(r,e,t=null){return pr(t,{getShadow:({light:n,shadowColorNode:i})=>e===n?i.mul(r):i})}function AA(r,e=null){return pr(e,{getAO:(t,{material:n})=>n.transparent===!0?t:t!==null?t.mul(r):r})}function NA(r,e,t=null){const n=r.max(.001);return pr(t,{getAO:(i,{material:s})=>s.transparent===!0?i:i!==null?i.mul(n):n,getGI:(i,{material:s})=>{if(s.transparent===!0)return i;const o=e.div(n);return i!==null?i.add(o):o}})}function EA(r,e){return Y('TSL: "label()" has been deprecated. Use "setName()" instead.'),Y_(r,e)}E("context",pr);E("label",EA);E("uniformFlow",wA);E("setName",Y_);E("builtinShadowContext",(r,e,t)=>RA(e,t,r));E("builtinAOContext",(r,e)=>AA(e,r));E("builtinGIContext",(r,e,t)=>NA(e,t,r));class Ka extends te{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return e.getDataFromNode(this).forceDeclaration===!0?!1:this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0],n=this.getShared(t);if(this!==n)return n.build(...e);if(this._hasStack(t)===!1&&t.buildStage==="setup"&&(t.context.nodeLoop||t.context.nodeBlock)){let i=!1;if(this.node.isShaderCallNodeInternal&&this.node.shaderNode.getLayout()===null&&t.fnCall&&t.fnCall.shaderNode&&t.getDataFromNode(this.node.shaderNode).hasLoop){const a=t.getDataFromNode(this);a.forceDeclaration=!0,i=!0}const s=t.getBaseStack();i?s.addToStackBefore(this):s.addToStack(this)}return this.isIntent(t)&&this.isAssign(t)!==!0?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:n,readOnly:i}=this,{renderer:s}=e,o=s.backend.isWebGPUBackend===!0;let a=!1,u=!1;i&&(a=e.isDeterministic(t),u=o?i:a);const l=this.getNodeType(e);if(l=="void")return this.isIntent(e)!==!0&&V('TSL: ".toVar()" can not be used with void type.',this.stackTrace),t.build(e);const c=e.getVectorType(l),h=t.build(e,c),d=e.getVarFromNode(this,n,c,void 0,u),f=e.getPropertyName(d);let p=f;if(u)if(o)p=a?`const ${f}`:`let ${f}`;else{const g=t.getArrayCount(e);p=`const ${e.getVar(d.type,f,g)}`}return e.addLineFlowCode(`${p} = ${h}`,this),f}_hasStack(e){return e.getDataFromNode(this).stack!==void 0}}const Md=ke(Ka),CA=(r,e=null)=>Md(r,e).toStack(),MA=(r,e=null)=>Md(r,e,!0).toStack(),PA=r=>Md(r).setIntent(!0).toStack();E("toVar",CA);E("toConst",MA);E("toVarIntent",PA);class BA extends te{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(e){if(this.nodeType!==null)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const n=this.node.build(e,...t);return e.removeSubBuild(),n}}const ts=(r,e,t=null)=>new BA(K(r),e,t);class FA extends te{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=ts(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}generateNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(n===void 0){const i=this.name,s=this.getNodeType(e),o=this.interpolationType,a=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,i,s,o,a),t.node=ts(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation=e.shaderStage==="fragment"),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Bs.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Bs.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),i=this.setupVarying(e);if(n[t]===void 0){const s=this.getNodeType(e),o=e.getPropertyName(i,Bs.VERTEX);if(e.shaderStage===Bs.VERTEX){const a=n.node.build(e,s);e.addLineFlowCode(`${o} = ${a}`,this)}else e.flowNodeFromShaderStage(Bs.VERTEX,n.node,s,o);n[t]=o}return e.getPropertyName(i)}}const Ai=ke(FA).setParameterLength(1,2),DA=r=>Ai(r);E("toVarying",Ai);E("toVertexStage",DA);const LA=P(([r])=>{const e=r.mul(.9478672986).add(.0521327014).pow(2.4),t=r.mul(.0773993808),n=r.lessThanEqual(.04045);return Se(e,t,n)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),OA=P(([r])=>{const e=r.pow(.41666).mul(1.055).sub(.055),t=r.mul(12.92),n=r.lessThanEqual(.0031308);return Se(e,t,n)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Pd="WorkingColorSpace",UA="OutputColorSpace";class Q_ extends ut{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===Pd?Ye.workingColorSpace:t===UA?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let s=t;return Ye.enabled===!1||n===i||!n||!i||(Ye.getTransfer(n)===le&&(s=q(LA(s.rgb),s.a)),Ye.getPrimaries(n)!==Ye.getPrimaries(i)&&(s=q(nt(Ye._getMatrix(new gs,n,i)).mul(s.rgb),s.a)),Ye.getTransfer(i)===le&&(s=q(OA(s.rgb),s.a))),s}}const IA=(r,e)=>new Q_(K(r),Pd,e),Bd=(r,e)=>new Q_(K(r),e,Pd);E("workingToColorSpace",IA);E("colorSpaceToWorking",Bd);class Z_ extends Lo{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(e),i=this.getNodeType(e);return e.format(t,n,i)}}class J_ extends te{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=ie.OBJECT}setGroup(e){return this.group=e,this}element(e){return new Z_(this,K(e))}setNodeType(e){const t=ne(null,e);this.group!==null&&t.setGroup(this.group),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let i=1;i<t.length;i++)n=n[t[i]];return n}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const kA=(r,e,t)=>new J_(r,e,t);class GA extends J_{static get type(){return"RendererReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(Q)}updateReference(e){return this.reference=this.renderer!==null?this.renderer:e.renderer,this.reference}}const VA=(r,e,t=null)=>new GA(r,e,t);class $A extends ut{static get type(){return"ToneMappingNode"}constructor(e,t=WA,n=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return oo(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,n=this._toneMapping;if(n===Ki)return t;let i=null;const s=e.renderer.library.getToneMappingFunction(n);return s!==null?i=q(s(t.rgb,this.exposureNode),t.a):(V("ToneMappingNode: Unsupported Tone Mapping configuration.",n),i=t),i}}const zA=(r,e,t)=>new $A(r,K(e),K(t)),WA=VA("toneMappingExposure","float");E("toneMapping",(r,e,t)=>zA(e,t,r));const hp=new WeakMap;function dp(r,e){let t=hp.get(r);return t===void 0&&(t=new kv(r,e),hp.set(r,t)),t}class yr extends md{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=ad,this.instanced=!1,this.attribute=null,this.global=!0,e&&e.isBufferAttribute===!0&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){let t;if(this.bufferStride===0&&this.bufferOffset===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}generateNodeType(e){return this.bufferType===null&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(this.attribute!==null)return;const t=this.getNodeType(e),n=e.getTypeLength(t),i=this.value,s=this.bufferStride||n,o=this.bufferOffset;let a;i.isInterleavedBuffer===!0?a=i:i.isBufferAttribute===!0?a=dp(i.array,s):a=dp(i,s);const u=new Iv(a,n,o);a.setUsage(this.usage),this.attribute=u,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.context.nodeName;n!==void 0&&delete e.context.nodeName;const i=e.getBufferAttributeFromNode(this,t,n),s=e.getPropertyName(i);let o=null;if(e.shaderStage==="vertex"||e.shaderStage==="compute")this.name=s,o=s;else{let a;n&&(a=n+"Varying"),o=Ai(this,a).build(e,t)}return o}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&this.attribute.isBufferAttribute===!0&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function Fd(r,e=null,t=0,n=0,i=ad,s=!1){return e==="mat3"||e===null&&r.itemSize===9?nt(new yr(r,"vec3",9,0).setUsage(i).setInstanced(s),new yr(r,"vec3",9,3).setUsage(i).setInstanced(s),new yr(r,"vec3",9,6).setUsage(i).setInstanced(s)):e==="mat4"||e===null&&r.itemSize===16?Gr(new yr(r,"vec4",16,0).setUsage(i).setInstanced(s),new yr(r,"vec4",16,4).setUsage(i).setInstanced(s),new yr(r,"vec4",16,8).setUsage(i).setInstanced(s),new yr(r,"vec4",16,12).setUsage(i).setInstanced(s)):new yr(r,e,t,n).setUsage(i)}const ey=(r,e=null,t=0,n=0)=>Fd(r,e,t,n),ty=(r,e=null,t=0,n=0)=>Fd(r,e,t,n,ad,!0),ny=(r,e=null,t=0,n=0)=>Fd(r,e,t,n,rs,!0);E("toAttribute",r=>ey(r.value,r.bufferType));class De extends te{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let i;if(n===De.VERTEX)i=e.getVertexIndex();else if(n===De.INSTANCE)i=e.getInstanceIndex();else if(n===De.DRAW)i=e.getDrawIndex();else if(n===De.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(n===De.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else if(n===De.SUBGROUP)i=e.getSubgroupIndex();else throw new Error("THREE.IndexNode: Unknown scope: "+n);let s;return e.shaderStage==="vertex"||e.shaderStage==="compute"?s=i:s=Ai(this).build(e,t),s}}De.VERTEX="vertex";De.INSTANCE="instance";De.SUBGROUP="subgroup";De.INVOCATION_LOCAL="invocationLocal";De.INVOCATION_SUBGROUP="invocationSubgroup";De.DRAW="draw";const xh=$(De,De.VERTEX),ls=$(De,De.INSTANCE);De.SUBGROUP;De.INVOCATION_SUBGROUP;De.INVOCATION_LOCAL;const HA=$(De,De.DRAW);class jA extends te{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.onInitFunction=null,this.countNode=null,this.updateBeforeType=ie.FRAME}setName(e){return this.name=e,this}label(e){return Y('TSL: "label()" has been deprecated. Use "setName()" instead.',new Ft),this.setName(e)}onInit(e){return this.onInitFunction=e,this}getUpdateBeforeType(e){return e.compute!==this?this.updateBeforeType:ie.NONE}updateBefore({renderer:e}){e.compute(this)}setup(e){this.count!==null&&this.countNode===null&&(this.countNode=ne(this.count,"uint").onObjectUpdate(()=>this.count));const t=this.computeNode.build(e);if(t){const n=e.getNodeProperties(this);n.outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:n}=e;if(n==="compute"){const i=this.computeNode.build(e,"void");if(i!==""&&e.addLineFlowCode(i,this),this.count!==null&&e.allowEarlyReturns===!0){const s=this.countNode.build(e,"uint"),o=ls.build(e,"uint");e.flow.code=`${e.tab}if ( ${o} >= ${s} ) { return; }
528
+
529
+ ${e.flow.code}`}}else{const s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}}const ry=(r,e=[64])=>{(e.length===0||e.length>3)&&V("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Ft);for(let t=0;t<e.length;t++){const n=e[t];(typeof n!="number"||n<=0||!Number.isInteger(n))&&V(`TSL: compute() workgroupSize element at index [ ${t} ] must be a positive integer`,new Ft)}for(;e.length<3;)e.push(1);return new jA(K(r),e)},qA=(r,e,t)=>{const n=ry(r,t);return typeof e=="number"?n.count=e:n.dispatchSize=e,n};E("compute",qA);E("computeKernel",ry);class XA extends te{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const n=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const s=this.node.build(e,...t);return e.setCache(n),s}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const qi=r=>new XA(K(r));function KA(r,e=!0){return Y('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),qi(r).setParent(e)}E("cache",KA);E("isolate",qi);class YA extends te{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return t!==""&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const QA=ke(YA).setParameterLength(2);E("bypass",QA);const iy=P(([r,e,t,n=N(0),i=N(1),s=Oo(!1)])=>{let o=r.sub(e).div(t.sub(e));return dh(s)&&(o=o.clamp()),o.mul(i.sub(n)).add(n)});function ZA(r,e,t,n=N(0),i=N(1)){return iy(r,e,t,n,i,!0)}E("remap",iy);E("remapClamp",ZA);class Ya extends te{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),i=this.snippet;if(n==="void")e.addLineFlowCode(i,this);else return e.format(i,n,t)}}const Fr=ke(Ya).setParameterLength(1,2),JA=r=>(r?Zt(r,Fr("discard")):Fr("discard")).toStack();E("discard",JA);const sy=P(([r])=>q(r.rgb.mul(r.a),r.a),{color:"vec4",return:"vec4"}),eN=P(([r])=>r.a.equal(0).select(q(0),q(r.rgb.div(r.a),r.a)),{color:"vec4",return:"vec4"});class tN extends ut{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;t=q(t.rgb,t.a.clamp(0,1)),t=eN(t);const n=(this._toneMapping!==null?this._toneMapping:e.toneMapping)||Ki,i=(this.outputColorSpace!==null?this.outputColorSpace:e.outputColorSpace)||os;return n!==Ki&&(t=t.toneMapping(n)),i!==os&&i!==Ye.workingColorSpace&&(t=t.workingToColorSpace(i)),t=sy(t),t}}const oy=(r,e=null,t=null)=>new tN(K(r),e,t);E("renderOutput",oy);class nN extends ut{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,n=this.node.build(e);if(t!==null)t(e,n);else{const i="--- TSL debug - "+e.shaderStage+" shader ---",s="-".repeat(i.length);let o="";o+="// #"+i+`#
530
+ `,o+=e.flow.code.replace(/^\t/mg,"")+`
531
+ `,o+="/* ... */ "+n+` /* ... */
532
+ `,o+="// #"+s+`#
533
+ `,Wv(o)}return n}}const rN=(r,e=null)=>new nN(K(r),e).toStack();E("debug",rN);class ay extends Lu{constructor(){super(),this._renderer=null,this.currentFrame=null,this.isRunning=!1,this.enabled=!0}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}begin(){this.isRunning=!0}finish(){this.isRunning=!1}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}dispose(){this.isRunning===!0&&this.finish(),this.dispatchEvent({type:"dispose"})}}class iN extends te{static get type(){return"InspectorNode"}constructor(e,t="",n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=ie.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return e.context.inspector===!0&&this.callback!==null&&(t=this.callback(t)),e.renderer.backend.isWebGPUBackend!==!0&&e.renderer.inspector.constructor!==ay&&Fe('TSL: ".toInspector()" is only available with WebGPU.'),t}}function sN(r,e="",t=null){return r=K(r),r.before(new iN(r,e,t))}E("toInspector",sN);class uy extends te{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(e){let t=this.nodeType;if(t===null){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const i=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(e.hasGeometryAttribute(t)===!0){const s=e.geometry.getAttribute(t),o=e.getTypeFromAttribute(s),a=e.getAttribute(t,o);return e.shaderStage==="vertex"?e.format(a.name,o,n):Ai(this).build(e,n)}else return Y(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Jt=(r,e=null)=>new uy(r,e),Io=(r=0)=>Jt("uv"+(r>0?r:""),"vec2");class oN extends te{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e){const t=this.textureNode.build(e,"property"),n=this.levelNode===null?"0":this.levelNode.build(e,"int"),i=e.generateTextureSize(this.textureNode.value,t,n);return e.format(i,this.getNodeType(e))}}const cs=ke(oN).setParameterLength(1,2);class aN extends Uo{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=ie.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&n.width!==void 0){const{width:i,height:s}=n;this.value=Math.log2(Math.max(i,s))}}}const uN=ke(aN).setParameterLength(1);class lN extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const ly=new od;class Xu extends Uo{static get type(){return"TextureNode"}constructor(e=ly,t=null,n=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.gatherNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=ie.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this._samplerComparison=!1,this.setUpdateMatrix(t===null)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return this.gatherNode!==null?"vec4":C_(this.value)}getInputType(){return"texture"}getDefaultUV(){return Io(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=ne(this.value.matrix)),this._matrixUniform.mul(D(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(this._flipYUniform===null&&(this._flipYUniform=ne(!1)),t=t.toVar(),this.sampler?t=this._flipYUniform.select(t.flipY(),t):t=this._flipYUniform.select(t.setY(Ae(cs(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const n=this.value;if(!n||n.isTexture!==!0)throw new lN("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=P(()=>{let u=this.uvNode;return(u===null||e.context.forceUVContext===!0)&&e.context.getUV&&(u=e.context.getUV(this,e)),u||(u=this.getDefaultUV()),this.updateMatrix===!0&&(u=this.getTransformedUV(u)),u=this.setupUV(e,u),this.updateType=this._matrixUniform!==null||this._flipYUniform!==null?ie.OBJECT:ie.NONE,u})();let s=this.levelNode;s===null&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this));let o=null,a=null;if(this.compareNode!==null)if(e.renderer.hasCompatibility(Si.TEXTURE_COMPARE))o=this.compareNode;else{const u=n.compareFunction;u===null||u===id||u===Fo||u===su||u===ss?a=this.compareNode:(o=this.compareNode,Fe('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=s,t.biasNode=this.biasNode,t.compareNode=o,t.compareStepNode=a,t.gradNode=this.gradNode,t.gatherNode=this.gatherNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,this.sampler===!0?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,n,i,s,o,a,u,l,c,h){const d=this.value;let f;return s?f=e.generateTextureBias(d,t,n,s,o,c):u?f=e.generateTextureGrad(d,t,n,u,o,c):l?a?f=e.generateTextureGatherCompare(d,t,n,a,o,c,h):f=e.generateTextureGather(d,t,n,l,o,c,h):a?f=e.generateTextureCompare(d,t,n,a,o,c):this.sampler===!1?f=e.generateTextureLoad(d,t,n,i,o,c):i?f=e.generateTextureLevel(d,t,n,i,o,c):f=e.generateTexture(d,t,n,o,c),f}generate(e,t){const n=this.value,i=e.getNodeProperties(this),s=super.generate(e,"property");if(/^sampler/.test(t)){if(t==="samplerComparison"){this._samplerComparison=!0;const o=this.getSharedNode(e);o._samplerComparison=!0}return s+"_sampler"}else{if(e.isReference(t))return s;{const o=e.getDataFromNode(this),a=this.getNodeType(e);let u=o.propertyName;if(u===void 0){const{uvNode:c,levelNode:h,biasNode:d,compareNode:f,compareStepNode:p,depthNode:g,gradNode:_,gatherNode:m,offsetNode:y}=i,b=this.generateUV(e,c),T=h?h.build(e,"float"):null,x=d?d.build(e,"float"):null,v=g?g.build(e,"int"):null,w=f?f.build(e,"float"):null,R=p?p.build(e,"float"):null,F=_?[_[0].build(e,"vec2"),_[1].build(e,"vec2")]:null,M=m?m.build(e,"int"):null,O=y?this.generateOffset(e,y):null,U=this._flipYUniform?this._flipYUniform.build(e,"bool"):null;let X=v;X===null&&n.isArrayTexture&&this.isTexture3DNode!==!0&&(X="0");const oe=e.getVarFromNode(this);u=e.getPropertyName(oe);let H=this.generateSnippet(e,s,b,T,x,X,w,F,M,O,U),ue;if(n.isDepthTexture===!0&&M===null?ue="float":ue=n.type===qe?"uvec4":n.type===gt?"ivec4":"vec4",H=e.format(H,ue,a),R!==null){const L=n.compareFunction;L===su||L===ss?H=So(Fr(H,a),Fr(R,"float")).build(e,a):H=So(Fr(R,"float"),Fr(H,a)).build(e,a)}e.addLineFlowCode(`${u} = ${H}`,this),o.snippet=H,o.propertyName=u}let l=u;return e.needsToWorkingColorSpace(n)&&(l=Bd(Fr(l,a),n.colorSpace).setup(e).build(e,a)),e.format(l,a,t)}}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=K(e),t.referenceNode=this.getBase(),K(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=K(e).mul(uN(t)),t.referenceNode=this.getBase();const n=t.value;return t.generateMipmaps===!1&&(n&&n.generateMipmaps===!1||n.minFilter===zt||n.magFilter===zt)&&(Y("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),K(t)}level(e){const t=this.clone();return t.levelNode=K(e),t.referenceNode=this.getBase(),K(t)}size(e){return cs(this,e)}bias(e){const t=this.clone();return t.biasNode=K(e),t.referenceNode=this.getBase(),K(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=K(e),t.referenceNode=this.getBase(),K(t)}grad(e,t){const n=this.clone();return n.gradNode=[K(e),K(t)],n.referenceNode=this.getBase(),K(n)}gather(e=0){const t=this.clone();return t.gatherNode=K(e),t.referenceNode=this.getBase(),K(t)}isSampleCompare(){return this.compareNode!==null||this._samplerComparison===!0}depth(e){const t=this.clone();return t.depthNode=K(e),t.referenceNode=this.getBase(),K(t)}offset(e){const t=this.clone();return t.offsetNode=K(e),t.referenceNode=this.getBase(),K(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;t!==null&&(t.value=e.matrix),e.matrixAutoUpdate===!0&&e.updateMatrix();const n=this._flipYUniform;n!==null&&(n.value=e.image instanceof ImageBitmap&&e.flipY===!0||e.isRenderTargetTexture===!0||e.isFramebufferTexture===!0||e.isDepthTexture===!0)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}}const cN=ke(Xu).setParameterLength(1,4).setName("texture"),ve=(r=ly,e=null,t=null,n=null)=>{let i;return r&&r.isTextureNode===!0?(i=K(r.clone()),i.referenceNode=r.getBase(),e!==null&&(i.uvNode=K(e)),t!==null&&(i.levelNode=K(t)),n!==null&&(i.biasNode=K(n))):i=cN(r,e,t,n),i},fn=(...r)=>ve(...r).setSampler(!1);class Dd extends Uo{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Ld=(r,e,t)=>new Dd(r,e,t);class hN extends Lo{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(e),i=this.node.getPaddedType();return e.format(t,i,n)}}class dN extends Dd{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?_u(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=ie.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return e==="mat2"?t="mat2":/mat/.test(e)===!0?t="mat4":e.charAt(0)==="i"?t="ivec4":e.charAt(0)==="u"&&(t="uvec4"),t}update(){this.updateBuffer()}onUpdate(e,t){return e=e.bind(this),super.onUpdate((n,i)=>{e(n,i),this.updateBuffer()},t)}updateBuffer(){const{array:e,value:t}=this,n=this.elementType;if(n==="float"||n==="int"||n==="uint")for(let i=0;i<e.length;i++){const s=i*4;t[s]=e[i]}else if(n==="color")for(let i=0;i<e.length;i++){const s=i*4,o=e[i];t[s]=o.r,t[s+1]=o.g,t[s+2]=o.b||0}else if(n==="mat2")for(let i=0;i<e.length;i++){const s=i*4,o=e[i];t[s]=o.elements[0],t[s+1]=o.elements[1],t[s+2]=o.elements[2],t[s+3]=o.elements[3]}else if(n==="mat3")for(let i=0;i<e.length;i++){const s=i*16,o=e[i];t[s]=o.elements[0],t[s+1]=o.elements[1],t[s+2]=o.elements[2],t[s+4]=o.elements[3],t[s+5]=o.elements[4],t[s+6]=o.elements[5],t[s+8]=o.elements[6],t[s+9]=o.elements[7],t[s+10]=o.elements[8],t[s+15]=1}else if(n==="mat4")for(let i=0;i<e.length;i++){const s=i*16,o=e[i];for(let a=0;a<o.elements.length;a++)t[s+a]=o.elements[a]}else for(let i=0;i<e.length;i++){const s=i*4,o=e[i];t[s]=o.x,t[s+1]=o.y,t[s+2]=o.z||0,t[s+3]=o.w||0}}setup(e){const t=this.array.length,n=this.elementType;let i=Float32Array;const s=this.paddedType,o=e.getTypeLength(s);return n.charAt(0)==="i"&&(i=Int32Array),n.charAt(0)==="u"&&(i=Uint32Array),this.value=new i(t*o),this.bufferCount=t,this.bufferType=s,this.updateBuffer(),super.setup(e)}element(e){return new hN(this,K(e))}}const _t=(r,e)=>new dN(r,e);class fN extends te{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const gr=ke(fN).setParameterLength(1);let Fs,Ds;class Qe extends te{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}generateNodeType(){return this.scope===Qe.VIEWPORT?"vec4":"vec2"}update({renderer:e}){const t=e.getRenderTarget();this.scope===Qe.VIEWPORT?t!==null?Ds.copy(t.viewport):(e.getViewport(Ds),Ds.multiplyScalar(e.getPixelRatio())):t!==null?(Fs.width=t.width,Fs.height=t.height):e.getDrawingBufferSize(Fs)}setup(){const e=this.scope;let t=null;e===Qe.SIZE?t=ne(Fs||(Fs=new de)).setGroup(Q):e===Qe.VIEWPORT?t=ne(Ds||(Ds=new tt)).setGroup(Q):t=re(ys.div(wo));let n=ie.NONE;return(this.scope===Qe.SIZE||this.scope===Qe.VIEWPORT)&&(n=ie.RENDER),this.updateType=n,t}generate(e){if(this.scope===Qe.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(wo).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}Qe.COORDINATE="coordinate";Qe.VIEWPORT="viewport";Qe.SIZE="size";Qe.UV="uv";const cy=ne(1).setGroup(Q).onRenderUpdate(({renderer:r})=>r.getPixelRatio()),Or=$(Qe,Qe.UV),wo=$(Qe,Qe.SIZE),ys=$(Qe,Qe.COORDINATE),co=$(Qe,Qe.VIEWPORT),pN=co.zw;co.xy;let Ml=null,ea=null,Pl=null,ta=null,Bl=null,na=null,Fl=null,ra=null,Dl=null,ia=null,Ll=null,sa=null;const Hr=ne(0,"uint").setName("u_cameraIndex").setGroup(Sd("cameraIndex")).toVarying("v_cameraIndex"),oi=ne("float").setName("cameraNear").setGroup(Q).onRenderUpdate(({camera:r})=>r.near),ai=ne("float").setName("cameraFar").setGroup(Q).onRenderUpdate(({camera:r})=>r.far),mn=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const n of r.cameras)t.push(n.projectionMatrix);ea===null?ea=_t(t).setGroup(Q).setName("cameraProjectionMatrices"):ea.array=t,e=ea.element(r.isMultiViewCamera?gr("gl_ViewID_OVR"):Hr)}else Ml===null&&(Ml=ne(r.projectionMatrix).setName("cameraProjectionMatrix").setGroup(Q).onRenderUpdate(({camera:t})=>t.projectionMatrix)),e=Ml;return e}).once()(),gN=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const n of r.cameras)t.push(n.projectionMatrixInverse);ta===null?ta=_t(t).setGroup(Q).setName("cameraProjectionMatricesInverse"):ta.array=t,e=ta.element(r.isMultiViewCamera?gr("gl_ViewID_OVR"):Hr)}else Pl===null&&(Pl=ne(r.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(Q).onRenderUpdate(({camera:t})=>t.projectionMatrixInverse)),e=Pl;return e}).once()(),bs=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const n of r.cameras)t.push(n.matrixWorldInverse);na===null?na=_t(t).setGroup(Q).setName("cameraViewMatrices"):na.array=t,e=na.element(r.isMultiViewCamera?gr("gl_ViewID_OVR"):Hr)}else Bl===null&&(Bl=ne(r.matrixWorldInverse).setName("cameraViewMatrix").setGroup(Q).onRenderUpdate(({camera:t})=>t.matrixWorldInverse)),e=Bl;return e}).once()(),Ku=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const n of r.cameras)t.push(n.matrixWorld);ra===null?ra=_t(t).setGroup(Q).setName("cameraWorldMatrices"):ra.array=t,e=ra.element(r.isMultiViewCamera?gr("gl_ViewID_OVR"):Hr)}else Fl===null&&(Fl=ne(r.matrixWorld).setName("cameraWorldMatrix").setGroup(Q).onRenderUpdate(({camera:t})=>t.matrixWorld)),e=Fl;return e}).once()(),mN=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(let n=0,i=r.cameras.length;n<i;n++)t.push(new z);ia===null?ia=_t(t).setGroup(Q).setName("cameraPositions").onRenderUpdate(({camera:n},i)=>{const s=n.cameras,o=i.array;for(let a=0,u=s.length;a<u;a++)o[a].setFromMatrixPosition(s[a].matrixWorld)}):ia.array=t,e=ia.element(r.isMultiViewCamera?gr("gl_ViewID_OVR"):Hr)}else Dl===null&&(Dl=ne(new z).setName("cameraPosition").setGroup(Q).onRenderUpdate(({camera:t},n)=>n.value.setFromMatrixPosition(t.matrixWorld))),e=Dl;return e}).once()(),Ol=P(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const n of r.cameras)t.push(n.viewport);sa===null?sa=_t(t,"vec4").setGroup(Q).setName("cameraViewports"):sa.array=t,e=sa.element(Hr)}else Ll===null&&(Ll=q(0,0,wo.x,wo.y).toConst("cameraViewport")),e=Ll;return e}).once()(),fp=new Gv;class Ee extends te{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ie.OBJECT,this.uniformNode=new Uo(null)}generateNodeType(){const e=this.scope;if(e===Ee.WORLD_MATRIX)return"mat4";if(e===Ee.POSITION||e===Ee.VIEW_POSITION||e===Ee.DIRECTION||e===Ee.SCALE)return"vec3";if(e===Ee.RADIUS)return"float"}update(e){const t=this.object3d,n=this.uniformNode,i=this.scope;if(i===Ee.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===Ee.POSITION)n.value=n.value||new z,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===Ee.SCALE)n.value=n.value||new z,n.value.setFromMatrixScale(t.matrixWorld);else if(i===Ee.DIRECTION)n.value=n.value||new z,t.getWorldDirection(n.value);else if(i===Ee.VIEW_POSITION){const s=e.camera;n.value=n.value||new z,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(s.matrixWorldInverse)}else if(i===Ee.RADIUS){const s=e.object.geometry;s.boundingSphere===null&&s.computeBoundingSphere(),fp.copy(s.boundingSphere).applyMatrix4(t.matrixWorld),n.value=fp.radius}}generate(e){const t=this.scope;return t===Ee.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Ee.POSITION||t===Ee.VIEW_POSITION||t===Ee.DIRECTION||t===Ee.SCALE?this.uniformNode.nodeType="vec3":t===Ee.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Ee.WORLD_MATRIX="worldMatrix";Ee.POSITION="position";Ee.SCALE="scale";Ee.VIEW_POSITION="viewPosition";Ee.DIRECTION="direction";Ee.RADIUS="radius";const pp=new bt;class sn extends Ee{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}sn.DIRECTION;const bi=$(sn,sn.WORLD_MATRIX);sn.POSITION;sn.SCALE;sn.VIEW_POSITION;sn.RADIUS;const _N=ne(new gs).onObjectUpdate(({object:r},e)=>e.value.getNormalMatrix(r.matrixWorld)),xi=P(r=>r.context.modelViewMatrix||yN).once()().toVar("modelViewMatrix"),yN=bs.mul(bi),gp=P(r=>{r.context.isHighPrecisionModelViewMatrix=!0;const e=r.camera;let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(let s=0;s<e.cameras.length;s++)n.push(new bt);t=_t(n).onObjectUpdate(({object:s,camera:o},a)=>{const u=o.cameras,l=a.array;for(let c=0,h=u.length;c<h;c++)l[c].multiplyMatrices(u[c].matrixWorldInverse,s.matrixWorld)}).element(e.isMultiViewCamera?gr("gl_ViewID_OVR"):Hr)}else t=ne("mat4").onObjectUpdate(({object:n,camera:i})=>n.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,n.matrixWorld));return t}).once()().toVar("highpModelViewMatrix"),mp=P(r=>{const e=r.context.isHighPrecisionModelViewMatrix,t=r.camera;let n;if(t.isArrayCamera&&t.cameras.length>0){const i=[];for(let o=0;o<t.cameras.length;o++)i.push(new gs);n=_t(i).onObjectUpdate(({object:o,camera:a},u)=>{const l=a.cameras,c=u.array;for(let h=0,d=l.length;h<d;h++)pp.multiplyMatrices(l[h].matrixWorldInverse,o.matrixWorld),c[h].getNormalMatrix(pp)}).element(t.isMultiViewCamera?gr("gl_ViewID_OVR"):Hr)}else n=ne("mat3").onObjectUpdate(({object:i,camera:s})=>(e!==!0&&i.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,i.matrixWorld),i.normalMatrix.getNormalMatrix(i.modelViewMatrix)));return n}).once()().toVar("highpModelNormalViewMatrix"),bN=P(r=>r.shaderStage!=="fragment"?(Fe("TSL: `clipSpace` is only available in fragment stage."),q()):r.context.clipSpace.toVarying("v_clipSpace")).once()(),vt=Jt("position","vec3"),et=vt.toVarying("positionLocal"),hs=vt.toVarying("positionPrevious"),Ro=P(r=>bi.mul(et).xyz.toVarying(r.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),hy=P(()=>et.transformDirection(bi).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Xe=P(r=>{if(r.shaderStage==="fragment"&&r.material.vertexNode){const e=gN.mul(bN);return e.xyz.div(e.w).toVar("positionView")}return r.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Ce=P(r=>{let e;return r.camera.isOrthographicCamera?e=D(0,0,1):e=Xe.negate().toVarying("v_positionViewDirection").normalize(),e.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class xN extends te{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if(e.shaderStage!=="fragment")return"true";const{material:t}=e;return t.side===yt?"false":e.getFrontFacing()}}const vN=$(xN),dy=N(vN).mul(2).sub(1),ko=P(([r],{material:e})=>{const t=e.side;return t===yt?r=r.mul(-1):t===sr&&(r=r.mul(dy)),r}),TN=Jt("normal","vec3"),In=P(r=>r.geometry.hasAttribute("normal")===!1?(Y('TSL: Vertex attribute "normal" not found on geometry.'),D(0,1,0)):TN,"vec3").once()().toVar("normalLocal"),SN=Xe.dFdx().cross(Xe.dFdy()).normalize().toVar("normalFlat"),Ao=P(r=>{let e;return r.isFlatShading()?e=SN:e=py(In).toVarying("v_normalViewGeometry").normalize(),e},"vec3").once()().toVar("normalViewGeometry"),wN=P(r=>{let e=Ao.transformNormalByInverseViewMatrix(bs);return r.isFlatShading()!==!0&&(e=e.toVarying("v_normalWorldGeometry")),e.normalize().toVar("normalWorldGeometry")},"vec3").once()(),ge=P(r=>{let e;return r.subBuildFn==="NORMAL"||r.subBuildFn==="VERTEX"?(e=Ao,r.isFlatShading()!==!0&&(e=ko(e))):e=r.context.setupNormal().context({getUV:null,getTextureLevel:null}),e},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),xs=ge.transformNormalByInverseViewMatrix(bs).toVar("normalWorld"),ui=P(({subBuildFn:r,context:e})=>{let t;return r==="NORMAL"||r==="VERTEX"?t=ge:t=e.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),fy=P(([r,e=bi])=>nt(e).inverse().transpose().mul(r).normalize());E("transformNormal",fy);const py=P(([r],e)=>{const t=e.context.modelNormalViewMatrix;return t?r.transformNormalByViewMatrix(t):_N.mul(r).transformNormalByViewMatrix(bs)});P(()=>(Y('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),ge)).once(["NORMAL","VERTEX"])();P(()=>(Y('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),xs)).once(["NORMAL","VERTEX"])();P(()=>(Y('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),ui)).once(["NORMAL","VERTEX"])();const Ul=new bt,RN=ne(0).onReference(({material:r})=>r).onObjectUpdate(({material:r})=>r.refractionRatio),oa=ne(1).onReference(({material:r})=>r).onObjectUpdate(function({material:r,scene:e}){return r.envMap?r.envMapIntensity:e.environmentIntensity}),vh=ne(new bt).onReference(function(r){return r.material}).onObjectUpdate(function({material:r,scene:e}){const n=(e.environment!==null||e.environmentNode&&e.environmentNode.isNode)&&r.envMap===null?e.environmentRotation:r.envMapRotation;return n?Ul.makeRotationFromEuler(n).transpose():Ul.identity(),Ul}),AN=Ce.negate().reflect(ge),NN=Ce.negate().refract(ge,RN),EN=AN.transformDirection(Ku).toVar("reflectVector"),CN=NN.transformDirection(Ku).toVar("refractVector"),MN=new Gu;class PN extends Xu{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,i=null){super(e,t,n,i),this.isCubeTextureNode=!0}getInputType(){return this.value.isDepthTexture===!0?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===cu?EN:e.mapping===hu?CN:(V('CubeTextureNode: Mapping "%s" not supported.',e.mapping),D(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return n.isDepthTexture===!0?e.renderer.coordinateSystem===bo?D(t.x,t.y.negate(),t.z):t:(t=vh.mul(t),(e.renderer.coordinateSystem===bo||!n.isRenderTargetTexture)&&(t=D(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}}const BN=ke(PN).setParameterLength(1,4).setName("cubeTexture"),Mt=(r=MN,e=null,t=null,n=null)=>{let i;return r&&r.isCubeTextureNode===!0?(i=K(r.clone()),i.referenceNode=r,e!==null&&(i.uvNode=K(e)),t!==null&&(i.levelNode=K(t)),n!==null&&(i.biasNode=K(n))):i=BN(r,e,t,n),i};class Od extends te{static get type(){return"ReferenceNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=ie.OBJECT}element(e){return new Z_(this,K(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return Y('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;this.count!==null?t=Ld(null,e,this.count):Array.isArray(this.getValueFromReference())?(t=_t(null,e),t.updateType=ie.OBJECT):e==="texture"?t=ve(null):e==="cubeTexture"?t=Mt(null):t=ne(null,e),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.setName(this.name),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let i=1;i<t.length;i++)n=n[t[i]];return n}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const Be=(r,e,t)=>new Od(r,e,t),FN=(r,e,t,n)=>new Od(r,e,n,t);class DN extends Od{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=this.material!==null?this.material:e.material,this.reference}}const Dr=(r,e,t=null)=>new DN(r,e,t),gy=Io(),LN=Xe.dFdx(),ON=Xe.dFdy(),my=gy.dFdx(),_y=gy.dFdy(),yy=ge,by=ON.cross(yy),xy=yy.cross(LN),Th=by.mul(my.x).add(xy.mul(_y.x)),Sh=by.mul(my.y).add(xy.mul(_y.y)),_p=Th.dot(Th).max(Sh.dot(Sh)),vy=_p.equal(0).select(0,_p.inverseSqrt()),UN=Th.mul(vy).toVar("tangentViewFrame"),IN=Sh.mul(vy).toVar("bitangentViewFrame"),Ty=Jt("tangent","vec4"),vu=Ty.xyz.toVar("tangentLocal"),Sy=P(r=>{let e;return r.subBuildFn==="VERTEX"||r.geometry.hasAttribute("tangent")?e=xi.mul(q(vu,0)).xyz.toVarying("v_tangentView").normalize():e=UN,r.isFlatShading()!==!0&&(e=ko(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),kN=P(([r,e],t)=>{let n=r.mul(Ty.w).xyz;return t.subBuildFn==="NORMAL"&&t.isFlatShading()!==!0&&(n=n.toVarying(e)),n}).once(["NORMAL"]),GN=P(r=>{let e;return r.subBuildFn==="VERTEX"||r.geometry.hasAttribute("tangent")?e=kN(ge.cross(Sy),"v_bitangentView").normalize():e=IN,r.isFlatShading()!==!0&&(e=ko(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),eo=nt(Sy,GN,ge).toVar("TBNViewMatrix"),VN=P(()=>{let r=Ji.cross(Ce);return r=r.cross(Ji).normalize(),r=Se(r,ge,ni.mul(hn.oneMinus()).oneMinus().pow2().pow2()).normalize(),r}).once()(),$N=r=>K(r).mul(.5).add(.5),yp=r=>D(r,hr(Ed(N(1).sub(yi(r,r)))));class zN extends ut{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=ll,this.unpackNormalMode=cl}setup(e){const{normalMapType:t,scaleNode:n,unpackNormalMode:i}=this;let s=this.node.mul(2).sub(1);if(t===ll?i===qm?s=yp(s.xy):i===Vv?s=yp(s.yw):i!==cl&&V(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):i!==cl&&V(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),n!==null){let a=n;e.isFlatShading()===!0&&(a=ko(a)),s=D(s.xy.mul(a),s.z)}let o=null;return t===$v?o=py(s):t===ll?o=eo.mul(s).normalize():(V(`NodeMaterial: Unsupported normal map type: ${t}`),o=ge),o}}const bp=ke(zN).setParameterLength(1,2),WN=P(({textureNode:r,bumpScale:e})=>{const t=i=>r.isolate().context({getUV:s=>i(s.uvNode||Io()),forceUVContext:!0}),n=N(t(i=>i));return re(N(t(i=>i.add(i.dFdx()))).sub(n),N(t(i=>i.add(i.dFdy()))).sub(n)).mul(e)}),HN=P(r=>{const{surf_pos:e,surf_norm:t,dHdxy:n}=r,i=e.dFdx().normalize(),s=e.dFdy().normalize(),o=t,a=s.cross(o),u=o.cross(i),l=i.dot(a).mul(dy),c=l.sign().mul(n.x.mul(a).add(n.y.mul(u)));return l.abs().mul(t).sub(c).normalize()});class jN extends ut{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(e){if(e.material.wireframe===!0)return ge;const t=this.scaleNode!==null?this.scaleNode:1,n=WN({textureNode:this.textureNode,bumpScale:t});return HN({surf_pos:Xe,surf_norm:ge,dHdxy:n})}}const qN=ke(jN).setParameterLength(1,2),xp=new Map;class C extends te{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=xp.get(e);return n===void 0&&(n=Dr(e,t),xp.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache(e==="map"?"map":e+"Map","texture")}setup(e){const t=e.context.material,n=this.scope;let i=null;if(n===C.COLOR){const s=t.color!==void 0?this.getColor(n):D();t.map&&t.map.isTexture===!0?i=s.mul(this.getTexture("map")):i=s}else if(n===C.OPACITY){const s=this.getFloat(n);t.alphaMap&&t.alphaMap.isTexture===!0?i=s.mul(this.getTexture("alpha")):i=s}else if(n===C.SPECULAR_STRENGTH)t.specularMap&&t.specularMap.isTexture===!0?i=this.getTexture("specular").r:i=N(1);else if(n===C.SPECULAR_INTENSITY){const s=this.getFloat(n);t.specularIntensityMap&&t.specularIntensityMap.isTexture===!0?i=s.mul(this.getTexture(n).a):i=s}else if(n===C.SPECULAR_COLOR){const s=this.getColor(n);t.specularColorMap&&t.specularColorMap.isTexture===!0?i=s.mul(this.getTexture(n).rgb):i=s}else if(n===C.ROUGHNESS){const s=this.getFloat(n);t.roughnessMap&&t.roughnessMap.isTexture===!0?i=s.mul(this.getTexture(n).g):i=s}else if(n===C.METALNESS){const s=this.getFloat(n);t.metalnessMap&&t.metalnessMap.isTexture===!0?i=s.mul(this.getTexture(n).b):i=s}else if(n===C.EMISSIVE){const s=this.getFloat("emissiveIntensity"),o=this.getColor(n).mul(s);t.emissiveMap&&t.emissiveMap.isTexture===!0?i=o.mul(this.getTexture(n)):i=o}else if(n===C.NORMAL)t.normalMap?(i=bp(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,(t.normalMap.format==pn||t.normalMap.format==au||t.normalMap.format==ou)&&(i.unpackNormalMode=qm)):t.bumpMap?i=qN(this.getTexture("bump").r,this.getFloat("bumpScale")):i=ge;else if(n===C.CLEARCOAT){const s=this.getFloat(n);t.clearcoatMap&&t.clearcoatMap.isTexture===!0?i=s.mul(this.getTexture(n).r):i=s}else if(n===C.CLEARCOAT_ROUGHNESS){const s=this.getFloat(n);t.clearcoatRoughnessMap&&t.clearcoatRoughnessMap.isTexture===!0?i=s.mul(this.getTexture(n).r):i=s}else if(n===C.CLEARCOAT_NORMAL)t.clearcoatNormalMap?i=bp(this.getTexture(n),this.getCache(n+"Scale","vec2")):i=ge;else if(n===C.SHEEN){const s=this.getColor("sheenColor").mul(this.getFloat("sheen"));t.sheenColorMap&&t.sheenColorMap.isTexture===!0?i=s.mul(this.getTexture("sheenColor").rgb):i=s}else if(n===C.SHEEN_ROUGHNESS){const s=this.getFloat(n);t.sheenRoughnessMap&&t.sheenRoughnessMap.isTexture===!0?i=s.mul(this.getTexture(n).a):i=s,i=i.clamp(1e-4,1)}else if(n===C.ANISOTROPY)if(t.anisotropyMap&&t.anisotropyMap.isTexture===!0){const s=this.getTexture(n);i=vd(Ls.x,Ls.y,Ls.y.negate(),Ls.x).mul(s.rg.mul(2).sub(re(1)).normalize().mul(s.b))}else i=Ls;else if(n===C.IRIDESCENCE_THICKNESS){const s=Be("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const o=Be("0","float",t.iridescenceThicknessRange);i=s.sub(o).mul(this.getTexture(n).g).add(o)}else i=s}else if(n===C.TRANSMISSION){const s=this.getFloat(n);t.transmissionMap?i=s.mul(this.getTexture(n).r):i=s}else if(n===C.THICKNESS){const s=this.getFloat(n);t.thicknessMap?i=s.mul(this.getTexture(n).g):i=s}else if(n===C.IOR)i=this.getFloat(n);else if(n===C.LIGHT_MAP)t.lightMap?i=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity")):i=D(0);else if(n===C.AO)t.aoMap?i=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1):i=N(1);else if(n===C.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(n):N(0);else{const s=this.getNodeType(e);i=this.getCache(n,s)}return i}}C.ALPHA_TEST="alphaTest";C.COLOR="color";C.OPACITY="opacity";C.SHININESS="shininess";C.SPECULAR="specular";C.SPECULAR_STRENGTH="specularStrength";C.SPECULAR_INTENSITY="specularIntensity";C.SPECULAR_COLOR="specularColor";C.REFLECTIVITY="reflectivity";C.ROUGHNESS="roughness";C.METALNESS="metalness";C.NORMAL="normal";C.CLEARCOAT="clearcoat";C.CLEARCOAT_ROUGHNESS="clearcoatRoughness";C.CLEARCOAT_NORMAL="clearcoatNormal";C.EMISSIVE="emissive";C.ROTATION="rotation";C.SHEEN="sheen";C.SHEEN_ROUGHNESS="sheenRoughness";C.ANISOTROPY="anisotropy";C.IRIDESCENCE="iridescence";C.IRIDESCENCE_IOR="iridescenceIOR";C.IRIDESCENCE_THICKNESS="iridescenceThickness";C.IOR="ior";C.TRANSMISSION="transmission";C.THICKNESS="thickness";C.ATTENUATION_DISTANCE="attenuationDistance";C.ATTENUATION_COLOR="attenuationColor";C.LINE_SCALE="scale";C.LINE_DASH_SIZE="dashSize";C.LINE_GAP_SIZE="gapSize";C.LINE_WIDTH="linewidth";C.LINE_DASH_OFFSET="dashOffset";C.POINT_SIZE="size";C.DISPERSION="dispersion";C.RETROREFLECTIVITY="retroreflectivity";C.LIGHT_MAP="light";C.AO="ao";const XN=$(C,C.ALPHA_TEST),KN=$(C,C.COLOR),YN=$(C,C.SHININESS),QN=$(C,C.EMISSIVE),wy=$(C,C.OPACITY),ZN=$(C,C.SPECULAR),JN=$(C,C.SPECULAR_INTENSITY),eE=$(C,C.SPECULAR_COLOR),Qa=$(C,C.SPECULAR_STRENGTH),Il=$(C,C.REFLECTIVITY),tE=$(C,C.ROUGHNESS),nE=$(C,C.METALNESS),rE=$(C,C.NORMAL),iE=$(C,C.CLEARCOAT),sE=$(C,C.CLEARCOAT_ROUGHNESS),oE=$(C,C.CLEARCOAT_NORMAL),aE=$(C,C.ROTATION),uE=$(C,C.SHEEN),lE=$(C,C.SHEEN_ROUGHNESS),cE=$(C,C.ANISOTROPY),hE=$(C,C.IRIDESCENCE),dE=$(C,C.IRIDESCENCE_IOR),fE=$(C,C.IRIDESCENCE_THICKNESS),pE=$(C,C.TRANSMISSION),gE=$(C,C.THICKNESS),mE=$(C,C.IOR),_E=$(C,C.ATTENUATION_DISTANCE),yE=$(C,C.ATTENUATION_COLOR),Ry=$(C,C.LINE_SCALE),Ay=$(C,C.LINE_DASH_SIZE),Ny=$(C,C.LINE_GAP_SIZE),wh=$(C,C.LINE_WIDTH),Ey=$(C,C.LINE_DASH_OFFSET),bE=$(C,C.POINT_SIZE),xE=$(C,C.DISPERSION),vE=$(C,C.RETROREFLECTIVITY),Cy=$(C,C.LIGHT_MAP),TE=$(C,C.AO),Ls=ne(new de).onReference(function(r){return r.material}).onRenderUpdate(function({material:r}){this.value.set(r.anisotropy*Math.cos(r.anisotropyRotation),r.anisotropy*Math.sin(r.anisotropyRotation))}),SE=P(r=>r.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class Ve extends te{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===Ve.OBJECT?this.updateType=ie.OBJECT:e===Ve.MATERIAL?this.updateType=ie.RENDER:e===Ve.FRAME?this.updateType=ie.FRAME:e===Ve.AFTER_OBJECT?this.updateAfterType=ie.OBJECT:e===Ve.BEFORE_OBJECT?this.updateBeforeType=ie.OBJECT:e===Ve.BEFORE_MATERIAL?this.updateBeforeType=ie.RENDER:e===Ve.BEFORE_FRAME&&(this.updateBeforeType=ie.FRAME)}setup(e){const{eventType:t,callback:n}=this;if(t===Ve.BEFORE_RENDER_PIPELINE){const i=e.context.onBeforePipelineCallbacks;i&&i.push(n)}else if(t===Ve.AFTER_RENDER_PIPELINE){const i=e.context.onAfterPipelineCallbacks;i&&i.push(n)}return super.setup(e)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}updateAfter(e){this.callback(e)}}Ve.OBJECT="object";Ve.MATERIAL="material";Ve.FRAME="frame";Ve.AFTER_OBJECT="afterObject";Ve.BEFORE_OBJECT="beforeObject";Ve.BEFORE_MATERIAL="beforeMaterial";Ve.BEFORE_FRAME="beforeFrame";Ve.BEFORE_RENDER_PIPELINE="beforeRenderPipeline";Ve.AFTER_RENDER_PIPELINE="afterRenderPipeline";const Ud=(r,e)=>new Ve(r,e).toStack(),Id=r=>Ud(Ve.OBJECT,r),My=r=>Ud(Ve.AFTER_OBJECT,r),wE=r=>Ud(Ve.BEFORE_FRAME,r);class RE extends Lo{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const n=this.storageBufferNode.structTypeNode;return n?n.getMemberType(e,t):"void"}setup(e){return e.isAvailable("storageBuffer")===!1&&this.node.isPBO===!0&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let n;const i=e.isContextAssign();if(e.isAvailable("storageBuffer")===!1?this.node.isPBO===!0&&i!==!0&&(this.node.value.isInstancedBufferAttribute||e.shaderStage!=="compute")?n=e.generatePBO(this):n=this.node.build(e):n=super.generate(e),i!==!0){const s=this.getNodeType(e);n=e.format(n,s,t)}return n}}const AE=ke(RE).setParameterLength(2);class NE extends Dd{static get type(){return"StorageBufferNode"}constructor(e,t=null,n=0){let i,s=null;t&&t.isStructTypeNode?(i="struct",s=t,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):t===null&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=pd(e.itemSize),n=e.count):i=t,super(e,i,n),this.isStorageBufferNode=!0,this.structTypeNode=s,this.access=Wt.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,e.isStorageBufferAttribute!==!0&&e.isStorageInstancedBufferAttribute!==!0&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){let t;if(this.bufferCount===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return AE(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Wt.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return this._attribute===null&&(this._attribute=ey(this.value),this._varying=Ai(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(this.structTypeNode!==null)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generateNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return this.structTypeNode!==null?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(this.structTypeNode!==null&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:n}=this.getAttributeData(),i=n.build(e);return e.registerTransform(i,t),i}}const Py=(r,e=null,t=0)=>new NE(r,e,t),Tu=new WeakMap,vp=new WeakMap,Rh=new WeakMap;function By(r,e){let t;const n=Math.max(e.count,1);if(e.isStorageInstancedBufferAttribute===!0)t=Py(e,"mat4",n).element(ls);else if(n*16*4<=r.getUniformBufferLimit())t=Ld(e.array,"mat4",n).element(ls);else{let o=Tu.get(e);o||(o=new Uv(e.array,16,1),Tu.set(e,o));const a=e.usage===rs?ny:ty,u=[a(o,"vec4",16,0),a(o,"vec4",16,4),a(o,"vec4",16,8),a(o,"vec4",16,12)];t=Gr(...u)}return t}function EE(r,e,t){let n=Rh.get(r);if(n===void 0){const i=e.clone();n={previousInstanceMatrix:i,node:By(t,i)},Rh.set(r,n)}return n.node}const Fy=Ri("vec3","vInstanceColor"),CE=P(([r,e=null],t)=>{const n=r.isStorageInstancedBufferAttribute===!0,i=e&&e.isStorageInstancedBufferAttribute===!0,s=By(t,r);let o=null;n||Math.max(r.count,1)*16*4>t.getUniformBufferLimit()&&(o=Tu.get(r));let a=null,u=null;if(e)if(i)a=Py(e,"vec3",Math.max(e.count,1)).element(ls);else{let c=vp.get(e);c||(c=new Fv(e.array,3),vp.set(e,c)),u=c;const h=e.usage===rs?ny:ty;a=D(h(c,"vec3",3,0))}(o!==null||u!==null)&&wE(()=>{o!==null&&o.version!==r.version&&(o.clearUpdateRanges(),o.updateRanges.push(...r.updateRanges),r.clearUpdateRanges(),o.version=r.version),e&&u!==null&&u.version!==e.version&&(u.clearUpdateRanges(),u.updateRanges.push(...e.updateRanges),e.clearUpdateRanges(),u.version=e.version)});const l=s.mul(et).xyz;if(et.assign(l),t.needsPreviousData()){const c=t.object;My(({object:d})=>{const{previousInstanceMatrix:f}=Rh.get(d);f.array.set(r.array),f.version=r.version;const p=Tu.get(f);p!==void 0&&(p.version=r.version)});const h=EE(c,r,t);hs.assign(h.mul(hs).xyz)}if(t.hasGeometryAttribute("normal")){const c=fy(In,s);In.assign(c)}a!==null&&Fy.assign(a)},"void"),ME=P(([r])=>{const{instanceMatrix:e,instanceColor:t}=r;CE(e,t)},"void"),Ah=new WeakMap,PE=P(([r,e])=>{const t=Ae(cs(fn(r),0).x).toConst(),n=Ae(e),i=n.mod(t).toConst(),s=n.div(t).toConst();return fn(r,Ht(i,s))}),BE=P(([r,e])=>{const t=Ae(cs(fn(r),0).x).toConst(),n=Ae(e).mod(t).toConst(),i=Ae(e).div(t).toConst();return fn(r,Ht(n,i)).x});function Dy(r,e){const t=Ae(cs(fn(r),0).x).toConst(),n=N(e).mul(4).toInt().toConst(),i=n.mod(t).toConst(),s=n.div(t).toConst();return Gr(fn(r,Ht(i,s)),fn(r,Ht(i.add(1),s)),fn(r,Ht(i.add(2),s)),fn(r,Ht(i.add(3),s)))}function FE(r,e){let t=Ah.get(r);if(t===void 0){const{image:n,format:i,type:s}=r._matricesTexture,o=new ku(n.data.slice(),n.width,n.height,i,s);t={previousMatricesTexture:o,node:Dy(o,e)},Ah.set(r,t)}return t.node}const Ly=Ri("vec4","vBatchColor"),DE=Ri("uint","vBatchIndirectId"),LE=P(([r],e)=>{const t=e.getDrawIndex()===null?ls:HA,n=BE(r._indirectTexture,Ae(t));DE.assign(n);const i=Dy(r._matricesTexture,n),s=r._colorsTexture;if(s!==null){const l=PE(s,n);Ly.assign(l)}const o=nt(i);if(et.assign(i.mul(et)),e.needsPreviousData()){My(({object:c})=>{const h=Ah.get(c);h.previousMatricesTexture.image.data.set(c._matricesTexture.image.data),h.previousMatricesTexture.needsUpdate=!0});const l=FE(r,n);hs.assign(l.mul(hs).xyz)}const a=In.div(D(o[0].dot(o[0]),o[1].dot(o[1]),o[2].dot(o[2]))),u=o.mul(a).xyz;In.assign(u),e.hasGeometryAttribute("tangent")&&vu.mulAssign(o)},"void"),Tp=new WeakMap,Nh=new WeakMap;function Oy(r){return{element:e=>{const t=Ae(cs(r).x).toConst(),n=Ae(e).mul(4).toConst(),i=n.div(t).toConst(),s=n.sub(i.mul(t)).toConst();return Gr(r.load(Ht(s,i)),r.load(Ht(s.add(1),i)),r.load(Ht(s.add(2),i)),r.load(Ht(s.add(3),i)))}}}function OE(r,e){let t;if(e.bones.length*16*4<=r.getUniformBufferLimit())t=FN("skeleton.boneMatrices","mat4",e.bones.length);else{e.boneTexture===null&&e.computeBoneTexture();const i=ve(e.boneTexture);Id(({object:s})=>{const o=s.skeleton;o.boneTexture===null&&o.computeBoneTexture(),i.value=o.boneTexture}),t=Oy(i)}return t}function Uy(r,e,t,n,i,s){const o=r.element(i.x),a=r.element(i.y),u=r.element(i.z),l=r.element(i.w),c=t.mul(e),h=jt(o.mul(s.x).mul(c),a.mul(s.y).mul(c),u.mul(s.z).mul(c),l.mul(s.w).mul(c));return n.mul(h).xyz}function UE(r,e,t,n,i,s,o){const a=r.element(s.x),u=r.element(s.y),l=r.element(s.z),c=r.element(s.w);let h=jt(o.x.mul(a),o.y.mul(u),o.z.mul(l),o.w.mul(c));h=i.mul(h).mul(n);const d=nt(h),f=d.mul(e),p=d.mul(t);return{skinNormal:f,skinTangent:p}}function IE(r,e,t,n,i,s){const o=e.skeleton;let a=Nh.get(o);if(a===void 0){if(o.update(),o.bones.length*16*4<=r.getUniformBufferLimit()){const l=new Float32Array(o.boneMatrices);a={previousBoneMatrices:l,previousBoneTexture:null,node:Ld(l,"mat4",o.bones.length)}}else{o.boneTexture===null&&o.computeBoneTexture();const{width:l,height:c}=o.boneTexture.image,h=new Float32Array(o.boneMatrices),d=new ku(h,l,c,Qt,mt);d.needsUpdate=!0,a={previousBoneMatrices:h,previousBoneTexture:d,node:Oy(ve(d))}}Nh.set(o,a)}return Uy(a.node,hs,t,n,i,s)}const kE=P(([r],e)=>{const t=Jt("skinIndex","uvec4"),n=Jt("skinWeight","vec4"),i=Be("bindMatrix","mat4"),s=Be("bindMatrixInverse","mat4"),o=OE(e,r.skeleton);if(Id(({object:u,frameId:l})=>{const c=u.skeleton;if(Tp.get(c)!==l){Tp.set(c,l);const h=Nh.get(c);h!==void 0&&(h.previousBoneMatrices.set(c.boneMatrices),h.previousBoneTexture!==null&&(h.previousBoneTexture.needsUpdate=!0)),c.update()}}),e.needsPreviousData()){const u=IE(e,r,i,s,t,n);hs.assign(u)}const a=Uy(o,et,i,s,t,n);if(et.assign(a),e.hasGeometryAttribute("normal")){const{skinNormal:u,skinTangent:l}=UE(o,In,vu,i,s,t,n);In.assign(u),e.hasGeometryAttribute("tangent")&&vu.assign(l)}},"void");class GE extends te{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode(105+e)}getProperties(e){const t=e.getNodeProperties(this);if(t.stackNode!==void 0)return t;const n={},i=this._getInternalParams();for(let u=0,l=i.length-1;u<l;u++){const c=i[u],h=c.isNode!==!0&&c.name||this.getVarName(u),d=c.isNode!==!0&&c.type||"int";n[h]=Fr(h,d)}const s=e.addStack(),o=i[i.length-1](n);t.returnsNode=o.context({nodeLoop:o}),t.stackNode=s;const a=i[0];if(a.isNode!==!0&&typeof a.update=="function"){const u=P(a.update)(n);t.updateNode=u.context({nodeLoop:u})}return e.removeStack(),t}_getInternalParams(){const e=this.params;return typeof e[0]=="function"?[Oo(!0),e[0]]:e}setup(e){if(this.getProperties(e),e.fnCall){const t=e.getDataFromNode(e.fnCall.shaderNode);t.hasLoop=!0}}generate(e){const t=this.getProperties(e),n=this._getInternalParams(),i=t.stackNode;for(let o=0,a=n.length-1;o<a;o++){const u=n[o];let l=!1,c=null,h=null,d=null,f=null,p=null,g=null;u.isNode?u.getNodeType(e)==="bool"?(l=!0,f="bool",h=u.build(e,f)):(f="int",d=this.getVarName(o),c="0",h=u.build(e,f),p="<"):(f=u.type||"int",d=u.name||this.getVarName(o),c=u.start,h=u.end,p=u.condition,g=u.update,typeof c=="number"?c=e.generateConst(f,c):c&&c.isNode&&(c=c.build(e,f)),typeof h=="number"?h=e.generateConst(f,h):h&&h.isNode&&(h=h.build(e,f)),c!==void 0&&h===void 0?(c=c+" - 1",h="0",p=">="):h!==void 0&&c===void 0&&(c="0",p="<"),p===void 0&&(Number(c)>Number(h)?p=">=":p="<"));let _;if(l)_=`while ( ${h} )`;else{const m={start:c,end:h},y=m.start,b=m.end;let T;const x=()=>p.includes("<")?"+=":"-=";if(g!=null)switch(typeof g){case"function":T=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":T=d+" "+x()+" "+e.generateConst(f,g);break;case"string":T=d+" "+g;break;default:g.isNode?T=d+" "+x()+" "+g.build(e):(V("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),T="break /* invalid update */")}else f==="int"||f==="uint"?g=p.includes("<")?"++":"--":g=x()+" 1.",T=d+" "+g;const v=e.getVar(f,d)+" = "+y,w=d+" "+p+" "+b;_=`for ( ${v}; ${w}; ${T} )`}e.addFlowCode((o===0?`
534
+ `:"")+e.tab+_+` {
535
+
536
+ `).addFlowTab()}const s=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode(`
537
+ `+e.tab+s);for(let o=0,a=n.length-1;o<a;o++)e.addFlowCode((o===0?"":e.tab)+`}
538
+
539
+ `).removeFlowTab();e.addFlowTab()}}const Yt=(...r)=>new GE(Zi(r,"int")).toStack(),kl=new WeakMap,Ot=new tt,Sp=new WeakMap,wp=P(({bufferMap:r,influence:e,stride:t,width:n,depth:i,offset:s})=>{const o=Ae(xh).mul(t).add(s),a=o.div(n),u=o.sub(a.mul(n));return fn(r,Ht(u,a)).depth(i).xyz.mul(e)});function VE(r){const e=r.morphAttributes.position!==void 0,t=r.morphAttributes.normal!==void 0,n=r.morphAttributes.color!==void 0,i=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,s=i!==void 0?i.length:0;let o=kl.get(r);if(o===void 0||o.count!==s){let m=function(){g.dispose(),kl.delete(r),r.removeEventListener("dispose",m)};o!==void 0&&o.texture.dispose();const a=r.morphAttributes.position||[],u=r.morphAttributes.normal||[],l=r.morphAttributes.color||[];let c=0;e===!0&&(c=1),t===!0&&(c=2),n===!0&&(c=3);let h=r.attributes.position.count*c,d=1;const f=4096;h>f&&(d=Math.ceil(h/f),h=f);const p=new Float32Array(h*d*4*s),g=new Bv(p,h,d,s);g.type=mt,g.needsUpdate=!0;const _=c*4;for(let y=0;y<s;y++){const b=a[y],T=u[y],x=l[y],v=h*d*4*y;for(let w=0;w<b.count;w++){const R=w*_;e===!0&&(Ot.fromBufferAttribute(b,w),p[v+R+0]=Ot.x,p[v+R+1]=Ot.y,p[v+R+2]=Ot.z,p[v+R+3]=0),t===!0&&(Ot.fromBufferAttribute(T,w),p[v+R+4]=Ot.x,p[v+R+5]=Ot.y,p[v+R+6]=Ot.z,p[v+R+7]=0),n===!0&&(Ot.fromBufferAttribute(x,w),p[v+R+8]=Ot.x,p[v+R+9]=Ot.y,p[v+R+10]=Ot.z,p[v+R+11]=x.itemSize===4?Ot.w:1)}}o={count:s,texture:g,stride:c,size:new de(h,d)},kl.set(r,o),r.addEventListener("dispose",m)}return o}const $E=P(([r])=>{const{geometry:e}=r,t=e.morphAttributes.position!==void 0,n=e.hasAttribute("normal")&&e.morphAttributes.normal!==void 0,i=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=i!==void 0?i.length:0;if(s===0)return;let o=Sp.get(r);(o===void 0||o.count!==s)&&(o={base:ne(1),influences:r.morphTargetInfluences?_t(r.morphTargetInfluences,"float"):null,count:s},Sp.set(r,o));const{base:a,influences:u}=o,{texture:l,stride:c,size:h}=VE(e);t===!0&&et.mulAssign(a),n===!0&&In.mulAssign(a);const d=Ae(h.width);Yt(s,({i:f})=>{const p=N(0).toVar();r.count>1&&r.morphTexture!==null&&r.morphTexture!==void 0?p.assign(fn(r.morphTexture,Ht(Ae(f).add(1),Ae(ls))).r):p.assign(u.element(f).toVar()),Me(p.notEqual(0),()=>{t===!0&&et.addAssign(wp({bufferMap:l,influence:p,stride:c,width:d,depth:f,offset:Ae(0)})),n===!0&&In.addAssign(wp({bufferMap:l,influence:p,stride:c,width:d,depth:f,offset:Ae(1)}))})}),Id(({object:f})=>{const{base:p,influences:g}=o;f.geometry.morphTargetsRelative?p.value=1:p.value=1-f.morphTargetInfluences.reduce((_,m)=>_+m,0),g&&(g.array=f.morphTargetInfluences,g.update())})},"void");class vs extends te{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class zE extends vs{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class WE extends Cd{static get type(){return"LightingContextNode"}constructor(e,t=null,n=[],i=null,s=null){super(e),this.lightingModel=t,this.materialLightings=n,this.backdropNode=i,this.backdropAlphaNode=s,this._value=null}getContext(){const{materialLightings:e,backdropNode:t,backdropAlphaNode:n}=this,i=D().toVar("directDiffuse"),s=D().toVar("directSpecular"),o=D().toVar("indirectDiffuse"),a=D().toVar("indirectSpecular"),u={directDiffuse:i,directSpecular:s,indirectDiffuse:o,indirectSpecular:a};return{radiance:D().toVar("radiance"),irradiance:D().toVar("irradiance"),iblIrradiance:D().toVar("iblIrradiance"),ambientOcclusion:N(1).toVar("ambientOcclusion"),reflectedLight:u,materialLightings:e,backdrop:t,backdropAlpha:n}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const HE=ke(WE);class Rp extends vs{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const Qr=new de;class Iy extends Xu{static get type(){return"ViewportTextureNode"}constructor(e=Or,t=null,n=null){let i=null;n===null?(i=new cm,i.minFilter=Ir,n=i):i=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=ie.RENDER,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,n;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,n=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,n=this._cacheTextures),e===null)return t;if(n.has(e)===!1){const i=t.clone();n.set(e,i)}return n.get(e)}updateReference(e){const t=e.renderer,n=t.getRenderTarget(),i=t.getCanvasTarget(),s=n||i;return this.value=this.getTextureForReference(s),this.value}updateBefore(e){const t=e.renderer,n=t.getRenderTarget(),i=t.getCanvasTarget(),s=n||i;s===null?t.getDrawingBufferSize(Qr):s.getDrawingBufferSize?s.getDrawingBufferSize(Qr):Qr.set(s.width,s.height);const o=this.getTextureForReference(s);(o.image.width!==Qr.width||o.image.height!==Qr.height)&&(o.image.width=Qr.width,o.image.height=Qr.height,o.needsUpdate=!0);const a=o.generateMipmaps;o.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(o),o.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const ky=ke(Iy,null,null,{generateMipmaps:!0}).setParameterLength(0,3),jE=ky(),qE=(r=Or,e=null)=>jE.sample(r,e);let Gl=null;class XE extends Iy{static get type(){return"ViewportDepthTextureNode"}constructor(e=Or,t=null,n=null){n===null&&(Gl===null&&(Gl=new ar),n=Gl),super(e,t,n)}}const KE=ke(XE).setParameterLength(0,3);class Bt extends te{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===Bt.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let i=null;if(t===Bt.DEPTH_BASE)n!==null&&(i=$y().assign(n));else if(t===Bt.DEPTH)e.isPerspectiveCamera?i=Gy(Xe.z,oi,ai):i=ho(Xe.z,oi,ai);else if(t===Bt.LINEAR_DEPTH)if(n!==null)if(e.isPerspectiveCamera){const s=Vy(n,oi,ai);i=ho(s,oi,ai)}else i=n;else i=ho(Xe.z,oi,ai);return i}}Bt.DEPTH_BASE="depthBase";Bt.DEPTH="depth";Bt.LINEAR_DEPTH="linearDepth";const ho=(r,e,t)=>r.add(e).div(e.sub(t)),YE=P(([r,e,t],n)=>n.renderer.reversedDepthBuffer===!0?t.sub(e).mul(r).sub(t):e.sub(t).mul(r).sub(e)),Gy=(r,e,t)=>e.add(r).mul(t).div(t.sub(e).mul(r)),QE=(r,e,t)=>e.mul(r.add(t)).div(r.mul(e.sub(t))),Vy=P(([r,e,t],n)=>n.renderer.reversedDepthBuffer===!0?e.mul(t).div(e.sub(t).mul(r).sub(e)):e.mul(t).div(t.sub(e).mul(r).sub(t))),kd=(r,e,t)=>{e=e.max(1e-6).toVar();const n=cr(r.negate().div(e)),i=cr(t.div(e));return n.div(i)},$y=ke(Bt,Bt.DEPTH_BASE),zy=$(Bt,Bt.DEPTH),ZE=ke(Bt,Bt.LINEAR_DEPTH).setParameterLength(0,1);KE();zy.assign=r=>$y(r);class nn extends te{static get type(){return"ClippingNode"}constructor(e=nn.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:i}=t;return this.hardwareClipping=e.hardwareClipping,this.scope===nn.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,i):this.scope===nn.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(n,i)}setupAlphaToCoverage(e,t){return P(()=>{const n=N().toVar("distanceToPlane"),i=N().toVar("distanceToGradient"),s=N(1).toVar("clipOpacity"),o=t.length;if(this.hardwareClipping===!1&&o>0){const u=_t(t).setGroup(Q);Yt(o,({i:l})=>{const c=u.element(l);n.assign(Xe.dot(c.xyz).negate().add(c.w)),i.assign(n.fwidth().div(2)),s.mulAssign(Un(i.negate(),i,n))})}const a=e.length;if(a>0){const u=_t(e).setGroup(Q),l=N(1).toVar("intersectionClipOpacity");Yt(a,({i:c})=>{const h=u.element(c);n.assign(Xe.dot(h.xyz).negate().add(h.w)),i.assign(n.fwidth().div(2)),l.mulAssign(Un(i.negate(),i,n).oneMinus())}),s.mulAssign(l.oneMinus())}xe.a.mulAssign(s),xe.a.equal(0).discard()})()}setupDefault(e,t){return P(()=>{const n=t.length;if(this.hardwareClipping===!1&&n>0){const s=_t(t).setGroup(Q);Yt(n,({i:o})=>{const a=s.element(o);Xe.dot(a.xyz).greaterThan(a.w).discard()})}const i=e.length;if(i>0){const s=_t(e).setGroup(Q),o=Oo(!0).toVar("clipped");Yt(i,({i:a})=>{const u=s.element(a);o.assign(Xe.dot(u.xyz).greaterThan(u.w).and(o))}),o.discard()}})()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),P(()=>{const i=_t(e).setGroup(Q),s=gr(t.getClipDistance());Yt(n,({i:o})=>{const a=i.element(o),u=Xe.dot(a.xyz).sub(a.w).negate();s.element(o).assign(u)})})()}}nn.ALPHA_TO_COVERAGE="alphaToCoverage";nn.DEFAULT="default";nn.HARDWARE="hardware";const JE=()=>new nn,eC=()=>new nn(nn.ALPHA_TO_COVERAGE),tC=()=>new nn(nn.HARDWARE),nC=.05,Ap=P(([r])=>fr(he(1e4,Tt(he(17,r.x).add(he(.1,r.y)))).mul(jt(.1,Ct(Tt(he(13,r.y).add(r.x))))))),Np=P(([r])=>Ap(re(Ap(r.xy),r.z))),rC=P(([r])=>{const e=ot(dr(H_(r.xyz)),dr(j_(r.xyz))),t=N(1).div(N(nC).mul(e)).toVar("pixScale"),n=re(To(di(cr(t))),To(Ad(cr(t)))),i=re(Np(di(n.x.mul(r.xyz))),Np(di(n.y.mul(r.xyz)))),s=fr(cr(t)),o=jt(he(s.oneMinus(),i.x),he(s,i.y)),a=_i(s,s.oneMinus()),u=D(o.mul(o).div(he(2,a).mul(Et(1,a))),o.sub(he(.5,a)).div(Et(1,a)),Et(1,Et(1,o).mul(Et(1,o)).div(he(2,a).mul(Et(1,a))))),l=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(u.x,u.y),u.z);return $r(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class iC extends uy{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e),n=e.hasGeometryAttribute(t);let i;return n===!0?i=super.generate(e):i=e.generateConst(this.nodeType,new tt(1,1,1,1)),i}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const sC=(r=0)=>new iC(r);class Ke extends nf{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(t.startsWith("_")===!0)continue;const n=this[t];n&&n.isNode===!0&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:n}of this._getNodeChildren())e.push(wi(t.slice(0,-4)),n.getCacheKey());return this.type+Do(e)}build(e){this.setup(e)}setupObserver(e){return new Rw(e)}setup(e){e.context.setupNormal=()=>ts(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();e.addStack();const i=this.setupVertex(e),s=ts(this.vertexNode||i,"VERTEX");e.context.clipSpace=s,e.stack.outputNode=s,this.setupHardwareClipping(e),this.geometryNode!==null&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();let o;const a=this.setupClipping(e);if((this.depthWrite===!0||this.depthTest===!0)&&(n!==null?n.depthBuffer===!0&&this.setupDepth(e):t.depth===!0&&this.setupDepth(e)),this.fragmentNode===null){this.setupDiffuseColor(e),this.setupAmbientOcclusion(e),this.setupVariants(e);const u=this.setupLighting(e);a!==null&&e.stack.addToStack(a);const l=q(u,xe.a).max(0);o=this.setupOutput(e,l),lo.assign(o);const c=this.outputNode!==null;if(c&&(o=this.outputNode),e.context.getOutput&&(o=e.context.getOutput(o,e)),n!==null){const h=t.getMRT(),d=this.mrtNode;h!==null?(c&&lo.assign(o),o=h,d!==null&&(o=h.merge(d))):d!==null&&(o=d)}}else{let u=this.fragmentNode;u.isOutputStructNode!==!0&&(u=u.convert(e.getOutputType())),o=this.setupOutput(e,u)}e.stack.outputNode=o,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(e.clippingContext===null)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let i=null;if(t.length>0||n.length>0){const s=e.renderer.currentSamples;this.alphaToCoverage&&s>1?i=eC():e.stack.addToStack(JE())}return i}setupHardwareClipping(e){if(e.hardwareClipping=!1,e.clippingContext===null)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(tC()),e.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let i=this.depthNode;if(i===null){const s=t.getMRT();s&&s.has("depth")?i=s.get("depth"):t.logarithmicDepthBuffer===!0&&(n.isPerspectiveCamera?i=kd(Xe.z,oi,ai):i=ho(Xe.z,oi,ai))}i!==null&&zy.assign(i).toStack()}setupPositionView(){return xi.mul(et).xyz}setupModelViewProjection(){return mn.mul(Xe)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),SE}setupPosition(e){const{object:t,geometry:n}=e;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&$E(t),t.isSkinnedMesh===!0&&kE(t),this.displacementMap){const i=Dr("displacementMap","texture"),s=Dr("displacementScale","float"),o=Dr("displacementBias","float");et.addAssign(In.normalize().mul(i.x.mul(s).add(o)))}return t.isBatchedMesh&&LE(t),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&ME(t),this.positionNode!==null&&et.assign(ts(this.positionNode,"POSITION","vec3")),et}setupDiffuseColor(e){const{object:t,geometry:n}=e;this.maskNode!==null&&Oo(this.maskNode).not().discard();let i=this.colorNode?q(this.colorNode):KN;this.vertexColors===!0&&n.hasAttribute("color")&&(i=i.mul(sC())),t.instanceColor&&(i=Fy.mul(i)),t.isBatchedMesh&&t._colorsTexture&&(i=Ly.mul(i)),xe.assign(i);const s=this.opacityNode?N(this.opacityNode):wy;xe.a.assign(xe.a.mul(s));let o=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(o=this.alphaTestNode!==null?N(this.alphaTestNode):XN,this.alphaToCoverage===!0?(xe.a=Un(o,o.add(q_(xe.a)),xe.a),xe.a.lessThanEqual(0).discard()):xe.a.lessThanEqual(o).discard()),this.alphaHash===!0&&xe.a.lessThan(rC(et)).discard(),e.isOpaque()&&xe.a.assign(1)}setupVariants(){}setupOutgoingLight(){return this.lights===!0?D(0):xe.rgb}setupNormal(){return this.normalNode?D(this.normalNode):rE}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Dr("envMap","cubeTexture"):Dr("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Rp(Cy)),t}setupMaterialLightings(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),e.context.ambientOcclusion&&t.push(new zE(e.context.ambientOcclusion)),e.context.getGI){const s=e.context.getGI(null,e);s!==null&&t.push(new Rp(s))}return t}setupAmbientOcclusion(e){let t=this.aoNode;t===null&&e.material.aoMap&&(t=TE),e.context.getAO&&(t=e.context.getAO(t,e)),t!==null&&(lp.assign(t),e.context.ambientOcclusion=lp)}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:s}=this,o=this.lights===!0&&e.renderer.lighting.enabled,a=o||this.lightsNode!==null,u=o?this.setupMaterialLightings(e):[],l=a?this.lightsNode||e.lightsNode:null;let c=this.setupOutgoingLight(e);if(l&&(u.length>0||l.getScope().hasLights)){const h=this.setupLightingModel(e)||null;c=HE(l,h,u,n,i)}else n!==null&&(c=D(i!==null?Se(c,n,i):n));return(s&&s.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(up.assign(D(s||QN)),c=c.add(up)),c}setupFog(e,t){const n=e.fogNode;return n&&(lo.assign(t),t=q(n.toVar())),t}setupPremultipliedAlpha(e,t){return sy(t)}setupOutput(e,t){return this.fog===!0&&(t=this.setupFog(e,t)),this.premultipliedAlpha===!0&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const n in e){const i=e[n];this[n]===void 0&&(this[n]=i,i&&i.clone&&(this[n]=i.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const n in t)Object.getOwnPropertyDescriptor(this.constructor.prototype,n)===void 0&&t[n].get!==void 0&&Object.defineProperty(this.constructor.prototype,n,t[n])}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{},nodes:{}});const n=nf.prototype.toJSON.call(this,e);n.inputNodes={};for(const{property:s,childNode:o}of this._getNodeChildren())n.inputNodes[s]=o.toJSON(e).uuid;function i(s){const o=[];for(const a in s){const u=s[a];delete u.metadata,o.push(u)}return o}if(t){const s=i(e.textures),o=i(e.images),a=i(e.nodes);s.length>0&&(n.textures=s),o.length>0&&(n.images=o),a.length>0&&(n.nodes=a)}return n}copy(e){const t=Object.getOwnPropertyDescriptors(this.constructor.prototype);for(const n in t)if(t[n].set!==void 0&&e[n]!==void 0){const i=e[n];this[n]&&this[n].copy!==void 0?this[n].copy(i):this[n]=i}for(const n in this)if(!/^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test(n)&&this[n]!==void 0&&e[n]!==void 0){const i=e[n];this[n]&&this[n].copy!==void 0?this[n].copy(i):this[n]=i}return this.clippingPlanes=e.clippingPlanes?e.clippingPlanes.map(n=>n.clone()):null,this.userData=JSON.parse(JSON.stringify(e.userData)),this}}const oC=new sm;class aC extends Ke{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(oC),this.setValues(e)}}const uC=new sv;class lC extends Ke{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(uC),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?N(this.offsetNode):Ey,t=this.dashScaleNode?N(this.dashScaleNode):Ry,n=this.dashSizeNode?N(this.dashSizeNode):Ay,i=this.gapSizeNode?N(this.gapSizeNode):Ny;es.assign(n),bu.assign(i);const s=Ai(Jt("lineDistance").mul(t));(e?s.add(e):s).mod(es.add(bu)).greaterThan(es).discard()}}const Za=Ri("vec3","worldStart"),Eh=Ri("vec3","worldEnd"),Wy=Ri("float","lineDistance"),ri=Ri("vec4","worldPos"),Ep=P(({start:r,end:e})=>{const t=mn.element(2).element(2),n=mn.element(3).element(2);return t.greaterThan(0).select(n.negate().div(t.add(1)),n.mul(-.5).div(t)).sub(r.z).div(e.z.sub(r.z))},{start:"vec4",end:"vec4",return:"float"}),cC=P(({p1:r,p2:e,p3:t,p4:n})=>{const i=r.sub(t),s=n.sub(t),o=e.sub(r),a=i.dot(s),u=s.dot(o),l=i.dot(o),c=s.dot(s),d=o.dot(o).mul(c).sub(u.mul(u)),p=a.mul(u).sub(l.mul(c)).div(d).clamp(),g=a.add(u.mul(p)).div(c).clamp();return re(p,g)},{p1:"vec3",p2:"vec3",p3:"vec3",p4:"vec3",return:"vec2"});P(({material:r})=>{const e=r._useDash,t=r._useWorldUnits,n=Jt("instanceStart"),i=Jt("instanceEnd"),s=q(xi.mul(q(n,1))).toVar("start"),o=q(xi.mul(q(i,1))).toVar("end");let a,u;e&&(a=N(Jt("instanceDistanceStart")).toVar("distanceStart"),u=N(Jt("instanceDistanceEnd")).toVar("distanceEnd")),t&&(Za.assign(s.xyz),Eh.assign(o.xyz));const l=co.z.div(co.w),c=mn.element(2).element(3).equal(-1);if(Me(c,()=>{Me(s.z.lessThan(0).and(o.z.greaterThan(0)),()=>{const m=Ep({start:s,end:o});o.assign(q(Se(s.xyz,o.xyz,m),o.w)),e&&u.assign(Se(a,u,m))}).ElseIf(o.z.lessThan(0).and(s.z.greaterThanEqual(0)),()=>{const m=Ep({start:o,end:s});s.assign(q(Se(o.xyz,s.xyz,m),s.w)),e&&a.assign(Se(u,a,m))})}),e){const m=r.dashScaleNode?N(r.dashScaleNode):Ry,y=r.offsetNode?N(r.offsetNode):Ey;let b=vt.y.lessThan(.5).select(m.mul(a),m.mul(u));b=b.add(y),Wy.assign(b)}const h=mn.mul(s),d=mn.mul(o),f=h.xyz.div(h.w),p=d.xyz.div(d.w),g=p.xy.sub(f.xy).toVar();g.x.assign(g.x.mul(l)),g.assign(g.normalize());const _=q().toVar();if(t){const m=o.xyz.sub(s.xyz).normalize(),y=Se(s.xyz,o.xyz,.5).normalize(),b=m.cross(y).normalize(),T=m.cross(b);ri.assign(vt.y.lessThan(.5).select(s,o));const x=wh.mul(.5);ri.addAssign(q(vt.x.lessThan(0).select(b.mul(x),b.mul(x).negate()),0)),e||(ri.addAssign(q(vt.y.lessThan(.5).select(m.mul(x).negate(),m.mul(x)),0)),ri.addAssign(q(T.mul(x),0)),Me(vt.y.greaterThan(1).or(vt.y.lessThan(0)),()=>{ri.subAssign(q(T.mul(2).mul(x),0))})),_.assign(mn.mul(ri));const v=D().toVar();v.assign(vt.y.lessThan(.5).select(f,p)),_.z.assign(v.z.mul(_.w))}else{const m=re(g.y,g.x.negate()).toVar("offset");g.x.assign(g.x.div(l)),m.x.assign(m.x.div(l)),m.assign(vt.x.lessThan(0).select(m.negate(),m)),Me(vt.y.lessThan(0),()=>{m.assign(m.sub(g))}).ElseIf(vt.y.greaterThan(1),()=>{m.assign(m.add(g))}),m.assign(m.mul(wh)),m.assign(m.div(co.w.div(cy))),_.assign(vt.y.lessThan(.5).select(h,d)),m.assign(m.mul(_.w)),_.assign(_.add(q(m,0,0)))}return _})();P(({material:r,renderer:e})=>{const t=r._useAlphaToCoverage,n=r._useDash,i=r._useWorldUnits,s=Io();if(n){const a=r.dashSizeNode?N(r.dashSizeNode):Ay,u=r.gapSizeNode?N(r.gapSizeNode):Ny;es.assign(a),bu.assign(u),s.y.lessThan(-1).or(s.y.greaterThan(1)).discard(),Wy.mod(es.add(bu)).greaterThan(es).discard()}const o=N(1).toVar("alpha");if(i){const a=ri.xyz.normalize().mul(1e5),u=Eh.sub(Za),l=cC({p1:Za,p2:Eh,p3:D(0,0,0),p4:a}),c=Za.add(u.mul(l.x)),h=a.mul(l.y),p=c.sub(h).length().div(wh);if(!n)if(t&&e.currentSamples>0){const g=p.fwidth();o.assign(Un(g.negate().add(.5),g.add(.5),p).oneMinus())}else p.greaterThan(.5).discard()}else if(t&&e.currentSamples>0){const a=s.x,u=s.y.greaterThan(0).select(s.y.sub(1),s.y.add(1)),l=a.mul(a).add(u.mul(u)),c=N(l.fwidth()).toVar("dlen");Me(s.y.abs().greaterThan(1),()=>{o.assign(Un(c.oneMinus(),c.add(1),l).oneMinus())})}else Me(s.y.abs().greaterThan(1),()=>{const a=s.x,u=s.y.greaterThan(0).select(s.y.sub(1),s.y.add(1));a.mul(a).add(u.mul(u)).greaterThan(1).discard()});return o})();const hC=new rv;class dC extends Ke{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(hC),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?N(this.opacityNode):wy;xe.assign(Bd(q($N(ge),e),Xh))}}const Hy=P(([r=hy])=>{const e=r.z.atan(r.x).mul(1/(Math.PI*2)).add(.5),t=r.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return re(e,t)}),Cp=P(([r=Io()])=>{const e=r.x.sub(.5).mul(Math.PI*2),t=r.y.sub(.5).mul(Math.PI),n=t.cos(),i=n.mul(e.cos()),s=t.sin(),o=n.mul(e.sin());return D(i,s,o)});class jy extends Ti{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new Gu(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const s=new jm(5,5,5),o=Hy(hy),a=new Ke;a.colorNode=ve(t,o,0),a.side=yt,a.blending=ur;const u=new yn(s,a),l=new Kh;l.add(u),t.minFilter===Ir&&(t.minFilter=Rt);const c=new Dv(1,10,this),h=e.getMRT();return e.setMRT(null),c.update(e,l),e.setMRT(h),t.minFilter=n,t.generateMipmaps=i,u.geometry.dispose(),u.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,i);e.setRenderTarget(s)}}const fo=new WeakMap;class fC extends ut{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Mt(null);const t=new Gu;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=ie.RENDER}updateBefore(e){const{renderer:t,material:n}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const s=i.isTextureNode?i.value:n[i.property];if(s&&s.isTexture){const o=s.mapping;if(o===td||o===nd){if(fo.has(s)){const a=fo.get(s);Mp(a,s.mapping),this._cubeTexture=a}else{const a=s.image;if(pC(a)){const u=new jy(a.height);u.fromEquirectangularTexture(t,s),Mp(u.texture,s.mapping),this._cubeTexture=u.texture,fo.set(s,u.texture),s.addEventListener("dispose",qy)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function pC(r){return r==null?!1:r.height>0}function qy(r){const e=r.target;e.removeEventListener("dispose",qy);const t=fo.get(e);t!==void 0&&(fo.delete(e),t.dispose())}function Mp(r,e){e===td?r.mapping=cu:e===nd&&(r.mapping=hu)}const Xy=ke(fC).setParameterLength(1);class Gd extends vs{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Xy(this.envNode)}}class gC extends vs{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=N(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Yu{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Ky extends Yu{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,i=e.irradianceLightMap;n.indirectDiffuse.assign(q(0)),i?n.indirectDiffuse.addAssign(i):n.indirectDiffuse.addAssign(q(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(xe.rgb)}finish(e){const{material:t,context:n}=e,i=n.outgoingLight,s=e.context.environment;if(s)switch(t.combine){case Pv:i.rgb.assign(Se(i.rgb,i.rgb.mul(s.rgb),Qa.mul(Il)));break;case Mv:i.rgb.assign(Se(i.rgb,s.rgb,Qa.mul(Il)));break;case Cv:i.rgb.addAssign(s.rgb.mul(Qa.mul(Il)));break;default:Y("BasicLightingModel: Unsupported .combine value:",t.combine);break}}}const mC=new Br;class _C extends Ke{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(mC),this.setValues(e)}setupNormal(){return ko(Ao)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Gd(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new gC(Cy)),t}setupOutgoingLight(){return xe.rgb}setupLightingModel(){return new Ky}}const fi=P(({f0:r,f90:e,dotVH:t})=>{const n=t.mul(-5.55473).sub(6.98316).mul(t).exp2();return r.mul(n.oneMinus()).add(e.mul(n))}),ds=P(r=>r.diffuseColor.mul(1/Math.PI)),yC=()=>N(.25),bC=P(({dotNH:r})=>_h.mul(N(.5)).add(1).mul(N(1/Math.PI)).mul(r.pow(_h))),xC=P(({lightDirection:r})=>{const e=r.add(Ce).normalize(),t=ge.dot(e).clamp(),n=Ce.dot(e).clamp(),i=fi({f0:En,f90:1,dotVH:n}),s=yC(),o=bC({dotNH:t});return i.mul(s).mul(o)});class Yy extends Ky{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const s=ge.dot(e).clamp().mul(t);n.directDiffuse.addAssign(s.mul(ds({diffuseColor:xe.rgb}))),this.specular===!0&&n.directSpecular.addAssign(s.mul(xC({lightDirection:e})).mul(Qa))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(ds({diffuseColor:xe}))),i.indirectDiffuse.mulAssign(t)}}const vC=new tm;class TC extends Ke{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(vC),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Gd(t):null}setupLightingModel(){return new Yy(!1)}}const SC=new Jx;class wC extends Ke{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(SC),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Gd(t):null}setupLightingModel(){return new Yy}setupVariants(){const e=(this.shininessNode?N(this.shininessNode):YN).max(1e-4);_h.assign(e);const t=this.specularNode||ZN;En.assign(t)}}const RC=P(r=>{if(r.geometry.hasAttribute("normal")===!1)return N(0);const e=Ao.dFdx().abs().max(Ao.dFdy().abs());return e.x.max(e.y).max(e.z)}),Qy=P(r=>{const{roughness:e}=r,t=RC();let n=e.max(.0525);return n=n.add(t),n=n.min(1),n}),AC=P(({alpha:r,dotNL:e,dotNV:t})=>{const n=r.pow2(),i=e.mul(n.add(n.oneMinus().mul(t.pow2())).sqrt()),s=t.mul(n.add(n.oneMinus().mul(e.pow2())).sqrt());return On(.5,i.add(s).max($_))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),NC=P(({alphaT:r,alphaB:e,dotTV:t,dotBV:n,dotTL:i,dotBL:s,dotNV:o,dotNL:a})=>{const u=a.mul(D(r.mul(t),e.mul(n),o).length()),l=o.mul(D(r.mul(i),e.mul(s),a).length());return On(.5,u.add(l).max($_))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),EC=P(({alpha:r,dotNH:e})=>{const t=r.pow2(),n=e.pow2().mul(t.oneMinus()).oneMinus();return t.div(n.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),CC=N(1/Math.PI),MC=P(({alphaT:r,alphaB:e,dotNH:t,dotTH:n,dotBH:i})=>{const s=r.mul(e),o=D(e.mul(n),r.mul(i),s.mul(t)),a=o.dot(o),u=s.div(a);return CC.mul(s.mul(u.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),Vl=P(({lightDirection:r,f0:e,f90:t,roughness:n,f:i,normalView:s=ge,viewDirection:o=Ce,USE_IRIDESCENCE:a,USE_ANISOTROPY:u})=>{const l=n.pow2(),c=r.add(o).normalize(),h=s.dot(r).clamp(),d=s.dot(o).clamp(),f=s.dot(c).clamp(),p=o.dot(c).clamp();let g=fi({f0:e,f90:t,dotVH:p}),_,m;if(dh(a)&&(g=Td.mix(g,i)),dh(u)){const y=qa.dot(r),b=qa.dot(o),T=qa.dot(c),x=Ji.dot(r),v=Ji.dot(o),w=Ji.dot(c);_=NC({alphaT:mh,alphaB:l,dotTV:b,dotBV:v,dotTL:y,dotBL:x,dotNV:d,dotNL:h}),m=MC({alphaT:mh,alphaB:l,dotNH:f,dotTH:T,dotBH:w})}else _=AC({alpha:l,dotNL:h,dotNV:d}),m=EC({alpha:l,dotNH:f});return g.mul(_).mul(m)}),PC=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Sn=null;const Zy=P(({roughness:r,dotNV:e})=>{Sn===null&&(Sn=new ku(PC,16,16,pn,wt),Sn.name="DFG_LUT",Sn.minFilter=Rt,Sn.magFilter=Rt,Sn.wrapS=xo,Sn.wrapT=xo,Sn.generateMipmaps=!1,Sn.needsUpdate=!0);const t=re(r,e);return ve(Sn,t).rg}),Jy=P(r=>{const{dotNV:e,specularColor:t,specularF90:n,roughness:i}=r,s=Zy({dotNV:e,roughness:i});return t.mul(s.x).add(n.mul(s.y))}),Pp=P(({f:r,f90:e,dotVH:t})=>{const n=t.oneMinus().saturate(),i=n.mul(n),s=n.mul(i,i).clamp(0,.9999);return r.sub(D(e).mul(s)).div(s.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),BC=P(({roughness:r,dotNH:e})=>{const t=r.pow2(),n=N(1).div(t),s=e.pow2().oneMinus().max(.0078125);return N(2).add(n).mul(s.pow(n.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),FC=P(({dotNV:r,dotNL:e})=>N(1).div(N(4).mul(e.add(r).sub(e.mul(r)))).clamp()).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),DC=P(({lightDirection:r})=>{const e=r.add(Ce).normalize(),t=ge.dot(r).clamp(),n=ge.dot(Ce).clamp(),i=ge.dot(e).clamp(),s=BC({roughness:si,dotNH:i}),o=FC({dotNV:n,dotNL:t});return $t.mul(s).mul(o)}),Bp=P(({N:r,V:e,roughness:t})=>{const s=.0078125,o=r.dot(e).saturate(),a=re(t,o.oneMinus().sqrt());return a.assign(a.mul(.984375).add(s)),a}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),LC=P(({f:r})=>{const e=r.length();return ot(e.mul(e).add(r.z).div(e.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),aa=P(({v1:r,v2:e})=>{const t=r.dot(e),n=t.abs().toVar(),i=n.mul(.0145206).add(.4965155).mul(n).add(.8543985).toVar(),s=n.add(4.1616724).mul(n).add(3.417594).toVar(),o=i.div(s),a=t.greaterThan(0).select(o,ot(t.mul(t).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return r.cross(e).mul(a)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),$l=P(({N:r,V:e,P:t,mInv:n,p0:i,p1:s,p2:o,p3:a})=>{const u=s.sub(i).toVar(),l=a.sub(i).toVar(),c=u.cross(l),h=D().toVar();return Me(c.dot(t.sub(i)).greaterThanEqual(0),()=>{const d=e.sub(r.mul(e.dot(r))).normalize(),f=r.cross(d).negate(),p=n.mul(nt(d,f,r).transpose()).toVar(),g=p.mul(i.sub(t)).normalize().toVar(),_=p.mul(s.sub(t)).normalize().toVar(),m=p.mul(o.sub(t)).normalize().toVar(),y=p.mul(a.sub(t)).normalize().toVar(),b=D(0).toVar();b.addAssign(aa({v1:g,v2:_})),b.addAssign(aa({v1:_,v2:m})),b.addAssign(aa({v1:m,v2:y})),b.addAssign(aa({v1:y,v2:g})),h.assign(D(LC({f:b})))}),h}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Qu=1/6,eb=r=>he(Qu,he(r,he(r,r.negate().add(3)).sub(3)).add(1)),Ch=r=>he(Qu,he(r,he(r,he(3,r).sub(6))).add(4)),tb=r=>he(Qu,he(r,he(r,he(-3,r).add(3)).add(3)).add(1)),Mh=r=>he(Qu,qu(r,3)),Fp=r=>eb(r).add(Ch(r)),Dp=r=>tb(r).add(Mh(r)),Lp=r=>jt(-1,Ch(r).div(eb(r).add(Ch(r)))),Op=r=>jt(1,Mh(r).div(tb(r).add(Mh(r)))),Up=(r,e,t)=>{const n=r.uvNode,i=he(n,e.zw).add(.5),s=di(i),o=fr(i),a=Fp(o.x),u=Dp(o.x),l=Lp(o.x),c=Op(o.x),h=Lp(o.y),d=Op(o.y),f=re(s.x.add(l),s.y.add(h)).sub(.5).mul(e.xy),p=re(s.x.add(c),s.y.add(h)).sub(.5).mul(e.xy),g=re(s.x.add(l),s.y.add(d)).sub(.5).mul(e.xy),_=re(s.x.add(c),s.y.add(d)).sub(.5).mul(e.xy),m=Fp(o.y).mul(jt(a.mul(r.sample(f).level(t)),u.mul(r.sample(p).level(t)))),y=Dp(o.y).mul(jt(a.mul(r.sample(g).level(t)),u.mul(r.sample(_).level(t))));return m.add(y)},OC=P(([r,e])=>{const t=re(r.size(Ae(e))),n=re(r.size(Ae(e.add(1)))),i=On(1,t),s=On(1,n),o=Up(r,q(i,t),di(e)),a=Up(r,q(s,n),Ad(e));return fr(e).mix(o,a)}),Ip=P(([r,e,t,n,i])=>{const s=D(K_(e.negate(),tn(r),On(1,n))),o=D(dr(i[0].xyz),dr(i[1].xyz),dr(i[2].xyz));return tn(s).mul(t.mul(o))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),UC=P(([r,e])=>r.mul($r(e.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),IC=ky(),kC=qE(),kp=P(([r,e,t],{material:n})=>{const s=(n.side===yt?IC:kC).sample(r.mul(Ol.zw).add(Ol.xy).div(wo)),o=cr(Ol.z).mul(UC(e,t));return OC(s,o)}),Gp=P(([r,e,t])=>(Me(t.notEqual(0),()=>{const n=Rd(e).negate().div(t);return wd(n.negate().mul(r))}),D(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),GC=P(([r,e,t,n,i,s,o,a,u,l,c,h,d,f,p])=>{let g,_;if(p){g=q().toVar(),_=D().toVar();const x=c.sub(1).mul(p.mul(.025)),v=D(c.sub(x),c,c.add(x));Yt({start:0,end:3},({i:w})=>{const R=v.element(w),F=Ip(r,e,h,R,a),M=o.add(F),O=l.mul(u.mul(q(M,1))),U=re(O.xy.div(O.w)).toVar();U.addAssign(1),U.divAssign(2),U.assign(re(U.x,U.y.oneMinus()));const X=kp(U,t,R);g.element(w).assign(X.element(w)),g.a.addAssign(X.a),_.element(w).assign(n.element(w).mul(Gp(dr(F),d,f).element(w)))}),g.a.divAssign(3)}else{const x=Ip(r,e,h,c,a),v=o.add(x),w=l.mul(u.mul(q(v,1))),R=re(w.xy.div(w.w)).toVar();R.addAssign(1),R.divAssign(2),R.assign(re(R.x,R.y.oneMinus())),g=kp(R,t,c),_=n.mul(Gp(dr(x),d,f))}const m=_.rgb.mul(g.rgb),y=r.dot(e).clamp(),b=D(Jy({dotNV:y,specularColor:i,specularF90:s,roughness:t})),T=_.r.add(_.g,_.b).div(3);return q(b.oneMinus().mul(m),g.a.oneMinus().mul(T).oneMinus())}),VC=nt(3.2404542,-1.5371385,-.4985314,-.969266,1.8760108,.041556,.0556434,-.2040259,1.0572252),$C=r=>{const e=r.sqrt();return D(1).add(e).div(D(1).sub(e))},Vp=(r,e)=>r.sub(e).div(r.add(e)).pow2(),zC=(r,e)=>{const t=r.mul(2*Math.PI*1e-9),n=D(54856e-17,44201e-17,52481e-17),i=D(1681e3,1795300,2208400),s=D(43278e5,93046e5,66121e5),o=N(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(t.mul(2239900).add(e.x).cos()).mul(t.pow2().mul(-45282e5).exp());let a=n.mul(s.mul(2*Math.PI).sqrt()).mul(i.mul(t).add(e).cos()).mul(t.pow2().negate().mul(s).exp());return a=D(a.x.add(o),a.y,a.z).div(10685e-11),VC.mul(a)},$p=P(({outsideIOR:r,eta2:e,cosTheta1:t,thinFilmThickness:n,baseF0:i})=>{const s=Se(r,e,Un(0,.03,n)),a=r.div(s).pow2().mul(t.pow2().oneMinus()).oneMinus();Me(a.lessThan(0),()=>D(1));const u=a.sqrt(),l=Vp(s,r),c=fi({f0:l,f90:1,dotVH:t}),h=c.oneMinus(),d=s.lessThan(r).select(Math.PI,0),f=N(Math.PI).sub(d),p=$C(i.clamp(0,.9999)),g=Vp(p,s.toVec3()),_=fi({f0:g,f90:1,dotVH:u}),m=D(p.x.lessThan(s).select(Math.PI,0),p.y.lessThan(s).select(Math.PI,0),p.z.lessThan(s).select(Math.PI,0)),y=s.mul(n,u,2),b=D(f).add(m),T=c.mul(_).clamp(1e-5,.9999),x=T.sqrt(),v=h.pow2().mul(_).div(D(1).sub(T)),R=c.add(v).toVar(),F=v.sub(h).toVar();return Yt({start:1,end:2,condition:"<=",name:"m"},({m:M})=>{F.mulAssign(x);const O=zC(N(M).mul(y),N(M).mul(b)).mul(2);R.addAssign(F.mul(O))}),R.max(D(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),Os=P(({normal:r,viewDir:e,roughness:t})=>{const n=r.dot(e).saturate(),i=t.mul(t),s=t.add(.1).reciprocal(),o=N(-1.9362).add(t.mul(1.0678)).add(i.mul(.4573)).sub(s.mul(.8469)),a=N(-.6014).add(t.mul(.5538)).sub(i.mul(.467)).sub(s.mul(.1255));return o.mul(n).add(a).exp().saturate()}),Us=D(.04),ua=N(1);class nb extends Yu{constructor(e=!1,t=!1,n=!1,i=!1,s=!1,o=!1,a=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=i,this.transmission=s,this.dispersion=o,this.retroreflection=a,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null,this.dfg=null,this.multiScatteringCompensation=null}start(e){if(this.clearcoat===!0&&(this.clearcoatRadiance=D().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=D().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=D().toVar("clearcoatSpecularIndirect")),this.sheen===!0&&(this.sheenSpecularDirect=D().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=D().toVar("sheenSpecularIndirect")),this.iridescence===!0){const i=ge.dot(Ce).clamp(),s=$p({outsideIOR:N(1),eta2:ph,cosTheta1:i,thinFilmThickness:gh,baseF0:En}),o=$p({outsideIOR:N(1),eta2:ph,cosTheta1:i,thinFilmThickness:gh,baseF0:xe.rgb});this.iridescenceFresnel=Se(s,o,hi),this.iridescenceF0Dielectric=Pp({f:s,f90:1,dotVH:i}),this.iridescenceF0Metallic=Pp({f:o,f90:1,dotVH:i})}if(this.transmission===!0){const i=Ro,s=mN.sub(Ro).normalize(),o=xs,a=e.context;a.backdrop=GC(o,s,hn,zi,Mr,Xn,i,bi,bs,mn,Xa,O_,I_,U_,this.dispersion?k_:null),a.backdropAlpha=yh,xe.a.mulAssign(Se(1,a.backdrop.a,yh))}const t=ge.dot(Ce).clamp();this.dfg=Zy({roughness:hn,dotNV:t}).toConst("dfg");const n=this.dfg.x.add(this.dfg.y);this.multiScatteringCompensation=Mr.mul(n.reciprocal().sub(1)).add(1).toConst("multiScatteringCompensation"),super.start(e)}computeMultiscattering(e,t,n,i,s=null){const o=this.dfg,a=s?Td.mix(i,s):i,u=a.mul(o.x).add(n.mul(o.y)),c=o.x.add(o.y).oneMinus(),h=a.add(a.oneMinus().mul(.047619)),d=u.mul(h).div(c.mul(h).oneMinus());e.addAssign(u),t.addAssign(d.mul(c))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const s=ge.dot(e).clamp().mul(t).toVar();if(this.sheen===!0){this.sheenSpecularDirect.addAssign(s.mul(DC({lightDirection:e})));const c=Os({normal:ge,viewDir:Ce,roughness:si}),h=Os({normal:ge,viewDir:e,roughness:si}),d=$t.r.max($t.g).max($t.b).mul(c.max(h)).oneMinus();s.mulAssign(d)}if(this.clearcoat===!0){const h=ui.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(h.mul(Vl({lightDirection:e,f0:Us,f90:ua,roughness:uo,normalView:ui})))}const o=e.add(Ce).normalize(),a=Ce.dot(o).clamp();let u=fi({f0:En,f90:Xn,dotVH:a}),l=Vl({lightDirection:e,f0:Mr,f90:1,roughness:hn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});if(this.retroreflection===!0){const c=Ce.negate().reflect(ge),h=e.add(c).normalize(),d=c.dot(h).clamp(),f=fi({f0:En,f90:Xn,dotVH:d}),p=Vl({lightDirection:e,viewDirection:c,f0:Mr,f90:1,roughness:hn,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});u=Se(u,f,xu.clamp()),l=Se(l,p,xu.clamp())}n.directDiffuse.addAssign(s.mul(ds({diffuseColor:zi})).mul(u.oneMinus())),n.directSpecular.addAssign(s.mul(l).mul(this.multiScatteringCompensation))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:i,reflectedLight:s,ltc_1:o,ltc_2:a}){const u=t.add(n).sub(i),l=t.sub(n).sub(i),c=t.sub(n).add(i),h=t.add(n).add(i),d=ge,f=Ce,p=Xe.toVar(),g=Bp({N:d,V:f,roughness:hn}),_=o.sample(g).toVar(),m=a.sample(g).toVar(),y=nt(D(_.x,0,_.y),D(0,1,0),D(_.z,0,_.w)).toVar(),b=Mr.mul(m.x).add(Xn.sub(Mr).mul(m.y)).toVar();if(s.directSpecular.addAssign(e.mul(b).mul($l({N:d,V:f,P:p,mInv:y,p0:u,p1:l,p2:c,p3:h}))),s.directDiffuse.addAssign(e.mul(zi).mul($l({N:d,V:f,P:p,mInv:nt(1,0,0,0,1,0,0,0,1),p0:u,p1:l,p2:c,p3:h}))),this.clearcoat===!0){const T=ui,x=Bp({N:T,V:f,roughness:uo}),v=o.sample(x),w=a.sample(x),R=nt(D(v.x,0,v.y),D(0,1,0),D(v.z,0,v.w)),F=Us.mul(w.x).add(ua.sub(Us).mul(w.y));this.clearcoatSpecularDirect.addAssign(e.mul(F).mul($l({N:T,V:f,P:p,mInv:R,p0:u,p1:l,p2:c,p3:h})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context,i=D().toVar(),s=D().toVar();this.computeMultiscattering(i,s,Xn,En,this.iridescenceF0Dielectric);const o=t.mul(ds({diffuseColor:zi})).mul(i.add(s).oneMinus()).toVar();if(this.sheen===!0){const a=Os({normal:ge,viewDir:Ce,roughness:si});this.sheenSpecularIndirect.addAssign(t.mul($t,a,1/Math.PI));const u=$t.r.max($t.g).max($t.b).mul(a).oneMinus();o.mulAssign(u)}n.indirectDiffuse.addAssign(o)}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:i}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(n.mul($t,Os({normal:ge,viewDir:Ce,roughness:si}),1/Math.PI)),this.clearcoat===!0){const _=ui.dot(Ce).clamp(),m=Jy({dotNV:_,specularColor:Us,specularF90:ua,roughness:uo});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(m))}const s=D().toVar("singleScatteringDielectric"),o=D().toVar("multiScatteringDielectric"),a=D().toVar("singleScatteringMetallic"),u=D().toVar("multiScatteringMetallic");this.computeMultiscattering(s,o,Xn,En,this.iridescenceF0Dielectric),this.computeMultiscattering(a,u,Xn,xe.rgb,this.iridescenceF0Metallic);const l=Se(s,a,hi),c=Se(o,u,hi),h=s.add(o),d=zi.mul(h.oneMinus()),f=n.mul(1/Math.PI),p=t.mul(l).add(c.mul(f)).toVar(),g=d.mul(f).toVar();if(this.sheen===!0){const _=Os({normal:ge,viewDir:Ce,roughness:si}),m=$t.r.max($t.g).max($t.b).mul(_).oneMinus();p.mulAssign(m),g.mulAssign(m)}i.indirectSpecular.addAssign(p),i.indirectDiffuse.addAssign(g)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,s=ge.dot(Ce).clamp().add(t),o=hn.mul(-16).oneMinus().negate().exp2(),a=t.sub(s.pow(o).oneMinus()).clamp();this.clearcoat===!0&&this.clearcoatSpecularIndirect.mulAssign(t),this.sheen===!0&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(a)}finish({context:e}){const{outgoingLight:t}=e;if(this.clearcoat===!0){const n=ui.dot(Ce).clamp(),i=fi({dotVH:n,f0:Us,f90:ua}),s=t.mul(fh.mul(i).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(fh));t.assign(s)}if(this.sheen===!0){const n=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(n)}}}const WC=2.399963229728653,zp=N(1),Ph=N(-2),la=N(.8),zl=N(-1),ca=N(.4),Wl=N(2),ha=N(.305),Hl=N(3),Wp=N(.21),HC=N(4),Hp=N(4),jC=N(16),qC=P(([r])=>{const e=D(Ct(r)).toVar(),t=N(-1).toVar();return Me(e.x.greaterThan(e.z),()=>{Me(e.x.greaterThan(e.y),()=>{t.assign(Zt(r.x.greaterThan(0),0,3))}).Else(()=>{t.assign(Zt(r.y.greaterThan(0),1,4))})}).Else(()=>{Me(e.z.greaterThan(e.y),()=>{t.assign(Zt(r.z.greaterThan(0),2,5))}).Else(()=>{t.assign(Zt(r.y.greaterThan(0),1,4))})}),t}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),XC=P(([r,e])=>{const t=re().toVar();return Me(e.equal(0),()=>{t.assign(re(r.z,r.y).div(Ct(r.x)))}).ElseIf(e.equal(1),()=>{t.assign(re(r.x.negate(),r.z.negate()).div(Ct(r.y)))}).ElseIf(e.equal(2),()=>{t.assign(re(r.x.negate(),r.y).div(Ct(r.z)))}).ElseIf(e.equal(3),()=>{t.assign(re(r.z.negate(),r.y).div(Ct(r.x)))}).ElseIf(e.equal(4),()=>{t.assign(re(r.x.negate(),r.z).div(Ct(r.y)))}).Else(()=>{t.assign(re(r.x,r.y).div(Ct(r.z)))}),he(.5,t.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),KC=P(([r])=>{const e=N(0).toVar();return Me(r.greaterThanEqual(la),()=>{e.assign(zp.sub(r).mul(zl.sub(Ph)).div(zp.sub(la)).add(Ph))}).ElseIf(r.greaterThanEqual(ca),()=>{e.assign(la.sub(r).mul(Wl.sub(zl)).div(la.sub(ca)).add(zl))}).ElseIf(r.greaterThanEqual(ha),()=>{e.assign(ca.sub(r).mul(Hl.sub(Wl)).div(ca.sub(ha)).add(Wl))}).ElseIf(r.greaterThanEqual(Wp),()=>{e.assign(ha.sub(r).mul(HC.sub(Hl)).div(ha.sub(Wp)).add(Hl))}).Else(()=>{e.assign(N(-2).mul(cr(he(1.16,r))))}),e}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),YC=P(([r,e,t,n,i,s])=>{const o=N(t),a=D(e),u=$r(KC(o),Ph,s),l=fr(u),c=di(u),h=D(fs(r,a,c,n,i,s)).toVar();return Me(l.notEqual(0),()=>{const d=D(fs(r,a,c.add(1),n,i,s)).toVar();h.assign(Se(h,d,l))}),h}),fs=P(([r,e,t,n,i,s])=>{const o=N(t).toVar(),a=D(e),u=N(qC(a)).toVar(),l=N(ot(Hp.sub(o),0)).toVar();o.assign(ot(o,Hp));const c=N(To(o)).toVar(),h=re(XC(a,u).mul(c.sub(2)).add(1)).toVar();return Me(u.greaterThan(2),()=>{h.y.addAssign(c),u.subAssign(3)}),h.x.addAssign(u.mul(c)),h.x.addAssign(l.mul(he(3,jC))),h.y.addAssign(he(4,To(s).sub(c))),h.x.mulAssign(n),h.y.mulAssign(i),r.sample(h).grad(re(),re())}),QC=P(({SAMPLES:r,sigma:e,outputDirection:t,mipInt:n,envMap:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const u=D(0).toVar();return Me(e.equal(0),()=>{u.assign(fs(i,t,n,s,o,a))}).Else(()=>{const l=Zt(Ct(t.z).lessThan(.999),D(0,0,1),D(1,0,0)),c=tn(Vr(l,t)).toVar(),h=Vr(t,c).toVar(),d=_i(e.mul(3),Math.PI),f=wd(d.mul(d).mul(-.5).div(e.mul(e))).oneMinus().toVar(),p=N(0).toVar();Yt({start:Ae(0),end:r},({i:g})=>{const _=N(g).add(.5).div(N(r)),m=e.mul(hr(Rd(_.mul(f).oneMinus()).mul(-2))).toVar(),y=N(g).mul(WC).toVar(),b=c.mul(dn(y)).add(h.mul(Tt(y))),T=t.mul(dn(m)).add(b.mul(Tt(m))),x=Tt(m).div(m).toVar();u.addAssign(fs(i,T,n,s,o,a).mul(x)),p.addAssign(x)}),u.divAssign(p)}),q(u,1)}),ZC=P(([r])=>{const e=He(r).toVar();return e.assign(e.shiftLeft(He(16)).bitOr(e.shiftRight(He(16)))),e.assign(e.bitAnd(He(1431655765)).shiftLeft(He(1)).bitOr(e.bitAnd(He(2863311530)).shiftRight(He(1)))),e.assign(e.bitAnd(He(858993459)).shiftLeft(He(2)).bitOr(e.bitAnd(He(3435973836)).shiftRight(He(2)))),e.assign(e.bitAnd(He(252645135)).shiftLeft(He(4)).bitOr(e.bitAnd(He(4042322160)).shiftRight(He(4)))),e.assign(e.bitAnd(He(16711935)).shiftLeft(He(8)).bitOr(e.bitAnd(He(4278255360)).shiftRight(He(8)))),N(e).mul(23283064365386963e-26)}),JC=P(([r,e])=>re(N(r).div(N(e)),ZC(r))),e1=P(([r,e,t])=>{const n=t.mul(t).toConst(),i=D(1,0,0).toConst(),s=Vr(e,i).toConst(),o=hr(r.x).toConst(),a=he(2,3.14159265359).mul(r.y).toConst(),u=o.mul(dn(a)).toConst(),l=o.mul(Tt(a)).toVar(),c=he(.5,e.z.add(1)).toConst();l.assign(c.oneMinus().mul(hr(u.mul(u).oneMinus())).add(c.mul(l)));const h=i.mul(u).add(s.mul(l)).add(e.mul(hr(ot(0,u.mul(u).add(l.mul(l)).oneMinus()))));return tn(D(n.mul(h.x),n.mul(h.y),ot(0,h.z)))}),t1=P(({roughness:r,mipInt:e,envMap:t,N_immutable:n,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const u=D(n).toVar(),l=D(0).toVar(),c=N(0).toVar();return Me(r.lessThan(.001),()=>{l.assign(fs(t,u,e,s,o,a))}).Else(()=>{const h=Zt(Ct(u.z).lessThan(.999),D(0,0,1),D(1,0,0)),d=tn(Vr(h,u)).toVar(),f=Vr(u,d).toVar();Yt({start:He(0),end:i},({i:p})=>{const g=JC(p,i),_=e1(g,D(0,0,1),r),m=tn(d.mul(_.x).add(f.mul(_.y)).add(u.mul(_.z))),y=tn(m.mul(yi(u,m).mul(2)).sub(u)),b=ot(yi(u,y),0);Me(b.greaterThan(0),()=>{const T=fs(t,y,e,s,o,a);l.addAssign(T.mul(b)),c.addAssign(b)})}),Me(c.greaterThan(0),()=>{l.assign(l.div(c))})}),q(l,1)}),Xi=4,n1=6,r1=20,i1=256,Is=new rd(-1,1,1,-1,0,1),s1=new yo(90,1),jp=new Dt;let jl=null,ql=0,Xl=0;const o1=new z,Zr=new z,Su=new WeakMap,a1=[3,1,5,0,4,2],Zu=Jt("outputDirection").normalize();class u1{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,i=100,s={}){const{size:o=256,position:a=o1,renderTarget:u=null}=s;if(this._setSize(o),this._hasInitialized===!1)throw new Error('THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.');jl=this._renderer.getRenderTarget(),ql=this._renderer.getActiveCubeFace(),Xl=this._renderer.getActiveMipmapLevel();const l=u||this._allocateTarget(!0);return this._init(l),this._sceneToCubeUV(e,n,i,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,i=100,s={}){return Fe('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,n,i,s)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1)throw new Error('THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Fe('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(this._hasInitialized===!1)throw new Error('THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Fe('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Xp(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Kp(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===cu||e.mapping===hu?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(jl,ql,Xl),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),jl=this._renderer.getRenderTarget(),ql=this._renderer.getActiveCubeFace(),Xl=this._renderer.getActiveMipmapLevel();const n=t||this._allocateTarget(!1);return this._init(n),this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTarget(e){const t=3*Math.max(this._cubeSize,112),n=4*this._cubeSize;return qp(t,n,e)}_init(e){if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=qp(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=l1(t)),this._blurMaterial=c1(t,e.width,e.height),this._ggxMaterial=h1(t,e.width,e.height)}}async _compileMaterial(e){const t=new yn(new Eo,e);await this._renderer.compile(t,Is)}_sceneToCubeUV(e,t,n,i,s){const o=s1;o.near=t,o.far=n;const a=[1,1,1,1,-1,1],u=[1,-1,1,-1,1,-1],l=this._renderer,c=l.autoClear;l.getClearColor(jp),l.autoClear=!1,this._backgroundBox===null&&(this._backgroundBox=new yn(new jm,new Br({name:"PMREM.Background",side:yt,depthWrite:!1,depthTest:!1})));const h=this._backgroundBox,d=h.material;let f=!1;const p=e.background;p?p.isColor&&(d.color.copy(p),e.background=null,f=!0):(d.color.copy(jp),f=!0),l.setRenderTarget(i),l.clear(),f&&l.render(h,o);for(let g=0;g<6;g++){const _=g%3;_===0?(o.up.set(0,a[g],0),o.position.set(s.x,s.y,s.z),o.lookAt(s.x+u[g],s.y,s.z)):_===1?(o.up.set(0,0,a[g]),o.position.set(s.x,s.y,s.z),o.lookAt(s.x,s.y+u[g],s.z)):(o.up.set(0,a[g],0),o.position.set(s.x,s.y,s.z),o.lookAt(s.x,s.y,s.z+u[g]));const m=this._cubeSize;this._setViewport(i,_*m,g>2?m:0,m,m),l.render(e,o)}l.autoClear=c,e.background=p}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===cu||e.mapping===hu;i?this._cubemapMaterial===null&&(this._cubemapMaterial=Xp(e)):this._equirectMaterial===null&&(this._equirectMaterial=Kp(e));const s=i?this._cubemapMaterial:this._equirectMaterial;s.fragmentNode.value=e;const o=this._lodMeshes[0];o.material=s;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(o,Is)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let s=1;s<i;s++)this._applyGGXFilter(e,s-1,s);t.autoClear=n}_applyGGXFilter(e,t,n){const i=this._renderer,s=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;const u=Su.get(o),l=n/(this._lodMeshes.length-1),c=t/(this._lodMeshes.length-1),h=Math.sqrt(l*l-c*c),d=l*1.25,f=h*d,{_lodMax:p}=this,g=this._sizeLods[n],_=3*g*(n>p-Xi?n-p+Xi:0),m=4*(this._cubeSize-g);e.texture.frame=(e.texture.frame||0)+1,u.envMap.value=e.texture,u.roughness.value=f,u.mipInt.value=p-t,this._setViewport(s,_,m,3*g,2*g),i.setRenderTarget(s),i.render(a,Is),s.texture.frame=(s.texture.frame||0)+1,u.envMap.value=s.texture,u.roughness.value=0,u.mipInt.value=p-n,this._setViewport(e,_,m,3*g,2*g),i.setRenderTarget(e),i.render(a,Is)}_blur(e,t,n,i){const s=this._pingPongRenderTarget,o=Math.min(i,Math.PI)/Math.SQRT2;this._blurPass(e,s,t,n,o),this._blurPass(s,e,n,n,o)}_blurPass(e,t,n,i,s){const o=this._renderer,a=this._blurMaterial,u=this._lodMeshes[i];u.material=a;const l=Su.get(a);e.texture.frame=(e.texture.frame||0)+1,l.envMap.value=e.texture,l.sigma.value=s,l.mipInt.value=this._lodMax-n;const c=this._sizeLods[i],h=3*c*(i>this._lodMax-Xi?i-this._lodMax+Xi:0),d=4*(this._cubeSize-c);this._setViewport(t,h,d,3*c,2*c),o.setRenderTarget(t),o.render(u,Is)}_setViewport(e,t,n,i,s){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-s-n,i,s),e.scissor.set(t,e.height-s-n,i,s)):(e.viewport.set(t,n,i,s),e.scissor.set(t,n,i,s))}}function l1(r){const e=[],t=[];let n=r;const i=r-Xi+1+n1;for(let s=0;s<i;s++){const o=Math.pow(2,n);e.push(o);const a=1/(o-2),u=-a,l=1+a,c=[u,u,l,u,l,l,u,u,l,l,u,l],h=6,d=6,f=3,p=new Float32Array(f*d*h),g=new Float32Array(f*d*h);for(let m=0;m<h;m++){const y=m%3*2/3-1,b=m>2?0:-1,T=[y,b,0,y+2/3,b,0,y+2/3,b+1,0,y,b,0,y+2/3,b+1,0,y,b+1,0],x=a1[m];p.set(T,f*d*x);for(let v=0;v<d;v++){const w=c[v*2]*2-1,R=c[v*2+1]*2-1;x===0?Zr.set(1,R,w):x===1?Zr.set(-w,1,-R):x===2?Zr.set(-w,R,1):x===3?Zr.set(-1,R,-w):x===4?Zr.set(-w,-1,R):Zr.set(w,R,-1),Zr.toArray(g,(x*d+v)*f)}}const _=new Eo;_.setAttribute("position",new Rc(p,f)),_.setAttribute("outputDirection",new Rc(g,f)),t.push(new yn(_,null)),n>Xi&&n--}return{lodMeshes:t,sizeLods:e}}function qp(r,e,t){const n={magFilter:Rt,minFilter:Rt,generateMipmaps:!1,type:wt,format:Qt,colorSpace:zv,depthBuffer:t},i=new Ti(r,e,n);return i.texture.mapping=ru,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function Ju(r){const e=new Ke;return e.depthTest=!1,e.depthWrite=!1,e.blending=ur,e.name=`PMREM_${r}`,e}function c1(r,e,t){const n=ve(),i=ne(0),s=ne(0),o=N(1/e),a=N(1/t),u=N(r),l={envMap:n,sigma:i,mipInt:s,CUBEUV_TEXEL_WIDTH:o,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:u},c=Ju("blur");return c.fragmentNode=QC({...l,outputDirection:Zu,SAMPLES:Ae(r1)}),Su.set(c,l),c}function h1(r,e,t){const n=ve(),i=ne(0),s=ne(0),o=N(1/e),a=N(1/t),u=N(r),l={envMap:n,roughness:i,mipInt:s,CUBEUV_TEXEL_WIDTH:o,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:u},c=Ju("ggx");return c.fragmentNode=t1({...l,N_immutable:Zu,GGX_SAMPLES:He(i1)}),Su.set(c,l),c}function Xp(r){const e=Ju("cubemap");return e.fragmentNode=Mt(r,Zu),e}function Kp(r){const e=Ju("equirect");return e.fragmentNode=ve(r,Hy(Zu),0),e}const Yp=new WeakMap;function d1(r){const e=Math.log2(r)-2,t=1/r;return{texelWidth:1/(3*Math.max(Math.pow(2,e),112)),texelHeight:t,maxMip:e}}function f1(r,e,t){const n=p1(e);let i=n.get(r);if((i!==void 0?i.pmremVersion:-1)!==r.pmremVersion){const o=r.image;if(r.isCubeTexture)if(m1(o))i=t.fromCubemap(r,i);else return null;else if(_1(o))i=t.fromEquirectangular(r,i);else return null;if(i.pmremVersion=r.pmremVersion,n.has(r)===!1){const a=()=>{r.removeEventListener("dispose",a);const u=n.get(r);u!==void 0&&(u.dispose(),n.delete(r))};r.addEventListener("dispose",a)}n.set(r,i)}return i.texture}function p1(r){let e=Yp.get(r);return e===void 0&&(e=new WeakMap,Yp.set(r,e)),e}class g1 extends ut{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;const i=new od;i.isRenderTargetTexture=!0,this._texture=ve(i),this._width=ne(0),this._height=ne(0),this._maxMip=ne(0),this.updateBeforeType=ie.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=d1(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const n=t?t.pmremVersion:-1,i=this._value;n!==i.pmremVersion&&(i.isPMREMTexture===!0||i.mapping===ru?t=i:t=f1(i,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new u1(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this,e)),t=this._pmrem===null||this._pmrem.isRenderTargetTexture?vh.mul(D(t.x,t.y.negate(),t.z)):vh.mul(t);let n=this.levelNode;return n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),YC(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}}function m1(r){if(r==null)return!1;let e=0;const t=6;for(let n=0;n<t;n++)r[n]!==void 0&&e++;return e===t}function _1(r){return r==null?!1:r.height>0}const rb=ke(g1).setParameterLength(1,3),Qp=new WeakMap;class y1 extends vs{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const c=n.isTextureNode?n.value:t[n.property],h=this._getPMREMNodeCache(e.renderer);let d=h.get(c);d===void 0&&(d=rb(c),h.set(c,d)),n=d}const s=t.useAnisotropy===!0||t.anisotropy>0?VN:ge;let o=qi(n.context(Zp(hn,s)).mul(oa));if(t.useRetroreflection===!0||t.retroreflectivity>0){const c=qi(n.context(b1(hn,s)).mul(oa));o=xu.clamp().mix(o,c)}const a=n.context(x1(xs)).mul(Math.PI).mul(oa),u=qi(a);e.context.radiance.addAssign(o),e.context.iblIrradiance.addAssign(u);const l=e.context.lightingModel.clearcoatRadiance;if(l){const c=n.context(Zp(uo,ui)).mul(oa),h=qi(c);l.addAssign(h)}}_getPMREMNodeCache(e){let t=Qp.get(e);return t===void 0&&(t=new WeakMap,Qp.set(e,t)),t}}const Zp=(r,e)=>{let t=null;return{getUV:()=>(t===null&&(t=Ce.negate().reflect(e),t=Nd(r).mix(t,e).normalize(),t=t.transformDirection(Ku)),t),getTextureLevel:()=>r}},b1=(r,e)=>{let t=null;return{getUV:()=>(t===null&&(t=Nd(r).mix(Ce,e).normalize(),t=t.transformDirection(Ku)),t),getTextureLevel:()=>r}},x1=r=>({getUV:()=>r,getTextureLevel:()=>N(1)}),v1=new ev;class ib extends Ke{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(v1),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new y1(t):null}setupLightingModel(){return new nb}setupSpecular(){const e=Se(D(.04),xe.rgb,hi);En.assign(D(.04)),Mr.assign(e),Xn.assign(1)}setupVariants(){const e=this.metalnessNode?N(this.metalnessNode):nE;hi.assign(e);let t=this.roughnessNode?N(this.roughnessNode):tE;t=Qy({roughness:t}),hn.assign(t),this.setupSpecular(),zi.assign(xe.rgb.mul(e.oneMinus()))}}const T1=new tv;class S1 extends ib{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.retroreflectivityNode=null,this.anisotropyNode=null,this.setDefaultValues(T1),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||this.clearcoatNode!==null}get useIridescence(){return this.iridescence>0||this.iridescenceNode!==null}get useSheen(){return this.sheen>0||this.sheenNode!==null}get useAnisotropy(){return this.anisotropy>0||this.anisotropyNode!==null}get useTransmission(){return this.transmission>0||this.transmissionNode!==null}get useDispersion(){return this.dispersion>0||this.dispersionNode!==null}get useRetroreflection(){return this.retroreflectivity>0||this.retroreflectivityNode!==null}setupSpecular(){const e=this.iorNode?N(this.iorNode):mE,t=this.specularColorNode?D(this.specularColorNode):eE,n=this.specularIntensityNode?N(this.specularIntensityNode):JN;Xa.assign(e),En.assign(_i(X_(Xa.sub(1).div(Xa.add(1))).mul(t),D(1)).mul(n)),Mr.assign(Se(En,xe.rgb,hi)),Xn.assign(Se(n,1,hi))}setupLightingModel(){return new nb(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useRetroreflection)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const t=this.clearcoatNode?N(this.clearcoatNode):iE,n=this.clearcoatRoughnessNode?N(this.clearcoatRoughnessNode):sE;fh.assign(t),uo.assign(Qy({roughness:n}))}if(this.useSheen){const t=this.sheenNode?D(this.sheenNode):uE,n=this.sheenRoughnessNode?N(this.sheenRoughnessNode):lE;$t.assign(t),si.assign(n)}if(this.useRetroreflection){const t=this.retroreflectivityNode?N(this.retroreflectivityNode):vE;xu.assign(t)}if(this.useIridescence){const t=this.iridescenceNode?N(this.iridescenceNode):hE,n=this.iridescenceIORNode?N(this.iridescenceIORNode):dE,i=this.iridescenceThicknessNode?N(this.iridescenceThicknessNode):fE;Td.assign(t),ph.assign(n),gh.assign(i)}if(this.useAnisotropy){const t=(this.anisotropyNode?re(this.anisotropyNode):cE).toVar();ni.assign(t.length()),Me(ni.equal(0),()=>{t.assign(re(1,0))}).Else(()=>{t.divAssign(re(ni)),ni.assign(ni.saturate())}),mh.assign(ni.pow2().mix(hn.pow2(),1)),qa.assign(eo[0].mul(t.x).add(eo[1].mul(t.y))),Ji.assign(eo[1].mul(t.x).sub(eo[0].mul(t.y)))}if(this.useTransmission){const t=this.transmissionNode?N(this.transmissionNode):pE,n=this.thicknessNode?N(this.thicknessNode):gE,i=this.attenuationDistanceNode?N(this.attenuationDistanceNode):_E,s=this.attenuationColorNode?D(this.attenuationColorNode):yE;if(yh.assign(t),O_.assign(n),U_.assign(i),I_.assign(s),this.useDispersion){const o=this.dispersionNode?N(this.dispersionNode):xE;k_.assign(o)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?D(this.clearcoatNormalNode):oE}setup(e){e.context.setupClearcoatNormal=()=>ts(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}}const w1=P(({normal:r,lightDirection:e,builder:t})=>{const n=r.dot(e),i=re(n.mul(.5).add(.5),0);if(t.material.gradientMap){const s=Dr("gradientMap","texture").context({getUV:()=>i});return D(s.r)}else{const s=i.fwidth().mul(.5);return Se(D(.7),D(1),Un(N(.7).sub(s.x),N(.7).add(s.x),i.x))}});class R1 extends Yu{direct({lightDirection:e,lightColor:t,reflectedLight:n},i){const s=w1({normal:ge,lightDirection:e,builder:i}).mul(t);n.directDiffuse.addAssign(s.mul(ds({diffuseColor:xe.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(ds({diffuseColor:xe}))),i.indirectDiffuse.mulAssign(t)}}const A1=new nv;class N1 extends Ke{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(A1),this.setValues(e)}setupLightingModel(){return new R1}}const E1=P(()=>{const r=D(Ce.z,0,Ce.x.negate()).normalize(),e=Ce.cross(r);return re(r.dot(ge),e.dot(ge)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),C1=new iv;class M1 extends Ke{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(C1),this.setValues(e)}setupVariants(e){const t=E1;let n;e.material.matcap?n=Dr("matcap","texture").context({getUV:()=>t}):n=D(Se(.2,.8,t.y)),xe.rgb.mulAssign(n.rgb)}}class P1 extends ut{static get type(){return"RotateNode"}constructor(e,t,n="XYZ"){super(),this.positionNode=e,this.rotationNode=t,this._order=n}customCacheKey(){return wi(this._order)}setOrder(e){return this._order=e,this}getOrder(){return this._order}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if(this.getNodeType(e)==="vec2"){const s=t.cos(),o=t.sin();return vd(s,o,o.negate(),s).mul(n)}else{const s=t,o=this._order,a=Gr(q(1,0,0,0),q(0,dn(s.x),Tt(s.x),0),q(0,Tt(s.x).negate(),dn(s.x),0),q(0,0,0,1)),u=Gr(q(dn(s.y),0,Tt(s.y).negate(),0),q(0,1,0,0),q(Tt(s.y),0,dn(s.y),0),q(0,0,0,1)),l=Gr(q(dn(s.z),Tt(s.z),0,0),q(Tt(s.z).negate(),dn(s.z),0,0),q(0,0,1,0),q(0,0,0,1)),c={X:a,Y:u,Z:l};return c[o.charAt(0)].mul(c[o.charAt(1)]).mul(c[o.charAt(2)]).mul(q(n,1)).xyz}}serialize(e){super.serialize(e),e.order=this._order}deserialize(e){super.deserialize(e),this._order=e.order}}const sb=ke(P1).setParameterLength(2,3),B1=new av;class ob extends Ke{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(B1),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,{positionNode:i,rotationNode:s,scaleNode:o,sizeAttenuation:a}=this,u=xi.mul(D(i||0));let l=re(bi[0].xyz.length(),bi[1].xyz.length());o!==null&&(l=l.mul(re(o))),n.isPerspectiveCamera&&a===!1&&(l=l.mul(u.z.negate()));let c=vt.xy;if(t.center&&t.center.isVector2===!0){const f=kA("center","vec2",t);c=c.sub(f.sub(.5))}c=c.mul(l);const h=N(s||aE),d=sb(c,h);return q(u.xy.add(d),u.zw)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const F1=new ov,D1=new de;class L1 extends ob{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(F1),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return xi.mul(D(e||et)).xyz}setupVertexSprite(e){const{material:t,camera:n}=e,{rotationNode:i,scaleNode:s,sizeNode:o,sizeAttenuation:a}=this;let u=super.setupVertex(e);if(t.isNodeMaterial!==!0)return u;let l=o!==null?re(o):bE;l=l.mul(cy),n.isPerspectiveCamera&&a===!0&&(l=l.mul(O1.div(Xe.z.negate()))),s&&s.isNode&&(l=l.mul(re(s)));let c=vt.xy;if(i&&i.isNode){const h=N(i);c=sb(c,h)}return c=c.mul(l),c=c.div(pN.div(2)),c=c.mul(u.w),u=u.add(q(c,0,0)),u}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const O1=ne(1).setGroup(Q).onRenderUpdate(function({renderer:r}){const e=r.getSize(D1);this.value=.5*e.y});class U1 extends Yu{constructor(){super(),this.shadowNode=N(1).toVar("shadowMask")}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){xe.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(xe.rgb)}}const I1=new uv;class k1 extends Ke{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(I1),this.setValues(e)}setupLightingModel(){return new U1}}Wr("vec3");Wr("vec3");Wr("vec3");class G1{constructor(e,t,n){this.renderer=e,this.nodes=t,this.info=n,this._context=typeof self<"u"?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),this.info.autoReset===!0&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),this._animationLoop!==null&&this._animationLoop(t,n)};e()}stop(){this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),this._context!==null&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class zr{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let n=this.weakMaps[t];return n===void 0&&(n=new WeakMap,this.weakMaps[t]=n),n}get(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),t===void 0)return;return t.get(e[e.length-1])}set(e,t){let n=this._getWeakMap(e);for(let i=0;i<e.length-1;i++){const s=e[i];n.has(s)===!1&&n.set(s,new WeakMap),n=n.get(s)}return n.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),t===void 0)return!1;return t.delete(e[e.length-1])}}let V1=0;const Jp=new WeakMap;function $1(r){const e=Object.keys(r);let t=Jp.get(r.constructor);if(t===void 0){t=[];let n=Object.getPrototypeOf(r);for(;n;){const i=Object.getOwnPropertyDescriptors(n);for(const s in i){const o=i[s];o&&typeof o.get=="function"&&t.push(s)}n=Object.getPrototypeOf(n)}Jp.set(r.constructor,t)}for(let n=0;n<t.length;n++)e.push(t[n]);return e}class z1{constructor(e,t,n,i,s,o,a,u,l,c){this.id=V1++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=i,this.material=s,this.scene=o,this.camera=a,this.lightsNode=u,this.context=l,this.geometry=i.geometry,this.version=s.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=c,this.clippingContextCacheKey=c!==null?c.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this._sourceMaterial=n._currentSourceMaterial,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.onObjectDispose=()=>{this.dispose()},this.object.addEventListener("dispose",this.onObjectDispose),this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose),this._sourceMaterial!==null&&this._sourceMaterial.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return this.clippingContext===null||this.clippingContext.cacheKey===this.clippingContextCacheKey?!1:(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return this.getNodeBuilderState().hardwareClipping===!0?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(this.attributes!==null)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set,s={};for(const o of e){let a;if(o.node&&o.node.attribute?a=o.node.attribute:(a=t.getAttribute(o.name),a!==void 0&&(a.isInterleavedBufferAttribute?s[o.name]=a.data.uuid:s[o.name]=a.id)),a===void 0)continue;n.push(a);const u=a.isInterleavedBufferAttribute?a.data:a;i.add(u)}return this.attributes=n,this.attributesId=s,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:i,drawRange:s}=this,o=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),u=a!==null;let l=1;if(n.isInstancedBufferGeometry===!0?l=n.instanceCount:e.count!==void 0&&(l=Math.max(0,e.count)),l===0)return null;if(o.instanceCount=l,e.isBatchedMesh===!0)return o;let c=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(c=2);let h=s.start*c,d=(s.start+s.count)*c;i!==null&&(h=Math.max(h,i.start*c),d=Math.min(d,(i.start+i.count)*c));const f=n.attributes.position;let p=1/0;u?p=a.count:f!=null&&(p=f.count),h=Math.max(h,0),d=Math.min(d,p);const g=d-h;return g<0||g===1/0?null:(o.vertexCount=g,o.firstVertex=h,o)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const i=e.attributes[n];t+=n+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[n];t+="morph-"+n+",";for(let s=0,o=i.length;s<o;s++){const a=i[s];t+=a.id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:n}=this;let i=t.customProgramCacheKey();for(const s of $1(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(s))continue;const o=t[s];let a;if(o!==null){const u=typeof o;u==="number"?s==="side"?a=String(o):a=o!==0?"1":"0":u==="object"?(a="{",o.isTexture&&(a+=o.mapping,n.backend.isWebGPUBackend===!0&&(a+=o.magFilter,a+=o.minFilter,a+=o.wrapS,a+=o.wrapT,a+=o.wrapR)),a+="}"):a=String(o)}else a=String(o);i+=a+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",e._colorsTexture!==null&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1)&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",wi(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(this.attributes!==null){const e=this.attributesId;for(const t in e){const n=this.geometry.getAttribute(t);if(n===void 0)return!0;const i=n.isInterleavedBufferAttribute?n.data.uuid:n.id;if(e[t]!==i)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return this.material.isShadowPassMaterial!==!0&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=oo(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=oo(e,1)),e=oo(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.object.removeEventListener("dispose",this.onObjectDispose),this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this._sourceMaterial!==null&&this._sourceMaterial.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const wn=[];class W1{constructor(e,t,n,i,s,o){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=s,this.info=o,this._chainMaps={},this._renderObjects=new Set}get(e,t,n,i,s,o,a,u){const l=this.getChainMap(u);wn[0]=e,wn[1]=t,wn[2]=o,wn[3]=s;let c=l.get(wn);return c===void 0?(c=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,s,o,a,u),l.set(wn,c)):(c.camera=i,c.updateClipping(a),c.needsGeometryUpdate&&c.setGeometry(e.geometry),(c.version!==t.version||c.needsUpdate)&&(c.initialCacheKey!==c.getCacheKey()?(c.dispose(),c=this.get(e,t,n,i,s,o,a,u)):c.version=t.version)),wn[0]=null,wn[1]=null,wn[2]=null,wn[3]=null,c}getChainMap(e="default"){return this._chainMaps[e]||(this._chainMaps[e]=new zr)}dispose(){for(const e of this._renderObjects)e.dispose();this._renderObjects.clear(),this._chainMaps={}}createRenderObject(e,t,n,i,s,o,a,u,l,c,h){const d=this.getChainMap(h),f=new z1(e,t,n,i,s,o,a,u,l,c);return f.onDispose=()=>{this.pipelines.delete(f),this.bindings.deleteForRender(f),this.nodes.delete(f),d.delete(f.getChainArray()),this._renderObjects.delete(f)},this._renderObjects.add(f),f}}class jr{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const en={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},Lr=16;class H1 extends jr{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){const t=super.delete(e);return t!==null&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){const n=this.get(e);if(n.version===void 0)t===en.VERTEX?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===en.INDEX?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===en.STORAGE?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===en.INDIRECT&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),n.version=this._getBufferAttribute(e).version;else{const i=this._getBufferAttribute(e);(n.version<i.version||i.usage===rs)&&(this.backend.updateAttribute(e),n.version=i.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function ab(r){return r.index!==null?r.index.version:r.attributes.position.version}function ub(r){return r.index!==null?r.index.id:r.attributes.position.id}function eg(r){const e=[],t=r.index,n=r.attributes.position;if(t!==null){const s=t.array;for(let o=0,a=s.length;o<a;o+=3){const u=s[o+0],l=s[o+1],c=s[o+2];e.push(u,l,l,c,c,u)}}else{const s=n.array;for(let o=0,a=s.length/3-1;o<a;o+=3){const u=o+0,l=o+1,c=o+2;e.push(u,l,l,c,c,u)}}const i=new(n.count>=65535?hv:dv)(e,1);return i.version=ab(r),i.__id=ub(r),i}class j1 extends jr{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&this.get(t).initialized===!0}updateForRender(e){this.has(e)===!1&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry,n=this.get(t);n.initialized=!0,this.info.memory.geometries++;const i=()=>{this.info.memory.geometries--;const s=t.index;s!==null&&this.attributes.delete(s);for(const u of Object.values(t.attributes))this.attributes.delete(u);const o=this.wireframes.get(t);o!==void 0&&this.attributes.delete(o);const a=new Set(Object.values(e.geometry.attributes));for(const u of e.getAttributes())a.has(u)===!1&&this.attributes.delete(u);t.removeEventListener("dispose",i),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",i),this._geometryDisposeListeners.set(t,i)}updateAttributes(e){const t=e.getAttributes();for(const s of t)s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute?this.updateAttribute(s,en.STORAGE):this.updateAttribute(s,en.VERTEX);const n=this.getIndex(e);n!==null&&this.updateAttribute(n,en.INDEX);const i=e.geometry.indirect;i!==null&&this.updateAttribute(i,en.INDIRECT)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?this.attributeCall.get(e)===void 0?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:n}=e;let i=t.index;if(n.wireframe===!0){const s=this.wireframes;let o=s.get(t);o===void 0?(o=eg(t),s.set(t,o)):(o.version!==ab(t)||o.__id!==ub(t))&&(this.attributes.delete(o),o=eg(t),s.set(t,o)),i=o}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class q1{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={attributes:0,attributesSize:0,geometries:0,indexAttributes:0,indexAttributesSize:0,indirectStorageAttributes:0,indirectStorageAttributesSize:0,programs:0,programsSize:0,readbackBuffers:0,readbackBuffersSize:0,renderTargets:0,storageAttributes:0,storageAttributesSize:0,textures:0,texturesSize:0,uniformBuffers:0,uniformBuffersSize:0,total:0},this.memoryMap=new WeakMap}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):V("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap=new WeakMap}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const n=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:n,type:t}),this.memory[t]++,this.memory.total+=n,this.memory[t+"Size"]+=n}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createUniformBuffer(e){const t=e.byteLength;this.memoryMap.set(e,{size:t,type:"uniformBuffers"}),this.memory.uniformBuffers++,this.memory.total+=t,this.memory.uniformBuffersSize+=t}destroyUniformBuffer(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory.uniformBuffers--,this.memory.total-=t.size,this.memory.uniformBuffersSize-=t.size)}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===Yi||e.type===Pt?t=1:e.type===Ur||e.type===rr||e.type===wt?t=2:(e.type===gt||e.type===qe||e.type===mt)&&(t=4);let n=4;e.format===Qh||e.format===Co||e.format===Mo||e.format===Dn||e.format===Ln?n=1:e.format===pn||e.format===Po?n=2:(e.format===Bo||e.format===Zh)&&(n=3);let i=t*n;e.type===um||e.type===lm?i=2:(e.type===or||e.type===Jh||e.type===ed)&&(i=4);const s=e.width||1,o=e.height||1,a=e.isCubeTexture?6:e.depth||1;let u=s*o*a*i;const l=e.mipmaps;if(l&&l.length>0){let c=0;for(let h=0;h<l.length;h++){const d=l[h];if(d.data)c+=d.data.byteLength;else{const f=d.width||Math.max(1,s>>h),p=d.height||Math.max(1,o>>h);c+=f*p*a*i}}u+=c}else e.generateMipmaps&&(u=u*1.333);return Math.round(u)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}}class lb{constructor(e){this.cacheKey=e,this.usedTimes=0}}class X1 extends lb{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class K1 extends lb{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Y1=0;class Kl{constructor(e,t,n,i=null,s=null){this.id=Y1++,this.code=e,this.stage=t,this.name=n,this.transforms=i,this.attributes=s,this.usedTimes=0}}class Q1 extends jr{constructor(e,t,n){super(),this.backend=e,this.nodes=t,this.info=n,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t,n=null){const{backend:i}=this,s=this.get(e);if(this._needsComputeUpdate(e)){const o=s.pipeline;o&&(o.usedTimes--,o.computeProgram.usedTimes--);const a=this.nodes.getForCompute(e);let u=this.programs.compute.get(a.computeShader);u===void 0&&(o&&o.computeProgram.usedTimes===0&&this._releaseProgram(o.computeProgram),u=new Kl(a.computeShader,"compute",e.name,a.transforms,a.nodeAttributes),this.programs.compute.set(a.computeShader,u),i.createProgram(u),this.info.createProgram(u));const l=this._getComputeCacheKey(e,u);let c=this.caches.get(l);c===void 0&&(o&&o.usedTimes===0&&this._releasePipeline(o),c=this._getComputePipeline(e,u,l,t,n)),c.usedTimes++,u.usedTimes++,s.version=e.version,s.pipeline=c}return s.pipeline}getForRender(e,t=null){const{backend:n}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const s=i.pipeline;s&&(s.usedTimes--,s.vertexProgram.usedTimes--,s.fragmentProgram.usedTimes--);const o=e.getNodeBuilderState(),a=e.material?e.material.name:"";let u=this.programs.vertex.get(o.vertexShader);u===void 0&&(s&&s.vertexProgram.usedTimes===0&&this._releaseProgram(s.vertexProgram),u=new Kl(o.vertexShader,"vertex",a),this.programs.vertex.set(o.vertexShader,u),n.createProgram(u),this.info.createProgram(u));let l=this.programs.fragment.get(o.fragmentShader);l===void 0&&(s&&s.fragmentProgram.usedTimes===0&&this._releaseProgram(s.fragmentProgram),l=new Kl(o.fragmentShader,"fragment",a),this.programs.fragment.set(o.fragmentShader,l),n.createProgram(l),this.info.createProgram(l));const c=this._getRenderCacheKey(e,u,l);let h=this.caches.get(c);h===void 0?(s&&s.usedTimes===0&&this._releasePipeline(s),h=this._getRenderPipeline(e,u,l,c,t)):e.pipeline=h,h.usedTimes++,u.usedTimes++,l.usedTimes++,i.pipeline=h}return i.pipeline}isReady(e){const n=this.get(e).pipeline;if(n===void 0)return!1;const i=this.backend.get(n);return i.pipeline!==void 0&&i.pipeline!==null}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,t.usedTimes===0&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,t.computeProgram.usedTimes===0&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,t.vertexProgram.usedTimes===0&&this._releaseProgram(t.vertexProgram),t.fragmentProgram.usedTimes===0&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,i,s){n=n||this._getComputeCacheKey(e,t);let o=this.caches.get(n);return o===void 0&&(o=new K1(n,t),this.caches.set(n,o),this.backend.createComputePipeline(o,i,s)),o}_getRenderPipeline(e,t,n,i,s){i=i||this._getRenderCacheKey(e,t,n);let o=this.caches.get(i);return o===void 0&&(o=new X1(i,t,n),this.caches.set(i,o),e.pipeline=o,this.backend.createRenderPipeline(e,s)),o}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t),this.info.destroyProgram(e)}_needsComputeUpdate(e){const t=this.get(e);return t.pipeline===void 0||t.version!==e.version}_needsRenderUpdate(e){return this.get(e).pipeline===void 0||this.backend.needsRenderUpdate(e)}}class Z1 extends jr{constructor(e,t,n,i,s,o){super(),this.backend=e,this.textures=n,this.pipelines=s,this.attributes=i,this.nodes=t,this.info=o,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings(),n=this.get(e);return n.initialized!==!0&&(this._createBindings(t),n.initialized=!0),t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings,n=this.get(e);return(n.initialized!==!0||n.bindings!==t)&&(n.bindings!==void 0&&this._destroyBindings(n.bindings),this._createBindings(t),n.initialized=!0,n.bindings=t),t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}updateSharedForRender(e){const t=this.getForRender(e);for(const n of t)for(const i of n.bindings)if((i.isNodeUniformsGroup===!0||i.isNodeUniformBuffer===!0)&&i.groupNode.shared===!0){if(this.nodes.updateGroup(i)===!1)continue;i.update()&&this.backend.updateBinding(i),i.updateRanges.length>0&&i.clearUpdateRanges()}}deleteForCompute(e){const n=this.get(e).bindings||this.nodes.getForCompute(e).bindings;this._destroyBindings(n),this.delete(e)}deleteForRender(e){const t=e.getBindings();this._destroyBindings(t),this.delete(e)}_createBindings(e){for(const t of e){const n=this.get(t);if(n.bindGroup===void 0){for(const i of t.bindings)if(i.isUniformBuffer)this.backend.createUniformBuffer(i),this.info.createUniformBuffer(i);else if(i.isSampledTexture)this.textures.updateTexture(i.texture);else if(i.isSampler)this.textures.updateSampler(i);else if(i.isStorageBuffer){const s=i.attribute,o=s.isIndirectStorageBufferAttribute?en.INDIRECT:en.STORAGE;this.attributes.update(s,o)}this.backend.createBindings(t,e,""),n.bindGroup=t,n.usedTimes=1}else n.usedTimes++}}_destroyBindings(e){for(const t of e){const n=this.get(t);if(n.usedTimes--,n.usedTimes===0){for(const i of t.bindings)if(i.isUniformBuffer)this.backend.destroyUniformBuffer(i),this.info.destroyUniformBuffer(i),i.release();else if(i.isSampler){if(i.isSampledTexture!==!0)this.backend.destroySampler(i);else if(i.texture!==null){const s=this.textures.get(i.texture);s.bindGroups!==void 0&&s.bindGroups.delete(t)}i.release()}this.backend.deleteBindGroupData(t),this.delete(t)}}}_updateBindings(e){for(const t of e)this._update(t,e)}_update(e,t){const{backend:n}=this;let i=!1,s=!0,o="",a=0;for(const u of e.bindings)if(this.nodes.updateGroup(u)!==!1){if(u.isStorageBuffer){const c=u.attribute,h=c.isIndirectStorageBufferAttribute?en.INDIRECT:en.STORAGE,d=n.get(u);this.attributes.update(c,h),d.attribute!==c&&(d.attribute=c,i=!0),o+=c.id+","}if(u.isUniformBuffer)u.update()&&n.updateBinding(u);else if(u.isSampledTexture){const c=u.update(),h=u.texture,d=this.textures.get(h);if(c&&(this.textures.updateTexture(h),u.generation!==d.generation&&(u.generation=d.generation,i=!0),d.bindGroups.add(e)),n.get(h).externalTexture!==void 0||d.isDefaultTexture?s=!1:(o+=h.id+",",a+=h.version),h.isStorageTexture===!0&&h.mipmapsAutoUpdate===!0){const p=this.get(h);u.store===!0?p.needsMipmap=!0:this.textures.needsMipmaps(h)&&p.needsMipmap===!0&&(this.backend.generateMipmaps(h),p.needsMipmap=!1)}}else if(u.isSampler&&u.update()){const h=this.textures.updateSampler(u);u.samplerKey!==h&&(u.samplerKey=h,i=!0)}u.isBuffer&&u.updateRanges.length>0&&u.clearUpdateRanges()}i===!0&&this.backend.updateBindings(e,t,s?o:"",a)}}const J1=Object.freeze([]);function eM(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?r.z-e.z:r.id-e.id}function tg(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?e.z-r.z:r.id-e.id}function ng(r){return(r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode)&&r.side===sr&&r.forceSinglePass===!1}class tM{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lighting=e,this.lightsNode=e.getNode(t),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0,this.frameId=-1,this._lastOcclusionObject=null}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,i,s,o,a){let u=this.renderItems[this.renderItemsIndex];return u===void 0?(u={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:s,group:o,clippingContext:a},this.renderItems[this.renderItemsIndex]=u):(u.id=e.id,u.object=e,u.geometry=t,u.material=n,u.groupOrder=i,u.renderOrder=e.renderOrder,u.z=s,u.group=o,u.clippingContext=a),this.renderItemsIndex++,u}push(e,t,n,i,s,o,a){this.camera.reversedDepth===!0&&(s=-s);const u=this.getNextRenderItem(e,t,n,i,s,o,a);e.occlusionTest===!0&&this._lastOcclusionObject!==e&&(this.occlusionQueryCount++,this._lastOcclusionObject=e),n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(ng(n)&&this.transparentDoublePass.push(u),this.transparent.push(u)):this.opaque.push(u)}unshift(e,t,n,i,s,o,a){const u=this.getNextRenderItem(e,t,n,i,s,o,a);n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(ng(n)&&this.transparentDoublePass.unshift(u),this.transparent.unshift(u)):this.opaque.unshift(u)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||eM),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||tg),this.transparent.length>1&&this.transparent.sort(t||tg)}finish(){this.lightsNode.setLights(this.lighting.enabled?this.lightsArray:J1);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const n=this.renderItems[e];if(n.id===null)break;rg(n)}this._lastOcclusionObject=null}clear(){for(let e=0,t=this.renderItems.length;e<t;e++){const n=this.renderItems[e];if(n.id===null)break;rg(n)}this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0}}function rg(r){r.id=null,r.object=null,r.geometry=null,r.material=null,r.groupOrder=null,r.renderOrder=null,r.z=null,r.group=null,r.clippingContext=null}const br=[];class nM{constructor(){this.lists=new zr,this._activeLists=new Set,this._frameId=-1}get(e,t,n){const i=this.lists;br[0]=e,br[1]=t,br[2]=n;let s=i.get(br);return s===void 0&&(s=new tM(n,e,t),i.set(br,s)),br[0]=null,br[1]=null,br[2]=null,s.frameId=this._frameId,this._activeLists.add(s),s}update(e){if(e!==this._frameId){this._frameId=e;for(const t of this._activeLists)e-t.frameId>10&&(t.clear(),this._activeLists.delete(t))}}dispose(){this.lists=new zr,this._activeLists.clear(),this._frameId=-1}}let rM=0;class iM{constructor(){this.id=rM++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new tt,this.scissor=!1,this.scissorValue=new tt,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.fullscreenPass=!1,this.isRenderContext=!0}getCacheKey(){return cb(this)}}function cb(r){const{textures:e,activeCubeFace:t,activeMipmapLevel:n}=r,i=[t,n];for(const s of e)i.push(s.id);return Do(i)}class sM{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,n=0){let i;if(e===null)i="default";else{const u=e.texture.format,l=e.texture.type;i=`${e.textures.length}:${u}:${l}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const s=t!==null?t.id:"default",o=i+"-"+s+"-"+n;let a=this._renderContexts[o];return a===void 0&&(a=new iM,a.mrt=t,this._renderContexts[o]=a),e!==null&&(a.sampleCount=e.samples===0?1:e.samples),a.clearDepthValue=this.renderer.getClearDepth(),a.clearStencilValue=this.renderer.getClearStencil(),a}dispose(){this._renderContexts={}}}const oM=new z;class aM extends jr{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n,this._htmlTextures=new Set}updateRenderTarget(e,t=0){const n=this.get(e),i=e.samples===0?1:e.samples,s=n.depthTextureMips||(n.depthTextureMips={}),o=e.textures,a=this.getSize(o[0]),u=a.width>>t,l=a.height>>t;let c=e.depthTexture||s[t];const h=e.depthBuffer===!0||e.stencilBuffer===!0;let d=!1;const f=c!==void 0&&c.image!==void 0&&c.image.depth>1,p=a.depth>1&&(e.useArrayDepthTexture||e.multiview||f);c===void 0&&h&&(c=new ar,c.format=e.stencilBuffer?Ln:Dn,c.type=e.stencilBuffer?or:qe,c.image.width=u,c.image.height=l,c.image.depth=a.depth,c.renderTarget=e,s[t]=c),c&&(c.isArrayTexture=p),(n.width!==a.width||a.height!==n.height)&&(d=!0,c&&c.renderTarget===e&&(c.needsUpdate=!0,c.image.width=u,c.image.height=l,c.image.depth=p?a.depth:1)),n.width=a.width,n.height=a.height,n.textures=o,n.depthTexture=c||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==i&&(d=!0,c&&c.renderTarget===e&&(c.needsUpdate=!0),n.sampleCount=i);const g={sampleCount:i};if(e.isXRRenderTarget!==!0){for(let _=0;_<o.length;_++){const m=o[_];d&&(m.needsUpdate=!0),this.updateTexture(m,g)}c&&this.updateTexture(c,g)}n.initialized!==!0&&(n.initialized=!0,this.info.memory.renderTargets++,n.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",n.onDispose))}updateTexture(e,t={}){const n=this.get(e);if(n.initialized===!0&&n.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,s=this.backend;if(i&&n.initialized===!0&&s.destroyTexture(e),e.isFramebufferTexture){const l=this.renderer.getRenderTarget();l?e.type=l.texture.type:e.type=Pt}if(e.isHTMLTexture&&e.image){const l=this.renderer.domElement;if("requestPaint"in l){if(l.hasAttribute("layoutsubtree")||l.setAttribute("layoutsubtree","true"),e.image.parentNode!==l&&l.appendChild(e.image),this._htmlTextures.size===0){const c=this._htmlTextures;l.onpaint=h=>{const d=h&&h.changedElements;for(const f of c)(!d||d.includes(f.image))&&(f.needsUpdate=!0)}}this._htmlTextures.add(e)}}const{width:o,height:a,depth:u}=this.getSize(e);if(t.width=o,t.height=a,t.depth=u,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,o,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||e.isStorageTexture===!0||e.isExternalTexture===!0)s.createTexture(e,t),n.generation=e.version;else if(e.version>0){const l=e.image;if(l===void 0)Y("Renderer: Texture marked for update but image is undefined.");else if(l.complete===!1)Y("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const h=[];for(const d of e.images)h.push(d);t.images=h}else t.image=l;(n.isDefaultTexture===void 0||n.isDefaultTexture===!0)&&(s.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),e.source.dataReady===!0&&s.updateTexture(e,t);const c=e.isStorageTexture===!0&&e.mipmapsAutoUpdate===!1;t.needsMipmaps&&e.mipmaps.length===0&&!c&&s.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else s.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;n.initialized!==!0&&(n.initialized=!0,n.generation=e.version,n.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&Ye.enabled===!0&&Ye.getTransfer(e.colorSpace)!==le&&Y("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),n.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",n.onDispose)),n.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=oM){let n=e.images?e.images[0]:e.image;return n?(n.image!==void 0&&(n=n.image),e.isHTMLTexture?(t.width=n.offsetWidth||1,t.height=n.offsetHeight||1,t.depth=1):typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement?(t.width=n.videoWidth||1,t.height=n.videoHeight||1,t.depth=1):typeof VideoFrame<"u"&&n instanceof VideoFrame?(t.width=n.displayWidth||1,t.height=n.displayHeight||1,t.depth=1):(t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let i;return e.mipmaps.length>0?i=e.mipmaps.length:e.isCompressedTexture===!0?i=1:i=Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return e.generateMipmaps===!0||e.mipmaps.length>0}_destroyRenderTarget(e){if(this.has(e)===!0){const t=this.get(e),n=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let s=0;s<n.length;s++)this._destroyTexture(n[s]);i&&i.renderTarget===e&&this._destroyTexture(i),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(this.has(e)===!0){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const n=t.isDefaultTexture;if(this.backend.destroyTexture(e,n),t.bindGroups)for(const i of t.bindGroups){const s=this.backend.get(i);s.groups=void 0,s.versions=void 0;for(const o of i.bindings)o.isSampler&&o.texture===e&&(o.isSampledTexture!==!0&&this.backend.destroySampler(o),o.reset(),o.release())}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}}class Vd extends Dt{constructor(e,t,n,i=1){super(e,t,n),this.a=i}set(e,t,n,i=1){return this.a=i,super.set(e,t,n)}copy(e){return e.a!==void 0&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b,yield this.a}}class hb extends Cd{static get type(){return"OverrideContextNode"}constructor(e,t=null){super(t,{overrideNodes:e}),this.isOverrideContextNode=!0}getFlowContextData(){const e=[];this.traverse(i=>{i.isOverrideContextNode===!0&&e.push(i.value.overrideNodes)});const t=new Map(e.flatMap(i=>Array.from(i.entries()))),n=super.getFlowContextData();return n.overrideNodes=t,n}}function uM(r,e=null,t=null){if(e&&e.isNode){const n=e;e=()=>n}return new hb(new Map([[r,e]]),t)}E("overrideNode",(r,e,t)=>uM(e,t,r));function lM(r,e=null){const t=new Map;for(const[n,i]of r){const s=i!==null?typeof i=="function"?i:()=>i:null;t.set(n,s)}return new hb(t,e)}E("overrideNodes",(r,e)=>lM(e,r));class cM extends _e{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const n=this.getNodeType(e),i=e.getStructTypeNode(n);let s;return i!==null?s=i.getMemberType(e,t):(V(`TSL: Member "${t}" not found in struct "${n}".`,new Ft),s="float"),s}getHash(){return String(this.id)}generate(){return this.name}}class hM extends te{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this._nodeDataLibrary=new Map,this.isStackNode=!0}getElementType(e){return this.outputNode?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=-1){if(e.isNode!==!0)return V("TSL: Invalid node added to stack.",new Ft),this;if(t===-1)if(this._currentNode){let n=this._nodeDataLibrary.get(this._currentNode);n===void 0&&(n={delta:0},this._nodeDataLibrary.set(this._currentNode,n)),n.delta++,t=this.nodes.indexOf(this._currentNode)+n.delta}else t=this.nodes.length;return this.nodes.splice(t,0,e),this}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const n=new Js(t);return this._currentCond=Zt(e,n),this.addToStack(this._currentCond)}ElseIf(e,t){const n=new Js(t),i=Zt(e,n);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new Js(e),this}Switch(e){return this._expressionNode=K(e),this}Case(...e){const t=[];if(e.length>=2)for(let a=0;a<e.length-1;a++)t.push(this._expressionNode.equal(K(e[a])));else V("TSL: Invalid parameter length. Case() requires at least two parameters.",new Ft);const n=e[e.length-1],i=new Js(n);let s=t[0];for(let a=1;a<t.length;a++)s=s.or(t[a]);const o=Zt(s,i);return this._currentCond===null?(this._currentCond=o,this.addToStack(this._currentCond)):(this._currentCond.elseNode=o,this._currentCond=o,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let n=0;for(const i of this.getChildren())i.isVarNode&&i.isIntent(e)&&i.isAssign(e)!==!0||(t["node"+n++]=i);return t.outputNode||null}build(e,...t){const n=L_(),i=e.buildStage;yu(this),e.setActiveStack(this);for(let o=0;o<this.nodes.length;o++){const a=this.nodes[o],u=this._currentNode;if(this._currentNode=a,!(a.isVarNode&&a.isIntent(e)&&a.isAssign(e)!==!0)){if(i==="setup")a.build(e);else if(i==="analyze")a.build(e,this);else if(i==="generate"){const l=e.getDataFromNode(a,"any").stages,c=l&&l[e.shaderStage];if(a.isVarNode&&c&&c.length===1&&c[0]&&c[0].isStackNode)continue;a.build(e,"void")}this._currentNode=u}}let s;if(this.outputNode){const o=this.outputNode.build(e,...t);(e.buildStage!=="generate"||this.outputNode.getNodeType(e)!=="void")&&(s=o)}else s=super.build(e,...t);return yu(n),e.removeActiveStack(this),s}}const Yl=ke(hM).setParameterLength(0,1);new bt;const dM=new Ti;Or.flipX();dM.depthTexture=new ar(1,1);const Ql=new rd(-1,1,1,-1,0,1);class fM extends Eo{constructor(e=!1){super();const t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new uu([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new uu(t,2))}}const pM=new fM,gM=q(bh([-1,-1,3]).element(xh),bh([3,-1,-1]).element(xh),0,1);class db extends yn{constructor(e){super(pM,e),this.camera=Ql,this.isQuadMesh=!0}async renderAsync(e){Fe('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,Ql)}render(e){const t=this.material.vertexNode;this.material.vertexNode=gM,e.render(this,Ql),this.material.vertexNode=t}}function mM(r,e={}){return e.toneMapping=r.toneMapping,e.toneMappingExposure=r.toneMappingExposure,e.outputColorSpace=r.outputColorSpace,e.renderTarget=r.getRenderTarget(),e.activeCubeFace=r.getActiveCubeFace(),e.activeMipmapLevel=r.getActiveMipmapLevel(),e.renderObjectFunction=r.getRenderObjectFunction(),e.pixelRatio=r.getPixelRatio(),e.mrt=r.getMRT(),e.clearColor=r.getClearColor(e.clearColor||new Dt),e.clearAlpha=r.getClearAlpha(),e.autoClear=r.autoClear,e.scissorTest=r.getScissorTest(),e}function _M(r,e){return e=mM(r,e),r.setMRT(null),r.setRenderObjectFunction(null),r.setClearColor(0,1),r.autoClear=!0,e}function yM(r,e){r.toneMapping=e.toneMapping,r.toneMappingExposure=e.toneMappingExposure,r.outputColorSpace=e.outputColorSpace,r.setRenderTarget(e.renderTarget,e.activeCubeFace,e.activeMipmapLevel),r.setRenderObjectFunction(e.renderObjectFunction),r.setPixelRatio(e.pixelRatio),r.setMRT(e.mrt),r.setClearColor(e.clearColor,e.clearAlpha),r.autoClear=e.autoClear,r.setScissorTest(e.scissorTest)}function bM(r,e={}){return e.background=r.background,e.backgroundNode=r.backgroundNode,e.overrideMaterial=r.overrideMaterial,e}function xM(r,e){return e=bM(r,e),r.background=null,r.backgroundNode=null,r.overrideMaterial=null,e}function vM(r,e){r.background=e.background,r.backgroundNode=e.backgroundNode,r.overrideMaterial=e.overrideMaterial}function TM(r,e,t){return t=_M(r,t),t=xM(e,t),t}function SM(r,e,t){yM(r,t),vM(e,t)}const fb=P(([r])=>fr(N(52.9829189).mul(fr(yi(r,re(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),Cn=P(([r,e,t])=>{const n=N(2.399963229728653),i=hr(N(r).add(.5).div(N(e))),s=N(r).mul(n).add(t);return re(dn(s),Tt(s)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]}),Zl=new bt,wM=ne(0).setGroup(Q).onRenderUpdate(({scene:r})=>r.backgroundBlurriness),ig=ne(1).setGroup(Q).onRenderUpdate(({scene:r})=>r.backgroundIntensity),RM=ne(new bt).setGroup(Q).onRenderUpdate(({scene:r})=>{const e=r.background;return e!==null&&e.isTexture&&e.mapping!==cv||r.backgroundNode&&r.backgroundNode.isNode?Zl.makeRotationFromEuler(r.backgroundRotation).transpose():Zl.identity(),Zl}),AM=P(([r,e])=>r.mul(e).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),NM=P(([r,e])=>(r=r.mul(e),r.div(r.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),EM=P(([r,e])=>{r=r.mul(e),r=r.sub(.004).max(0);const t=r.mul(r.mul(6.2).add(.5)),n=r.mul(r.mul(6.2).add(1.7)).add(.06);return t.div(n).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),CM=P(([r])=>{const e=r.mul(r.add(.0245786)).sub(90537e-9),t=r.mul(r.add(.432951).mul(.983729)).add(.238081);return e.div(t)}),MM=P(([r,e])=>{const t=nt(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),n=nt(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return r=r.mul(e).div(.6),r=t.mul(r),r=CM(r),r=n.mul(r),r.clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),PM=nt(D(1.6605,-.1246,-.0182),D(-.5876,1.1329,-.1006),D(-.0728,-.0083,1.1187)),BM=nt(D(.6274,.0691,.0164),D(.3293,.9195,.088),D(.0433,.0113,.8956)),FM=P(([r])=>{const e=D(r).toVar(),t=D(e.mul(e)).toVar(),n=D(t.mul(t)).toVar();return N(15.5).mul(n.mul(t)).sub(he(40.14,n.mul(e))).add(he(31.96,n).sub(he(6.868,t.mul(e))).add(he(.4298,t).add(he(.1191,e).sub(.00232))))}),DM=P(([r,e])=>{const t=D(r).toVar(),n=nt(D(.856627153315983,.137318972929847,.11189821299995),D(.0951212405381588,.761241990602591,.0767994186031903),D(.0482516061458583,.101439036467562,.811302368396859)),i=nt(D(1.1271005818144368,-.1413297634984383,-.14132976349843826),D(-.11060664309660323,1.157823702216272,-.11060664309660294),D(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=N(-12.47393),o=N(4.026069);return t.mulAssign(e),t.assign(BM.mul(t)),t.assign(n.mul(t)),t.assign(ot(t,1e-10)),t.assign(cr(t)),t.assign(t.sub(s).div(o.sub(s))),t.assign($r(t,0,1)),t.assign(FM(t)),t.assign(i.mul(t)),t.assign(qu(ot(D(0),t),D(2.2))),t.assign(PM.mul(t)),t.assign($r(t,0,1)),t}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),LM=P(([r,e])=>{const t=N(.76),n=N(.15);r=r.mul(e);const i=_i(r.r,_i(r.g,r.b)),s=Zt(i.lessThan(.08),i.sub(he(6.25,i.mul(i))),.04);r.subAssign(s);const o=ot(r.r,ot(r.g,r.b));Me(o.lessThan(t),()=>r);const a=Et(1,t),u=Et(1,a.mul(a).div(o.add(a.sub(t))));r.mulAssign(u.div(o));const l=Et(1,On(1,n.mul(o.sub(u)).add(1)));return Se(r,D(u),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class we extends te{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=n}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const i of t)i.build(e,"void");const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class OM extends we{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return n===void 0&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),i=n.name,s=n.type,o=e.getCodeFromNode(this,s);if(i!==""){const l=e.getDataFromNode(this);l.declarationRegistered!==!0&&(o.name=i,e.registerDeclaration(o),l.declarationRegistered=!0)}const a=e.getPropertyName(o),u=this.getNodeFunction(e).getCode(a);return o.code=u+`
540
+ `,t==="property"?a:e.format(`${a}()`,s,t)}}function pb(r){let e;const t=r.context.getViewZ;return t!==void 0&&(e=t(this)),(e||Xe.z).negate()}const UM=P(([r,e],t)=>{const n=pb(t);return Un(r,e,n)}),IM=P(([r],e)=>{const t=pb(e);return r.mul(r,t,t).negate().exp().oneMinus()}),sg=P(([r,e])=>q(e.toFloat().mix(lo.rgb,r.toVec3()),lo.a));let da;function el(r){da=da||new WeakMap;let e=da.get(r);return e===void 0&&da.set(r,e={}),e}function $d(r){const e=el(r);return e.shadowMatrix||(e.shadowMatrix=ne("mat4").setGroup(Q).onRenderUpdate(t=>((r.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&(r.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(r.shadow.camera.coordinateSystem=t.camera.coordinateSystem,r.shadow.camera.updateProjectionMatrix()),r.shadow.updateMatrices(r)),r.shadow.matrix)))}function kM(r,e=Ro){const t=$d(r).mul(e);return t.xyz.div(t.w)}function gb(r){const e=el(r);return e.position||(e.position=ne(new z).setGroup(Q).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(r.matrixWorld)))}function GM(r){const e=el(r);return e.targetPosition||(e.targetPosition=ne(new z).setGroup(Q).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(r.target.matrixWorld)))}function mb(r){const e=el(r);return e.viewPosition||(e.viewPosition=ne(new z).setGroup(Q).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new z,n.value.setFromMatrixPosition(r.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}const _b=r=>bs.transformDirection(gb(r).sub(GM(r))),VM=Wr("vec3","totalDiffuse"),$M=Wr("vec3","totalSpecular"),zM=Wr("vec3","outgoingLight"),WM=r=>r.sort((e,t)=>e.id-t.id),HM=(r,e)=>{for(const t of e)if(t.isAnalyticLightNode&&t.light.id===r)return t;return null},Jl=new WeakMap,ks=[];class yb extends te{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=VM,this.totalSpecularNode=$M,this.outgoingLightNode=zM,this._lights=[],this.global=!0}customCacheKey(){const e=this.getBuiltinLights();for(let n=0;n<e.length;n++){const i=e[n];if(ks.push(i.id),ks.push(i.castShadow?1:0),i.isSpotLight===!0){const s=i.map!==null?i.map.id:-1,o=i.colorNode?i.colorNode.getCacheKey():-1;ks.push(s,o)}}const t=Do(ks);return ks.length=0,t}getHash(e){const t=e.getDataFromNode(this);if(t.lightNodesHash===void 0){const n=this.setupLightsNode(e);t.lightNodes=n;const i=[];for(const s of n)i.push(s.getHash());t.lightNodesHash="lights-"+i.join(",")}return t.lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const n of t.nodes)n.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=e.getDataFromNode(this),n=[],i=t.lightNodes||null,s=e.context.materialLightings,o=this.getBuiltinLights(),a=WM([...s,...o]),u=e.renderer.library;for(const l of a)if(l.isNode)n.push(l);else{let c=null;if(i!==null&&(c=HM(l.id,i)),c===null){const h=u.getLightNodeClass(l.constructor);if(h===null){Y(`LightsNode.setupNodeLights: Light node not found for ${l.constructor.name}`);continue}Jl.has(l)===!1&&Jl.set(l,new h(l)),c=Jl.get(l)}n.push(c)}return n}setupDirectLight(e,t,n){const{lightingModel:i,reflectedLight:s}=e.context;i.direct({...n,lightNode:t,reflectedLight:s},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:i,reflectedLight:s}=e.context;i.directRectArea({...n,lightNode:t,reflectedLight:s},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){const t=e.getDataFromNode(this);return t.lightNodes===void 0&&(t.lightNodes=this.setupLightsNode(e)),t.lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const i=e.context,s=i.lightingModel,o=e.getNodeProperties(this);if(s){const{totalDiffuseNode:a,totalSpecularNode:u}=this;i.outgoingLight=n;const l=e.addStack();o.nodes=l.nodes,s.start(e);const{backdrop:c,backdropAlpha:h}=i,{directDiffuse:d,directSpecular:f,indirectDiffuse:p,indirectSpecular:g}=i.reflectedLight;let _=d.add(p);c!==null&&(h!==null?_=D(h.mix(_,c)):_=D(c)),a.assign(_),u.assign(f.add(g)),n.assign(a.add(u)),s.finish(e),n=n.bypass(e.removeStack())}else o.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this}getLights(){return this._lights}getBuiltinLights(){return this._lights}get hasLights(){return this._lights.length>0}}const wu=new WeakMap,og=new zr,Fi=[],jM=r=>{let e=wu.get(r);return e===void 0&&(e=new Ke,e.colorNode=q(0,0,0,1),e.isShadowPassMaterial=!0,e.name="ShadowMaterial",e.blending=ur,e.fog=!1,wu.set(r,e)),e},qM=r=>{const e=wu.get(r);e!==void 0&&(e.dispose(),wu.delete(r))},XM=(r,e,t,n)=>{Fi[0]=r,Fi[1]=e;let i=og.get(Fi);return(i===void 0||i.shadowType!==t||i.useVelocity!==n)&&(i=(s,o,a,u,l,c,h,d,f)=>{(s.castShadow===!0||s.receiveShadow&&t===io)&&(n&&(M_(s).useVelocity=!0),s.onBeforeShadow(r,s,a,e.camera,u,o.overrideMaterial,c),r.renderObject(s,o,a,u,l,c,h,d,f),s.onAfterShadow(r,s,a,e.camera,u,o.overrideMaterial,c))},i.shadowType=t,i.useVelocity=n,og.set(Fi,i)),Fi[0]=null,Fi[1]=null,i};class KM extends te{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=ie.RENDER,this.isShadowBaseNode=!0}getShadowMaterial(){return jM(this.light)}disposeShadowMaterial(){qM(this.light)}getShadowRenderObjectFunction(e,t=this.light.shadow){const n=e.shadowMap.type,i=e.getMRT(),s=i?i.has("velocity"):!1;return XM(e,t,n,s)}setupShadowPosition({context:e,material:t}){bb.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Ro)}}const bb=Wr("vec3","shadowPositionWorld"),YM=P(({depthTexture:r,shadowCoord:e,depthLayer:t})=>{let n=ve(r,e.xy).setName("t_basic");return r.isArrayTexture&&(n=n.depth(t)),n.compare(e.z)}),QM=P(({depthTexture:r,shadowCoord:e,shadow:t,depthLayer:n})=>{const i=(c,h)=>{let d=ve(r,c);return r.isArrayTexture&&(d=d.depth(n)),d.compare(h)},s=Be("mapSize","vec2",t).setGroup(Q),o=Be("radius","float",t).setGroup(Q),a=re(1).div(s),u=o.mul(a.x),l=fb(ys.xy).mul(6.28318530718);return jt(i(e.xy.add(Cn(0,5,l).mul(u)),e.z),i(e.xy.add(Cn(1,5,l).mul(u)),e.z),i(e.xy.add(Cn(2,5,l).mul(u)),e.z),i(e.xy.add(Cn(3,5,l).mul(u)),e.z),i(e.xy.add(Cn(4,5,l).mul(u)),e.z)).mul(1/5)}),ZM=P(({depthTexture:r,shadowCoord:e,depthLayer:t},n)=>{let i=ve(r).sample(e.xy);r.isArrayTexture&&(i=i.depth(t)),i=i.rg;const s=i.x,o=ot(1e-7,i.y.mul(i.y)),a=n.renderer.reversedDepthBuffer?So(s,e.z):So(e.z,s),u=N(1).toVar();return Me(a.notEqual(1),()=>{const l=e.z.sub(s);let c=o.div(o.add(l.mul(l)));c=$r(Et(c,.3).div(.65)),u.assign(ot(a,c))}),u}),JM=P(({samples:r,radius:e,size:t,shadowPass:n,depthLayer:i})=>{const s=N(0).toVar("meanVertical"),o=N(0).toVar("squareMeanVertical"),a=r.lessThanEqual(N(1)).select(N(0),N(2).div(r.sub(1))),u=r.lessThanEqual(N(1)).select(N(0),N(-1));Yt({start:Ae(0),end:Ae(r),type:"int",condition:"<"},({i:c})=>{const h=u.add(N(c).mul(a));let d=n.sample(jt(ys.xy,re(0,h).mul(e)).div(t));n.value.isArrayTexture&&(d=d.depth(i)),d=d.x,s.addAssign(d),o.addAssign(d.mul(d))}),s.divAssign(r),o.divAssign(r);const l=hr(o.sub(s.mul(s)).max(0));return re(s,l)}),eP=P(({samples:r,radius:e,size:t,shadowPass:n,depthLayer:i})=>{const s=N(0).toVar("meanHorizontal"),o=N(0).toVar("squareMeanHorizontal"),a=r.lessThanEqual(N(1)).select(N(0),N(2).div(r.sub(1))),u=r.lessThanEqual(N(1)).select(N(0),N(-1));Yt({start:Ae(0),end:Ae(r),type:"int",condition:"<"},({i:c})=>{const h=u.add(N(c).mul(a));let d=n.sample(jt(ys.xy,re(h,0).mul(e)).div(t));n.value.isArrayTexture&&(d=d.depth(i)),s.addAssign(d.x),o.addAssign(jt(d.y.mul(d.y),d.x.mul(d.x)))}),s.divAssign(r),o.divAssign(r);const l=hr(o.sub(s.mul(s)).max(0));return re(s,l)}),tP=[YM,QM,null,ZM];let ec;const fa=new db;class xb extends KM{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:s,depthLayer:o}){const a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),u=t({depthTexture:n,shadowCoord:i,shadow:s,depthLayer:o});return a.select(u,N(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:i}=e,s=n.biasNode||Be("bias","float",n).setGroup(Q);let o=t,a;if(n.camera.isOrthographicCamera||i.logarithmicDepthBuffer!==!0)o=o.xyz.div(o.w),a=o.z;else{const u=o.w;o=o.xy.div(u);const l=Be("near","float",n.camera).setGroup(Q),c=Be("far","float",n.camera).setGroup(Q);a=kd(u.negate(),l,c)}return o=D(o.x,o.y.oneMinus(),i.reversedDepthBuffer?a.sub(s):a.add(s)),o}getShadowFilterFn(e){return tP[e]}setupRenderTarget(e,t){const n=new ar(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?ss:Fo;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=n,{shadowMap:i,depthTexture:n}}setupShadow(e){const{renderer:t,camera:n}=e,{light:i,shadow:s}=this,{depthTexture:o,shadowMap:a}=this.setupRenderTarget(s,e),u=t.shadowMap.type,l=t.hasCompatibility(Si.TEXTURE_COMPARE);if(u===Ga&&l?(o.minFilter=Rt,o.magFilter=Rt):(o.minFilter=zt,o.magFilter=zt),s.camera.coordinateSystem=n.coordinateSystem,s.camera.updateProjectionMatrix(),u===io&&s.isPointLightShadow!==!0){o.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:pn,type:wt,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:pn,type:wt,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:pn,type:wt,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:pn,type:wt,depthBuffer:!1}));let v=ve(o);o.isArrayTexture&&(v=v.depth(this.depthLayer));let w=ve(this.vsmShadowMapVertical.texture);o.isArrayTexture&&(w=w.depth(this.depthLayer));const R=Be("blurSamples","float",s).setGroup(Q),F=Be("radius","float",s).setGroup(Q),M=Be("mapSize","vec2",s).setGroup(Q),O=pr(e.getSharedContext());let U=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Ke);U.contextNode=O,U.fragmentNode=JM({samples:R,radius:F,size:M,shadowPass:v,depthLayer:this.depthLayer}),U.name="VSMVertical",U=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Ke),U.contextNode=O,U.fragmentNode=eP({samples:R,radius:F,size:M,shadowPass:w,depthLayer:this.depthLayer}),U.name="VSMHorizontal"}const c=Be("intensity","float",s).setGroup(Q),h=Be("normalBias","float",s).setGroup(Q),d=$d(i),f=xs.mul(h);let p;!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld?p=d.mul(bb.add(f)):p=ne("mat4").onObjectUpdate(({object:w},R)=>R.value.multiplyMatrices(d.value,w.matrixWorld)).mul(et).add(d.mul(q(f,0)));const g=this.setupShadowCoord(e,p),_=s.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(_===null)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const m=u===io&&s.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:o,y=this.setupShadowFilter(e,{filterFn:_,shadowTexture:a.texture,depthTexture:m,shadowCoord:g,shadow:s,depthLayer:this.depthLayer});let b;t.shadowMap.transmitted===!0&&(a.texture.isCubeTexture?b=Mt(a.texture,g.xyz):(b=ve(a.texture,g),o.isArrayTexture&&(b=b.depth(this.depthLayer))));let T;b?T=Se(1,y.rgb.mix(b,1),c.mul(b.a)).toVar():T=Se(1,y,c).toVar(),this.shadowMap=a,this.shadow.map=a;const x=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return b&&T.toInspector(`${x} / Color`,()=>this.shadowMap.texture.isCubeTexture?Mt(this.shadowMap.texture,Cp()):ve(this.shadowMap.texture)),T.toInspector(`${x} / Depth`,()=>{const v=Be("near","float",this.shadow.camera),w=Be("far","float",this.shadow.camera);let R;this.shadowMap.texture.isCubeTexture?R=Mt(this.shadowMap.depthTexture,Cp()).r:R=ve(this.shadowMap.depthTexture).r;let F;return this.shadow.camera.isPerspectiveCamera?F=Vy(R,v,w):F=YE(R,v,w),F=ho(F,v,w),F.oneMinus()})}setup(e){if(e.renderer.shadowMap.enabled!==!1)return P(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let n=this._node;return this.setupShadowPosition(e),n===null&&(this._node=n=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:s,scene:o}=e;t.updateMatrices(i),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);const a=o.name;o.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,s.render(o,t.camera),o.name=a}updateShadow(e){const{shadowMap:t,shadow:n}=this,{renderer:i,scene:s,camera:o}=e,a=i.shadowMap.type,u=t.depthTexture.version;this._depthVersionCached=u;const l=n.camera.layers.mask;(n.camera.layers.mask&4294967294)===0&&(n.camera.layers.mask=o.layers.mask);const c=i.getRenderObjectFunction();ec=TM(i,s,ec),s.overrideMaterial=this.getShadowMaterial(),i.setRenderObjectFunction(this.getShadowRenderObjectFunction(i,this.shadow||this.light.shadow)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(c),a===io&&n.isPointLightShadow!==!0&&this.vsmPass(i),n.camera.layers.mask=l,SM(i,s,ec)}vsmPass(e){const{shadow:t}=this,n=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,n),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,n),e.setRenderTarget(this.vsmShadowMapVertical),fa.material=this.vsmMaterialVertical,fa.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),fa.material=this.vsmMaterialHorizontal,fa.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,this.disposeShadowMaterial(),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),this.vsmShadowMapVertical!==null&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),this.vsmShadowMapHorizontal!==null&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){if(e.renderer._isPreCompiling===!0)return;const{shadow:t}=this;let n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId.get(e.camera)===e.frameId&&(n=!1),this._cameraFrameId.set(e.camera,e.frameId)),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const nP=(r,e)=>new xb(r,e),rP=new Dt,ag=new bt,Gs=new z,tc=new z,iP=[new z(1,0,0),new z(-1,0,0),new z(0,-1,0),new z(0,1,0),new z(0,0,1),new z(0,0,-1)],sP=[new z(0,-1,0),new z(0,-1,0),new z(0,0,-1),new z(0,0,1),new z(0,-1,0),new z(0,-1,0)],oP=[new z(1,0,0),new z(-1,0,0),new z(0,1,0),new z(0,-1,0),new z(0,0,1),new z(0,0,-1)],aP=[new z(0,-1,0),new z(0,-1,0),new z(0,0,1),new z(0,0,-1),new z(0,-1,0),new z(0,-1,0)],uP=P(({depthTexture:r,bd3D:e,dp:t})=>Mt(r,e).compare(t)),lP=P(({depthTexture:r,bd3D:e,dp:t,shadow:n})=>{const i=Be("radius","float",n).setGroup(Q),s=Be("mapSize","vec2",n).setGroup(Q),o=i.div(s.x),a=Ct(e),u=tn(Vr(e,a.x.greaterThan(a.z).select(D(0,1,0),D(1,0,0)))),l=Vr(e,u),c=fb(ys.xy).mul(6.28318530718),h=Cn(0,5,c),d=Cn(1,5,c),f=Cn(2,5,c),p=Cn(3,5,c),g=Cn(4,5,c);return Mt(r,e.add(u.mul(h.x).add(l.mul(h.y)).mul(o))).compare(t).add(Mt(r,e.add(u.mul(d.x).add(l.mul(d.y)).mul(o))).compare(t)).add(Mt(r,e.add(u.mul(f.x).add(l.mul(f.y)).mul(o))).compare(t)).add(Mt(r,e.add(u.mul(p.x).add(l.mul(p.y)).mul(o))).compare(t)).add(Mt(r,e.add(u.mul(g.x).add(l.mul(g.y)).mul(o))).compare(t)).mul(1/5)}),cP=P(({filterFn:r,depthTexture:e,shadowCoord:t,shadow:n},i)=>{const s=t.xyz.toConst(),o=s.abs().toConst(),a=o.x.max(o.y).max(o.z),u=ne("float").setGroup(Q).onRenderUpdate(()=>n.camera.near),l=ne("float").setGroup(Q).onRenderUpdate(()=>n.camera.far),c=Be("bias","float",n).setGroup(Q),h=N(1).toVar();return Me(a.sub(l).lessThanEqual(0).and(a.sub(u).greaterThanEqual(0)),()=>{let d;i.renderer.reversedDepthBuffer?(d=QE(a.negate(),u,l),d.subAssign(c)):i.renderer.logarithmicDepthBuffer?(d=kd(a.negate(),u,l),d.addAssign(c)):(d=Gy(a.negate(),u,l),d.addAssign(c));const f=s.normalize();h.assign(r({depthTexture:e,bd3D:f,dp:d,shadow:n}))}),h});class hP extends xb{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===Lv?uP:lP}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:s}){return cP({filterFn:t,depthTexture:n,shadowCoord:i,shadow:s})}setupRenderTarget(e,t){const n=new Ov(e.mapSize.width);n.name="PointShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?ss:Fo;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=n,{shadowMap:i,depthTexture:n}}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:s,scene:o}=e,a=t.camera,u=t.matrix,l=s.coordinateSystem===bo,c=l?iP:oP,h=l?sP:aP;n.setSize(t.mapSize.width,t.mapSize.width);const d=s.autoClear,f=s.getClearColor(rP),p=s.getClearAlpha();s.autoClear=!1,s.setClearColor(t.clearColor,t.clearAlpha);for(let g=0;g<6;g++){s.setRenderTarget(n,g),s.clear();const _=i.distance||a.far;_!==a.far&&(a.far=_,a.updateProjectionMatrix()),Gs.setFromMatrixPosition(i.matrixWorld),a.position.copy(Gs),tc.copy(a.position),tc.add(c[g]),a.up.copy(h[g]),a.lookAt(tc),a.updateMatrixWorld(),u.makeTranslation(-Gs.x,-Gs.y,-Gs.z),ag.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(ag,a.coordinateSystem,a.reversedDepth);const m=o.name;o.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${g+1}`,s.render(o,a),o.name=m}s.autoClear=d,s.setClearColor(f,p)}}const dP=(r,e)=>new hP(r,e);class Ni extends vs{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Dt,this.colorNode=e&&e.colorNode||ne(this.color).setGroup(Q),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=ie.FRAME,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,this.baseColorNode!==null&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return mb(this.light).sub(e.context.positionView||Xe)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return nP(this.light)}setupShadow(e){const{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let n=this.shadowColorNode;if(n===null){const i=this.light.shadow.shadowNode;let s;i!==void 0?s=K(i):s=this.setupShadowNode(),this.shadowNode=s,this.shadowColorNode=n=this.colorNode.mul(s),this.baseColorNode=this.colorNode}e.context.getShadow&&(n=e.context.getShadow(this,e)),this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const vb=P(({lightDistance:r,cutoffDistance:e,decayExponent:t})=>{const n=r.pow(t).max(.01).reciprocal();return e.greaterThan(0).select(n.mul(r.div(e).pow4().oneMinus().clamp().pow2()),n)}),fP=({color:r,lightVector:e,cutoffDistance:t,decayExponent:n})=>{const i=e.normalize(),s=e.length(),o=vb({lightDistance:s,cutoffDistance:t,decayExponent:n}),a=r.mul(o);return{lightDirection:i,lightColor:a}};class pP extends Ni{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=ne(0).setGroup(Q),this.decayExponentNode=ne(2).setGroup(Q)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return dP(this.light)}setupDirect(e){return fP({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const gP=P(([r,e])=>{const t=r.x,n=r.y,i=r.z;let s=e.element(0).mul(.886227);return s=s.add(e.element(1).mul(2*.511664).mul(n)),s=s.add(e.element(2).mul(2*.511664).mul(i)),s=s.add(e.element(3).mul(2*.511664).mul(t)),s=s.add(e.element(4).mul(2*.429043).mul(t).mul(n)),s=s.add(e.element(5).mul(2*.429043).mul(n).mul(i)),s=s.add(e.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),s=s.add(e.element(7).mul(2*.429043).mul(t).mul(i)),s=s.add(e.element(8).mul(.429043).mul(he(t,t).sub(he(n,n)))),s}),an=new Vd;class mP extends jr{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const i=this.renderer,s=this.nodes.getBackgroundNode(e)||e.background;let o=!1;if(s===null)i._clearColor.getRGB(an),an.a=i._clearColor.a;else if(s.isColor===!0)s.getRGB(an),an.a=1,o=!0;else if(s.isNode===!0){const u=this.get(e),l=s;an.copy(i._clearColor);let c=u.backgroundMesh;if(c===void 0){let b=function(){s.removeEventListener("dispose",b),c.material.dispose(),c.geometry.dispose()};const d=q(l).mul(ig).context({getUV:()=>RM.mul(wN),getTextureLevel:()=>wM}),f=mn.element(3).element(3).equal(1),p=On(1,mn.element(1).element(1)).mul(3),g=f.select(et.mul(p),et),_=xi.mul(q(g,0));let m=mn.mul(q(_.xyz,1));m=m.setZ(m.w);const y=new Ke;y.name="Background.material",y.side=yt,y.depthTest=!1,y.depthWrite=!1,y.allowOverride=!1,y.fog=!1,y.lights=!1,y.vertexNode=m,y.colorNode=d,u.backgroundMeshNode=d,u.backgroundMesh=c=new yn(new qh(1,32,32),y),c.frustumCulled=!1,c.name="Background.mesh",s.addEventListener("dispose",b)}const h=l.getCacheKey();u.backgroundCacheKey!==h&&(u.backgroundMeshNode.node=q(l).mul(ig),u.backgroundMeshNode.needsUpdate=!0,c.material.needsUpdate=!0,u.backgroundCacheKey=h),t.unshift(c,c.geometry,c.material,0,0,null,null)}else V("Renderer: Unsupported background configuration.",s);const a=i.xr.getEnvironmentBlendMode();if(a==="additive"?an.set(0,0,0,1):a==="alpha-blend"&&an.set(0,0,0,0),i.autoClear===!0||o===!0){const u=n.clearColorValue;u.r=an.r,u.g=an.g,u.b=an.b,u.a=an.a,(i.backend.isWebGLBackend===!0||i.alpha===!0)&&(u.r*=u.a,u.g*=u.a,u.b*=u.a),n.depthClearValue=i.getClearDepth(),n.stencilClearValue=i.getClearStencil(),n.clearColor=i.autoClearColor===!0,n.clearDepth=i.autoClearDepth===!0,n.clearStencil=i.autoClearStencil===!0}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let _P=0;class Bh{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=_P++}}class yP{constructor(e,t,n,i,s,o,a,u,l,c,h=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=h,this.nodeAttributes=i,this.bindings=s,this.updateNodes=o,this.updateBeforeNodes=a,this.updateAfterNodes=u,this.observer=l,this.hardwareClipping=c,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings)if(t.bindings[0].groupNode.shared!==!0){const i=new Bh(t.name,[]);e.push(i);for(const s of t.bindings)i.bindings.push(s.clone())}else e.push(t);return e}}class ug{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class bP{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class Tb{constructor(e,t,n=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=i}}class xP extends Tb{constructor(e,t,n=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=i}}class vP{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let TP=0;class nc{constructor(e=null){this.id=TP++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return t===void 0&&this.parent!==null&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class SP{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class qr{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class wP extends qr{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class RP extends qr{constructor(e,t=new de){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class AP extends qr{constructor(e,t=new z){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class NP extends qr{constructor(e,t=new tt){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class EP extends qr{constructor(e,t=new Dt){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class CP extends qr{constructor(e,t=new Hm){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class MP extends qr{constructor(e,t=new gs){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class PP extends qr{constructor(e,t=new bt){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class BP extends wP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class FP extends RP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class DP extends AP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class LP extends NP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class OP extends EP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class UP extends CP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class IP extends MP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kP extends PP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let GP=0;const lg=new WeakMap,cg=new WeakMap,VP=new WeakMap,$P=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),pa=r=>/e/g.test(r)?String(r).replace(/\+/g,""):(r=Number(r),r+(r%1?"":".0")),Sb=r=>{if(r.writeUsageCount>0)return!0;if(r.subBuildsCache!==void 0){for(const e in r.subBuildsCache)if(Sb(r.subBuildsCache[e]))return!0}return!1};class wb{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.compute=null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=new Set,this.sequentialNodes=new Set,this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.hardwareClipping=!1,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=Yl(),this.stacks=[],this.tab=" ",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new nc,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:GP++})}isFlatShading(){return this.material.flatShading===!0||this.geometry.hasAttribute("normal")===!1}isOpaque(){const e=this.material;return e.transparent===!1&&e.blending===Zn&&e.alphaToCoverage===!1}createRenderTarget(e,t,n){return new Ti(e,t,n)}createCubeRenderTarget(e,t){return new jy(e,t)}includes(e){return this.nodes.has(e)}getOutputType(e=0){const t=this.renderer.getRenderTarget();return t!==null?C_(t.textures[e]):"vec4"}getOutputStructName(){}_getBindGroup(e,t){const n=t[0].groupNode;let i=n.shared;if(i)for(let o=1;o<t.length;o++)n!==t[o].groupNode&&(i=!1);let s;if(i){let o="";for(const c of t)if(c.isNodeUniformsGroup){c.uniforms.sort((h,d)=>h.nodeUniform.node.id-d.nodeUniform.node.id);for(const h of c.uniforms)o+=h.nodeUniform.node.id}else o+=c.nodeUniform.id;const a=this.renderer._currentRenderContext||this.renderer;let u=lg.get(a);u===void 0&&(u=new Map,lg.set(a,u));const l=wi(o);s=u.get(l),s===void 0&&(s=new Bh(e,t),u.set(l,s))}else s=new Bh(e,t);return s}getBindGroupArray(e,t){const n=this.bindings[t];let i=n[e];return i===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(e===null){const t={},n=this.bindings;for(const i of Cl)for(const s in n[i]){const o=n[i][s],a=t[s]||(t[s]=[]);for(const u of o)a.includes(u)===!1&&a.push(u)}e=[];for(const i in t){const s=t[i],o=this._getBindGroup(i,s);e.push(o)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((t,n)=>t.bindings[0].groupNode.order-n.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const n=e[t];this.bindingsIndexes[n.name].group=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){this.nodes.has(e)===!1&&(this.nodes.add(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.updateBeforeType,n=e.updateAfterType;(t!==ie.NONE||n!==ie.NONE)&&this.sequentialNodes.add(e)}buildUpdateNodes(){for(const e of this.nodes)e.updateType!==ie.NONE&&this.updateNodes.push(e);for(const e of this.sequentialNodes){const t=e.updateBeforeType,n=e.updateAfterType;t!==ie.NONE&&this.updateBeforeNodes.push(e),n!==ie.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}get renderPipeline(){return this.context.renderPipeline}isFilteredTexture(e){return e.magFilter===Rt||e.magFilter===Nc||e.magFilter===is||e.magFilter===Ir||e.minFilter===Rt||e.minFilter===Nc||e.minFilter===is||e.minFilter===Ir}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("THREE.NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getGI,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const n=this.getDataFromNode(e);return n.cache===void 0&&(n.cache=new nc(t?this.getCache():null)),n.cache}isAvailable(){return!1}getVertexIndex(){Y("Abstract function.")}getInstanceIndex(){Y("Abstract function.")}getDrawIndex(){Y("Abstract function.")}getFrontFacing(){Y("Abstract function.")}getFragCoord(){Y("Abstract function.")}isFlipY(){return!1}isContextAssign(){return this.context.assign===!0}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=t.usageCount===void 0?1:t.usageCount+1,this.isContextAssign()?t.writeUsageCount=t.writeUsageCount===void 0?1:t.writeUsageCount+1:t.readUsageCount=t.readUsageCount===void 0?1:t.readUsageCount+1,t.usageCount}hasWriteUsage(e){const t=e.getShared(this),i=(t.isGlobal(this)?this.globalCache:this.cache).getData(t);if(i!==void 0){for(const s in i)if(Sb(i[s]))return!0}return!1}generateTexture(){Y("Abstract function.")}generateTextureLod(){Y("Abstract function.")}generateTextureSize(){Y("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,n=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let s=0;s<t;s++){const o=n?n[s]:null;o!==null?i+=o.build(this,e):i+=this.generateConst(e),s<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,n=null){const i=[];for(const s of t){const{name:o,type:a}=s;n&&n[o]&&n[o].isNode?i.push(n[o].build(this,a)):i.push(this.generateConst(a))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(t===null&&(e==="float"||e==="int"||e==="uint"?t=0:e==="bool"?t=!1:e==="color"?t=new Dt:e==="vec2"||e==="uvec2"||e==="ivec2"?t=new de:e==="vec3"||e==="uvec3"||e==="ivec3"?t=new z:(e==="vec4"||e==="uvec4"||e==="ivec4")&&(t=new tt)),e==="float")return pa(t);if(e==="int")return`${Math.round(t)}`;if(e==="uint")return t>=0?`${Math.round(t)}u`:"0u";if(e==="bool")return t?"true":"false";if(e==="color")return`${this.getType("vec3")}( ${pa(t.r)}, ${pa(t.g)}, ${pa(t.b)} )`;const n=this.getTypeLength(e),i=this.getComponentType(e),s=o=>this.generateConst(i,o);if(n===2)return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)} )`;if(n===3)return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)}, ${s(t.z)} )`;if(n===4&&e!=="mat2")return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)}, ${s(t.z)}, ${s(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(s).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`THREE.NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return e==="color"?"vec3":e}hasGeometryAttribute(e){return this.geometry&&this.geometry.getAttribute(e)!==void 0}getAttribute(e,t){const n=this.attributes;for(const s of n)if(s.name===e)return s;const i=new ug(e,t);return this.registerDeclaration(i),n.push(i),i}getPropertyName(e){return e.name}isReservedKeyword(){return!1}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return e==="void"||e==="property"||e==="sampler"||e==="samplerComparison"||e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="depthTexture"||e==="texture3D"}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;return e.isDepthTexture===!0?"float":t===gt?"int":t===qe?"uint":"float"}getElementType(e){return e==="mat2"?"vec2":e==="mat3"?"vec3":e==="mat4"?"vec4":this.getComponentType(e)}getComponentType(e){if(e=this.getVectorType(e),e==="float"||e==="bool"||e==="int"||e==="uint")return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return t===null?null:t[1]==="b"?"bool":t[1]==="i"?"int":t[1]==="u"?"uint":"float"}getVectorType(e){return e==="color"?"vec3":e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="texture3D"?"vec4":e}getTypeFromLength(e,t="float"){if(e===1)return t;let n=pd(e);const i=t==="float"?"":t[0];return/mat2/.test(t)===!0&&(n=n.replace("vec","mat")),i+n}getTypeFromArray(e){return $P.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,i=e.itemSize,s=e.normalized;let o;return!(e instanceof Wm)&&s!==!0&&(o=this.getTypeFromArray(n)),this.getTypeFromLength(i,o)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return n!==null?Number(n[1]):t==="float"||t==="bool"||t==="int"||t==="uint"?1:/mat2/.test(e)===!0?4:/mat3/.test(e)===!0?9:/mat4/.test(e)===!0?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return t==="int"||t==="uint"?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]===e)this.activeStacks.pop();else throw new Error("THREE.NodeBuilder: Invalid active stack removal.")}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=Yl(this.stack);const e=L_();return this.stacks.push(e),yu(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){const n=this.getDataFromNode(t);n.stack=e}return this.stack=e.parent,yu(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){n=n===null?e.isGlobal(this)?this.globalCache:this.cache:n;let i=n.getData(e);i===void 0&&(i={},n.setData(e,i)),i[t]===void 0&&(i[t]={});let s=i[t];if(this.subBuildLayers.length===0)return s;const o=i.any?i.any.subBuilds:null,a=this.getClosestSubBuild(o);return a&&(s.subBuildsCache===void 0&&(s.subBuildsCache={}),s=s.subBuildsCache[a]||(s.subBuildsCache[a]={}),s.subBuilds=o),s}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t,n=null){const i=this.getDataFromNode(e,"vertex");let s=i.bufferAttribute;if(s===void 0){const o=this.uniforms.index++;n===null&&(n="nodeAttribute"+o),s=new ug(n,t,e),this.bufferAttributes.push(s),i.bufferAttribute=s}return s}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,i=this.shaderStage){const s=this.getDataFromNode(e,i,this.globalCache);let o=s.structType;if(o===void 0){const a=this.structs.index++;n===null&&(n="StructType"+a),o=new SP(n,t),this.structs[i].push(o),this.types[i][n]=e,s.structType=o}return o}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,i=null){const s=this.getDataFromNode(e,n,this.globalCache);let o=s.uniform;if(o===void 0){const a=this.uniforms.index++;o=new bP(i||"nodeUniform"+a,t,e),this.uniforms[n].push(o),this.registerDeclaration(o),s.uniform=o}return o}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage,s=!1){const o=this.getDataFromNode(e,i),a=this.getSubBuildProperty("variable",o.subBuilds);let u=o[a];if(u===void 0){const l=s?"_const":"_var",c=this.vars[i]||(this.vars[i]=[]),h=this.vars[l]||(this.vars[l]=0);t===null&&(t=(s?"nodeConst":"nodeVar")+h,this.vars[l]++),a!=="variable"&&(t=this.getSubBuildProperty(t,o.subBuilds));const d=e.getArrayCount(this);u=new Tb(t,n,s,d),s||c.push(u),this.registerDeclaration(u),o[a]=u}return u}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0)&&(e.cNode?this.isDeterministic(e.cNode):!0);if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0);if(e.isArrayNode){if(e.values!==null){for(const t of e.values)if(!this.isDeterministic(t))return!1}return!0}else if(e.isConstNode)return!0;return!1}getVaryingFromNode(e,t=null,n=e.getNodeType(this),i=null,s=null){const o=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",o.subBuilds);let u=o[a];if(u===void 0){const l=this.varyings,c=l.length;t===null&&(t="nodeVarying"+c),a!=="varying"&&(t=this.getSubBuildProperty(t,o.subBuilds)),u=new xP(t,n,i,s),l.push(u),this.registerDeclaration(u),o[a]=u}return u}registerDeclaration(e){const t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),i=this.renderer.debug.diagnostics.keywords,s=e.name;let o=s,a=this.getPropertyName(e),u=1;for(;i&&this.isReservedKeyword(o)||n[a]!==void 0;)o=s+"_"+u++,e.name=o,a=this.getPropertyName(e);o!==s&&Y(`TSL: Declaration name '${s}' of '${e.type}' is a reserved keyword or already in use. Renamed to '${o}'.`),n[a]=e}getCodeFromNode(e,t,n=this.shaderStage){const i=this.getDataFromNode(e);let s=i.code;if(s===void 0){const o=this.codes[n]||(this.codes[n]=[]),a=o.length;s=new vP("nodeCode"+a,t),o.push(s),i.code=s}return s}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:i}=this.getDataFromNode(e);let s=!0,o=t;for(;o;){if(i.get(o)===!0){s=!1;break}o=this.getDataFromNode(o).parentNodeBlock}if(s)for(const a of n)this.addLineFlowCode(a)}addLineFlowCodeBlock(e,t,n){const i=this.getDataFromNode(e),s=i.flowCodes||(i.flowCodes=[]),o=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);s.push(t),o.set(n,!0)}addLineFlowCode(e,t=null){return e===""?this:(t!==null&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e=e+`;
541
+ `),this.flow.code+=e,this)}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+=" ",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=this.renderer.backend;let n=cg.get(t);n===void 0&&(n=new WeakMap,cg.set(t,n));let i=n.get(e);if(i===void 0){i=new OM;const s=this.currentFunctionNode;this.currentFunctionNode=i,i.code=this.buildFunctionCode(e),this.currentFunctionNode=s,n.set(e,i)}return i}flowShaderNode(e){const t=e.layout,n={[Symbol.iterator](){let o=0;const a=Object.values(this);return{next:()=>({value:a[o],done:o++>=a.length})}}};for(const o of t.inputs)n[o.name]=new cM(o.type,o.name);e.layout=null;const i=e.call(n),s=this.flowStagesNode(i,t.type);return e.layout=t,s}flowBuildStage(e,t,n=null){const i=this.getBuildStage();this.setBuildStage(t);const s=e.build(this,n);return this.setBuildStage(i),s}flowStagesNode(e,t=null){const n=this.flow,i=this.vars,s=this.declarations,o=this.cache,a=this.buildStage,u=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new nc,this.stack=Yl();for(const c of El)this.setBuildStage(c),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.declarations=s,this.cache=o,this.stack=u,this.setBuildStage(a),l}getFunctionOperator(){return null}buildFunctionCode(){Y("Abstract function.")}flowChildNode(e,t=null){const n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){const s=this.tab,o=this.cache,a=this.shaderStage,u=this.context;this.setShaderStage(e);const l={...this.context};delete l.nodeBlock,this.cache=this.globalCache,this.tab=" ",this.context=l;let c=null;if(this.buildStage==="generate"){const h=this.flowChildNode(t,n);i!==null&&(h.code+=`${this.tab+i} = ${h.result};
542
+ `),this.flowCode[e]=this.flowCode[e]+h.code,c=h}else c=t.build(this);return this.setShaderStage(a),this.cache=o,this.tab=s,this.context=u,c}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){Y("Abstract function.")}getVaryings(){Y("Abstract function.")}getVar(e,t,n=null){return`${n!==null?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e,t=!1){const n=[],i=this.vars[e];if(i!==void 0)for(const s of i)n.push(`${this.getVar(s.type,s.name,s.count)};`);return n.join(t?`
543
+ `:`
544
+ `)}getUniforms(){Y("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(t!==void 0)for(const i of t)n+=i.code+`
545
+ `;return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){Y("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(e&&e.isNode?e.isShaderCallNodeInternal?t=e.shaderNode.subBuilds:e.isStackNode?t=[e.subBuild]:t=this.getDataFromNode(e,"any").subBuilds:e instanceof Set?t=[...e]:t=e,!t)return null;const n=this.subBuildLayers;for(let i=t.length-1;i>=0;i--){const s=t[i];if(n.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let n;t!==null?n=this.getClosestSubBuild(t):n=this.subBuildFn;let i;return n?i=e?n+"_"+e:n:i=e,i}prebuild(){const{renderer:e,material:t}=this;if(e.contextNode.isContextNode===!0?this.context={...this.context,...e.contextNode.getFlowContextData()}:V('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),t&&t.contextNode&&(t.contextNode.isContextNode===!0?this.context={...this.context,...t.contextNode.getFlowContextData()}:V('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),t!==null){let n=e.library.fromMaterial(t);n===null&&(V(`NodeBuilder: Material "${t.type}" is not compatible.`),n=new Ke),n.build(this)}else this.addFlow("compute",this.compute)}build(){this.prebuild();for(const e of El){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Cl){this.setShaderStage(t);const n=this.flowNodes[t];for(const i of n)e==="generate"?this.flowNode(i):i.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(const e of El){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Cl){this.setShaderStage(t);const n=this.flowNodes[t];for(const i of n)e==="generate"?this.flowNode(i):i.build(this);await Ac()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=VP.get(e);return t===void 0&&(t={}),t}getNodeUniform(e,t){const n=this.getSharedDataFromNode(e);let i=n.cache;if(i===void 0){if(t==="float"||t==="int"||t==="uint")i=new BP(e);else if(t==="vec2"||t==="ivec2"||t==="uvec2")i=new FP(e);else if(t==="vec3"||t==="ivec3"||t==="uvec3")i=new DP(e);else if(t==="vec4"||t==="ivec4"||t==="uvec4")i=new LP(e);else if(t==="color")i=new OP(e);else if(t==="mat2")i=new UP(e);else if(t==="mat3")i=new IP(e);else if(t==="mat4")i=new kP(e);else throw new Error(`THREE.NodeBuilder: Uniform "${t}" not implemented.`);n.cache=i}return i}format(e,t,n){if(t=this.getVectorType(t),n=this.getVectorType(n),t===n||n===null||this.isReference(n))return e;const i=this.getTypeLength(t),s=this.getTypeLength(n);return i===16&&s===9?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:i===9&&s===4?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||s>4||s===0?e:i===s?`${this.getType(n)}( ${e} )`:i>s?(e=n==="bool"?`all( ${e} )`:`${e}.${"xyz".slice(0,s)}`,this.format(e,this.getTypeFromLength(s,this.getComponentType(t)),n)):s===4&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:i===2?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(i===1&&s>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${Ou} - Node System
546
+ `}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||this.object!==null&&M_(this.object).useVelocity===!0}}class hg{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null,this.compute=null}_getMaps(e,t){let n=e.get(t);return n===void 0&&(n={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(this),n=e.updateReference(this);if(t===ie.FRAME){const i=this._getMaps(this.updateBeforeMap,n);if(i.frameId!==this.frameId){const s=i.frameId;i.frameId=this.frameId,e.updateBefore(this)===!1&&(i.frameId=s)}}else if(t===ie.RENDER){const i=this._getMaps(this.updateBeforeMap,n);if(i.renderId!==this.renderId){const s=i.renderId;i.renderId=this.renderId,e.updateBefore(this)===!1&&(i.renderId=s)}}else t===ie.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(this),n=e.updateReference(this);if(t===ie.FRAME){const i=this._getMaps(this.updateAfterMap,n);i.frameId!==this.frameId&&e.updateAfter(this)!==!1&&(i.frameId=this.frameId)}else if(t===ie.RENDER){const i=this._getMaps(this.updateAfterMap,n);i.renderId!==this.renderId&&e.updateAfter(this)!==!1&&(i.renderId=this.renderId)}else t===ie.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(this),n=e.updateReference(this);if(t===ie.FRAME){const i=this._getMaps(this.updateMap,n);i.frameId!==this.frameId&&e.update(this)!==!1&&(i.frameId=this.frameId)}else if(t===ie.RENDER){const i=this._getMaps(this.updateMap,n);i.renderId!==this.renderId&&e.update(this)!==!1&&(i.renderId=this.renderId)}else t===ie.OBJECT&&e.update(this)}update(){this.frameId++,this.lastTime===void 0&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class zd{constructor(e,t,n=null,i="",s=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=s}}zd.isNodeFunctionInput=!0;class zP extends Ni{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class WP extends Ni{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:_b(this.light),lightColor:e}}}class HP extends Ni{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=gb(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=ne(new Dt).setGroup(Q)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:n,lightDirectionNode:i}=this,o=xs.dot(i).mul(.5).add(.5),a=Se(n,t,o);e.context.irradiance.addAssign(a)}}class Wd extends Ni{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=ne(0).setGroup(Q),this.penumbraCosNode=ne(0).setGroup(Q),this.cutoffDistanceNode=ne(0).setGroup(Q),this.decayExponentNode=ne(0).setGroup(Q),this.colorNode=ne(this.color).setGroup(Q)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:n,penumbraCosNode:i}=this;return Un(n,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return n===void 0&&(n=kM(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:s}=this,o=this.getLightVector(e),a=o.normalize(),u=a.dot(_b(s)),l=this.getSpotAttenuation(e,u),c=o.length(),h=vb({lightDistance:c,cutoffDistance:n,decayExponent:i});let d=t.mul(l).mul(h),f,p;return s.colorNode?(p=this.getLightCoord(e),f=s.colorNode(p)):s.map&&(p=this.getLightCoord(e),f=ve(s.map,p.xy).onRenderUpdate(()=>s.map)),f&&(d=p.mul(2).sub(1).abs().lessThan(1).all().select(d.mul(f),d)),{lightColor:d,lightDirection:a}}}class jP extends Wd{static get type(){return"IESSpotLightNode"}constructor(e=null){super(e),this._iesTextureNode=null}getSpotAttenuation(e,t){const n=this.light.iesMap;let i=null;if(n&&n.isTexture===!0){const s=t.acos().mul(1/Math.PI);this._iesTextureNode=ve(n,re(s,0),0),i=this._iesTextureNode.r}else i=super.getSpotAttenuation(e,t);return i}update(e){super.update(e),this._iesTextureNode!==null&&this.light.iesMap&&(this._iesTextureNode.value=this.light.iesMap)}}class qP extends Ni{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let n=0;n<9;n++)t.push(new z);this.lightProbe=_t(t)}update(e){const{light:t}=this;super.update(e);for(let n=0;n<9;n++)this.lightProbe.array[n].copy(t.sh.coefficients[n]).multiplyScalar(t.intensity)}setup(e){const t=gP(xs,this.lightProbe);e.context.irradiance.addAssign(t)}}const XP=P(([r,e])=>{const t=r.abs().sub(e);return dr(ot(t,0)).add(_i(ot(t.x,t.y),0))});class KP extends Wd{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),t.aspect===null){let n=1;t.map!==null&&(n=t.map.width/t.map.height),t.shadow.aspect=n}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=N(0),n=this.penumbraCosNode,i=$d(this.light).mul(e.context.positionWorld||Ro);return Me(i.w.greaterThan(0),()=>{const s=i.xyz.div(i.w),o=XP(s.xy.sub(re(.5)),re(.5)),a=On(-1,Et(1,z_(n)).sub(1));t.assign(Ed(o.mul(-2).mul(a)))}),t}}const rc=new bt,ga=new bt;let Vs=null;class YP extends Ni{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=ne(new z).setGroup(Q),this.halfWidth=ne(new z).setGroup(Q),this.updateType=ie.RENDER}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;ga.identity(),rc.copy(t.matrixWorld),rc.premultiply(n),ga.extractRotation(rc),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(ga),this.halfHeight.value.applyMatrix4(ga)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=ve(Vs.LTC_FLOAT_1),n=ve(Vs.LTC_FLOAT_2)):(t=ve(Vs.LTC_HALF_1),n=ve(Vs.LTC_HALF_2));const{colorNode:i,light:s}=this,o=mb(s);return{lightColor:i,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){Vs=e}}class Rb{parseFunction(){Y("Abstract function.")}}class Hd{constructor(e,t,n="",i=""){this.type=e,this.inputs=t,this.name=n,this.precision=i}getCode(){Y("Abstract function.")}}Hd.isNodeFunction=!0;const QP=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,ZP=/[a-z_0-9]+/ig,dg="#pragma main",JP=r=>{r=r.trim();const e=r.indexOf(dg),t=(e!==-1?r.slice(e+dg.length):r).replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,""),n=t.match(QP);if(n!==null&&n.length===5){const i=n[4],s=[];let o=null;for(;(o=ZP.exec(i))!==null;)s.push(o);const a=[];let u=0;for(;u<s.length;){const p=s[u][0]==="const";p===!0&&u++;let g=s[u][0];g==="in"||g==="out"||g==="inout"?u++:g="";const _=s[u++][0];let m=Number.parseInt(s[u][0]);Number.isNaN(m)===!1?u++:m=null;const y=s[u++][0];a.push(new zd(_,y,m,g,p))}const l=t.substring(n[0].length),c=n[3]!==void 0?n[3]:"",h=n[2],d=n[1]!==void 0?n[1]:"",f=e!==-1?r.slice(0,e):"";return{type:h,inputs:a,name:c,precision:d,inputsCode:i,blockCode:l,headerCode:f}}else throw new Error("THREE.FunctionNode: Function is not a GLSL code.")};class eB extends Hd{constructor(e){const{type:t,inputs:n,name:i,precision:s,inputsCode:o,blockCode:a,headerCode:u}=JP(e);super(t,n,i,s),this.inputsCode=o,this.blockCode=a,this.headerCode=u}getCode(e=this.name){let t;const n=this.blockCode;if(n!==""){const{type:i,inputsCode:s,headerCode:o,precision:a}=this;let u=`${i} ${e} ( ${s.trim()} )`;a!==""&&(u=`${a} ${u}`),t=o+u+n}else t="";return t}}class tB extends Rb{parseFunction(e){return new eB(e)}}const Xt=[],zn=[],fg=ne(0,"int").setGroup(Q);class nB extends jr{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new hg,this.nodeBuilderCache=new Map,this.callHashCache=new zr,this.groupsData=new zr,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;if(t.updateType===ie.OBJECT)return!0;Xt[0]=t,Xt[1]=e;let n=this.groupsData.get(Xt);return n===void 0&&this.groupsData.set(Xt,n={}),Xt[0]=null,Xt[1]=null,n.version!==t.version?(n.version=t.version,!0):!1}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){const n=this.backend.createNodeBuilder(e.object,this.renderer),i=this.renderer.debug.onNodeBuilderCreated;return i!==null&&i(n,e),n.scene=e.scene,n.material=t,n.camera=e.camera,n.context.material=t,n.lightsNode=e.lightsNode,n.environmentNode=this.getEnvironmentNode(e.scene),n.fogNode=this.getFogNode(e.scene),n.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&n.enableMultiview(),n}getForRender(e,t=!1){const n=this.get(e);let i=n.nodeBuilderState;if(i===void 0){const{nodeBuilderCache:s}=this,o=this.getForRenderCacheKey(e);if(i=s.get(o),i===void 0){const a=async()=>{let u=this._createNodeBuilder(e,e.material);try{t?await u.buildAsync():u.build()}catch(l){u=this._createNodeBuilder(e,new Ke),t?await u.buildAsync():u.build(),V("TSL: "+l)}return u};if(t)return a().then(u=>(i=this._createNodeBuilderState(u),s.set(o,i),i.usedTimes++,n.nodeBuilderState=i,i));{let u=this._createNodeBuilder(e,e.material);try{u.build()}catch(l){u=this._createNodeBuilder(e,new Ke),u.build();let c=l.stackTrace;!c&&l.stack&&(c=new Ft(l.stack)),V("TSL: "+l,c)}i=this._createNodeBuilderState(u),s.set(o,i)}}i.usedTimes++,n.nodeBuilderState=i}return i}getForRenderAsync(e){const t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){const t=this.get(e);if(t.nodeBuilderState!==void 0)return t.nodeBuilderState;const n=this.getForRenderCacheKey(e),i=this.nodeBuilderCache.get(n);return i!==void 0?(i.usedTimes++,t.nodeBuilderState=i,i):(t.pendingBuild!==!0&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||this._buildQueue.length===0)return;this._buildInProgress=!0,this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t!==void 0&&(t.usedTimes--,t.usedTimes===0&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e,t=!1){const n=this.get(e);let i=n.nodeBuilderState;if(i===void 0||n.version!==e.version){const s=this.backend.createNodeBuilder(null,this.renderer);s.compute=e;const o=this.renderer.debug.onNodeBuilderCreated;if(o!==null&&o(s,e),t)return s.buildAsync().then(()=>(i=this._createNodeBuilderState(s),n.nodeBuilderState=i,n.version=e.version,i));s.build(),i=this._createNodeBuilderState(s),n.nodeBuilderState=i,n.version=e.version}return i}getForComputeAsync(e){const t=this.getForCompute(e,!0);return t.then?t:Promise.resolve(t)}_createNodeBuilderState(e){return new yP(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.hardwareClipping,e.transforms)}getEnvironmentNode(e){if(this.renderer.lighting.enabled===!1)return null;this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const n=this.get(e);n.environmentNode&&(t=n.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const n=this.get(e);n.backgroundNode&&(t=n.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){Xt[0]=e,Xt[1]=t;const n=this.renderer.info.calls,i=this.callHashCache.get(Xt)||{};if(i.callId!==n){if(zn.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),zn.push(this.renderer.lighting.enabled?1:0),this.renderer.lighting.enabled){zn.push(t.getCacheKey(!0)),zn.push(this.renderer.shadowMap.enabled?1:0),zn.push(this.renderer.shadowMap.type);const o=this.getEnvironmentNode(e);o&&zn.push(o.getCacheKey())}const s=this.getFogNode(e);s&&zn.push(s.getCacheKey()),i.callId=n,i.cacheKey=Do(zn),this.callHashCache.set(Xt,i),zn.length=0}return Xt[0]=null,Xt[1]=null,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),n=e.background;if(n){const i=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;if(t.background!==n||i){const s=this.getCacheNode("background",n,()=>{if(n.isCubeTexture===!0||n.mapping===td||n.mapping===nd||n.mapping===ru){if(e.backgroundBlurriness>0||n.mapping===ru)return rb(n);{let o;return n.isCubeTexture===!0?o=Mt(n):o=ve(n),Xy(o)}}else{if(n.isTexture===!0)return ve(n,Or.flipY()).setUpdateMatrix(!0);n.isColor!==!0&&V("WebGPUNodes: Unsupported background configuration.",n)}},i);t.backgroundNode=s,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,i=!1){const s=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let o=s.get(t);if(o===void 0||i){if(o===void 0&&t.isTexture===!0){const a=()=>{t.removeEventListener("dispose",a);const u=s.get(t);u!==void 0&&(s.delete(t),u.dispose())};t.addEventListener("dispose",a)}o=n(),s.set(t,o)}return o}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const i=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){const s=Be("color","color",n).setGroup(Q),o=Be("density","float",n).setGroup(Q);return sg(s,IM(o))}else if(n.isFog){const s=Be("color","color",n).setGroup(Q),o=Be("near","float",n).setGroup(Q),a=Be("far","float",n).setGroup(Q);return sg(s,UM(o,a))}else V("Renderer: Unsupported fog configuration.",n)});t.fogNode=i,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){const i=this.getCacheNode("environment",n,()=>{if(n.isCubeTexture===!0)return Mt(n);if(n.isTexture===!0)return ve(n);V("Nodes: Unsupported environment configuration.",n)});t.environmentNode=i,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,s=null,o=null){const a=this.nodeFrame;return a.renderer=e,a.scene=t,a.object=n,a.camera=i,a.material=s,a.compute=o,a}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getNodeFrameForCompute(e){return this.getNodeFrame(this.renderer,null,null,null,null,e)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;let n;return e.isArrayTexture?this.backend.isWebGLBackend?n=ve(e,Or).depth(gr("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):n=ve(e,Or).depth(fg).renderOutput(t.toneMapping,t.currentColorSpace):n=ve(e,Or).renderOutput(t.toneMapping,t.currentColorSpace),n}setOutputLayerIndex(e){fg.value=e}updateBefore(e){const t=e.getNodeBuilderState();for(const n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){const t=e.getNodeBuilderState();for(const n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateBeforeForCompute(e){const t=this.getForCompute(e);for(const n of t.updateBeforeNodes)this.getNodeFrameForCompute(e).updateBeforeNode(n)}updateAfterForCompute(e){const t=this.getForCompute(e);for(const n of t.updateAfterNodes)this.getNodeFrameForCompute(e).updateAfterNode(n)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const i of n.updateNodes)t.updateNode(i)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const i of n.updateNodes)t.updateNode(i)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new hg,this.nodeBuilderCache=new Map,this.cacheLib={}}}const ic=new jh;let rB=0;class Ru{constructor(e=null){this.id=rB++,this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewMatrix=new bt,this.viewNormalMatrix=new gs,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,e!==null&&(this.viewMatrix=e.viewMatrix,this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass)}projectPlanes(e,t,n){const i=e.length;for(let s=0;s<i;s++){ic.copy(e[s]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const o=t[n+s],a=ic.normal;o.x=-a.x,o.y=-a.y,o.z=-a.z,o.w=ic.constant}}updateGlobal(e,t){this.shadowPass=e.overrideMaterial!==null&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix.copy(t.matrixWorldInverse),this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let n=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,s=i.length;let o,a;if(this.clipIntersection?(o=this.intersectionPlanes,a=e.intersectionPlanes.length):(o=this.unionPlanes,a=e.unionPlanes.length),o.length!==a+s){o.length=a+s;for(let u=0;u<s;u++)o[a+u]=new tt;n=!0}this.projectPlanes(i,o,a),n&&(this.version++,this.cacheKey=`${this.id}:${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return t===void 0&&(t=new Ru(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class iB{constructor(e,t,n){this.bundleGroup=e,this.camera=t,this.renderContext=n}}const xr=[];class sB{constructor(){this.bundles=new zr}get(e,t,n){const i=this.bundles;xr[0]=e,xr[1]=t,xr[2]=n;let s=i.get(xr);return s===void 0&&(s=new iB(e,t,n),i.set(xr,s)),xr[0]=null,xr[1]=null,xr[2]=null,s}dispose(){this.bundles=new zr}}class Ab{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const n=this.getMaterialNodeClass(e.type);if(n!==null){t=new n;for(const i in e)t[i]=e[i]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,n){if(n.has(t)){Y(`Redefinition of node ${t}`);return}if(typeof e!="function")throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if(typeof t=="function"||typeof t=="object")throw new Error(`THREE.NodeLibrary: Base class ${t} is not a class.`);n.set(t,e)}addClass(e,t,n){if(n.has(t)){Y(`Redefinition of node ${t.name}`);return}if(typeof e!="function")throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if(typeof t!="function")throw new Error(`THREE.NodeLibrary: Base class ${t.name} is not a class.`);n.set(t,e)}}const oB=new yb;class aB{constructor(){this.enabled=!0,this._cache=[],this._lightsNodeMap=new WeakMap}createNode(e=[]){return new yb().setLights(e)}getNode(e){if(e.isScene!==!0&&e.isGroup!==!0)return oB;let t=this._lightsNodeMap.get(e);return t===void 0&&(t=this.createNode(),this._lightsNodeMap.set(e,t)),t}beginRender(e){this._cache.push(this.getNode(e).getLights())}finishRender(e){this.getNode(e).setLights(this._cache.pop())}}class to extends Ti{constructor(e=1,t=1,n={}){super(e,t,n),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const pg=new z,gg=new z,mg=new WeakMap;class uB extends Lu{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new yo,this._cameraL.viewport=new tt,this._cameraL.matrixWorldAutoUpdate=!1,this._cameraR=new yo,this._cameraR.viewport=new tt,this._cameraR.matrixWorldAutoUpdate=!1,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new jx,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding=typeof XRWebGLBinding<"u",this._supportsWebGPUBinding=typeof globalThis.XRGPUBinding<"u",this._createXRLayer=pB.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new de,this._currentCameraSettings=null,this._onSessionEvent=hB.bind(this),this._onSessionEnd=dB.bind(this),this._onInputSourcesChange=fB.bind(this),this._onAnimationFrame=gB.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._webgpuBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){return this._foveation}setFoveation(e){this._foveation=e,this._glProjLayer!==null&&(this._glProjLayer.fixedFoveation=e),this._glBaseLayer!==null&&this._glBaseLayer.fixedFoveation!==void 0&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,this.isPresenting===!0&&Y("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,this.isPresenting===!0&&Y("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(this._session!==null)return this._session.environmentBlendMode}getBaseLayer(){return this._glProjLayer!==null?this._glProjLayer:this._glBaseLayer}getBinding(){return this._glBinding===null&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}foveateBoundTexture(e){if(e===null||e.isPostProcessingRenderTarget!==!0||this.isPresenting!==!0||this._glProjLayer===null)return;const t=this._renderer.backend;if(t===void 0||t.isWebGLBackend!==!0||t.state===null)return;const n=this._renderer.getOutputRenderTarget();if(n===null||n.isXRRenderTarget!==!0)return;const i=this.getBinding();if(i===null||typeof i.foveateBoundTexture!="function")return;this._renderer._textures.updateRenderTarget(e);const{textureGPU:s,glTextureType:o}=t.get(e.texture);if(!(s===void 0||o===void 0)&&e._xrFoveationTextureGPU!==s){e._xrFoveationTextureGPU=s,t.state.bindTexture(o,s);try{i.foveateBoundTexture(o,this.getFoveation())}catch(a){Fe(`XRManager: Unable to foveate bound XR post-processing texture. ${a.name}: ${a.message}`)}finally{t.state.unbindTexture()}}}getWebGPUBinding(){return this._webgpuBinding===null&&this._supportsWebGPUBinding&&(this._webgpuBinding=new globalThis.XRGPUBinding(this._session,this._renderer.backend.device)),this._webgpuBinding}_isWebGPUSession(){return this._renderer.backend.isWebGPUBackend===!0&&this._session!==null&&this._session.enabledFeatures.includes("webgpu")}_validateWebGPUSession(){if(this._renderer.backend.isWebGPUBackend===!0&&this._session.enabledFeatures.includes("webgpu")===!1)throw new Error('THREE.XRManager: WebGPU XR sessions require the "webgpu" session feature. Use VRButtonGPU/XRButton with "webgpu" enabled or use a WebGL backend.')}async _initWebGPUSession(e){const t=this.getWebGPUBinding(),n=t.createProjectionLayer({colorFormat:t.getPreferredColorFormat()});this._glProjLayer=n,e.updateRenderState({layers:[n]}),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._xrRenderTarget=new Ti(n.textureWidth,n.textureHeight,{depth:2,minFilter:Rt,magFilter:Rt,depthBuffer:!0,multiview:!1,useArrayDepthTexture:!0,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,samples:this._renderer.samples}),this._xrRenderTarget.texture.isArrayTexture=!0,this._useMultiviewIfPossible===!0&&Fe("THREE.XRManager: WebGPU XR does not support multiview yet. Disabling multiview for this XR session."),this._useMultiview=!1}_disposeWebGPUSession(){const e=this._renderer,t=e.backend,n=this._xrRenderTarget;if(!(n===null||t.isWebGPUBackend!==!0)){e._renderContexts&&e._renderContexts.dispose&&e._renderContexts.dispose(),n.dispose();for(const i of n.textures)t.has(i)&&t.destroyTexture(i);t.delete(n)}}_getWebGPUViewData(e){const t=this.getWebGPUBinding(),n={colorTexture:null,viewDescriptors:[],viewports:[]};for(let i=0;i<e.length;i++){const s=t.getViewSubImage(this._glProjLayer,e[i]);n.colorTexture===null&&(n.colorTexture=s.colorTexture),n.viewports.push(s.viewport),s.getViewDescriptor&&n.viewDescriptors.push(s.getViewDescriptor())}return n}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,n,i,s,o,a,u={}){const l=new qx(e,t),c=new to(s,o,{format:Qt,type:Pt,depthTexture:new ar(s,o,u.stencil?or:qe,void 0,void 0,void 0,void 0,void 0,void 0,u.stencil?Ln:Dn),stencilBuffer:u.stencil,samples:u.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),h=new Br({color:16777215,side:li});h.map=c.texture,h.map.offset.y=1,h.map.repeat.y=-1;const d=new yn(l,h);d.position.copy(n),d.quaternion.copy(i);const f={type:"quad",width:e,height:t,translation:n,quaternion:i,pixelwidth:s,pixelheight:o,samples:c.samples,plane:d,material:h,rendercall:a,renderTarget:c};if(this._layers.push(f),this._session!==null){f.plane.material=new Br({color:16777215,side:li}),f.plane.material.blending=ci,f.plane.material.blendEquation=Qn,f.plane.material.blendSrc=Cr,f.plane.material.blendDst=Cr,f.xrlayer=this._createXRLayer(f);const p=this._session.renderState.layers;p.unshift(f.xrlayer),this._session.updateRenderState({layers:p})}else c.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,n,i,s,o,a,u,l={}){const c=new rm(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),h=new to(o,a,{format:Qt,type:Pt,depthTexture:new ar(o,a,l.stencil?or:qe,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?Ln:Dn),stencilBuffer:l.stencil,samples:l.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),d=new Br({color:16777215,side:yt});d.map=h.texture,d.map.offset.y=1,d.map.repeat.y=-1;const f=new yn(c,d);f.position.copy(i),f.quaternion.copy(s);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:n,translation:i,quaternion:s,pixelwidth:o,pixelheight:a,samples:h.samples,plane:f,material:d,rendercall:u,renderTarget:h};if(this._layers.push(p),this._session!==null){p.plane.material=new Br({color:16777215,side:yt}),p.plane.material.blending=ci,p.plane.material.blendEquation=Qn,p.plane.material.blendSrc=Cr,p.plane.material.blendDst=Cr,p.xrlayer=this._createXRLayer(p);const g=this._session.renderState.layers;g.unshift(p.xrlayer),this._session.updateRenderState({layers:g})}else h.isXRRenderTarget=!1;return f}renderLayers(){const e=new z,t=new ns,n=this._renderer,i=this.isPresenting;this.isPresenting=!1;const s=new de;n.getSize(s);const o=n.getRenderTarget();for(const a of this._layers){a.renderTarget.isXRRenderTarget=this._session!==null,a.renderTarget._hasExternalTextures=a.renderTarget.isXRRenderTarget;const u=n.contextNode;let l;if(a.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){a.xrlayer.transform=new XRRigidTransform(a.plane.getWorldPosition(e),a.plane.getWorldQuaternion(t));const c=this._glBinding.getSubImage(a.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(a.renderTarget,c.colorTexture,void 0),n._setXRLayerSize(a.renderTarget.width,a.renderTarget.height),l=mg.get(u),l===void 0&&(l=pr({getOutput:h=>oy(h,n.toneMapping,n.outputColorSpace),...u.getFlowContextData()}),mg.set(u,l))}else l=u;n.contextNode=l,n.setRenderTarget(a.renderTarget),a.rendercall(),n.contextNode=u}n.setRenderTarget(o),n._setXRLayerSize(s.x,s.y),this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer;t.initialized===!1&&await t.init(),this._gl=t.getContext();const n=this._gl;if(this._session=e,e!==null){if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),this._validateWebGPUSession(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._isWebGPUSession())await this._initWebGPUSession(e);else if(this._supportsLayers===!0){let i=null,s=null,o=null;const a=n.getContextAttributes();await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation()),t.depth&&(o=t.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,i=t.stencil?Ln:Dn,s=t.stencil?or:qe);const u={colorFormat:n.RGBA8,depthFormat:o,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(u.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const l=this._glBinding.createProjectionLayer(u),c=[l];this._glProjLayer=l,t.setPixelRatio(1),t._setXRLayerSize(l.textureWidth,l.textureHeight);const h=this._useMultiview?2:1,d=new ar(l.textureWidth,l.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,i,h);if(this._xrRenderTarget=new to(l.textureWidth,l.textureHeight,{format:Qt,type:Pt,colorSpace:t.outputColorSpace,depthTexture:d,stencilBuffer:t.stencil,samples:a.antialias?4:0,resolveDepthBuffer:l.ignoreDepthValues===!1,resolveStencilBuffer:l.ignoreDepthValues===!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:l.ignoreDepthValues===!1,storeMultisampledStencilBuffer:l.ignoreDepthValues===!1,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const f of this._layers)f.plane.material=new Br({color:16777215,side:f.type==="cylinder"?yt:li}),f.plane.material.blending=ci,f.plane.material.blendEquation=Qn,f.plane.material.blendSrc=Cr,f.plane.material.blendDst=Cr,f.xrlayer=this._createXRLayer(f),c.unshift(f.xrlayer);e.updateRenderState({layers:c})}else{await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation());const i={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},s=new XRWebGLLayer(e,n,i);this._glBaseLayer=s,e.updateRenderState({baseLayer:s}),t.setPixelRatio(1),t._setXRLayerSize(s.framebufferWidth,s.framebufferHeight),this._xrRenderTarget=new to(s.framebufferWidth,s.framebufferHeight,{format:Qt,type:Pt,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(t===null)return;const n=e.near,i=e.far,s=this._cameraXR,o=this._cameraL,a=this._cameraR;s.near=a.near=o.near=n,s.far=a.far=o.far=i,s.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==s.near||this._currentDepthFar!==s.far)&&(t.updateRenderState({depthNear:s.near,depthFar:s.far}),this._currentDepthNear=s.near,this._currentDepthFar=s.far),s.layers.mask=e.layers.mask|6,o.layers.mask=s.layers.mask&-5,a.layers.mask=s.layers.mask&-3;const u=e.parent,l=s.cameras;_g(s,u);for(let c=0;c<l.length;c++)_g(l[c],u);l.length===2?lB(s,o,a):s.projectionMatrix.copy(o.projectionMatrix),this._currentCameraSettings===null&&e.isPerspectiveCamera&&(this._currentCameraSettings={camera:e,fov:e.fov,zoom:e.zoom}),cB(e,s,u)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new Xx,this._controllers[e]=t),t}}function lB(r,e,t){pg.setFromMatrixPosition(e.matrixWorld),gg.setFromMatrixPosition(t.matrixWorld);const n=pg.distanceTo(gg),i=e.projectionMatrix.elements,s=t.projectionMatrix.elements,o=i[14]/(i[10]-1),a=i[14]/(i[10]+1),u=(i[9]+1)/i[5],l=(i[9]-1)/i[5],c=(i[8]-1)/i[0],h=(s[8]+1)/s[0],d=o*c,f=o*h,p=n/(-c+h),g=p*-c;if(e.matrixWorld.decompose(r.position,r.quaternion,r.scale),r.translateX(g),r.translateZ(p),r.matrixWorld.compose(r.position,r.quaternion,r.scale),r.matrixWorldInverse.copy(r.matrixWorld).invert(),i[10]===-1)r.projectionMatrix.copy(e.projectionMatrix),r.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{const _=o+p,m=a+p,y=d-g,b=f+(n-g),T=u*a/m*_,x=l*a/m*_;r.projectionMatrix.makePerspective(y,b,T,x,_,m),r.projectionMatrixInverse.copy(r.projectionMatrix).invert()}}function _g(r,e){e===null?r.matrixWorld.copy(r.matrix):r.matrixWorld.multiplyMatrices(e.matrixWorld,r.matrix),r.matrixWorldInverse.copy(r.matrixWorld).invert()}function cB(r,e,t){t===null?r.matrix.copy(e.matrixWorld):(r.matrix.copy(t.matrixWorld),r.matrix.invert(),r.matrix.multiply(e.matrixWorld)),r.matrix.decompose(r.position,r.quaternion,r.scale),r.updateMatrixWorld(!0),r.projectionMatrix.copy(e.projectionMatrix),r.projectionMatrixInverse.copy(e.projectionMatrixInverse),r.isPerspectiveCamera&&(r.fov=lv*2*Math.atan(1/r.projectionMatrix.elements[5]),r.zoom=1)}function hB(r){const e=this._controllerInputSources.indexOf(r.inputSource);if(e===-1)return;const t=this._controllers[e];if(t!==void 0){const n=this.getReferenceSpace();t.update(r.inputSource,r.frame,n),t.dispatchEvent({type:r.type,data:r.inputSource})}}function dB(){const r=this._session,e=this._renderer;r.removeEventListener("select",this._onSessionEvent),r.removeEventListener("selectstart",this._onSessionEvent),r.removeEventListener("selectend",this._onSessionEvent),r.removeEventListener("squeeze",this._onSessionEvent),r.removeEventListener("squeezestart",this._onSessionEvent),r.removeEventListener("squeezeend",this._onSessionEvent),r.removeEventListener("end",this._onSessionEnd),r.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let t=0;t<this._controllers.length;t++){const n=this._controllerInputSources[t];n!==null&&(this._controllerInputSources[t]=null,this._controllers[t].disconnect(n))}if(this._currentDepthNear=null,this._currentDepthFar=null,e._resetXRState(),this._disposeWebGPUSession(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._webgpuBinding=null,this._glBaseLayer=null,this._glProjLayer=null,this._sessionUsesLayers===!0)for(const t of this._layers)t.renderTarget=new to(t.pixelwidth,t.pixelheight,{format:Qt,type:Pt,depthTexture:new ar(t.pixelwidth,t.pixelheight,t.stencilBuffer?or:qe,void 0,void 0,void 0,void 0,void 0,void 0,t.stencilBuffer?Ln:Dn),stencilBuffer:t.stencilBuffer,samples:t.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),t.renderTarget.isXRRenderTarget=!1,t.plane.material=t.material,t.material.map=t.renderTarget.texture,t.material.map.offset.y=1,t.material.map.repeat.y=-1,delete t.xrlayer;if(this.isPresenting=!1,this._useMultiview=!1,e._animation.stop(),e._animation.setAnimationLoop(this._currentAnimationLoop),e._animation.setContext(this._currentAnimationContext),e._animation.start(),e.setPixelRatio(this._currentPixelRatio),e.setSize(this._currentSize.width,this._currentSize.height,!1),this._currentCameraSettings!==null){const t=this._currentCameraSettings.camera;t.fov=this._currentCameraSettings.fov,t.zoom=this._currentCameraSettings.zoom,t.updateProjectionMatrix(),this._currentCameraSettings=null}this.dispatchEvent({type:"sessionend"})}function fB(r){const e=this._controllers,t=this._controllerInputSources;for(let n=0;n<r.removed.length;n++){const i=r.removed[n],s=t.indexOf(i);s>=0&&(t[s]=null,e[s].disconnect(i))}for(let n=0;n<r.added.length;n++){const i=r.added[n];let s=t.indexOf(i);if(s===-1){for(let a=0;a<e.length;a++)if(a>=t.length){t.push(i),s=a;break}else if(t[a]===null){t[a]=i,s=a;break}if(s===-1)break}const o=e[s];o&&o.connect(i)}}function pB(r){return r.type==="quad"?this._glBinding.createQuadLayer({transform:new XRRigidTransform(r.translation,r.quaternion),width:r.width/2,height:r.height/2,space:this._referenceSpace,viewPixelWidth:r.pixelwidth,viewPixelHeight:r.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(r.translation,r.quaternion),radius:r.radius,centralAngle:r.centralAngle,aspectRatio:r.aspectRatio,space:this._referenceSpace,viewPixelWidth:r.pixelwidth,viewPixelHeight:r.pixelheight,clearOnAccess:!1})}function gB(r,e){if(e===void 0)return;const t=this._cameraXR,n=this._renderer,i=n.backend,s=this._glBaseLayer,o=this.getReferenceSpace(),a=e.getViewerPose(o);if(this._xrFrame=e,a!==null){const u=a.views,l=this._isWebGPUSession()?this._getWebGPUViewData(u):null;this._glBaseLayer!==null&&l===null&&i.setXRTarget(s.framebuffer);let c=!1;u.length!==t.cameras.length&&(t.cameras.length=0,c=!0);for(let d=0;d<u.length;d++){const f=u[d];let p;if(l!==null)p=l.viewports[d];else if(this._supportsLayers===!0){const _=this._glBinding.getViewSubImage(this._glProjLayer,f);p=_.viewport,d===0&&i.setXRRenderTargetTextures(this._xrRenderTarget,_.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:_.depthStencilTexture)}else p=s.getViewport(f);let g=this._cameras[d];g===void 0&&(g=new yo,g.layers.enable(d),g.viewport=new tt,g.matrixWorldAutoUpdate=!1,this._cameras[d]=g),g.matrix.fromArray(f.transform.matrix),g.matrix.decompose(g.position,g.quaternion,g.scale),g.projectionMatrix.fromArray(f.projectionMatrix),g.projectionMatrixInverse.copy(g.projectionMatrix).invert(),g.viewport.set(p.x,p.y,p.width,p.height),d===0&&(t.matrix.copy(g.matrix),t.matrix.decompose(t.position,t.quaternion,t.scale)),c===!0&&t.cameras.push(g)}l!==null&&l.colorTexture!==null&&i.setXRRenderTargetTextures(this._xrRenderTarget,l.colorTexture,l.viewDescriptors),n.setOutputRenderTarget(this._xrRenderTarget);const h=n._getFrameBufferTarget();l!==null&&(this._xrRenderTarget.samples=h===null?n.samples:0,this._xrRenderTarget.depthBuffer=h===null),n.xr.foveateBoundTexture(h)}for(let u=0;u<this._controllers.length;u++){const l=this._controllerInputSources[u],c=this._controllers[u];l!==null&&c!==void 0&&c.update(l,e,o)}this._currentAnimationLoop&&this._currentAnimationLoop(r,e),e.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:e}),this._xrFrame=null}class mB extends Lu{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new tt(0,0,this._width,this._height),this._scissor=new tt(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new cm,this.depthTexture=new ar}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),n===!0&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,n,i){const s=this._scissor;e.isVector4?s.copy(e):s.set(e,t,n,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,i,s=0,o=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,i),a.minDepth=s,a.maxDepth=o}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const yg=new Kh,Di=new de,sc=new tt,ma=new Lx,_a=new Dx,Li=new bt,Wn=new tt,_B={[li]:yt,[yt]:li,[sr]:sr};class yB{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,reversedDepthBuffer:i=!1,alpha:s=!0,depth:o=!0,stencil:a=!1,antialias:u=!1,samples:l=0,getFallback:c=null,outputBufferType:h=wt,multiview:d=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=s,this.logarithmicDepthBuffer=n,this.reversedDepthBuffer=i,this.outputColorSpace=Xh,this.toneMapping=Ki,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=o,this.stencil=a,this.info=new q1,this.contextNode=pr(),this.library=new Ab,this.lighting=new aB,this._samples=l||(u===!0?4:0),this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new mB(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new ay,this._inspector.setRenderer(this),this._getFallback=c,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;const f=this.alpha===!0?0:1;this._clearColor=new Vd(0,0,0,f),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this.onError=this._onError,this._outputBufferType=h,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this._isPreCompiling=!1,this._currentSourceMaterial=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:Ga},this.xr=new uB(this,d),this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onNodeBuilderCreated:null,onShaderError:null,getShaderAsync:async(p,g,_)=>{await this.compileAsync(_,g,p);const y=this.needsFrameBufferTarget&&this._renderTarget===null?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,b=this._renderLists.get(p,g,this.lighting),T=this._renderContexts.get(y,this._mrt),x=p.overrideMaterial||_.material,v=this._objects.get(_,x,p,g,b.lightsNode,T,T.clippingContext),{fragmentShader:w,vertexShader:R}=v.getNodeBuilderState();return{fragmentShader:w,vertexShader:R}}}}async init(){return this._initPromise!==null?this._initPromise:(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(i){if(this._getFallback!==null)try{this.backend=n=this._getFallback(i),await n.init(this)}catch(s){t(s);return}else{t(i);return}}this._nodes=new nB(this,n),this._animation=new G1(this,this._nodes,this.info),this._attributes=new H1(n,this.info),this._background=new mP(this,this._nodes),this._geometries=new j1(this._attributes,this.info),this._textures=new aM(this,n,this.info),this._pipelines=new Q1(n,this._nodes,this.info),this._bindings=new Z1(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new W1(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new nM,this._bundles=new sB,this._renderContexts=new sM(this),this._animation.start(),this._initialized=!0,e(this)}),this._initPromise)}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null,i=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init(),this.shadowMap.type===tf&&(Y("WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.shadowMap.type=Ga);const s=this._nodes.nodeFrame,o=s.renderId,a=this._currentRenderContext,u=this._currentRenderObjectFunction,l=this._handleObjectFunction,c=this._compilationPromises;n===null&&(n=e);const h=e.isScene===!0?e:n.isScene===!0?n:yg,d=this.needsFrameBufferTarget&&this._renderTarget===null,f=this._renderTarget||this._outputRenderTarget,p=this.xr.isPresenting===!0&&this.isOutputTarget,g=d?this._getFrameBufferTarget():f,_=this._renderContexts.get(g,this._mrt),m=this._activeMipmapLevel,y=[];this._currentRenderContext=_,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=y,s.renderId++,s.update(),_.depth=this.depth,_.stencil=this.stencil,_.clippingContext||(_.clippingContext=new Ru),_.clippingContext.updateGlobal(h,t),e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t=this._updateCamera(t,p),h.onBeforeRender(this,e,t,g),Li.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?_a.setFromArrayCamera(t):ma.setFromProjectionMatrix(Li,t.coordinateSystem,t.reversedDepth);const b=this._renderLists.get(h,t,this.lighting);if(b.begin(),this._projectObject(e,t,0,b,_.clippingContext),n!==e&&n.traverseVisible(function(M){M.isLight&&M.layers.test(t.layers)&&b.pushLight(M)}),b.finish(),g!==null){this._textures.updateRenderTarget(g,m);const M=this._textures.get(g);_.textures=M.textures,_.depthTexture=M.depthTexture}else _.textures=null,_.depthTexture=null;n!==e?this._background.update(n,b,_):this._background.update(h,b,_);const T=b.opaque,x=b.transparent,v=b.transparentDoublePass,w=b.lightsNode;this.opaque===!0&&T.length>0&&this._renderObjects(T,t,h,w),this.transparent===!0&&x.length>0&&this._renderTransparents(x,v,t,h,w),s.renderId=o,this._currentRenderContext=a,this._currentRenderObjectFunction=u,this._handleObjectFunction=l,this._compilationPromises=c;const R=y.length;let F=0;for(const M of y){const O=this._objects.get(M.object,M.material,M.scene,M.camera,M.lightsNode,M.renderContext,M.clippingContext,M.passId);O.drawRange=M.object.geometry.drawRange,O.group=M.group,await this._nodes.getForRenderAsync(O),this._isPreCompiling=!0,this._nodes.updateBefore(O),this._geometries.updateForRender(O),this._nodes.updateForRender(O),this._bindings.updateForRender(O),this._isPreCompiling=!1;const U=[];this._pipelines.getForRender(O,U),U.length>0&&await Promise.all(U),this._isPreCompiling=!0,this._nodes.updateAfter(O),this._isPreCompiling=!1,F++,i!==null&&i(new ProgressEvent("progress",{lengthComputable:!0,loaded:F,total:R})),await Ac()}}async compileComputeAsync(e,t=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init();const n=Array.isArray(e)?e:[e];if(n.length===0||n.some(l=>l==null||l.isComputeNode!==!0))throw new Error("THREE.Renderer: .compileComputeAsync() expects a ComputeNode.");const i=n.length;let s=0;const o=this._pipelines,a=this._bindings,u=this._nodes;for(const l of n){if(o.has(l)===!1){const d=()=>{l.removeEventListener("dispose",d),o.delete(l),a.deleteForCompute(l),u.delete(l)};l.addEventListener("dispose",d);const f=l.onInitFunction;f!==null&&f.call(l,{renderer:this})}await u.getForComputeAsync(l),u.updateBeforeForCompute(l),u.updateForCompute(l),a.updateForCompute(l);const c=a.getForCompute(l),h=[];o.getForCompute(l,c,h),await Promise.all(h),u.updateAfterForCompute(l),s++,t!==null&&t(new ProgressEvent("progress",{lengthComputable:!0,loaded:s,total:i})),s<i&&await Ac()}}async renderAsync(e,t){Fe('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){V("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){this._inspector!==null&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;e===!0?(t.modelViewMatrix=gp,t.modelNormalViewMatrix=mp):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===gp&&e.modelNormalViewMatrix===mp}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Fe('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:
547
+
548
+ Message: ${e.message}`;e.reason&&(t+=`
549
+ Reason: ${e.reason}`),V(t),this._isDeviceLost=!0}_onError(e){let t=`WebGPURenderer: Uncaptured ${e.api} ${e.type}`;e.message&&(t+=`: ${e.message}`),V(t)}_bundleNeedsUpdate(e,t){return t.bundleGPU===void 0||e.version!==t.version}_renderBundle(e,t,n){const{bundleGroup:i,camera:s,renderList:o}=e,a=this._currentRenderContext,u=this._bundles.get(i,s,a),l=this.backend.get(u);if(this._bundleNeedsUpdate(i,l)){this.backend.beginBundle(a),this._currentRenderBundle=u;const{transparentDoublePass:h,transparent:d,opaque:f}=o;this.opaque===!0&&f.length>0&&this._renderObjects(f,s,t,n),this.transparent===!0&&d.length>0&&this._renderTransparents(d,h,s,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,u),l.version=i.version}else{const{renderObjects:h}=l;for(let d=0,f=h.length;d<f;d++){const p=h[d],g=this._nodes.needsRefresh(p);g===Yn.FULL?(this._nodes.updateBefore(p),this._geometries.updateForRender(p),this._nodes.updateForRender(p),this._bindings.updateForRender(p),this._nodes.updateAfter(p)):g===Yn.SHARED&&(this._nodes.updateBefore(p),this._nodes.updateForRender(p),this._bindings.updateSharedForRender(p),this._nodes.updateAfter(p))}}this.backend.addBundle(a,u)}render(e,t){if(this._initialized===!1)throw new Error('THREE.Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_renderOutputLayers(e,t){if(this.backend.isWebGLBackend===!0&&t.multiview===!0||t.texture.isArrayTexture!==!0||t.texture.image.depth<=1){this._renderScene(e,e.camera,!1);return}const i=this._activeCubeFace;try{for(let s=0;s<t.texture.image.depth;s++)this._nodes.setOutputLayerIndex(s),this._activeCubeFace=s,this._renderScene(e,e.camera,!1)}finally{this._nodes.setOutputLayerIndex(0),this._activeCubeFace=i}}_getFrameBufferTarget(){if(this.needsFrameBufferTarget===!1)return null;const{width:e,height:t}=this.getDrawingBufferSize(Di),{depth:n,stencil:i}=this,s=this._outputRenderTarget||this._canvasTarget;let o=this._frameBufferTargets.get(s);if(o===void 0){o=new Ti(e,t,{depthBuffer:n,stencilBuffer:i,type:this._outputBufferType,format:Qt,colorSpace:Ye.workingColorSpace,generateMipmaps:!1,minFilter:Rt,magFilter:Rt,samples:this.samples}),o.isPostProcessingRenderTarget=!0;const d=()=>{s.removeEventListener("dispose",d),o.dispose(),this._frameBufferTargets.delete(s)};s.addEventListener("dispose",d),this._frameBufferTargets.set(s,o)}const a=this.getOutputRenderTarget();o.depthBuffer=n,o.stencilBuffer=i,a!==null?o.setSize(a.width,a.height,a.depth):o.setSize(e,t,1);const u=this._outputRenderTarget?this._outputRenderTarget.viewport:s._viewport,l=this._outputRenderTarget?this._outputRenderTarget.scissor:s._scissor,c=this._outputRenderTarget?1:s._pixelRatio,h=this._outputRenderTarget?this._outputRenderTarget.scissorTest:s._scissorTest;return o.viewport.copy(u),o.scissor.copy(l),o.viewport.multiplyScalar(c),o.scissor.multiplyScalar(c),o.scissorTest=h,o.multiview=a!==null?a.multiview:!1,o.useArrayDepthTexture=a!==null?a.useArrayDepthTexture:!1,o.resolveDepthBuffer=a!==null?a.resolveDepthBuffer:!0,o.resolveStencilBuffer=a!==null?a.resolveStencilBuffer:!0,o.storeMultisampledColorBuffer=a!==null?a.storeMultisampledColorBuffer:!0,o.storeMultisampledDepthBuffer=a!==null?a.storeMultisampledDepthBuffer:!0,o.storeMultisampledStencilBuffer=a!==null?a.storeMultisampledStencilBuffer:!0,o._autoAllocateDepthBuffer=a!==null?a._autoAllocateDepthBuffer:!1,o}_renderScene(e,t,n=!0){if(this._isDeviceLost===!0)return;this.shadowMap.type===tf&&(Y("WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.shadowMap.type=Ga);const i=n?this._getFrameBufferTarget():null,s=this._nodes.nodeFrame,o=s.renderId,a=this._currentRenderContext,u=this._currentRenderObjectFunction,l=this._handleObjectFunction;this.lighting.beginRender(e),this._callDepth++;const c=e.isScene===!0?e:yg,h=this._renderTarget||this._outputRenderTarget,d=this.xr.isPresenting===!0&&this.isOutputTarget,f=this._activeCubeFace,p=this._activeMipmapLevel;let g;if(i!==null?(g=i,this.setRenderTarget(g)):g=h,g!==null&&g.depthBuffer===!0){const X=this._textures.get(g);X.depthInitialized!==!0&&((this.autoClear===!1||this.autoClear===!0&&this.autoClearDepth===!1)&&this.clearDepth(),X.depthInitialized=!0)}const _=this._renderContexts.get(g,this._mrt,this._callDepth);this._currentRenderContext=_,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,s.renderId=this.info.calls,this.backend.updateTimeStampUID(_),this.inspector.beginRender(this.backend.getTimestampUID(_),e,t,g),e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t=this._updateCamera(t,d);const m=this._canvasTarget;let y=m._viewport,b=m._scissor,T=m._pixelRatio;g!==null&&(y=g.viewport,b=g.scissor,T=1),this.getDrawingBufferSize(Di),sc.set(0,0,Di.width,Di.height);const x=y.minDepth===void 0?0:y.minDepth,v=y.maxDepth===void 0?1:y.maxDepth;_.viewportValue.copy(y).multiplyScalar(T).floor(),_.viewportValue.width>>=p,_.viewportValue.height>>=p,_.viewportValue.minDepth=x,_.viewportValue.maxDepth=v,_.viewport=_.viewportValue.equals(sc)===!1,_.scissorValue.copy(b).multiplyScalar(T).floor(),_.scissor=m._scissorTest&&_.scissorValue.equals(sc)===!1,_.scissorValue.width>>=p,_.scissorValue.height>>=p,_.clippingContext||(_.clippingContext=new Ru),_.clippingContext.updateGlobal(c,t),c.onBeforeRender(this,e,t,g),Li.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?_a.setFromArrayCamera(t):ma.setFromProjectionMatrix(Li,t.coordinateSystem,t.reversedDepth),this._renderLists.update(s.frameId);const w=this._renderLists.get(e,t,this.lighting);if(w.begin(),this._projectObject(e,t,0,w,_.clippingContext),w.finish(),this.sortObjects===!0&&w.sort(this._opaqueSort,this._transparentSort),g!==null){this._textures.updateRenderTarget(g,p);const X=this._textures.get(g);_.textures=X.textures,_.depthTexture=X.depthTexture,_.width=X.width,_.height=X.height,_.renderTarget=g,_.depth=g.depthBuffer,_.stencil=g.stencilBuffer}else _.textures=null,_.depthTexture=null,_.width=Di.width,_.height=Di.height,_.depth=this.depth,_.stencil=this.stencil;_.width>>=p,_.height>>=p,_.activeCubeFace=f,_.activeMipmapLevel=p,_.occlusionQueryCount=w.occlusionQueryCount,_.fullscreenPass=e.isQuadMesh===!0,_.scissorValue.max(Wn.set(0,0,0,0)),_.scissorValue.x+_.scissorValue.width>_.width&&(_.scissorValue.width=Math.max(_.width-_.scissorValue.x,0)),_.scissorValue.y+_.scissorValue.height>_.height&&(_.scissorValue.height=Math.max(_.height-_.scissorValue.y,0)),this._background.update(c,w,_),_.camera=t,this.backend.beginRender(_);const{bundles:R,lightsNode:F,transparentDoublePass:M,transparent:O,opaque:U}=w;return R.length>0&&this._renderBundles(R,c,F),this.opaque===!0&&U.length>0&&this._renderObjects(U,t,c,F),this.transparent===!0&&O.length>0&&this._renderTransparents(O,M,t,c,F),this.backend.finishRender(_),s.renderId=o,this._currentRenderContext=a,this._currentRenderObjectFunction=u,this._handleObjectFunction=l,this.lighting.finishRender(e),this._callDepth--,i!==null&&(this.setRenderTarget(h,f,p),this._renderOutput(g)),c.onAfterRender(this,e,t,g),this.inspector.finishRender(this.backend.getTimestampUID(_)),_}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._nodes.getOutputCacheKey();let n=this._quadCache.get(e.texture),i;if(n===void 0){i=new db(new Ke),i.name="Output Color Transform",i.material.name="outputColorTransform",i.material.fragmentNode=this._nodes.getOutputNode(e.texture),n={quad:i,cacheKey:t},this._quadCache.set(e.texture,n);const a=()=>{i.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",a)};e.texture.addEventListener("dispose",a)}else i=n.quad,n.cacheKey!==t&&(i.material.fragmentNode=this._nodes.getOutputNode(e.texture),i.material.needsUpdate=!0,n.cacheKey=t);const s=this.autoClear,o=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderOutputLayers(i,e),this.autoClear=s,this.xr.enabled=o}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){this._initialized===!1&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,n=0,i=-1){if(t!==null&&t.isReadbackBuffer&&this.info.memoryMap.has(t)===!1){this.info.createReadbackBuffer(t);const s=()=>{t.removeEventListener("dispose",s),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",s)}if(n%4!==0||i>0&&i%4!==0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,n,i)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,n)}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,n)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,n,i){this._canvasTarget.setScissor(e,t,n,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}resetState(){if(this._initialized===!1)throw new Error('THREE.Renderer: .resetState() called before the backend is initialized. Use "await renderer.init();" before using this method.');this.backend.resetState()}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,i,s=0,o=1){this._canvasTarget.setViewport(e,t,n,i,s,o)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this.reversedDepthBuffer===!0?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(this._initialized===!1)throw new Error('THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let s=null;if(i!==null){this._textures.updateRenderTarget(i);const o=this._textures.get(i);s=this._renderContexts.get(i,null,-1),s.textures=o.textures,s.depthTexture=o.depthTexture,s.width=o.width,s.height=o.height,s.renderTarget=i,s.depth=i.depthBuffer,s.stencil=i.stencilBuffer;const a=this.backend.getClearColor();s.clearColorValue.r=a.r,s.clearColorValue.g=a.g,s.clearColorValue.b=a.b,s.clearColorValue.a=a.a,s.clearDepthValue=this.getClearDepth(),s.clearStencilValue=this.getClearStencil(),s.activeCubeFace=this.getActiveCubeFace(),s.activeMipmapLevel=this.getActiveMipmapLevel(),i.depthBuffer===!0&&(o.depthInitialized=!0)}this.backend.clear(e,t,n,s),i!==null&&this._renderTarget===null&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){Fe('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,n)}async clearColorAsync(){Fe('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Fe('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Fe('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==Ki,t=this.currentColorSpace!==Ye.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){var t;let e=this._samples;return this._renderTarget!==null?e=this._renderTarget.samples:(this.needsFrameBufferTarget||((t=this._currentRenderContext)==null?void 0:t.fullscreenPass)===!0)&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:Ki}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Ye.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}async dispose(){if(this._initialized===!0){this.info.dispose(),this._inspector.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();await this.backend.dispose()}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null);for(const e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(this._isDeviceLost===!0)return;if(this._initialized===!1)return Y('Renderer: ".compute()" called before the backend is initialized. Try using ".computeAsync()" instead.'),this.computeAsync(e,t);const n=this._nodes.nodeFrame,i=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const s=this.backend,o=this._pipelines,a=this._bindings,u=this._nodes,l=Array.isArray(e)?e:[e];if(l[0]===void 0||l[0].isComputeNode!==!0)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");s.beginCompute(e);for(const c of l){if(o.has(c)===!1){const f=()=>{c.removeEventListener("dispose",f),o.delete(c),a.deleteForCompute(c),u.delete(c)};c.addEventListener("dispose",f);const p=c.onInitFunction;p!==null&&p.call(c,{renderer:this})}u.updateBeforeForCompute(c),u.updateForCompute(c),a.updateForCompute(c);const h=a.getForCompute(c),d=o.getForCompute(c,h);s.compute(e,c,h,d,t),u.updateAfterForCompute(c)}s.finishCompute(e),n.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){this._initialized===!1&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Fe('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return this._initialized===!1&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(this._initialized===!1)throw new Error('THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Fe('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(this._initialized===!1)throw new Error('THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(this._initialized===!1)throw new Error('THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),n=this._renderContexts.get(e);n.textures=t.textures,n.depthTexture=t.depthTexture,n.width=t.width,n.height=t.height,n.renderTarget=e,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,this.backend.initRenderTarget(n)}copyFramebufferToTexture(e,t=null){if(t!==null)if(t.isVector2)t=Wn.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=Wn.copy(t).floor();else{V("Renderer.copyFramebufferToTexture: Invalid rectangle.");return}else t=Wn.set(0,0,e.image.width,e.image.height);let n=this._currentRenderContext,i;n!==null?i=n.renderTarget:(i=this._renderTarget||this._getFrameBufferTarget(),i!==null&&(this._textures.updateRenderTarget(i),n=this._textures.get(i))),this._textures.updateTexture(e,{renderTarget:i}),this.backend.copyFramebufferToTexture(e,n,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,i=null,s=0,o=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,i,s,o),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,i,s,o=0,a=0){return this.backend.copyTextureToBuffer(e.textures[o],t,n,i,s,a)}_projectObject(e,t,n,i,s){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(s=s.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const u=t.isArrayCamera?_a:ma;if(!e.frustumCulled||e.intersectsFrustum(u)){this.sortObjects===!0&&Wn.setFromMatrixPosition(e.matrixWorld).applyMatrix4(Li);const{geometry:l,material:c}=e;c.visible&&i.push(e,l,c,n,Wn.z,null,s)}}else if(e.isLineLoop)V("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const u=t.isArrayCamera?_a:ma;if(!e.frustumCulled||e.intersectsFrustum(u)){const{geometry:l,material:c}=e;if(this.sortObjects===!0&&(l.boundingSphere===null&&l.computeBoundingSphere(),Wn.copy(l.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(Li)),Array.isArray(c)){const h=l.groups;for(let d=0,f=h.length;d<f;d++){const p=h[d],g=c[p.materialIndex];g&&g.visible&&i.push(e,l,g,n,Wn.z,p,s)}}else c.visible&&i.push(e,l,c,n,Wn.z,null,s)}}}if(e.isBundleGroup===!0&&this.backend.beginBundle!==void 0){const u=i;i=this._renderLists.get(e,t,this.lighting);const l=this._bundles.get(e,t,this._currentRenderContext),c=this.backend.get(l);if(this._bundleNeedsUpdate(e,c)){i.begin(),c.renderObjects===void 0?c.renderObjects=[]:c.renderObjects.length=0;const d=e.children;for(let f=0,p=d.length;f<p;f++)this._projectObject(d[f],t,n,i,s);i.finish()}u.pushBundle({bundleGroup:e,camera:t,renderList:i});return}const a=e.children;for(let u=0,l=a.length;u<l;u++)this._projectObject(a[u],t,n,i,s)}_renderBundles(e,t,n){for(const i of e)this._renderBundle(i,t,n)}_renderTransparents(e,t,n,i,s){if(t.length>0){for(const{material:o}of t)o.side=yt;this._renderObjects(t,n,i,s,"backSide");for(const{material:o}of t)o.side=li;this._renderObjects(e,n,i,s);for(const{material:o}of t)o.side=sr}else this._renderObjects(e,n,i,s)}_renderObjects(e,t,n,i,s=null){for(let o=0,a=e.length;o<a;o++){const{object:u,geometry:l,material:c,group:h,clippingContext:d}=e[o];this._currentRenderObjectFunction(u,n,t,l,c,h,i,d,s)}}_getShadowNodes(e){const t=e.version;let n=this._cacheShadowNodes.get(e);if(n===void 0||n.version!==t){const i=e.map&&e.map.isTexture,s=e.colorNode&&e.colorNode.isNode,o=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let u=null,l=null,c=null;if(i||s||o||a){let h,d;if(o?(h=e.castShadowNode.rgb,d=e.castShadowNode.a,this.shadowMap.transmitted!==!0&&Fe("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(h=D(0),d=N(1)),i&&(d=d.mul(Be("map","texture",e).a)),s&&(d=d.mul(e.colorNode.a)),l=q(h,d),a){const f=e.maskShadowNode||e.maskNode;l=P(([p])=>(f.not().discard(),p))(l)}}e.depthNode&&e.depthNode.isNode&&(c=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?u=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(u=e.positionNode),n={version:t,colorNode:l,depthNode:c,positionNode:u},this._cacheShadowNodes.set(e,n)}return n}_updateCamera(e,t){const n=this.xr;if(n.isPresenting===!1||t===!1){let i=!1;if(this.reversedDepthBuffer===!0&&e.reversedDepth!==!0){if(e._reversedDepth=!0,e.isArrayCamera)for(const o of e.cameras)o._reversedDepth=!0;i=!0}const s=this.coordinateSystem;if(e.coordinateSystem!==s){if(e.coordinateSystem=s,e.isArrayCamera)for(const o of e.cameras)o.coordinateSystem=s;i=!0}if(i===!0&&(e.updateProjectionMatrix(),e.isArrayCamera))for(const o of e.cameras)o.updateProjectionMatrix()}return e.parent===null&&e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t===!0&&n.enabled===!0&&n.isPresenting===!0&&(n.cameraAutoUpdate===!0&&n.updateCamera(e),e=n.getCamera()),e}renderObject(e,t,n,i,s,o,a,u=null,l=null){let c=!1,h,d,f,p,g,_,m;const y=this._currentSourceMaterial;if(e.onBeforeRender(this,t,n,i,s,o),s.allowOverride===!0&&t.overrideMaterial!==null){this._currentSourceMaterial=s;const b=t.overrideMaterial;if(c=!0,h=b.isNodeMaterial?b.colorNode:null,d=b.isNodeMaterial?b.depthNode:null,f=b.isNodeMaterial?b.positionNode:null,p=t.overrideMaterial.side,g=b.displacementMap,_=b.displacementScale,m=b.displacementBias,s.positionNode&&s.positionNode.isNode&&(b.positionNode=s.positionNode),b.alphaTest=s.alphaTest,b.alphaMap=s.alphaMap,b.displacementMap=s.displacementMap,b.displacementScale=s.displacementScale,b.displacementBias=s.displacementBias,b.transparent=s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode,b.isShadowPassMaterial){const{colorNode:T,depthNode:x,positionNode:v}=this._getShadowNodes(s);this.shadowMap.type===io?b.side=s.shadowSide!==null?s.shadowSide:s.side:b.side=s.shadowSide!==null?s.shadowSide:_B[s.side],T!==null&&(b.colorNode=T),x!==null&&(b.depthNode=x),v!==null&&(b.positionNode=v)}s=b}s.transparent===!0&&s.side===sr&&s.forceSinglePass===!1?(s.side=yt,this._handleObjectFunction(e,s,t,n,a,o,u,"backSide"),s.side=li,this._handleObjectFunction(e,s,t,n,a,o,u,l),s.side=sr):this._handleObjectFunction(e,s,t,n,a,o,u,l),c&&(t.overrideMaterial.colorNode=h,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=f,t.overrideMaterial.side=p,t.overrideMaterial.displacementMap=g,t.overrideMaterial.displacementScale=_,t.overrideMaterial.displacementBias=m),this._currentSourceMaterial=y,e.onAfterRender(this,t,n,i,s,o)}hasCompatibility(e){if(this._initialized===!1)throw new Error('THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,n,i,s,o,a,u){const l=this._objects.get(e,t,n,i,s,this._currentRenderContext,a,u);l.drawRange=e.geometry.drawRange,l.group=o,this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup);const c=this._nodes.needsRefresh(l);c===Yn.FULL?(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)):c===Yn.SHARED&&(this._nodes.updateBefore(l),this._nodes.updateForRender(l),this._bindings.updateSharedForRender(l)),this._pipelines.updateForRender(l),this._pipelines.isReady(l)&&(this.backend.draw(l,this.info),c!==Yn.NONE&&this._nodes.updateAfter(l))}_createObjectPipeline(e,t,n,i,s,o,a,u){if(this._compilationPromises!==null){this._compilationPromises.push({object:e,material:t,scene:n,camera:i,lightsNode:s,group:o,clippingContext:a,passId:u,renderContext:this._currentRenderContext});return}const l=this._objects.get(e,t,n,i,s,this._currentRenderContext,a,u);l.drawRange=e.geometry.drawRange,l.group=o,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class Nb{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}function Eb(r){return r+(Lr-r%Lr)%Lr}class Cb extends Nb{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return Eb(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}release(){this._buffer=null}}class Mb extends Cb{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let bB=0;class Pb extends Mb{constructor(e,t){const n=e&&e.name?e.name:bB++;super("UniformBuffer_"+n,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get byteLength(){return Eb(this.buffer.byteLength)}get buffer(){return this.nodeUniform.value}}class xB extends Mb{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map,this._addedIndices=new Set}addUniformUpdateRange(e){const t=e.index;if(this._addedIndices.has(t))return;let n=this._updateRangeCache.get(t);n===void 0&&(n={start:0,count:0},this._updateRangeCache.set(t,n)),n.start=e.offset,n.count=e.itemSize,this._addedIndices.add(t),this.updateRanges.push(n)}clearUpdateRanges(){this._addedIndices.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}get values(){return this._values===null&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(e===null){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let n=0,i=this.uniforms.length;n<i;n++){const s=this.uniforms[n],o=s.boundary,a=s.itemSize*e,u=t%Lr,l=u%o,c=u+l;t+=l,c!==0&&Lr-c<a&&(t+=Lr-c),s.offset=t/e,s.index=n,t+=a}return Math.ceil(t/Lr)*Lr}update(){let e=!1;for(const t of this.uniforms)this.updateByType(t)===!0&&(e=!0);return e}release(){super.release(),this._values=null}updateByType(e){if(e.isNumberUniform)return this.updateNumber(e);if(e.isVector2Uniform)return this.updateVector2(e);if(e.isVector3Uniform)return this.updateVector3(e);if(e.isVector4Uniform)return this.updateVector4(e);if(e.isColorUniform)return this.updateColor(e);if(e.isMatrix3Uniform)return this.updateMatrix3(e);if(e.isMatrix4Uniform)return this.updateMatrix4(e);V("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset,o=e.getType();if(n[s]!==i){const a=this._getBufferForType(o);a[s]=n[s]=i,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset,o=e.getType();if(n[s+0]!==i.x||n[s+1]!==i.y){const a=this._getBufferForType(o);a[s+0]=n[s+0]=i.x,a[s+1]=n[s+1]=i.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset,o=e.getType();if(n[s+0]!==i.x||n[s+1]!==i.y||n[s+2]!==i.z){const a=this._getBufferForType(o);a[s+0]=n[s+0]=i.x,a[s+1]=n[s+1]=i.y,a[s+2]=n[s+2]=i.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset,o=e.getType();if(n[s+0]!==i.x||n[s+1]!==i.y||n[s+2]!==i.z||n[s+3]!==i.w){const a=this._getBufferForType(o);a[s+0]=n[s+0]=i.x,a[s+1]=n[s+1]=i.y,a[s+2]=n[s+2]=i.z,a[s+3]=n[s+3]=i.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset;if(n[s+0]!==i.r||n[s+1]!==i.g||n[s+2]!==i.b){const o=this.buffer;o[s+0]=n[s+0]=i.r,o[s+1]=n[s+1]=i.g,o[s+2]=n[s+2]=i.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const n=this.values,i=e.getValue().elements,s=e.offset;if(n[s+0]!==i[0]||n[s+1]!==i[1]||n[s+2]!==i[2]||n[s+4]!==i[3]||n[s+5]!==i[4]||n[s+6]!==i[5]||n[s+8]!==i[6]||n[s+9]!==i[7]||n[s+10]!==i[8]){const o=this.buffer;o[s+0]=n[s+0]=i[0],o[s+1]=n[s+1]=i[1],o[s+2]=n[s+2]=i[2],o[s+4]=n[s+4]=i[3],o[s+5]=n[s+5]=i[4],o[s+6]=n[s+6]=i[5],o[s+8]=n[s+8]=i[6],o[s+9]=n[s+9]=i[7],o[s+10]=n[s+10]=i[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const n=this.values,i=e.getValue().elements,s=e.offset;return TB(n,i,s)===!1&&(this.buffer.set(i,s),vB(n,i,s),t=!0,this.addUniformUpdateRange(e)),t}_getBufferForType(e){return e==="int"||e==="ivec2"||e==="ivec3"||e==="ivec4"?new Int32Array(this.buffer.buffer):e==="uint"||e==="uvec2"||e==="uvec3"||e==="uvec4"?new Uint32Array(this.buffer.buffer):this.buffer}}function vB(r,e,t){for(let n=0,i=e.length;n<i;n++)r[t+n]=e[n]}function TB(r,e,t){for(let n=0,i=e.length;n<i;n++)if(r[t+n]!==e[n])return!1;return!0}let SB=0;class Bb extends xB{constructor(e,t){super(e),this.id=SB++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class Fb extends Nb{constructor(e,t){super(e),this._texture=t,this.version=-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture=e,this.reset())}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version?(this.version=e.version,!0):!1}reset(){this.generation=null,this.version=-1}release(){this._texture=null}}let wB=0;class RB extends Fb{constructor(e,t){super(e,t),this.id=wB++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class tl extends RB{constructor(e,t,n,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class Db extends tl{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledCubeTexture=!0}}class Fh extends tl{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledTexture3D=!0}}const bg={textureGather:new we(`
550
+ vec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {
551
+ if ( flipY ) offset.y = - offset.y;
552
+ vec2 size = vec2( textureSize( map, 0 ) );
553
+ vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
554
+ vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
555
+ vec4 ret = vec4(
556
+ textureLod( map, ij.xw, 0.0 )[ comp ],
557
+ textureLod( map, ij.zw, 0.0 )[ comp ],
558
+ textureLod( map, ij.zy, 0.0 )[ comp ],
559
+ textureLod( map, ij.xy, 0.0 )[ comp ]
560
+ );
561
+ return flipY ? ret.wzyx : ret;
562
+ }
563
+ `),textureGatherArray:new we(`
564
+ vec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {
565
+ if ( flipY ) offset.y = - offset.y;
566
+ vec2 size = vec2( textureSize( map, 0 ).xy );
567
+ vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
568
+ vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
569
+ vec4 ret = vec4(
570
+ textureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],
571
+ textureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],
572
+ textureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],
573
+ textureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]
574
+ );
575
+ return flipY ? ret.wzyx : ret;
576
+ }
577
+ `),textureGatherCompare:new we(`
578
+ vec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {
579
+ if ( flipY ) offset.y = - offset.y;
580
+ vec2 size = vec2( textureSize( map, 0 ) );
581
+ vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
582
+ vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
583
+ vec4 ret = vec4(
584
+ textureLod( map, vec3( ij.xw, ref ), 0.0 ),
585
+ textureLod( map, vec3( ij.zw, ref ), 0.0 ),
586
+ textureLod( map, vec3( ij.zy, ref ), 0.0 ),
587
+ textureLod( map, vec3( ij.xy, ref ), 0.0 )
588
+ );
589
+ return flipY ? ret.wzyx : ret;
590
+ }
591
+ `),textureGatherCompareArray:new we(`
592
+ vec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {
593
+ if ( flipY ) offset.y = - offset.y;
594
+ vec2 size = vec2( textureSize( map, 0 ).xy );
595
+ vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
596
+ vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
597
+ vec4 ret = vec4(
598
+ texture( map, vec4( ij.xw, coord.z, ref ) ),
599
+ texture( map, vec4( ij.zw, coord.z, ref ) ),
600
+ texture( map, vec4( ij.zy, coord.z, ref ) ),
601
+ texture( map, vec4( ij.xy, coord.z, ref ) )
602
+ );
603
+ return flipY ? ret.wzyx : ret;
604
+ }
605
+ `),floatpack_snorm_4x8:new we("uint tsl_packSnorm4x8( vec4 v ) { uvec4 u = uvec4( ivec4( round( clamp( v, -1.0, 1.0 ) * 127.0 ) ) & 0xff ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }"),floatpack_unorm_4x8:new we("uint tsl_packUnorm4x8( vec4 v ) { uvec4 u = uvec4( round( clamp( v, 0.0, 1.0 ) * 255.0 ) ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }"),floatunpack_snorm_4x8:new we("vec4 tsl_unpackSnorm4x8( uint x ) { return max( vec4( ivec4( x << 24, x << 16, x << 8, x ) >> 24 ) / 127.0, -1.0 ); }"),floatunpack_unorm_4x8:new we("vec4 tsl_unpackUnorm4x8( uint x ) { return vec4( uvec4( x, x >> 8, x >> 16, x >> 24 ) & 0xffu ) / 255.0; }")},AB={equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatpack_snorm_4x8:"tsl_packSnorm4x8",floatpack_unorm_4x8:"tsl_packUnorm4x8",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16",floatunpack_snorm_4x8:"tsl_unpackSnorm4x8",floatunpack_unorm_4x8:"tsl_unpackUnorm4x8"},xg={low:"lowp",medium:"mediump",high:"highp"},vg={swizzleAssign:!0,storageBuffer:!1},Tg={perspective:"smooth",linear:"noperspective"},Sg={centroid:"centroid"},wg=`
606
+ precision highp float;
607
+ precision highp int;
608
+ precision highp sampler2D;
609
+ precision highp sampler3D;
610
+ precision highp samplerCube;
611
+ precision highp sampler2DArray;
612
+
613
+ precision highp usampler2D;
614
+ precision highp usampler3D;
615
+ precision highp usamplerCube;
616
+ precision highp usampler2DArray;
617
+
618
+ precision highp isampler2D;
619
+ precision highp isampler3D;
620
+ precision highp isamplerCube;
621
+ precision highp isampler2DArray;
622
+
623
+ precision highp sampler2DShadow;
624
+ precision highp sampler2DArrayShadow;
625
+ precision highp samplerCubeShadow;
626
+ `,NB=new Set(["const","uniform","buffer","shared","attribute","varying","coherent","volatile","restrict","readonly","writeonly","atomic_uint","layout","centroid","flat","smooth","noperspective","patch","sample","invariant","precise","break","continue","do","for","while","switch","case","default","if","else","subroutine","in","out","inout","int","void","bool","true","false","float","double","discard","return","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","uint","uvec2","uvec3","uvec4","dvec2","dvec3","dvec4","mat2","mat3","mat4","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","dmat2","dmat3","dmat4","dmat2x2","dmat2x3","dmat2x4","dmat3x2","dmat3x3","dmat3x4","dmat4x2","dmat4x3","dmat4x4","lowp","mediump","highp","precision","sampler2D","sampler3D","samplerCube","sampler2DShadow","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","struct","common","partition","active","asm","class","union","enum","typedef","template","this","resource","goto","inline","noinline","public","static","extern","external","interface","long","short","half","fixed","unsigned","superp","input","output","hvec2","hvec3","hvec4","fvec2","fvec3","fvec4","sampler3DRect","filter","sizeof","cast","namespace","using","main"]);class EB extends wb{constructor(e,t){super(e,t,new tB),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==os}_include(e){const t=bg[e];return t.build(this),this.addInclude(t),t}getMethod(e){return bg[e]!==void 0&&this._include(e),AB[e]||e}getBitcastMethod(e,t){const n=this.getComponentType(t),i=this.getComponentType(e);return n!=="float"&&i!=="float"&&this.getTypeLength(t)===this.getTypeLength(e)?this.getType(e):this.getMethod(`bitcast_${n}_${i}`)}getFloatPackingMethod(e,t="2x16"){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t="2x16"){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,n){return`${e} ? ${t} : ${n}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const o of t.inputs)i.push(this.getType(o.type)+" "+o.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {
627
+
628
+ ${n.vars}
629
+
630
+ ${n.code}
631
+ return ${n.result};
632
+
633
+ }`}setupPBO(e){const t=e.value;if(t.pbo===void 0){const n=t.array,i=t.count*t.itemSize,{itemSize:s}=t,o=t.array.constructor.name.toLowerCase().includes("int");let a=o?Mo:Co;s===2?a=o?Po:pn:s===3?a=o?Zh:Bo:s===4&&(a=o?sd:Qt);const u={Float32Array:mt,Uint8Array:Pt,Uint16Array:rr,Uint32Array:qe,Int8Array:Yi,Int16Array:Ur,Int32Array:gt,Uint8ClampedArray:Pt},l=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(i/s))));let c=Math.ceil(i/s/l);l*c*s<i&&c++;const h=l*c*s,d=new n.constructor(h);d.set(n,0),t.array=d;const f=new ku(t.array,l,c,a,u[t.array.constructor.name]||mt);f.needsUpdate=!0,f.isPBOTexture=!0;const p=new Xu(f,null,null);p.setPrecision("high"),t.pboNode=p,t.pbo=p.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&e.node.isTextureNode!==!0&&e.node.isBufferNode!==!0?e.name:super.getPropertyName(e,t)}isReservedKeyword(e){return NB.has(e)}generatePBO(e){const{node:t,indexNode:n}=e,i=t.value;if(this.renderer.backend.has(i)){const c=this.renderer.backend.get(i);c.pbo=i.pbo}const s=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),o=this.getPropertyName(s);this.increaseUsage(n);const a=n.build(this,"uint"),u=this.getDataFromNode(e);let l=u.propertyName;if(l===void 0){const c=this.getVarFromNode(e);l=this.getPropertyName(c);const h=this.getDataFromNode(t);let d=h.propertySizeName;d===void 0&&(d=l+"Size",this.getVarFromNode(t,d,"uint"),this.addLineFlowCode(`${d} = uint( textureSize( ${o}, 0 ).x )`,e),h.propertySizeName=d);const{itemSize:f}=i,p="."+_s.join("").slice(0,f),g=`ivec2(${a} % ${d}, ${a} / ${d})`,_=this.generateTextureLoad(null,o,g,"0",null,null);let m="vec4";i.pbo.type===qe?m="uvec4":i.pbo.type===gt&&(m="ivec4"),this.addLineFlowCode(`${l} = ${m}(${_})${p}`,e),u.propertyName=l}return l}generateTextureLoad(e,t,n,i,s,o){i===null&&(i="0");let a;return s?o?a=`texelFetchOffset( ${t}, ivec3( ${n}, ${s} ), int( ${i} ), ${o} )`:a=`texelFetch( ${t}, ivec3( ${n}, ${s} ), int( ${i} ) )`:o?a=`texelFetchOffset( ${t}, ${n}, int( ${i} ), ${o} )`:a=`texelFetch( ${t}, ${n}, int( ${i} ) )`,e!==null&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,n,i,s){return i&&(n=`vec3( ${n}, ${i} )`),e.isDepthTexture?s?`textureOffset( ${t}, ${n}, ${s} ).x`:`texture( ${t}, ${n} ).x`:s?`textureOffset( ${t}, ${n}, ${s} )`:`texture( ${t}, ${n} )`}generateTextureSize(e,t,n){return`textureSize( ${t}, ${n} )`}generateTextureLevel(e,t,n,i,s,o){return s&&(n=`vec3( ${n}, ${s} )`),o?`textureLodOffset( ${t}, ${n}, ${i}, ${o} )`:`textureLod( ${t}, ${n}, ${i} )`}generateTextureBias(e,t,n,i,s,o){return s&&(n=`vec3( ${n}, ${s} )`),o?`textureOffset( ${t}, ${n}, ${o}, ${i} )`:`texture( ${t}, ${n}, ${i} )`}generateTextureGrad(e,t,n,i,s,o){return s&&(n=`vec3( ${n}, ${s} )`),o?`textureGradOffset( ${t}, ${n}, ${i[0]}, ${i[1]}, ${o} )`:`textureGrad( ${t}, ${n}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,n,i,s,o,a=this.shaderStage){if(a==="fragment")return e.isCubeTexture?`texture( ${t}, vec4( ${n}, ${i} ) )`:s?o?`textureOffset( ${t}, vec4( ${n}, ${s}, ${i} ), ${o} )`:`texture( ${t}, vec4( ${n}, ${s}, ${i} ) )`:o?`textureOffset( ${t}, vec3( ${n}, ${i} ), ${o} )`:`texture( ${t}, vec3( ${n}, ${i} ) )`;V(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,n,i,s,o,a){return e.isDepthTexture&&(i="0"),o===null&&(o="ivec2( 0 )"),a===null&&(a="false"),s?(this._include("textureGatherArray"),`tsl_textureGather_array( ${i}, ${t}, vec3( ${n}, ${s} ), ${o}, ${a} )`):(this._include("textureGather"),`tsl_textureGather( ${i}, ${t}, ${n}, ${o}, ${a} )`)}generateTextureGatherCompare(e,t,n,i,s,o,a){return o===null&&(o="ivec2( 0 )"),a===null&&(a="false"),s?(this._include("textureGatherCompareArray"),`tsl_textureGatherCompare_array( ${t}, vec3( ${n}, ${s} ), ${o}, ${i}, ${a} )`):(this._include("textureGatherCompare"),`tsl_textureGatherCompare( ${t}, ${n}, ${o}, ${i}, ${a} )`)}getUniforms(e){const t=this.uniforms[e],n=[],i={};for(const o of t){let a=null,u=!1;if(o.type==="texture"||o.type==="texture3D"){const l=o.node,c=l.value,h=this.getComponentTypeFromTexture(c),d=h==="float"?"":h.charAt(0);o.type==="texture3D"&&c.isArrayTexture===!1?a=`${d}sampler3D ${o.name};`:c.compareFunction&&l.isSampleCompare()?c.isArrayTexture===!0?a=`sampler2DArrayShadow ${o.name};`:a=`sampler2DShadow ${o.name};`:c.isArrayTexture===!0||c.isDataArrayTexture===!0||c.isCompressedArrayTexture===!0?a=`${d}sampler2DArray ${o.name};`:a=`${d}sampler2D ${o.name};`}else if(o.type==="cubeTexture")a=`samplerCube ${o.name};`;else if(o.type==="cubeDepthTexture")o.node.value.compareFunction?a=`samplerCubeShadow ${o.name};`:a=`samplerCube ${o.name};`;else if(o.type==="buffer"){const l=o.node,c=this.getType(l.bufferType),h=l.bufferCount,d=h>0?h:"";a=`${l.name} {
634
+ ${c} ${o.name}[${d}];
635
+ };
636
+ `}else{const l=o.groupNode.name;if(i[l]===void 0){const c=this.uniformGroups[l];if(c!==void 0){const h=[];for(const d of c.uniforms){const f=d.getType(),p=this.getVectorType(f),g=d.nodeUniform.node.precision;let _=`${p} ${d.name};`;g!==null&&(_=xg[g]+" "+_),h.push(" "+_)}i[l]=h}}u=!0}if(!u){const l=o.node.precision;l!==null&&(a=xg[l]+" "+a),a="uniform "+a,n.push(a)}}let s="";for(const o in i){const a=i[o];s+=this._getGLSLUniformStruct(o,a.join(`
637
+ `))+`
638
+ `}return s+=n.join(`
639
+ `),s}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==gt){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const i=n.array;i instanceof Uint32Array||i instanceof Int32Array||(t=t.slice(1))}return t}getAttributes(e){let t="";if(e==="vertex"||e==="compute"){const n=this.getAttributesArray();let i=0;for(const s of n)t+=`layout( location = ${i++} ) in ${s.type} ${s.name};
640
+ `}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(` ${n.type} ${n.name};`);return t.join(`
641
+ `)}getStructs(e){const t=[],n=this.structs[e],i=[];for(const s of n)if(s.output)for(const o of s.members)i.push(`layout( location = ${o.index} ) out ${o.type} ${o.name};`);else{let o="struct "+s.name+` {
642
+ `;o+=this.getStructMembers(s),o+=`
643
+ };
644
+ `,t.push(o)}return e==="fragment"&&i.length===0&&i.push(`layout( location = 0 ) out ${this.getOutputType()} fragColor;`),`
645
+ `+i.join(`
646
+ `)+`
647
+
648
+ `+t.join(`
649
+ `)}getVaryings(e){let t="";const n=this.varyings;if(e==="vertex"||e==="compute")for(const i of n){e==="compute"&&(i.needsInterpolation=!0);const s=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){const o=Tg[i.interpolationType]||i.interpolationType,a=Sg[i.interpolationSampling]||"";t+=`${o} ${a} out ${s} ${i.name};
650
+ `}else{const o=s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":"";t+=`${o}out ${s} ${i.name};
651
+ `}else t+=`${s} ${i.name};
652
+ `}else if(e==="fragment"){for(const i of n)if(i.needsInterpolation){const s=this.getType(i.type);if(i.interpolationType){const o=Tg[i.interpolationType]||i.interpolationType,a=Sg[i.interpolationSampling]||"";t+=`${o} ${a} in ${s} ${i.name};
653
+ `}else{const o=s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":"";t+=`${o}in ${s} ${i.name};
654
+ `}}}for(const i of this.builtins[e])t+=`${i};
655
+ `;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.compute.workgroupSize.reduce((n,i)=>n*i,1)}u`}getSubgroupSize(){V("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){V("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){V("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const i=this.extensions[n]||(this.extensions[n]=new Map);i.has(e)===!1&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if(e==="vertex"){const i=this.renderer.backend.extensions;this.object.isBatchedMesh&&i.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const n=this.extensions[e];if(n!==void 0)for(const{name:i,behavior:s}of n.values())t.push(`#extension ${i} : ${s}`);return t.join(`
656
+ `)}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=vg[e];if(t===void 0){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance";break}if(n!==void 0){const i=this.renderer.backend.extensions;i.has(n)&&(i.get(n),t=!0)}vg[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let n=0;n<e.length;n++){const i=e[n],s=this.getPropertyName(i.attributeNode);s&&(t+=`${i.varyingName} = ${s};
657
+ `)}return t}_getGLSLUniformStruct(e,t){return`
658
+ layout( std140 ) uniform ${e} {
659
+ ${t}
660
+ };`}_getGLSLVertexCode(e){return`#version 300 es
661
+
662
+ ${this.getSignature()}
663
+
664
+ // extensions
665
+ ${e.extensions}
666
+
667
+ // precision
668
+ ${wg}
669
+
670
+ // structs
671
+ ${e.structs}
672
+
673
+ // uniforms
674
+ ${e.uniforms}
675
+
676
+ // varyings
677
+ ${e.varyings}
678
+
679
+ // attributes
680
+ ${e.attributes}
681
+
682
+ // vars
683
+ ${e.vars}
684
+
685
+ // codes
686
+ ${e.codes}
687
+
688
+ void main() {
689
+
690
+ // transforms
691
+ ${e.transforms}
692
+
693
+ // flow
694
+ ${e.flow}
695
+
696
+ gl_PointSize = 1.0;
697
+
698
+ }
699
+ `}_getGLSLFragmentCode(e){return`#version 300 es
700
+
701
+ ${this.getSignature()}
702
+
703
+ // extensions
704
+ ${e.extensions}
705
+
706
+ // precision
707
+ ${wg}
708
+
709
+ // structs
710
+ ${e.structs}
711
+
712
+ // uniforms
713
+ ${e.uniforms}
714
+
715
+ // varyings
716
+ ${e.varyings}
717
+
718
+ // vars
719
+ ${e.vars}
720
+
721
+ // codes
722
+ ${e.codes}
723
+
724
+ void main() {
725
+
726
+ // flow
727
+ ${e.flow}
728
+
729
+ }
730
+ `}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let n=`// code
731
+
732
+ `;n+=this.flowCode[t];const i=this.flowNodes[t],s=i[i.length-1];for(const a of i){const u=this.getFlowData(a),l=a.name;l&&(n.length>0&&(n+=`
733
+ `),n+=` // flow -> ${l}
734
+ `),n+=`${u.code}
735
+ `,a===s&&t!=="compute"&&(n+=`// result
736
+ `,t==="vertex"?(n+="gl_Position = ",n+=`${this.format(u.result,s.getNodeType(this),"vec4")};`):t==="fragment"&&(a.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${this.format(u.result,s.getNodeType(this),this.getOutputType())};`)))}const o=e[t];if(o.extensions=this.getExtensions(t),o.uniforms=this.getUniforms(t),o.attributes=this.getAttributes(t),o.varyings=this.getVaryings(t),o.vars=this.getVars(t,!0),o.structs=this.getStructs(t),o.codes=this.getCodes(t),o.transforms=this.getTransforms(t),o.flow=n,t==="vertex"){const a=this.renderer.backend.extensions;this.object.isBatchedMesh&&a.has("WEBGL_multi_draw")===!1&&(o.uniforms+=`
737
+ uniform uint nodeUniformDrawId;
738
+ `)}}this.material!==null?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,i=null){const s=super.getUniformFromNode(e,t,n,i),o=this.getDataFromNode(e,n,this.globalCache);let a=o.uniformGPU;if(a===void 0){const u=e.groupNode,l=u.name,c=this.getBindGroupArray(l,n);if(t==="texture")a=new tl(s.name,s.node,u),c.push(a);else if(t==="cubeTexture"||t==="cubeDepthTexture")a=new Db(s.name,s.node,u),c.push(a);else if(t==="texture3D")a=new Fh(s.name,s.node,u),c.push(a);else if(t==="buffer"){s.name=`buffer${e.id}`;const h=this.getSharedDataFromNode(e);let d=h.buffer;d===void 0&&(e.name=`NodeBuffer_${e.id}`,d=new Pb(e,u),d.name=e.name,h.buffer=d),c.push(d),a=d}else{let h=this.uniformGroups[l];h===void 0?(h=new Bb(l,u),this.uniformGroups[l]=h,c.push(h)):c.indexOf(h)===-1&&c.push(h),a=this.getNodeUniform(s,t);const d=a.name;h.uniforms.some(p=>p.name===d)||h.addUniform(a)}o.uniformGPU=a}return s}}let oc=null,Oi=null;class Lb{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Pn.RENDER]:null,[Pn.COMPUTE]:null},this.trackTimestamp=e.trackTimestamp===!0}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}setXRTarget(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}createUniformBuffer(){}destroyUniformBuffer(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),n=this.renderer.info.frame;let i,s=e.id;Array.isArray(e)?(s=e.map(o=>o.id).join(","),i="c:"+this.renderer.info.compute.frameCalls):e.isComputeNode===!0?i="c:"+this.renderer.info.compute.frameCalls:i="r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+s+":f"+n}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?Pn.COMPUTE:Pn.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}get hasTimestamp(){return!1}hasTimestampQuery(e){return this._getQueryPool(e).hasTimestampQuery(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp){Fe("WebGPURenderer: Timestamp tracking is disabled.");return}const t=this.timestampQueryPool[e];if(!t)return;const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return oc=oc||new de,this.renderer.getDrawingBufferSize(oc)}setScissorTest(){}resetState(){}getClearColor(){const e=this.renderer;return Oi=Oi||new Vd,e.getClearColor(Oi),Oi.getRGB(Oi),Oi}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas!==void 0?this.parameters.canvas:Kx(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Ou} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}async dispose(){for(const e of Object.values(this.timestampQueryPool))e!==null&&await e.dispose()}}let CB=0;class MB{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[this.activeBufferIndex^1]}switchBuffers(){this.activeBufferIndex^=1}}class PB{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:i}=n,s=e.array,o=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,u=n.get(a);let l=u.bufferGPU;l===void 0&&(l=this._createBuffer(i,t,s,o),u.bufferGPU=l,u.bufferType=t,u.version=a.version);let c;if(s instanceof Float32Array)c=i.FLOAT;else if(typeof Float16Array<"u"&&s instanceof Float16Array)c=i.HALF_FLOAT;else if(s instanceof Uint16Array)e.isFloat16BufferAttribute?c=i.HALF_FLOAT:c=i.UNSIGNED_SHORT;else if(s instanceof Int16Array)c=i.SHORT;else if(s instanceof Uint32Array)c=i.UNSIGNED_INT;else if(s instanceof Int32Array)c=i.INT;else if(s instanceof Int8Array)c=i.BYTE;else if(s instanceof Uint8Array)c=i.UNSIGNED_BYTE;else if(s instanceof Uint8ClampedArray)c=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+s);let h={bufferGPU:l,bufferType:t,type:c,byteLength:s.byteLength,bytesPerElement:s.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:c===i.INT||c===i.UNSIGNED_INT||e.gpuType===gt,id:CB++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const d=this._createBuffer(i,t,s,o);h=new MB(h,d)}n.set(e,h)}updateAttribute(e){const t=this.backend,{gl:n}=t,i=e.array,s=e.isInterleavedBufferAttribute?e.data:e,o=t.get(s),a=o.bufferType,u=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,o.bufferGPU),u.length===0)n.bufferSubData(a,0,i);else{for(let l=0,c=u.length;l<c;l++){const h=u[l];n.bufferSubData(a,h.start*i.BYTES_PER_ELEMENT,i,h.start,h.count)}s.clearUpdateRanges()}n.bindBuffer(a,null),o.version=s.version}destroyAttribute(e){const t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);n.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,i=-1){const s=this.backend,{gl:o}=s,a=e.isInterleavedBufferAttribute?e.data:e,u=s.get(a),{bufferGPU:l}=u,c=i===-1?u.byteLength-n:i;let h;if(t===null)h=new Uint8Array(new ArrayBuffer(c));else if(t.isReadbackBuffer){if(t._mapped===!0)throw new Error("THREE.WebGPURenderer: ReadbackBuffer must be released before being used again.");const d=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener("release",d),t.removeEventListener("dispose",d)};t.addEventListener("release",d),t.addEventListener("dispose",d),h=new Uint8Array(new ArrayBuffer(c)),t.buffer=h.buffer}else h=new Uint8Array(t);return o.bindBuffer(o.COPY_READ_BUFFER,l),o.getBufferSubData(o.COPY_READ_BUFFER,n,h),o.bindBuffer(o.COPY_READ_BUFFER,null),o.bindBuffer(o.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:h.buffer}_createBuffer(e,t,n,i){const s=e.createBuffer();return e.bindBuffer(t,s),e.bufferData(t,n,i),e.bindBuffer(t,null),s}}let $s,Hn;class BB{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor=new Dt(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;$s={[Qn]:e.FUNC_ADD,[bm]:e.FUNC_SUBTRACT,[ym]:e.FUNC_REVERSE_SUBTRACT,[_m]:e.MIN,[mm]:e.MAX},Hn={[Cr]:e.ZERO,[Fm]:e.ONE,[Bm]:e.SRC_COLOR,[Pm]:e.SRC_ALPHA,[Mm]:e.SRC_ALPHA_SATURATE,[Cm]:e.DST_COLOR,[Em]:e.DST_ALPHA,[Nm]:e.ONE_MINUS_SRC_COLOR,[Am]:e.ONE_MINUS_SRC_ALPHA,[Rm]:e.ONE_MINUS_DST_COLOR,[wm]:e.ONE_MINUS_DST_ALPHA,[Sm]:e.CONSTANT_COLOR,[Tm]:e.ONE_MINUS_CONSTANT_COLOR,[vm]:e.CONSTANT_ALPHA,[xm]:e.ONE_MINUS_CONSTANT_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=new tt().fromArray(t),this.currentViewport=new tt().fromArray(n),this._tempVec4=new tt}enable(e){const{enabled:t}=this;t[e]!==!0&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;t[e]!==!1&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;e!==Yx?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===Qx?t.cullFace(t.BACK):e===Zx?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,n){const i=this.gl,s=this.backend.drawBuffersIndexedExt;if(!s){Fe("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.");return}for(let o=0;o<e.length;o++){const a=e[o];let u=null;if(t!==null){const l=t.getBlendMode(a.name);l.blending===Dm?u=n:l.blending!==ur&&(u=l)}else u=n;u!==null?this._setMRTBlendingIndex(o,u):s.blendFuncSeparateiOES(o,i.ONE,i.ZERO,i.ONE,i.ZERO)}}_setMRTBlendingIndex(e,t){const{gl:n}=this,i=this.backend.drawBuffersIndexedExt,s=t.blending,o=t.blendSrc,a=t.blendDst,u=t.blendEquation,l=t.premultipliedAlpha;if(s===ci){const c=t.blendSrcAlpha!==null?t.blendSrcAlpha:o,h=t.blendDstAlpha!==null?t.blendDstAlpha:a,d=t.blendEquationAlpha!==null?t.blendEquationAlpha:u;i.blendEquationSeparateiOES(e,$s[u],$s[d]),i.blendFuncSeparateiOES(e,Hn[o],Hn[a],Hn[c],Hn[h])}else if(i.blendEquationSeparateiOES(e,n.FUNC_ADD,n.FUNC_ADD),l)switch(s){case Zn:i.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case ji:i.blendFuncSeparateiOES(e,n.ONE,n.ONE,n.ONE,n.ONE);break;case Hi:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case Wi:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:i.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break}else switch(s){case Zn:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case ji:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case Hi:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case Wi:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break}}setBlending(e,t,n,i,s,o,a,u,l,c){const{gl:h}=this;if(e===ur){this.currentBlendingEnabled===!0&&(this.disable(h.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(h.BLEND),this.currentBlendingEnabled=!0),e!==ci){if(e!==this.currentBlending||c!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==Qn||this.currentBlendEquationAlpha!==Qn)&&(h.blendEquation(h.FUNC_ADD),this.currentBlendEquation=Qn,this.currentBlendEquationAlpha=Qn),c)switch(e){case Zn:h.blendFuncSeparate(h.ONE,h.ONE_MINUS_SRC_ALPHA,h.ONE,h.ONE_MINUS_SRC_ALPHA);break;case ji:h.blendFunc(h.ONE,h.ONE);break;case Hi:h.blendFuncSeparate(h.ZERO,h.ONE_MINUS_SRC_COLOR,h.ZERO,h.ONE);break;case Wi:h.blendFuncSeparate(h.DST_COLOR,h.ONE_MINUS_SRC_ALPHA,h.ZERO,h.ONE);break;default:V("WebGLState: Invalid blending: ",e);break}else switch(e){case Zn:h.blendFuncSeparate(h.SRC_ALPHA,h.ONE_MINUS_SRC_ALPHA,h.ONE,h.ONE_MINUS_SRC_ALPHA);break;case ji:h.blendFuncSeparate(h.SRC_ALPHA,h.ONE,h.ONE,h.ONE);break;case Hi:V("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Wi:V("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:V("WebGLState: Invalid blending: ",e);break}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=c}return}s=s||t,o=o||n,a=a||i,(t!==this.currentBlendEquation||s!==this.currentBlendEquationAlpha)&&(h.blendEquationSeparate($s[t],$s[s]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=s),(n!==this.currentBlendSrc||i!==this.currentBlendDst||o!==this.currentBlendSrcAlpha||a!==this.currentBlendDstAlpha)&&(h.blendFuncSeparate(Hn[n],Hn[i],Hn[o],Hn[a]),this.currentBlendSrc=n,this.currentBlendDst=i,this.currentBlendSrcAlpha=o,this.currentBlendDstAlpha=a),(u.equals(this.currentBlendColor)===!1||l!==this.currentBlendAlpha)&&(h.blendColor(u.r,u.g,u.b,l),this.currentBlendColor.copy(u),this.currentBlendAlpha=l),this.currentBlending=e,this.currentPremultipledAlpha=!1}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=zm[e]),this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case $m:t.depthFunc(t.NEVER);break;case Vm:t.depthFunc(t.ALWAYS);break;case Gm:t.depthFunc(t.LESS);break;case km:t.depthFunc(t.LEQUAL);break;case Im:t.depthFunc(t.EQUAL);break;case Um:t.depthFunc(t.GEQUAL);break;case Om:t.depthFunc(t.GREATER);break;case Lm:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,i){const s=this._tempVec4.set(e,t,n,i);if(this.currentScissor.equals(s)===!1){const{gl:o}=this;o.scissor(s.x,s.y,s.z,s.w),this.currentScissor.copy(s)}}viewport(e,t,n,i){const s=this._tempVec4.set(e,t,n,i);if(this.currentViewport.equals(s)===!1){const{gl:o}=this;o.viewport(s.x,s.y,s.z,s.w),this.currentViewport.copy(s)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,n){(this.currentStencilFunc!==e||this.currentStencilRef!==t||this.currentStencilFuncMask!==n)&&(this.gl.stencilFunc(e,t,n),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=n)}setStencilOp(e,t,n){(this.currentStencilFail!==e||this.currentStencilZFail!==t||this.currentStencilZPass!==n)&&(this.gl.stencilOp(e,t,n),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=n)}setMaterial(e,t,n){const{gl:i}=this;e.side===sr?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let s=e.side===yt;t&&(s=!s),this.setFlipSided(s),e.blending===Zn&&e.transparent===!1?this.setBlending(ur):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.blendColor,e.blendAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const o=e.stencilWrite;if(this.setStencilTest(o),o&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),e.alphaToCoverage===!0&&this.backend.renderer.currentSamples>0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),this.currentClippingPlanes!==n){for(let u=0;u<8;u++)u<n?this.enable(12288+u):this.disable(12288+u);this.currentClippingPlanes=n}}setPolygonOffset(e,t,n){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),(this.currentPolygonOffsetFactor!==t||this.currentPolygonOffsetUnits!==n)&&(i.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e?(this.gl.useProgram(e),this.currentProgram=e,!0):!1}setVertexState(e,t=null){const n=this.gl;return this.currentVAO!==e||this.currentIndex!==t?(n.bindVertexArray(e),t!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0):!1}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:n,currentBoundFramebuffers:i}=this;return i[e]!==t?(n.bindFramebuffer(e,t),i[e]=t,e===n.DRAW_FRAMEBUFFER&&(i[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(i[n.DRAW_FRAMEBUFFER]=t),!0):!1}drawBuffers(e,t){const{gl:n}=this;let i=[],s=!1;if(e.textures!==null){i=this.currentDrawbuffers.get(t),i===void 0&&(i=[],this.currentDrawbuffers.set(t,i));const o=e.textures;if(i.length!==o.length||i[0]!==n.COLOR_ATTACHMENT0){for(let a=0,u=o.length;a<u;a++)i[a]=n.COLOR_ATTACHMENT0+a;i.length=o.length,s=!0}}else i[0]!==n.BACK&&(i[0]=n.BACK,s=!0);s&&n.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:n,maxTextures:i}=this;e===void 0&&(e=t.TEXTURE0+i-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){const{gl:i,currentTextureSlot:s,currentBoundTextures:o,maxTextures:a}=this;n===void 0&&(s===null?n=i.TEXTURE0+a-1:n=s);let u=o[n];u===void 0&&(u={type:void 0,texture:void 0},o[n]=u),(u.type!==e||u.texture!==t)&&(s!==n&&(i.activeTexture(n),this.currentTextureSlot=n),i.bindTexture(e,t),u.type=e,u.texture=t)}bindBufferBase(e,t,n){const{gl:i}=this,s=`${e}-${t}`;return this.currentBoundBufferBases[s]!==n?(i.bindBufferBase(e,t,n),this.currentBoundBufferBases[s]=n,!0):!1}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,i=n[t];i!==void 0&&i.type!==void 0&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}getParameter(e){const{gl:t,parameters:n}=this;return n[e]!==void 0?n[e]:t.getParameter(e)}pixelStorei(e,t){const{gl:n,parameters:i}=this;i[e]!==t&&(n.pixelStorei(e,t),i[e]=t)}reset(){const{gl:e}=this;e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),this.resetVertexState(),this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor.set(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this.currentScissor.set(0,0,e.canvas.width,e.canvas.height),this.currentViewport.set(0,0,e.canvas.width,e.canvas.height),this.currentDepthReversed=!1,this.backend.renderer.reversedDepthBuffer===!0&&this.setReversedDepth(!0)}}class FB{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=os){const{gl:n,extensions:i}=this;let s;const o=Ye.getTransfer(t);if(e===Pt)return n.UNSIGNED_BYTE;if(e===um)return n.UNSIGNED_SHORT_4_4_4_4;if(e===lm)return n.UNSIGNED_SHORT_5_5_5_1;if(e===Jh)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===ed)return n.UNSIGNED_INT_10F_11F_11F_REV;if(e===Yi)return n.BYTE;if(e===Ur)return n.SHORT;if(e===rr)return n.UNSIGNED_SHORT;if(e===gt)return n.INT;if(e===qe)return n.UNSIGNED_INT;if(e===mt)return n.FLOAT;if(e===wt)return n.HALF_FLOAT;if(e===Qh)return n.ALPHA;if(e===Bo)return n.RGB;if(e===Qt)return n.RGBA;if(e===Dn)return n.DEPTH_COMPONENT;if(e===Ln)return n.DEPTH_STENCIL;if(e===Co)return n.RED;if(e===Mo)return n.RED_INTEGER;if(e===pn)return n.RG;if(e===Po)return n.RG_INTEGER;if(e===sd)return n.RGBA_INTEGER;if(e===Va||e===$a||e===za||e===Wa)if(o===le)if(s=i.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(e===Va)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===$a)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===za)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Wa)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=i.get("WEBGL_compressed_texture_s3tc"),s!==null){if(e===Va)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===$a)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===za)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Wa)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(e===of||e===af||e===uf||e===lf)if(s=i.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(e===of)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===af)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===uf)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===lf)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(e===Ec||e===Cc||e===Mc||e===Pc||e===Bc||e===ou||e===Fc)if(s=i.get("WEBGL_compressed_texture_etc"),s!==null){if(e===Ec||e===Cc)return o===le?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(e===Mc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(e===Pc)return s.COMPRESSED_R11_EAC;if(e===Bc)return s.COMPRESSED_SIGNED_R11_EAC;if(e===ou)return s.COMPRESSED_RG11_EAC;if(e===Fc)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(e===Dc||e===Lc||e===Oc||e===Uc||e===Ic||e===kc||e===Gc||e===Vc||e===$c||e===zc||e===Wc||e===Hc||e===jc||e===qc)if(s=i.get("WEBGL_compressed_texture_astc"),s!==null){if(e===Dc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Lc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Oc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Uc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Ic)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===kc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Gc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Vc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===$c)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===zc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Wc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Hc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===jc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===qc)return o===le?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(e===Xc||e===Kc||e===Yc)if(s=i.get("EXT_texture_compression_bptc"),s!==null){if(e===Xc)return o===le?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(e===Kc)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(e===Yc)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(e===Qc||e===Zc||e===au||e===Jc)if(s=i.get("EXT_texture_compression_rgtc"),s!==null){if(e===Qc)return s.COMPRESSED_RED_RGTC1_EXT;if(e===Zc)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===au)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===Jc)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return e===or?n.UNSIGNED_INT_24_8:n[e]!==void 0?n[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((n,i)=>{function s(){const o=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(o===e.WAIT_FAILED){e.deleteSync(t),i();return}if(o===e.TIMEOUT_EXPIRED){requestAnimationFrame(s);return}e.deleteSync(t),n()}s()})}}let Rg=!1,ya,ac,Ag;class DB{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,Rg===!1&&(this._init(),Rg=!0)}_init(){const e=this.gl;ya={[Iu]:e.REPEAT,[xo]:e.CLAMP_TO_EDGE,[Uu]:e.MIRRORED_REPEAT},ac={[zt]:e.NEAREST,[hm]:e.NEAREST_MIPMAP_NEAREST,[is]:e.NEAREST_MIPMAP_LINEAR,[Rt]:e.LINEAR,[Nc]:e.LINEAR_MIPMAP_NEAREST,[Ir]:e.LINEAR_MIPMAP_LINEAR},Ag={[gm]:e.NEVER,[pm]:e.ALWAYS,[id]:e.LESS,[Fo]:e.LEQUAL,[fm]:e.EQUAL,[ss]:e.GEQUAL,[su]:e.GREATER,[dm]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return e.isCubeTexture===!0?n=t.TEXTURE_CUBE_MAP:e.isArrayTexture===!0||e.isDataArrayTexture===!0||e.isCompressedArrayTexture===!0?n=t.TEXTURE_2D_ARRAY:e.isData3DTexture===!0?n=t.TEXTURE_3D:n=t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,s,o=!1){const{gl:a,extensions:u}=this;if(e!==null){if(a[e]!==void 0)return a[e];Y("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let l=null;i&&(l=u.get("EXT_texture_norm16"),l||Y("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let c=t;if(t===a.RED&&(n===a.FLOAT&&(c=a.R32F),n===a.HALF_FLOAT&&(c=a.R16F),n===a.UNSIGNED_BYTE&&(c=a.R8),n===a.BYTE&&(c=a.R8_SNORM),n===a.UNSIGNED_SHORT&&l&&(c=l.R16_EXT),n===a.SHORT&&l&&(c=l.R16_SNORM_EXT)),t===a.RED_INTEGER&&(n===a.UNSIGNED_BYTE&&(c=a.R8UI),n===a.UNSIGNED_SHORT&&(c=a.R16UI),n===a.UNSIGNED_INT&&(c=a.R32UI),n===a.BYTE&&(c=a.R8I),n===a.SHORT&&(c=a.R16I),n===a.INT&&(c=a.R32I)),t===a.RG&&(n===a.FLOAT&&(c=a.RG32F),n===a.HALF_FLOAT&&(c=a.RG16F),n===a.UNSIGNED_BYTE&&(c=a.RG8),n===a.BYTE&&(c=a.RG8_SNORM),n===a.UNSIGNED_SHORT&&l&&(c=l.RG16_EXT),n===a.SHORT&&l&&(c=l.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(n===a.UNSIGNED_BYTE&&(c=a.RG8UI),n===a.UNSIGNED_SHORT&&(c=a.RG16UI),n===a.UNSIGNED_INT&&(c=a.RG32UI),n===a.BYTE&&(c=a.RG8I),n===a.SHORT&&(c=a.RG16I),n===a.INT&&(c=a.RG32I)),t===a.RGB){const h=o?rf:Ye.getTransfer(s);n===a.FLOAT&&(c=a.RGB32F),n===a.HALF_FLOAT&&(c=a.RGB16F),n===a.UNSIGNED_BYTE&&(c=h===le?a.SRGB8:a.RGB8),n===a.BYTE&&(c=a.RGB8_SNORM),n===a.UNSIGNED_SHORT&&l&&(c=l.RGB16_EXT),n===a.SHORT&&l&&(c=l.RGB16_SNORM_EXT),n===a.UNSIGNED_SHORT_5_6_5&&(c=a.RGB565),n===a.UNSIGNED_SHORT_5_5_5_1&&(c=a.RGB5_A1),n===a.UNSIGNED_SHORT_4_4_4_4&&(c=a.RGB4),n===a.UNSIGNED_INT_5_9_9_9_REV&&(c=a.RGB9_E5),n===a.UNSIGNED_INT_10F_11F_11F_REV&&(c=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(n===a.UNSIGNED_BYTE&&(c=a.RGB8UI),n===a.UNSIGNED_SHORT&&(c=a.RGB16UI),n===a.UNSIGNED_INT&&(c=a.RGB32UI),n===a.BYTE&&(c=a.RGB8I),n===a.SHORT&&(c=a.RGB16I),n===a.INT&&(c=a.RGB32I)),t===a.RGBA){const h=o?rf:Ye.getTransfer(s);n===a.FLOAT&&(c=a.RGBA32F),n===a.HALF_FLOAT&&(c=a.RGBA16F),n===a.UNSIGNED_BYTE&&(c=h===le?a.SRGB8_ALPHA8:a.RGBA8),n===a.BYTE&&(c=a.RGBA8_SNORM),n===a.UNSIGNED_SHORT&&l&&(c=l.RGBA16_EXT),n===a.SHORT&&l&&(c=l.RGBA16_SNORM_EXT),n===a.UNSIGNED_SHORT_4_4_4_4&&(c=a.RGBA4),n===a.UNSIGNED_SHORT_5_5_5_1&&(c=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(n===a.UNSIGNED_BYTE&&(c=a.RGBA8UI),n===a.UNSIGNED_SHORT&&(c=a.RGBA16UI),n===a.UNSIGNED_INT&&(c=a.RGBA32UI),n===a.BYTE&&(c=a.RGBA8I),n===a.SHORT&&(c=a.RGBA16I),n===a.INT&&(c=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(n===a.UNSIGNED_SHORT&&(c=a.DEPTH_COMPONENT16),n===a.UNSIGNED_INT&&(c=a.DEPTH_COMPONENT24),n===a.FLOAT&&(c=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&n===a.UNSIGNED_INT_24_8&&(c=a.DEPTH24_STENCIL8),(c===a.R16F||c===a.R32F||c===a.RG16F||c===a.RG32F||c===a.RGBA16F||c===a.RGBA32F)&&u.get("EXT_color_buffer_float"),c}setTextureParameters(e,t){const{gl:n,extensions:i,backend:s}=this,{state:o}=this.backend,a=Ye.getPrimaries(Ye.workingColorSpace),u=t.colorSpace===os?null:Ye.getPrimaries(t.colorSpace),l=t.colorSpace===os||a===u?n.NONE:n.BROWSER_DEFAULT_WEBGL;o.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),o.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),o.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),o.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,l),n.texParameteri(e,n.TEXTURE_WRAP_S,ya[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,ya[t.wrapT]),(e===n.TEXTURE_3D||e===n.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,ya[t.wrapR])),n.texParameteri(e,n.TEXTURE_MAG_FILTER,ac[t.magFilter]);const c=t.mipmaps!==void 0&&t.mipmaps.length>0,h=t.minFilter===Rt&&c?Ir:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,ac[h]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,Ag[t.compareFunction])),i.has("EXT_texture_filter_anisotropic")===!0){if(t.magFilter===zt||t.minFilter!==is&&t.minFilter!==Ir||t.type===mt&&i.has("OES_texture_float_linear")===!1)return;if(t.anisotropy>1){const d=i.get("EXT_texture_filter_anisotropic");n.texParameterf(e,d.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,s.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:i}=this,s=this.getGLTextureType(e);let o=i[s];o===void 0&&(o=t.createTexture(),n.state.bindTexture(s,o),t.texParameteri(s,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(s,t.TEXTURE_MAG_FILTER,t.NEAREST),i[s]=o),n.set(e,{textureGPU:o,glTextureType:s})}createTexture(e,t){const{gl:n,backend:i}=this;let s,o,a,u,l;if(e.isExternalTexture===!0)s=e.sourceTexture,o=this.getGLTextureType(e);else{const{levels:c,width:h,height:d,depth:f}=t;a=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,a,u,e.normalized,e.colorSpace,e.isVideoTexture),s=n.createTexture(),o=this.getGLTextureType(e),i.state.bindTexture(o,s),this.setTextureParameters(o,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,c,l,h,d,f):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,c,l,h,d,f):e.isVideoTexture||n.texStorage2D(o,c,l,h,d)}i.set(e,{textureGPU:s,glTextureType:o,glFormat:a,glType:u,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:n,backend:i}=this,{state:s}=i,{textureGPU:o,glTextureType:a,glFormat:u,glType:l}=i.get(t),{width:c,height:h}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(a,o),s.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(a,0,0,0,c,h,u,l,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:i,height:s}=t,{textureGPU:o,glTextureType:a,glFormat:u,glType:l,glInternalFormat:c}=this.backend.get(e);if(!(e.isRenderTargetTexture||o===void 0))if(this.backend.state.bindTexture(a,o),this.setTextureParameters(a,e),e.isCompressedTexture){const h=e.mipmaps,d=t.image;for(let f=0;f<h.length;f++){const p=h[f];if(e.isCompressedArrayTexture)if(e.format!==n.RGBA)if(u!==null)if(e.layerUpdates.size>0){const g=sf(p.width,p.height,e.format,e.type);for(const _ of e.layerUpdates){const m=p.data.subarray(_*g/p.data.BYTES_PER_ELEMENT,(_+1)*g/p.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,f,0,0,_,p.width,p.height,1,u,m)}}else n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,f,0,0,0,p.width,p.height,d.depth,u,p.data);else Y("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()");else n.texSubImage3D(n.TEXTURE_2D_ARRAY,f,0,0,0,p.width,p.height,d.depth,u,l,p.data);else u!==null?n.compressedTexSubImage2D(n.TEXTURE_2D,f,0,0,p.width,p.height,u,p.data):Y("WebGLBackend: Unsupported compressed texture format")}e.isCompressedArrayTexture&&e.layerUpdates.size>0&&e.clearLayerUpdates()}else if(e.isCubeTexture){const h=t.images,d=e.mipmaps;for(let f=0;f<6;f++){const p=ba(h[f]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,0,0,i,s,u,l,p);for(let g=0;g<d.length;g++){const _=d[g],m=ba(_.images[f]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+f,g+1,0,0,m.width,m.height,u,l,m)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const h=t.image;if(e.layerUpdates.size>0){const d=sf(h.width,h.height,e.format,e.type);for(const f of e.layerUpdates){const p=h.data.subarray(f*d/h.data.BYTES_PER_ELEMENT,(f+1)*d/h.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,f,h.width,h.height,1,u,l,p)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,h.width,h.height,h.depth,u,l,h.data)}else if(e.isData3DTexture){const h=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,h.width,h.height,h.depth,u,l,h.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(a,0,c,u,l,t.image);else if(e.isHTMLTexture)typeof n.texElementImage2D=="function"&&(n.texElementImage2D.length===3?n.texElementImage2D(n.TEXTURE_2D,n.RGBA8,t.image):n.texElementImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t.image));else{const h=e.mipmaps;if(h.length>0)for(let d=0,f=h.length;d<f;d++){const p=h[d],g=ba(p);n.texSubImage2D(a,d,0,0,p.width,p.height,u,l,g)}else{const d=ba(t.image);n.texSubImage2D(a,0,0,0,i,s,u,l,d)}}}generateMipmaps(e){const{gl:t,backend:n}=this,{textureGPU:i,glTextureType:s}=n.get(e);n.state.bindTexture(s,i),t.generateMipmap(s)}deallocateRenderBuffers(e){const{gl:t,backend:n}=this;if(e){const i=n.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const s in i.framebuffers)t.deleteFramebuffer(i.framebuffers[s]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let s=0;s<i.msaaRenderbuffers.length;s++)t.deleteRenderbuffer(i.msaaRenderbuffers[s]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:n,backend:i}=this,{textureGPU:s,renderTarget:o}=i.get(e);this.deallocateRenderBuffers(o),t===!1&&e.isExternalTexture!==!0&&n.deleteTexture(s),i.delete(e)}copyTextureToTexture(e,t,n=null,i=null,s=0,o=0){const{gl:a,backend:u}=this,{state:l}=this.backend,{textureGPU:c,glTextureType:h,glType:d,glFormat:f}=u.get(t);l.bindTexture(h,c);let p,g,_,m,y,b,T,x,v;const w=e.isCompressedTexture?e.mipmaps[o]:e.image;if(n!==null)p=n.max.x-n.min.x,g=n.max.y-n.min.y,_=n.isBox3?n.max.z-n.min.z:1,m=n.min.x,y=n.min.y,b=n.isBox3?n.min.z:0;else{const H=Math.pow(2,-s);p=Math.floor(w.width*H),g=Math.floor(w.height*H),e.isDataArrayTexture||e.isArrayTexture?_=w.depth:e.isData3DTexture?_=Math.floor(w.depth*H):_=1,m=0,y=0,b=0}i!==null?(T=i.x,x=i.y,v=i.z):(T=0,x=0,v=0),l.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),l.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),l.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const R=l.getParameter(a.UNPACK_ROW_LENGTH),F=l.getParameter(a.UNPACK_IMAGE_HEIGHT),M=l.getParameter(a.UNPACK_SKIP_PIXELS),O=l.getParameter(a.UNPACK_SKIP_ROWS),U=l.getParameter(a.UNPACK_SKIP_IMAGES);l.pixelStorei(a.UNPACK_ROW_LENGTH,w.width),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,w.height),l.pixelStorei(a.UNPACK_SKIP_PIXELS,m),l.pixelStorei(a.UNPACK_SKIP_ROWS,y),l.pixelStorei(a.UNPACK_SKIP_IMAGES,b);const X=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,oe=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const H=u.get(e),ue=u.get(t),L=u.get(H.renderTarget),G=u.get(ue.renderTarget),Z=L.framebuffers[H.cacheKey],ce=G.framebuffers[ue.cacheKey],k=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,j=l.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;l.bindFramebuffer(a.READ_FRAMEBUFFER,Z),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,ce);for(let ae=0;ae<_;ae++)X&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,H.textureGPU,s,b+ae),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,c,o,v+ae)),a.blitFramebuffer(m,y,p,g,T,x,p,g,a.DEPTH_BUFFER_BIT,a.NEAREST);l.bindFramebuffer(a.READ_FRAMEBUFFER,k),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,j)}else if(s!==0||e.isRenderTargetTexture||u.has(e)){const H=u.get(e);this._srcFramebuffer===null&&(this._srcFramebuffer=a.createFramebuffer()),this._dstFramebuffer===null&&(this._dstFramebuffer=a.createFramebuffer());const ue=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,L=l.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;l.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let G=0;G<_;G++)X?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,H.textureGPU,s,b+G):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,H.textureGPU,s),oe?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,c,o,v+G):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,c,o),s!==0?a.blitFramebuffer(m,y,p,g,T,x,p,g,a.COLOR_BUFFER_BIT,a.NEAREST):oe?a.copyTexSubImage3D(h,o,T,x,v+G,m,y,p,g):a.copyTexSubImage2D(h,o,T,x,m,y,p,g);l.bindFramebuffer(a.READ_FRAMEBUFFER,ue),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,L)}else oe?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(h,o,T,x,v,p,g,_,f,d,w.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(h,o,T,x,v,p,g,_,f,w.data):a.texSubImage3D(h,o,T,x,v,p,g,_,f,d,w):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,o,T,x,p,g,f,d,w.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,o,T,x,w.width,w.height,f,w.data):a.texSubImage2D(a.TEXTURE_2D,o,T,x,p,g,f,d,w);l.pixelStorei(a.UNPACK_ROW_LENGTH,R),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,F),l.pixelStorei(a.UNPACK_SKIP_PIXELS,M),l.pixelStorei(a.UNPACK_SKIP_ROWS,O),l.pixelStorei(a.UNPACK_SKIP_IMAGES,U),o===0&&t.generateMipmaps&&a.generateMipmap(h),l.unbindTexture()}copyFramebufferToTexture(e,t,n){const{gl:i}=this,{state:s}=this.backend,{textureGPU:o}=this.backend.get(e),{x:a,y:u,z:l,w:c}=n,h=e.isDepthTexture===!0||t.renderTarget&&t.renderTarget.samples>0,d=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(h){const f=a!==0||u!==0;let p,g;if(e.isDepthTexture===!0?(p=i.DEPTH_BUFFER_BIT,g=i.DEPTH_ATTACHMENT,t.stencil&&(p|=i.STENCIL_BUFFER_BIT)):(p=i.COLOR_BUFFER_BIT,g=i.COLOR_ATTACHMENT0),f){const _=this.backend.get(t.renderTarget),m=_.framebuffers[t.getCacheKey()],y=_.msaaFrameBuffer;s.bindFramebuffer(i.DRAW_FRAMEBUFFER,m),s.bindFramebuffer(i.READ_FRAMEBUFFER,y);const b=d-u-c;i.blitFramebuffer(a,b,a+l,b+c,a,b,a+l,b+c,p,i.NEAREST),s.bindFramebuffer(i.READ_FRAMEBUFFER,m),s.bindTexture(i.TEXTURE_2D,o),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,b,l,c),s.unbindTexture()}else{const _=i.createFramebuffer();s.bindFramebuffer(i.DRAW_FRAMEBUFFER,_),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,g,i.TEXTURE_2D,o,0),i.blitFramebuffer(0,0,l,c,0,0,l,c,p,i.NEAREST),i.deleteFramebuffer(_)}}else s.bindTexture(i.TEXTURE_2D,o),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,d-c-u,l,c),s.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,i=!1){const{gl:s}=this,o=t.renderTarget,{depthTexture:a,depthBuffer:u,stencilBuffer:l,width:c,height:h}=o;if(s.bindRenderbuffer(s.RENDERBUFFER,e),u&&!l){let d=s.DEPTH_COMPONENT24;i===!0?this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(s.RENDERBUFFER,o.samples,d,c,h):n>0?(a&&a.isDepthTexture&&a.type===s.FLOAT&&(d=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,n,d,c,h)):s.renderbufferStorage(s.RENDERBUFFER,d,c,h),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else u&&l&&(n>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH24_STENCIL8,c,h):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,c,h),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e));s.bindRenderbuffer(s.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,i,s,o){const{backend:a,gl:u}=this,{textureGPU:l,glFormat:c,glType:h}=this.backend.get(e),d=u.createFramebuffer();if(a.state.bindFramebuffer(u.READ_FRAMEBUFFER,d),e.isData3DTexture||e.isDataArrayTexture||e.isArrayTexture)u.framebufferTextureLayer(u.READ_FRAMEBUFFER,u.COLOR_ATTACHMENT0,l,0,o);else{const b=e.isCubeTexture?u.TEXTURE_CUBE_MAP_POSITIVE_X+o:u.TEXTURE_2D;u.framebufferTexture2D(u.READ_FRAMEBUFFER,u.COLOR_ATTACHMENT0,b,l,0)}const f=this._getTypedArrayType(h),p=this._getBytesPerTexel(h,c),_=i*s*p,m=u.createBuffer();u.bindBuffer(u.PIXEL_PACK_BUFFER,m),u.bufferData(u.PIXEL_PACK_BUFFER,_,u.STREAM_READ),u.readPixels(t,n,i,s,c,h,0),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const y=new f(_/f.BYTES_PER_ELEMENT);return u.bindBuffer(u.PIXEL_PACK_BUFFER,m),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,y),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(u.READ_FRAMEBUFFER,null),u.deleteBuffer(m),u.deleteFramebuffer(d),y}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`THREE.WebGLTextureUtils: Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:n}=this;let i=0;if(e===n.UNSIGNED_BYTE&&(i=1),(e===n.UNSIGNED_SHORT_4_4_4_4||e===n.UNSIGNED_SHORT_5_5_5_1||e===n.UNSIGNED_SHORT_5_6_5||e===n.UNSIGNED_SHORT||e===n.HALF_FLOAT)&&(i=2),(e===n.UNSIGNED_INT||e===n.FLOAT)&&(i=4),t===n.RGBA)return i*4;if(t===n.RGB)return i*3;if(t===n.ALPHA)return i}dispose(){const{gl:e}=this;this._srcFramebuffer!==null&&e.deleteFramebuffer(this._srcFramebuffer),this._dstFramebuffer!==null&&e.deleteFramebuffer(this._dstFramebuffer)}}function ba(r){return r.isDataTexture?r.image.data:typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas?r:r.data}class LB{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return t===void 0&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class OB{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=null}getMaxAnisotropy(){if(this.maxAnisotropy!==null)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(t.has("EXT_texture_filter_anisotropic")===!0){const n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}getUniformBufferLimit(){if(this.maxUniformBlockSize!==null)return this.maxUniformBlockSize;const e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}}const Ng={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class UB{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:n,mode:i,object:s,type:o,info:a,index:u}=this;u!==0?n.drawElements(i,t,o,e):n.drawArrays(i,e,t),a.update(s,t,1)}renderInstances(e,t,n){const{gl:i,mode:s,type:o,index:a,object:u,info:l}=this;n!==0&&(a!==0?i.drawElementsInstanced(s,t,o,e,n):i.drawArraysInstanced(s,e,t,n),l.update(u,t,n))}renderMultiDraw(e,t,n){const{extensions:i,mode:s,object:o,info:a}=this;if(n===0)return;const u=i.get("WEBGL_multi_draw");if(u===null)for(let l=0;l<n;l++)this.render(e[l],t[l]);else{this.index!==0?u.multiDrawElementsWEBGL(s,t,0,this.type,e,0,n):u.multiDrawArraysWEBGL(s,e,0,t,0,n);let l=0;for(let c=0;c<n;c++)l+=t[c];a.update(o,l,1)}}}class Ob{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return t===void 0&&(Y(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestampQuery(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class IB extends Ob{constructor(e,t,n=2048){if(super(n),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext){Y("EXT_disjoint_timer_query not supported; timestamps will be disabled."),this.trackTimestamp=!1;return}this.queries=[];for(let i=0;i<this.maxQueries;i++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null);const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(t==null||this.activeQuery!==null)return;const n=this.queries[t];if(n)try{this.queryStates.get(t)==="inactive"&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(i){V("Error in beginQuery:",i),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(t!=null&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(n){V("Error in endQuery:",n),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[s,o]of this.queryOffsets)if(this.queryStates.get(o)==="ended"){const u=this.queries[o];e.set(s,this.resolveQuery(u))}if(e.size===0)return this.lastValue;const t={},n=[];this.timestamps.clear();for(const[s,o]of e){const a=s.match(/^(.*):f(\d+)$/),u=parseInt(a[2]);n.includes(u)===!1&&n.push(u),t[u]===void 0&&(t[u]=0);const l=await o;this.timestamps.set(s,l),t[u]+=l}const i=t[n[n.length-1]];return this.lastValue=i,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return V("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed){t(this.lastValue);return}let n,i=!1;const s=()=>{n&&(clearTimeout(n),n=null)},o=u=>{i||(i=!0,s(),t(u))},a=()=>{if(this.isDisposed){o(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){o(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){n=setTimeout(a,1);return}const c=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(c)/1e6)}catch(u){V("Error checking query:",u),t(this.lastValue)}};a()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,!!this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.timestamps.clear(),this.frames=[],this.lastValue=0,this.activeQuery=null}}}const zs=[];class Eg extends Lb{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,n={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=t.context!==void 0?t.context:e.domElement.getContext("webgl2",n);function s(o){o.preventDefault();const a={api:"WebGL",message:o.statusMessage||"Unknown reason",reason:null,originalEvent:o};e.onDeviceLost(a)}this._onContextLost=s,e.domElement.addEventListener("webglcontextlost",s,!1),this.gl=i,this.extensions=new LB(this),this.capabilities=new OB(this),this.attributeUtils=new PB(this),this.textureUtils=new DB(this),this.bufferRenderer=new UB(this),this.state=new BB(this),this.utils=new FB(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(Y("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return nu}get hasTimestamp(){return this.disjoint!==null}async getArrayBufferAsync(e,t=null,n=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,i)}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),n!==null){const s=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:s}),this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer===!0&&e.multiview===!1&&Y("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new IB(this.gl,e,2048));const n=this.timestampQueryPool[e];n.allocateQueriesForContext(t)!==null&&n.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:s,height:o}=this.getDrawingBufferSize();t.viewport(0,0,s,o)}if(e.scissor)this.updateScissor(e);else{const{width:s,height:o}=this.getDrawingBufferSize();t.scissor(0,0,s,o)}this.initTimestampQuery(Pn.RENDER,this.getTimestampUID(e)),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0?(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(i),n.occlusionQueryObjects=new Array(i),n.occlusionQueryIndex=0):n.lastOcclusionObject!==void 0&&(n.lastOcclusionObject=void 0)}finishRender(e){const{gl:t,state:n}=this,i=this.get(e),s=i.previousContext;if(n.resetVertexState(),e.occlusionQueryCount>0){const u=i.lastOcclusionObject;u&&u.occlusionTest===!0&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e)}const a=e.textures;if(a!==null)for(let u=0;u<a.length;u++){const l=a[u];l.generateMipmaps&&this.generateMipmaps(l)}if(this._currentContext=s,this._resolveRenderTarget(e),s!==null){if(this._setFramebuffer(s),s.viewport)this.updateViewport(s);else{const{width:u,height:l}=this.getDrawingBufferSize();n.viewport(0,0,u,l)}if(s.scissor)this.updateScissor(s);else{const{width:u,height:l}=this.getDrawingBufferSize();n.scissor(0,0,u,l)}}this.prepareTimestampBuffer(Pn.RENDER,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const s=new WeakSet,{gl:o}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const a=()=>{let u=!0;for(let l=0;l<n.length;l++){const c=n[l];c&&(o.getQueryParameter(c,o.QUERY_RESULT_AVAILABLE)?(o.getQueryParameter(c,o.QUERY_RESULT)===0&&s.add(i[l]),n[l]=null,o.deleteQuery(c)):u=!1)}u===!1?requestAnimationFrame(a):t.occluded=s};a()}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:n,y:i,width:s,height:o}=e.viewportValue;t.viewport(n,e.height-o-i,s,o)}updateScissor(e){const{state:t}=this,{x:n,y:i,width:s,height:o}=e.scissorValue;t.scissor(n,e.height-o-i,s,o)}setScissorTest(e){this.state.setScissorTest(e)}resetState(){this.state.reset()}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,n,i=null,s=!0,o=!0){const{gl:a,renderer:u}=this;i===null&&(i={textures:null,clearColorValue:this.getClearColor()});let l=0;if(e&&(l|=a.COLOR_BUFFER_BIT),t&&(l|=a.DEPTH_BUFFER_BIT),n&&(l|=a.STENCIL_BUFFER_BIT),l!==0){let c;i.clearColorValue?c=i.clearColorValue:c=this.getClearColor();const h=u.getClearDepth(),d=u.getClearStencil();if(t&&this.state.setDepthMask(!0),n&&this.state.setStencilMask(4294967295),i.textures===null)e&&a.clearColor(c.r,c.g,c.b,c.a),t&&a.clearDepth(h),n&&a.clearStencil(d),a.clear(l);else{if(s&&this._setFramebuffer(i),e)for(let f=0;f<i.textures.length;f++){const p=i.mrt?i.mrt.getClearColor(i.textures[f].name):null;p!==null?a.clearBufferfv(a.COLOR,f,[p.r,p.g,p.b,p.a]):f===0?a.clearBufferfv(a.COLOR,f,[c.r,c.g,c.b,c.a]):a.clearBufferfv(a.COLOR,f,[0,0,0,1])}t&&n?a.clearBufferfi(a.DEPTH_STENCIL,0,h,d):t?a.clearBufferfv(a.DEPTH,0,[h]):n&&a.clearBufferiv(a.STENCIL,0,[d]),s&&o&&this._resolveRenderTarget(i),s&&this._currentContext!==null&&this._currentContext!==i&&this._setFramebuffer(this._currentContext)}}}beginCompute(e){const{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(Pn.COMPUTE,this.getTimestampUID(e))}compute(e,t,n,i,s=null){const{state:o,gl:a}=this;this.discard===!1&&(o.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:u,transformBuffers:l,attributes:c}=this.get(i),h=this._getVaoKey(c),d=this.vaoCache[h];d===void 0?this.vaoCache[h]=this._createVao(c):o.setVertexState(d),o.useProgram(u),this._bindUniforms(n);const f=this._getTransformFeedback(l);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,f),a.beginTransformFeedback(a.POINTS),s=s!==null?s:t.count,Array.isArray(s)?(Fe("WebGLBackend.compute(): The count parameter must be a single number, not an array."),s=s[0]):s&&typeof s=="object"&&s.isIndirectStorageBufferAttribute&&(Fe("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),s=t.count),c[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,s):a.drawArrays(a.POINTS,0,s),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let p=0;p<l.length;p++){const g=l[p];g.pbo&&this.has(g.pbo)&&this.textureUtils.copyBufferToTexture(g.transformBuffer,g.pbo),g.switchBuffers()}}finishCompute(e){const{state:t,gl:n}=this;this.discard=!1,t.disable(n.RASTERIZER_DISCARD),this.prepareTimestampBuffer(Pn.COMPUTE,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,n,i,s,o){if(e.isBatchedMesh)if(this.hasFeature("WEBGL_multi_draw")===!1){const{gl:a}=this,u=a.getUniformLocation(o,"nodeUniformDrawId"),l=e._multiDrawStarts,c=e._multiDrawCounts,h=e._multiDrawCount;for(let d=0;d<h;d++)a.uniform1ui(u,d),t.render(l[d],c[d])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else s>1?t.renderInstances(n,i,s):t.render(n,i)}draw(e){const{object:t,pipeline:n,material:i,context:s,hardwareClippingPlanes:o}=e,{programGPU:a}=this.get(n),{gl:u,state:l}=this,c=this.get(s),h=e.getDrawParameters();if(h===null)return;this._bindUniforms(e.getBindings());const d=t.isMesh&&t.matrixWorld.determinantAffine()<0;l.setMaterial(i,d,o),s.mrt!==null&&s.textures!==null&&l.setMRTBlending(s.textures,s.mrt,i),l.useProgram(a);const f=e.getAttributes(),p=this.get(f);let g=p.vaoGPU;if(g===void 0){const w=this._getVaoKey(f);g=this.vaoCache[w],g===void 0&&(g=this._createVao(f),this.vaoCache[w]=g,p.vaoGPU=g)}const _=e.getIndex(),m=_!==null?this.get(_).bufferGPU:null;l.setVertexState(g,m);const y=c.lastOcclusionObject;if(y!==t&&y!==void 0){if(y!==null&&y.occlusionTest===!0&&(u.endQuery(u.ANY_SAMPLES_PASSED),c.occlusionQueryIndex++),t.occlusionTest===!0){const w=u.createQuery();u.beginQuery(u.ANY_SAMPLES_PASSED,w),c.occlusionQueries[c.occlusionQueryIndex]=w,c.occlusionQueryObjects[c.occlusionQueryIndex]=t}c.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=u.POINTS:t.isLineSegments?b.mode=u.LINES:t.isLine?b.mode=u.LINE_STRIP:t.isLineLoop?b.mode=u.LINE_LOOP:i.wireframe===!0?(l.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=u.LINES):b.mode=u.TRIANGLES;const{vertexCount:T,instanceCount:x}=h;let{firstVertex:v}=h;if(b.object=t,_!==null){v*=_.array.BYTES_PER_ELEMENT;const w=this.get(_);b.index=_.count,b.type=w.type}else b.index=0;if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){const w=this.get(e.camera),R=e.camera.cameras,F=e.getBindingGroup("cameraIndex").bindings[0];if(w.indexesGPU===void 0||w.indexesGPU.length!==R.length){const H=new Uint32Array([0,0,0,0]),ue=[];for(let L=0,G=R.length;L<G;L++){const Z=u.createBuffer();H[0]=L,u.bindBuffer(u.UNIFORM_BUFFER,Z),u.bufferData(u.UNIFORM_BUFFER,H,u.STATIC_DRAW),ue.push(Z)}w.indexesGPU=ue}let M=0;e:for(const H of e.getBindings())for(const ue of H.bindings){if(ue===F)break e;(ue.isUniformsGroup||ue.isUniformBuffer)&&M++}const O=this._currentContext.renderTarget,U=O===null||O.isPostProcessingRenderTarget===!0?this.renderer.getPixelRatio():1,X=this._isRenderCameraDepthArray(this._currentContext),oe=this._currentContext.activeCubeFace;if(X){const H=this.get(O.depthTexture);if(H.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){H.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:ue}=O;for(let L=0,G=R.length;L<G;L++)this.renderer._activeCubeFace=L,this._currentContext.activeCubeFace=L,this._setFramebuffer(this._currentContext),this.clear(!1,!0,ue,this._currentContext,!1,!1);this.renderer._activeCubeFace=oe,this._currentContext.activeCubeFace=oe}}for(let H=0,ue=R.length;H<ue;H++){const L=R[H];if(t.layers.test(L.layers)){X&&(this.renderer._activeCubeFace=H,this._currentContext.activeCubeFace=H,this._setFramebuffer(this._currentContext));const G=L.viewport;if(G!==void 0){const Z=G.x*U,ce=G.y*U,k=G.width*U,j=G.height*U;l.viewport(Math.floor(Z),Math.floor(e.context.height-j-ce),Math.floor(k),Math.floor(j))}l.bindBufferBase(u.UNIFORM_BUFFER,M,w.indexesGPU[H]),this._draw(t,b,v,T,x,a)}this._currentContext.activeCubeFace=oe,this.renderer._activeCubeFace=oe}}else this._draw(t,b,v,T,x,a)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,s,o){return this.textureUtils.copyTextureToBuffer(e,t,n,i,s,o)}updateSampler(){return""}createNodeBuilder(e,t){return new EB(e,t)}createProgram(e){const t=this.gl,{stage:n,code:i}=e,s=n==="fragment"?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(s,i),t.compileShader(s),this.set(e,{shaderGPU:s})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const n=this.gl,i=e.pipeline,{fragmentProgram:s,vertexProgram:o}=i,a=n.createProgram(),u=this.get(s).shaderGPU,l=this.get(o).shaderGPU;if(n.attachShader(a,u),n.attachShader(a,l),n.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:u,vertexShader:l}),t!==null&&this.parallel){const c=new Promise(h=>{const d=this.parallel,f=()=>{n.getProgramParameter(a,d.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),h()):requestAnimationFrame(f)};f()});t.push(c);return}this._completeCompile(e,i)}_handleSource(e,t){const n=e.split(`
739
+ `),i=[],s=Math.max(t-6,0),o=Math.min(t+6,n.length);for(let a=s;a<o;a++){const u=a+1;i.push(`${u===t?">":" "} ${u}: ${n[a]}`)}return i.join(`
740
+ `)}_getShaderErrors(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),o=(e.getShaderInfoLog(t)||"").trim();if(i&&o==="")return"";const a=/ERROR: 0:(\d+)/.exec(o);if(a){const u=parseInt(a[1]);return n.toUpperCase()+`
741
+
742
+ `+o+`
743
+
744
+ `+this._handleSource(e.getShaderSource(t),u)}else return o}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const i=this.gl,o=(i.getProgramInfoLog(e)||"").trim();if(i.getProgramParameter(e,i.LINK_STATUS)===!1)if(typeof this.renderer.debug.onShaderError=="function")this.renderer.debug.onShaderError(i,e,n,t);else{const a=this._getShaderErrors(i,n,"vertex"),u=this._getShaderErrors(i,t,"fragment");V("WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+`
745
+
746
+ Program Info Log: `+o+`
747
+ `+a+`
748
+ `+u)}else o!==""&&Y("WebGLProgram: Program Info Log:",o)}}_completeCompile(e,t){const{state:n,gl:i}=this,s=this.get(t),{programGPU:o,fragmentShader:a,vertexShader:u}=s;i.getProgramParameter(o,i.LINK_STATUS)===!1&&this._logProgramError(o,a,u),n.useProgram(o);const l=e.getBindings();this._setupBindings(l,o),this.set(t,{programGPU:o,pipeline:o})}createComputePipeline(e,t,n=null){const{gl:i}=this,s={stage:"fragment",code:`#version 300 es
749
+ precision highp float;
750
+ void main() {}`};this.createProgram(s);const{computeProgram:o}=e,a=i.createProgram(),u=this.get(s).shaderGPU,l=this.get(o).shaderGPU,c=o.transforms,h=[],d=[];for(let _=0;_<c.length;_++){const m=c[_];h.push(m.varyingName),d.push(m.attributeNode)}i.attachShader(a,u),i.attachShader(a,l),i.transformFeedbackVaryings(a,h,i.SEPARATE_ATTRIBS),i.linkProgram(a);const f=o.attributes,p=[],g=[];for(let _=0;_<f.length;_++){const m=f[_].node.attribute;p.push(m),this.has(m)||this.attributeUtils.createAttribute(m,i.ARRAY_BUFFER)}for(let _=0;_<d.length;_++){const m=d[_].attribute;this.has(m)||this.attributeUtils.createAttribute(m,i.ARRAY_BUFFER);const y=this.get(m);g.push(y)}if(this.set(e,{programGPU:a,fragmentShader:u,vertexShader:l,transformBuffers:g,attributes:p}),n!==null&&this.parallel){const _=this.parallel,m=new Promise(y=>{const b=()=>{i.getProgramParameter(a,_.COMPLETION_STATUS_KHR)?(this._completeComputeCompile(e,t),y()):requestAnimationFrame(b)};b()});n.push(m);return}this._completeComputeCompile(e,t)}_completeComputeCompile(e,t){const{state:n,gl:i}=this,{programGPU:s,fragmentShader:o,vertexShader:a}=this.get(e);i.getProgramParameter(s,i.LINK_STATUS)===!1&&this._logProgramError(s,o,a),n.useProgram(s),this._setupBindings(t,s)}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let n=0,i=0;for(const s of t){this.set(s,{textures:i,uniformBuffers:n});for(const o of s.bindings)o.isUniformBuffer&&n++,o.isSampledTexture&&i++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this;for(const n of e.bindings){const i=this.get(n);if(n.isUniformsGroup||n.isUniformBuffer){const s=n.buffer,o=i.bufferGPU;t.bindBuffer(t.UNIFORM_BUFFER,o);const a=n.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,o),a.length===0)t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW);else{const u=iu(s),l=u?1:s.BYTES_PER_ELEMENT;for(let c=0,h=a.length;c<h;c++){const d=a[c],f=d.start*l,p=d.count*l,g=f*(u?s.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,g,s,f,p)}}this.set(n,i)}else if(n.isSampledTexture){const{textureGPU:s,glTextureType:o}=this.get(n.texture);i.textureGPU=s,i.glTextureType=o,this.set(n,i)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const i=this.get(e).bufferGPU,s=e.buffer,o=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,i),o.length===0)t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW);else{const a=iu(s),u=a?1:s.BYTES_PER_ELEMENT;let l=o[0].start;for(let c=0,h=o.length;c<h;c++){const d=o[c],f=o[c+1],p=d.start+d.count;if(f!==void 0&&f.start===p)continue;const g=l*u,_=(p-l)*u,m=g*(a?s.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,m,s,g,_),f!==void 0&&(l=f.start)}}}}createUniformBuffer(e){const t=this.get(e);if(t.bufferGPU===void 0){const n=this.gl,i=e.buffer;t.bufferGPU=n.createBuffer(),n.bindBuffer(n.UNIFORM_BUFFER,t.bufferGPU),n.bufferData(n.UNIFORM_BUFFER,i.byteLength,n.DYNAMIC_DRAW)}}destroyUniformBuffer(e){const t=this.get(e);this.gl.deleteBuffer(t.bufferGPU),this.delete(e)}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(Ng).filter(i=>Ng[i]===e),n=this.extensions;for(let i=0;i<t.length;i++)if(n.has(t[i]))return!0;return!1}copyTextureToTexture(e,t,n=null,i=null,s=0,o=0){this.textureUtils.copyTextureToTexture(e,t,n,i,s,o)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}hasCompatibility(e){return e===Si.TEXTURE_COMPARE?!0:super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:n}=this;this._setFramebuffer(e),n.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:n}=this;let i=null;if(e.textures!==null){const s=e.renderTarget,o=this.get(s),{depthBuffer:a,stencilBuffer:u}=s,l=s.isCubeRenderTarget===!0,c=s.isRenderTarget3D===!0,h=s.depth>1,d=s.isXRRenderTarget===!0,f=d===!0&&s._hasExternalTextures===!0;let p=o.msaaFrameBuffer,g=o.depthRenderbuffer;const _=this.extensions.get("WEBGL_multisampled_render_to_texture"),m=this.extensions.get("OVR_multiview2"),y=this._useMultisampledExtension(s);let b=s.samples;e.depthTexture!==null&&e.depthTexture.renderTarget!==s&&y===!1&&b>0&&(Fe('WebGLBackend: Shared depth texture is not supported with MSAA when "WEBGL_multisampled_render_to_texture" is unsupported. Falling back to single-sample rendering.'),b=0);const T=cb(e);let x;if(l?(o.cubeFramebuffers||(o.cubeFramebuffers={}),x=o.cubeFramebuffers[T]):d&&f===!1?x=this._xrFramebuffer:(o.framebuffers||(o.framebuffers={}),x=o.framebuffers[T]),x===void 0){x=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,x);const v=e.textures,w=[];if(l){o.cubeFramebuffers[T]=x;const{textureGPU:F}=this.get(v[0]),M=this.renderer._activeCubeFace,O=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+M,F,O)}else{o.framebuffers[T]=x;for(let F=0;F<v.length;F++){const M=v[F],O=this.get(M);O.renderTarget=e.renderTarget,O.cacheKey=T;const U=t.COLOR_ATTACHMENT0+F;if(s.multiview)m.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,U,O.textureGPU,0,b,0,2);else if(c||h){const X=this.renderer._activeCubeFace,oe=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,U,O.textureGPU,oe,X)}else if(y)_.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,U,t.TEXTURE_2D,O.textureGPU,0,b);else{const X=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,U,t.TEXTURE_2D,O.textureGPU,X)}}}const R=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(s._autoAllocateDepthBuffer===!0){const F=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(F,e,0,y),o.xrDepthRenderbuffer=F,w.push(u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,F),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,F)}else if(e.depthTexture!==null){w.push(u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const F=this.get(e.depthTexture);if(F.renderTarget=e.renderTarget,F.cacheKey=T,s.multiview)m.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,F.textureGPU,0,b,0,2);else if(f&&y)_.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,F.textureGPU,0,b);else if(e.depthTexture.isArrayTexture){const M=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,R,F.textureGPU,0,M)}else if(e.depthTexture.isCubeTexture){const M=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_CUBE_MAP_POSITIVE_X+M,F.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,F.textureGPU,0)}o.depthInvalidationArray=w}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,x);const w=this.renderer._activeCubeFace,R=this.get(e.depthTexture),F=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,F,R.textureGPU,0,w)}if((d||y||s.multiview)&&s._isOpaqueFramebuffer!==!0){n.bindFramebuffer(t.FRAMEBUFFER,x);const w=this.get(e.textures[0]);s.multiview?m.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,w.textureGPU,0,b,0,2):y?_.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,w.textureGPU,0,b):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,w.textureGPU,0);const R=u?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(s._autoAllocateDepthBuffer===!0){const F=o.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,F),t.framebufferRenderbuffer(t.FRAMEBUFFER,R,t.RENDERBUFFER,F)}else{const F=this.get(e.depthTexture);s.multiview?m.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,R,F.textureGPU,0,b,0,2):y?_.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,R,t.TEXTURE_2D,F.textureGPU,0,b):t.framebufferTexture2D(t.FRAMEBUFFER,R,t.TEXTURE_2D,F.textureGPU,0)}}}if(b>0&&y===!1&&!s.multiview){if(p===void 0){p=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,p);const v=[],w=e.textures;for(let R=0;R<w.length;R++){v[R]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,v[R]);const F=e.textures[R],M=this.get(F);t.renderbufferStorageMultisample(t.RENDERBUFFER,b,M.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+R,t.RENDERBUFFER,v[R])}t.bindRenderbuffer(t.RENDERBUFFER,null),o.msaaFrameBuffer=p,o.msaaRenderbuffers=v,a&&g===void 0&&(g=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(g,e,b),o.depthRenderbuffer=g)}i=o.msaaFrameBuffer}else i=x;n.drawBuffers(e,x)}n.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let n=0;n<e.length;n++){const i=this.get(e[n]);t+=":"+i.id}return t}_createVao(e){const{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let i=0;i<e.length;i++){const s=e[i],o=this.get(s);t.bindBuffer(t.ARRAY_BUFFER,o.bufferGPU),t.enableVertexAttribArray(i);let a,u;s.isInterleavedBufferAttribute===!0?(a=s.data.stride*o.bytesPerElement,u=s.offset*o.bytesPerElement):(a=0,u=0),o.isInteger?t.vertexAttribIPointer(i,s.itemSize,o.type,a,u):t.vertexAttribPointer(i,s.itemSize,o.type,s.normalized,a,u),s.isInstancedBufferAttribute&&!s.isInterleavedBufferAttribute?t.vertexAttribDivisor(i,s.meshPerAttribute):s.isInterleavedBufferAttribute&&s.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(i,s.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t="";for(let s=0;s<e.length;s++)t+=":"+e[s].id;let n=this.transformFeedbackCache[t];if(n!==void 0)return n;const{gl:i}=this;n=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,n);for(let s=0;s<e.length;s++){const o=e[s];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,s,o.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){const n=this.gl;let i=0,s=0;for(const o of e)for(const a of o.bindings)if(a.isUniformsGroup||a.isUniformBuffer){const u=i++,l=n.getUniformBlockIndex(t,a.name);n.uniformBlockBinding(t,l,u)}else if(a.isSampledTexture){const u=s++,l=n.getUniformLocation(t,a.name);n.uniform1i(l,u)}}_bindUniforms(e){const{gl:t,state:n}=this;let i=0,s=0;for(const o of e)for(const a of o.bindings){const u=this.get(a);if(a.isUniformsGroup||a.isUniformBuffer){const l=i++;n.bindBufferBase(t.UNIFORM_BUFFER,l,u.bufferGPU)}else if(a.isSampledTexture){const l=s++;n.bindTexture(u.glTextureType,u.textureGPU,t.TEXTURE0+l)}}}_resolveRenderTarget(e){const{gl:t,state:n}=this,i=e.renderTarget;if(e.textures!==null&&i){const s=this.get(i);if(i.samples>0&&s.msaaFrameBuffer!==void 0&&this._useMultisampledExtension(i)===!1){const o=s.framebuffers[e.getCacheKey()];let a=i.resolveColorBuffer===!1?0:t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const u=s.msaaFrameBuffer,l=s.msaaRenderbuffers,c=e.textures,h=c.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,u),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,o),h)for(let d=0;d<c.length;d++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.TEXTURE_2D,null,0);for(let d=0;d<c.length;d++){if(h){const{textureGPU:f}=this.get(c[d]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,l[d]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,f,0)}if(e.scissor){const{x:f,y:p,width:g,height:_}=e.scissorValue,m=e.height-_-p;t.blitFramebuffer(f,m,f+g,m+_,f,m,f+g,m+_,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(h)for(let d=0;d<c.length;d++){const{textureGPU:f}=this.get(c[d]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.RENDERBUFFER,l[d]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.TEXTURE_2D,f,0)}if(this._supportsInvalidateFramebuffer===!0){if(i.storeMultisampledColorBuffer===!1)for(let d=0;d<c.length;d++)zs.push(t.COLOR_ATTACHMENT0+d);i.depthBuffer&&i.storeMultisampledDepthBuffer===!1&&zs.push(i.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),zs.length>0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,zs),zs.length=0)}}else if(this._supportsInvalidateFramebuffer===!0&&s.framebuffers&&(i._autoAllocateDepthBuffer===!0||i.samples>0&&i.storeMultisampledDepthBuffer===!1)){const o=s.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,o),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,s.depthInvalidationArray)}}}_useMultisampledExtension(e){return e.multiview===!0?!0:e.samples>0&&this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer!==!1}async dispose(){await super.dispose(),this.textureUtils!==null&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const no={PointList:"point-list",LineList:"line-list",LineStrip:"line-strip",TriangleList:"triangle-list"},_n=typeof self<"u"&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},rt={Never:"never",Less:"less",Equal:"equal",LessEqual:"less-equal",Greater:"greater",NotEqual:"not-equal",GreaterEqual:"greater-equal",Always:"always"},je={Store:"store",Discard:"discard"},me={Load:"load",Clear:"clear"},Cg={CCW:"ccw",CW:"cw"},Mg={None:"none",Back:"back"},Au={Uint16:"uint16",Uint32:"uint32"},S={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R16Unorm:"r16unorm",R16Snorm:"r16snorm",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RG16Unorm:"rg16unorm",RG16Snorm:"rg16snorm",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10UFloat:"rg11b10ufloat",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA16Unorm:"rgba16unorm",RGBA16Snorm:"rgba16snorm",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-unorm-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},uc={ClampToEdge:"clamp-to-edge",Repeat:"repeat",MirrorRepeat:"mirror-repeat"},Kt={Linear:"linear",Nearest:"nearest"},fe={Zero:"zero",One:"one",Src:"src",OneMinusSrc:"one-minus-src",SrcAlpha:"src-alpha",OneMinusSrcAlpha:"one-minus-src-alpha",Dst:"dst",OneMinusDst:"one-minus-dst",DstAlpha:"dst-alpha",OneMinusDstAlpha:"one-minus-dst-alpha",SrcAlphaSaturated:"src-alpha-saturated",Constant:"constant",OneMinusConstant:"one-minus-constant"},Jr={Add:"add",Subtract:"subtract",ReverseSubtract:"reverse-subtract",Min:"min",Max:"max"},Pg={None:0,All:15},vr={Keep:"keep",Zero:"zero",Replace:"replace",Invert:"invert",IncrementClamp:"increment-clamp",DecrementClamp:"decrement-clamp",IncrementWrap:"increment-wrap",DecrementWrap:"decrement-wrap"},xa={Storage:"storage",ReadOnlyStorage:"read-only-storage"},lc={WriteOnly:"write-only",ReadOnly:"read-only",ReadWrite:"read-write"},Bg={NonFiltering:"non-filtering",Comparison:"comparison"},Tr={Float:"float",UnfilterableFloat:"unfilterable-float",Depth:"depth",SInt:"sint",UInt:"uint"},cc={TwoD:"2d",ThreeD:"3d"},it={TwoD:"2d",TwoDArray:"2d-array",Cube:"cube",ThreeD:"3d"},kB={All:"all"},va={Vertex:"vertex",Instance:"instance"},Nu={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},Fg={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class GB extends Fb{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class VB extends Cb{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let $B=0;class zB extends VB{constructor(e,t){const n=e&&e.name?e.name:$B++;super("StorageBuffer_"+n,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Wt.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}const hc=[null];class WB{constructor(e){this.backend=e,this._preferredCanvasFormat=null}getCurrentDepthStencilFormat(e){let t;return e.depth&&(e.depthTexture!==null?t=this.getTextureFormatGPU(e.depthTexture):e.stencil?this.backend.renderer.reversedDepthBuffer===!0?t=S.Depth32FloatStencil8:t=S.Depth24PlusStencil8:this.backend.renderer.reversedDepthBuffer===!0?t=S.Depth32Float:t=S.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const o=this.backend.get(e);o.texture!==void 0?t=o.texture.sampleCount:t=this.backend.renderer.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=this.getSampleCount(t||1);const n=t>1&&e.renderTarget!==null&&e.isDepthTexture!==!0&&e.isFramebufferTexture!==!0,i=t>1&&e.renderTarget!==null&&e.isDepthTexture===!0&&e.isArrayTexture===!0;return{samples:t,primarySamples:n||i?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return e.textures!==null?t=this.getTextureFormatGPU(e.textures[0]):t=this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return e.textures!==null?e.textures.map(t=>this.getTextureFormatGPU(t)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return e.textures!==null?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return no.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return no.LineList;if(e.isLine)return no.LineStrip;if(e.isMesh)return no.TriangleList}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return e.textures!==null?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const t=this.backend.parameters.outputType;if(t===void 0)return this._preferredCanvasFormat===null&&(this._preferredCanvasFormat=navigator.gpu.getPreferredCanvasFormat()),this._preferredCanvasFormat;if(t===Pt)return S.BGRA8Unorm;if(t===wt)return S.RGBA16Float;throw new Error("THREE.WebGPUUtils: Unsupported output buffer type.")}}function Mn(r,e){hc[0]=e,r.queue.submit(hc),hc[0]=null}class Ub{constructor(){this.label="",this.layout=null,this.entries=[]}reset(){this.label="",this.layout=null,this.entries.length=0}}class Ts{constructor(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}reset(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}}class Go{constructor(){this.label=""}reset(){this.label=""}}class Ib{constructor(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}reset(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}}class po{constructor(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}reset(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}}class go{constructor(){this.label="",this.colorAttachments=[],this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}reset(){this.label="",this.colorAttachments.length=0,this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}}class kb{constructor(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample=new HB,this.fragment=null}reset(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample.reset(),this.fragment=null}}class HB{constructor(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}reset(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}}class Gb{constructor(){this.label="",this.code="",this.compilationHints=[]}reset(){this.label="",this.code="",this.compilationHints.length=0}}class nl{constructor(){this.label="",this.size={width:0,height:1,depthOrArrayLayers:1},this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats=[],this.textureBindingViewDimension=void 0}reset(){this.label="",this.size.width=0,this.size.height=1,this.size.depthOrArrayLayers=1,this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats.length=0,this.textureBindingViewDimension=void 0}}class jd{constructor(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}reset(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}}const Sr=new Ub,wr=new Ts,Ta=new Go,dc=new Ib,fc=new go,Ui=new kb,Ws=new po,Sa=new Gb,Ii=new nl,We=new jd;class jB extends jr{constructor(e){super(),this.device=e;const t=`
751
+ struct VarysStruct {
752
+ @builtin( position ) Position: vec4f,
753
+ @location( 0 ) vTex : vec2f,
754
+ @location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
755
+ };
756
+
757
+ @group( 0 ) @binding ( 2 )
758
+ var<uniform> flipY: u32;
759
+
760
+ @vertex
761
+ fn mainVS(
762
+ @builtin( vertex_index ) vertexIndex : u32,
763
+ @builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
764
+
765
+ var Varys : VarysStruct;
766
+
767
+ var pos = array(
768
+ vec2f( -1, -1 ),
769
+ vec2f( -1, 3 ),
770
+ vec2f( 3, -1 ),
771
+ );
772
+
773
+ let p = pos[ vertexIndex ];
774
+ let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
775
+ Varys.vTex = p * mult + vec2f( 0.5 );
776
+ Varys.Position = vec4f( p, 0, 1 );
777
+ Varys.vBaseArrayLayer = instanceIndex;
778
+
779
+ return Varys;
780
+
781
+ }
782
+
783
+ @group( 0 ) @binding( 0 )
784
+ var imgSampler : sampler;
785
+
786
+ @group( 0 ) @binding( 1 )
787
+ var img2d : texture_2d<f32>;
788
+
789
+ @fragment
790
+ fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
791
+
792
+ return textureSample( img2d, imgSampler, Varys.vTex );
793
+
794
+ }
795
+
796
+ @group( 0 ) @binding( 1 )
797
+ var img2dArray : texture_2d_array<f32>;
798
+
799
+ @fragment
800
+ fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
801
+
802
+ return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
803
+
804
+ }
805
+
806
+ const faceMat = array(
807
+ mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
808
+ mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
809
+ mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
810
+ mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
811
+ mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
812
+ mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
813
+ );
814
+
815
+ @group( 0 ) @binding( 1 )
816
+ var imgCube : texture_cube<f32>;
817
+
818
+ @fragment
819
+ fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
820
+
821
+ return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
822
+
823
+ }
824
+ `;this.mipmapSampler=e.createSampler({minFilter:Kt.Linear}),this.flipYSampler=e.createSampler({minFilter:Kt.Nearest}),wr.size=4,wr.usage=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,this.flipUniformBuffer=e.createBuffer(wr),wr.reset(),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),wr.size=4,wr.usage=GPUBufferUsage.UNIFORM,this.noFlipUniformBuffer=e.createBuffer(wr),wr.reset(),this.transferPipelines={},Sa.label="mipmap",Sa.code=t,this.mipmapShaderModule=e.createShaderModule(Sa),Sa.reset()}getTransferPipeline(e,t){t=t||"2d-array";const n=`${e}-${t}`;let i=this.transferPipelines[n];return i===void 0&&(Ui.label=`mipmap-${e}-${t}`,Ui.vertex={module:this.mipmapShaderModule},Ui.fragment={module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},Ui.layout="auto",i=this.device.createRenderPipeline(Ui),Ui.reset(),this.transferPipelines[n]=i),i}flipY(e,t,n=0){const i=t.format,{width:s,height:o}=t.size;Ii.size.width=s,Ii.size.height=o,Ii.format=i,Ii.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;const a=this.device.createTexture(Ii);Ii.reset();const u=this.getTransferPipeline(i,e.textureBindingViewDimension),l=this.getTransferPipeline(i,a.textureBindingViewDimension),c=this.device.createCommandEncoder(Ta),h=(d,f,p,g,_,m)=>{const y=d.getBindGroupLayout(0);We.dimension=f.textureBindingViewDimension||"2d-array",We.mipLevelCount=1;const b=f.createView(We);We.reset(),Sr.layout=y,Sr.entries.push({binding:0,resource:this.flipYSampler},{binding:1,resource:b},{binding:2,resource:{buffer:m?this.flipUniformBuffer:this.noFlipUniformBuffer}});const T=this.device.createBindGroup(Sr);Sr.reset(),We.dimension="2d",We.mipLevelCount=1,We.baseArrayLayer=_,We.arrayLayerCount=1;const x=g.createView(We);We.reset(),Ws.view=x,Ws.loadOp=me.Clear,Ws.storeOp=je.Store,fc.colorAttachments.push(Ws);const v=c.beginRenderPass(fc);fc.reset(),Ws.reset(),v.setPipeline(d),v.setBindGroup(0,T),v.draw(3,1,0,p),v.end()};h(u,e,n,a,0,!1),h(l,a,0,e,n,!0),Mn(this.device,c.finish()),a.destroy()}generateMipmaps(e,t=null){const n=this.get(e),i=n.layers||this._mipmapCreateBundles(e);let s=t;s===null&&(Ta.label="mipmapEncoder",s=this.device.createCommandEncoder(Ta),Ta.reset()),this._mipmapRunBundles(s,i),t===null&&Mn(this.device,s.finish()),n.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",n=this.getTransferPipeline(e.format,t),i=n.getBindGroupLayout(0),s=[];for(let o=1;o<e.mipLevelCount;o++)for(let a=0;a<e.depthOrArrayLayers;a++){We.dimension=t,We.baseMipLevel=o-1,We.mipLevelCount=1;const u=e.createView(We);We.reset(),Sr.layout=i,Sr.entries.push({binding:0,resource:this.mipmapSampler},{binding:1,resource:u},{binding:2,resource:{buffer:this.noFlipUniformBuffer}});const l=this.device.createBindGroup(Sr);Sr.reset(),We.dimension="2d",We.baseMipLevel=o,We.mipLevelCount=1,We.baseArrayLayer=a,We.arrayLayerCount=1;const c=e.createView(We);We.reset();const h=new po;h.view=c,h.loadOp=me.Clear,h.storeOp=je.Store;const d=new go;d.colorAttachments.push(h),dc.colorFormats=[e.format];const f=this.device.createRenderBundleEncoder(dc);dc.reset(),f.setPipeline(n),f.setBindGroup(0,l),f.draw(3,1,0,a),s.push({renderBundles:[f.finish()],passDescriptor:d})}return s}_mipmapRunBundles(e,t){const n=t.length;for(let i=0;i<n;i++){const s=t[i],o=e.beginRenderPass(s.passDescriptor);o.executeBundles(s.renderBundles),o.end()}}}class qB{constructor(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}reset(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}}class rl{constructor(){this.texture=null,this.mipLevel=0,this.origin={x:0,y:0,z:0},this.aspect="all"}reset(){this.texture=null,this.mipLevel=0,this.origin.x=0,this.origin.y=0,this.origin.z=0,this.aspect="all"}}class XB{constructor(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}}class KB{constructor(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}}class YB{constructor(){this.source=null,this.origin={x:0,y:0},this.flipY=!1}reset(){this.source=null,this.origin.x=0,this.origin.y=0,this.flipY=!1}}class QB extends rl{constructor(){super(),this.colorSpace="srgb",this.premultipliedAlpha=!1}reset(){super.reset(),this.colorSpace="srgb",this.premultipliedAlpha=!1}}class Vb{constructor(){this.width=0,this.height=1,this.depthOrArrayLayers=1}reset(){this.width=0,this.height=1,this.depthOrArrayLayers=1}}const wa=new Ts,ZB=new Go,ct=new qB,ft=new rl,Ra=new XB,tr=new KB,Aa=new YB,ki=new QB,Rr=new nl,dt=new Vb,JB={[gm]:"never",[id]:"less",[fm]:"equal",[Fo]:"less-equal",[su]:"greater",[ss]:"greater-equal",[pm]:"always",[dm]:"not-equal"},eF=[0,1,3,2,4,5];function Dg(r,e,t,n,i,s,o,a,u,l){ft.texture=e,ft.mipLevel=t,ft.origin.z=n,tr.offset=n*s,tr.bytesPerRow=o,tr.rowsPerImage=a,dt.width=u,dt.height=l,r.queue.writeTexture(ft,i.data,tr,dt),ft.reset(),tr.reset(),dt.reset()}class tF{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,n=e.texture,i=e.textureNode,s=n.isDepthTexture===!0&&n.compareFunction!==null&&i.isSampleCompare()&&t.hasCompatibility(Si.TEXTURE_COMPARE),o=n.minFilter+"-"+n.magFilter+"-"+n.wrapS+"-"+n.wrapT+"-"+(n.wrapR||"0")+"-"+n.anisotropy+"-"+(n.isDepthTexture===!0?1:0)+"-"+(s?n.compareFunction:0);let a=this._samplerCache.get(o);if(a===void 0){ct.addressModeU=this._convertAddressMode(n.wrapS),ct.addressModeV=this._convertAddressMode(n.wrapT),ct.addressModeW=this._convertAddressMode(n.wrapR),ct.magFilter=this._convertFilterMode(n.magFilter),ct.minFilter=this._convertFilterMode(n.minFilter),ct.mipmapFilter=this._convertMipmapFilterMode(n.minFilter),n.isDepthTexture&&s===!1&&(ct.magFilter=Kt.Nearest,ct.minFilter=Kt.Nearest,ct.mipmapFilter=Kt.Nearest),ct.magFilter===Kt.Linear&&ct.minFilter===Kt.Linear&&ct.mipmapFilter===Kt.Linear&&(ct.maxAnisotropy=n.anisotropy),s&&(ct.compare=JB[n.compareFunction]);const l=t.device.createSampler(ct);ct.reset(),a={sampler:l,usedTimes:0},this._samplerCache.set(o,a)}const u=t.get(e);return u.sampler!==a.sampler&&(this._releaseSampler(u),u.samplerKey=o,u.sampler=a.sampler,a.usedTimes++),o}destroySampler(e){this._releaseSampler(this.backend.get(e))}_releaseSampler(e){if(e.sampler!==void 0){const t=this._samplerCache.get(e.samplerKey);t.usedTimes--,t.usedTimes===0&&this._samplerCache.delete(e.samplerKey),e.sampler=void 0,e.samplerKey=void 0}}createDefaultTexture(e){let t;const n=Dh(e,this.backend.device);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(n):t=this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){const n=this.backend,i=n.get(e);if(i.initialized){if(i.externalTexture===!0)return;throw new Error("THREE.WebGPUTextureUtils: Texture already initialized.")}if(e.isExternalTexture){i.texture=e.sourceTexture,i.initialized=!0;return}t.needsMipmaps===void 0&&(t.needsMipmaps=!1),t.levels===void 0&&(t.levels=1),t.depth===void 0&&(t.depth=1);const{width:s,height:o,depth:a,levels:u}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const l=this._getDimension(e),c=e.internalFormat||t.format||Dh(e,n.device);i.format=c;const{samples:h,primarySamples:d,isMSAA:f}=n.utils.getTextureSampleData(e),p=e.renderTarget,g=h>1&&p!==null&&a>1&&l===cc.TwoD,m=GPUTextureUsage.TRANSIENT_ATTACHMENT!==void 0&&g===!1,y=e.isDepthTexture===!0&&m&&(p==null?void 0:p.storeMultisampledDepthBuffer)===!1&&(p.stencilBuffer===!1||p.storeMultisampledStencilBuffer===!1),b=e.isDepthTexture!==!0&&m&&(p==null?void 0:p.storeMultisampledColorBuffer)===!1;let T=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(T|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&c!==S.RGB9E5UFloat&&(T|=GPUTextureUsage.RENDER_ATTACHMENT),d>1&&y&&(T=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT);const x=new nl;if(x.label=e.name,x.size.width=s,x.size.height=o,x.size.depthOrArrayLayers=a,x.mipLevelCount=u,x.sampleCount=d,x.dimension=l,x.format=c,x.usage=T,c===void 0){Y("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);return}e.isCubeTexture&&(x.textureBindingViewDimension=it.Cube);try{i.texture=n.device.createTexture(x)}catch{Y("WebGPURenderer: Failed to create texture with descriptor:",x),this.createDefaultTexture(e);return}if(f||g){const v=Object.assign({},x);if(v.label=v.label+"-msaa",v.sampleCount=h,v.mipLevelCount=1,(y||b)&&(v.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT),g){v.size=Object.assign({},v.size,{depthOrArrayLayers:1}),i.msaaTextures=[];for(let w=0;w<a;w++)v.label=x.label+"-msaa-"+w,i.msaaTextures.push(n.device.createTexture(v))}else i.msaaTexture=n.device.createTexture(v)}i.initialized=!0,i.textureDescriptorGPU=x}destroyTexture(e,t=!1){const n=this.backend,i=n.get(e);if(i.texture!==void 0&&t===!1&&e.isExternalTexture!==!0&&i.externalTexture!==!0&&i.texture.destroy(),i.msaaTexture!==void 0&&i.msaaTexture.destroy(),i.msaaTextures!==void 0)for(const s of i.msaaTextures)s.destroy();n.delete(e)}generateMipmaps(e,t=null){const n=this.backend.get(e);this._generateMipmaps(n.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:n,height:i}=e.getDrawingBufferSize(),s=e.renderer.currentSamples,o=t.colorTexture,a=e.get(o);if(o.width===n&&o.height===i&&o.samples===s)return a.texture;let u=a.texture;return u&&u.destroy(),Rr.label="colorBuffer",Rr.size.width=n,Rr.size.height=i,Rr.sampleCount=e.utils.getSampleCount(e.renderer.currentSamples),Rr.format=e.utils.getPreferredCanvasFormat(),Rr.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,u=e.device.createTexture(Rr),Rr.reset(),o.source.width=n,o.source.height=i,o.samples=s,a.texture=u,u}getDepthBuffer(e=!0,t=!1){const n=this.backend,i=n.renderer.getCanvasTarget(),{width:s,height:o}=n.getDrawingBufferSize(),a=n.renderer.currentSamples,u=i.depthTexture;if(u.width===s&&u.height===o&&u.samples===a&&u.depth===e&&u.stencil===t)return n.get(u).texture;const l=n.get(u).texture;let c,h;if(t?(c=Ln,h=n.renderer.reversedDepthBuffer===!0?mt:or):e&&(c=Dn,h=n.renderer.reversedDepthBuffer===!0?mt:qe),l!==void 0){if(u.image.width===s&&u.image.height===o&&u.format===c&&u.type===h&&u.samples===a)return l;this.destroyTexture(u)}return u.name="depthBuffer",u.format=c,u.type=h,u.image.width=s,u.image.height=o,u.samples=a,this.createTexture(u,{width:s,height:o}),n.get(u).texture}updateTexture(e,t){const n=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:s}=n;if(!(e.isRenderTargetTexture||s===void 0)){if(e.isDataTexture)if(i.length>0)for(let o=0,a=i.length;o<a;o++){const u=i[o];this._copyBufferToTexture(u,n.texture,s,0,e.flipY,0,o)}else this._copyBufferToTexture(t.image,n.texture,s,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)if(e.layerUpdates&&e.layerUpdates.size>0){for(const o of e.layerUpdates)this._copyBufferToTexture(t.image,n.texture,s,o,e.flipY,o);e.clearLayerUpdates()}else for(let o=0;o<t.image.depth;o++)this._copyBufferToTexture(t.image,n.texture,s,o,e.flipY,o);else if(e.isCompressedTexture||e.isCompressedArrayTexture)e.isCompressedArrayTexture&&e.layerUpdates.size>0?(this._copyCompressedBufferToTexture(e.mipmaps,n.texture,s,e.layerUpdates),e.clearLayerUpdates()):this._copyCompressedBufferToTexture(e.mipmaps,n.texture,s);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,n.texture,s);else if(e.isHTMLTexture){const o=this.backend.device,a=this.backend.renderer.domElement,u=e.image;if(typeof o.queue.copyElementImageToTexture!="function")return;if(!n.hasPaintCallback){n.hasPaintCallback=!0,a.requestPaint();return}const l=s.size.width,c=s.size.height;o.queue.copyElementImageToTexture.length===2?o.queue.copyElementImageToTexture({source:u},{destination:{texture:n.texture},width:l,height:c}):o.queue.copyElementImageToTexture(u,l,c,{texture:n.texture}),e.flipY&&this._flipY(n.texture,s)}else if(i.length>0)for(let o=0,a=i.length;o<a;o++){const u=i[o];this._copyImageToTexture(u,n.texture,s,0,e.flipY,e.premultiplyAlpha,o)}else this._copyImageToTexture(t.image,n.texture,s,0,e.flipY,e.premultiplyAlpha);n.version=e.version}}async copyTextureToBuffer(e,t,n,i,s,o){const a=this.backend.device,u=this.backend.get(e),l=u.texture,c=u.textureDescriptorGPU.format,h=this._getBytesPerTexel(c);let d=i*h;d=Math.ceil(d/256)*256,wa.size=(s-1)*d+i*h,wa.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const f=a.createBuffer(wa);wa.reset();const p=a.createCommandEncoder(ZB);ft.texture=l,ft.origin.x=t,ft.origin.y=n,ft.origin.z=o,Ra.buffer=f,Ra.bytesPerRow=d,dt.width=i,dt.height=s,p.copyTextureToBuffer(ft,Ra,dt),ft.reset(),Ra.reset(),dt.reset();const g=this._getTypedArrayType(c);Mn(a,p.finish()),await f.mapAsync(GPUMapMode.READ);const _=f.getMappedRange().slice();return f.destroy(),new g(_)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const n=new od;n.minFilter=zt,n.magFilter=zt,this.createTexture(n,{width:1,height:1,format:e}),this.defaultTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(t===void 0){const n=new Gu;n.minFilter=zt,n.magFilter=zt,this.createTexture(n,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=n}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,n){const i=e.images,s=e.mipmaps;for(let o=0;o<6;o++){const a=i[o],u=e.flipY===!0?eF[o]:o;a.isDataTexture?this._copyBufferToTexture(a.image,t,n,u,e.flipY):this._copyImageToTexture(a,t,n,u,e.flipY,e.premultiplyAlpha);for(let l=0;l<s.length;l++){const h=s[l].images[o];h.isDataTexture?this._copyBufferToTexture(h.image,t,n,u,e.flipY,0,l+1):this._copyImageToTexture(h,t,n,u,e.flipY,e.premultiplyAlpha,l+1)}}}_copyImageToTexture(e,t,n,i,s,o,a=0){const u=this.backend.device,l=a>0?e.width:n.size.width,c=a>0?e.height:n.size.height;Aa.source=e,Aa.flipY=s,ki.texture=t,ki.mipLevel=a,ki.origin.z=i,ki.premultipliedAlpha=o,dt.width=l,dt.height=c;try{u.queue.copyExternalImageToTexture(Aa,ki,dt)}catch{}finally{Aa.reset(),ki.reset(),dt.reset()}}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new jB(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,i,s,o=0,a=0){const u=this.backend.device,l=e.data,c=this._getBytesPerTexel(n.format),h=e.width*c;ft.texture=t,ft.mipLevel=a,ft.origin.z=i,tr.offset=e.width*e.height*c*o,tr.bytesPerRow=h,dt.width=e.width,dt.height=e.height,u.queue.writeTexture(ft,l,tr,dt),ft.reset(),tr.reset(),dt.reset(),s===!0&&this._flipY(t,n,i)}_copyCompressedBufferToTexture(e,t,n,i=null){const s=this.backend.device,o=this._getBlockData(n.format),a=n.size.depthOrArrayLayers>1,u=i&&i.size>0?i:null;for(let l=0;l<e.length;l++){const c=e[l],h=c.width,d=c.height,f=a?n.size.depthOrArrayLayers:1,p=Math.ceil(h/o.width)*o.byteLength,g=Math.ceil(d/o.height),_=p*g,m=Math.ceil(h/o.width)*o.width,y=g*o.height;if(u!==null)for(const b of u)Dg(s,t,l,b,c,_,p,g,m,y);else for(let b=0;b<f;b++)Dg(s,t,l,b,c,_,p,g,m,y)}}_getBlockData(e){if(e===S.BC1RGBAUnorm||e===S.BC1RGBAUnormSRGB)return{byteLength:8,width:4,height:4};if(e===S.BC2RGBAUnorm||e===S.BC2RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===S.BC3RGBAUnorm||e===S.BC3RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===S.BC4RUnorm||e===S.BC4RSnorm)return{byteLength:8,width:4,height:4};if(e===S.BC5RGUnorm||e===S.BC5RGSnorm)return{byteLength:16,width:4,height:4};if(e===S.BC6HRGBUFloat||e===S.BC6HRGBFloat)return{byteLength:16,width:4,height:4};if(e===S.BC7RGBAUnorm||e===S.BC7RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===S.ETC2RGB8Unorm||e===S.ETC2RGB8UnormSRGB)return{byteLength:8,width:4,height:4};if(e===S.ETC2RGB8A1Unorm||e===S.ETC2RGB8A1UnormSRGB)return{byteLength:8,width:4,height:4};if(e===S.ETC2RGBA8Unorm||e===S.ETC2RGBA8UnormSRGB)return{byteLength:16,width:4,height:4};if(e===S.EACR11Unorm)return{byteLength:8,width:4,height:4};if(e===S.EACR11Snorm)return{byteLength:8,width:4,height:4};if(e===S.EACRG11Unorm)return{byteLength:16,width:4,height:4};if(e===S.EACRG11Snorm)return{byteLength:16,width:4,height:4};if(e===S.ASTC4x4Unorm||e===S.ASTC4x4UnormSRGB)return{byteLength:16,width:4,height:4};if(e===S.ASTC5x4Unorm||e===S.ASTC5x4UnormSRGB)return{byteLength:16,width:5,height:4};if(e===S.ASTC5x5Unorm||e===S.ASTC5x5UnormSRGB)return{byteLength:16,width:5,height:5};if(e===S.ASTC6x5Unorm||e===S.ASTC6x5UnormSRGB)return{byteLength:16,width:6,height:5};if(e===S.ASTC6x6Unorm||e===S.ASTC6x6UnormSRGB)return{byteLength:16,width:6,height:6};if(e===S.ASTC8x5Unorm||e===S.ASTC8x5UnormSRGB)return{byteLength:16,width:8,height:5};if(e===S.ASTC8x6Unorm||e===S.ASTC8x6UnormSRGB)return{byteLength:16,width:8,height:6};if(e===S.ASTC8x8Unorm||e===S.ASTC8x8UnormSRGB)return{byteLength:16,width:8,height:8};if(e===S.ASTC10x5Unorm||e===S.ASTC10x5UnormSRGB)return{byteLength:16,width:10,height:5};if(e===S.ASTC10x6Unorm||e===S.ASTC10x6UnormSRGB)return{byteLength:16,width:10,height:6};if(e===S.ASTC10x8Unorm||e===S.ASTC10x8UnormSRGB)return{byteLength:16,width:10,height:8};if(e===S.ASTC10x10Unorm||e===S.ASTC10x10UnormSRGB)return{byteLength:16,width:10,height:10};if(e===S.ASTC12x10Unorm||e===S.ASTC12x10UnormSRGB)return{byteLength:16,width:12,height:10};if(e===S.ASTC12x12Unorm||e===S.ASTC12x12UnormSRGB)return{byteLength:16,width:12,height:12}}_convertAddressMode(e){let t=uc.ClampToEdge;return e===Iu?t=uc.Repeat:e===Uu&&(t=uc.MirrorRepeat),t}_convertFilterMode(e){let t=Kt.Linear;return(e===zt||e===hm||e===is)&&(t=Kt.Nearest),t}_convertMipmapFilterMode(e){return e===is||e===Ir?Kt.Linear:Kt.Nearest}_getBytesPerTexel(e){if(e===S.R8Unorm||e===S.R8Snorm||e===S.R8Uint||e===S.R8Sint)return 1;if(e===S.R16Uint||e===S.R16Sint||e===S.R16Float||e===S.RG8Unorm||e===S.RG8Snorm||e===S.RG8Uint||e===S.RG8Sint||e===S.R16Unorm||e===S.R16Snorm)return 2;if(e===S.R32Uint||e===S.R32Sint||e===S.R32Float||e===S.RG16Uint||e===S.RG16Sint||e===S.RG16Float||e===S.RGBA8Unorm||e===S.RGBA8UnormSRGB||e===S.RGBA8Snorm||e===S.RGBA8Uint||e===S.RGBA8Sint||e===S.BGRA8Unorm||e===S.BGRA8UnormSRGB||e===S.RG16Unorm||e===S.RG16Snorm||e===S.RGB9E5UFloat||e===S.RGB10A2Unorm||e===S.RG11B10UFloat||e===S.Depth32Float||e===S.Depth24Plus||e===S.Depth24PlusStencil8||e===S.Depth32FloatStencil8)return 4;if(e===S.RG32Uint||e===S.RG32Sint||e===S.RG32Float||e===S.RGBA16Uint||e===S.RGBA16Sint||e===S.RGBA16Float||e===S.RGBA16Unorm||e===S.RGBA16Snorm)return 8;if(e===S.RGBA32Uint||e===S.RGBA32Sint||e===S.RGBA32Float)return 16}_getTypedArrayType(e){if(e===S.R8Uint)return Uint8Array;if(e===S.R8Sint)return Int8Array;if(e===S.R8Unorm)return Uint8Array;if(e===S.R8Snorm)return Int8Array;if(e===S.RG8Uint)return Uint8Array;if(e===S.RG8Sint)return Int8Array;if(e===S.RG8Unorm)return Uint8Array;if(e===S.RG8Snorm)return Int8Array;if(e===S.RGBA8Uint)return Uint8Array;if(e===S.RGBA8Sint)return Int8Array;if(e===S.RGBA8Unorm||e===S.RGBA8UnormSRGB)return Uint8Array;if(e===S.RGBA8Snorm)return Int8Array;if(e===S.R16Uint)return Uint16Array;if(e===S.R16Sint)return Int16Array;if(e===S.RG16Uint)return Uint16Array;if(e===S.RG16Sint)return Int16Array;if(e===S.RGBA16Uint)return Uint16Array;if(e===S.RGBA16Sint)return Int16Array;if(e===S.R16Float||e===S.RG16Float||e===S.RGBA16Float||e===S.R16Unorm)return Uint16Array;if(e===S.R16Snorm)return Int16Array;if(e===S.RG16Unorm)return Uint16Array;if(e===S.RG16Snorm)return Int16Array;if(e===S.RGBA16Unorm)return Uint16Array;if(e===S.RGBA16Snorm)return Int16Array;if(e===S.R32Uint)return Uint32Array;if(e===S.R32Sint)return Int32Array;if(e===S.R32Float)return Float32Array;if(e===S.RG32Uint)return Uint32Array;if(e===S.RG32Sint)return Int32Array;if(e===S.RG32Float)return Float32Array;if(e===S.RGBA32Uint)return Uint32Array;if(e===S.RGBA32Sint)return Int32Array;if(e===S.RGBA32Float)return Float32Array;if(e===S.BGRA8Unorm||e===S.BGRA8UnormSRGB)return Uint8Array;if(e===S.RGB10A2Unorm||e===S.RGB9E5UFloat||e===S.RG11B10UFloat)return Uint32Array;if(e===S.Depth32Float)return Float32Array;if(e===S.Depth24Plus||e===S.Depth24PlusStencil8)return Uint32Array;if(e===S.Depth32FloatStencil8)return Float32Array}_getDimension(e){let t;return e.is3DTexture||e.isData3DTexture?t=cc.ThreeD:t=cc.TwoD,t}}function Dh(r,e){const t=r.format,n=r.type,i=r.normalized,s=r.colorSpace,o=Ye.getTransfer(s);let a,u=!1;if(i&&(u=e.features.has(Nu.TextureFormatsTier1),u===!1&&Y("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),r.isCompressedTexture===!0||r.isCompressedArrayTexture===!0)switch(t){case Va:case $a:a=o===le?S.BC1RGBAUnormSRGB:S.BC1RGBAUnorm;break;case za:a=o===le?S.BC2RGBAUnormSRGB:S.BC2RGBAUnorm;break;case Wa:a=o===le?S.BC3RGBAUnormSRGB:S.BC3RGBAUnorm;break;case Qc:a=S.BC4RUnorm;break;case Zc:a=S.BC4RSnorm;break;case au:a=S.BC5RGUnorm;break;case Jc:a=S.BC5RGSnorm;break;case Xc:a=o===le?S.BC7RGBAUnormSRGB:S.BC7RGBAUnorm;break;case Kc:a=S.BC6HRGBFloat;break;case Yc:a=S.BC6HRGBUFloat;break;case Cc:case Ec:a=o===le?S.ETC2RGB8UnormSRGB:S.ETC2RGB8Unorm;break;case Mc:a=o===le?S.ETC2RGBA8UnormSRGB:S.ETC2RGBA8Unorm;break;case Pc:a=S.EACR11Unorm;break;case Bc:a=S.EACR11Snorm;break;case ou:a=S.EACRG11Unorm;break;case Fc:a=S.EACRG11Snorm;break;case Dc:a=o===le?S.ASTC4x4UnormSRGB:S.ASTC4x4Unorm;break;case Lc:a=o===le?S.ASTC5x4UnormSRGB:S.ASTC5x4Unorm;break;case Oc:a=o===le?S.ASTC5x5UnormSRGB:S.ASTC5x5Unorm;break;case Uc:a=o===le?S.ASTC6x5UnormSRGB:S.ASTC6x5Unorm;break;case Ic:a=o===le?S.ASTC6x6UnormSRGB:S.ASTC6x6Unorm;break;case kc:a=o===le?S.ASTC8x5UnormSRGB:S.ASTC8x5Unorm;break;case Gc:a=o===le?S.ASTC8x6UnormSRGB:S.ASTC8x6Unorm;break;case Vc:a=o===le?S.ASTC8x8UnormSRGB:S.ASTC8x8Unorm;break;case $c:a=o===le?S.ASTC10x5UnormSRGB:S.ASTC10x5Unorm;break;case zc:a=o===le?S.ASTC10x6UnormSRGB:S.ASTC10x6Unorm;break;case Wc:a=o===le?S.ASTC10x8UnormSRGB:S.ASTC10x8Unorm;break;case Hc:a=o===le?S.ASTC10x10UnormSRGB:S.ASTC10x10Unorm;break;case jc:a=o===le?S.ASTC12x10UnormSRGB:S.ASTC12x10Unorm;break;case qc:a=o===le?S.ASTC12x12UnormSRGB:S.ASTC12x12Unorm;break;case Qt:a=o===le?S.RGBA8UnormSRGB:S.RGBA8Unorm;break;default:V("WebGPURenderer: Unsupported texture format.",t)}else switch(t){case Qt:switch(n){case Yi:a=S.RGBA8Snorm;break;case Ur:a=u?S.RGBA16Snorm:S.RGBA16Sint;break;case rr:a=u?S.RGBA16Unorm:S.RGBA16Uint;break;case qe:a=S.RGBA32Uint;break;case gt:a=S.RGBA32Sint;break;case Pt:a=o===le?S.RGBA8UnormSRGB:S.RGBA8Unorm;break;case wt:a=S.RGBA16Float;break;case mt:a=S.RGBA32Float;break;default:V("WebGPURenderer: Unsupported texture type with RGBAFormat.",n)}break;case Bo:switch(n){case Jh:a=S.RGB9E5UFloat;break;case ed:a=S.RG11B10UFloat;break;default:V("WebGPURenderer: Unsupported texture type with RGBFormat.",n)}break;case Co:switch(n){case Yi:a=S.R8Snorm;break;case Ur:a=u?S.R16Snorm:S.R16Sint;break;case rr:a=u?S.R16Unorm:S.R16Uint;break;case qe:a=S.R32Uint;break;case gt:a=S.R32Sint;break;case Pt:a=S.R8Unorm;break;case wt:a=S.R16Float;break;case mt:a=S.R32Float;break;default:V("WebGPURenderer: Unsupported texture type with RedFormat.",n)}break;case pn:switch(n){case Yi:a=S.RG8Snorm;break;case Ur:a=u?S.RG16Snorm:S.RG16Sint;break;case rr:a=u?S.RG16Unorm:S.RG16Uint;break;case qe:a=S.RG32Uint;break;case gt:a=S.RG32Sint;break;case Pt:a=S.RG8Unorm;break;case wt:a=S.RG16Float;break;case mt:a=S.RG32Float;break;default:V("WebGPURenderer: Unsupported texture type with RGFormat.",n)}break;case Dn:switch(n){case rr:a=S.Depth16Unorm;break;case qe:a=S.Depth24Plus;break;case mt:a=S.Depth32Float;break;default:V("WebGPURenderer: Unsupported texture type with DepthFormat.",n)}break;case Ln:switch(n){case or:a=S.Depth24PlusStencil8;break;case mt:e&&e.features.has(Nu.Depth32FloatStencil8)===!1&&V('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),a=S.Depth32FloatStencil8;break;default:V("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",n)}break;case Mo:switch(n){case gt:a=S.R32Sint;break;case qe:a=S.R32Uint;break;default:V("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",n)}break;case Po:switch(n){case gt:a=S.RG32Sint;break;case qe:a=S.RG32Uint;break;default:V("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",n)}break;case sd:switch(n){case gt:a=S.RGBA32Sint;break;case qe:a=S.RGBA32Uint;break;default:V("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",n)}break;default:V("WebGPURenderer: Unsupported texture format.",t)}return a}const nF=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,rF=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig,Lg={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",sampler_comparison:"samplerComparison",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"},iF=r=>{r=r.replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,"");const e=r.match(nF);if(e!==null&&e.length===4){const t=e[2],n=[];let i=null;for(;(i=rF.exec(t))!==null;)n.push({name:i[1],type:i[2]});const s=[];for(let c=0;c<n.length;c++){const{name:h,type:d}=n[c];let f=d;f.startsWith("ptr")?f="pointer":(f.startsWith("texture")&&(f=d.split("<")[0]),f=Lg[f]),s.push(new zd(f,h))}const o=r.substring(e[0].length),a=e[3]||"void",u=e[1]!==void 0?e[1]:"";return{type:Lg[a]||a,inputs:s,name:u,inputsCode:t,blockCode:o,outputType:a}}else throw new Error("THREE.WGSLNodeFunction: Function is not a WGSL code.")};class sF extends Hd{constructor(e){const{type:t,inputs:n,name:i,inputsCode:s,blockCode:o,outputType:a}=iF(e);super(t,n,i),this.inputsCode=s,this.blockCode=o,this.outputType=a}getCode(e=this.name){const t=this.outputType!=="void"?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class oF extends Rb{parseFunction(e){return new sF(e)}}const aF={[Wt.READ_ONLY]:"read",[Wt.WRITE_ONLY]:"write",[Wt.READ_WRITE]:"read_write"},Og={[Iu]:"repeat",[xo]:"clamp",[Uu]:"mirror"},pc={vertex:_n.VERTEX,fragment:_n.FRAGMENT,compute:_n.COMPUTE},Ug={instance:!0,swizzleAssign:!1,storageBuffer:!0},uF={"^^":"tsl_xor"},lF={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},Ig={},Hs={tsl_xor:new we("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new we("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new we("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new we("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new we("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new we("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new we("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new we("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new we("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new we("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new we("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new we("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),inverse_mat2:new we(`
825
+ fn tsl_inverse_mat2( m : mat2x2<f32> ) -> mat2x2<f32> {
826
+
827
+ let det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];
828
+
829
+ return mat2x2<f32>(
830
+ m[ 1 ][ 1 ], - m[ 0 ][ 1 ],
831
+ - m[ 1 ][ 0 ], m[ 0 ][ 0 ]
832
+ ) * ( 1.0 / det );
833
+
834
+ }
835
+ `),inverse_mat3:new we(`
836
+ fn tsl_inverse_mat3( m : mat3x3<f32> ) -> mat3x3<f32> {
837
+
838
+ let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ];
839
+ let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ];
840
+ let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ];
841
+
842
+ let b01 = a22 * a11 - a12 * a21;
843
+ let b11 = - a22 * a10 + a12 * a20;
844
+ let b21 = a21 * a10 - a11 * a20;
845
+
846
+ let det = a00 * b01 + a01 * b11 + a02 * b21;
847
+
848
+ return mat3x3<f32>(
849
+ b01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ),
850
+ b11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ),
851
+ b21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 )
852
+ ) * ( 1.0 / det );
853
+
854
+ }
855
+ `),inverse_mat4:new we(`
856
+ fn tsl_inverse_mat4( m : mat4x4<f32> ) -> mat4x4<f32> {
857
+
858
+ let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ];
859
+ let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ];
860
+ let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ];
861
+ let a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ];
862
+
863
+ let b00 = a00 * a11 - a01 * a10;
864
+ let b01 = a00 * a12 - a02 * a10;
865
+ let b02 = a00 * a13 - a03 * a10;
866
+ let b03 = a01 * a12 - a02 * a11;
867
+ let b04 = a01 * a13 - a03 * a11;
868
+ let b05 = a02 * a13 - a03 * a12;
869
+ let b06 = a20 * a31 - a21 * a30;
870
+ let b07 = a20 * a32 - a22 * a30;
871
+ let b08 = a20 * a33 - a23 * a30;
872
+ let b09 = a21 * a32 - a22 * a31;
873
+ let b10 = a21 * a33 - a23 * a31;
874
+ let b11 = a22 * a33 - a23 * a32;
875
+
876
+ let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
877
+
878
+ return mat4x4<f32>(
879
+ a11 * b11 - a12 * b10 + a13 * b09,
880
+ a02 * b10 - a01 * b11 - a03 * b09,
881
+ a31 * b05 - a32 * b04 + a33 * b03,
882
+ a22 * b04 - a21 * b05 - a23 * b03,
883
+ a12 * b08 - a10 * b11 - a13 * b07,
884
+ a00 * b11 - a02 * b08 + a03 * b07,
885
+ a32 * b02 - a30 * b05 - a33 * b01,
886
+ a20 * b05 - a22 * b02 + a23 * b01,
887
+ a10 * b10 - a11 * b08 + a13 * b06,
888
+ a01 * b08 - a00 * b10 - a03 * b06,
889
+ a30 * b04 - a31 * b02 + a33 * b00,
890
+ a21 * b02 - a20 * b04 - a23 * b00,
891
+ a11 * b07 - a10 * b09 - a12 * b06,
892
+ a00 * b09 - a01 * b07 + a02 * b06,
893
+ a31 * b01 - a30 * b03 - a32 * b00,
894
+ a20 * b03 - a21 * b01 + a22 * b00
895
+ ) * ( 1.0 / det );
896
+
897
+ }
898
+ `),biquadraticTexture:new we(`
899
+ fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
900
+
901
+ let res = vec2f( iRes );
902
+
903
+ let uvScaled = coord * res;
904
+ let uvWrapping = ( ( uvScaled % res ) + res ) % res;
905
+
906
+ // https://www.shadertoy.com/view/WtyXRy
907
+
908
+ let uv = uvWrapping - 0.5;
909
+ let iuv = floor( uv );
910
+ let f = fract( uv );
911
+
912
+ let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
913
+ let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
914
+ let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
915
+ let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
916
+
917
+ return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
918
+
919
+ }
920
+ `),biquadraticTextureArray:new we(`
921
+ fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
922
+
923
+ let res = vec2f( iRes );
924
+
925
+ let uvScaled = coord * res;
926
+ let uvWrapping = ( ( uvScaled % res ) + res ) % res;
927
+
928
+ // https://www.shadertoy.com/view/WtyXRy
929
+
930
+ let uv = uvWrapping - 0.5;
931
+ let iuv = floor( uv );
932
+ let f = fract( uv );
933
+
934
+ let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
935
+ let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
936
+ let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
937
+ let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
938
+
939
+ return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
940
+
941
+ }
942
+ `)},cF={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inverse_mat2:"tsl_inverse_mat2",inverse_mat3:"tsl_inverse_mat3",inverse_mat4:"tsl_inverse_mat4",inversesqrt:"inverseSqrt",faceforward:"faceForward",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatpack_snorm_4x8:"pack4x8snorm",floatpack_unorm_4x8:"pack4x8unorm",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float",floatunpack_snorm_4x8:"unpack4x8snorm",floatunpack_unorm_4x8:"unpack4x8unorm"},hF=new Set(["alias","break","case","const","const_assert","continue","continuing","default","diagnostic","discard","else","enable","false","fn","for","if","let","loop","override","requires","return","struct","switch","true","var","while","NULL","Self","abstract","active","alignas","alignof","as","asm","asm_fragment","async","attribute","auto","await","become","binding_array","cast","catch","class","co_await","co_return","co_yield","coherent","column_major","common","compile","compile_fragment","concept","const_cast","consteval","constexpr","constinit","crate","debugger","decltype","delete","demote","demote_to_helper","do","dynamic_cast","enum","explicit","export","extends","extern","external","fallthrough","filter","final","finally","friend","from","fxgroup","get","goto","groupshared","highp","impl","implements","import","inline","instanceof","interface","layout","lowp","macro","macro_rules","match","mediump","meta","mod","module","move","mut","mutable","namespace","new","nil","noexcept","noinline","nointerpolation","non_coherent","noncoherent","noperspective","null","nullptr","of","operator","package","packoffset","partition","pass","patch","pixelfragment","precise","precision","premerge","priv","protected","pub","public","readonly","ref","regardless","register","reinterpret_cast","require","resource","restrict","self","set","shared","sizeof","smooth","snorm","static","static_assert","static_cast","std","subroutine","super","target","template","this","thread_local","throw","trait","try","type","typedef","typeid","typename","typeof","union","unless","unorm","unsafe","unsized","use","using","varying","virtual","volatile","wgsl","where","with","writeonly","yield","main"]);let $b="";(typeof navigator<"u"&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&($b+=`diagnostic( off, derivative_uniformity );
943
+ `);class dF extends wb{constructor(e,t){super(e,t,new oF),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,n,i,s,o=this.shaderStage){return o==="fragment"?i?s?`textureSample( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:s?`textureSample( ${t}, ${t}_sampler, ${n}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,"0",i)}generateTextureSampleLevel(e,t,n,i,s,o){return this.isUnfilterable(e)===!1?s?o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,o,i,s):this.generateTextureLod(e,t,n,s,o,i)}generateWrapFunction(e){const t=`tsl_coord_${Og[e.wrapS]}S_${Og[e.wrapT]}T_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}`;let n=Ig[t];if(n===void 0){const i=[],s=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let o=`fn ${t}( coord : ${s} ) -> ${s} {
944
+
945
+ return ${s}(
946
+ `;const a=(u,l)=>{u===Iu?(i.push(Hs.repeatWrapping_float),o+=` tsl_repeatWrapping_float( coord.${l} )`):u===xo?(i.push(Hs.clampWrapping_float),o+=` tsl_clampWrapping_float( coord.${l} )`):u===Uu?(i.push(Hs.mirrorWrapping_float),o+=` tsl_mirrorWrapping_float( coord.${l} )`):(o+=` coord.${l}`,Y(`WebGPURenderer: Unsupported texture wrap type "${u}" for vertex shader.`))};a(e.wrapS,"x"),o+=`,
947
+ `,a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(o+=`,
948
+ `,a(e.wrapR,"z")),o+=`
949
+ );
950
+
951
+ }
952
+ `,Ig[t]=n=new we(o,i)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const i=this.getDataFromNode(e,this.shaderStage,this.cache);i.dimensionsSnippet===void 0&&(i.dimensionsSnippet={});let s=i.dimensionsSnippet[n];if(i.dimensionsSnippet[n]===void 0){let o,a;const{primarySamples:u}=this.renderer.backend.utils.getTextureSampleData(e),l=u>1;e.is3DTexture||e.isData3DTexture?a="vec3<u32>":a="vec2<u32>",l||e.isStorageTexture?o=t:o=`${t}${n?`, u32( ${n} )`:""}`,s=new Ka(new Ya(`textureDimensions( ${o} )`,a)),i.dimensionsSnippet[n]=s,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Ka(new Ya(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Ka(new Ya("6u","u32")))}return s.build(this)}generateTextureSize(e,t,n){const{primarySamples:i}=this.renderer.backend.utils.getTextureSampleData(e);return`textureDimensions( ${i>1||e.isStorageTexture?t:`${t}, ${n}`} )`}generateFilteredTexture(e,t,n,i,s="0u",o){const a=this.generateWrapFunction(e),u=this.generateTextureDimension(e,t,s);return i&&(n=`${n} + vec2<f32>(${i}) / ${u}`),o?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${n} ), ${u}, u32( ${o} ), u32( ${s} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${n} ), ${u}, u32( ${s} ) )`)}generateTextureLod(e,t,n,i,s,o="0u"){if(e.isCubeTexture===!0){s&&(n=`${n} + vec3<f32>(${s})`);const f=e.isDepthTexture?"u32":"f32";return`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${f}( ${o} ) )`}const a=this.generateWrapFunction(e),u=this.generateTextureDimension(e,t,o),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",c=l==="vec3"?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )";s&&(n=`${n} + ${l}<f32>(${s}) / ${l}<f32>( ${u} )`);const h=`${l}<f32>( 0 )`,d=`${l}<f32>( ${u} - ${c} )`;return n=`${l}<u32>( clamp( floor( ${a}( ${n} ) * ${l}<f32>( ${u} ) ), ${h}, ${d} ) )`,this.generateTextureLoad(e,t,n,o,i,null)}generateStorageTextureLoad(e,t,n,i,s,o){o&&(n=`${n} + ${o}`);let a;return s?a=`textureLoad( ${t}, ${n}, ${s} )`:a=`textureLoad( ${t}, ${n} )`,a}generateTextureLoad(e,t,n,i,s,o){i===null&&(i="0u"),o&&(n=`${n} + ${o}`);let a;return s?a=`textureLoad( ${t}, ${n}, ${s}, u32( ${i} ) )`:(a=`textureLoad( ${t}, ${n}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,n,i,s){let o;return i?o=`textureStore( ${t}, ${n}, ${i}, ${s} )`:o=`textureStore( ${t}, ${n}, ${s} )`,o}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null&&this.renderer.hasCompatibility(Si.TEXTURE_COMPARE)}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!=="float"||!this.isAvailable("float32Filterable")&&e.type===mt||this.isSampleCompare(e)===!1&&e.minFilter===zt&&e.magFilter===zt||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1||e.normalized===!0&&(e.type===Ur||e.type===rr)}generateTexture(e,t,n,i,s,o=this.shaderStage){let a=null;return this.isUnfilterable(e)?a=this.generateTextureLod(e,t,n,i,s,"0",o):a=this._generateTextureSample(e,t,n,i,s,o),a}generateTextureGrad(e,t,n,i,s,o,a=this.shaderStage){if(a==="fragment")return s?o?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${s}, ${i[0]}, ${i[1]}, ${o} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${s}, ${i[0]}, ${i[1]} )`:o?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]}, ${o} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]} )`;V(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,n,i,s,o,a=this.shaderStage){if(a==="fragment")return e.isDepthTexture===!0&&e.isArrayTexture===!0?o?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${o} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:o?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${o} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`;V(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,n,i,s,o){const a=e.isDepthTexture===!0?"":`${i}, `;return s?o?`textureGather( ${a}${t}, ${t}_sampler, ${n}, ${s}, ${o} )`:`textureGather( ${a}${t}, ${t}_sampler, ${n}, ${s} )`:o?`textureGather( ${a}${t}, ${t}_sampler, ${n}, ${o} )`:`textureGather( ${a}${t}, ${t}_sampler, ${n})`}generateTextureGatherCompare(e,t,n,i,s,o){return s?o?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${o} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i})`:o?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${o} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i})`}generateTextureLevel(e,t,n,i,s,o){return this.isUnfilterable(e)===!1?s?o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,o,i,s):this.generateTextureLod(e,t,n,s,o,i)}generateTextureBias(e,t,n,i,s,o,a=this.shaderStage){if(a==="fragment")return s?o?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${o} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:o?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${o} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i} )`;V(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(e.isNodeVarying===!0&&e.needsInterpolation===!0){if(t==="vertex")return`varyings.${e.name}`}else if(e.isNodeUniform===!0){const n=e.name,i=e.type;return i==="texture"||i==="cubeTexture"||i==="cubeDepthTexture"||i==="storageTexture"||i==="texture3D"?n:i==="buffer"||i==="storageBuffer"||i==="indirectStorageBuffer"?this.isCustomStruct(e)?n:n+".value":e.groupNode.name+"."+n}return super.getPropertyName(e)}isReservedKeyword(e){return hF.has(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=uF[e];return t!==void 0?(this._include(t),t):null}getNodeAccess(e,t){return t!=="compute"?e.isAtomic===!0?t==="vertex"?(Y("WebGPURenderer: Atomic operations are not supported in the vertex stage. They are only available in the fragment and compute stages."),Wt.READ_ONLY):Wt.READ_WRITE:Wt.READ_ONLY:e.access}getStorageAccess(e,t){return aF[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,i=null){const s=super.getUniformFromNode(e,t,n,i),o=this.getDataFromNode(e,n,this.globalCache);if(o.uniformGPU===void 0){let a;const u=e.groupNode,l=u.name,c=this.getBindGroupArray(l,n);if(t==="texture"||t==="cubeTexture"||t==="cubeDepthTexture"||t==="storageTexture"||t==="texture3D"){let h=null;const d=this.getNodeAccess(e,n);if(t==="texture"||t==="storageTexture"?e.value.is3DTexture===!0?h=new Fh(s.name,s.node,u,d):h=new tl(s.name,s.node,u,d):t==="cubeTexture"||t==="cubeDepthTexture"?h=new Db(s.name,s.node,u,d):t==="texture3D"&&(h=new Fh(s.name,s.node,u,d)),h.store=e.isStorageTextureNode===!0,h.mipLevel=h.store?e.mipLevel:0,h.setVisibility(pc[n]),e.value.isCubeTexture===!0||this.isUnfilterable(e.value)===!1&&h.store===!1||e.gatherNode!==null){const p=new GB(`${s.name}_sampler`,s.node,u);p.setVisibility(pc[n]),c.push(p,h),a=[p,h]}else c.push(h),a=[h]}else if(t==="buffer"||t==="storageBuffer"||t==="indirectStorageBuffer"){const h=this.getSharedDataFromNode(e);let d=h.buffer;if(d===void 0){const f=t==="buffer"?Pb:zB;d=new f(e,u),h.buffer=d}d.setVisibility(d.getVisibility()|pc[n]),c.push(d),a=d,s.name=i||"NodeBuffer_"+s.id}else{let h=this.uniformGroups[l];h===void 0&&(h=new Bb(l,u),h.setVisibility(_n.VERTEX|_n.FRAGMENT|_n.COMPUTE),this.uniformGroups[l]=h),c.indexOf(h)===-1&&c.push(h),a=this.getNodeUniform(s,t);const d=a.name;h.uniforms.some(p=>p.name===d)||h.addUniform(a)}o.uniformGPU=a}return s}getBuiltin(e,t,n,i=this.shaderStage){const s=this.builtins[i]||(this.builtins[i]=new Map);return s.has(e)===!1&&s.set(e,{name:e,property:t,type:n}),t}hasBuiltin(e,t=this.shaderStage){return this.builtins[t]!==void 0&&this.builtins[t].has(e)}getVertexIndex(){return this.shaderStage==="vertex"?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const o of t.inputs)i.push(o.name+" : "+this.getType(o.type));let s=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {
953
+ ${n.vars}
954
+ ${n.code}
955
+ `;return n.result&&(s+=` return ${n.result};
956
+ `),s+=`
957
+ }
958
+ `,s}getInstanceIndex(){return this.shaderStage==="vertex"?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],n=this.directives[e];if(n!==void 0)for(const i of n)t.push(`enable ${i};`);return t.join(`
959
+ `)}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],n=this.builtins[e];if(n!==void 0)for(const{name:i,property:s,type:o}of n.values())t.push(`@builtin( ${i} ) ${s} : ${o}`);return t.join(`,
960
+ `)}getScopedArray(e,t,n,i,s){return this.scopedArrays.has(e)===!1&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:i,isAtomic:s}),e}getScopedArrays(e){if(e!=="compute")return;const t=[];for(const{name:n,scope:i,bufferType:s,bufferCount:o,isAtomic:a}of this.scopedArrays.values()){let u=this.getType(s);a===!0&&(u=`atomic<${u}>`),t.push(`var<${i}> ${n}: array< ${u}, ${o} >;`)}return t.join(`
961
+ `)}getAttributes(e){const t=[];if(e==="compute"&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),e==="vertex"||e==="compute"){const n=this.getBuiltins("attribute");n&&t.push(n);const i=this.getAttributesArray();for(let s=0,o=i.length;s<o;s++){const a=i[s],u=a.name,l=this.getType(a.type);t.push(`@location( ${s} ) ${u} : ${l}`)}}return t.join(`,
962
+ `)}getStructMembers(e){const t=[];for(const n of e.members){const i=e.output?"@location( "+n.index+" ) ":"";let s=this.getType(n.type);n.atomic&&(s="atomic< "+s+" >"),t.push(` ${i+n.name} : ${s}`)}return e.output&&t.push(` ${this.getBuiltins("output")}`),t.join(`,
963
+ `)}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const i=[];for(const s of n){let o=`struct ${s.name} {
964
+ `;o+=this.getStructMembers(s),o+=`
965
+ };`,i.push(o)}t=`
966
+ `+i.join(`
967
+
968
+ `)+`
969
+ `}return t}getVar(e,t,n=null,i=""){let s=`var${i} ${t} : `;return n!==null?s+=this.generateArrayDeclaration(e,n):s+=this.getType(e),s}getVars(e,t=!1){let n="";t&&(n="<private>");const i=[],s=this.vars[e];if(s!==void 0)for(const o of s)i.push(`${this.getVar(o.type,o.name,o.count,n)};`);return t?i.join(`
970
+ `):`
971
+ ${i.join(`
972
+ `)}
973
+ `}getVaryings(e){const t=[];if(e==="vertex"&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),e==="vertex"||e==="fragment"){const s=this.varyings,o=this.vars[e];let a=0;for(let u=0;u<s.length;u++){const l=s[u];if(l.needsInterpolation){let c=`@location( ${a++} )`;if(l.interpolationType){const h=l.interpolationSampling!==null?`, ${l.interpolationSampling} )`:" )";c+=` @interpolate( ${l.interpolationType}${h}`}else/^(int|uint|ivec|uvec)/.test(l.type)&&(c+=" @interpolate(flat, either)");t.push(`${c} ${l.name} : ${this.getType(l.type)}`)}else e==="vertex"&&o.includes(l)===!1&&o.push(l)}}const n=this.getBuiltins(e);n&&t.push(n);const i=t.join(`,
974
+ `);return e==="vertex"?this._getWGSLStruct("VaryingsStruct"," "+i):i}isCustomStruct(e){const t=e.value,n=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&n.structTypeNode!==null,s=n.value&&n.value.array&&typeof n.value.itemSize=="number"&&n.value.array.length>n.value.itemSize;return i&&!s}getUniforms(e){const t=this.renderer.backend,n=this.uniforms[e],i=[],s=[],o=[],a={};for(const l of n){const c=l.groupNode.name,h=this.bindingsIndexes[c];if(l.type==="texture"||l.type==="cubeTexture"||l.type==="cubeDepthTexture"||l.type==="storageTexture"||l.type==="texture3D"){const d=l.node,f=d.value;(f.isCubeTexture===!0||this.isUnfilterable(f)===!1&&d.isStorageTextureNode!==!0||d.gatherNode!==null)&&(this.isSampleCompare(f)&&d.isSampleCompare()?i.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name}_sampler : sampler_comparison;`):i.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name}_sampler : sampler;`));let g,_="";const{primarySamples:m}=t.utils.getTextureSampleData(f);if(m>1&&(_="_multisampled"),f.isCubeTexture===!0&&f.isDepthTexture===!0)g="texture_depth_cube";else if(f.isCubeTexture===!0)g="texture_cube<f32>";else if(f.isDepthTexture===!0)t.compatibilityMode&&f.compareFunction===null?g=`texture${_}_2d<f32>`:g=`texture_depth${_}_2d${f.isArrayTexture===!0?"_array":""}`;else if(l.node.isStorageTextureNode===!0){const y=Dh(f,t.device),b=this.getStorageAccess(l.node,e),T=l.node.value.is3DTexture,x=l.node.value.isArrayTexture;g=`texture_storage_${T?"3d":`2d${x?"_array":""}`}<${y}, ${b}>`}else if(f.isArrayTexture===!0||f.isDataArrayTexture===!0||f.isCompressedArrayTexture===!0)g=`texture_2d_array<${this.getComponentTypeFromTexture(f).charAt(0)}32>`;else if(f.is3DTexture===!0||f.isData3DTexture===!0)g=`texture_3d<${this.getComponentTypeFromTexture(f).charAt(0)}32>`;else{const y=this.getComponentTypeFromTexture(f).charAt(0);g=`texture${_}_2d<${y}32>`}i.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${l.name} : ${g};`)}else if(l.type==="buffer"||l.type==="storageBuffer"||l.type==="indirectStorageBuffer"){const d=l.node,f=this.getType(d.getNodeType(this)),p=d.bufferCount,g=p>0&&l.type==="buffer"?", "+p:"",_=d.isStorageBufferNode?`storage, ${this.getStorageAccess(d,e)}`:"uniform";if(this.isCustomStruct(l))s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var<${_}> ${l.name} : ${f};`);else{const y=` value : array< ${d.isAtomic?`atomic<${f}>`:`${f}`}${g} >`;s.push(this._getWGSLStructBinding(l.name,y,_,h.binding++,h.group))}}else{const d=l.groupNode.name;if(a[d]===void 0){const f=this.uniformGroups[d];if(f!==void 0){const p=[];for(const _ of f.uniforms){const m=_.getType(),y=this.getType(this.getVectorType(m));p.push(` ${_.name} : ${y}`)}let g=this.uniformGroupsBindings[d];g===void 0&&(g={index:h.binding++,id:h.group},this.uniformGroupsBindings[d]=g),a[d]={index:g.index,id:g.id,snippets:p}}}}}for(const l in a){const c=a[l];o.push(this._getWGSLStructBinding(l,c.snippets.join(`,
975
+ `),"uniform",c.index,c.id))}return[...i,...s,...o].join(`
976
+ `)}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=this.allowGlobalVariables,i=e[t];i.uniforms=this.getUniforms(t),i.attributes=this.getAttributes(t),i.varyings=this.getVaryings(t),i.structs=this.getStructs(t),i.vars=this.getVars(t,n),i.codes=this.getCodes(t),i.directives=this.getDirectives(t),i.scopedArrays=this.getScopedArrays(t);let s=`// code
977
+
978
+ `;s+=this.flowCode[t];const o=this.flowNodes[t],a=o[o.length-1],u=a.outputNode,l=u!==void 0&&u.isOutputStructNode===!0;for(const c of o){const h=this.getFlowData(c),d=c.name;if(d&&(s.length>0&&(s+=`
979
+ `),s+=` // flow -> ${d}
980
+ `),s+=`${h.code}
981
+ `,c===a&&t!=="compute"){if(s+=`// result
982
+
983
+ `,t==="vertex")s+=`varyings.builtinClipSpace = ${h.result};`;else if(t==="fragment")if(l)i.returnType=u.getNodeType(this),i.structs+="var<private> output : "+i.returnType+";",s+=`return ${h.result};`;else{let f=` @location( 0 ) color: ${this.getType(this.getOutputType())}`;const p=this.getBuiltins("output");p&&(f+=`,
984
+ `+p),i.returnType="OutputStruct",i.structs+=this._getWGSLStruct("OutputStruct",f),i.structs+=`
985
+ var<private> output : OutputStruct;`,s+=`output.color = ${this.format(h.result,a.getNodeType(this),this.getOutputType())};
986
+
987
+ return output;`}}}i.flow=s}if(this.shaderStage=null,this.material!==null)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.compute.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let n;return t!==null&&(n=this._getWGSLMethod(e+"_"+t)),n===void 0&&(n=this._getWGSLMethod(e)),n||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e,t="2x16"){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t="2x16"){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,n){return`select( ${n}, ${t}, ${e} )`}getType(e){return lF[e]||e}isAvailable(e){let t=Ug[e];return t===void 0&&(e==="float32Filterable"?t=this.renderer.hasFeature("float32-filterable"):e==="clipDistance"&&(t=this.renderer.hasFeature("clip-distances")),Ug[e]=t),t}_getWGSLMethod(e){return Hs[e]!==void 0&&this._include(e),cF[e]}_include(e){const t=Hs[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}
988
+ // directives
989
+ ${e.directives}
990
+
991
+ // structs
992
+ ${e.structs}
993
+
994
+ // uniforms
995
+ ${e.uniforms}
996
+
997
+ // varyings
998
+ ${e.varyings}
999
+ var<private> varyings : VaryingsStruct;
1000
+
1001
+ // vars
1002
+ ${e.vars}
1003
+
1004
+ // codes
1005
+ ${e.codes}
1006
+
1007
+ @vertex
1008
+ fn main( ${e.attributes} ) -> VaryingsStruct {
1009
+
1010
+ // flow
1011
+ ${e.flow}
1012
+
1013
+ return varyings;
1014
+
1015
+ }
1016
+ `}_getWGSLFragmentCode(e){return`${this.getSignature()}
1017
+ // global
1018
+ ${$b}
1019
+
1020
+ // structs
1021
+ ${e.structs}
1022
+
1023
+ // uniforms
1024
+ ${e.uniforms}
1025
+
1026
+ // vars
1027
+ ${e.vars}
1028
+
1029
+ // codes
1030
+ ${e.codes}
1031
+
1032
+ @fragment
1033
+ fn main( ${e.varyings} ) -> ${e.returnType} {
1034
+
1035
+ // flow
1036
+ ${e.flow}
1037
+
1038
+ }
1039
+ `}_getWGSLComputeCode(e,t){const[n,i,s]=t;return`${this.getSignature()}
1040
+ // directives
1041
+ ${e.directives}
1042
+
1043
+ // system
1044
+ var<private> instanceIndex : u32;
1045
+
1046
+ // locals
1047
+ ${e.scopedArrays}
1048
+
1049
+ // structs
1050
+ ${e.structs}
1051
+
1052
+ // uniforms
1053
+ ${e.uniforms}
1054
+
1055
+ // vars
1056
+ ${this.allowGlobalVariables?e.vars:""}
1057
+
1058
+ // codes
1059
+ ${e.codes}
1060
+
1061
+ @compute @workgroup_size( ${n}, ${i}, ${s} )
1062
+ fn main( ${e.attributes} ) {
1063
+
1064
+ // local vars
1065
+ ${this.allowGlobalVariables?"":e.vars}
1066
+
1067
+ // system
1068
+ instanceIndex = globalId.x
1069
+ + globalId.y * ( ${n} * numWorkgroups.x )
1070
+ + globalId.z * ( ${n} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );
1071
+
1072
+ // flow
1073
+ ${e.flow}
1074
+
1075
+ }
1076
+ `}_getWGSLStruct(e,t){return`
1077
+ struct ${e} {
1078
+ ${t}
1079
+ };`}_getWGSLStructBinding(e,t,n,i=0,s=0){const o=e+"Struct";return`${this._getWGSLStruct(o,t)}
1080
+ @binding( ${i} ) @group( ${s} )
1081
+ var<${n}> ${e} : ${o};`}}const ht=new Ts,gc=new Go,zb=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32"]],[Uint32Array,["uint32"]],[Float32Array,["float32"]]]);typeof Float16Array<"u"&&zb.set(Float16Array,["float16"]);const fF=new Map([[Wm,["float16"]]]),pF=new Map([[Int32Array,"sint32"],[Uint32Array,"uint32"],[Float32Array,"float32"]]);class gF{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),i=this.backend,s=i.get(n);let o=s.buffer;if(o===void 0){const a=i.device;let u=n.array;if(e.normalized===!1&&e.isInterleavedBufferAttribute!==!0){if(u.constructor===Int16Array||u.constructor===Int8Array)u=new Int32Array(u);else if((u.constructor===Uint16Array||u.constructor===Uint8Array)&&(u=new Uint32Array(u),t&GPUBufferUsage.INDEX))for(let d=0;d<u.length;d++)u[d]===65535&&(u[d]=4294967295)}n.array=u;let l;if((n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&n.itemSize===3)l=4;else if(n.itemSize>1&&n.itemSize*u.BYTES_PER_ELEMENT%4!==0){const d=n.itemSize*u.BYTES_PER_ELEMENT;l=Math.floor((d+3)/4)*4/u.BYTES_PER_ELEMENT}if(l!==void 0){const d=n.itemSize,f=new u.constructor(n.count*l);for(let p=0;p<n.count;p++)f.set(u.subarray(p*d,p*d+d),p*l);(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&(n.itemSize=l,n.array=f),u=f,s._itemSize=d,s._paddedItemSize=l}const c=u.byteLength,h=c+(4-c%4)%4;ht.label=n.name,ht.size=h,ht.usage=t,ht.mappedAtCreation=!0,o=a.createBuffer(ht),ht.reset(),new u.constructor(o.getMappedRange()).set(u),o.unmap(),s.buffer=o}}updateAttribute(e){const t=this._getBufferAttribute(e),n=this.backend,i=n.device,s=n.get(t),o=n.get(t).buffer;let a=t.array;const u=s._itemSize,l=s._paddedItemSize;if(l!==void 0){a=new a.constructor(t.count*l);for(let h=0;h<t.count;h++)a.set(t.array.subarray(h*u,h*u+u),h*l);(t.isStorageBufferAttribute||t.isStorageInstancedBufferAttribute)&&(t.array=a)}const c=t.updateRanges;if(c.length===0)i.queue.writeBuffer(o,0,a,0);else{const h=iu(a),d=h?1:a.BYTES_PER_ELEMENT;for(let f=0,p=c.length;f<p;f++){const g=c[f];let _,m;if(l!==void 0){const b=Math.floor(g.start/u),T=Math.ceil((g.start+g.count)/u)-b;_=b*l*d,m=T*l*d}else _=g.start*d,m=g.count*d;const y=_*(h?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(o,y,a,_,m)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),n=new Map;for(let i=0;i<t.length;i++){const s=t[i],o=s.array.BYTES_PER_ELEMENT,a=this._getBufferAttribute(s);let u=n.get(a);if(u===void 0){let h,d;s.isInterleavedBufferAttribute===!0?(h=s.data.stride*o,d=s.data.isInstancedInterleavedBuffer?va.Instance:va.Vertex):(h=s.itemSize*o,d=s.isInstancedBufferAttribute?va.Instance:va.Vertex,s.itemSize>1&&h%4!==0&&(h=Math.floor((h+3)/4)*4)),u={arrayStride:h,attributes:[],stepMode:d},n.set(a,u)}const l=this._getVertexFormat(s),c=s.isInterleavedBufferAttribute===!0?s.offset*o:0;u.attributes.push({shaderLocation:i,offset:c,format:l})}return Array.from(n.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,i=-1){const s=this.backend,o=s.device,u=s.get(this._getBufferAttribute(e)).buffer,l=i===-1?u.size-n:i;let c;if(t!==null&&t.isReadbackBuffer){const f=s.get(t);if(t._mapped===!0)throw new Error("THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,f.readBufferGPU===void 0){ht.label=`${t.name}_readback`,ht.size=t.maxByteLength,ht.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,c=o.createBuffer(ht),ht.reset();const p=()=>{t.buffer=null,t._mapped=!1,c.unmap()},g=()=>{t.buffer=null,t._mapped=!1,c.destroy(),s.delete(t),t.removeEventListener("release",p),t.removeEventListener("dispose",g)};t.addEventListener("release",p),t.addEventListener("dispose",g),f.readBufferGPU=c}else c=f.readBufferGPU}else ht.label=`${e.name}_readback`,ht.size=l,ht.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,c=o.createBuffer(ht),ht.reset();gc.label=`readback_encoder_${e.name}`;const h=o.createCommandEncoder(gc);gc.reset(),h.copyBufferToBuffer(u,n,c,0,l);const d=h.finish();if(Mn(o,d),await c.mapAsync(GPUMapMode.READ,0,l),t===null){const p=c.getMappedRange(0,l).slice();return c.destroy(),p}else{if(t.isReadbackBuffer)return t.buffer=c.getMappedRange(0,l),t;{const f=c.getMappedRange(0,l);return new Uint8Array(t).set(new Uint8Array(f)),c.destroy(),t}}}_getVertexFormat(e){const{itemSize:t,normalized:n}=e,i=e.array.constructor,s=e.constructor;let o;if(t===1)o=pF.get(i);else{const u=(fF.get(s)||zb.get(i))[n?1:0];if(u){const l=i.BYTES_PER_ELEMENT*t,h=Math.floor((l+3)/4)*4/i.BYTES_PER_ELEMENT;if(h%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");o=`${u}x${h}`}}return o||V("WebGPUAttributeUtils: Vertex format not supported yet."),o}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}const Ut=new Ub,js=new Ts,Gi=new jd;class mF{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class _F{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,n=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;const s=this._createLayoutEntries(e),o=wi(JSON.stringify(s));let a=this._bindGroupLayoutCache.get(o);return a===void 0&&(a=new mF(n.createBindGroupLayout({entries:s})),this._bindGroupLayoutCache.set(o,a)),a.usedTimes++,i.layout=a,i.layoutKey=o,a.layoutGPU}createBindings(e,t,n,i=0){const{backend:s}=this,o=s.get(e),a=this.createBindingsLayout(e);let u;n!==""&&(o.groups===void 0&&(o.groups={},o.versions={}),o.versions[n]===i&&(u=o.groups[n])),u===void 0&&(u=this.createBindGroup(e,a),n!==""&&(o.groups[n]=u,o.versions[n]=i)),o.group=u}updateBinding(e){const t=this.backend,n=t.device,i=e.buffer,s=t.get(e).buffer,o=e.updateRanges;if(o.length===0)n.queue.writeBuffer(s,0,i,0);else{const a=iu(i),u=a?1:i.BYTES_PER_ELEMENT;let l=o[0].start;for(let c=0,h=o.length;c<h;c++){const d=o[c],f=o[c+1],p=d.start+d.count;if(f!==void 0&&f.start===p)continue;const g=l*u,_=(p-l)*u,m=g*(a?i.BYTES_PER_ELEMENT:1);n.queue.writeBuffer(s,m,i,g,_),f!==void 0&&(l=f.start)}}}createBindGroupIndex(e,t){const i=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,o=e[0];js.label="bindingCameraIndex_"+o,js.size=16,js.usage=s;const a=i.createBuffer(js);js.reset(),i.queue.writeBuffer(a,0,e,0),Ut.label="bindGroupCameraIndex_"+o,Ut.layout=t,Ut.entries.push({binding:0,resource:{buffer:a}});const u=i.createBindGroup(Ut);return Ut.reset(),u}createBindGroup(e,t){const n=this.backend,i=n.device;let s=0;Ut.label="bindGroup_"+e.name,Ut.layout=t;for(const a of e.bindings){if(a.isUniformBuffer){const u=n.get(a);Ut.entries.push({binding:s,resource:{buffer:u.buffer}})}else if(a.isStorageBuffer){const u=n.get(a.attribute).buffer;Ut.entries.push({binding:s,resource:{buffer:u}})}else if(a.isSampledTexture){const u=n.get(a.texture);let l;if(u.externalTexture!==void 0)l=i.importExternalTexture({source:u.externalTexture});else{const c=a.store?1:u.texture.mipLevelCount,h=a.store?a.mipLevel:0;let d=`view-${u.texture.width}-${u.texture.height}`;if(u.texture.depthOrArrayLayers>1&&(d+=`-${u.texture.depthOrArrayLayers}`),d+=`-${c}-${h}`,l=u[d],l===void 0){const f=kB.All;let p;a.isSampledCubeTexture?p=it.Cube:a.texture.isArrayTexture||a.texture.isDataArrayTexture||a.texture.isCompressedArrayTexture?p=it.TwoDArray:a.isSampledTexture3D?p=it.ThreeD:p=it.TwoD,Gi.aspect=f,Gi.dimension=p,Gi.mipLevelCount=c,Gi.baseMipLevel=h,l=u[d]=u.texture.createView(Gi),Gi.reset()}}Ut.entries.push({binding:s,resource:l})}else if(a.isSampler){const u=n.get(a);Ut.entries.push({binding:s,resource:u.sampler})}s++}const o=i.createBindGroup(Ut);return Ut.reset(),o}_createLayoutEntries(e){const t=[];let n=0;for(const i of e.bindings){const s=this.backend,o={binding:n,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const a={};i.isStorageBuffer&&(i.visibility&_n.COMPUTE?i.access===Wt.READ_WRITE||i.access===Wt.WRITE_ONLY?a.type=xa.Storage:a.type=xa.ReadOnlyStorage:i.nodeUniform&&i.nodeUniform.isAtomic&&i.visibility&_n.FRAGMENT?a.type=xa.Storage:a.type=xa.ReadOnlyStorage),o.buffer=a}else if(i.isSampledTexture&&i.store){const a={};a.format=this.backend.get(i.texture).texture.format;const u=i.access;u===Wt.READ_WRITE?a.access=lc.ReadWrite:u===Wt.WRITE_ONLY?a.access=lc.WriteOnly:a.access=lc.ReadOnly,i.texture.isArrayTexture?a.viewDimension=it.TwoDArray:i.texture.is3DTexture&&(a.viewDimension=it.ThreeD),o.storageTexture=a}else if(i.isSampledTexture){const a={},{primarySamples:u}=s.utils.getTextureSampleData(i.texture);if(u>1&&(a.multisampled=!0,i.texture.isDepthTexture||(a.sampleType=Tr.UnfilterableFloat)),i.texture.isDepthTexture)s.compatibilityMode&&i.texture.compareFunction===null?a.sampleType=Tr.UnfilterableFloat:a.sampleType=Tr.Depth;else{const l=i.texture.type;l===gt?a.sampleType=Tr.SInt:l===qe?a.sampleType=Tr.UInt:i.texture.normalized===!0&&(l===Ur||l===rr)?a.sampleType=Tr.UnfilterableFloat:l===mt&&(this.backend.hasFeature("float32-filterable")?a.sampleType=Tr.Float:a.sampleType=Tr.UnfilterableFloat)}i.isSampledCubeTexture?a.viewDimension=it.Cube:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?a.viewDimension=it.TwoDArray:i.isSampledTexture3D&&(a.viewDimension=it.ThreeD),o.texture=a}else if(i.isSampler){const a={};i.texture.isDepthTexture&&(i.texture.compareFunction!==null&&i.textureNode.isSampleCompare()&&s.hasCompatibility(Si.TEXTURE_COMPARE)?a.type=Bg.Comparison:a.type=Bg.NonFiltering),o.sampler=a}else V(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(o),n++}return t}deleteBindGroupData(e){const{backend:t}=this,n=t.get(e);n.layout&&(n.layout.usedTimes--,n.layout.usedTimes===0&&this._bindGroupLayoutCache.delete(n.layoutKey),n.layout=void 0,n.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class yF{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}class bF{constructor(){this.label="",this.layout=null,this.compute=null}reset(){this.label="",this.layout=null,this.compute=null}}class xF{constructor(){this.label="",this.bindGroupLayouts=null}reset(){this.label="",this.bindGroupLayouts=null}}const ei=new bF,Vi=new xF,$i=new Ib,It=new kb;class vF{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:n,material:i,geometry:s,pipeline:o}=e,{vertexProgram:a,fragmentProgram:u}=o,l=this.backend,c=l.device,h=l.utils,d=l.get(o),f=[];for(const H of e.getBindings()){const ue=l.get(H),{layoutGPU:L}=ue.layout;f.push(L)}const p=l.attributeUtils.createShaderVertexBuffers(e);let g;i.blending!==ur&&(i.blending!==Zn||i.transparent!==!1)&&(g=this._getBlending(i));let _={};i.stencilWrite===!0&&(_={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const m=this._getColorWriteMask(i),y=[];if(e.context.textures!==null){const H=e.context.textures,ue=e.context.mrt;for(let L=0;L<H.length;L++){const G=H[L],Z=h.getTextureFormatGPU(G);let ce;if(ue!==null)if(this.backend.compatibilityMode!==!0){const k=ue.getBlendMode(G.name);k.blending===Dm?ce=g:k.blending!==ur&&(ce=this._getBlending(k))}else Fe("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),ce=g;else ce=g;y.push({format:Z,blend:ce,writeMask:m})}}else{const H=h.getCurrentColorFormat(e.context);y.push({format:H,blend:g,writeMask:m})}const b=l.get(a).module,T=l.get(u).module,x=this._getPrimitiveState(n,s,i),v=this._getDepthCompare(i),w=h.getCurrentDepthStencilFormat(e.context),R=this._getSampleCount(e.context);Vi.bindGroupLayouts=f;const F=c.createPipelineLayout(Vi);Vi.reset(),It.label=`renderPipeline_${i.name||i.type}_${i.id}`,It.vertex=Object.assign({},b,{buffers:p}),It.fragment=Object.assign({},T,{targets:y}),It.primitive=x,It.multisample.count=R,It.multisample.alphaToCoverageEnabled=i.alphaToCoverage&&R>1,It.layout=F;const M={},O=e.context.depth,U=e.context.stencil;(O===!0||U===!0)&&(O===!0&&(M.format=w,M.depthWriteEnabled=i.depthWrite,M.depthCompare=v),U===!0&&(M.stencilFront=_,M.stencilBack=_,M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),i.polygonOffset===!0&&x.topology===no.TriangleList&&(M.depthBias=i.polygonOffsetUnits,M.depthBiasSlopeScale=i.polygonOffsetFactor,M.depthBiasClamp=0),It.depthStencil=M),c.pushErrorScope("validation");const X=[{program:a,module:b.module},{program:u,module:T.module}],oe=It.label;if(t===null)d.pipeline=c.createRenderPipeline(It),It.reset(),c.popErrorScope().then(H=>{H!==null&&(d.error=!0,V(`WebGPURenderer: Render pipeline creation failed (${oe}): ${H.message}`),this._reportShaderDiagnostics(X,oe))});else{const H=new Promise(async ue=>{try{let L=null,G=null;try{G=c.createRenderPipelineAsync(It)}catch(ce){L=ce}if(It.reset(),G!==null)try{d.pipeline=await G}catch(ce){L=ce}const Z=await c.popErrorScope();if(Z!==null||L!==null){d.error=!0;const ce=Z&&Z.message||L&&L.message||"unknown";V(`WebGPURenderer: Async render pipeline creation failed (${oe}): ${ce}`),await this._reportShaderDiagnostics(X,oe)}}finally{ue()}});t.push(H)}}createBundleEncoder(e,t="renderBundleEncoder"){const n=this.backend,{utils:i,device:s}=n,o=i.getCurrentDepthStencilFormat(e),a=i.getCurrentColorFormats(e),u=this._getSampleCount(e);$i.label=t,$i.colorFormats=a,$i.depthStencilFormat=o,$i.sampleCount=u;const l=s.createRenderBundleEncoder($i);return $i.reset(),l}createComputePipeline(e,t,n=null){const i=this.backend,s=i.device,o=i.get(e.computeProgram).module,a=i.get(e),u=[];for(const d of t){const f=i.get(d),{layoutGPU:p}=f.layout;u.push(p)}const l=e.computeProgram,c=`computePipeline_${l.stage}${l.name?`_${l.name}`:""}`;s.pushErrorScope("validation"),Vi.bindGroupLayouts=u;const h=s.createPipelineLayout(Vi);if(Vi.reset(),ei.label=c,ei.compute=o,ei.layout=h,n===null)a.pipeline=s.createComputePipeline(ei),ei.reset(),s.popErrorScope().then(d=>{d!==null&&(a.error=!0,V(`WebGPURenderer: Compute pipeline creation failed (${c}): ${d.message}`),this._reportShaderDiagnostics([{program:l,module:o.module}],c))});else{const d=new Promise(async f=>{try{let p=null,g=null;try{g=s.createComputePipelineAsync(ei)}catch(m){p=m}if(ei.reset(),g!==null)try{a.pipeline=await g}catch(m){p=m}const _=await s.popErrorScope();if(_!==null||p!==null){a.error=!0;const m=_&&_.message||p&&p.message||"unknown";V(`WebGPURenderer: Async compute pipeline creation failed (${c}): ${m}`),await this._reportShaderDiagnostics([{program:l,module:o.module}],c)}}finally{f()}});n.push(d)}}async _reportShaderDiagnostics(e,t){for(const{program:n,module:i}of e){const s=await i.getCompilationInfo();if(s.messages.length===0)continue;const o=n.code.split(`
1082
+ `);for(const a of s.messages){const u=a.lineNum>0?` at line ${a.lineNum}${a.linePos>0?`:${a.linePos}`:""}`:"",l=`WebGPURenderer [${t} / ${n.stage} ${a.type}]${u}: ${a.message}`;let c="";a.lineNum>0&&a.lineNum<=o.length&&(c=`
1083
+ ${o[a.lineNum-1]}`,a.linePos>0&&(c+=`
1084
+ ${" ".repeat(a.linePos-1)}^`)),(a.type==="error"?V:Y)(l+c)}}}_getBlending(e){let t,n;const i=e.blending,s=e.blendSrc,o=e.blendDst,a=e.blendEquation;if(i===ci){const u=e.blendSrcAlpha!==null?e.blendSrcAlpha:s,l=e.blendDstAlpha!==null?e.blendDstAlpha:o,c=e.blendEquationAlpha!==null?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(s),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(u),dstFactor:this._getBlendFactor(l),operation:this._getBlendOperation(c)}}else{const u=e.premultipliedAlpha,l=(c,h,d,f)=>{t={srcFactor:c,dstFactor:h,operation:Jr.Add},n={srcFactor:d,dstFactor:f,operation:Jr.Add}};if(u)switch(i){case Zn:l(fe.One,fe.OneMinusSrcAlpha,fe.One,fe.OneMinusSrcAlpha);break;case ji:l(fe.One,fe.One,fe.One,fe.One);break;case Hi:l(fe.Zero,fe.OneMinusSrc,fe.Zero,fe.One);break;case Wi:l(fe.Dst,fe.OneMinusSrcAlpha,fe.Zero,fe.One);break}else switch(i){case Zn:l(fe.SrcAlpha,fe.OneMinusSrcAlpha,fe.One,fe.OneMinusSrcAlpha);break;case ji:l(fe.SrcAlpha,fe.One,fe.One,fe.One);break;case Hi:V(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case Wi:V(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break}}if(t!==void 0&&n!==void 0)return{color:t,alpha:n};V("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case Cr:t=fe.Zero;break;case Fm:t=fe.One;break;case Bm:t=fe.Src;break;case Nm:t=fe.OneMinusSrc;break;case Pm:t=fe.SrcAlpha;break;case Am:t=fe.OneMinusSrcAlpha;break;case Cm:t=fe.Dst;break;case Rm:t=fe.OneMinusDst;break;case Em:t=fe.DstAlpha;break;case wm:t=fe.OneMinusDstAlpha;break;case Mm:t=fe.SrcAlphaSaturated;break;case Sm:case vm:t=fe.Constant;break;case Tm:case xm:t=fe.OneMinusConstant;break;default:V("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case xv:t=rt.Never;break;case bv:t=rt.Always;break;case yv:t=rt.Less;break;case _v:t=rt.LessEqual;break;case mv:t=rt.Equal;break;case gv:t=rt.GreaterEqual;break;case pv:t=rt.Greater;break;case fv:t=rt.NotEqual;break;default:V("WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case Ev:t=vr.Keep;break;case Nv:t=vr.Zero;break;case Av:t=vr.Replace;break;case Rv:t=vr.Invert;break;case wv:t=vr.IncrementClamp;break;case Sv:t=vr.DecrementClamp;break;case Tv:t=vr.IncrementWrap;break;case vv:t=vr.DecrementWrap;break;default:V("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Qn:t=Jr.Add;break;case bm:t=Jr.Subtract;break;case ym:t=Jr.ReverseSubtract;break;case _m:t=Jr.Min;break;case mm:t=Jr.Max;break;default:V("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const i={},s=this.backend.utils;i.topology=s.getPrimitiveTopology(e,n),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?Au.Uint16:Au.Uint32);let o=n.side===yt;return e.isMesh&&e.matrixWorld.determinantAffine()<0&&(o=!o),i.frontFace=o===!0?Cg.CW:Cg.CCW,i.cullMode=n.side===sr?Mg.None:Mg.Back,i}_getColorWriteMask(e){return e.colorWrite===!0?Pg.All:Pg.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=rt.Always;else{const n=this.backend.parameters.reversedDepthBuffer?zm[e.depthFunc]:e.depthFunc;switch(n){case $m:t=rt.Never;break;case Vm:t=rt.Always;break;case Gm:t=rt.Less;break;case km:t=rt.LessEqual;break;case Im:t=rt.Equal;break;case Um:t=rt.GreaterEqual;break;case Om:t=rt.Greater;break;case Lm:t=rt.NotEqual;break;default:V("WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class Wb{constructor(){this.label="",this.type=void 0,this.count=0}reset(){this.label="",this.type=void 0,this.count=0}}const Rn=new Ts,TF=new Go,qs=new Wb;class SF extends Ob{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,qs.label=`queryset_global_timestamp_${t}`,qs.type="timestamp",qs.count=this.maxQueries,this.querySet=this.device.createQuerySet(qs),qs.reset();const i=this.maxQueries*8;Rn.label=`buffer_timestamp_resolve_${t}`,Rn.size=i,Rn.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,this.resolveBuffer=this.device.createBuffer(Rn),Rn.reset(),Rn.label=`buffer_timestamp_result_${t}`,Rn.size=i,Rn.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this.resultBuffer=this.device.createBuffer(Rn),Rn.reset()}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear());const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||this.currentQueryIndex===0||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if(this.resultBuffer.mapState!=="unmapped")return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=t*8;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder(TF);i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const s=i.finish();if(Mn(this.device,s),this.resultBuffer.mapState!=="unmapped")return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue;const o=new BigUint64Array(this.resultBuffer.getMappedRange(0,n)),a={},u=[];this.timestamps.clear();for(const[c,h]of e){const d=c.match(/^(.*):f(\d+)$/),f=parseInt(d[2]);u.includes(f)===!1&&u.push(f),a[f]===void 0&&(a[f]=0);const p=o[h],g=o[h+1],_=Number(g-p)/1e6;this.timestamps.set(c,_),a[f]+=_}const l=a[u[u.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=u,l}catch(e){return V("Error resolving queries:",e),this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){V("Error waiting for pending resolve:",e)}if(this.resultBuffer&&this.resultBuffer.mapState==="mapped")try{this.resultBuffer.unmap()}catch(e){V("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.timestamps.clear(),this.frames=[],this.pendingResolve=null}}}class wF{constructor(){this.label="",this.timestampWrites=void 0}reset(){this.label="",this.timestampWrites=void 0}}class Na{constructor(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}reset(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}}class RF{constructor(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}reset(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}}const un={r:0,g:0,b:0,a:1},Xs={r:0,g:0,b:0,a:0},kt=new Ts,xt=new Go,Ea=new wF,Ks=new Wb,Ca=new Gb,Ma=new RF,Gt=new rl,An=new rl,Ar=new nl,Pe=new jd,jn=new Vb;class AF extends Lb{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0?!0:e.alpha,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new WB(this),this.attributeUtils=new gF(this),this.bindingUtils=new _F(this),this.capabilities=new yF(this),this.pipelineUtils=new vF(this),this.textureUtils=new tF(this),this.occludedResolveCache=new Map;const t=typeof navigator>"u"?!0:/Android/.test(navigator.userAgent)===!1;this._compatibility={[Si.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);const t=this.parameters;let n;if(t.device===void 0){const i={powerPreference:t.powerPreference,featureLevel:"compatibility",xrCompatible:e.xr.enabled},s=typeof navigator<"u"?await navigator.gpu.requestAdapter(i):null;if(s===null)throw new Error("THREE.WebGPUBackend: Unable to create WebGPU adapter.");const o=Object.values(Nu),a=[];for(const l of o)s.features.has(l)&&a.push(l);const u={requiredFeatures:a,requiredLimits:t.requiredLimits};n=await s.requestDevice(u)}else n=t.device;this.compatibilityMode=!n.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),n.lost.then(i=>{if(i.reason==="destroyed")return;const s={api:"WebGPU",message:i.message||"Unknown reason",reason:i.reason||null,originalEvent:i};e.onDeviceLost(s)}),n.onuncapturederror=i=>{const s=i.error,o=s&&s.constructor?s.constructor.name:"GPUError",a=s&&s.message||"Unknown uncaptured GPU error";e.onError({api:"WebGPU",type:o,message:a,originalEvent:i})},this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(Nu.TimestampQuery),this.updateSize()}setXRRenderTargetTextures(e,t,n=null){const i=this.get(e.texture);i.texture=t,i.format=t.format,i.externalTexture=!0,i.xrViewDescriptors=n,i.initialized=!0}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let n=t.context;if(n===void 0){const i=this.parameters;e.isDefaultCanvasTarget===!0&&i.context!==void 0?n=i.context:n=e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${Ou} webgpu`);const s=i.alpha?"premultiplied":"opaque",o=i.outputType===wt?"extended":"standard";n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:s,toneMapping:{mode:o}}),t.context=n}return n}get coordinateSystem(){return bo}get hasTimestamp(){return!0}async getArrayBufferAsync(e,t=null,n=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,i)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),i=e.currentSamples;let s=n.descriptor;if(s===void 0||n.samples!==i){if(s=new go,s.colorAttachments.push(new po),e.depth===!0||e.stencil===!0){const u=new Na;u.view=this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView(),s.depthStencilAttachment=u}const a=s.colorAttachments[0];i>0?a.view=this.textureUtils.getColorBuffer().createView():a.resolveTarget=void 0,n.descriptor=s,n.samples=i}const o=s.colorAttachments[0];return i>0?o.resolveTarget=this.context.getCurrentTexture().createView():o.view=this.context.getCurrentTexture().createView(),s}_isRenderCameraDepthArray(e){const t=e.camera;return e.depthTexture&&e.depthTexture.isArrayTexture===!0&&t!==null&&t.isArrayCamera===!0}_hasExternalTexture(e){const t=e.textures;if(t===null)return!1;for(let n=0;n<t.length;n++)if(this.get(t[n]).externalTexture===!0)return!0;return!1}_getExternalMSAATextures(e,t,n){const i=this.utils.getSampleCount(e.sampleCount);if(i===1){if(t.msaaTextures!==void 0){for(const l of t.msaaTextures)l.destroy();t.msaaTextures=void 0}return null}const s=e.renderTarget,o=s.width,a=s.height,u=t.format;if(t.msaaTextures===void 0||t.msaaTextures.length!==n||t.msaaWidth!==o||t.msaaHeight!==a||t.msaaSamples!==i||t.msaaFormat!==u){if(t.msaaTextures!==void 0)for(const l of t.msaaTextures)l.destroy();Ar.size.width=o,Ar.size.height=a,Ar.sampleCount=i,Ar.format=u,Ar.usage=GPUTextureUsage.RENDER_ATTACHMENT,t.msaaTextures=[];for(let l=0;l<n;l++)Ar.label=s.texture.name+"-msaa-"+l,t.msaaTextures.push(this.device.createTexture(Ar));Ar.reset(),t.msaaWidth=o,t.msaaHeight=a,t.msaaSamples=i,t.msaaFormat=u}return t.msaaTextures}_createExternalTextureViews(e,t){const n=[],i=e.camera,s=t.xrViewDescriptors,o=Math.max((s==null?void 0:s.length)||0,e.activeCubeFace+1,1),a=this._getExternalMSAATextures(e,t,o);if(s&&i!==null&&i.isArrayCamera===!0)for(let u=0;u<s.length;u++){const l=t.texture.createView(s[u]);n.push({view:a!==null?a[u].createView():l,resolveTarget:a!==null&&e.renderTarget.resolveColorBuffer===!0?l:void 0,depthSlice:void 0})}else{const u=e.activeCubeFace,l=t.texture.createView({dimension:it.TwoD,baseArrayLayer:u,arrayLayerCount:1});n.push({view:a!==null?a[u].createView():l,resolveTarget:a!==null&&e.renderTarget.resolveColorBuffer===!0?l:void 0,depthSlice:void 0})}return n}_getRenderPassDescriptor(e,t={}){var c,h;const n=e.renderTarget,i=this.get(n),s=this._hasExternalTexture(e);let o=i.descriptors;(o===void 0||i.width!==n.width||i.height!==n.height||i.samples!==n.samples||s)&&(o={},i.descriptors=o);const a=e.getCacheKey();let u=o[a];if(u===void 0||s){const d=e.textures,f=[];let p;const g=this._isRenderCameraDepthArray(e);for(let m=0;m<d.length;m++){const y=this.get(d[m]);if(y.externalTexture===!0){f.push(...this._createExternalTextureViews(e,y));continue}if(Pe.label=`colorAttachment_${m}`,Pe.baseMipLevel=e.activeMipmapLevel,Pe.mipLevelCount=1,Pe.baseArrayLayer=e.activeCubeFace,Pe.arrayLayerCount=1,Pe.dimension=it.TwoD,n.isRenderTarget3D)p=e.activeCubeFace,Pe.baseArrayLayer=0,Pe.dimension=it.ThreeD;else if(n.isRenderTarget&&d[m].image.depth>1)if(g===!0){const b=e.camera.cameras;for(let T=0;T<b.length;T++){Pe.baseArrayLayer=T,Pe.arrayLayerCount=1,Pe.dimension=it.TwoD;const x=y.texture.createView(Pe),v=(c=y.msaaTextures)==null?void 0:c[T];f.push({view:v!==void 0?v.createView():x,resolveTarget:v!==void 0&&n.resolveColorBuffer===!0?x:void 0,depthSlice:void 0})}}else Pe.dimension=it.TwoDArray;if(g!==!0){const b=y.texture.createView(Pe);let T,x;y.msaaTexture!==void 0?(T=y.msaaTexture.createView(),x=n.resolveColorBuffer===!0?b:void 0):y.msaaTextures!==void 0?(T=y.msaaTextures[e.activeCubeFace].createView(),x=n.resolveColorBuffer===!0?b:void 0):(T=b,x=void 0),f.push({view:T,resolveTarget:x,depthSlice:p})}Pe.reset()}const _=[];for(let m=0;m<f.length;m++){const y=f[m],b=new po;b.view=y.view,b.depthSlice=y.depthSlice,b.resolveTarget=y.resolveTarget,_.push(b)}if(u={textureViews:f,colorAttachments:_,descriptor:new go},e.depth){const m=this.get(e.depthTexture);(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(Pe.dimension=it.TwoD,Pe.arrayLayerCount=1,Pe.baseArrayLayer=e.activeCubeFace);const y=new Na,b=(h=m.msaaTextures)==null?void 0:h[e.activeCubeFace];y.view=b!==void 0?b.createView():m.texture.createView(Pe),u.depthStencilAttachment=y,Pe.reset()}o[a]=u,i.width=n.width,i.height=n.height,i.samples=n.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const l=u.descriptor;l.reset();for(let d=0;d<u.colorAttachments.length;d++){const f=u.colorAttachments[d];let p={r:0,g:0,b:0,a:1};d===0&&t.clearValue&&(p=t.clearValue),f.loadOp=t.loadOp||me.Load,f.storeOp=t.storeOp||je.Store,f.clearValue=p,l.colorAttachments.push(f)}return u.depthStencilAttachment&&(l.depthStencilAttachment=u.depthStencilAttachment),l}beginRender(e){const t=this.get(e),n=this.device,i=e.occlusionQueryCount;let s;i>0?(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,Ks.label=`occlusionQuerySet_${e.id}`,Ks.type="occlusion",Ks.count=i,s=n.createQuerySet(Ks),Ks.reset(),t.occlusionQuerySet=s,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null):t.lastOcclusionObject!==void 0&&(t.lastOcclusionObject=void 0,t.occlusionQuerySet.destroy(),t.occlusionQuerySet=void 0);let o;e.textures===null?o=this._getDefaultRenderPassDescriptor():o=this._getRenderPassDescriptor(e,{loadOp:me.Load}),this.initTimestampQuery(Pn.RENDER,this.getTimestampUID(e),o),o.occlusionQuerySet=s;const a=o.depthStencilAttachment,u=e.renderTarget,l=e.sampleCount>1&&(u==null?void 0:u.storeMultisampledColorBuffer)===!1,c=e.sampleCount>1&&(u==null?void 0:u.storeMultisampledDepthBuffer)===!1,h=e.sampleCount>1&&(u==null?void 0:u.storeMultisampledStencilBuffer)===!1,d=e.fullscreenPass===!0&&this._hasExternalTexture(e);if(e.textures!==null){const p=o.colorAttachments;for(let g=0;g<p.length;g++){const _=p[g];if(e.clearColor||l||d){const m=e.mrt?e.mrt.getClearColor(e.textures[g].name):null;m!==null?_.clearValue=m:g===0?_.clearValue=e.clearColorValue:(un.r=0,un.g=0,un.b=0,un.a=1,_.clearValue=un),_.loadOp=me.Clear}else _.loadOp=me.Load;l?_.storeOp=je.Discard:_.storeOp=je.Store}}else{const p=o.colorAttachments[0];e.clearColor?(p.clearValue=e.clearColorValue,p.loadOp=me.Clear):p.loadOp=me.Load,p.storeOp=je.Store}e.depth&&(e.clearDepth||c?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=me.Clear):a.depthLoadOp=me.Load,c?a.depthStoreOp=je.Discard:a.depthStoreOp=je.Store),e.stencil&&(e.clearStencil||h?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=me.Clear):a.stencilLoadOp=me.Load,h?a.stencilStoreOp=je.Discard:a.stencilStoreOp=je.Store),xt.label="renderContext_"+e.id;const f=n.createCommandEncoder(xt);if(xt.reset(),this._isRenderCameraDepthArray(e)===!0){const p=e.camera.cameras;!t.layerDescriptors||t.layerDescriptors.length!==p.length?this._createArrayCameraLayerDescriptors(e,t,o,p):this._updateArrayCameraLayerDescriptors(e,t,o,p),this._createArrayCameraBundleEncoders(e,t),t.arrayCameraRenderStages=[],t.currentPass=null}else{t.bundleEncoders=void 0,t.bundleSets=void 0,t.arrayCameraRenderStages=void 0;const p=f.beginRenderPass(o);t.currentPass=p,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=o,t.encoder=f,t.renderBundles=[],this._resetRenderContextData(t)}_resetRenderContextData(e){e.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},e.currentBlendColor===void 0&&(e.currentBlendColor=new Dt),e.currentBlendColor.setRGB(0,0,0),e.currentBlendAlpha=0,e.currentStencilRef=0}_createArrayCameraBundleEncoders(e,t){const n=e.camera.cameras;t.bundleEncoders=[],t.bundleSets=[];for(let i=0;i<n.length;i++){const s=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+i),o={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(s),t.bundleSets.push(o)}}_finishArrayCameraBundleEncoders(e){const t=[];for(const n of e.bundleEncoders)t.push(n.finish());return t}_createArrayCameraLayerDescriptors(e,t,n,i){var a;const s=n.depthStencilAttachment;t.layerDescriptors=[];const o=this.get(e.depthTexture);o.viewCache||(o.viewCache=[]);for(let u=0;u<i.length;u++){const l=n.colorAttachments[0],c=n.colorAttachments[u],h=new po;h.view=c.view,h.depthSlice=c.depthSlice,h.resolveTarget=c.resolveTarget,h.loadOp=l.loadOp,h.storeOp=l.storeOp,h.clearValue=l.clearValue;const d=new go;if(d.label=n.label,d.occlusionQuerySet=n.occlusionQuerySet,d.timestampWrites=n.timestampWrites,d.colorAttachments.push(h),n.depthStencilAttachment){const f=u;if(!o.viewCache[f]){const g=(a=o.msaaTextures)==null?void 0:a[f];g!==void 0?o.viewCache[f]=g.createView():(Pe.dimension=it.TwoD,Pe.baseArrayLayer=u,Pe.arrayLayerCount=1,o.viewCache[f]=o.texture.createView(Pe)),Pe.reset()}const p=new Na;p.view=o.viewCache[f],p.depthLoadOp=s.depthLoadOp||me.Clear,p.depthStoreOp=s.depthStoreOp||je.Store,p.depthClearValue=s.depthClearValue||1,e.stencil&&(p.stencilLoadOp=s.stencilLoadOp,p.stencilStoreOp=s.stencilStoreOp,p.stencilClearValue=s.stencilClearValue),d.depthStencilAttachment=p}else{const f=new Na;f.view=s.view,f.depthLoadOp=s.depthLoadOp,f.depthStoreOp=s.depthStoreOp,f.depthClearValue=s.depthClearValue,f.depthReadOnly=s.depthReadOnly,f.stencilLoadOp=s.stencilLoadOp,f.stencilStoreOp=s.stencilStoreOp,f.stencilClearValue=s.stencilClearValue,f.stencilReadOnly=s.stencilReadOnly,d.depthStencilAttachment=f}t.layerDescriptors.push(d)}}_updateArrayCameraLayerDescriptors(e,t,n,i){const s=e.renderTarget,o=e.sampleCount>1&&(s==null?void 0:s.storeMultisampledDepthBuffer)===!1,a=e.sampleCount>1&&(s==null?void 0:s.storeMultisampledStencilBuffer)===!1;for(let u=0;u<i.length;u++){const l=t.layerDescriptors[u],c=n.colorAttachments[0],h=n.colorAttachments[u],d=l.colorAttachments[0];if(d.view=h.view,d.resolveTarget=h.resolveTarget,d.depthSlice=h.depthSlice,d.loadOp=c.loadOp,d.storeOp=c.storeOp,d.clearValue=c.clearValue,l.depthStencilAttachment){const f=l.depthStencilAttachment;e.depth&&(e.clearDepth||o?(f.depthClearValue=e.clearDepthValue,f.depthLoadOp=me.Clear):f.depthLoadOp=me.Load),e.stencil&&(e.clearStencil||a?(f.stencilClearValue=e.clearStencilValue,f.stencilLoadOp=me.Clear):f.stencilLoadOp=me.Load)}}}finishRender(e){var o,a,u,l;const t=this.get(e),n=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles);const i=t.lastOcclusionObject;i&&i.occlusionTest===!0&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){const c=this._finishArrayCameraBundleEncoders(t),h=t.arrayCameraRenderStages;h.push({bundles:c});for(let d=0;d<t.layerDescriptors.length;d++){const f=t.layerDescriptors[d],p=f.colorAttachments.map(T=>T.loadOp),g=f.colorAttachments.map(T=>T.storeOp),_=(o=f.depthStencilAttachment)==null?void 0:o.depthLoadOp,m=(a=f.depthStencilAttachment)==null?void 0:a.depthStoreOp,y=(u=f.depthStencilAttachment)==null?void 0:u.stencilLoadOp,b=(l=f.depthStencilAttachment)==null?void 0:l.stencilStoreOp;for(let T=0;T<h.length;T++){const x=h[T],v=x.bundles[d],w=T===h.length-1;for(let F=0;F<f.colorAttachments.length;F++){const M=f.colorAttachments[F];M.loadOp=T===0?p[F]:me.Load,M.storeOp=w?g[F]:je.Store}e.depth&&(f.depthStencilAttachment.depthLoadOp=T===0?_:me.Load,f.depthStencilAttachment.depthStoreOp=w?m:je.Store),e.stencil&&(f.depthStencilAttachment.stencilLoadOp=T===0?y:me.Load,f.depthStencilAttachment.stencilStoreOp=w?b:je.Store);const R=s.beginRenderPass(f);if(e.viewport){const{x:F,y:M,width:O,height:U,minDepth:X,maxDepth:oe}=e.viewportValue;R.setViewport(F,M,O,U,X,oe)}if(e.scissor){const{x:F,y:M,width:O,height:U}=e.scissorValue;R.setScissorRect(F,M,O,U)}if(R.executeBundles([v]),R.end(),x.framebufferCopy!==void 0){const{texture:F,sourceGPU:M,destinationGPU:O,rectangle:U,generateMipmaps:X}=x.framebufferCopy;this._copyFramebufferToTexture(s,F,M,O,U,d,X)}}for(let T=0;T<f.colorAttachments.length;T++)f.colorAttachments[T].loadOp=p[T],f.colorAttachments[T].storeOp=g[T];e.depth&&(f.depthStencilAttachment.depthLoadOp=_,f.depthStencilAttachment.depthStoreOp=m),e.stencil&&(f.depthStencilAttachment.stencilLoadOp=y,f.depthStencilAttachment.stencilStoreOp=b)}}else t.currentPass&&t.currentPass.end();if(n>0){const c=n*8;let h=this.occludedResolveCache.get(c);h===void 0&&(kt.size=c,kt.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,h=this.device.createBuffer(kt),kt.reset(),this.occludedResolveCache.set(c,h)),kt.size=c,kt.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const d=this.device.createBuffer(kt);kt.reset(),t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,h,0),t.encoder.copyBufferToBuffer(h,0,d,0,c),t.occlusionQueryBuffer=d,this.resolveOccludedAsync(e)}if(Mn(this.device,t.encoder.finish()),e.textures!==null){const c=e.textures;for(let h=0;h<c.length;h++){const d=c[h];d.generateMipmaps===!0&&this.textureUtils.generateMipmaps(d)}}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const s=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await n.mapAsync(GPUMapMode.READ);const o=n.getMappedRange(),a=new BigUint64Array(o);for(let u=0;u<i.length;u++){const l=i[u];l!==void 0&&a[u]===BigInt(0)&&s.add(l)}n.destroy(),t.occluded=s}}updateViewport(e){const{currentPass:t}=this.get(e),{x:n,y:i,width:s,height:o,minDepth:a,maxDepth:u}=e.viewportValue;t.setViewport(n,i,s,o,a,u)}updateScissor(e){const{currentPass:t}=this.get(e),{x:n,y:i,width:s,height:o}=e.scissorValue;t.setScissorRect(n,i,s,o)}getClearColor(){const e=super.getClearColor();return this.renderer.alpha===!0&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,n,i=null){const s=this.device,o=this.renderer;let a=[],u,l,c;if(e){const f=this.getClearColor();un.r=f.r,un.g=f.g,un.b=f.b,un.a=f.a}if(i===null){l=o.depth,c=o.stencil;const f=this._getDefaultRenderPassDescriptor();if(e){a=f.colorAttachments;const p=a[0];p.clearValue=un,p.loadOp=me.Clear,p.storeOp=je.Store}(l||c)&&(u=f.depthStencilAttachment)}else{l=i.depth,c=i.stencil;const f={loadOp:e?me.Clear:me.Load,clearValue:e?un:void 0};l&&(f.depthLoadOp=t?me.Clear:me.Load,f.depthClearValue=t?o.getClearDepth():void 0,f.depthStoreOp=je.Store),c&&(f.stencilLoadOp=n?me.Clear:me.Load,f.stencilClearValue=n?o.getClearStencil():void 0,f.stencilStoreOp=je.Store);const p=this._getRenderPassDescriptor(i,f);a=p.colorAttachments,u=p.depthStencilAttachment}l&&u&&(t?(u.depthLoadOp=me.Clear,u.depthClearValue=o.getClearDepth(),u.depthStoreOp=je.Store):(u.depthLoadOp=me.Load,u.depthStoreOp=je.Store)),c&&u&&(n?(u.stencilLoadOp=me.Clear,u.stencilClearValue=o.getClearStencil(),u.stencilStoreOp=je.Store):(u.stencilLoadOp=me.Load,u.stencilStoreOp=je.Store)),xt.label="clear";const h=s.createCommandEncoder(xt);xt.reset(),h.beginRenderPass({colorAttachments:a,depthStencilAttachment:u}).end(),Mn(s,h.finish())}beginCompute(e){const t=this.get(e),n="computeGroup_"+e.id;Ea.label=n,xt.label=n,this.initTimestampQuery(Pn.COMPUTE,this.getTimestampUID(e),Ea),t.cmdEncoderGPU=this.device.createCommandEncoder(xt),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(Ea),t.currentPipeline=null,xt.reset(),Ea.reset()}compute(e,t,n,i,s=null){const o=this.get(t),a=this.get(e),{passEncoderGPU:u}=a,l=this.get(i).pipeline;a.currentPipeline!==l&&(u.setPipeline(l),a.currentPipeline=l);for(let c=0,h=n.length;c<h;c++){const d=n[c],f=this.get(d);u.setBindGroup(c,f.group)}if(s===null&&(s=t.dispatchSize||t.count),s&&s.isIndirectStorageBufferAttribute){const c=this.get(s).buffer;u.dispatchWorkgroupsIndirect(c,0);return}if(typeof s=="number"){const c=s;if(o.dispatchSize===void 0||o.count!==c){o.dispatchSize=[0,1,1],o.count=c;const h=t.workgroupSize;let d=h[0];for(let g=1;g<h.length;g++)d*=h[g];const f=Math.ceil(c/d),p=this.device.limits.maxComputeWorkgroupsPerDimension;s=[f,1,1],f>p&&(s[0]=Math.min(f,p),s[1]=Math.ceil(f/p)),o.dispatchSize=s}s=o.dispatchSize}u.dispatchWorkgroups(s[0],s[1]||1,s[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),Mn(this.device,t.cmdEncoderGPU.finish())}_draw(e,t,n,i,s,o,a,u,l,c=-1){const{object:h,material:d,context:f}=e,p=e.getIndex(),g=p!==null;l.pipeline!==i&&(u.setPipeline(i),l.pipeline=i);const _=l.bindingGroups;for(let m=0,y=s.length;m<y;m++){if(m===c)continue;const b=s[m],T=this.get(b).group;_[m]!==T&&(u.setBindGroup(m,T),_[m]=T)}if(g===!0&&l.index!==p){const m=this.get(p).buffer,y=p.array instanceof Uint16Array?Au.Uint16:Au.Uint32;u.setIndexBuffer(m,y),l.index=p}for(let m=0,y=o.length;m<y;m++){const b=o[m];if(l.attributes[m]!==b){const T=this.get(b).buffer;u.setVertexBuffer(m,T),l.attributes[m]=b}}if(f.stencil===!0&&d.stencilWrite===!0&&n.currentStencilRef!==d.stencilRef&&(u.setStencilReference(d.stencilRef),n.currentStencilRef=d.stencilRef),d.blending===ci&&u.setBlendConstant!==void 0){const m=d.blendColor,y=d.blendAlpha;(m.equals(n.currentBlendColor)===!1||y!==n.currentBlendAlpha)&&(Xs.r=m.r,Xs.g=m.g,Xs.b=m.b,Xs.a=y,u.setBlendConstant(Xs),n.currentBlendColor.copy(m),n.currentBlendAlpha=y)}if(h.isBatchedMesh===!0){const m=h._multiDrawStarts,y=h._multiDrawCounts,b=h._multiDrawCount,T=h._multiDrawBytesPerElement;for(let x=0;x<b;x++)g===!0?u.drawIndexed(y[x],1,m[x]/T,0,x):u.draw(y[x],1,m[x],x),t.update(h,y[x],1)}else if(g===!0){const{vertexCount:m,instanceCount:y,firstVertex:b}=a,T=e.getIndirect();if(T!==null){const x=this.get(T).buffer,v=e.getIndirectOffset(),w=Array.isArray(v)?v:[v];for(let R=0;R<w.length;R++)u.drawIndexedIndirect(x,w[R])}else u.drawIndexed(m,y,b,0,0);t.update(h,m,y)}else{const{vertexCount:m,instanceCount:y,firstVertex:b}=a,T=e.getIndirect();if(T!==null){const x=this.get(T).buffer,v=e.getIndirectOffset(),w=Array.isArray(v)?v:[v];for(let R=0;R<w.length;R++)u.drawIndirect(x,w[R])}else u.draw(m,y,b,0);t.update(h,m,y)}}draw(e,t){const{object:n,context:i,pipeline:s}=e,o=this.get(i),a=this.get(s),u=a.pipeline;if(a.error===!0)return;const l=e.getDrawParameters();if(l===null)return;const c=e.getBindings(),h=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const d=this.get(e.camera),f=e.camera.cameras,p=e.getBindingGroup("cameraIndex");if(d.indexesGPU===void 0||d.indexesGPU.length!==f.length){const y=this.get(p),b=[],T=new Uint32Array([0,0,0,0]);for(let x=0,v=f.length;x<v;x++){T[0]=x;const{layoutGPU:w}=y.layout,R=this.bindingUtils.createBindGroupIndex(T,w);b.push(R)}d.indexesGPU=b}const g=i.renderTarget,_=g===null||g.isPostProcessingRenderTarget===!0?this.renderer.getPixelRatio():1,m=p?c.indexOf(p):-1;for(let y=0,b=f.length;y<b;y++){const T=f[y];if(n.layers.test(T.layers)){const x=T.viewport;let v=o.currentPass,w=o.currentSets;const R=o.bundleEncoders!==void 0;if(R){const F=o.bundleEncoders[y],M=o.bundleSets[y];v=F,w=M}if(x&&!R&&v.setViewport(Math.floor(x.x*_),Math.floor(x.y*_),Math.floor(x.width*_),Math.floor(x.height*_),i.viewportValue.minDepth,i.viewportValue.maxDepth),m!==-1&&d.indexesGPU){const F=d.indexesGPU[y];w.bindingGroups[m]!==F&&(v.setBindGroup(m,F),w.bindingGroups[m]=F)}this._draw(e,t,o,u,c,h,l,v,w,m)}}}else if(o.currentPass){if(o.currentPass instanceof GPURenderBundleEncoder)n.occlusionTest===!0&&Fe("WebGPUBackend: Occlusion queries can not be recorded into render bundles.");else if(o.occlusionQuerySet!==void 0){const d=o.lastOcclusionObject;d!==n&&(d!==null&&d.occlusionTest===!0&&(o.currentPass.endOcclusionQuery(),o.occlusionQueryIndex++),n.occlusionTest===!0&&(o.currentPass.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=n),o.lastOcclusionObject=n)}this._draw(e,t,o,u,c,h,l,o.currentPass,o.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:n,material:i}=e,s=this.utils,o=s.getSampleCountRenderContext(e.context),a=s.getCurrentColorSpace(e.context),u=s.getCurrentColorFormat(e.context),l=s.getCurrentDepthStencilFormat(e.context),c=s.getPrimitiveTopology(n,i),h=n.isMesh&&n.matrixWorld.determinantAffine()<0;let d=!1;return(t.material!==i||t.materialVersion!==i.version||t.transparent!==i.transparent||t.blending!==i.blending||t.premultipliedAlpha!==i.premultipliedAlpha||t.blendSrc!==i.blendSrc||t.blendDst!==i.blendDst||t.blendEquation!==i.blendEquation||t.blendSrcAlpha!==i.blendSrcAlpha||t.blendDstAlpha!==i.blendDstAlpha||t.blendEquationAlpha!==i.blendEquationAlpha||t.colorWrite!==i.colorWrite||t.depthWrite!==i.depthWrite||t.depthTest!==i.depthTest||t.depthFunc!==i.depthFunc||t.stencilWrite!==i.stencilWrite||t.stencilFunc!==i.stencilFunc||t.stencilFail!==i.stencilFail||t.stencilZFail!==i.stencilZFail||t.stencilZPass!==i.stencilZPass||t.stencilFuncMask!==i.stencilFuncMask||t.stencilWriteMask!==i.stencilWriteMask||t.polygonOffset!==i.polygonOffset||t.polygonOffsetFactor!==i.polygonOffsetFactor||t.polygonOffsetUnits!==i.polygonOffsetUnits||t.side!==i.side||t.alphaToCoverage!==i.alphaToCoverage||t.sampleCount!==o||t.colorSpace!==a||t.colorFormat!==u||t.depthStencilFormat!==l||t.primitiveTopology!==c||t.frontFaceCW!==h||t.clippingContextCacheKey!==e.clippingContextCacheKey)&&(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.polygonOffset=i.polygonOffset,t.polygonOffsetFactor=i.polygonOffsetFactor,t.polygonOffsetUnits=i.polygonOffsetUnits,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=o,t.colorSpace=a,t.colorFormat=u,t.depthStencilFormat=l,t.primitiveTopology=c,t.frontFaceCW=h,t.clippingContextCacheKey=e.clippingContextCacheKey,d=!0),d}getRenderCacheKey(e){const{object:t,material:n}=e,i=this.utils,s=e.context,o=t.isMesh&&t.matrixWorld.determinantAffine()<0;return[n.transparent,n.blending,n.premultipliedAlpha,n.blendSrc,n.blendDst,n.blendEquation,n.blendSrcAlpha,n.blendDstAlpha,n.blendEquationAlpha,n.colorWrite,n.depthWrite,n.depthTest,n.depthFunc,n.stencilWrite,n.stencilFunc,n.stencilFail,n.stencilZFail,n.stencilZPass,n.stencilFuncMask,n.stencilWriteMask,n.polygonOffset,n.polygonOffsetFactor,n.polygonOffsetUnits,n.side,n.alphaToCoverage,o,i.getSampleCountRenderContext(s),i.getCurrentColorSpace(s),i.getCurrentColorFormat(s),i.getCurrentDepthStencilFormat(s),i.getPrimitiveTopology(t,n),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,s,o){return this.textureUtils.copyTextureToBuffer(e,t,n,i,s,o)}initTimestampQuery(e,t,n){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new SF(this.device,e,2048));const i=this.timestampQueryPool[e],s=i.allocateQueriesForContext(t);Ma.querySet=i.querySet,Ma.beginningOfPassWriteIndex=s,Ma.endOfPassWriteIndex=s+1,n.timestampWrites=Ma}createNodeBuilder(e,t){return new dF(e,t)}createProgram(e){const t=this.get(e);Ca.label=e.stage+(e.name!==""?`_${e.name}`:""),Ca.code=e.code,t.module={module:this.device.createShaderModule(Ca),entryPoint:"main"},Ca.reset()}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t,n=null){this.pipelineUtils.createComputePipeline(e,t,n)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const n=this.get(e),s=n.currentPass.finish();this.get(t).bundleGPU=s,n.currentSets=n._currentSets,n.currentPass=n._currentPass,n._currentPass=null,n._currentSets=null}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createUniformBuffer(e){const t=this.get(e);if(t.buffer===void 0){const n=e.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,s=[];e.visibility&_n.VERTEX&&s.push("vertex"),e.visibility&_n.FRAGMENT&&s.push("fragment"),e.visibility&_n.COMPUTE&&s.push("compute");const o=`(${s.join(",")})`;kt.label=`bindingBuffer${e.id}_${e.name}_${o}`,kt.size=n,kt.usage=i;const a=this.device.createBuffer(kt);kt.reset(),t.buffer=a}}destroyUniformBuffer(e){this.get(e).buffer.destroy(),this.delete(e)}createBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}hasFeature(e){return Fg[e]!==void 0&&(e=Fg[e]),this.device.features.has(e)}copyTextureToTexture(e,t,n=null,i=null,s=0,o=0){let a=0,u=0,l=0,c=0,h=0,d=0,f=e.image.width,p=e.image.height,g=1;n!==null&&(n.isBox3===!0?(c=n.min.x,h=n.min.y,d=n.min.z,f=n.max.x-n.min.x,p=n.max.y-n.min.y,g=n.max.z-n.min.z):(c=n.min.x,h=n.min.y,f=n.max.x-n.min.x,p=n.max.y-n.min.y,g=1)),i!==null&&(a=i.x,u=i.y,l=i.z||0),xt.label="copyTextureToTexture_"+e.id+"_"+t.id;const _=this.device.createCommandEncoder(xt);xt.reset();const m=this.get(e).texture,y=this.get(t).texture;Gt.texture=m,Gt.mipLevel=s,Gt.origin.x=c,Gt.origin.y=h,Gt.origin.z=d,An.texture=y,An.mipLevel=o,An.origin.x=a,An.origin.y=u,An.origin.z=l,jn.width=f,jn.height=p,jn.depthOrArrayLayers=g,_.copyTextureToTexture(Gt,An,jn),Gt.reset(),An.reset(),jn.reset(),Mn(this.device,_.finish()),o===0&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){const i=this.get(t);let s=null;t.renderTarget?e.isDepthTexture?s=this.get(t.depthTexture).texture:s=this.get(t.textures[0]).texture:e.isDepthTexture?s=this.textureUtils.getDepthBuffer(t.depth,t.stencil):s=this.context.getCurrentTexture();const o=this.get(e).texture;if(s.format!==o.format){V("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",s.format,o.format);return}if(this._isRenderCameraDepthArray(t)===!0){const u=this._finishArrayCameraBundleEncoders(i);i.arrayCameraRenderStages.push({bundles:u,framebufferCopy:{texture:e,sourceGPU:s,destinationGPU:o,rectangle:{x:n.x,y:n.y,z:n.z,w:n.w},generateMipmaps:e.generateMipmaps}}),this._createArrayCameraBundleEncoders(t,i);return}let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):(xt.label="copyFramebufferToTexture_"+e.id,a=this.device.createCommandEncoder(xt),xt.reset()),this._copyFramebufferToTexture(a,e,s,o,n),i.currentPass){const{descriptor:u}=i;for(let l=0;l<u.colorAttachments.length;l++)u.colorAttachments[l].loadOp=me.Load;t.depth&&(u.depthStencilAttachment.depthLoadOp=me.Load),t.stencil&&(u.depthStencilAttachment.stencilLoadOp=me.Load),i.currentPass=a.beginRenderPass(u),this._resetRenderContextData(i),t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else Mn(this.device,a.finish())}_copyFramebufferToTexture(e,t,n,i,s,o=0,a=t.generateMipmaps){Gt.texture=n,Gt.origin.x=s.x,Gt.origin.y=s.y,Gt.origin.z=o,An.texture=i,jn.width=s.z,jn.height=s.w,e.copyTextureToTexture(Gt,An,jn),Gt.reset(),An.reset(),jn.reset(),a&&this.textureUtils.generateMipmaps(t,e)}hasCompatibility(e){return this._compatibility[e]!==void 0?this._compatibility[e]:super.hasCompatibility(e)}async dispose(){if(await super.dispose(),this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}this.parameters.device===void 0&&this.device!==null&&this.device.destroy()}}class NF extends Yh{constructor(e,t,n,i,s,o){super(e,t,n,i,s,o),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class EF extends Yh{constructor(e,t,n,i,s,o){super(e,t,n,i,s,o),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class CF extends Ab{constructor(){super(),this.addMaterial(wC,"MeshPhongMaterial"),this.addMaterial(ib,"MeshStandardMaterial"),this.addMaterial(S1,"MeshPhysicalMaterial"),this.addMaterial(N1,"MeshToonMaterial"),this.addMaterial(_C,"MeshBasicMaterial"),this.addMaterial(TC,"MeshLambertMaterial"),this.addMaterial(dC,"MeshNormalMaterial"),this.addMaterial(M1,"MeshMatcapMaterial"),this.addMaterial(aC,"LineBasicMaterial"),this.addMaterial(lC,"LineDashedMaterial"),this.addMaterial(L1,"PointsMaterial"),this.addMaterial(ob,"SpriteMaterial"),this.addMaterial(k1,"ShadowMaterial"),this.addLight(pP,Ox),this.addLight(WP,om),this.addLight(YP,Ux),this.addLight(Wd,Yh),this.addLight(zP,am),this.addLight(HP,Ix),this.addLight(qP,kx),this.addLight(jP,NF),this.addLight(KP,EF),this.addToneMapping(AM,Gx),this.addToneMapping(NM,Vx),this.addToneMapping(EM,$x),this.addToneMapping(MM,zx),this.addToneMapping(DM,Wx),this.addToneMapping(LM,Hx)}}class MF extends yB{constructor(e={}){let t;e.forceWebGL?t=Eg:(t=AF,e.getFallback=()=>(Y("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Eg(e)));const n=new t(e);super(n,e),this.library=new CF,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const mc={type:"change"},qd={type:"start"},Xd={type:"end"},Pa=1e-6,be={NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4},Ba=new de,Nr=new de,PF=new z,Fa=new z,_c=new z,Er=new ns,Da=new z,La=new z,yc=new z,Oa=new z;class BF extends Du{constructor(e,t=null){super(e,t),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.rollSpeed=1,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.multiTouchRoll=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:st.ROTATE,MIDDLE:st.DOLLY,RIGHT:st.PAN},this.target=new z,this.state=be.NONE,this.keyState=be.NONE,this._lastPosition=new z,this._lastUp=new z,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._touchRollAngle=0,this._touchRollPointerIds="",this._lastAngle=0,this._lastRollAngle=0,this._eye=new z,this._movePrev=new de,this._moveCurr=new de,this._lastAxis=new z,this._zoomStart=new de,this._zoomEnd=new de,this._panStart=new de,this._panEnd=new de,this._pointers=[],this._pointerPositions={},this._onPointerMove=DF.bind(this),this._onPointerDown=FF.bind(this),this._onPointerUp=LF.bind(this),this._onPointerCancel=OF.bind(this),this._onContextMenu=zF.bind(this),this._onMouseWheel=$F.bind(this),this._onKeyDown=IF.bind(this),this._onKeyUp=UF.bind(this),this._onTouchStart=WF.bind(this),this._onTouchMove=HF.bind(this),this._onTouchEnd=jF.bind(this),this._onMouseDown=kF.bind(this),this._onMouseMove=GF.bind(this),this._onMouseUp=VF.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,t!==null&&(this.connect(t),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){if(this._eye.subVectors(this.object.position,this.target),this.noRotate||(this._rotateCamera(),this.multiTouchRoll===!0&&this._rollCamera()),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera){this._checkDistances(),this.object.lookAt(this.target);const e=this._lastPosition.distanceToSquared(this.object.position)>Pa,t=this._lastUp.distanceToSquared(this.object.up)>Pa;(e||t)&&(this.dispatchEvent(mc),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up))}else if(this.object.isOrthographicCamera){this.object.lookAt(this.target);const e=this._lastPosition.distanceToSquared(this.object.position)>Pa,t=this._lastUp.distanceToSquared(this.object.up)>Pa,n=this._lastZoom!==this.object.zoom;(e||t||n)&&(this.dispatchEvent(mc),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom)}else console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=be.NONE,this.keyState=be.NONE,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(mc),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom}_panCamera(){if(Nr.copy(this._panEnd).sub(this._panStart),Nr.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;Nr.x*=e,Nr.y*=t}Nr.multiplyScalar(this._eye.length()*this.panSpeed),Fa.copy(this._eye).cross(this.object.up).setLength(Nr.x),Fa.add(PF.copy(this.object.up).setLength(Nr.y)),this.object.position.add(Fa),this.target.add(Fa),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(Nr.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){Oa.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=Oa.length();e?(this._eye.copy(this.object.position).sub(this.target),Da.copy(this._eye).normalize(),La.copy(this.object.up).normalize(),yc.crossVectors(La,Da).normalize(),La.setLength(this._moveCurr.y-this._movePrev.y),yc.setLength(this._moveCurr.x-this._movePrev.x),Oa.copy(La.add(yc)),_c.crossVectors(Oa,this._eye).normalize(),e*=this.rotateSpeed,Er.setFromAxisAngle(_c,e),this._eye.applyQuaternion(Er),this.object.up.applyQuaternion(Er),this._lastAxis.copy(_c),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),Er.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(Er),this.object.up.applyQuaternion(Er)),this._movePrev.copy(this._moveCurr)}_rollCamera(){const e=this._getTouchRollAngle();if(e)this._lastRollAngle=e*this.rollSpeed;else if(!this.staticMoving&&this._lastRollAngle)this._lastRollAngle*=Math.sqrt(1-this.dynamicDampingFactor);else return;Da.copy(this._eye).normalize(),Er.setFromAxisAngle(Da,this._lastRollAngle),this.object.up.applyQuaternion(Er)}_getTouchRollAngle(){const e=this._pointers[0],t=this._pointers[1];if(t===void 0||e.pointerType!=="touch"||t.pointerType!=="touch")return this._touchRollPointerIds="",0;const n=`${e.pointerId},${t.pointerId}`,i=this._pointerPositions[e.pointerId],s=this._pointerPositions[t.pointerId],o=Math.atan2(s.y-i.y,s.x-i.x);if(n!==this._touchRollPointerIds)return this._touchRollPointerIds=n,this._touchRollAngle=o,0;let a=o-this._touchRollAngle;return this._touchRollAngle=o,a>Math.PI?a-=2*Math.PI:a<-Math.PI&&(a+=2*Math.PI),a}_zoomCamera(){let e;this.state===be.TOUCH_ZOOM_PAN?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=lu.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(e=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,e!==1&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=lu.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return Ba.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),Ba}_getMouseOnCircle(e,t){return Ba.set((e-this.screen.width*.5-this.screen.left)/(this.screen.width*.5),(this.screen.height+2*(this.screen.top-t))/this.screen.width),Ba}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId==e.pointerId){this._pointers.splice(t,1);return}}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new de,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0].pointerId?this._pointers[1]:this._pointers[0];return this._pointerPositions[t.pointerId]}_checkDistances(){(!this.noZoom||!this.noPan)&&(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}}function FF(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r))}function DF(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function LF(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchEnd(r):this._onMouseUp(),this._removePointer(r),this._pointers.length===0&&(this.domElement.releasePointerCapture(r.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp)))}function OF(r){this._removePointer(r)}function UF(){this.enabled!==!1&&(this.keyState=be.NONE,window.addEventListener("keydown",this._onKeyDown))}function IF(r){this.enabled!==!1&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===be.NONE&&(r.code===this.keys[be.ROTATE]&&!this.noRotate?this.keyState=be.ROTATE:r.code===this.keys[be.ZOOM]&&!this.noZoom?this.keyState=be.ZOOM:r.code===this.keys[be.PAN]&&!this.noPan&&(this.keyState=be.PAN)))}function kF(r){let e;switch(r.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case st.DOLLY:this.state=be.ZOOM;break;case st.ROTATE:this.state=be.ROTATE;break;case st.PAN:this.state=be.PAN;break;default:this.state=be.NONE}const t=this.keyState!==be.NONE?this.keyState:this.state;t===be.ROTATE&&!this.noRotate?(this._moveCurr.copy(this._getMouseOnCircle(r.pageX,r.pageY)),this._movePrev.copy(this._moveCurr)):t===be.ZOOM&&!this.noZoom?(this._zoomStart.copy(this._getMouseOnScreen(r.pageX,r.pageY)),this._zoomEnd.copy(this._zoomStart)):t===be.PAN&&!this.noPan&&(this._panStart.copy(this._getMouseOnScreen(r.pageX,r.pageY)),this._panEnd.copy(this._panStart)),this.dispatchEvent(qd)}function GF(r){const e=this.keyState!==be.NONE?this.keyState:this.state;e===be.ROTATE&&!this.noRotate?this._moveCurr.copy(this._getMouseOnCircle(r.pageX,r.pageY)):e===be.ZOOM&&!this.noZoom?this._zoomEnd.copy(this._getMouseOnScreen(r.pageX,r.pageY)):e===be.PAN&&!this.noPan&&this._panEnd.copy(this._getMouseOnScreen(r.pageX,r.pageY))}function VF(){this.state=be.NONE,this.dispatchEvent(Xd)}function $F(r){if(this.enabled!==!1&&this.noZoom!==!0){switch(r.preventDefault(),r.deltaMode){case 2:this._zoomStart.y-=r.deltaY*.025;break;case 1:this._zoomStart.y-=r.deltaY*.01;break;default:this._zoomStart.y-=r.deltaY*25e-5;break}this.dispatchEvent(qd),this.dispatchEvent(Xd)}}function zF(r){this.enabled!==!1&&r.preventDefault()}function WF(r){switch(this._trackPointer(r),this._pointers.length){case 1:this.state=be.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);break;default:this.state=be.TOUCH_ZOOM_PAN;const e=this._pointers[0].pageX-this._pointers[1].pageX,t=this._pointers[0].pageY-this._pointers[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(e*e+t*t);const n=(this._pointers[0].pageX+this._pointers[1].pageX)/2,i=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(n,i)),this._panEnd.copy(this._panStart);break}this.dispatchEvent(qd)}function HF(r){switch(this._trackPointer(r),this._pointers.length){case 1:this._moveCurr.copy(this._getMouseOnCircle(r.pageX,r.pageY));break;default:const e=this._getSecondPointerPosition(r),t=r.pageX-e.x,n=r.pageY-e.y;this._touchZoomDistanceEnd=Math.sqrt(t*t+n*n);const i=(r.pageX+e.x)/2,s=(r.pageY+e.y)/2;this._panEnd.copy(this._getMouseOnScreen(i,s));break}}function jF(r){switch(this._pointers.length){case 0:this.state=be.NONE;break;case 1:this.state=be.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(r.pageX,r.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=be.TOUCH_ZOOM_PAN;for(let e=0;e<this._pointers.length;e++)if(this._pointers[e].pointerId!==r.pointerId){const t=this._pointerPositions[this._pointers[e].pointerId];this._moveCurr.copy(this._getMouseOnCircle(t.x,t.y)),this._movePrev.copy(this._moveCurr);break}break}this.dispatchEvent(Xd)}const kg={type:"change"},Kd={type:"start"},Hb={type:"end"},Ua=new Hv,Gg=new jh,qF=Math.cos(70*lu.DEG2RAD),Je=new z,Nt=2*Math.PI,Te={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},bc=1e-6;class XF extends Du{constructor(e,t=null){super(e,t),this.state=Te.NONE,this.target=new z,this.cursor=new z,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:st.ROTATE,MIDDLE:st.DOLLY,RIGHT:st.PAN},this.touches={ONE:nr.ROTATE,TWO:nr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new z,this._lastQuaternion=new ns,this._lastTargetPosition=new z,this._quat=new ns().setFromUnitVectors(e.up,new z(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new cf,this._sphericalDelta=new cf,this._scale=1,this._panOffset=new z,this._rotateStart=new de,this._rotateEnd=new de,this._rotateDelta=new de,this._panStart=new de,this._panEnd=new de,this._panDelta=new de,this._dollyStart=new de,this._dollyEnd=new de,this._dollyDelta=new de,this._dollyDirection=new z,this._mouse=new de,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=YF.bind(this),this._onPointerDown=KF.bind(this),this._onPointerUp=QF.bind(this),this._onContextMenu=iD.bind(this),this._onMouseWheel=eD.bind(this),this._onKeyDown=tD.bind(this),this._onTouchStart=nD.bind(this),this._onTouchMove=rD.bind(this),this._onMouseDown=ZF.bind(this),this._onMouseMove=JF.bind(this),this._interceptControlDown=sD.bind(this),this._interceptControlUp=oD.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.state=Te.NONE,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();const e=this.domElement.getRootNode();e.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),e.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(kg),this.update(),this.state=Te.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;Je.copy(t).sub(this.target),Je.applyQuaternion(this._quat),this._spherical.setFromVector3(Je),this.autoRotate&&this.state===Te.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=Nt:n>Math.PI&&(n-=Nt),i<-Math.PI?i+=Nt:i>Math.PI&&(i-=Nt),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=o!=this._spherical.radius}if(Je.setFromSpherical(this._spherical),Je.applyQuaternion(this._quatInverse),t.copy(this.target).add(Je),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const a=Je.length();o=this._clampDistance(a*this._scale);const u=a-o;this.object.position.addScaledVector(this._dollyDirection,u),this.object.updateMatrixWorld(),s=!!u}else if(this.object.isOrthographicCamera){const a=new z(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const u=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=u!==this.object.zoom;const l=new z(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(a),this.object.updateMatrixWorld(),o=Je.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(Ua.origin.copy(this.object.position),Ua.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Ua.direction))<qF?this.object.lookAt(this.target):(Gg.setFromNormalAndCoplanarPoint(this.object.up,this.target),Ua.intersectPlane(Gg,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>bc||8*(1-this._lastQuaternion.dot(this.object.quaternion))>bc||this._lastTargetPosition.distanceToSquared(this.target)>bc?(this.dispatchEvent(kg),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Nt/60*this.autoRotateSpeed*e:Nt/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Je.setFromMatrixColumn(t,0),Je.multiplyScalar(-e),this._panOffset.add(Je)}_panUp(e,t){this.screenSpacePanning===!0?Je.setFromMatrixColumn(t,1):(Je.setFromMatrixColumn(t,0),Je.crossVectors(this.object.up,Je)),Je.multiplyScalar(e),this._panOffset.add(Je)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;Je.copy(i).sub(this.target);let s=Je.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/n.clientHeight,this.object.matrix),this._panUp(2*t*s/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),i=e-n.left,s=t-n.top,o=n.width,a=n.height;this._mouse.x=i/o*2-1,this._mouse.y=-(s/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Nt*this._rotateDelta.x/t.clientHeight),this._rotateUp(Nt*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Nt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Nt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Nt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Nt*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),i=.5*(e.pageX+n.x),s=.5*(e.pageY+n.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Nt*this._rotateDelta.x/t.clientHeight),this._rotateUp(Nt*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new de,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function KF(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(r)&&(this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function YF(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function QF(r){switch(this._removePointer(r),this._pointers.length){case 0:this.domElement.releasePointerCapture(r.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Hb),this.state=Te.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function ZF(r){let e;switch(r.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case st.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(r),this.state=Te.DOLLY;break;case st.ROTATE:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=Te.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=Te.ROTATE}break;case st.PAN:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=Te.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=Te.PAN}break;default:this.state=Te.NONE}this.state!==Te.NONE&&this.dispatchEvent(Kd)}function JF(r){switch(this.state){case Te.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(r);break;case Te.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(r);break;case Te.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(r);break}}function eD(r){this.enabled===!1||this.enableZoom===!1||this.state!==Te.NONE||(r.preventDefault(),this.dispatchEvent(Kd),this._handleMouseWheel(this._customWheelEvent(r)),this.dispatchEvent(Hb))}function tD(r){this.enabled!==!1&&this._handleKeyDown(r)}function nD(r){switch(this._trackPointer(r),this._pointers.length){case 1:switch(this.touches.ONE){case nr.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(r),this.state=Te.TOUCH_ROTATE;break;case nr.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(r),this.state=Te.TOUCH_PAN;break;default:this.state=Te.NONE}break;case 2:switch(this.touches.TWO){case nr.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(r),this.state=Te.TOUCH_DOLLY_PAN;break;case nr.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(r),this.state=Te.TOUCH_DOLLY_ROTATE;break;default:this.state=Te.NONE}break;default:this.state=Te.NONE}this.state!==Te.NONE&&this.dispatchEvent(Kd)}function rD(r){switch(this._trackPointer(r),this.state){case Te.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(r),this.update();break;case Te.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(r),this.update();break;case Te.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(r),this.update();break;case Te.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(r),this.update();break;default:this.state=Te.NONE}}function iD(r){this.enabled!==!1&&r.preventDefault()}function sD(r){r.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function oD(r){r.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const aD={type:"change"},Vg=1e-6,$g=new ns;class uD extends Du{constructor(e,t=null){super(e,t),this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1,this._moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this._moveVector=new z(0,0,0),this._rotationVector=new z(0,0,0),this._lastQuaternion=new ns,this._lastPosition=new z,this._status=0,this._onKeyDown=lD.bind(this),this._onKeyUp=cD.bind(this),this._onPointerMove=dD.bind(this),this._onPointerDown=hD.bind(this),this._onPointerUp=fD.bind(this),this._onPointerCancel=pD.bind(this),this._onContextMenu=gD.bind(this),t!==null&&this.connect(t)}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}update(e){if(this.enabled===!1)return;const t=this.object,n=e*this.movementSpeed,i=e*this.rollSpeed;t.translateX(this._moveVector.x*n),t.translateY(this._moveVector.y*n),t.translateZ(this._moveVector.z*n),$g.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply($g),(this._lastPosition.distanceToSquared(t.position)>Vg||8*(1-this._lastQuaternion.dot(t.quaternion))>Vg)&&(this.dispatchEvent(aD),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function lD(r){if(!(r.altKey||this.enabled===!1)){switch(r.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1;break}this._updateMovementVector(),this._updateRotationVector()}}function cD(r){if(this.enabled!==!1){switch(r.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0;break}this._updateMovementVector(),this._updateRotationVector()}}function hD(r){if(this.enabled!==!1)if(this.dragToLook)this._status++;else{switch(r.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1;break}this._updateMovementVector()}}function dD(r){if(this.enabled!==!1&&(!this.dragToLook||this._status>0)){const e=this._getContainerDimensions(),t=e.size[0]/2,n=e.size[1]/2;this._moveState.yawLeft=-(r.pageX-e.offset[0]-t)/t,this._moveState.pitchDown=(r.pageY-e.offset[1]-n)/n,this._updateRotationVector()}}function fD(r){if(this.enabled!==!1){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(r.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0;break}this._updateMovementVector()}this._updateRotationVector()}}function pD(){this.enabled!==!1&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function gD(r){this.enabled!==!1&&r.preventDefault()}const mD={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
1085
+
1086
+ varying vec2 vUv;
1087
+
1088
+ void main() {
1089
+
1090
+ vUv = uv;
1091
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
1092
+
1093
+ }`,fragmentShader:`
1094
+
1095
+ uniform float opacity;
1096
+
1097
+ uniform sampler2D tDiffuse;
1098
+
1099
+ varying vec2 vUv;
1100
+
1101
+ void main() {
1102
+
1103
+ vec4 texel = texture2D( tDiffuse, vUv );
1104
+ gl_FragColor = opacity * texel;
1105
+
1106
+
1107
+ }`};class il{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const _D=new rd(-1,1,1,-1,0,1);class yD extends Eo{constructor(){super(),this.setAttribute("position",new uu([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new uu([0,2,0,0,2,0],2))}}const bD=new yD;class xD{constructor(e){this._mesh=new yn(bD,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,_D)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class vD extends il{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof hf?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=jv.clone(e.uniforms),this.material=new hf({name:e.name!==void 0?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new xD(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class zg extends il{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const i=e.getContext(),s=e.state;s.buffers.color.setMask(!1),s.buffers.depth.setMask(!1),s.buffers.color.setLocked(!0),s.buffers.depth.setLocked(!0);let o,a;this.inverse?(o=0,a=1):(o=1,a=0),s.buffers.stencil.setTest(!0),s.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),s.buffers.stencil.setFunc(i.ALWAYS,o,4294967295),s.buffers.stencil.setClear(a),s.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),s.buffers.color.setLocked(!1),s.buffers.depth.setLocked(!1),s.buffers.color.setMask(!0),s.buffers.depth.setMask(!0),s.buffers.stencil.setLocked(!1),s.buffers.stencil.setFunc(i.EQUAL,1,4294967295),s.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),s.buffers.stencil.setLocked(!0)}}class TD extends il{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class SD{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){const n=e.getSize(new de);this._width=n.width,this._height=n.height,t=new qv(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:wt}),t.texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new vD(mD),this.copyPass.material.blending=ur,this.timer=new Xm}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){this.timer.update(),e===void 0&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let n=!1;for(let i=0,s=this.passes.length;i<s;i++){const o=this.passes[i];if(o.enabled!==!1){if(o.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(i),o.render(this.renderer,this.writeBuffer,this.readBuffer,e,n),o.needsSwap){if(n){const a=this.renderer.getContext(),u=this.renderer.state.buffers.stencil;u.setFunc(a.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),u.setFunc(a.EQUAL,1,4294967295)}this.swapBuffers()}zg!==void 0&&(o instanceof zg?n=!0:o instanceof TD&&(n=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(e===void 0){const t=this.renderer.getSize(new de);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,e=this.renderTarget1.clone(),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget1.setSize(n,i),this.renderTarget2.setSize(n,i);for(let s=0;s<this.passes.length;s++)this.passes[s].setSize(n,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class wD extends il{constructor(e,t,n=null,i=null,s=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=n,this.clearColor=i,this.clearAlpha=s,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new Dt}render(e,t,n){const i=e.autoClear;e.autoClear=!1;let s,o;this.overrideMaterial!==null&&(o=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),this.clearColor!==null&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),this.clearAlpha!==null&&(s=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),this.clearDepth==!0&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:n),this.clear===!0&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),this.clearColor!==null&&e.setClearColor(this._oldClearColor),this.clearAlpha!==null&&e.setClearAlpha(s),this.overrideMaterial!==null&&(this.scene.overrideMaterial=o),e.autoClear=i}}function RD(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function No(r,e){return No=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},No(r,e)}function AD(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,No(r,e)}function Lh(r){return Lh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Lh(r)}function ND(r){try{return Function.toString.call(r).indexOf("[native code]")!==-1}catch{return typeof r=="function"}}function jb(){try{var r=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(jb=function(){return!!r})()}function ED(r,e,t){if(jb())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(r.bind.apply(r,n));return t&&No(i,t.prototype),i}function Oh(r){var e=typeof Map=="function"?new Map:void 0;return Oh=function(n){if(n===null||!ND(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,i)}function i(){return ED(n,arguments,Lh(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),No(i,n)},Oh(r)}var Bn=(function(r){AD(e,r);function e(t){var n;return n=r.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+t+" for more information.")||this,RD(n)}return e})(Oh(Error));function xc(r){return Math.round(r*255)}function CD(r,e,t){return xc(r)+","+xc(e)+","+xc(t)}function Eu(r,e,t,n){if(n===void 0&&(n=CD),e===0)return n(t,t,t);var i=(r%360+360)%360/60,s=(1-Math.abs(2*t-1))*e,o=s*(1-Math.abs(i%2-1)),a=0,u=0,l=0;i>=0&&i<1?(a=s,u=o):i>=1&&i<2?(a=o,u=s):i>=2&&i<3?(u=s,l=o):i>=3&&i<4?(u=o,l=s):i>=4&&i<5?(a=o,l=s):i>=5&&i<6&&(a=s,l=o);var c=t-s/2,h=a+c,d=u+c,f=l+c;return n(h,d,f)}var Wg={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};function MD(r){if(typeof r!="string")return r;var e=r.toLowerCase();return Wg[e]?"#"+Wg[e]:r}var PD=/^#[a-fA-F0-9]{6}$/,BD=/^#[a-fA-F0-9]{8}$/,FD=/^#[a-fA-F0-9]{3}$/,DD=/^#[a-fA-F0-9]{4}$/,vc=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,LD=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,OD=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,UD=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function ps(r){if(typeof r!="string")throw new Bn(3);var e=MD(r);if(e.match(PD))return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16)};if(e.match(BD)){var t=parseFloat((parseInt(""+e[7]+e[8],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16),alpha:t}}if(e.match(FD))return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16)};if(e.match(DD)){var n=parseFloat((parseInt(""+e[4]+e[4],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16),alpha:n}}var i=vc.exec(e);if(i)return{red:parseInt(""+i[1],10),green:parseInt(""+i[2],10),blue:parseInt(""+i[3],10)};var s=LD.exec(e.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var o=OD.exec(e);if(o){var a=parseInt(""+o[1],10),u=parseInt(""+o[2],10)/100,l=parseInt(""+o[3],10)/100,c="rgb("+Eu(a,u,l)+")",h=vc.exec(c);if(!h)throw new Bn(4,e,c);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10)}}var d=UD.exec(e.substring(0,50));if(d){var f=parseInt(""+d[1],10),p=parseInt(""+d[2],10)/100,g=parseInt(""+d[3],10)/100,_="rgb("+Eu(f,p,g)+")",m=vc.exec(_);if(!m)throw new Bn(4,e,_);return{red:parseInt(""+m[1],10),green:parseInt(""+m[2],10),blue:parseInt(""+m[3],10),alpha:parseFloat(""+d[4])>1?parseFloat(""+d[4])/100:parseFloat(""+d[4])}}throw new Bn(5)}function ID(r){var e=r.red/255,t=r.green/255,n=r.blue/255,i=Math.max(e,t,n),s=Math.min(e,t,n),o=(i+s)/2;if(i===s)return r.alpha!==void 0?{hue:0,saturation:0,lightness:o,alpha:r.alpha}:{hue:0,saturation:0,lightness:o};var a,u=i-s,l=o>.5?u/(2-i-s):u/(i+s);switch(i){case e:a=(t-n)/u+(t<n?6:0);break;case t:a=(n-e)/u+2;break;default:a=(e-t)/u+4;break}return a*=60,r.alpha!==void 0?{hue:a,saturation:l,lightness:o,alpha:r.alpha}:{hue:a,saturation:l,lightness:o}}function Xr(r){return ID(ps(r))}var kD=function(e){return e.length===7&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e},Uh=kD;function ii(r){var e=r.toString(16);return e.length===1?"0"+e:e}function Tc(r){return ii(Math.round(r*255))}function GD(r,e,t){return Uh("#"+Tc(r)+Tc(e)+Tc(t))}function qb(r,e,t){return Eu(r,e,t,GD)}function VD(r,e,t){if(typeof r=="object"&&e===void 0&&t===void 0)return qb(r.hue,r.saturation,r.lightness);throw new Bn(1)}function $D(r,e,t,n){if(typeof r=="object"&&e===void 0&&t===void 0&&n===void 0)return r.alpha>=1?qb(r.hue,r.saturation,r.lightness):"rgba("+Eu(r.hue,r.saturation,r.lightness)+","+r.alpha+")";throw new Bn(2)}function Xb(r,e,t){if(typeof r=="number"&&typeof e=="number"&&typeof t=="number")return Uh("#"+ii(r)+ii(e)+ii(t));if(typeof r=="object"&&e===void 0&&t===void 0)return Uh("#"+ii(r.red)+ii(r.green)+ii(r.blue));throw new Bn(6)}function sl(r,e,t,n){if(typeof r=="object"&&e===void 0&&t===void 0&&n===void 0)return r.alpha>=1?Xb(r.red,r.green,r.blue):"rgba("+r.red+","+r.green+","+r.blue+","+r.alpha+")";throw new Bn(7)}var zD=function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&(typeof e.alpha!="number"||typeof e.alpha>"u")},WD=function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"},HD=function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&(typeof e.alpha!="number"||typeof e.alpha>"u")},jD=function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&typeof e.alpha=="number"};function Kr(r){if(typeof r!="object")throw new Bn(8);if(WD(r))return sl(r);if(zD(r))return Xb(r);if(jD(r))return $D(r);if(HD(r))return VD(r);throw new Bn(8)}function Kb(r,e,t){return function(){var i=t.concat(Array.prototype.slice.call(arguments));return i.length>=e?r.apply(this,i):Kb(r,e,i)}}function qt(r){return Kb(r,r.length,[])}function qD(r,e){if(e==="transparent")return e;var t=Xr(e);return Kr(rn({},t,{hue:t.hue+parseFloat(r)}))}qt(qD);function Ss(r,e,t){return Math.max(r,Math.min(e,t))}function XD(r,e){if(e==="transparent")return e;var t=Xr(e);return Kr(rn({},t,{lightness:Ss(0,1,t.lightness-parseFloat(r))}))}qt(XD);function KD(r,e){if(e==="transparent")return e;var t=Xr(e);return Kr(rn({},t,{saturation:Ss(0,1,t.saturation-parseFloat(r))}))}qt(KD);function YD(r,e){if(e==="transparent")return e;var t=Xr(e);return Kr(rn({},t,{lightness:Ss(0,1,t.lightness+parseFloat(r))}))}qt(YD);function QD(r,e,t){if(e==="transparent")return t;if(t==="transparent")return e;if(r===0)return t;var n=ps(e),i=rn({},n,{alpha:typeof n.alpha=="number"?n.alpha:1}),s=ps(t),o=rn({},s,{alpha:typeof s.alpha=="number"?s.alpha:1}),a=i.alpha-o.alpha,u=parseFloat(r)*2-1,l=u*a===-1?u:u+a,c=1+u*a,h=(l/c+1)/2,d=1-h,f={red:Math.floor(i.red*h+o.red*d),green:Math.floor(i.green*h+o.green*d),blue:Math.floor(i.blue*h+o.blue*d),alpha:i.alpha*parseFloat(r)+o.alpha*(1-parseFloat(r))};return sl(f)}var ZD=qt(QD),Yb=ZD;function JD(r,e){if(e==="transparent")return e;var t=ps(e),n=typeof t.alpha=="number"?t.alpha:1,i=rn({},t,{alpha:Ss(0,1,(n*100+parseFloat(r)*100)/100)});return sl(i)}var eL=qt(JD),tL=eL;function nL(r,e){if(e==="transparent")return e;var t=Xr(e);return Kr(rn({},t,{saturation:Ss(0,1,t.saturation+parseFloat(r))}))}qt(nL);function rL(r,e){return e==="transparent"?e:Kr(rn({},Xr(e),{hue:parseFloat(r)}))}qt(rL);function iL(r,e){return e==="transparent"?e:Kr(rn({},Xr(e),{lightness:parseFloat(r)}))}qt(iL);function sL(r,e){return e==="transparent"?e:Kr(rn({},Xr(e),{saturation:parseFloat(r)}))}qt(sL);function oL(r,e){return e==="transparent"?e:Yb(parseFloat(r),"rgb(0, 0, 0)",e)}qt(oL);function aL(r,e){return e==="transparent"?e:Yb(parseFloat(r),"rgb(255, 255, 255)",e)}qt(aL);function uL(r,e){if(e==="transparent")return e;var t=ps(e),n=typeof t.alpha=="number"?t.alpha:1,i=rn({},t,{alpha:Ss(0,1,+(n*100-parseFloat(r)*100).toFixed(2)/100)});return sl(i)}qt(uL);var pi=Object.freeze({Linear:Object.freeze({None:function(r){return r},In:function(r){return r},Out:function(r){return r},InOut:function(r){return r}}),Quadratic:Object.freeze({In:function(r){return r*r},Out:function(r){return r*(2-r)},InOut:function(r){return(r*=2)<1?.5*r*r:-.5*(--r*(r-2)-1)}}),Cubic:Object.freeze({In:function(r){return r*r*r},Out:function(r){return--r*r*r+1},InOut:function(r){return(r*=2)<1?.5*r*r*r:.5*((r-=2)*r*r+2)}}),Quartic:Object.freeze({In:function(r){return r*r*r*r},Out:function(r){return 1- --r*r*r*r},InOut:function(r){return(r*=2)<1?.5*r*r*r*r:-.5*((r-=2)*r*r*r-2)}}),Quintic:Object.freeze({In:function(r){return r*r*r*r*r},Out:function(r){return--r*r*r*r*r+1},InOut:function(r){return(r*=2)<1?.5*r*r*r*r*r:.5*((r-=2)*r*r*r*r+2)}}),Sinusoidal:Object.freeze({In:function(r){return 1-Math.sin((1-r)*Math.PI/2)},Out:function(r){return Math.sin(r*Math.PI/2)},InOut:function(r){return .5*(1-Math.sin(Math.PI*(.5-r)))}}),Exponential:Object.freeze({In:function(r){return r===0?0:Math.pow(1024,r-1)},Out:function(r){return r===1?1:1-Math.pow(2,-10*r)},InOut:function(r){return r===0?0:r===1?1:(r*=2)<1?.5*Math.pow(1024,r-1):.5*(-Math.pow(2,-10*(r-1))+2)}}),Circular:Object.freeze({In:function(r){return 1-Math.sqrt(1-r*r)},Out:function(r){return Math.sqrt(1- --r*r)},InOut:function(r){return(r*=2)<1?-.5*(Math.sqrt(1-r*r)-1):.5*(Math.sqrt(1-(r-=2)*r)+1)}}),Elastic:Object.freeze({In:function(r){return r===0?0:r===1?1:-Math.pow(2,10*(r-1))*Math.sin((r-1.1)*5*Math.PI)},Out:function(r){return r===0?0:r===1?1:Math.pow(2,-10*r)*Math.sin((r-.1)*5*Math.PI)+1},InOut:function(r){return r===0?0:r===1?1:(r*=2,r<1?-.5*Math.pow(2,10*(r-1))*Math.sin((r-1.1)*5*Math.PI):.5*Math.pow(2,-10*(r-1))*Math.sin((r-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(r){var e=1.70158;return r===1?1:r*r*((e+1)*r-e)},Out:function(r){var e=1.70158;return r===0?0:--r*r*((e+1)*r+e)+1},InOut:function(r){var e=2.5949095;return(r*=2)<1?.5*(r*r*((e+1)*r-e)):.5*((r-=2)*r*((e+1)*r+e)+2)}}),Bounce:Object.freeze({In:function(r){return 1-pi.Bounce.Out(1-r)},Out:function(r){return r<1/2.75?7.5625*r*r:r<2/2.75?7.5625*(r-=1.5/2.75)*r+.75:r<2.5/2.75?7.5625*(r-=2.25/2.75)*r+.9375:7.5625*(r-=2.625/2.75)*r+.984375},InOut:function(r){return r<.5?pi.Bounce.In(r*2)*.5:pi.Bounce.Out(r*2-1)*.5+.5}}),generatePow:function(r){return r===void 0&&(r=4),r=r<Number.EPSILON?Number.EPSILON:r,r=r>1e4?1e4:r,{In:function(e){return Math.pow(e,r)},Out:function(e){return 1-Math.pow(1-e,r)},InOut:function(e){return e<.5?Math.pow(e*2,r)/2:(1-Math.pow(2-e*2,r))/2+.5}}}}),ro=function(){return performance.now()},Qb=(function(){function r(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return r.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},r.prototype.removeAll=function(){this._tweens={}},r.prototype.add=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var i=0,s=t;i<s.length;i++){var o=s[i];(e=o._group)===null||e===void 0||e.remove(o),o._group=this,this._tweens[o.getId()]=o,this._tweensAddedDuringUpdate[o.getId()]=o}},r.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,i=e;n<i.length;n++){var s=i[n];s._group=void 0,delete this._tweens[s.getId()],delete this._tweensAddedDuringUpdate[s.getId()]}},r.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},r.prototype.update=function(e,t){e===void 0&&(e=ro()),t===void 0&&(t=!0);var n=Object.keys(this._tweens);if(n.length!==0)for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<n.length;i++){var s=this._tweens[n[i]],o=!t;s&&s.update(e,o)===!1&&!t&&this.remove(s)}n=Object.keys(this._tweensAddedDuringUpdate)}},r})(),Ih={Linear:function(r,e){var t=r.length-1,n=t*e,i=Math.floor(n),s=Ih.Utils.Linear;return e<0?s(r[0],r[1],n):e>1?s(r[t],r[t-1],t-n):s(r[i],r[i+1>t?t:i+1],n-i)},Utils:{Linear:function(r,e,t){return(e-r)*t+r}}},Zb=(function(){function r(){}return r.nextId=function(){return r._nextId++},r._nextId=0,r})(),kh=new Qb,Hg=(function(){function r(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=pi.Linear.None,this._interpolationFunction=Ih.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=Zb.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,typeof t=="object"?(this._group=t,t.add(this)):t===!0&&(this._group=kh,kh.add(this))}return r.prototype.getId=function(){return this._id},r.prototype.isPlaying=function(){return this._isPlaying},r.prototype.isPaused=function(){return this._isPaused},r.prototype.getDuration=function(){return this._duration},r.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},r.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e<0?0:e,this},r.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},r.prototype.start=function(e,t){if(e===void 0&&(e=ro()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var n in this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var s in this._valuesEnd)i[s]=this._valuesEnd[s];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},r.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},r.prototype._setupProperties=function(e,t,n,i,s){for(var o in n){var a=e[o],u=Array.isArray(a),l=u?"array":typeof a,c=!u&&Array.isArray(n[o]);if(!(l==="undefined"||l==="function")){if(c){var h=n[o];if(h.length===0)continue;for(var d=[a],f=0,p=h.length;f<p;f+=1){var g=this._handleRelativeValue(a,h[f]);if(isNaN(g)){c=!1,console.warn("Found invalid interpolation list. Skipping.");break}d.push(g)}c&&(n[o]=d)}if((l==="object"||u)&&a&&!c){t[o]=u?[]:{};var _=a;for(var m in _)t[o][m]=_[m];i[o]=u?[]:{};var h=n[o];if(!this._isDynamic){var y={};for(var m in h)y[m]=h[m];n[o]=h=y}this._setupProperties(_,t[o],h,i[o],s)}else(typeof t[o]>"u"||s)&&(t[o]=a),u||(t[o]*=1),c?i[o]=n[o].slice().reverse():i[o]=t[o]||0}}},r.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},r.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},r.prototype.pause=function(e){return e===void 0&&(e=ro()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this)},r.prototype.resume=function(e){return e===void 0&&(e=ro()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this)},r.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},r.prototype.group=function(e){return e?(e.add(this),this):(console.warn("tween.group() without args has been removed, use group.add(tween) instead."),this)},r.prototype.remove=function(){var e;return(e=this._group)===null||e===void 0||e.remove(this),this},r.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},r.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},r.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},r.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},r.prototype.easing=function(e){return e===void 0&&(e=pi.Linear.None),this._easingFunction=e,this},r.prototype.interpolation=function(e){return e===void 0&&(e=Ih.Linear),this._interpolationFunction=e,this},r.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},r.prototype.onStart=function(e){return this._onStartCallback=e,this},r.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},r.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},r.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},r.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},r.prototype.onStop=function(e){return this._onStopCallback=e,this},r.prototype.update=function(e,t){var n=this,i;if(e===void 0&&(e=ro()),t===void 0&&(t=r.autoStartOnUpdate),this._isPaused)return!0;var s;if(!this._goToEnd&&!this._isPlaying)if(t)this.start(e,!0);else return!1;if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var o=e-this._startTime,a=this._duration+((i=this._repeatDelayTime)!==null&&i!==void 0?i:this._delayTime),u=this._duration+this._repeat*a,l=function(){if(n._duration===0||o>u)return 1;var g=Math.trunc(o/a),_=o-g*a,m=Math.min(_/n._duration,1);return m===0&&o===n._duration?1:m},c=l(),h=this._easingFunction(c);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,h),this._onUpdateCallback&&this._onUpdateCallback(this._object,c),this._duration===0||o>=this._duration)if(this._repeat>0){var d=Math.min(Math.trunc((o-this._duration)/a)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=d);for(s in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[s]=="string"&&(this._valuesStartRepeat[s]=this._valuesStartRepeat[s]+parseFloat(this._valuesEnd[s])),this._yoyo&&this._swapEndStartRepeatValues(s),this._valuesStart[s]=this._valuesStartRepeat[s];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=a*d,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var f=0,p=this._chainedTweens.length;f<p;f++)this._chainedTweens[f].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},r.prototype._updateProperties=function(e,t,n,i){for(var s in n)if(t[s]!==void 0){var o=t[s]||0,a=n[s],u=Array.isArray(e[s]),l=Array.isArray(a),c=!u&&l;c?e[s]=this._interpolationFunction(a,i):typeof a=="object"&&a?this._updateProperties(e[s],o,a,i):(a=this._handleRelativeValue(o,a),typeof a=="number"&&(e[s]=o+(a-o)*i))}},r.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},r.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],n=this._valuesEnd[e];typeof n=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(n):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},r.autoStartOnUpdate=!1,r})();Zb.nextId;var kn=kh;kn.getAll.bind(kn);kn.removeAll.bind(kn);kn.add.bind(kn);kn.remove.bind(kn);kn.update.bind(kn);var Gh="http://www.w3.org/1999/xhtml";const jg={svg:"http://www.w3.org/2000/svg",xhtml:Gh,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Jb(r){var e=r+="",t=e.indexOf(":");return t>=0&&(e=r.slice(0,t))!=="xmlns"&&(r=r.slice(t+1)),jg.hasOwnProperty(e)?{space:jg[e],local:r}:r}function lL(r){return function(){var e=this.ownerDocument,t=this.namespaceURI;return t===Gh&&e.documentElement.namespaceURI===Gh?e.createElement(r):e.createElementNS(t,r)}}function cL(r){return function(){return this.ownerDocument.createElementNS(r.space,r.local)}}function ex(r){var e=Jb(r);return(e.local?cL:lL)(e)}function hL(){}function tx(r){return r==null?hL:function(){return this.querySelector(r)}}function dL(r){typeof r!="function"&&(r=tx(r));for(var e=this._groups,t=e.length,n=new Array(t),i=0;i<t;++i)for(var s=e[i],o=s.length,a=n[i]=new Array(o),u,l,c=0;c<o;++c)(u=s[c])&&(l=r.call(u,u.__data__,c,s))&&("__data__"in u&&(l.__data__=u.__data__),a[c]=l);return new on(n,this._parents)}function fL(r){return r==null?[]:Array.isArray(r)?r:Array.from(r)}function pL(){return[]}function gL(r){return r==null?pL:function(){return this.querySelectorAll(r)}}function mL(r){return function(){return fL(r.apply(this,arguments))}}function _L(r){typeof r=="function"?r=mL(r):r=gL(r);for(var e=this._groups,t=e.length,n=[],i=[],s=0;s<t;++s)for(var o=e[s],a=o.length,u,l=0;l<a;++l)(u=o[l])&&(n.push(r.call(u,u.__data__,l,o)),i.push(u));return new on(n,i)}function yL(r){return function(){return this.matches(r)}}function nx(r){return function(e){return e.matches(r)}}var bL=Array.prototype.find;function xL(r){return function(){return bL.call(this.children,r)}}function vL(){return this.firstElementChild}function TL(r){return this.select(r==null?vL:xL(typeof r=="function"?r:nx(r)))}var SL=Array.prototype.filter;function wL(){return Array.from(this.children)}function RL(r){return function(){return SL.call(this.children,r)}}function AL(r){return this.selectAll(r==null?wL:RL(typeof r=="function"?r:nx(r)))}function NL(r){typeof r!="function"&&(r=yL(r));for(var e=this._groups,t=e.length,n=new Array(t),i=0;i<t;++i)for(var s=e[i],o=s.length,a=n[i]=[],u,l=0;l<o;++l)(u=s[l])&&r.call(u,u.__data__,l,s)&&a.push(u);return new on(n,this._parents)}function rx(r){return new Array(r.length)}function EL(){return new on(this._enter||this._groups.map(rx),this._parents)}function Cu(r,e){this.ownerDocument=r.ownerDocument,this.namespaceURI=r.namespaceURI,this._next=null,this._parent=r,this.__data__=e}Cu.prototype={constructor:Cu,appendChild:function(r){return this._parent.insertBefore(r,this._next)},insertBefore:function(r,e){return this._parent.insertBefore(r,e)},querySelector:function(r){return this._parent.querySelector(r)},querySelectorAll:function(r){return this._parent.querySelectorAll(r)}};function CL(r){return function(){return r}}function ML(r,e,t,n,i,s){for(var o=0,a,u=e.length,l=s.length;o<l;++o)(a=e[o])?(a.__data__=s[o],n[o]=a):t[o]=new Cu(r,s[o]);for(;o<u;++o)(a=e[o])&&(i[o]=a)}function PL(r,e,t,n,i,s,o){var a,u,l=new Map,c=e.length,h=s.length,d=new Array(c),f;for(a=0;a<c;++a)(u=e[a])&&(d[a]=f=o.call(u,u.__data__,a,e)+"",l.has(f)?i[a]=u:l.set(f,u));for(a=0;a<h;++a)f=o.call(r,s[a],a,s)+"",(u=l.get(f))?(n[a]=u,u.__data__=s[a],l.delete(f)):t[a]=new Cu(r,s[a]);for(a=0;a<c;++a)(u=e[a])&&l.get(d[a])===u&&(i[a]=u)}function BL(r){return r.__data__}function FL(r,e){if(!arguments.length)return Array.from(this,BL);var t=e?PL:ML,n=this._parents,i=this._groups;typeof r!="function"&&(r=CL(r));for(var s=i.length,o=new Array(s),a=new Array(s),u=new Array(s),l=0;l<s;++l){var c=n[l],h=i[l],d=h.length,f=DL(r.call(c,c&&c.__data__,l,n)),p=f.length,g=a[l]=new Array(p),_=o[l]=new Array(p),m=u[l]=new Array(d);t(c,h,g,_,m,f,e);for(var y=0,b=0,T,x;y<p;++y)if(T=g[y]){for(y>=b&&(b=y+1);!(x=_[b])&&++b<p;);T._next=x||null}}return o=new on(o,n),o._enter=a,o._exit=u,o}function DL(r){return typeof r=="object"&&"length"in r?r:Array.from(r)}function LL(){return new on(this._exit||this._groups.map(rx),this._parents)}function OL(r,e,t){var n=this.enter(),i=this,s=this.exit();return typeof r=="function"?(n=r(n),n&&(n=n.selection())):n=n.append(r+""),e!=null&&(i=e(i),i&&(i=i.selection())),t==null?s.remove():t(s),n&&i?n.merge(i).order():i}function UL(r){for(var e=r.selection?r.selection():r,t=this._groups,n=e._groups,i=t.length,s=n.length,o=Math.min(i,s),a=new Array(i),u=0;u<o;++u)for(var l=t[u],c=n[u],h=l.length,d=a[u]=new Array(h),f,p=0;p<h;++p)(f=l[p]||c[p])&&(d[p]=f);for(;u<i;++u)a[u]=t[u];return new on(a,this._parents)}function IL(){for(var r=this._groups,e=-1,t=r.length;++e<t;)for(var n=r[e],i=n.length-1,s=n[i],o;--i>=0;)(o=n[i])&&(s&&o.compareDocumentPosition(s)^4&&s.parentNode.insertBefore(o,s),s=o);return this}function kL(r){r||(r=GL);function e(h,d){return h&&d?r(h.__data__,d.__data__):!h-!d}for(var t=this._groups,n=t.length,i=new Array(n),s=0;s<n;++s){for(var o=t[s],a=o.length,u=i[s]=new Array(a),l,c=0;c<a;++c)(l=o[c])&&(u[c]=l);u.sort(e)}return new on(i,this._parents).order()}function GL(r,e){return r<e?-1:r>e?1:r>=e?0:NaN}function VL(){var r=arguments[0];return arguments[0]=this,r.apply(null,arguments),this}function $L(){return Array.from(this)}function zL(){for(var r=this._groups,e=0,t=r.length;e<t;++e)for(var n=r[e],i=0,s=n.length;i<s;++i){var o=n[i];if(o)return o}return null}function WL(){let r=0;for(const e of this)++r;return r}function HL(){return!this.node()}function jL(r){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var i=e[t],s=0,o=i.length,a;s<o;++s)(a=i[s])&&r.call(a,a.__data__,s,i);return this}function qL(r){return function(){this.removeAttribute(r)}}function XL(r){return function(){this.removeAttributeNS(r.space,r.local)}}function KL(r,e){return function(){this.setAttribute(r,e)}}function YL(r,e){return function(){this.setAttributeNS(r.space,r.local,e)}}function QL(r,e){return function(){var t=e.apply(this,arguments);t==null?this.removeAttribute(r):this.setAttribute(r,t)}}function ZL(r,e){return function(){var t=e.apply(this,arguments);t==null?this.removeAttributeNS(r.space,r.local):this.setAttributeNS(r.space,r.local,t)}}function JL(r,e){var t=Jb(r);if(arguments.length<2){var n=this.node();return t.local?n.getAttributeNS(t.space,t.local):n.getAttribute(t)}return this.each((e==null?t.local?XL:qL:typeof e=="function"?t.local?ZL:QL:t.local?YL:KL)(t,e))}function ix(r){return r.ownerDocument&&r.ownerDocument.defaultView||r.document&&r||r.defaultView}function e2(r){return function(){this.style.removeProperty(r)}}function t2(r,e,t){return function(){this.style.setProperty(r,e,t)}}function n2(r,e,t){return function(){var n=e.apply(this,arguments);n==null?this.style.removeProperty(r):this.style.setProperty(r,n,t)}}function r2(r,e,t){return arguments.length>1?this.each((e==null?e2:typeof e=="function"?n2:t2)(r,e,t??"")):i2(this.node(),r)}function i2(r,e){return r.style.getPropertyValue(e)||ix(r).getComputedStyle(r,null).getPropertyValue(e)}function s2(r){return function(){delete this[r]}}function o2(r,e){return function(){this[r]=e}}function a2(r,e){return function(){var t=e.apply(this,arguments);t==null?delete this[r]:this[r]=t}}function u2(r,e){return arguments.length>1?this.each((e==null?s2:typeof e=="function"?a2:o2)(r,e)):this.node()[r]}function sx(r){return r.trim().split(/^|\s+/)}function Yd(r){return r.classList||new ox(r)}function ox(r){this._node=r,this._names=sx(r.getAttribute("class")||"")}ox.prototype={add:function(r){var e=this._names.indexOf(r);e<0&&(this._names.push(r),this._node.setAttribute("class",this._names.join(" ")))},remove:function(r){var e=this._names.indexOf(r);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(r){return this._names.indexOf(r)>=0}};function ax(r,e){for(var t=Yd(r),n=-1,i=e.length;++n<i;)t.add(e[n])}function ux(r,e){for(var t=Yd(r),n=-1,i=e.length;++n<i;)t.remove(e[n])}function l2(r){return function(){ax(this,r)}}function c2(r){return function(){ux(this,r)}}function h2(r,e){return function(){(e.apply(this,arguments)?ax:ux)(this,r)}}function d2(r,e){var t=sx(r+"");if(arguments.length<2){for(var n=Yd(this.node()),i=-1,s=t.length;++i<s;)if(!n.contains(t[i]))return!1;return!0}return this.each((typeof e=="function"?h2:e?l2:c2)(t,e))}function f2(){this.textContent=""}function p2(r){return function(){this.textContent=r}}function g2(r){return function(){var e=r.apply(this,arguments);this.textContent=e??""}}function m2(r){return arguments.length?this.each(r==null?f2:(typeof r=="function"?g2:p2)(r)):this.node().textContent}function _2(){this.innerHTML=""}function y2(r){return function(){this.innerHTML=r}}function b2(r){return function(){var e=r.apply(this,arguments);this.innerHTML=e??""}}function x2(r){return arguments.length?this.each(r==null?_2:(typeof r=="function"?b2:y2)(r)):this.node().innerHTML}function v2(){this.nextSibling&&this.parentNode.appendChild(this)}function T2(){return this.each(v2)}function S2(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function w2(){return this.each(S2)}function R2(r){var e=typeof r=="function"?r:ex(r);return this.select(function(){return this.appendChild(e.apply(this,arguments))})}function A2(){return null}function N2(r,e){var t=typeof r=="function"?r:ex(r),n=e==null?A2:typeof e=="function"?e:tx(e);return this.select(function(){return this.insertBefore(t.apply(this,arguments),n.apply(this,arguments)||null)})}function E2(){var r=this.parentNode;r&&r.removeChild(this)}function C2(){return this.each(E2)}function M2(){var r=this.cloneNode(!1),e=this.parentNode;return e?e.insertBefore(r,this.nextSibling):r}function P2(){var r=this.cloneNode(!0),e=this.parentNode;return e?e.insertBefore(r,this.nextSibling):r}function B2(r){return this.select(r?P2:M2)}function F2(r){return arguments.length?this.property("__data__",r):this.node().__data__}function D2(r){return function(e){r.call(this,e,this.__data__)}}function L2(r){return r.trim().split(/^|\s+/).map(function(e){var t="",n=e.indexOf(".");return n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}function O2(r){return function(){var e=this.__on;if(e){for(var t=0,n=-1,i=e.length,s;t<i;++t)s=e[t],(!r.type||s.type===r.type)&&s.name===r.name?this.removeEventListener(s.type,s.listener,s.options):e[++n]=s;++n?e.length=n:delete this.__on}}}function U2(r,e,t){return function(){var n=this.__on,i,s=D2(e);if(n){for(var o=0,a=n.length;o<a;++o)if((i=n[o]).type===r.type&&i.name===r.name){this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=s,i.options=t),i.value=e;return}}this.addEventListener(r.type,s,t),i={type:r.type,name:r.name,value:e,listener:s,options:t},n?n.push(i):this.__on=[i]}}function I2(r,e,t){var n=L2(r+""),i,s=n.length,o;if(arguments.length<2){var a=this.node().__on;if(a){for(var u=0,l=a.length,c;u<l;++u)for(i=0,c=a[u];i<s;++i)if((o=n[i]).type===c.type&&o.name===c.name)return c.value}return}for(a=e?U2:O2,i=0;i<s;++i)this.each(a(n[i],e,t));return this}function lx(r,e,t){var n=ix(r),i=n.CustomEvent;typeof i=="function"?i=new i(e,t):(i=n.document.createEvent("Event"),t?(i.initEvent(e,t.bubbles,t.cancelable),i.detail=t.detail):i.initEvent(e,!1,!1)),r.dispatchEvent(i)}function k2(r,e){return function(){return lx(this,r,e)}}function G2(r,e){return function(){return lx(this,r,e.apply(this,arguments))}}function V2(r,e){return this.each((typeof e=="function"?G2:k2)(r,e))}function*$2(){for(var r=this._groups,e=0,t=r.length;e<t;++e)for(var n=r[e],i=0,s=n.length,o;i<s;++i)(o=n[i])&&(yield o)}var z2=[null];function on(r,e){this._groups=r,this._parents=e}function W2(){return this}on.prototype={constructor:on,select:dL,selectAll:_L,selectChild:TL,selectChildren:AL,filter:NL,data:FL,enter:EL,exit:LL,join:OL,merge:UL,selection:W2,order:IL,sort:kL,call:VL,nodes:$L,node:zL,size:WL,empty:HL,each:jL,attr:JL,style:r2,property:u2,classed:d2,text:m2,html:x2,raise:T2,lower:w2,append:R2,insert:N2,remove:C2,clone:B2,datum:F2,on:I2,dispatch:V2,[Symbol.iterator]:$2};function H2(r){return typeof r=="string"?new on([[document.querySelector(r)]],[document.documentElement]):new on([[r]],z2)}function j2(r){let e;for(;e=r.sourceEvent;)r=e;return r}function q2(r,e){if(r=j2(r),e===void 0&&(e=r.currentTarget),e){var t=e.ownerSVGElement||e;if(t.createSVGPoint){var n=t.createSVGPoint();return n.x=r.clientX,n.y=r.clientY,n=n.matrixTransform(e.getScreenCTM().inverse()),[n.x,n.y]}if(e.getBoundingClientRect){var i=e.getBoundingClientRect();return[r.clientX-i.left-e.clientLeft,r.clientY-i.top-e.clientTop]}}return[r.pageX,r.pageY]}var Vo,Ue,cx,hx,Pr,qg,dx,fx,Sc,Ja,mo,px,Qd,Vh,$h,Mu={},Pu=[],X2=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,ol=Array.isArray;function Fn(r,e){for(var t in e)r[t]=e[t];return r}function Zd(r){r&&r.parentNode&&r.parentNode.removeChild(r)}function K2(r,e,t){var n,i,s,o={};for(s in e)s=="key"?n=e[s]:s=="ref"?i=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?Vo.call(arguments,2):t),typeof r=="function"&&r.defaultProps!=null)for(s in r.defaultProps)o[s]===void 0&&(o[s]=r.defaultProps[s]);return _o(r,o,n,i,null)}function _o(r,e,t,n,i){var s={type:r,props:e,key:t,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++cx,__i:-1,__u:0};return i==null&&Ue.vnode!=null&&Ue.vnode(s),s}function al(r){return r.children}function eu(r,e){this.props=r,this.context=e}function vi(r,e){if(e==null)return r.__?vi(r.__,r.__i+1):null;for(var t;e<r.__k.length;e++)if((t=r.__k[e])!=null&&t.__e!=null)return t.__e;return typeof r.type=="function"?vi(r):null}function Y2(r){if(r.__P&&r.__d){var e=r.__v,t=e.__e,n=[],i=[],s=Fn({},e);s.__v=e.__v+1,Ue.vnode&&Ue.vnode(s),Jd(r.__P,s,e,r.__n,r.__P.namespaceURI,32&e.__u?[t]:null,n,t??vi(e),!!(32&e.__u),i),s.__v=e.__v,s.__.__k[s.__i]=s,bx(n,s,i),e.__e=e.__=null,s.__e!=t&&gx(s)}}function gx(r){if((r=r.__)!=null&&r.__c!=null)return r.__e=r.__c.base=null,r.__k.some(function(e){if(e!=null&&e.__e!=null)return r.__e=r.__c.base=e.__e}),gx(r)}function Xg(r){(!r.__d&&(r.__d=!0)&&Pr.push(r)&&!Bu.__r++||qg!=Ue.debounceRendering)&&((qg=Ue.debounceRendering)||dx)(Bu)}function Bu(){try{for(var r,e=1;Pr.length;)Pr.length>e&&Pr.sort(fx),r=Pr.shift(),e=Pr.length,Y2(r)}finally{Pr.length=Bu.__r=0}}function mx(r,e,t,n,i,s,o,a,u,l,c){var h,d,f,p,g,_,m=n&&n.__k||Pu,y=e.length;for(u=Q2(t,e,m,u,y),h=0;h<y;h++)(f=t.__k[h])!=null&&(d=f.__i!=-1&&m[f.__i]||Mu,f.__i=h,_=Jd(r,f,d,i,s,o,a,u,l,c),p=f.__e,f.ref&&d.ref!=f.ref&&(d.ref&&ef(d.ref,null,f),c.push(f.ref,f.__c||p,f)),g==null&&p!=null&&(g=p),4&f.__u?(u=_x(f,u,r),d.__e&&(d.__e=null)):typeof f.type=="function"&&_!==void 0?u=_:p&&(u=p.nextSibling),f.__u&=-7);return t.__e=g,u}function Q2(r,e,t,n,i){var s,o,a,u,l,c=t.length,h=c,d=0;for(r.__k=new Array(i),s=0;s<i;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?o=r.__k[s]=_o(null,o,null,null,null):ol(o)?o=r.__k[s]=_o(al,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=r.__k[s]=_o(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):r.__k[s]=o,u=s+d,o.__=r,o.__b=r.__b+1,a=null,(l=o.__i=Z2(o,t,u,h))!=-1&&(h--,(a=t[l])&&(a.__u|=2)),a==null||a.__v==null?(l==-1&&(i>c?d--:i<c&&d++),typeof o.type!="function"&&(o.__u|=4)):l!=u&&(l==u-1?d--:l==u+1?d++:(l>u?d--:d++,o.__u|=4))):r.__k[s]=null;if(h)for(s=0;s<c;s++)(a=t[s])!=null&&(2&a.__u)==0&&(a.__e==n&&(n=vi(a)),vx(a,a));return n}function _x(r,e,t){var n,i;if(typeof r.type=="function"){for(n=r.__k,i=0;n&&i<n.length;i++)n[i]&&(n[i].__=r,e=_x(n[i],e,t));return e}r.__e!=e&&(e&&r.type&&!e.parentNode&&(e=vi(r)),e=t.insertBefore(r.__e,e||null));do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Z2(r,e,t,n){var i,s,o,a=r.key,u=r.type,l=e[t],c=l!=null&&(2&l.__u)==0;if(l===null&&a==null||c&&a==l.key&&u==l.type)return t;if(n>(c?1:0)){for(i=t-1,s=t+1;i>=0||s<e.length;)if((l=e[o=i>=0?i--:s++])!=null&&(2&l.__u)==0&&a==l.key&&u==l.type)return o}return-1}function Kg(r,e,t){e[0]=="-"?r.setProperty(e,t??""):r[e]=t==null?"":typeof t!="number"||X2.test(e)?t:t+"px"}function Ia(r,e,t,n,i){var s,o;e:if(e=="style")if(typeof t=="string")r.style.cssText=t;else{if(typeof n=="string"&&(r.style.cssText=n=""),n)for(e in n)t&&e in t||Kg(r.style,e,"");if(t)for(e in t)n&&t[e]==n[e]||Kg(r.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(px,"$1")),o=e.toLowerCase(),e=o in r||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),r.l||(r.l={}),r.l[e+s]=t,t?n?t[mo]=n[mo]:(t[mo]=Qd,r.addEventListener(e,s?$h:Vh,s)):r.removeEventListener(e,s?$h:Vh,s);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in r)try{r[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?r.removeAttribute(e):r.setAttribute(e,e=="popover"&&t==1?"":t))}}function Yg(r){return function(e){if(this.l){var t=this.l[e.type+r];if(e[Ja]==null)e[Ja]=Qd++;else if(e[Ja]<t[mo])return;return t(Ue.event?Ue.event(e):e)}}}function Jd(r,e,t,n,i,s,o,a,u,l){var c,h,d,f,p,g,_,m,y,b,T,x,v,w,R,F,M=e.type;if(e.constructor!==void 0)return null;128&t.__u&&(u=!!(32&t.__u),s=[a=e.__e=t.__e]),(c=Ue.__b)&&c(e);e:if(typeof M=="function"){h=o.length;try{if(y=e.props,b=M.prototype&&M.prototype.render,T=(c=M.contextType)&&n[c.__c],x=c?T?T.props.value:c.__:n,t.__c?m=(d=e.__c=t.__c).__=d.__E:(b?e.__c=d=new M(y,x):(e.__c=d=new eu(y,x),d.constructor=M,d.render=eO),T&&T.sub(d),d.state||(d.state={}),d.__n=n,f=d.__d=!0,d.__h=[],d._sb=[]),b&&d.__s==null&&(d.__s=d.state),b&&M.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Fn({},d.__s)),Fn(d.__s,M.getDerivedStateFromProps(y,d.__s))),p=d.props,g=d.state,d.__v=e,f)b&&M.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),b&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(b&&M.getDerivedStateFromProps==null&&y!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(y,x),e.__v==t.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(y,d.__s,x)===!1){e.__v!=t.__v&&(d.props=y,d.state=d.__s,d.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(O){O&&(O.__=e)}),Pu.push.apply(d.__h,d._sb),d._sb=[],d.__h.length&&o.push(d),a=vi(t);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(y,d.__s,x),b&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(p,g,_)})}if(d.context=x,d.props=y,d.__P=r,d.__e=!1,v=Ue.__r,w=0,b)d.state=d.__s,d.__d=!1,v&&v(e),c=d.render(d.props,d.state,d.context),Pu.push.apply(d.__h,d._sb),d._sb=[];else do d.__d=!1,v&&v(e),c=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++w<25);d.state=d.__s,d.getChildContext!=null&&(n=Fn(Fn({},n),d.getChildContext())),b&&!f&&d.getSnapshotBeforeUpdate!=null&&(_=d.getSnapshotBeforeUpdate(p,g)),R=c!=null&&c.type===al&&c.key==null?xx(c.props.children):c,a=mx(r,ol(R)?R:[R],e,t,n,i,s,o,a,u,l),d.base=e.__e,e.__u&=-161,d.__h.length&&o.push(d),m&&(d.__E=d.__=null)}catch(O){if(o.length=h,e.__v=null,u||s!=null){if(O.then){for(e.__u|=u?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;s!=null&&(s[s.indexOf(a)]=null),e.__e=a}else if(s!=null)for(F=s.length;F--;)Zd(s[F])}else e.__e=t.__e;e.__k==null&&(e.__k=t.__k||[]),O.then||yx(e),Ue.__e(O,e,t)}}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):a=e.__e=J2(t.__e,e,t,n,i,s,o,u,l);return(c=Ue.diffed)&&c(e),128&e.__u?void 0:a}function yx(r){r&&(r.__c&&(r.__c.__e=!0),r.__k&&r.__k.some(yx))}function bx(r,e,t){for(var n=0;n<t.length;n++)ef(t[n],t[++n],t[++n]);Ue.__c&&Ue.__c(e,r),r.some(function(i){try{r=i.__h,i.__h=[],r.some(function(s){s.call(i)})}catch(s){Ue.__e(s,i.__v)}})}function xx(r){return typeof r!="object"||r==null||r.__b>0?r:ol(r)?r.map(xx):r.constructor!==void 0?null:Fn({},r)}function J2(r,e,t,n,i,s,o,a,u){var l,c,h,d,f,p,g,_=t.props||Mu,m=e.props,y=e.type;if(y=="svg"?i="http://www.w3.org/2000/svg":y=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((f=s[l])&&"setAttribute"in f==!!y&&(y?f.localName==y:f.nodeType==3)){r=f,s[l]=null;break}}if(r==null){if(y==null)return document.createTextNode(m);r=document.createElementNS(i,y,m.is&&m),a&&(Ue.__m&&Ue.__m(e,s),a=!1),s=null}if(y==null)_===m||a&&r.data==m||(r.data=m);else{if(s=y=="textarea"&&m.defaultValue!=null?null:s&&Vo.call(r.childNodes),!a&&s!=null)for(_={},l=0;l<r.attributes.length;l++)_[(f=r.attributes[l]).name]=f.value;for(l in _)f=_[l],l=="dangerouslySetInnerHTML"?h=f:l=="children"||l in m||l=="value"&&"defaultValue"in m||l=="checked"&&"defaultChecked"in m||Ia(r,l,null,f,i);for(l in m)f=m[l],l=="children"?d=f:l=="dangerouslySetInnerHTML"?c=f:l=="value"?p=f:l=="checked"?g=f:a&&typeof f!="function"||_[l]===f||Ia(r,l,f,_[l],i);if(c)a||h&&(c.__html==h.__html||c.__html==r.innerHTML)||(r.innerHTML=c.__html),e.__k=[];else if(h&&(r.innerHTML=""),mx(e.type=="template"?r.content:r,ol(d)?d:[d],e,t,n,y=="foreignObject"?"http://www.w3.org/1999/xhtml":i,s,o,s?s[0]:t.__k&&vi(t,0),a,u),s!=null)for(l=s.length;l--;)Zd(s[l]);a&&y!="textarea"||(l="value",y=="progress"&&p==null?r.removeAttribute("value"):p!=null&&(p!==r[l]||y=="progress"&&!p||y=="option"&&p!=_[l])&&Ia(r,l,p,_[l],i),l="checked",g!=null&&g!=r[l]&&Ia(r,l,g,_[l],i))}return r}function ef(r,e,t){try{if(typeof r=="function"){var n=typeof r.__u=="function";n&&r.__u(),n&&e==null||(r.__u=r(e))}else r.current=e}catch(i){Ue.__e(i,t)}}function vx(r,e,t){var n,i;if(Ue.unmount&&Ue.unmount(r),(n=r.ref)&&(n.current&&n.current!=r.__e||ef(n,null,e)),(n=r.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(s){Ue.__e(s,e)}n.base=n.__P=n.__n=null}if(n=r.__k)for(i=0;i<n.length;i++)n[i]&&vx(n[i],e,t||typeof r.type!="function");t||Zd(r.__e),r.__c=r.__=r.__e=void 0}function eO(r,e,t){return this.constructor(r,t)}function tO(r,e,t){var n,i,s,o;e==document&&(e=document.documentElement),Ue.__&&Ue.__(r,e),i=(n=!1)?null:e.__k,s=[],o=[],Jd(e,r=e.__k=K2(al,null,[r]),i||Mu,Mu,e.namespaceURI,i?null:e.firstChild?Vo.call(e.childNodes):null,s,i?i.__e:e.firstChild,n,o),bx(s,r,o),r.props.children=null}function Tx(r,e,t){var n,i,s,o,a=Fn({},r.props);for(s in r.type&&r.type.defaultProps&&(o=r.type.defaultProps),e)s=="key"?n=e[s]:s=="ref"?i=e[s]:a[s]=e[s]===void 0&&o!=null?o[s]:e[s];return arguments.length>2&&(a.children=arguments.length>3?Vo.call(arguments,2):t),_o(r.type,a,n||r.key,i||r.ref,null)}Vo=Pu.slice,Ue={__e:function(r,e,t,n){for(var i,s,o;e=e.__;)if((i=e.__c)&&!i.__)try{if((s=i.constructor)&&s.getDerivedStateFromError!=null&&(i.setState(s.getDerivedStateFromError(r)),o=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(r,n||{}),o=i.__d),o)return i.__E=i}catch(a){r=a}throw r}},cx=0,hx=function(r){return r!=null&&r.constructor===void 0},eu.prototype.setState=function(r,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Fn({},this.state),typeof r=="function"&&(r=r(Fn({},t),this.props)),r&&Fn(t,r),r!=null&&this.__v&&(e&&this._sb.push(e),Xg(this))},eu.prototype.forceUpdate=function(r){this.__v&&(this.__e=!0,r&&this.__h.push(r),Xg(this))},eu.prototype.render=al,Pr=[],dx=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,fx=function(r,e){return r.__v.__b-e.__v.__b},Bu.__r=0,Sc=Math.random().toString(8),Ja="__d"+Sc,mo="__a"+Sc,px=/(PointerCapture)$|Capture$/i,Qd=0,Vh=Yg(!1),$h=Yg(!0);function Qg(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function nO(r){if(Array.isArray(r))return r}function rO(r,e,t){return(e=lO(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function iO(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n,i,s,o,a=[],u=!0,l=!1;try{if(s=(t=t.call(r)).next,e!==0)for(;!(u=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,i=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw i}}return a}}function sO(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1108
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Zg(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function oO(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Zg(Object(t),!0).forEach(function(n){rO(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Zg(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function aO(r,e){return nO(r)||iO(r,e)||cO(r,e)||sO()}function uO(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function lO(r){var e=uO(r,"string");return typeof e=="symbol"?e:e+""}function Fu(r){"@babel/helpers - typeof";return Fu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Fu(r)}function cO(r,e){if(r){if(typeof r=="string")return Qg(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Qg(r,e):void 0}}var zh=function(e){if(Fu(e)!=="object")return e;var t=Tx(e);if(t.props){var n;t.props=oO({},t.props),t!=null&&(n=t.props)!==null&&n!==void 0&&n.children&&(t.props.children=Array.isArray(t.props.children)?t.props.children.map(zh):zh(t.props.children))}return t},hO=function(e){return hx(Tx(e))},dO=function(e,t){delete t.__k,tO(zh(e),t)};function fO(r,e){e===void 0&&(e={});var t=e.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css",t==="top"&&n.firstChild?n.insertBefore(i,n.firstChild):n.appendChild(i),i.styleSheet?i.styleSheet.cssText=r:i.appendChild(document.createTextNode(r))}}var pO=`.float-tooltip-kap {
1109
+ position: absolute;
1110
+ width: max-content; /* prevent shrinking near right edge */
1111
+ max-width: max(50%, 150px);
1112
+ padding: 3px 5px;
1113
+ border-radius: 3px;
1114
+ font: 12px sans-serif;
1115
+ color: #eee;
1116
+ background: rgba(0,0,0,0.6);
1117
+ pointer-events: none;
1118
+ }
1119
+ `;fO(pO);var gO=$u({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=n.style,s=i===void 0?{}:i,o=!!e&&Fu(e)==="object"&&!!e.node&&typeof e.node=="function",a=H2(o?e.node():e);a.style("position")==="static"&&a.style("position","relative"),t.tooltipEl=a.append("div").attr("class","float-tooltip-kap"),Object.entries(s).forEach(function(l){var c=aO(l,2),h=c[0],d=c[1];return t.tooltipEl.style(h,d)}),t.tooltipEl.style("left","-10000px").style("display","none");var u="tooltip-".concat(Math.round(Math.random()*1e12));t.mouseInside=!1,a.on("mousemove.".concat(u),function(l){t.mouseInside=!0;var c=q2(l),h=a.node(),d=h.offsetWidth,f=h.offsetHeight,p=[t.offsetX===null||t.offsetX===void 0?"-".concat(c[0]/d*100,"%"):typeof t.offsetX=="number"?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,t.offsetY===null||t.offsetY===void 0?f>130&&f-c[1]<100?"calc(-100% - 6px)":"21px":typeof t.offsetY=="number"?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",c[0]+"px").style("top",c[1]+"px").style("transform","translate(".concat(p.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),a.on("mouseover.".concat(u),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),a.on("mouseout.".concat(u),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append(function(){return e.content})):typeof e.content=="string"?e.tooltipEl.html(e.content):hO(e.content)?(e.tooltipEl.text(""),dO(e.content,e.tooltipEl.node())):(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):e.tooltipEl.text("")}});function mO(r,e){e===void 0&&(e={});var t=e.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css",t==="top"&&n.firstChild?n.insertBefore(i,n.firstChild):n.appendChild(i),i.styleSheet?i.styleSheet.cssText=r:i.appendChild(document.createTextNode(r))}}var _O=`.scene-nav-info {
1120
+ position: absolute;
1121
+ bottom: 5px;
1122
+ width: 100%;
1123
+ text-align: center;
1124
+ color: slategrey;
1125
+ opacity: 0.7;
1126
+ font-size: 10px;
1127
+ font-family: sans-serif;
1128
+ pointer-events: none;
1129
+ user-select: none;
1130
+ }
1131
+
1132
+ .scene-container canvas:focus {
1133
+ outline: none;
1134
+ }`;mO(_O);function Wh(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function yO(r){if(Array.isArray(r))return r}function bO(r){if(Array.isArray(r))return Wh(r)}function xO(r,e,t){return(e=NO(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function vO(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function TO(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n,i,s,o,a=[],u=!0,l=!1;try{if(s=(t=t.call(r)).next,e!==0)for(;!(u=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);u=!0);}catch(c){l=!0,i=c}finally{try{if(!u&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw i}}return a}}function SO(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1135
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function wO(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
1136
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function RO(r,e){return yO(r)||TO(r,e)||Sx(r,e)||SO()}function ti(r){return bO(r)||vO(r)||Sx(r)||wO()}function AO(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function NO(r){var e=AO(r,"string");return typeof e=="symbol"?e:e+""}function Sx(r,e){if(r){if(typeof r=="string")return Wh(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Wh(r,e):void 0}}var wx=function(e){e instanceof Array?e.forEach(wx):(e.map&&e.map.dispose(),e.dispose())},Rx=function(e){e.geometry&&e.geometry.dispose(),e.material&&wx(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Rx)},EO=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),Rx(t)}},Le=window.THREE?window.THREE:{WebGLRenderer:Kv,Scene:Kh,PerspectiveCamera:yo,Raycaster:em,SRGBColorSpace:Xh,TextureLoader:Xv,Vector2:de,Vector3:z,Box3:im,Color:Dt,Mesh:yn,SphereGeometry:qh,MeshBasicMaterial:Br,BackSide:yt,Timer:Xm},Ax=$u({props:{width:{default:window.innerWidth,onChange:function(e,t,n){isNaN(e)&&(t.width=n)}},height:{default:window.innerHeight,onChange:function(e,t,n){isNaN(e)&&(t.height=n)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange:function(e,t){t.hoverObj=null,t.tooltip&&t.tooltip.content(null)},triggerUpdate:!1},pointerRaycasterThrottleMs:{default:50,triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},pointsHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{triggerUpdate:!1},hoverFilter:{default:function(){return!0},triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:function(){},triggerUpdate:!1},onClick:{default:function(){},triggerUpdate:!1},onRightClick:{triggerUpdate:!1}},methods:{tick:function(e){if(e.initialised){e.controls.enabled&&e.controls.update&&e.controls.update(Math.min(1,e.timer.update().getDelta())),e.postProcessingComposer?e.postProcessingComposer.render():e.renderer.render(e.scene,e.camera),e.extraRenderers.forEach(function(o){return o.render(e.scene,e.camera)});var t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var n=null;if(e.hoverDuringDrag||!e.isPointerDragging){var i=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&i.sort(function(o,a){return e.hoverOrderComparator(o.object,a.object)});var s=i.find(function(o){return e.hoverFilter(o.object)})||null;n=s?s.object:null,e.intersection=s||null}n!==e.hoverObj&&(e.onHover(n,e.hoverObj,e.intersection),e.tooltip.content(n&&pe(e.tooltipContent)(n,e.intersection)||null),e.hoverObj=n)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos,n=t.x,i=t.y;return{x:n,y:i}},cameraPosition:function(e,t,n,i){var s=e.camera;if(t&&e.initialised){var o,a,u=t,l=n||{x:0,y:0,z:0};if((o=e.povPosTween)===null||o===void 0||o.end(),(a=e.povTgtTween)===null||a===void 0||a.end(),!i)d(u),f(l);else{var c=Object.assign({},s.position),h=p();e.tweenGroup.add(e.povPosTween=new Hg(c).to(u,i).easing(pi.Quadratic.Out).onUpdate(d).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new Hg(h).to(l,i/3).easing(pi.Quadratic.Out).onUpdate(f).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}return this}return Object.assign({},s.position,{lookAt:p()});function d(g){var _=g.x,m=g.y,y=g.z;_!==void 0&&(s.position.x=_),m!==void 0&&(s.position.y=m),y!==void 0&&(s.position.z=y)}function f(g){var _=new Le.Vector3(g.x,g.y,g.z);e.controls.enabled&&e.controls.target?e.controls.target=_:s.lookAt(_)}function p(){return Object.assign(new Le.Vector3(0,0,-1e3).applyQuaternion(s.quaternion).add(s.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:10,i=arguments.length,s=new Array(i>3?i-3:0),o=3;o<i;o++)s[o-3]=arguments[o];return this.fitToBbox(this.getBbox.apply(this,s),t,n)},fitToBbox:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:10,s=e.camera;if(t){var o=new Le.Vector3(0,0,0),a=Math.max.apply(Math,ti(Object.entries(t).map(function(f){var p=RO(f,2),g=p[0],_=p[1];return Math.max.apply(Math,ti(_.map(function(m){return Math.abs(o[g]-m)})))})))*2,u=(1-i*2/e.height)*s.fov,l=a/Math.atan(u*Math.PI/180),c=l/s.aspect,h=Math.max(l,c);if(h>0){var d=o.clone().sub(s.position).normalize().multiplyScalar(-h);this.cameraPosition(d,o,n)}}return this},getBbox:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){return!0},n=new Le.Box3(new Le.Vector3(0,0,0),new Le.Vector3(0,0,0)),i=e.objects.filter(t);return i.length?(i.forEach(function(s){return n.expandByObject(s)}),Object.assign.apply(Object,ti(["x","y","z"].map(function(s){return xO({},s,[n.min[s],n.max[s]])})))):null},getScreenCoords:function(e,t,n,i){var s=new Le.Vector3(t,n,i);return s.project(this.camera()),{x:(s.x+1)*e.width/2,y:-(s.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,s=new Le.Vector2(t/e.width*2-1,-(n/e.height)*2+1),o=new Le.Raycaster;return o.setFromCamera(s,e.camera),Object.assign({},o.ray.at(i,new Le.Vector3))},intersectingObjects:function(e,t,n){var i=new Le.Vector2(t/e.width*2-1,-(n/e.height)*2+1),s=new Le.Raycaster;return s.params.Line.threshold=e.lineHoverPrecision,s.params.Points.threshold=e.pointsHoverPrecision,s.setFromCamera(i,e.camera),s.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls},_destructor:function(e){var t,n,i;EO(e.scene),(t=e.controls)===null||t===void 0||t.dispose(),(n=e.renderer)===null||n===void 0||n.dispose(),(i=e.postProcessingComposer)===null||i===void 0||i.dispose()}},stateInit:function(){return{scene:new Le.Scene,camera:new Le.PerspectiveCamera,timer:new Le.Timer,tweenGroup:new Qb,lastRaycasterCheck:0}},init:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=n.controlType,s=i===void 0?"trackball":i,o=n.useWebGPU,a=o===void 0?!1:o,u=n.rendererConfig,l=u===void 0?{}:u,c=n.extraRenderers,h=c===void 0?[]:c,d=n.waitForLoadComplete,f=d===void 0?!0:d;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[s]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new gO(t.container),t.pointerPos=new Le.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(p){return t.container.addEventListener(p,function(g){if(p==="pointerdown"&&(t.isPointerPressed=!0),!t.isPointerDragging&&g.type==="pointermove"&&(g.pressure>0||t.isPointerPressed)&&(g.pointerType==="mouse"||g.movementX===void 0||[g.movementX,g.movementY].some(function(y){return Math.abs(y)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var _=m(t.container);t.pointerPos.x=g.pageX-_.left,t.pointerPos.y=g.pageY-_.top}function m(y){var b=y.getBoundingClientRect(),T=window.pageXOffset||document.documentElement.scrollLeft,x=window.pageYOffset||document.documentElement.scrollTop;return{top:b.top+x,left:b.left+T}}},{passive:!0})}),t.container.addEventListener("pointerup",function(p){t.isPointerPressed&&(t.isPointerPressed=!1,!(t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag))&&requestAnimationFrame(function(){p.button===0&&t.onClick(t.hoverObj||null,p,t.intersection),p.button===2&&t.onRightClick&&t.onRightClick(t.hoverObj||null,p,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",function(p){t.onRightClick&&p.preventDefault()}),t.renderer=new(a?MF:Le.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},l)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=h,t.extraRenderers.forEach(function(p){p.domElement.style.position="absolute",p.domElement.style.top="0px",p.domElement.style.pointerEvents="none",t.container.appendChild(p.domElement)}),t.postProcessingComposer=new SD(t.renderer),t.postProcessingComposer.addPass(new wD(t.scene,t.camera)),t.controls=new{trackball:BF,orbit:XF,fly:uD}[s](t.camera,t.renderer.domElement),s==="fly"&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),(s==="trackball"||s==="orbit")&&(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",function(){t.controlsEngaged=!0}),t.controls.addEventListener("change",function(){t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",function(){t.controlsEngaged=!1,t.controlsDragging=!1})),[t.renderer,t.postProcessingComposer].concat(ti(t.extraRenderers)).forEach(function(p){return p.setSize(t.width,t.height)}),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new Le.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!f,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,i=e.width,s=e.height;e.container.style.width="".concat(i,"px"),e.container.style.height="".concat(s,"px"),[e.renderer,e.postProcessingComposer].concat(ti(e.extraRenderers)).forEach(function(f){return f.setSize(i,s)}),e.camera.aspect=i/s;var o=e.viewOffset.slice(0,2);o.some(function(f){return f})&&(n=e.camera).setViewOffset.apply(n,[i,s].concat(ti(o),[i,s])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,u=e.width,l=e.height,c=e.viewOffset.slice(0,2);c.some(function(f){return f})?(a=e.camera).setViewOffset.apply(a,[u,l].concat(ti(c),[u,l])):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=e.skyRadius*2.5,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new Le.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var h=ps(e.backgroundColor).alpha;h===void 0&&(h=1),e.renderer.setClearColor(new Le.Color(tL(1,e.backgroundColor)),h)}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?new Le.TextureLoader().load(e.backgroundImageUrl,function(f){f.colorSpace=Le.SRGBColorSpace,e.skysphere.material=new Le.MeshBasicMaterial({map:f,side:Le.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&d()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&d())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(function(f){return e.scene.remove(f)}),e.lights.forEach(function(f){return e.scene.add(f)})),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(function(f){return e.scene.remove(f)}),e.objects.forEach(function(f){return e.scene.add(f)}));function d(){e.loadComplete=e.scene.visible=!0}}});function CO(r,e){e===void 0&&(e={});var t=e.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css",t==="top"&&n.firstChild?n.insertBefore(i,n.firstChild):n.appendChild(i),i.styleSheet?i.styleSheet.cssText=r:i.appendChild(document.createTextNode(r))}}var MO=`.graph-info-msg {
1137
+ top: 50%;
1138
+ width: 100%;
1139
+ text-align: center;
1140
+ color: lavender;
1141
+ opacity: 0.7;
1142
+ font-size: 22px;
1143
+ position: absolute;
1144
+ font-family: Sans-serif;
1145
+ }
1146
+
1147
+ .scene-container .clickable {
1148
+ cursor: pointer;
1149
+ }
1150
+
1151
+ .scene-container .grabbable {
1152
+ cursor: move;
1153
+ cursor: grab;
1154
+ cursor: -moz-grab;
1155
+ cursor: -webkit-grab;
1156
+ }
1157
+
1158
+ .scene-container .grabbable:active {
1159
+ cursor: grabbing;
1160
+ cursor: -moz-grabbing;
1161
+ cursor: -webkit-grabbing;
1162
+ }`;CO(MO);function Hh(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function PO(r){if(Array.isArray(r))return Hh(r)}function $o(r,e,t){return(e=LO(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function BO(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function FO(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
1163
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Jg(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function ka(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Jg(Object(t),!0).forEach(function(n){$o(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Jg(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function ul(r){return PO(r)||BO(r)||OO(r)||FO()}function DO(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function LO(r){var e=DO(r,"string");return typeof e=="symbol"?e:e+""}function OO(r,e){if(r){if(typeof r=="string")return Hh(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Hh(r,e):void 0}}function Nx(r,e){var t=new e;return t._destructor&&t._destructor(),{linkProp:function(i){return{default:t[i](),onChange:function(o,a){a[r][i](o)},triggerUpdate:!1}},linkMethod:function(i){return function(s){for(var o=s[r],a=arguments.length,u=new Array(a>1?a-1:0),l=1;l<a;l++)u[l-1]=arguments[l];var c=o[i].apply(o,u);return c===o?this:c}}}}var wc=window.THREE?window.THREE:{AmbientLight:am,DirectionalLight:om,REVISION:Ou},UO=170,Ex=Nx("forceGraph",E_),IO=Object.assign.apply(Object,ul(["jsonUrl","graphData","numDimensions","dagMode","dagLevelDistance","dagNodeFilter","onDagError","nodeRelSize","nodeId","nodeVal","nodeResolution","nodeColor","nodeAutoColorBy","nodeOpacity","nodeVisibility","nodeThreeObject","nodeThreeObjectExtend","nodePositionUpdate","linkSource","linkTarget","linkVisibility","linkColor","linkAutoColorBy","linkOpacity","linkWidth","linkResolution","linkCurvature","linkCurveRotation","linkMaterial","linkThreeObject","linkThreeObjectExtend","linkPositionUpdate","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowRelPos","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleSpeed","linkDirectionalParticleOffset","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject","forceEngine","d3AlphaDecay","d3VelocityDecay","d3AlphaMin","ngraphPhysics","warmupTicks","cooldownTicks","cooldownTime","onEngineTick","onEngineStop"].map(function(r){return $o({},r,Ex.linkProp(r))}))),kO=Object.assign.apply(Object,ul(["refresh","getGraphBbox","d3Force","d3ReheatSimulation","emitParticle"].map(function(r){return $o({},r,Ex.linkMethod(r))}))),tu=Nx("renderObjs",Ax),GO=Object.assign.apply(Object,ul(["width","height","backgroundColor","showNavInfo","enablePointerInteraction"].map(function(r){return $o({},r,tu.linkProp(r))}))),VO=Object.assign.apply(Object,ul(["lights","cameraPosition","postProcessingComposer"].map(function(r){return $o({},r,tu.linkMethod(r))})).concat([{graph2ScreenCoords:tu.linkMethod("getScreenCoords"),screen2GraphCoords:tu.linkMethod("getSceneCoords")}])),WO=$u({props:ka(ka({nodeLabel:{default:"name",triggerUpdate:!1},linkLabel:{default:"name",triggerUpdate:!1},linkHoverPrecision:{default:1,onChange:function(e,t){return t.renderObjs.lineHoverPrecision(e)},triggerUpdate:!1},enableNavigationControls:{default:!0,onChange:function(e,t){var n=t.renderObjs.controls();n&&(n.enabled=e,e&&n.domElement&&n.domElement.dispatchEvent(new PointerEvent("pointerup")))},triggerUpdate:!1},enableNodeDrag:{default:!0,triggerUpdate:!1},onNodeDrag:{default:function(){},triggerUpdate:!1},onNodeDragEnd:{default:function(){},triggerUpdate:!1},onNodeClick:{triggerUpdate:!1},onNodeRightClick:{triggerUpdate:!1},onNodeHover:{triggerUpdate:!1},onLinkClick:{triggerUpdate:!1},onLinkRightClick:{triggerUpdate:!1},onLinkHover:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1},onBackgroundRightClick:{triggerUpdate:!1},showPointerCursor:{default:!0,triggerUpdate:!1}},IO),GO),methods:ka(ka({zoomToFit:function(e,t,n){for(var i,s=arguments.length,o=new Array(s>3?s-3:0),a=3;a<s;a++)o[a-3]=arguments[a];return e.renderObjs.fitToBbox((i=e.forceGraph).getGraphBbox.apply(i,o),t,n),this},pauseAnimation:function(e){return e.animationFrameRequestId!==null&&(cancelAnimationFrame(e.animationFrameRequestId),e.animationFrameRequestId=null),this},resumeAnimation:function(e){return e.animationFrameRequestId===null&&this._animationCycle(),this},_animationCycle:function(e){e.enablePointerInteraction&&(this.renderer().domElement.style.cursor=null),e.forceGraph.tickFrame(),e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},scene:function(e){return e.renderObjs.scene()},camera:function(e){return e.renderObjs.camera()},renderer:function(e){return e.renderObjs.renderer()},controls:function(e){return e.renderObjs.controls()},_destructor:function(e){var t,n;this.pauseAnimation(),this.graphData({nodes:[],links:[]}),(t=(n=e.forceGraph)._destructor)===null||t===void 0||t.call(n),e.renderObjs._destructor()}},kO),VO),stateInit:function(e){var t=e.controlType,n=e.rendererConfig,i=e.extraRenderers,s=new E_;return{forceGraph:s,renderObjs:Ax({controlType:t,rendererConfig:n,extraRenderers:i}).objects([s]).lights([new wc.AmbientLight(13421772,Math.PI),new wc.DirectionalLight(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.style.position="relative";var n=document.createElement("div");t.container.appendChild(n),t.renderObjs(n);var i=t.renderObjs.camera(),s=t.renderObjs.renderer(),o=t.renderObjs.controls();o.enabled=!!t.enableNavigationControls,t.lastSetCameraZ=i.position.z;var a;t.container.appendChild(a=document.createElement("div")),a.className="graph-info-msg",a.textContent="",t.forceGraph.onLoading(function(){a.textContent="Loading..."}).onFinishLoading(function(){a.textContent=""}).onUpdate(function(){t.graphData=t.forceGraph.graphData(),i.position.x===0&&i.position.y===0&&i.position.z===t.lastSetCameraZ&&t.graphData.nodes.length&&(i.lookAt(t.forceGraph.position),t.lastSetCameraZ=i.position.z=Math.cbrt(t.graphData.nodes.length)*UO)}).onFinishUpdate(function(){if(t._dragControls){var u=t.graphData.nodes.find(function(c){return c.__initialFixedPos&&!c.__disposeControlsAfterDrag});u?u.__disposeControlsAfterDrag=!0:t._dragControls.dispose(),t._dragControls=void 0}if(t.enableNodeDrag&&t.enablePointerInteraction&&t.forceEngine==="d3"){var l=t._dragControls=new e0(t.graphData.nodes.map(function(c){return c.__threeObj}).filter(function(c){return c}),i,s.domElement);l.addEventListener("dragstart",function(c){var h=qn(c.object);if(h){o.enabled=!1,c.object.__initialPos=c.object.position.clone(),c.object.__prevPos=c.object.position.clone();var d=h.__data;!d.__initialFixedPos&&(d.__initialFixedPos={fx:d.fx,fy:d.fy,fz:d.fz}),!d.__initialPos&&(d.__initialPos={x:d.x,y:d.y,z:d.z}),["x","y","z"].forEach(function(f){return d["f".concat(f)]=d[f]}),s.domElement.classList.add("grabbable")}}),l.addEventListener("drag",function(c){var h=qn(c.object);if(h){if(!c.object.hasOwnProperty("__graphObjType")){var d=c.object.__initialPos,f=c.object.__prevPos,p=c.object.position;h.position.add(p.clone().sub(f)),f.copy(p),p.copy(d)}var g=h.__data,_=h.position,m={x:_.x-g.x,y:_.y-g.y,z:_.z-g.z};["x","y","z"].forEach(function(y){return g["f".concat(y)]=g[y]=_[y]}),t.forceGraph.d3AlphaTarget(.3).resetCountdown(),g.__dragged=!0,t.onNodeDrag(g,m)}}),l.addEventListener("dragend",function(c){var h=qn(c.object);if(h){delete c.object.__initialPos,delete c.object.__prevPos;var d=h.__data;d.__disposeControlsAfterDrag&&(l.dispose(),delete d.__disposeControlsAfterDrag);var f=d.__initialFixedPos,p=d.__initialPos,g={x:p.x-d.x,y:p.y-d.y,z:p.z-d.z};if(f&&(["x","y","z"].forEach(function(m){var y="f".concat(m);f[y]===void 0&&delete d[y]}),delete d.__initialFixedPos,delete d.__initialPos,d.__dragged&&(delete d.__dragged,t.onNodeDragEnd(d,g))),t.forceGraph.d3AlphaTarget(0).resetCountdown(),t.enableNavigationControls){var _;o.enabled=!0,o._status&&((_=o._onPointerCancel)===null||_===void 0||_.call(o)),o.domElement&&o.domElement.ownerDocument&&o.domElement.ownerDocument.dispatchEvent(new PointerEvent("pointerup",{pointerType:"touch"}))}s.domElement.classList.remove("grabbable")}})}}),wc.REVISION<155&&(t.renderObjs.renderer().useLegacyLights=!1),t.renderObjs.hoverOrderComparator(function(u,l){var c=qn(u);if(!c)return 1;var h=qn(l);if(!h)return-1;var d=function(p){return p.__graphObjType==="node"};return d(h)-d(c)}).tooltipContent(function(u){var l=qn(u);return l&&pe(t["".concat(l.__graphObjType,"Label")])(l.__data)||""}).hoverDuringDrag(!1).onHover(function(u){var l=qn(u);if(l!==t.hoverObj){var c=t.hoverObj?t.hoverObj.__graphObjType:null,h=t.hoverObj?t.hoverObj.__data:null,d=l?l.__graphObjType:null,f=l?l.__data:null;if(c&&c!==d){var p=t["on".concat(c==="node"?"Node":"Link","Hover")];p&&p(null,h)}if(d){var g=t["on".concat(d==="node"?"Node":"Link","Hover")];g&&g(f,c===d?h:null)}s.domElement.classList[(l&&t["on".concat(d==="node"?"Node":"Link","Click")]||!l&&t.onBackgroundClick)&&pe(t.showPointerCursor)(f)?"add":"remove"]("clickable"),t.hoverObj=l}}).clickAfterDrag(!1).onClick(function(u,l){var c=qn(u);if(c){var h=t["on".concat(c.__graphObjType==="node"?"Node":"Link","Click")];h&&h(c.__data,l)}else t.onBackgroundClick&&t.onBackgroundClick(l)}).onRightClick(function(u,l){var c=qn(u);if(c){var h=t["on".concat(c.__graphObjType==="node"?"Node":"Link","RightClick")];h&&h(c.__data,l)}else t.onBackgroundRightClick&&t.onBackgroundRightClick(l)}),this._animationCycle()}});function qn(r){for(var e=r;e&&!e.hasOwnProperty("__graphObjType");)e=e.parent;return e}export{WO as default};