semiotic 3.8.5 → 3.8.7

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 (277) hide show
  1. package/CLAUDE.md +37 -10
  2. package/README.md +83 -56
  3. package/ai/behaviorContracts.cjs +88 -3
  4. package/ai/componentMetadata.cjs +5 -10
  5. package/ai/dist/mcp-server.js +99 -10
  6. package/ai/examples.md +198 -9
  7. package/ai/schema.json +2002 -165
  8. package/ai/surface-manifest.json +14 -10
  9. package/ai/system-prompt.md +9 -3
  10. package/dist/{chunk-chartContainerDataAudit-74TLKIP6.module.min.js → chunk-chartContainerDataAudit-JDSVSKGM.module.min.js} +1 -1
  11. package/dist/chunk-chunk-2JGJ5GUG.module.min.js +1 -0
  12. package/dist/chunk-chunk-2YAZHXL4.module.min.js +2 -0
  13. package/dist/chunk-chunk-3NGIKFD6.module.min.js +1 -0
  14. package/dist/{chunk-chunk-G7WFWHAD.module.min.js → chunk-chunk-4ITOQRXM.module.min.js} +1 -1
  15. package/dist/chunk-chunk-5SD6BHVW.module.min.js +2 -0
  16. package/dist/chunk-chunk-6V5VQVCT.module.min.js +2 -0
  17. package/dist/chunk-chunk-7TTBHSAG.module.min.js +2 -0
  18. package/dist/chunk-chunk-7ZDJSYKI.module.min.js +2 -0
  19. package/dist/chunk-chunk-BGHPD3RA.module.min.js +1 -0
  20. package/dist/chunk-chunk-BMRZ2SPU.module.min.js +2 -0
  21. package/dist/chunk-chunk-BNGBEY7N.module.min.js +2 -0
  22. package/dist/chunk-chunk-C7APLVQD.module.min.js +2 -0
  23. package/dist/chunk-chunk-DGWFBOGB.module.min.js +1 -0
  24. package/dist/chunk-chunk-DIVE2DRA.module.min.js +2 -0
  25. package/dist/chunk-chunk-FBUNUIPV.module.min.js +2 -0
  26. package/dist/chunk-chunk-FQPKOAIH.module.min.js +2 -0
  27. package/dist/chunk-chunk-FRO4TRXK.module.min.js +2 -0
  28. package/dist/chunk-chunk-G7QVPZUD.module.min.js +2 -0
  29. package/dist/chunk-chunk-GBPYV4FP.module.min.js +2 -0
  30. package/dist/chunk-chunk-GU2EJIDJ.module.min.js +2 -0
  31. package/dist/chunk-chunk-J5QD4RAM.module.min.js +2 -0
  32. package/dist/{chunk-chunk-LJLS6DY7.module.min.js → chunk-chunk-JWXLNZSM.module.min.js} +1 -1
  33. package/dist/chunk-chunk-KXAFCCDB.module.min.js +2 -0
  34. package/dist/chunk-chunk-LG7YKJAK.module.min.js +2 -0
  35. package/dist/{chunk-chunk-I36PJ4OC.module.min.js → chunk-chunk-LVHDZAT3.module.min.js} +1 -1
  36. package/dist/chunk-chunk-LWITSR2O.module.min.js +2 -0
  37. package/dist/chunk-chunk-MX35T6RX.module.min.js +2 -0
  38. package/dist/chunk-chunk-NH4MEAKP.module.min.js +2 -0
  39. package/dist/chunk-chunk-NJETWX42.module.min.js +2 -0
  40. package/dist/chunk-chunk-NW25WGLS.module.min.js +2 -0
  41. package/dist/{chunk-chunk-TMWIZL3K.module.min.js → chunk-chunk-OI7R7EJB.module.min.js} +1 -1
  42. package/dist/chunk-chunk-ONMLEXHR.module.min.js +2 -0
  43. package/dist/chunk-chunk-OY66GCE6.module.min.js +1 -0
  44. package/dist/chunk-chunk-PZFT457G.module.min.js +1 -0
  45. package/dist/chunk-chunk-Q3WW6JGR.module.min.js +1 -0
  46. package/dist/chunk-chunk-Q6XKQTOQ.module.min.js +1 -0
  47. package/dist/chunk-chunk-RJRM2E6P.module.min.js +1 -0
  48. package/dist/chunk-chunk-RPL7WYXI.module.min.js +1 -0
  49. package/dist/chunk-chunk-SV4XAZ3Q.module.min.js +1 -0
  50. package/dist/chunk-chunk-TSCFL235.module.min.js +1 -0
  51. package/dist/chunk-chunk-UOQRPGPK.module.min.js +2 -0
  52. package/dist/chunk-chunk-V3OAKG32.module.min.js +1 -0
  53. package/dist/chunk-chunk-WLOIUMWG.module.min.js +2 -0
  54. package/dist/chunk-chunk-XEGXX4F7.module.min.js +1 -0
  55. package/dist/chunk-chunk-XFRBLXYM.module.min.js +1 -0
  56. package/dist/chunk-chunk-Z2AJERX5.module.min.js +2 -0
  57. package/dist/chunk-chunk-ZXYDYAB7.module.min.js +2 -0
  58. package/dist/components/ai/SemioticVACPBridge.d.ts +22 -0
  59. package/dist/components/ai/chartCapabilities.d.ts +5 -3
  60. package/dist/components/ai/conversationArc.d.ts +2 -176
  61. package/dist/components/ai/conversationArcTypes.d.ts +202 -0
  62. package/dist/components/ai/readerGrounding.d.ts +12 -0
  63. package/dist/components/ai/vacpAdapter.d.ts +13 -0
  64. package/dist/components/ai/vacpAdapterActions.d.ts +2 -0
  65. package/dist/components/ai/vacpAdapterModel.d.ts +7 -0
  66. package/dist/components/ai/vacpAdapterRuntime.d.ts +26 -0
  67. package/dist/components/ai/vacpAdapterState.d.ts +3 -0
  68. package/dist/components/ai/vacpAdapterTypes.d.ts +169 -0
  69. package/dist/components/ai/vacpTypes.d.ts +160 -0
  70. package/dist/components/charts/custom/XYCustomChart.d.ts +3 -0
  71. package/dist/components/charts/geo/DistanceCartogram.d.ts +1 -1
  72. package/dist/components/charts/index.d.ts +7 -4
  73. package/dist/components/charts/ordinal/BarChart.d.ts +7 -14
  74. package/dist/components/charts/ordinal/GaugeChart.d.ts +3 -0
  75. package/dist/components/charts/ordinal/GroupedBarChart.d.ts +3 -0
  76. package/dist/components/charts/ordinal/StackedBarChart.d.ts +3 -0
  77. package/dist/components/charts/ordinal/SwimlaneChart.d.ts +4 -14
  78. package/dist/components/charts/physics/ChainReactionChart.capability.d.ts +9 -0
  79. package/dist/components/charts/physics/ChainReactionChart.d.ts +29 -0
  80. package/dist/components/charts/physics/CollisionSwarmChart.d.ts +1 -1
  81. package/dist/components/charts/physics/EventDropChart.d.ts +7 -2
  82. package/dist/components/charts/physics/GaltonBoardChart.d.ts +1 -1
  83. package/dist/components/charts/physics/{PhysicsPileChart.capability.d.ts → PacketFlowChart.capability.d.ts} +1 -1
  84. package/dist/components/charts/physics/{PhysicalFlowChart.d.ts → PacketFlowChart.d.ts} +22 -6
  85. package/dist/components/charts/physics/PhysicsCustomChart.d.ts +1 -1
  86. package/dist/components/charts/physics/ProcessFlowChart.d.ts +7 -4
  87. package/dist/components/charts/physics/{PhysicalFlowChart.capability.d.ts → UnitPileChart.capability.d.ts} +1 -1
  88. package/dist/components/charts/physics/{PhysicsPileChart.d.ts → UnitPileChart.d.ts} +19 -6
  89. package/dist/components/charts/physics/crucibleChartProps.d.ts +1 -1
  90. package/dist/components/charts/physics/crucibleChartUtils.d.ts +9 -0
  91. package/dist/components/charts/physics/gauntletChartProps.d.ts +6 -1
  92. package/dist/components/charts/physics/gauntletTerminal.d.ts +61 -0
  93. package/dist/components/charts/physics/packetFlowSemantics.d.ts +6 -0
  94. package/dist/components/charts/physics/physicsHocUtils.d.ts +45 -2
  95. package/dist/components/charts/shared/auditAccessibilityStyles.d.ts +9 -0
  96. package/dist/components/charts/shared/chartSpecCore.d.ts +2 -4
  97. package/dist/components/charts/shared/gaugeGradient.d.ts +4 -8
  98. package/dist/components/charts/shared/gradient.d.ts +35 -0
  99. package/dist/components/charts/shared/hatchFill.d.ts +3 -10
  100. package/dist/components/charts/shared/hooks.d.ts +2 -50
  101. package/dist/components/charts/shared/knownChartComponents.d.ts +1 -1
  102. package/dist/components/charts/shared/streamPropsHelpers.d.ts +1 -2
  103. package/dist/components/charts/shared/useChartLegend.d.ts +65 -0
  104. package/dist/components/charts/shared/useChartSetup.d.ts +12 -0
  105. package/dist/components/charts/shared/useCustomChartSetup.d.ts +6 -1
  106. package/dist/components/charts/shared/useNetworkChartSetup.d.ts +1 -0
  107. package/dist/components/charts/shared/useStreamingLegend.d.ts +1 -1
  108. package/dist/components/charts/xy/AreaChart.d.ts +25 -42
  109. package/dist/components/charts/xy/BumpChart.capability.d.ts +11 -0
  110. package/dist/components/charts/xy/BumpChart.d.ts +161 -0
  111. package/dist/components/charts/xy/DifferenceChart.d.ts +3 -10
  112. package/dist/components/charts/xy/Heatmap.d.ts +3 -0
  113. package/dist/components/charts/xy/LineChart.d.ts +6 -8
  114. package/dist/components/data/portability/capabilityBinding.d.ts +41 -0
  115. package/dist/components/data/portability/index.d.ts +2 -0
  116. package/dist/components/geometry/bumpRibbonGeometry.d.ts +36 -0
  117. package/dist/components/legendLayout.d.ts +75 -1
  118. package/dist/components/recipes/geographicDotGrid.d.ts +82 -0
  119. package/dist/components/recipes/geographicGrid.d.ts +100 -0
  120. package/dist/components/recipes/physics.d.ts +2 -0
  121. package/dist/components/recipes/physicsStageGeography.d.ts +137 -0
  122. package/dist/components/semiotic-ai.d.ts +6 -4
  123. package/dist/components/semiotic-experimental-vacp.d.ts +11 -0
  124. package/dist/components/semiotic-experimental.d.ts +6 -3
  125. package/dist/components/semiotic-geo.d.ts +5 -0
  126. package/dist/components/semiotic-network.d.ts +1 -0
  127. package/dist/components/semiotic-ordinal.d.ts +2 -0
  128. package/dist/components/semiotic-physics.d.ts +10 -6
  129. package/dist/components/semiotic-realtime-core.d.ts +1 -0
  130. package/dist/components/semiotic-recipes-core.d.ts +6 -1
  131. package/dist/components/semiotic-server-edge.d.ts +1 -1
  132. package/dist/components/semiotic-server.d.ts +1 -1
  133. package/dist/components/semiotic-xy.d.ts +4 -0
  134. package/dist/components/semiotic.d.ts +4 -4
  135. package/dist/components/server/renderEvidence.d.ts +1 -1
  136. package/dist/components/server/renderToStaticSVG.d.ts +2 -1
  137. package/dist/components/server/serverChartConfigHeatmap.d.ts +6 -0
  138. package/dist/components/server/serverChartConfigNetworkStyles.d.ts +12 -0
  139. package/dist/components/server/serverChartConfigShared.d.ts +16 -0
  140. package/dist/components/server/serverChartConfigs.d.ts +3 -2
  141. package/dist/components/server/serverChartConfigsPhysics.d.ts +2 -2
  142. package/dist/components/server/serverChartConfigsXY.d.ts +1 -1
  143. package/dist/components/server/staticLegend.d.ts +10 -2
  144. package/dist/components/server/staticSVGChrome.d.ts +14 -6
  145. package/dist/components/server/staticValue.d.ts +8 -0
  146. package/dist/components/stream/GeoSVGOverlay.d.ts +4 -10
  147. package/dist/components/stream/NetworkSVGOverlay.d.ts +2 -6
  148. package/dist/components/stream/OrdinalSVGOverlay.d.ts +2 -6
  149. package/dist/components/stream/SVGOverlay.d.ts +2 -6
  150. package/dist/components/stream/StalenessBadge.d.ts +2 -6
  151. package/dist/components/stream/geoPipelineConfig.d.ts +10 -0
  152. package/dist/components/stream/geoTypes.d.ts +3 -6
  153. package/dist/components/stream/legendRenderer.d.ts +10 -6
  154. package/dist/components/stream/ordinalTypes.d.ts +7 -31
  155. package/dist/components/stream/physics/PhysicsEvidence.d.ts +37 -0
  156. package/dist/components/stream/physics/PhysicsKernel.d.ts +1 -0
  157. package/dist/components/stream/physics/PhysicsPipelineStore.d.ts +9 -0
  158. package/dist/components/stream/physics/PhysicsSVGOverlay.d.ts +2 -6
  159. package/dist/components/stream/physics/PhysicsSettledScene.d.ts +5 -0
  160. package/dist/components/stream/physics/StreamPhysicsTypes.d.ts +2 -6
  161. package/dist/components/stream/physics/physicsFramePipelineConfig.d.ts +19 -0
  162. package/dist/components/stream/physics/physicsPipelineSettle.d.ts +52 -0
  163. package/dist/components/stream/physics/physicsRegionRuntime.d.ts +23 -0
  164. package/dist/components/stream/pipelineConfig.d.ts +7 -15
  165. package/dist/components/stream/renderers/canvasRenderHelpers.d.ts +9 -69
  166. package/dist/components/stream/renderers/cornerRadii.d.ts +2 -9
  167. package/dist/components/stream/renderers/thresholdLineSegments.d.ts +12 -0
  168. package/dist/components/stream/sceneToSVGShared.d.ts +3 -5
  169. package/dist/components/stream/types.d.ts +34 -56
  170. package/dist/components/stream/xySceneBuilders/areaGradient.d.ts +4 -20
  171. package/dist/components/stream/xySceneBuilders/types.d.ts +6 -6
  172. package/dist/components/types/legendTypes.d.ts +31 -6
  173. package/dist/controls.min.js +1 -1
  174. package/dist/controls.module.min.js +1 -1
  175. package/dist/geo.min.js +1 -1
  176. package/dist/geo.module.min.js +1 -1
  177. package/dist/network.min.js +1 -1
  178. package/dist/network.module.min.js +1 -1
  179. package/dist/ordinal.min.js +1 -1
  180. package/dist/ordinal.module.min.js +1 -1
  181. package/dist/physics.min.js +1 -1
  182. package/dist/physics.module.min.js +1 -1
  183. package/dist/physicsWorker.js +1 -1
  184. package/dist/realtime.min.js +1 -1
  185. package/dist/realtime.module.min.js +1 -1
  186. package/dist/semiotic-ai-core.min.js +1 -1
  187. package/dist/semiotic-ai-core.module.min.js +1 -1
  188. package/dist/semiotic-ai.d.ts +6 -4
  189. package/dist/semiotic-ai.min.js +1 -1
  190. package/dist/semiotic-ai.module.min.js +1 -1
  191. package/dist/semiotic-data.module.min.js +1 -1
  192. package/dist/semiotic-experimental-vacp.d.ts +11 -0
  193. package/dist/semiotic-experimental-vacp.min.js +1 -0
  194. package/dist/semiotic-experimental-vacp.module.min.js +1 -0
  195. package/dist/semiotic-experimental.d.ts +6 -3
  196. package/dist/semiotic-experimental.min.js +2 -1
  197. package/dist/semiotic-experimental.module.min.js +2 -1
  198. package/dist/semiotic-geo.d.ts +5 -0
  199. package/dist/semiotic-network.d.ts +1 -0
  200. package/dist/semiotic-ordinal.d.ts +2 -0
  201. package/dist/semiotic-physics.d.ts +10 -6
  202. package/dist/semiotic-realtime-core.d.ts +1 -0
  203. package/dist/semiotic-realtime-core.min.js +1 -1
  204. package/dist/semiotic-realtime-core.module.min.js +1 -1
  205. package/dist/semiotic-recipes-core.d.ts +6 -1
  206. package/dist/semiotic-recipes-core.min.js +1 -1
  207. package/dist/semiotic-recipes-core.module.min.js +1 -1
  208. package/dist/semiotic-recipes.min.js +1 -1
  209. package/dist/semiotic-recipes.module.min.js +1 -1
  210. package/dist/semiotic-server-edge.d.ts +1 -1
  211. package/dist/semiotic-server-edge.min.js +1 -1
  212. package/dist/semiotic-server-edge.module.min.js +1 -1
  213. package/dist/semiotic-server-node.min.js +1 -1
  214. package/dist/semiotic-server-node.module.min.js +1 -1
  215. package/dist/semiotic-server.d.ts +1 -1
  216. package/dist/semiotic-utils-core.min.js +1 -1
  217. package/dist/semiotic-utils-core.module.min.js +1 -1
  218. package/dist/semiotic-utils.min.js +1 -1
  219. package/dist/semiotic-utils.module.min.js +1 -1
  220. package/dist/semiotic-xy.d.ts +4 -0
  221. package/dist/semiotic.d.ts +4 -4
  222. package/dist/semiotic.min.js +1 -1
  223. package/dist/semiotic.module.min.js +1 -1
  224. package/dist/server.min.js +1 -1
  225. package/dist/server.module.min.js +1 -1
  226. package/dist/xy.min.js +1 -1
  227. package/dist/xy.module.min.js +1 -1
  228. package/package.json +18 -2
  229. package/spec/README.md +94 -2
  230. package/spec/bindings/README.md +14 -3
  231. package/spec/v0.1/examples/annotation-provenance-reviewed-revision.json +27 -0
  232. package/spec/v0.1/examples/annotation-provenance-watcher-threshold.json +21 -0
  233. package/spec/v0.1/examples/audience-profile-executive-review.json +24 -0
  234. package/spec/v0.1/examples/audience-profile-incident-operators.json +42 -0
  235. package/spec/v0.1/examples/chart-capability-bar-comparison.json +48 -0
  236. package/spec/v0.1/examples/chart-capability-service-flow.json +54 -0
  237. package/dist/chunk-chunk-4AANPFOX.module.min.js +0 -2
  238. package/dist/chunk-chunk-5I3UZV4Q.module.min.js +0 -2
  239. package/dist/chunk-chunk-5RKXZQ2P.module.min.js +0 -1
  240. package/dist/chunk-chunk-74CCPVXB.module.min.js +0 -1
  241. package/dist/chunk-chunk-7ALTGHK6.module.min.js +0 -1
  242. package/dist/chunk-chunk-ANYDWOZF.module.min.js +0 -1
  243. package/dist/chunk-chunk-AVBI6GDT.module.min.js +0 -1
  244. package/dist/chunk-chunk-BANTPINB.module.min.js +0 -2
  245. package/dist/chunk-chunk-C4YA6TDR.module.min.js +0 -1
  246. package/dist/chunk-chunk-C57LR3YG.module.min.js +0 -1
  247. package/dist/chunk-chunk-CKMD5NV3.module.min.js +0 -2
  248. package/dist/chunk-chunk-CO5KQMGH.module.min.js +0 -1
  249. package/dist/chunk-chunk-CWQ5YIHX.module.min.js +0 -2
  250. package/dist/chunk-chunk-E6TXX6MI.module.min.js +0 -1
  251. package/dist/chunk-chunk-GMQ5AYTD.module.min.js +0 -1
  252. package/dist/chunk-chunk-JCG72SGW.module.min.js +0 -2
  253. package/dist/chunk-chunk-K3DMEW22.module.min.js +0 -1
  254. package/dist/chunk-chunk-KT2VAZMZ.module.min.js +0 -1
  255. package/dist/chunk-chunk-L6EA5V3G.module.min.js +0 -2
  256. package/dist/chunk-chunk-LJPCLYSC.module.min.js +0 -2
  257. package/dist/chunk-chunk-LRIFN2HK.module.min.js +0 -1
  258. package/dist/chunk-chunk-N5DDKCCF.module.min.js +0 -1
  259. package/dist/chunk-chunk-NEVE562N.module.min.js +0 -1
  260. package/dist/chunk-chunk-NLO44TOS.module.min.js +0 -2
  261. package/dist/chunk-chunk-PZJ2SBLL.module.min.js +0 -2
  262. package/dist/chunk-chunk-QSQVBIJA.module.min.js +0 -1
  263. package/dist/chunk-chunk-QUJ6TTLY.module.min.js +0 -1
  264. package/dist/chunk-chunk-RBIDBUT4.module.min.js +0 -2
  265. package/dist/chunk-chunk-RCF52Z42.module.min.js +0 -2
  266. package/dist/chunk-chunk-RFLAG356.module.min.js +0 -1
  267. package/dist/chunk-chunk-RPU4IZAV.module.min.js +0 -2
  268. package/dist/chunk-chunk-SKMBCFIL.module.min.js +0 -2
  269. package/dist/chunk-chunk-TAE7W424.module.min.js +0 -2
  270. package/dist/chunk-chunk-TUBMTZMU.module.min.js +0 -2
  271. package/dist/chunk-chunk-UFFEXJQY.module.min.js +0 -1
  272. package/dist/chunk-chunk-XSCHTS4D.module.min.js +0 -2
  273. package/dist/chunk-chunk-XXWSHGPL.module.min.js +0 -2
  274. package/dist/chunk-chunk-ZOAQDIJO.module.min.js +0 -1
  275. package/dist/chunk-chunk-ZXIXAPRE.module.min.js +0 -2
  276. package/dist/chunk-statisticalOverlays-QGDLRUHX.module.min.js +0 -1
  277. package/dist/chunk-statisticalOverlays-T77OKLDY.module.min.js +0 -1
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{createProcessJourneyLedger as e,processJourneyRows as t,updateProcessJourney as n}from"./chunk-chunk-YWZB3KPI.module.min.js";import{BuiltInPhysicsEngineAdapter as s,CollisionSwarmChart as i,CrucibleChart as o,DEFAULT_CRUCIBLE_HEIGHT as r,DEFAULT_CRUCIBLE_OUTLETS as a,DEFAULT_CRUCIBLE_SIZE as c,DEFAULT_CRUCIBLE_WIDTH as l,EventDropChart as d,GaltonBoardChart as u,GauntletChart as h,GuantletChart as m,PhysicalFlowChart as p,PhysicsCustomChart as f,PhysicsPileChart as g,PhysicsPipelineStore as y,PhysicsSVGOverlay as k,PhysicsSedimentAccumulator as x,ProcessFlowChart as b,StreamPhysicsFrame as v,StreamPhysicsFrame_default as w,absorbRegion as I,aggregateRegionCounts as D,applyCrucibleEvent as M,bodiesToAnnotationAnchors as A,bodyGroupSpec as T,buildCollisionSwarmPhysics as S,buildCrucibleEvidence as C,buildCrucibleInitialSpawns as $,buildCrucibleLayout as E,buildCruciblePhysicsConfig as N,buildCrucibleProductEvents as j,buildCrucibleProjection as R,buildCrucibleStateSpawns as W,buildCrucibleTerminalSpawns as P,buildEventDropPhysics as B,buildGaltonBoardPhysics as F,buildPhysicalFlowPhysics as L,buildPhysicsAnnotationContext as q,buildPhysicsPile as O,buildProcessFlowPhysics as z,capacitatedRegion as H,chargeGateRegion as X,cloneCrucibleState as U,collidersFromPlotBounds as Y,collidersFromXScaleBins as J,compileCruciblePlan as Z,composePhysicsControllers as G,createCapacityQueueController as K,createDefaultPhysicsEngineAdapter as Q,createDependencyGateController as V,createInitialCrucibleState as _,createPortalController as ee,createServiceLevelController as te,createServiceResourcePoolController as ne,crucibleBondId as se,crucibleBoundaryColliders as ie,crucibleComponentBodyId as oe,crucibleProductBodyId as re,crucibleProjectionRows as ae,crucibleSemanticKey as ce,evaluateCrucibleConservation as le,evaluatePhysicsBodyBudget as de,forceFieldRegion as ue,groupCompletionRows as he,membraneRegion as me,normalizePhysicsAnnotations as pe,physicsProcessBoundaryColliders as fe,physicsProcessGroupSemanticItems as ge,physicsProcessRegionSemanticItem as ye,physicsProcessStageSemanticItems as ke,planGauntletPropertyWork as xe,portalRegion as be,pressureFieldRegion as ve,processChrome as we,processLaneWalls as Ie,processStageLayout as De,processStageRegions as Me,processVolumePolygons as Ae,regionCountsToProjectionRows as Te,replaceGauntletNegative as Se,replayCruciblePlan as Ce,resolveCrucibleSelector as $e,resolveCrucibleSnapshotAt as Ee,resolveCrucibleTime as Ne,routeSurfaceRegion as je,sedimentHeightfield as Re,stageTargetInVolume as We}from"./chunk-chunk-XSCHTS4D.module.min.js";import{mulberry32 as Pe}from"./chunk-chunk-SIRIJ3DY.module.min.js";import{composeStyleRules as Be,makeRuleValueResolver as Fe,matchesThreshold as Le,resolveStyleRules as qe,ruleMatches as Oe}from"./chunk-chunk-EMO5NUGE.module.min.js";import"./chunk-chunk-SV4XAZ3Q.module.min.js";import"./chunk-chunk-LJLS6DY7.module.min.js";import{compileMotionEncoding as ze,deriveMotionVector as He,hatchFillId as Xe,hatchPatternDef as Ue,isHatchFill as Ye,opacityFromAge as Je,resolveMotionAccessor as Ze,resolveMotionAge as Ge,resolveMotionVector as Ke,resolveSvgFill as Qe}from"./chunk-chunk-CWQ5YIHX.module.min.js";import"./chunk-chunk-JJ2OOIET.module.min.js";import"./chunk-chunk-WCX6U47H.module.min.js";import"./chunk-chunk-KTWEBFMX.module.min.js";import"./chunk-chunk-ACLDBMRH.module.min.js";import"./chunk-chunk-YHNZCPOZ.module.min.js";function Ve(e){const{data:t,encoding:n,defaults:s={},scales:i}=e,o=ze({data:t,encoding:n}),r=[],a=new Map,c=[],l=[],d=new Map;return o.rows.forEach((e,t)=>{const{id:o,datum:u}=e,h=Math.max(0,Ze(n.appearance?.size,u,t)??s.size??6),m=Ze(n.appearance?.shape,u,t)??s.shape??{type:"circle",radius:h},p=e.placement.x??s.x??0,f=e.placement.y??s.y??0,g=i?.x?i.x(p):p,y=i?.y?i.y(f):f,k=Ze(n.appearance?.color,u,t)??s.color,x=Ze(n.appearance?.opacity,u,t)??s.opacity,b=Ze(n.appearance?.stroke,u,t)??s.stroke,v=Ze(n.appearance?.strokeWidth,u,t)??s.strokeWidth,w=Ze(n.time?.spawnAt,u,t)??e.time.arrival,I=e.kinematics.velocityX,D=e.kinematics.velocityY,M=Ze(n.dynamics?.mass,u,t)??s.mass??1,A=Ze(n.dynamics?.friction,u,t),T=Ze(n.dynamics?.restitution,u,t),S=Ze(n.dynamics?.bodyCollisions,u,t),C={id:o,x:g,y:y,mass:M,shape:{...m},datum:u,...null!=w&&{spawnAt:w},...null!=I&&{vx:I},...null!=D&&{vy:D},...null!=A&&{friction:A},...null!=T&&{restitution:T},...null!=S&&{bodyCollisions:S}},$={...null!=k&&{fill:k},...null!=x&&{opacity:x},...null!=b&&{stroke:b},...null!=v&&{strokeWidth:v}},E={id:o,datum:u,appearance:{color:k,opacity:x,shape:m,size:h,stroke:b,strokeWidth:v},placement:{x:g,y:y,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:w,spawnAt:w,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:I,velocityY:D,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:S,friction:A,mass:M,restitution:T},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:C};r.push(E),a.set(o,E),c.push(C),d.set(o,$),l.push({id:o,bodyId:o,label:e.accessible.label,description:e.accessible.description,datum:u,x:g,y:y,group:e.accessible.group})}),{rows:r,byId:a,spawns:c,semanticItems:l,bodyStyle:e=>d.get(e.id)??{}}}function _e(e){return t=>{const n=Ve({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),s=e.extend?.(t,n)??{};return{...s,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...s.semanticItems??[]]}}}var et=[.1,.5,.9],tt=1e6;function nt(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function st(e,t,n,s,i){return"function"==typeof s?s(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,s??i)}function it(e){const t=Number(e.toFixed(12));return Object.is(t,-0)?0:t}function ot(e,t,n,s){const i=e.flatMap((e,i)=>{const o=nt(st(e,i,t,n,"time")),r=nt(st(e,i,t,s,"value"));return null==o||null==r?[]:[{time:it(o),value:r,index:i}]});i.sort((e,t)=>e.time-t.time||e.index-t.index);const o=[];for(const e of i){const t=o[o.length-1];t?.time===e.time?t.value=e.value:o.push({time:e.time,value:e.value})}return o}function rt(e,t,n,s){if(!e.length)return null;const i=e[0],o=e[e.length-1];if(i.time>t)return"clamp"===s?i.value:null;if(t>o.time)return"clamp"===s?o.value:null;const r=function(e,t){let n=0,s=e.length;for(;s>n;){const i=n+s>>>1;t>e[i].time?n=i+1:s=i}return n}(e,t),a=e[r];if(a?.time===t)return a.value;const c=e[Math.max(0,r-1)];return"step"!==n&&a&&a.time!==c.time?c.value+(t-c.time)/(a.time-c.time)*(a.value-c.value):c.value}function at(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,s=Math.floor(n),i=Math.ceil(n);return s===i?e[s]:e[s]+(e[i]-e[s])*(n-s)}function ct(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",s=function(e){const t=(e??et).map(e=>{const t=nt(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return it(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),i=function(e){if(Array.isArray(e)){if(e.length>tt)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(e.map(nt).filter(e=>null!=e).map(it))).sort((e,t)=>e-t)}const t=e,n=nt(t.start),s=nt(t.end),i=nt(t.step);if(null==n||null==s||null==i||0>=i||n>s)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const o=Math.floor((s-n)/i)+1;if(o>tt)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");const r=[],a=1e-10*Math.max(1,Math.abs(s),Math.abs(n));for(let e=0;o>e;e+=1){const t=n+e*i;if(t>s+a)break;r.push(it(Math.min(t,s)))}if(r.length&&a>=Math.abs(r[r.length-1]-s)||r.push(it(s)),r.length>tt)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(r)).sort((e,t)=>e-t)}(e.sampleAt),o=e.runs.map(t=>ot(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:i.map(e=>{const i=o.map(s=>rt(s,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),r={};for(const e of s)r[e]=i.length?at(i,e):null;return{time:e,count:i.length,min:i.length?i[0]:null,max:i.length?i[i.length-1]:null,median:i.length?at(i,.5):null,quantiles:r}}),quantiles:s,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function lt(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function dt(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=nt(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const s=it(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,s))throw Error(`comparePhysicsTrace could not find quantile ${s} in the reference envelope`);return e.quantiles[s]??null}function ut(e,t,n){return t>e?"below":e>n?"above":"inside"}function ht(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const s=e.value-e.lower,i=t.value-t.lower,o=e.value-e.upper,r=t.value-t.upper,a=[0,1];for(const[e,t]of[[s,i],[o,r]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let c=0,l=0,d=0;for(let s=0;a.length-1>s;s+=1){const i=a[s],o=a[s+1];if(i>=o)continue;const r=(i+o)/2,u=(o-i)*n,h=ut(e.value+(t.value-e.value)*r,e.lower+(t.lower-e.lower)*r,e.upper+(t.upper-e.upper)*r);"below"===h?c+=u:"above"===h?d+=u:l+=u}return{below:c,inside:l,above:d,observed:n}}function mt(e,t,n={}){const s=n.interpolation??t.interpolation,i=n.outsideDomain??t.outsideDomain,o=ot(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),r=n.lower??lt(t,"lower"),a=n.upper??lt(t,"upper"),c=t.points.map(e=>{const t=rt(o,e.time,s,i),n=dt(e,r),c=dt(e,a);if(null!=n&&null!=c&&n>c)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:c,status:null==t||null==n||null==c?"unobserved":ut(t,n,c)}});let l=0,d=0,u=0,h=0,m=null,p=0,f=null;for(const e of c){if("below"===e.status?l+=1:"inside"===e.status?d+=1:"above"===e.status&&(u+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,m=e.time),n>p&&(p=n,f=e.time)}let g=0,y=0,k=0,x=0;for(let e=0;c.length-1>e;e+=1){const t=c[e],n=c[e+1],i=Math.max(0,n.time-t.time);if(i>0){if("linear"===s){const e=ht(t,n);g+=e.below,y+=e.inside,k+=e.above,x+=e.observed;continue}"unobserved"!==t.status&&(x+=i,"below"===t.status?g+=i:"above"===t.status?k+=i:y+=i)}}const b=c[0]?.time,v=c[c.length-1]?.time,w=null==b||null==v?0:Math.max(0,v-b);return{points:c,sampleCount:c.length,observedSamples:l+d+u,belowSamples:l,insideSamples:d,aboveSamples:u,totalDuration:w,observedDuration:x,unobservedDuration:Math.max(0,w-x),belowDuration:g,insideDuration:y,aboveDuration:k,peakExcess:h,peakExcessAt:m,peakDeficit:p,peakDeficitAt:f}}function pt(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function ft(e,t,n,s){const i="function"==typeof e?e(t,n):e;return Number.isFinite(i)?Number(i):s}function gt(e,t,n){return pt(e[t])??n}function yt(e,t){return"number"==typeof e?e:e?.[t]??0}function kt(e){const{band:t,idPrefix:n,plot:s,projection:i}=e,{includeBoundaryWalls:o=!0,includeInteriorWalls:r=!0,wallThickness:a=4}=t,c=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const s of e.values){const i=e.scale(s);Number.isFinite(i)&&(n.add(Number(i)),n.add(Number(i)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>c.length)return[];const l=o?c.length-1:c.length-2,d=[];for(let e=o?0:1;l>=e;e+=1){if(!r&&e>0&&c.length-1>e)continue;const t=c[e];d.push({id:`${n}-wall-${e}`,shape:"x"===i?{type:"aabb",x:t,y:s.y+s.height/2,width:a,height:s.height}:{type:"aabb",x:s.x+s.width/2,y:t,width:s.width,height:a}})}return d}function xt(e){const{plot:t,idPrefix:n="physics-scale",bounds:s={},xBins:i,xBands:o,yBands:r}=e,a=[];if(!1!==s&&a.push(...Y(t,{idPrefix:n,...s})),i){const{idPrefix:e,yTop:s,yBottom:o,...r}=i;a.push(...J({...r,idPrefix:e??n+"-xbin",yTop:s??t.y,yBottom:o??t.y+t.height}))}return o&&a.push(...kt({band:o,idPrefix:o.idPrefix??n+"-xband",plot:t,projection:"x"})),r&&a.push(...kt({band:r,idPrefix:r.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function bt(e){const{plot:t,rows:n,columns:s=n+1,pegRadius:i=3,idPrefix:o="galton-peg",yStart:r=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:c=!0,restitution:l=.2,friction:d=.04}=e,u=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(s));if(0===u)return[];const m=u>1?(a-r)/(u-1):0,p=t.width/h,f=[];for(let e=0;u>e;e+=1){const n=c&&e%2==1?p/2:0;for(let s=0;h>s;s+=1){const a=t.x+p*(s+.5)+n;t.x+i>a||a>t.x+t.width-i||f.push({id:`${o}-${e}-${s}`,shape:{type:"aabb",x:a,y:r+e*m,width:2*i,height:2*i},restitution:l,friction:d})}}return f}function vt(e,t={}){const{idPrefix:n="physics-token",radius:s=5,shape:i,mass:o,vx:r,vy:a,spawnAt:c,seed:l=1,jitter:d,datum:u}=t,h=Pe(l),m=yt(d,"x"),p=yt(d,"y");return e.map((e,l)=>{const d=ft(t.x,e,l,gt(e,"x",0)),f=ft(t.y,e,l,gt(e,"y",0)),g=ft(s,e,l,5),y="function"==typeof i?i(e,l):i??{type:"circle",radius:g};return{id:`${n}-${e.index??l}`,x:d+(h()-.5)*m,y:f+(h()-.5)*p,vx:ft(r,e,l,0),vy:ft(a,e,l,0),mass:ft(o,e,l,1),spawnAt:ft(c,e,l,void 0),shape:y,datum:u?u(e,l):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function wt(e,t={}){const{idPrefix:n="sediment",collider:s=!0,colliderThickness:i=1,restitution:o=.05,friction:r=.2,...a}=t,c=Re(e,a),l=s?c.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+i/2,width:e.width,height:i},restitution:o,friction:r})):[];return{columns:c,colliders:l}}function It(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:s=1,startAt:i=0,rebase:o=!0,sort:r=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return pt("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),c=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:i+(o?t-c:t)})).sort((e,t)=>r?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:i,timeAccessor:"spawnAt",timeScale:s}}}import{forwardRef as Dt,useCallback as Mt,useEffect as At,useImperativeHandle as Tt,useMemo as St,useRef as Ct,useState as $t}from"react";function Et(e,t,n={}){const s=new Set,i=[...e.get(t)??[]];let o=0;for(;i.length>o;){const t=i[o];if(o+=1,!s.has(t)){s.add(t);for(const n of e.get(t)??[])i.push(n)}}return n.includeStart&&s.add(t),s}function Nt(e,t,n){return Ze(n,e,t)}function jt(e,t){return t>e?-1:e>t?1:0}function Rt(e,t){return`dependency:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Wt(e,t){return`socket:${encodeURIComponent(e)}:${t}`}function Pt(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function Bt(e){const t=[],n=new Map,s=[],i=new Set;e.data.forEach((o,r)=>{const a=(Nt(o,r,e.taskIDAccessor)??"")+"";if(!a)return void t.push({code:"duplicate-task-id",message:`Task row ${r} has an empty id.`,taskIDs:[]});if(n.has(a))return void t.push({code:"duplicate-task-id",message:`Task id "${a}" occurs more than once.`,taskIDs:[a]});const c=(Nt(o,r,e.laneAccessor)??"Unassigned")+"";i.has(c)||(i.add(c),s.push(c));const l=Nt(o,r,e.dependencyAccessor)??[],d=Array.from(new Set(Array.from(l,e=>e+""))).sort(jt),u=Nt(o,r,e.blockerAccessor),h=Nt(o,r,e.statusAccessor)??(u?"blocked":"waiting");n.set(a,{id:a,label:(Nt(o,r,e.labelAccessor)??a)+"",lane:c,laneIndex:0,level:0,index:r,datum:o,dependencyIDs:d,incomingEdgeIDs:[],outgoingEdgeIDs:[],socketIDs:[],start:Nt(o,r,e.startAccessor),end:Nt(o,r,e.endAccessor),progress:Pt(Nt(o,r,e.progressAccessor)),status:h,completionTime:Nt(o,r,e.completionTimeAccessor),blockerReason:u||void 0,milestone:!!Nt(o,r,e.milestoneAccessor)})});const o=e.laneOrder?[...e.laneOrder,...s.filter(t=>!e.laneOrder?.includes(t))]:s,r=new Map(o.map((e,t)=>[e,t]));for(const e of n.values())e.laneIndex=r.get(e.lane)??0;const a=new Map,c=new Map;for(const e of n.keys())a.set(e,[]),c.set(e,[]);const l=[],d=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of d)e.dependencyIDs.forEach((s,i)=>{const o=n.get(s);if(!o)return void t.push({code:"missing-dependency",message:`Task "${e.id}" depends on missing task "${s}".`,taskIDs:[e.id,s]});const r={id:Rt(s,e.id),sourceID:s,targetID:e.id,sourceIndex:o.index,targetIndex:e.index,socketID:Wt(e.id,i),socketIndex:i};l.push(r),a.get(e.id)?.push(r),c.get(s)?.push(r),e.incomingEdgeIDs.push(r.id),e.socketIDs.push(r.socketID),o.outgoingEdgeIDs.push(r.id)});for(const e of a.values())e.sort((e,t)=>jt(e.sourceID,t.sourceID)),e.forEach((e,t)=>{e.socketIndex=t,e.socketID=Wt(e.targetID,t)});for(const e of c.values())e.sort((e,t)=>jt(e.targetID,t.targetID));for(const e of n.values()){const t=a.get(e.id)??[];e.incomingEdgeIDs=t.map(e=>e.id),e.socketIDs=t.map(e=>e.socketID),e.outgoingEdgeIDs=(c.get(e.id)??[]).map(e=>e.id)}const u=new Map,h=new Map;for(const e of n.keys())u.set(e,a.get(e)?.length??0),h.set(e,0);const m=[...n.keys()].filter(e=>0===u.get(e)).sort(jt);let p=0;for(;m.length;){const e=m.shift();p+=1;for(const t of c.get(e)??[]){const n=Math.max(h.get(t.targetID)??0,(h.get(e)??0)+1);h.set(t.targetID,n);const s=(u.get(t.targetID)??0)-1;if(u.set(t.targetID,s),0===s){const e=m.findIndex(e=>e>t.targetID);0>e?m.push(t.targetID):m.splice(e,0,t.targetID)}}}if(p!==n.size){const e=[...n.keys()].filter(e=>(u.get(e)??0)>0).sort(jt);t.push({code:"cycle",message:`Dependency graph contains a cycle involving: ${e.join(", ")}.`,taskIDs:e})}let f=0;const g=[...n.values()].sort((e,t)=>e.index-t.index);for(const e of g)e.level=h.get(e.id)??0,f=Math.max(f,e.level);return{nodes:g,edges:l,byID:n,incoming:a,outgoing:c,lanes:o,maxLevel:f,diagnostics:t,valid:0===t.length}}function Ft(e,t,n={}){const s=Math.max(240,t.width),i=Math.max(220,t.height),o=t.paddingX??48,r=t.paddingTop??48,a=t.paddingBottom??44,c=Math.max(70,(s-2*o)/Math.max(1,e.lanes.length)),l=Math.max(76,(i-r-a)/Math.max(1,e.maxLevel+1)),d=Math.min(n.taskWidth??112,Math.max(58,.78*c)),u=Math.min(n.taskHeight??58,.64*l),h=n.socketRadius??5,m=Math.max(1,Math.round(n.gutterCount??3)),p=new Map;for(const t of e.nodes){const e=`${t.laneIndex}:${t.level}`,n=p.get(e)??[];n.push(t),p.set(e,n)}for(const e of p.values())e.sort((e,t)=>jt(e.id,t.id));const f=e.nodes.map(e=>{const t=p.get(`${e.laneIndex}:${e.level}`)??[e],n=Math.max(0,t.findIndex(t=>t.id===e.id));return{taskID:e.id,lane:e.lane,laneIndex:e.laneIndex,level:e.level,x:o+c*(e.laneIndex+.5),y:r+l*(e.level+.5)+(n-(t.length-1)/2)*Math.min(18,.3*u),width:d,height:u}}),g=new Map(f.map(e=>[e.taskID,e])),y=[],k=[];e.edges.forEach((t,n)=>{const s=g.get(t.sourceID),i=g.get(t.targetID);if(!s||!i)return;const o=e.incoming.get(t.targetID)??[],r=Math.min(.72*i.width,14*Math.max(1,o.length-1)),a=o.length>1?i.x-r/2+r*t.socketIndex/(o.length-1):i.x,c=i.y-i.height/2-h-2;y.push({id:t.socketID,edgeID:t.id,taskID:i.taskID,index:t.socketIndex,x:a,y:c,radius:h});const l={x:s.x,y:s.y+s.height/2+3},d=Math.min(c-10,l.y+.48*Math.max(18,c-l.y)+7*(n%m-(m-1)/2));var u;k.push({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,socketID:t.socketID,points:(u=[l,{x:l.x,y:d},{x:a,y:d},{x:a,y:c}],u.filter((e,t)=>{const n=u[t-1];return!n||n.x!==e.x||n.y!==e.y}))})});const x=new Map(y.map(e=>[e.id,e])),b=new Map(k.map(e=>[e.edgeID,e]));return{tasks:f,sockets:y,routes:k,taskByID:g,socketByID:x,routeByEdgeID:b}}function Lt(e,t,n="all"){const s=Array.from(new Set(t)).sort(jt),i=new Set,o=()=>s.every(e=>i.has(e));return{taskID:e,mode:n,incomingEdgeIDs:s,deliver:e=>s.includes(e)?(i.add(e),o()):o(),reset:(e=[])=>{i.clear();for(const t of e)s.includes(t)&&i.add(t)},isSatisfied:o,getSnapshot:()=>({taskID:e,mode:n,incomingEdgeIDs:[...s],deliveredEdgeIDs:[...i].sort(jt),satisfied:o()})}}function qt(e){return e instanceof Date?e.getTime():Number(e)}function Ot(e,t){const n=qt("object"!=typeof t||t instanceof Date?t:t.currentTime),s=e.map((e,t)=>({event:e,index:t,time:qt(e.at)})).filter(e=>Number.isFinite(e.time)&&n>=e.time).sort((e,t)=>e.time-t.time||e.index-t.index),i=new Set,o=new Map,r=new Set,a=new Set;for(const{event:e}of s)"task-completed"===e.type?(i.add(e.taskID),o.delete(e.taskID)):"task-blocked"===e.type?o.set(e.taskID,e.reason):"task-unblocked"===e.type?o.delete(e.taskID):"dependency-delivered"===e.type?r.add(e.edgeID):"task-armed"===e.type&&a.add(e.taskID);return{currentTime:n,appliedEvents:s.map(e=>e.event),completedTaskIDs:i,blockedByTaskID:o,deliveredEdgeIDs:r,armedTaskIDs:a}}function zt(e,t,n={}){const s=new Set(n.completedTaskIDs??[]),i=[...Et(function(e,t){const n=new Map;for(const t of e)n.set(t.id,new Set);for(const e of t)n.has(e.source)||n.set(e.source,new Set),n.has(e.target)||n.set(e.target,new Set),n.get(e.source).add(e.target);return n}(e.nodes,e.edges.map(e=>({source:e.sourceID,target:e.targetID}))),t)].map(t=>e.byID.get(t)).filter(e=>null!=e).filter(e=>!(n.isComplete?n.isComplete(e):s.has(e.id)||"done"===e.status)).sort((e,t)=>e.index-t.index),o=Array.from(new Set(i.map(e=>e.lane)));return{blockerID:t,downstreamTaskCount:i.length,affectedLaneCount:o.length,downstreamTaskIDs:i.map(e=>e.id),affectedLanes:o}}var Ht=[];function Xt(e,t=0){if(e instanceof Date)return e.getTime();const n=Number(e);return Number.isFinite(n)?n:t}function Ut(e){if(null==e.completionTime)return null;const t=Xt(e.completionTime,NaN);return Number.isFinite(t)?t:null}function Yt(e,t,n,s){const i=new Set;for(const o of e.nodes){const r=e.incoming.get(o.id)??[];(s.has(o.id)||!n.has(o.id)&&r.every(e=>t.has(e.id)))&&i.add(o.id)}return i}function Jt(e,t,n,s){const i=e.nodes.map(Ut).filter(e=>null!=e),o=i.length?Math.min(...i)-1:0,r="replay"!==t||s?n:o,a=new Set,c=new Map;for(const n of e.nodes){const e=Ut(n);(null!=e&&r>=e||"done"===n.status&&"replay"!==t)&&a.add(n.id),n.blockerReason&&!a.has(n.id)&&c.set(n.id,n.blockerReason)}const l=new Set;if("replay"!==t||s)for(const t of e.edges)a.has(t.sourceID)&&l.add(t.id);return{currentTime:r,playing:!1,completed:a,delivered:l,inFlight:new Set,armed:Yt(e,l,c,a),blockers:c,previewTaskID:null}}function Zt(e){return{...e,completed:new Set(e.completed),delivered:new Set(e.delivered),inFlight:new Set(e.inFlight),armed:new Set(e.armed),blockers:new Map(e.blockers)}}function Gt(e){const t=e.datum;return"dependency-ball"===t?.kind&&Array.isArray(t.route)?t:null}function Kt(e){const t=Gt(e.body);if(!t||2>t.route.length)return null;const n=function(e){let t=0;for(let n=1;e.length>n;n+=1)t+=Math.hypot(e[n].x-e[n-1].x,e[n].y-e[n-1].y);return t}(t.route),s=function(e,t){let n=1/0,s=0,i=0;for(let o=1;t.length>o;o+=1){const r=t[o-1],a=t[o],c=a.x-r.x,l=a.y-r.y,d=c*c+l*l,u=Math.sqrt(d);if(0>=u)continue;const h=Math.max(0,Math.min(1,((e.x-r.x)*c+(e.y-r.y)*l)/d)),m=Math.hypot(e.x-(r.x+c*h),e.y-(r.y+l*h));n>m&&(n=m,s=i+h*u),i+=u}return s}(e.body,t.route),i=function(e,t){if(2>e.length)return{point:e[0]??{x:0,y:0},tangent:{x:0,y:1}};let n=0;for(let s=1;e.length>s;s+=1){const i=e[s-1],o=e[s],r=o.x-i.x,a=o.y-i.y,c=Math.hypot(r,a);if(c>0){if(n+c>=t){const e=Math.max(0,Math.min(1,(t-n)/c));return{point:{x:i.x+r*e,y:i.y+a*e},tangent:{x:r/c,y:a/c}}}n+=c}}const s=e[e.length-2],i=e[e.length-1],o=i.x-s.x,r=i.y-s.y,a=Math.hypot(o,r)||1;return{point:i,tangent:{x:o/a,y:r/a}}}(t.route,Math.min(n,s+22));return{x:2.5*(78*i.tangent.x-e.body.vx)+8*(i.point.x-e.body.x),y:2.5*(78*i.tangent.y-e.body.vy)+8*(i.point.y-e.body.y)}}function Qt(e,t){const n=t.points[0]??{x:0,y:0},s=t.points[1]??n,i=s.x-n.x,o=s.y-n.y,r=Math.hypot(i,o)||1;return{id:"dependency-ball:"+e.id,x:n.x,y:n.y,vx:i/r*42,vy:o/r*42,mass:.7,restitution:.02,friction:.12,bodyCollisions:!1,shape:{type:"circle",radius:5},datum:{kind:"dependency-ball",edgeID:e.id,sourceID:e.sourceID,targetID:e.targetID,route:t.points}}}import{jsx as Vt,jsxs as _t}from"react/jsx-runtime";function en({machine:e,layout:t,runtime:n,downstreamSet:s,selectedSet:i,width:o,height:r,seed:a,reduced:c,onSelectTask:l}){return _t("svg",{"aria-hidden":"true",width:o,height:r,viewBox:`0 0 ${o} ${r}`,style:{position:"absolute",inset:0,overflow:"visible",pointerEvents:"none"},children:[Vt("defs",{children:Vt("filter",{id:"chain-shadow-"+a,x:"-20%",y:"-20%",width:"140%",height:"150%",children:Vt("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.2"})})}),e.lanes.map((e,n)=>{const s=t.tasks.filter(e=>e.laneIndex===n),i=s[0]?.x??0;return _t("g",{children:[Vt("line",{x1:i,x2:i,y1:32,y2:r-24,stroke:"var(--semiotic-grid, #d7dde0)",strokeWidth:1,strokeDasharray:"3 7"}),Vt("text",{x:i,y:23,textAnchor:"middle",fontSize:12,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e})]},e)}),t.routes.map(e=>{const t=n.delivered.has(e.edgeID),i=n.inFlight.has(e.edgeID),o=s.has(e.targetID)||s.has(e.sourceID),r=e.points.map(e=>`${e.x},${e.y}`).join(" ");return Vt("polyline",{points:r,fill:"none",stroke:o?"var(--semiotic-highlight, #e08a1e)":t?"var(--semiotic-success, #2b8a66)":"var(--semiotic-grid, #aeb8bd)",strokeWidth:o?4:i?3:2,strokeOpacity:t||i||o?.95:.48,strokeLinecap:"round",strokeLinejoin:"round"},e.edgeID)}),t.sockets.map(e=>{const t=n.delivered.has(e.edgeID);return _t("g",{children:[Vt("circle",{cx:e.x,cy:e.y,r:e.radius+2,fill:"var(--semiotic-background, #fff)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.5}),t&&Vt("circle",{cx:e.x,cy:e.y,r:e.radius-.5,fill:"var(--semiotic-success, #2b8a66)"})]},e.id)}),e.nodes.map(e=>{const o=t.taskByID.get(e.id);if(!o)return null;const r=n.completed.has(e.id),d=n.blockers.has(e.id),u=n.previewTaskID===e.id,h=i.has(e.id)||u,m=s.has(e.id),p=function(e,t){return t.completed.has(e.id)?"var(--semiotic-success, #2b8a66)":t.blockers.has(e.id)?"var(--semiotic-error, #c64035)":"in-progress"===e.status?"var(--semiotic-warning, #d18a22)":t.armed.has(e.id)?"var(--semiotic-primary, #2474a6)":"var(--semiotic-muted, #75818a)"}(e,n),f=o.x-o.width/2,g=o.y-o.height/2,y=Math.max(2,o.height*e.progress);return _t("g",{children:[_t("g",{style:{transform:`rotate(${r?76:0}deg)`,transformBox:"fill-box",transformOrigin:"50% 100%",transition:c?"none":"transform 520ms cubic-bezier(.2,.8,.25,1)",filter:"url(#chain-shadow-"+a+")"},children:[Vt("rect",{x:f,y:g,width:o.width,height:o.height,rx:e.milestone?12:4,fill:"var(--semiotic-background, #fff)",stroke:h||m?"var(--semiotic-highlight, #e08a1e)":p,strokeWidth:h?4:m?3:2}),Vt("rect",{x:f+3,y:g+o.height-y+1,width:o.width-6,height:Math.max(0,y-4),rx:2,fill:p,opacity:r?.86:.46})]}),d&&_t("g",{opacity:u?.28:1,children:[Vt("line",{x1:f-8,x2:f+14,y1:o.y+9,y2:o.y-9,stroke:"var(--semiotic-error, #c64035)",strokeWidth:7,strokeLinecap:"round"}),Vt("circle",{cx:f-8,cy:o.y+9,r:3,fill:"var(--semiotic-error, #c64035)"})]}),_t("g",{onPointerDown:()=>l(e.id),style:{cursor:"pointer",pointerEvents:"auto"},children:[Vt("rect",{x:f,y:g,width:o.width,height:o.height,fill:"transparent"}),Vt("text",{x:o.x,y:o.y-4,textAnchor:"middle",fontSize:10.5,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e.label.length>24?e.label.slice(0,22)+"…":e.label}),_t("text",{x:o.x,y:o.y+12,textAnchor:"middle",fontSize:9.5,fill:"var(--semiotic-text-muted, #5f6b72)",children:[Math.round(100*e.progress),"% · ",r?"done":d?"blocked":n.armed.has(e.id)?"ready":"waiting"]})]})]},e.id)})]})}import{jsx as tn,jsxs as nn}from"react/jsx-runtime";var sn={border:0,clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},on=Dt(function(e,t){const{data:n,taskIDAccessor:s,labelAccessor:i,laneAccessor:o,dependencyAccessor:r,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:m,mode:p="snapshot",insight:f="blocker-amplification",currentTime:g,controls:y=!1,selectedTaskIDs:k,onSelectionChange:x,onObservation:b,reducedMotion:v,seed:I=31,width:D=920,height:M=620,responsiveWidth:A,responsiveHeight:T,title:S="Dependency chain reaction",description:C,className:$,accessibleTable:E=!0,enableHover:N=!0}=e,j=Ct(null),[R,W]=$t([]),P=k?Array.from(k):R,B=St(()=>new Set(P),[P]),F=Xt(g,1/0),L="settle"===v,q=St(()=>Bt({data:n,taskIDAccessor:s,labelAccessor:i,laneAccessor:o,dependencyAccessor:r,startAccessor:a,endAccessor:c,progressAccessor:l,statusAccessor:d,completionTimeAccessor:u,blockerAccessor:h,milestoneAccessor:m}),[n,s,i,o,r,a,c,l,d,u,h,m]),O=St(()=>Ft(q,{width:D,height:M}),[q,D,M]),[z,H]=$t(()=>Jt(q,p,F,L)),X=Ct(z),U=Mt(e=>{X.current=e,H(e)},[]),Y=Mt(e=>b?.(e),[b]);At(()=>{const e=Jt(q,p,F,L);j.current?.clear(),X.current=e,H(e)},[q,p,F,L]);const J=Mt(e=>{const t=B.has(e)?P.filter(t=>t!==e):[e];k||W(t),x?.(t)},[k,x,B,P]),Z=Mt(e=>{if(L)return;const t=Zt(X.current),n=[];for(const s of q.outgoing.get(e)??[]){if(t.delivered.has(s.id)||t.inFlight.has(s.id))continue;const e=O.routeByEdgeID.get(s.id);e&&(t.inFlight.add(s.id),n.push(Qt(s,e)))}n.length&&(U(t),j.current?.pushMany(n,{pacing:{ratePerSec:8}}))},[U,O,q,L]),G=Mt((e,t)=>{const n=q.byID.get(e),s=X.current;if(!n||s.completed.has(e))return;const i=Zt(s);i.completed.add(e),i.blockers.delete(e),i.armed.add(e),null!=t&&(i.currentTime=t),U(i),Y({type:"task-completed",taskID:e,datum:n.datum}),Z(e)},[U,Y,q,Z]),K=Mt(e=>{const t=Zt(X.current),n=[],s=[];for(const s of e){if(t.delivered.has(s))continue;const e=q.edges.find(e=>e.id===s);e&&(t.delivered.add(s),t.inFlight.delete(s),n.push(e))}for(const e of n){const n=q.byID.get(e.targetID);!n||t.blockers.has(n.id)||t.armed.has(n.id)||(q.incoming.get(n.id)??[]).every(e=>t.delivered.has(e.id))&&(t.armed.add(n.id),s.push(n.id))}if(n.length){U(t);for(const e of n)Y({type:"dependency-delivered",sourceID:e.sourceID,targetID:e.targetID});for(const e of s)Y({type:"task-armed",taskID:e})}},[U,Y,q]),Q=Mt((e,t)=>{const n=[],s=[];for(const e of t.readBodies()){const t=Gt(e);if(!t||X.current.delivered.has(t.edgeID))continue;const i=t.route[t.route.length-1];i&&9>=Math.hypot(e.x-i.x,e.y-i.y)&&(n.push(t.edgeID),s.push(e.id))}s.length&&t.remove(s),n.length&&K(n)},[K]),V=Mt(()=>{const e=Zt(X.current);for(const t of q.edges)e.completed.has(t.sourceID)&&e.delivered.add(t.id);e.inFlight.clear(),e.armed=Yt(q,e.delivered,e.blockers,e.completed),e.playing=!1,j.current?.settle(),U(e),Y({type:"machine-settled"})},[U,Y,q]),_=Mt(()=>{const e=Zt(X.current);e.playing=!1,U(e)},[U]),ee=Mt(()=>{const e=X.current,t=q.nodes.map(e=>({node:e,time:Ut(e)})).filter(t=>null!=t.time&&t.time>e.currentTime&&!e.completed.has(t.node.id)).sort((e,t)=>e.time-t.time||e.node.index-t.node.index)[0];if(t)return void G(t.node.id,t.time);_();const n=[...e.blockers.keys()].map(t=>zt(q,t,{completedTaskIDs:e.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);n[0]&&Y({type:"machine-stalled",blockerID:n[0].blockerID,downstreamTaskCount:n[0].downstreamTaskCount,affectedLaneCount:n[0].affectedLaneCount})},[Y,q,_,G]),te=Mt(()=>{if(L)return void V();const e=Zt(X.current);e.playing=!0,U(e)},[U,L,V]);At(()=>{if(!z.playing||"replay"!==p||L)return;const e=window.setInterval(ee,760);return()=>window.clearInterval(e)},[p,L,z.playing,ee]);const ne=Mt(()=>{j.current?.clear(),U(Jt(q,p,F,L))},[U,q,p,F,L]),se=Mt(e=>{if(!q.byID.has(e))return;const t=Zt(X.current);t.previewTaskID=e,U(t);const n=zt(q,e,{completedTaskIDs:t.completed});Y({type:"blocker-previewed",blockerID:e,downstreamTaskIDs:n.downstreamTaskIDs})},[U,Y,q]),ie=Mt(()=>{const e=Zt(X.current);e.previewTaskID=null,U(e)},[U]),oe=Mt((e,t)=>{if(!q.byID.has(e))return;const n=Zt(X.current);n.blockers.set(e,t),n.armed.delete(e),U(n)},[U,q]),re=Mt(e=>{if(!q.byID.has(e))return;const t=Zt(X.current);t.blockers.delete(e),(q.incoming.get(e)??[]).every(e=>t.delivered.has(e.id))&&t.armed.add(e),U(t)},[U,q]),ae=Mt(e=>zt(q,e,{completedTaskIDs:X.current.completed}),[q]),ce=Mt(()=>{const e=X.current;return{currentTime:e.currentTime,playing:e.playing,previewTaskID:e.previewTaskID,selectedTaskIDs:[...P],tasks:q.nodes.map(t=>({taskID:t.id,completed:e.completed.has(t.id),armed:e.armed.has(t.id),blocked:e.blockers.has(t.id),blockerReason:e.blockers.get(t.id)})),dependencies:q.edges.map(t=>({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,state:e.delivered.has(t.id)?"delivered":e.inFlight.has(t.id)?"in-flight":"waiting"}))}},[q,P]);Tt(t,()=>({play:te,pause:_,step:ee,reset:ne,settle:V,previewResolve:se,clearPreview:ie,completeTask:G,blockTask:oe,unblockTask:re,getAmplification:ae,getMachineState:ce}),[oe,ie,ae,ce,_,G,te,se,ne,V,ee,re]);const le=z.previewTaskID??P[0]??null,de=le?zt(q,le,{completedTaskIDs:z.completed}):null,ue=St(()=>new Set(de?.downstreamTaskIDs??[]),[de?.downstreamTaskIDs]),he=St(()=>function(e,t,n){return e.nodes.flatMap(s=>{const i=t.taskByID.get(s.id);if(!i)return[];const o=e.incoming.get(s.id)??[],r=o.filter(e=>n.delivered.has(e.id)).length,a=n.blockers.get(s.id),c=n.completed.has(s.id)?"completed":a?"blocked: "+a:n.armed.has(s.id)?"armed":"waiting";return[{id:s.id,label:`${s.label}, ${s.lane}, ${Math.round(100*s.progress)}%, ${c}`,description:`${r} of ${o.length} prerequisites delivered.`,datum:s.datum,x:i.x,y:i.y,width:i.width,height:i.height,shape:"rect",group:s.lane}]})}(q,O,z),[O,q,z]),me=St(()=>tn(en,{machine:q,layout:O,runtime:z,downstreamSet:ue,selectedSet:B,width:D,height:M,seed:I,reduced:L,onSelectTask:J}),[ue,M,O,q,L,z,I,J,B,D]),pe=St(()=>{const e=[...z.blockers.keys()].map(e=>zt(q,e,{completedTaskIDs:z.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);return e.length?e.map(e=>`${q.byID.get(e.blockerID)?.label??e.blockerID} affects ${e.downstreamTaskCount} unfinished tasks across ${e.affectedLaneCount} lanes.`).join(" "):"No explicit blockers are active."},[q,z.blockers,z.completed]),fe=St(()=>[{id:"chain-left",shape:{type:"segment",x1:2,y1:0,x2:2,y2:M,thickness:4}},{id:"chain-right",shape:{type:"segment",x1:D-2,y1:0,x2:D-2,y2:M,thickness:4}},{id:"chain-top",shape:{type:"segment",x1:0,y1:2,x2:D,y2:2,thickness:4}},{id:"chain-bottom",shape:{type:"segment",x1:0,y1:M-2,x2:D,y2:M-2,thickness:4}}],[M,D]),ge=!0===y?["play","pause","step","reset","settle"]:y||[];return nn("div",q.valid?{className:$,style:{width:D,maxWidth:"100%",position:"relative"},children:[ge.length>0&&tn("div",{"aria-label":"Chain reaction replay controls",style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8},children:ge.map(e=>tn("button",{type:"button",onClick:"play"===e?te:"pause"===e?_:"step"===e?ee:"reset"===e?ne:V,"aria-pressed":"play"===e?z.playing:void 0,children:e[0].toUpperCase()+e.slice(1)},e))}),tn(w,{ref:j,size:[D,M],responsiveWidth:A,responsiveHeight:T,title:S,description:C??"Tasks are arranged by workstream and dependency depth. Balls represent satisfied prerequisites; task completion remains an explicit data event.",summary:`${pe}${de&&"blocker-amplification"===f?` Selected task reaches ${de.downstreamTaskCount} unfinished tasks across ${de.affectedLaneCount} lanes.`:""}`,accessibleTable:!1,enableHover:N,initialSpawns:Ht,bodyForces:Kt,bodyStyle:{fill:"var(--semiotic-accent, #f0a329)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.25},bodySemanticItems:!1,semanticItems:he,onSemanticItemActivate:e=>e.id&&J(e.id),foregroundGraphics:()=>me,paused:L,continuous:z.inFlight.size>0,onTick:Q,config:{bodyLimit:Math.max(16,q.edges.length+4),colliders:fe,settleStepLimit:2200,kernel:{seed:I,gravity:{x:0,y:7},fixedDt:1/60,cellSize:28,collisionIterations:2,velocityDamping:.992,restitution:.02,friction:.12,maxVelocity:150,sleepSpeed:1.1,sleepAfter:.8},observation:{chartType:"ChainReactionChart"}}}),E&&nn("table",{style:sn,children:[tn("caption",{children:pe}),tn("thead",{children:nn("tr",{children:[tn("th",{children:"Task"}),tn("th",{children:"Lane"}),tn("th",{children:"Progress"}),tn("th",{children:"State"}),tn("th",{children:"Waiting on"}),tn("th",{children:"Downstream reach"})]})}),tn("tbody",{children:q.nodes.map(e=>{const t=zt(q,e.id,{completedTaskIDs:z.completed});return nn("tr",{children:[tn("th",{scope:"row",children:e.label}),tn("td",{children:e.lane}),nn("td",{children:[Math.round(100*e.progress),"%"]}),tn("td",{children:z.completed.has(e.id)?"Completed":z.blockers.has(e.id)?"Blocked":z.armed.has(e.id)?"Armed":"Waiting"}),tn("td",{children:z.blockers.get(e.id)??(e.dependencyIDs.filter(e=>!z.completed.has(e)).join(", ")||"None")}),nn("td",{children:[t.downstreamTaskCount," tasks / ",t.affectedLaneCount," lanes"]})]},e.id)})})]})]}:{className:$,role:"alert",style:{width:D,maxWidth:"100%"},children:[tn("strong",{children:"ChainReactionChart could not compile this dependency graph."}),tn("ul",{children:q.diagnostics.map((e,t)=>tn("li",{children:e.message},`${e.code}-${t}`))})]})});on.displayName="ChainReactionChart";var rn=w;export{s as BuiltInPhysicsEngineAdapter,on as ChainReactionChart,i as CollisionSwarmChart,o as CrucibleChart,r as DEFAULT_CRUCIBLE_HEIGHT,a as DEFAULT_CRUCIBLE_OUTLETS,c as DEFAULT_CRUCIBLE_SIZE,l as DEFAULT_CRUCIBLE_WIDTH,d as EventDropChart,u as GaltonBoardChart,h as GauntletChart,m as GuantletChart,p as PhysicalFlowChart,f as PhysicsCustomChart,g as PhysicsPileChart,y as PhysicsPipelineStore,k as PhysicsSVGOverlay,x as PhysicsSedimentAccumulator,b as ProcessFlowChart,v as StreamPhysicsFrame,I as absorbRegion,D as aggregateRegionCounts,M as applyCrucibleEvent,It as arrivalReplay,A as bodiesToAnnotationAnchors,T as bodyGroupSpec,S as buildCollisionSwarmPhysics,C as buildCrucibleEvidence,$ as buildCrucibleInitialSpawns,E as buildCrucibleLayout,N as buildCruciblePhysicsConfig,j as buildCrucibleProductEvents,R as buildCrucibleProjection,W as buildCrucibleStateSpawns,P as buildCrucibleTerminalSpawns,B as buildEventDropPhysics,F as buildGaltonBoardPhysics,L as buildPhysicalFlowPhysics,q as buildPhysicsAnnotationContext,O as buildPhysicsPile,z as buildProcessFlowPhysics,zt as calculateBlockerAmplification,H as capacitatedRegion,X as chargeGateRegion,U as cloneCrucibleState,xt as collidersFromScales,mt as comparePhysicsTrace,Z as compileCruciblePlan,Bt as compileDependencyMachine,ze as compileMotionEncoding,Ve as compilePhysicsEncoding,G as composePhysicsControllers,Be as composeStyleRules,K as createCapacityQueueController,Q as createDefaultPhysicsEngineAdapter,V as createDependencyGateController,_ as createInitialCrucibleState,Lt as createLogicalJoin,_e as createPhysicsEncodingLayout,ee as createPortalController,e as createProcessJourneyLedger,te as createServiceLevelController,ne as createServiceResourcePoolController,se as crucibleBondId,ie as crucibleBoundaryColliders,oe as crucibleComponentBodyId,re as crucibleProductBodyId,ae as crucibleProjectionRows,ce as crucibleSemanticKey,rn as default,He as deriveMotionVector,le as evaluateCrucibleConservation,de as evaluatePhysicsBodyBudget,ue as forceFieldRegion,bt as galtonPegs,he as groupCompletionRows,Xe as hatchFillId,Ue as hatchPatternDef,Ye as isHatchFill,Fe as makeRuleValueResolver,Le as matchesThreshold,me as membraneRegion,pe as normalizePhysicsAnnotations,Je as opacityFromAge,fe as physicsProcessBoundaryColliders,ge as physicsProcessGroupSemanticItems,ye as physicsProcessRegionSemanticItem,ke as physicsProcessStageSemanticItems,ct as physicsReferenceEnvelope,xe as planGauntletPropertyWork,be as portalRegion,ve as pressureFieldRegion,we as processChrome,t as processJourneyRows,Ie as processLaneWalls,De as processStageLayout,Me as processStageRegions,Ae as processVolumePolygons,Te as regionCountsToProjectionRows,Se as replaceGauntletNegative,Ce as replayCruciblePlan,Ot as replayStateTransitions,$e as resolveCrucibleSelector,Ee as resolveCrucibleSnapshotAt,Ne as resolveCrucibleTime,Ze as resolveMotionAccessor,Ge as resolveMotionAge,Ke as resolveMotionVector,qe as resolveStyleRules,Qe as resolveSvgFill,Ft as routeDependencyTracks,je as routeSurfaceRegion,Oe as ruleMatches,wt as sedimentBake,Re as sedimentHeightfield,vt as spawnFromTokens,We as stageTargetInVolume,n as updateProcessJourney};
2
+ import{createProcessJourneyLedger as e,processJourneyRows as t,updateProcessJourney as n}from"./chunk-chunk-YWZB3KPI.module.min.js";import{ChainReactionChart as i,calculateBlockerAmplification as o,compileDependencyMachine as r,createLogicalJoin as s,replayStateTransitions as a,routeDependencyTracks as l}from"./chunk-chunk-FRO4TRXK.module.min.js";import{CollisionSwarmChart as u,CrucibleChart as c,DEFAULT_CRUCIBLE_HEIGHT as p,DEFAULT_CRUCIBLE_OUTLETS as h,DEFAULT_CRUCIBLE_SIZE as m,DEFAULT_CRUCIBLE_WIDTH as d,EventDropChart as f,GaltonBoardChart as y,GauntletChart as w,GuantletChart as g,PacketFlowChart as x,PhysicalFlowChart as b,PhysicsPileChart as v,ProcessFlowChart as k,UnitPileChart as M,applyCrucibleEvent as A,applyGauntletEffect as P,buildCrucibleEvidence as j,buildCrucibleInitialSpawns as E,buildCrucibleLayout as S,buildCruciblePhysicsConfig as $,buildCrucibleProductEvents as N,buildCrucibleProjection as R,buildCrucibleStateSpawns as D,buildCrucibleTerminalSpawns as I,cloneCrucibleState as q,compileCruciblePlan as W,createInitialCrucibleState as X,crucibleBondId as T,crucibleBoundaryColliders as Y,crucibleComponentBodyId as B,crucibleProductBodyId as C,crucibleProjectionRows as F,crucibleSemanticKey as O,defaultViability as Z,evaluateCrucibleConservation as J,eventLogItem as z,physicsProcessBoundaryColliders as H,physicsProcessGroupSemanticItems as K,physicsProcessRegionSemanticItem as L,physicsProcessStageSemanticItems as G,planGauntletPropertyWork as U,processChrome as V,recordGauntletEvent as _,replaceGauntletNegative as Q,replayCruciblePlan as ee,resolveCrucibleSelector as te,resolveCrucibleSnapshotAt as ne,resolveCrucibleTime as ie}from"./chunk-chunk-Z2AJERX5.module.min.js";import{BuiltInPhysicsEngineAdapter as oe,PhysicsCustomChart as re,PhysicsPipelineStore as se,PhysicsSVGOverlay as ae,PhysicsSedimentAccumulator as le,StreamPhysicsFrame as ue,StreamPhysicsFrame_default as ce,absorbRegion as pe,aggregateRegionCounts as he,bodiesToAnnotationAnchors as me,bodyGroupSpec as de,buildCollisionSwarmPhysics as fe,buildEventDropPhysics as ye,buildGaltonBoardPhysics as we,buildPhysicalFlowPhysics as ge,buildPhysicsAnnotationContext as xe,buildPhysicsPile as be,buildProcessFlowPhysics as ve,capacitatedRegion as ke,chargeGateRegion as Me,collidersFromPlotBounds as Ae,collidersFromXScaleBins as Pe,composePhysicsControllers as je,createCapacityQueueController as Ee,createDefaultPhysicsEngineAdapter as Se,createDependencyGateController as $e,createPortalController as Ne,createServiceLevelController as Re,createServiceResourcePoolController as De,evaluatePhysicsBodyBudget as Ie,forceFieldRegion as qe,groupCompletionRows as We,membraneRegion as Xe,normalizePhysicsAnnotations as Te,portalRegion as Ye,pressureFieldRegion as Be,processLaneWalls as Ce,processStageLayout as Fe,processStageRegions as Oe,processVolumePolygons as Ze,regionCountsToProjectionRows as Je,routeSurfaceRegion as ze,sedimentHeightfield as He,stageTargetInVolume as Ke}from"./chunk-chunk-NW25WGLS.module.min.js";import{mulberry32 as Le}from"./chunk-chunk-SIRIJ3DY.module.min.js";import{composeStyleRules as Ge,makeRuleValueResolver as Ue,matchesThreshold as Ve,resolveStyleRules as _e,ruleMatches as Qe}from"./chunk-chunk-EMO5NUGE.module.min.js";import"./chunk-chunk-SV4XAZ3Q.module.min.js";import"./chunk-chunk-JWXLNZSM.module.min.js";import{compileMotionEncoding as et,deriveMotionVector as tt,opacityFromAge as nt,resolveMotionAccessor as it,resolveMotionAge as ot,resolveMotionVector as rt}from"./chunk-chunk-5SD6BHVW.module.min.js";import{hatchFillId as st,hatchPatternDef as at,isHatchFill as lt,resolveSvgFill as ut}from"./chunk-chunk-7ZDJSYKI.module.min.js";import"./chunk-chunk-JJ2OOIET.module.min.js";import"./chunk-chunk-WCX6U47H.module.min.js";import"./chunk-chunk-KTWEBFMX.module.min.js";import"./chunk-chunk-ACLDBMRH.module.min.js";import"./chunk-chunk-YHNZCPOZ.module.min.js";function ct(e){const{data:t,encoding:n,defaults:i={},scales:o}=e,r=et({data:t,encoding:n}),s=[],a=new Map,l=[],u=[],c=new Map;return r.rows.forEach((e,t)=>{const{id:r,datum:p}=e,h=Math.max(0,it(n.appearance?.size,p,t)??i.size??6),m=it(n.appearance?.shape,p,t)??i.shape??{type:"circle",radius:h},d=e.placement.x??i.x??0,f=e.placement.y??i.y??0,y=o?.x?o.x(d):d,w=o?.y?o.y(f):f,g=it(n.appearance?.color,p,t)??i.color,x=it(n.appearance?.opacity,p,t)??i.opacity,b=it(n.appearance?.stroke,p,t)??i.stroke,v=it(n.appearance?.strokeWidth,p,t)??i.strokeWidth,k=it(n.time?.spawnAt,p,t)??e.time.arrival,M=e.kinematics.velocityX,A=e.kinematics.velocityY,P=it(n.dynamics?.mass,p,t)??i.mass??1,j=it(n.dynamics?.friction,p,t),E=it(n.dynamics?.restitution,p,t),S=it(n.dynamics?.bodyCollisions,p,t),$={id:r,x:y,y:w,mass:P,shape:{...m},datum:p,...null!=k&&{spawnAt:k},...null!=M&&{vx:M},...null!=A&&{vy:A},...null!=j&&{friction:j},...null!=E&&{restitution:E},...null!=S&&{bodyCollisions:S}},N={...null!=g&&{fill:g},...null!=x&&{opacity:x},...null!=b&&{stroke:b},...null!=v&&{strokeWidth:v}},R={id:r,datum:p,appearance:{color:g,opacity:x,shape:m,size:h,stroke:b,strokeWidth:v},placement:{x:y,y:w,lane:e.placement.lane,space:n.placement?.space??"world"},time:{arrival:k,spawnAt:k,basis:n.time?.basis??"simulation",unit:n.time?.unit},kinematics:{velocityX:M,velocityY:A,space:n.kinematics?.space??"world"},dynamics:{bodyCollisions:S,friction:j,mass:P,restitution:E},process:e.process,evidence:e.evidence,accessible:e.accessible,spawn:$};s.push(R),a.set(r,R),l.push($),c.set(r,N),u.push({id:r,bodyId:r,label:e.accessible.label,description:e.accessible.description,datum:p,x:y,y:w,group:e.accessible.group})}),{rows:s,byId:a,spawns:l,semanticItems:u,bodyStyle:e=>c.get(e.id)??{}}}function pt(e){return t=>{const n=ct({data:t.data,encoding:e.encoding,defaults:e.defaults,scales:t.scales}),i=e.extend?.(t,n)??{};return{...i,initialSpawns:n.spawns,bodyStyle:n.bodyStyle,semanticItems:[...n.semanticItems,...i.semanticItems??[]]}}}function ht(e,t){const{layout:n,positiveProperties:i,negativeProperties:o,viability:r,outcome:s}=t,a=function(e){return new Map(e.gates.map(e=>[e.id,e]))}(n),l=[...("function"==typeof t.events?t.events(e,n):t.events)??[]].sort((e,t)=>e.time-t.time);let u=e;for(const e of l){const t=e.gateId?a.get(e.gateId):void 0,l=e.effects??[],c={...z(e,l),appliedAt:e.time},p=_(u,c);if(p!==u){u=p;for(const n of l){const r={event:e,gate:t,negativeProperties:o,positiveProperties:i,project:u};n.when&&!n.when(r)||(u=P(u,n,r))}u={...u,viability:r?.(u,{negativeProperties:o,positiveProperties:i})??Z(u,i,o)},e.final&&(u={...u,outcome:e.outcome??s?.(u,{layout:n,negativeProperties:o,positiveProperties:i})??(u.viability>20?"built":"approved_not_built")})}}return u}function mt(e){return e.projects.map(t=>ht(t,e))}var dt=[.1,.5,.9],ft=1e6;function yt(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function wt(e,t,n,i,o){return"function"==typeof i?i(e,t,n):function(e,t){let n=e;for(const e of t.split(".")){if(null==n||"object"!=typeof n)return;n=n[e]}return n}(e,i??o)}function gt(e){const t=Number(e.toFixed(12));return Object.is(t,-0)?0:t}function xt(e,t,n,i){const o=e.flatMap((e,o)=>{const r=yt(wt(e,o,t,n,"time")),s=yt(wt(e,o,t,i,"value"));return null==r||null==s?[]:[{time:gt(r),value:s,index:o}]});o.sort((e,t)=>e.time-t.time||e.index-t.index);const r=[];for(const e of o){const t=r[r.length-1];t?.time===e.time?t.value=e.value:r.push({time:e.time,value:e.value})}return r}function bt(e,t,n,i){if(!e.length)return null;const o=e[0],r=e[e.length-1];if(o.time>t)return"clamp"===i?o.value:null;if(t>r.time)return"clamp"===i?r.value:null;const s=function(e,t){let n=0,i=e.length;for(;i>n;){const o=n+i>>>1;t>e[o].time?n=o+1:i=o}return n}(e,t),a=e[s];if(a?.time===t)return a.value;const l=e[Math.max(0,s-1)];return"step"!==n&&a&&a.time!==l.time?l.value+(t-l.time)/(a.time-l.time)*(a.value-l.value):l.value}function vt(e,t){if(1===e.length)return e[0];const n=(e.length-1)*t,i=Math.floor(n),o=Math.ceil(n);return i===o?e[i]:e[i]+(e[o]-e[i])*(n-i)}function kt(e){const t=e.interpolation??"step",n=e.outsideDomain??"omit",i=function(e){const t=(e??dt).map(e=>{const t=yt(e);if(null==t||0>t||t>1)throw new RangeError("physicsReferenceEnvelope quantiles must be finite values from 0 to 1; received "+e);return gt(t)});return Array.from(new Set(t)).sort((e,t)=>e-t)}(e.quantiles),o=function(e){if(Array.isArray(e)){if(e.length>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(e.map(yt).filter(e=>null!=e).map(gt))).sort((e,t)=>e-t)}const t=e,n=yt(t.start),i=yt(t.end),o=yt(t.step);if(null==n||null==i||null==o||0>=o||n>i)throw new RangeError("physicsReferenceEnvelope sampleAt requires finite start/end values with end >= start and step > 0");const r=Math.floor((i-n)/o)+1;if(r>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");const s=[],a=1e-10*Math.max(1,Math.abs(i),Math.abs(n));for(let e=0;r>e;e+=1){const t=n+e*o;if(t>i+a)break;s.push(gt(Math.min(t,i)))}if(s.length&&a>=Math.abs(s[s.length-1]-i)||s.push(gt(i)),s.length>ft)throw new RangeError("physicsReferenceEnvelope sampleAt exceeds 1000000 points");return Array.from(new Set(s)).sort((e,t)=>e-t)}(e.sampleAt),r=e.runs.map(t=>xt(t.samples,t.id,e.timeAccessor,e.valueAccessor));return{points:o.map(e=>{const o=r.map(i=>bt(i,e,t,n)).filter(e=>null!=e).sort((e,t)=>e-t),s={};for(const e of i)s[e]=o.length?vt(o,e):null;return{time:e,count:o.length,min:o.length?o[0]:null,max:o.length?o[o.length-1]:null,median:o.length?vt(o,.5):null,quantiles:s}}),quantiles:i,interpolation:t,outsideDomain:n,runCount:e.runs.length}}function Mt(e,t){return e.quantiles.length?"lower"===t?e.quantiles[0]:e.quantiles[e.quantiles.length-1]:"lower"===t?"min":"max"}function At(e,t){if("min"===t||"median"===t||"max"===t)return e[t];const n=yt(t);if(null==n||0>n||n>1)throw new RangeError("comparePhysicsTrace quantile selectors must be from 0 to 1; received "+t);const i=gt(n);if(!Object.prototype.hasOwnProperty.call(e.quantiles,i))throw Error(`comparePhysicsTrace could not find quantile ${i} in the reference envelope`);return e.quantiles[i]??null}function Pt(e,t,n){return t>e?"below":e>n?"above":"inside"}function jt(e,t){const n=Math.max(0,t.time-e.time);if(0>=n||null==e.value||null==e.lower||null==e.upper||null==t.value||null==t.lower||null==t.upper)return{below:0,inside:0,above:0,observed:0};const i=e.value-e.lower,o=t.value-t.lower,r=e.value-e.upper,s=t.value-t.upper,a=[0,1];for(const[e,t]of[[i,o],[r,s]])(0>e&&t>0||e>0&&0>t)&&a.push(-e/(t-e));a.sort((e,t)=>e-t);let l=0,u=0,c=0;for(let i=0;a.length-1>i;i+=1){const o=a[i],r=a[i+1];if(o>=r)continue;const s=(o+r)/2,p=(r-o)*n,h=Pt(e.value+(t.value-e.value)*s,e.lower+(t.lower-e.lower)*s,e.upper+(t.upper-e.upper)*s);"below"===h?l+=p:"above"===h?c+=p:u+=p}return{below:l,inside:u,above:c,observed:n}}function Et(e,t,n={}){const i=n.interpolation??t.interpolation,o=n.outsideDomain??t.outsideDomain,r=xt(e,n.traceId??"trace",n.timeAccessor,n.valueAccessor),s=n.lower??Mt(t,"lower"),a=n.upper??Mt(t,"upper"),l=t.points.map(e=>{const t=bt(r,e.time,i,o),n=At(e,s),l=At(e,a);if(null!=n&&null!=l&&n>l)throw new RangeError("comparePhysicsTrace lower band exceeds upper band at time "+e.time);return{time:e.time,value:t,lower:n,upper:l,status:null==t||null==n||null==l?"unobserved":Pt(t,n,l)}});let u=0,c=0,p=0,h=0,m=null,d=0,f=null;for(const e of l){if("below"===e.status?u+=1:"inside"===e.status?c+=1:"above"===e.status&&(p+=1),null==e.value||null==e.lower||null==e.upper)continue;const t=Math.max(0,e.value-e.upper),n=Math.max(0,e.lower-e.value);t>h&&(h=t,m=e.time),n>d&&(d=n,f=e.time)}let y=0,w=0,g=0,x=0;for(let e=0;l.length-1>e;e+=1){const t=l[e],n=l[e+1],o=Math.max(0,n.time-t.time);if(o>0){if("linear"===i){const e=jt(t,n);y+=e.below,w+=e.inside,g+=e.above,x+=e.observed;continue}"unobserved"!==t.status&&(x+=o,"below"===t.status?y+=o:"above"===t.status?g+=o:w+=o)}}const b=l[0]?.time,v=l[l.length-1]?.time,k=null==b||null==v?0:Math.max(0,v-b);return{points:l,sampleCount:l.length,observedSamples:u+c+p,belowSamples:u,insideSamples:c,aboveSamples:p,totalDuration:k,observedDuration:x,unobservedDuration:Math.max(0,k-x),belowDuration:y,insideDuration:w,aboveDuration:g,peakExcess:h,peakExcessAt:m,peakDeficit:d,peakDeficitAt:f}}function St(e){const[t,n]=e.size,i=e.flow??"down",o=null==(v=e.padding)?{top:24,right:24,bottom:24,left:24}:"number"==typeof v?{top:v,right:v,bottom:v,left:v}:{top:v.top??0,right:v.right??0,bottom:v.bottom??0,left:v.left??0},r=Math.max(.05,Math.min(1,e.channelRatio??1)),s={x:o.left,y:o.top,width:Math.max(1,t-o.left-o.right),height:Math.max(1,n-o.top-o.bottom)},a="down"===i?s.height:s.width,l=a*Math.max(0,e.chargeExtent??.12),u=a*Math.max(0,e.projectionExtent??0),c=a*Math.max(0,e.destinationExtent??.55),p=Math.max(0,a-l-c-u),h=function(e){return"number"==typeof e?Array.from({length:Math.max(1,Math.round(e))},(e,t)=>({id:"bin-"+t,label:t+""})):0===e.length?[{id:"bin-0",label:"0"}]:e.map((e,t)=>({id:e.id,label:e.label??e.id??t+""}))}(e.destinations),m=("down"===i?s.width:s.height)/h.length,d="down"===i?(e,t)=>({x:s.x,y:s.y+e,width:s.width,height:t}):(e,t)=>({x:s.x+e,y:s.y,width:t,height:s.height}),f=d(0,l),y=d(l,p),w=l+p,g=d(w,c),x=d(w+c,u),b=h.map((e,t)=>{const n=t*m,o=m*r,a=(m-o)/2;return"down"===i?{id:e.id,label:e.label,order:t,x:s.x+n+a,y:g.y,width:o,height:g.height,centerX:s.x+(t+.5)*m,centerY:g.y+g.height/2}:{id:e.id,label:e.label,order:t,x:g.x,y:s.y+n+a,width:g.width,height:o,centerX:g.x+g.width/2,centerY:s.y+(t+.5)*m}});var v;return{width:t,height:n,flow:i,charge:f,apparatus:y,destinations:b,projection:x}}function $t(e,t){return e.destinations.find(e=>e.id===t)}function Nt(e,t,n){const{charge:i,flow:o}=e,r=Math.max(1,n),s=(t%r+.5)/r;return"down"===o?{x:i.x+i.width*s,y:i.y+i.height/2}:{x:i.x+i.width/2,y:i.y+i.height*s}}function Rt(e,t={}){const n=t.thickness??4,i=t.idPrefix??"stage",{destinations:o,flow:r,width:s,height:a}=e,l=[];if(o.length>0){const t=o[0];if("down"===r){const r=t.y+t.height;l.push({id:i+"-floor",shape:{type:"segment",x1:e.charge.x,y1:r,x2:e.charge.x+e.charge.width,y2:r,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerX-(o[e].centerX-o[e-1].centerX)/2;l.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:s,y1:t.y,x2:s,y2:r,thickness:n}})}}else{const r=t.x+t.width;l.push({id:i+"-floor",shape:{type:"segment",x1:r,y1:e.charge.y,x2:r,y2:e.charge.y+e.charge.height,thickness:n}});for(let e=1;o.length>e;e+=1){const s=o[e].centerY-(o[e].centerY-o[e-1].centerY)/2;l.push({id:`${i}-divider-${e}`,shape:{type:"segment",x1:t.x,y1:s,x2:r,y2:s,thickness:n}})}}}return!1!==t.walls&&l.push({id:i+"-wall-left",shape:{type:"segment",x1:1,y1:0,x2:1,y2:a,thickness:n}},{id:i+"-wall-right",shape:{type:"segment",x1:s-1,y1:0,x2:s-1,y2:a,thickness:n}}),l}function Dt(e,t={}){return`${t.charge??"bodies"} enter at the ${"down"===e.flow?"top":"left"}, travel ${"down"===e.flow?"downward":"left to right"} through ${t.apparatus??"the apparatus"}, and come to rest in ${e.destinations.length} ${t.destination??"destinations"}: ${e.destinations.map(e=>e.label).join(", ")}.`}function It(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function qt(e,t,n,i){const o="function"==typeof e?e(t,n):e;return Number.isFinite(o)?Number(o):i}function Wt(e,t,n){return It(e[t])??n}function Xt(e,t){return"number"==typeof e?e:e?.[t]??0}function Tt(e){const{band:t,idPrefix:n,plot:i,projection:o}=e,{includeBoundaryWalls:r=!0,includeInteriorWalls:s=!0,wallThickness:a=4}=t,l=function(e){const t=e.bandwidth??e.scale.bandwidth?.()??0,n=new Set;for(const i of e.values){const o=e.scale(i);Number.isFinite(o)&&(n.add(Number(o)),n.add(Number(o)+t))}return Array.from(n).sort((e,t)=>e-t)}(t);if(2>l.length)return[];const u=r?l.length-1:l.length-2,c=[];for(let e=r?0:1;u>=e;e+=1){if(!s&&e>0&&l.length-1>e)continue;const t=l[e];c.push({id:`${n}-wall-${e}`,shape:"x"===o?{type:"aabb",x:t,y:i.y+i.height/2,width:a,height:i.height}:{type:"aabb",x:i.x+i.width/2,y:t,width:i.width,height:a}})}return c}function Yt(e){const{plot:t,idPrefix:n="physics-scale",bounds:i={},xBins:o,xBands:r,yBands:s}=e,a=[];if(!1!==i&&a.push(...Ae(t,{idPrefix:n,...i})),o){const{idPrefix:e,yTop:i,yBottom:r,...s}=o;a.push(...Pe({...s,idPrefix:e??n+"-xbin",yTop:i??t.y,yBottom:r??t.y+t.height}))}return r&&a.push(...Tt({band:r,idPrefix:r.idPrefix??n+"-xband",plot:t,projection:"x"})),s&&a.push(...Tt({band:s,idPrefix:s.idPrefix??n+"-yband",plot:t,projection:"y"})),a}function Bt(e){const{plot:t,rows:n,columns:i=n+1,pegRadius:o=3,idPrefix:r="galton-peg",yStart:s=t.y+.18*t.height,yEnd:a=t.y+.58*t.height,stagger:l=!0,restitution:u=.2,friction:c=.04}=e,p=Math.max(0,Math.floor(n)),h=Math.max(1,Math.floor(i));if(0===p)return[];const m=p>1?(a-s)/(p-1):0,d=t.width/h,f=[];for(let e=0;p>e;e+=1){const n=l&&e%2==1?d/2:0;for(let i=0;h>i;i+=1){const a=t.x+d*(i+.5)+n;t.x+o>a||a>t.x+t.width-o||f.push({id:`${r}-${e}-${i}`,shape:{type:"aabb",x:a,y:s+e*m,width:2*o,height:2*o},restitution:u,friction:c})}}return f}function Ct(e,t={}){const{idPrefix:n="physics-token",radius:i=5,shape:o,mass:r,vx:s,vy:a,spawnAt:l,seed:u=1,jitter:c,datum:p}=t,h=Le(u),m=Xt(c,"x"),d=Xt(c,"y");return e.map((e,u)=>{const c=qt(t.x,e,u,Wt(e,"x",0)),f=qt(t.y,e,u,Wt(e,"y",0)),y=qt(i,e,u,5),w="function"==typeof o?o(e,u):o??{type:"circle",radius:y};return{id:`${n}-${e.index??u}`,x:c+(h()-.5)*m,y:f+(h()-.5)*d,vx:qt(s,e,u,0),vy:qt(a,e,u,0),mass:qt(r,e,u,1),spawnAt:qt(l,e,u,void 0),shape:w,datum:p?p(e,u):e.datum??e}}).map(e=>{if(Number.isFinite(e.spawnAt))return e;const{spawnAt:t,...n}=e;return n})}function Ft(e,t={}){const{idPrefix:n="sediment",collider:i=!0,colliderThickness:o=1,restitution:r=.05,friction:s=.2,...a}=t,l=He(e,a),u=i?l.filter(e=>e.height>0).map(e=>({id:`${n}-${e.binId}`,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+o/2,width:e.width,height:o},restitution:r,friction:s})):[];return{columns:l,colliders:u}}function Ot(e,t={}){const{timeAccessor:n="arrivalTime",timeScale:i=1,startAt:o=0,rebase:r=!0,sort:s=!0}=t,a=e.map((e,t)=>({spawn:e,time:function(e,t,n){return It("function"==typeof n?n(e,t):e[n]??e.datum?.[n])}(e,t,n)??e.spawnAt??t})),l=a.length?Math.min(...a.map(e=>e.time)):0;return{initialSpawns:a.map(({spawn:e,time:t})=>({...e,spawnAt:o+(r?t-l:t)})).sort((e,t)=>s?(e.spawnAt??0)-(t.spawnAt??0):0),initialSpawnPacing:{pacing:"arrival",startAt:o,timeAccessor:"spawnAt",timeScale:i}}}var Zt=ce;export{oe as BuiltInPhysicsEngineAdapter,i as ChainReactionChart,u as CollisionSwarmChart,c as CrucibleChart,p as DEFAULT_CRUCIBLE_HEIGHT,h as DEFAULT_CRUCIBLE_OUTLETS,m as DEFAULT_CRUCIBLE_SIZE,d as DEFAULT_CRUCIBLE_WIDTH,f as EventDropChart,y as GaltonBoardChart,w as GauntletChart,g as GuantletChart,x as PacketFlowChart,b as PhysicalFlowChart,re as PhysicsCustomChart,v as PhysicsPileChart,se as PhysicsPipelineStore,ae as PhysicsSVGOverlay,le as PhysicsSedimentAccumulator,k as ProcessFlowChart,ue as StreamPhysicsFrame,M as UnitPileChart,pe as absorbRegion,he as aggregateRegionCounts,A as applyCrucibleEvent,Ot as arrivalReplay,me as bodiesToAnnotationAnchors,de as bodyGroupSpec,fe as buildCollisionSwarmPhysics,j as buildCrucibleEvidence,E as buildCrucibleInitialSpawns,S as buildCrucibleLayout,$ as buildCruciblePhysicsConfig,N as buildCrucibleProductEvents,R as buildCrucibleProjection,D as buildCrucibleStateSpawns,I as buildCrucibleTerminalSpawns,ye as buildEventDropPhysics,we as buildGaltonBoardPhysics,ge as buildPhysicalFlowPhysics,xe as buildPhysicsAnnotationContext,be as buildPhysicsPile,ve as buildProcessFlowPhysics,o as calculateBlockerAmplification,ke as capacitatedRegion,Me as chargeGateRegion,q as cloneCrucibleState,Yt as collidersFromScales,Et as comparePhysicsTrace,W as compileCruciblePlan,r as compileDependencyMachine,et as compileMotionEncoding,ct as compilePhysicsEncoding,je as composePhysicsControllers,Ge as composeStyleRules,Ee as createCapacityQueueController,Se as createDefaultPhysicsEngineAdapter,$e as createDependencyGateController,X as createInitialCrucibleState,s as createLogicalJoin,pt as createPhysicsEncodingLayout,Ne as createPortalController,e as createProcessJourneyLedger,Re as createServiceLevelController,De as createServiceResourcePoolController,T as crucibleBondId,Y as crucibleBoundaryColliders,B as crucibleComponentBodyId,C as crucibleProductBodyId,F as crucibleProjectionRows,O as crucibleSemanticKey,Zt as default,tt as deriveMotionVector,Dt as describePhysicsStageGeography,J as evaluateCrucibleConservation,Ie as evaluatePhysicsBodyBudget,qe as forceFieldRegion,Bt as galtonPegs,We as groupCompletionRows,st as hatchFillId,at as hatchPatternDef,lt as isHatchFill,Ue as makeRuleValueResolver,Ve as matchesThreshold,Xe as membraneRegion,Te as normalizePhysicsAnnotations,nt as opacityFromAge,Nt as physicsChargePoint,$t as physicsDestination,H as physicsProcessBoundaryColliders,K as physicsProcessGroupSemanticItems,L as physicsProcessRegionSemanticItem,G as physicsProcessStageSemanticItems,kt as physicsReferenceEnvelope,Rt as physicsStageColliders,St as physicsStageGeography,U as planGauntletPropertyWork,Ye as portalRegion,Be as pressureFieldRegion,V as processChrome,t as processJourneyRows,Ce as processLaneWalls,Fe as processStageLayout,Oe as processStageRegions,Ze as processVolumePolygons,Je as regionCountsToProjectionRows,Q as replaceGauntletNegative,ee as replayCruciblePlan,a as replayStateTransitions,te as resolveCrucibleSelector,ne as resolveCrucibleSnapshotAt,ie as resolveCrucibleTime,ht as resolveGauntletTerminalState,mt as resolveGauntletTerminalStates,it as resolveMotionAccessor,ot as resolveMotionAge,rt as resolveMotionVector,_e as resolveStyleRules,ut as resolveSvgFill,l as routeDependencyTracks,ze as routeSurfaceRegion,Qe as ruleMatches,Ft as sedimentBake,He as sedimentHeightfield,Ct as spawnFromTokens,Ke as stageTargetInVolume,n as updateProcessJourney};
@@ -1 +1 @@
1
- function e(e){let t=e>>>0;return function(){t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}var t={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},s=1e-9,i=.005;function n(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function o(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function r(e,t,s){return Math.max(t,Math.min(s,e))}function a(e){return e<0?-1:1}function d(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,s=e.shape.height/2;return{minX:e.x-t,minY:e.y-s,maxX:e.x+t,maxY:e.y+s}}function h(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,s=t.height/2;return{minX:t.x-e,minY:t.y-s,maxX:t.x+e,maxY:t.y+s}}const s=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-s,minY:Math.min(t.y1,t.y2)-s,maxX:Math.max(t.x1,t.x2)+s,maxY:Math.max(t.y1,t.y2)+s}}function c(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function l(e,t,s,i,n,o,r,d){const h=n-e,c=(s+r)/2-Math.abs(h);if(c<=0)return null;const l=o-t,u=(i+d)/2-Math.abs(l);return u<=0?null:c<u?{nx:a(h),ny:0,penetration:c}:{nx:0,ny:a(l),penetration:u}}function u(e,t,i,n,o,a,d){const h=a/2,c=d/2;let l=e-r(e,n-h,n+h),u=t-r(t,o-c,o+c);const p=l*l+u*u;if(p>i*i)return null;if(p<=s){const s=Math.abs(e-(n-h)),r=Math.abs(e-(n+h)),a=Math.abs(t-(o-c)),d=Math.abs(t-(o+c)),p=Math.min(s,r,a,d);return p===s?(l=-1,u=0,{nx:l,ny:u,penetration:i+s}):p===r?(l=1,u=0,{nx:l,ny:u,penetration:i+r}):p===a?(l=0,u=-1,{nx:l,ny:u,penetration:i+a}):(l=0,u=1,{nx:l,ny:u,penetration:i+d})}const y=Math.sqrt(p);return{nx:l/y,ny:u/y,penetration:i-y}}function p(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,i,n,o,r){const a=n-e,d=o-t,h=i+r,c=a*a+d*d;if(c>=h*h)return null;if(c<=s)return{nx:1,ny:0,penetration:h};const l=Math.sqrt(c);return{nx:a/l,ny:d/l,penetration:h-l}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return l(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const s=u(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return s?{nx:-s.nx,ny:-s.ny,penetration:s.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?u(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function y(e,t){const i=t.shape;if("aabb"===i.type){if("circle"===e.shape.type)return u(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height);return l(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height)}const n="circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2;return function(e,t,i,n,o,a,d,h=0){const c=a-n,l=d-o,u=c*c+l*l,p=u<=s?0:r(((e-n)*c+(t-o)*l)/u,0,1),y=i+h/2,m=e-(n+c*p),v=t-(o+l*p),f=m*m+v*v;if(f>=y*y)return null;if(f<=s){const e=Math.sqrt(u);return e<=s?{nx:1,ny:0,penetration:y}:{nx:-l/e,ny:c/e,penetration:y}}const g=Math.sqrt(f);return{nx:m/g,ny:v/g,penetration:y-g}}(e.x,e.y,n,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function m(e,t){return`${e}\0${t}`}function v(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function f(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,shape:n(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function g(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function x(e){return{id:e.id,shape:o(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:g(e.bodyFilter),index:e.index}}function b(e,t){return Boolean(t?.some(t=>Object.is(e,t)))}function S(e,t){const s=e.bodyFilter;if(!s)return!0;if("function"==typeof s)return s(t);const i=function(e,t){if(!t)return;let s=e;for(const e of t.split(".")){if(null==s||"object"!=typeof s)return;s=s[e]}return s}(t,s.property);return!("equals"in s&&!Object.is(i,s.equals))&&((!("notEquals"in s)||!Object.is(i,s.notEquals))&&(!(s.oneOf&&!b(i,s.oneOf))&&(!s.notOneOf||!b(i,s.notOneOf))))}var w=class{constructor(s={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...t,...s},this.random=e(this.options.seed)}init(s={}){this.options={...t,...s},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const t={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(s,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:n(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))v(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:o(t.shape),bodyFilter:g(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??`spring-${this.nextSpringIndex}`;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,s){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=s/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const s=this.sortedBodies();for(const e of s)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of s)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const s=i/t;e.vx*=s,e.vy*=s}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const n=this.bodyPairKeys(s),o=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;e<this.options.collisionIterations;e+=1)this.resolveBodyPairs(s,n,0===e),this.resolveColliders(s,o,0===e);this.updateSensors(s),this.updateSleeping(s,t)}settle(e=1200,t=this.options.fixedDt){let s=0;for(;s<e&&!this.allSleeping();)this.step(t),s+=1;return s}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:n(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(v)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(f),colliders:this.sortedColliders().map(x),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(t){this.options={...t.options,gravity:{...t.options.gravity}},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(t.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const e of t.bodies){const t=f(e);this.bodies.set(t.id,t),this.nextBodyIndex=Math.max(this.nextBodyIndex,t.index+1)}this.nextColliderIndex=0;for(const e of t.colliders){const t=x(e);this.colliders.set(t.id,t),this.nextColliderIndex=Math.max(this.nextColliderIndex,t.index+1)}this.nextSpringIndex=0;for(const e of t.springs){this.springs.set(e.id,{...e,target:{...e.target}});const t=/^spring-(\d+)$/.exec(e.id);t&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(t[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const i=this.bodies.get(t.bodyId);if(!i||i.sleeping)continue;const n="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!n)continue;const o=n.x-i.x,r=n.y-i.y,a=o*o+r*r,d=Math.sqrt(a);if(d<=s)continue;const h=o/d,c=r/d,l="vx"in n?n.vx:0,u="vy"in n?n.vy:0,p=(l-i.vx)*h+(u-i.vy)*c,y=(d-t.restLength)*t.stiffness+p*t.damping;i.vx+=y*h*e/i.mass,i.vy+=y*c*e/i.mass}}resolveBodyPairs(e,t,s){for(const i of t){const[t,n]=i.split(":").map(Number),o=e[t],r=e[n];if(!o||!r)continue;const a=p(o,r);a&&(this.resolveDynamicCollision(o,r,a),s&&this.lastEvents.push({type:"contact",bodyId:o.id,otherId:r.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),s=new Map;for(let i=0;i<e.length;i+=1){if(!1===e[i].bodyCollisions)continue;const n=d(e[i]),o=Math.floor(n.minX/t),r=Math.floor(n.maxX/t),a=Math.floor(n.minY/t),h=Math.floor(n.maxY/t);for(let e=o;e<=r;e+=1)for(let t=a;t<=h;t+=1){const n=`${e}:${t}`,o=s.get(n);o?o.push(i):s.set(n,[i])}}const i=new Set;for(const t of Array.from(s.keys()).sort()){const n=s.get(t)??[];n.sort((e,t)=>e-t);for(let t=0;t<n.length;t+=1)for(let s=t+1;s<n.length;s+=1){const o=n[t],r=n[s];!1!==e[o].bodyCollisions&&!1!==e[r].bodyCollisions&&(c(d(e[o]),d(e[r]))&&i.add(`${o}:${r}`))}}return Array.from(i).sort((e,t)=>{const[s,i]=e.split(":").map(Number),[n,o]=t.split(":").map(Number);return s===n?i-o:s-n})}resolveDynamicCollision(e,t,n){e.sleeping&&this.supportedThisStep.add(t.id),t.sleeping&&this.supportedThisStep.add(e.id);const o=e.sleeping?0:1/e.mass,r=t.sleeping?0:1/t.mass,a=o+r;if(a<=s)return;const d=Math.max(0,n.penetration-i)/a;e.x-=n.nx*d*o,e.y-=n.ny*d*o,t.x+=n.nx*d*r,t.y+=n.ny*d*r;const h=t.vx-e.vx,c=t.vy-e.vy,l=h*n.nx+c*n.ny;if(l>0)return;const u=Math.abs(l),p=-(1+Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution))*l/a,y=p*n.nx,m=p*n.ny;e.vx-=y*o,e.vy-=m*o,t.vx+=y*r,t.vy+=m*r,this.applyFriction(e,t,n,p,o,r),u>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,n,o,a){const d=-i.ny,h=i.nx,c=(t.vx-e.vx)*d+(t.vy-e.vy)*h,l=o+a;if(Math.abs(c)<=s||l<=s)return;const u=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction))),p=r(-c/l,-n*u,n*u),y=p*d,m=p*h;e.vx-=y*o,e.vy-=m*o,t.vx+=y*a,t.vy+=m*a}resolveColliders(e,t,s){for(const i of e)for(const e of t){if(!S(e,i))continue;if(!c(d(i),h(e)))continue;const t=y(i,e);t&&(this.resolveStaticCollision(i,e,t),this.supportedThisStep.add(i.id),s&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,s){e.x+=s.nx*Math.max(0,s.penetration-i),e.y+=s.ny*Math.max(0,s.penetration-i);const n=e.vx*s.nx+e.vy*s.ny;if(n<0){const i=Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution);e.vx-=(1+i)*n*s.nx,e.vy-=(1+i)*n*s.ny;const o=-s.ny,r=s.nx,a=e.vx*o+e.vy*r,d=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction)));e.vx-=a*o*d,e.vy-=a*r*d}}updateSensors(e){const t=new Set,s=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=d(i);for(const n of s){if(!S(n,i))continue;if(!c(e,h(n)))continue;if(!y(i,n))continue;const s=m(n.id,i.id);t.add(s),this.activeSensors.has(s)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:n.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:s,bodyId:i}=v(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:s})}this.activeSensors=t}updateSleeping(e,t){const s=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e){const e=Math.sqrt(i.vx*i.vx+i.vy*i.vy),n=Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY));!(e<this.options.sleepSpeed&&n<this.options.sleepSpeed*t)||s&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,!i.sleeping&&i.sleepTime>=this.options.sleepAfter&&(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},I=class{constructor(e={}){this.id="builtin",this.capabilities={...(new w).capabilities,engine:"builtin"},this.world=new w(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function B(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):function(e={}){return new I(e)}(t)}var M=["binId","targetBin","category","windowIndex","lane","group"];function O(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function q(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const s=t-e.mean;e.mean+=s/e.count;const i=t-e.mean;e.m2+=s*i}function k(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function C(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:Number.POSITIVE_INFINITY,max:e.count>0?e.max:Number.NEGATIVE_INFINITY}}function T(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function A(e,t,s){return"function"==typeof e?e(t,s):"string"==typeof e?T(t,e):void 0}function D(e){if(null==e)return;const t=String(e);return t.trim()?t:void 0}function R(e){const t=k(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:k(e.x),y:k(e.y),value:t}}var N=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const s=D(A(this.config.binAccessor,e,t))??function(e){for(const t of M){const s=D(T(e,t));if(s)return s}return"sediment"}(e),i=D(A(this.config.labelAccessor,e,t))??s,n=function(e,t,s){if("number"==typeof e)return e;const i="function"==typeof e?e(t,s):"string"==typeof e?T(t,e):1,n="number"==typeof i?i:Number(i);return Number.isFinite(n)?n:1}(this.config.valueAccessor,e,t),o=Math.max(0,Math.floor(this.config.retainBodyIds??12));let r=this.bins.get(s);return r||(r={id:s,label:i,bodyIds:[],x:O(),y:O(),value:O()},this.bins.set(s,r)),r.label=i,r.lastBodyId=e.id,r.lastDatum=e.datum,q(r.x,e.x),q(r.y,e.y),q(r.value,n),o>0&&(r.bodyIds.push(e.id),r.bodyIds.length>o&&(r.bodyIds=r.bodyIds.slice(r.bodyIds.length-o))),R(r)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(R)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:C(t.x),y:C(t.y),value:C(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function P(e){const t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function E(e){const t=Math.max(0,Math.floor(e.liveBodies)),s=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+s,n=P(e.bodyLimit),o=P(e.engineMaxBodiesHint),r=function(e,t,s){if(!1===s)return;const i=P(s?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(n,o,e.options),a=null==n?0:Math.max(0,t-n),d=a>0?"overflow":null!=r&&i>=r?"warning":"ok";return{action:"overflow"!==d?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:o,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:s,state:d,warnAt:r}}var F={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Y={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function X(e={},t=Y){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function L(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function K(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function j(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function V(e,t={}){const s=K(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,s)=>function(e,t,s){return"function"==typeof s?K(s(e,t)):"string"==typeof s?K(j(e,s)):K(e.spawnAt)??K(j(e,"arrivalTime"))??K(j(e,"timestamp"))??K(j(e,"time"))??K(j(e,"eventTime"))}(e,s,t.timeAccessor)),n=i.filter(e=>null!=e),o=n.length>0?Math.min(...n):0,r=K(t.timeScale)??1,a=r>0?r:1;return e.map((e,t)=>{const n=i[t],r=null==n?0:Math.max(0,n-o);return{...L(e),spawnAt:s+r/a}})}if("object"==typeof i){const t=K(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...L(e),spawnAt:s+i/t}))}return e.map(e=>({...L(e),spawnAt:s}))}function $(e){return{...L(e),sequence:e.sequence,spawnAt:e.spawnAt}}function H(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function W(e){return!1!==e&&{...e}}function z(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function _(e){return{...e,gravity:{...e.gravity}}}function G(e,t,s,i){if("circle"===e.shape.type){const n=e.x-t,o=e.y-s,r=e.shape.radius+i,a=n*n+o*o;return a<=r*r?a:null}const n=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),o=Math.max(Math.abs(s-e.y)-e.shape.height/2,0),r=n*n+o*o;return r<=i*i?r:null}function U(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}var J={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function Q(e,t){const s={...e};for(const e of t){s[J[e]]++}return s}function Z(e,t,s){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:Q(s,i)}}var ee=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=Z({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}record(e,t){const s=Z(e,t,this.revisions);this.revisions=s.revisions,this.latest=s;for(const e of[...this.listeners])e();return s}};import{quadtree as te}from"d3-quadtree";var se=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,s,i,n,o=0){const r=this.ensure(e,t);if(!r)return null;let a=null,d=Number.POSITIVE_INFINITY;const h=Math.max(0,o)+this.maxSearchRadius,c=i-h,l=i+h,u=n-h,p=n+h;return r.visit((e,t,r,h,y)=>{if(h<c||t>l||y<u||r>p)return!0;if(e.length)return!1;let m=e;for(;m;){const e=m.data;if(e){const t=G(e,i,n,Math.max(0,o));null!=t&&(t<d||t===d&&s.indexOf(e.id)>s.indexOf(a?.id??""))&&(a=e,d=t)}m=m.next}return!1}),a}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const s=e.readState();return 0===s.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=s.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=te().x(e=>e.x).y(e=>e.y).addAll(s),this.revision=t,this.tree)}};var ie=["data","scene-geometry","data-paint","accessibility","evidence"],ne=["scene-geometry","data-paint","accessibility","evidence"],oe=["overlay","accessibility","evidence"],re=(e,t)=>({retainedData:e,invalidations:t}),ae=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],de=["scene-geometry","data-paint","accessibility","evidence"],he=[],ce={engine:re("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:re("preserve",de),colliders:re("preserve",de),sediment:re("preserve",de),bodyBudget:re("preserve",ae),bodyLimit:re("preserve",ae),eviction:re("preserve",ae),fixedDt:re("preserve",he),maxDeltaSeconds:re("preserve",he),maxSubsteps:re("preserve",he),settleStepLimit:re("preserve",he),timeScale:re("preserve",he),observation:re("preserve",he)},le=re("preserve",ae);function ue(e){let t="preserve";const s=new Set;for(const i of e){const e=ce[i]??le;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)s.add(t)}return{retainedData:t,invalidations:s}}var pe=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function ye(e,t){return e===t||!(!e||!t)&&(e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&pe.every(s=>e[s]===t[s]))}function me(e,t,s,i){return e||!t?"paused":s||!i?"running":"settled"}function ve(e,t,s,i,n,o){const r={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===s)return r;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return r;const d=n.length-a;if(d<=0)return r;const h=function(e,t,s){if("sleeping-first"!==t)return s.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),n=[],o=[];for(const e of s)i.get(e)?n.push(e):o.push(e);return[...n,...o]}(e,s,n),c=h.slice(0,d);if(0===c.length)return r;const l=function(e,t,s,i){const n=new Map(e.readState().map(e=>[e.id,e])),o=[];for(const e of s){const s=n.get(e);if(!s)continue;const r=t.add(s);r&&(o.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:s.datum,x:s.x,y:s.y,binId:r.id,count:r.count,total:r.total}))}return o}(e,t,c,o);e.remove(c);const u=new Set(c);return{evicted:c,sedimented:l,liveBodyOrder:n.filter(e=>!u.has(e))}}var fe=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,s){if(s>0)return void(this.seconds=0);const i=e.readState(this.scratch),n=this.speed*this.speed;let o=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=n){o=!1;break}this.seconds=o?this.seconds+Math.max(0,t):0}},ge=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new se,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new ee,this.simulationState="settled",this.visible=!0,this.quiescence=new fe;const{bodyBudget:t,colliders:s,engine:i,kernel:n,observation:o,sediment:r,...a}=e;this.config={...F,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=X(o),this.sediment=new N(r??!1),this.world=B(i,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),s&&this.world.setColliders(H(s))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(s=>"kernel"===s?!ye(e.kernel,t.kernel):e[s]!==t[s])}(e,this.configInput),{colliders:s,bodyBudget:i,engine:n,kernel:o,observation:r,sediment:a,...d}=e;if(this.config={...this.config,...d},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=B(n,e.options),this.world.restore(e),this.revision+=1}if(o&&!ye(o,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...o,gravity:{...e.options.gravity,...o.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}r&&(this.observation=X(r,this.observation)),this.sediment.updateConfig(a),s&&(this.world.setColliders(H(s)),this.revision+=1),this.configInput={...this.configInput,...e};const h=ue(t);this.updateResults.record({kind:"config",keys:t},h.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(H(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},ue(["colliders"]).invalidations)}enqueue(e,t){const s=Array.isArray(e)?e:[e],i=t?V(s,{...t,startAt:t.startAt??this.elapsedSeconds}):s;for(const e of i)this.queue.push({...L(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(z),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?ie:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(L(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},ie)}materializeDueSpawns(){const e=this.revision,t=[],s=[];return this.spawnDue(t,s),0===t.length||(this.observeBodyBudget(s),this.evictOverflow(s),this.syncSimulationState(s),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?ie:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},ie)}tick(e){const t=this.revision,s=[],i=[],n=[],o=[],r=[];if(this.paused||!this.visible){const e=this.result(0,s,i,n,o,r,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(s,r);const d=this.observeBodyBudget(r),h=this.evictOverflow(r);i.push(...h.evicted),n.push(...h.sedimented),this.syncSimulationState(r),this.accumulator+=a;let c=0;for(;this.accumulator>=this.config.fixedDt&&c<this.config.maxSubsteps;){this.world.step(this.config.fixedDt);const e=this.world.events();o.push(...e),this.observeKernelEvents(e,r),this.observeSensorTransitions(r),this.accumulator-=this.config.fixedDt,c+=1}c===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,s.length),(c>0||s.length>0||i.length>0||n.length>0||o.length>0)&&(this.revision+=1);const l=this.result(c,s,i,n,o,r,void 0,d);return this.updateResults.record({kind:"tick",count:c},this.revision!==t?s.length||i.length||n.length?ie:ne:[]),l}settle(e=this.config.settleStepLimit){const t=this.revision;this.spawnDue([],[]);const s=this.world.settle(e,this.config.fixedDt);return s>0&&(this.revision+=1),this.syncSimulationState(),this.updateResults.record({kind:"settle",count:s},this.revision!==t?ne:[]),s}settleWithObservations(e=this.config.settleStepLimit){const t=this.revision,s=[],i=[],n=[],o=[],r=[];if(this.paused||!this.visible){const e=this.result(0,s,i,n,o,r,!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(s,r);const a=this.observeBodyBudget(r),d=this.evictOverflow(r);i.push(...d.evicted),n.push(...d.sedimented),this.syncSimulationState(r);let h=0;for(s.length>0&&this.quiescence.reset();h<e&&!this.atRest();){this.world.step(this.config.fixedDt);const e=this.world.events();o.push(...e),this.observeKernelEvents(e,r),this.observeSensorTransitions(r),h+=1,this.quiescence.refresh(this.world,this.config.fixedDt,0)}(h>0||s.length>0||i.length>0||n.length>0||o.length>0)&&(this.revision+=1);const c=this.result(h,s,i,n,o,r,void 0,a);return this.updateResults.record({kind:"settle",count:h},this.revision!==t?s.length||i.length||n.length?ie:ne:[]),c}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return function(e,t={}){const{baselineY:s=0,binWidth:i=24,gap:n=2,maxHeight:o=80,value:r="count",x:a}=t,d=Math.max(1,...e.map(e=>e[r]));return e.map((e,t)=>{const h=Math.max(0,e[r]/d*o),c=a?.(e,t)??t*(i+n);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:c,y:s-h,width:i,height:h,meanX:e.x.mean,meanY:e.y.mean}})}(this.readSediment(),e)}hitTest(e,t,s=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,s)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:s,chartId:i,...n}=e,o={...n,timestamp:t??this.elapsedSeconds,chartType:s??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(o),this.updateResults.record({kind:"update",count:1},["evidence"]),o}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?oe:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?oe:[])}remove(e){const t=new Set(e),s=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const n=e.filter(e=>s.has(e)||i.has(e));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?ie:[]),n}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},ne),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},ne)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},ne)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,s,i)=>e.applyImpulse(t,s,i),clear:()=>e.clear(),hitTest:(t,s,i)=>e.hitTest(t,s,i),pause:()=>e.setPaused(!0),push:(t,s)=>e.enqueue(t,s),pushMany:(t,s)=>e.enqueue(t,s),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:W(this.bodyBudget),config:{...this.config,kernel:_(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map($),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:W(e.bodyBudget??{}),kernel:_(e.world.options)},this.bodyBudget=W(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map($).sort(z),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??me(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},ie)}spawnDue(e,t){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds;){const s=this.queue.shift();if(!s)return;this.spawnOne(s,t),e.push(s.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const s=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:s?.datum??e.datum,x:s?.x??e.x,y:s?.y??e.y},t)}result(e,t,s,i,n,o,r,a=this.evaluateBodyBudget()){this.syncSimulationState(o);const d=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:s,events:n,observations:o,queueSize:this.queue.length,revision:this.revision,shouldContinue:r??(this.queue.length>0||!this.atRest()),sleeping:d,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,s){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);s.emit({type:"physics-settle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,s){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const n=new Map(e.readState().map(e=>[e.id,e])),o=(e,t)=>{const{sensorId:i,bodyId:o}=U(t),r=s.observation.sensors[i],a=n.get(o);s.emit({type:"enter"===e?r?.enterType??"physics-bin-enter":r?.exitType??"physics-bin-exit",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:o,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:r?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||o("enter",e);for(const e of Array.from(t).sort())i.has(e)||o("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const s of e)t.has(U(s).bodyId)&&e.delete(s)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return E({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const s=`${t.state}:${t.action}`;return s===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=s,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=me(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const s=this.simulationState;this.simulationState=t,function(e,t,s){s.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||s.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,simulationState:t,previousSimulationState:e})}(s,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:s,liveBodyOrder:i}=ve(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:s}}};function xe(e,t){return function(e,t,s=[],i){const n=new Array(t.length),o=new Float32Array(2*t.length),r=new Float32Array(2*t.length),a=new Uint8Array(t.length);return t.forEach((e,t)=>{const s=2*t;n[t]=e.id,o[s]=e.x,o[s+1]=e.y,r[s]=e.vx,r[s+1]=e.vy,a[t]=e.sleeping?1:0}),{bodies:t,ids:n,positions:o,result:e,sediment:s,sleeping:a,snapshot:i,velocities:r}}(t,e.readBodies(),e.readSediment(),e.snapshot())}function be(e){return xe(e,e.tick(0))}var Se=function(){let e=new ge;return{handle(t){switch(t.type){case"init":return e=new ge(t.config),t.snapshot?e.restore(t.snapshot):t.initialSpawns?.length&&e.enqueue(t.initialSpawns,t.initialSpawnPacing),{type:"frame",frame:be(e)};case"configure":return e.updateConfig(t.config),{type:"frame",frame:be(e)};case"enqueue":return e.enqueue(t.spawns,t.pacing),{type:"frame",frame:be(e)};case"tick":return{type:"frame",frame:xe(e,e.tick(t.deltaSeconds))};case"settle":return{type:"frame",frame:xe(e,e.settleWithObservations(t.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:e.snapshot()};case"restore":return e.restore(t.snapshot),{type:"frame",frame:be(e)};case"clear":return e.clear(),{type:"frame",frame:be(e)};case"remove":return{type:"removed",removed:e.remove(t.ids),frame:be(e)};case"applyImpulse":return e.applyImpulse(t.id,t.ix,t.iy),{type:"frame",frame:be(e)};case"setPaused":return e.setPaused(t.paused),{type:"frame",frame:be(e)};case"setVisible":return e.setVisible(t.visible),{type:"frame",frame:be(e)}}}}}();function we(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:{message:String(e)}}self.onmessage=e=>{const t=e.data;try{const e=Se.handle(t.command);self.postMessage({ok:!0,payload:e,requestId:t.requestId},function(e){return"frame"===e.type||"removed"===e.type?[(t=e.frame).positions.buffer,t.velocities.buffer,t.sleeping.buffer]:[];var t}(e))}catch(e){self.postMessage({error:we(e),ok:!1,requestId:t.requestId})}};
1
+ function e(e){let t=e>>>0;return function(){t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296}}var t={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},s=1e-9,i=.005;function n(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function o(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function r(e,t,s){return Math.max(t,Math.min(s,e))}function a(e){return e<0?-1:1}function d(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,s=e.shape.height/2;return{minX:e.x-t,minY:e.y-s,maxX:e.x+t,maxY:e.y+s}}function h(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,s=t.height/2;return{minX:t.x-e,minY:t.y-s,maxX:t.x+e,maxY:t.y+s}}const s=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-s,minY:Math.min(t.y1,t.y2)-s,maxX:Math.max(t.x1,t.x2)+s,maxY:Math.max(t.y1,t.y2)+s}}function c(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function l(e,t,s,i,n,o,r,d){const h=n-e,c=(s+r)/2-Math.abs(h);if(c<=0)return null;const l=o-t,u=(i+d)/2-Math.abs(l);return u<=0?null:c<u?{nx:a(h),ny:0,penetration:c}:{nx:0,ny:a(l),penetration:u}}function u(e,t,i,n,o,a,d){const h=a/2,c=d/2;let l=e-r(e,n-h,n+h),u=t-r(t,o-c,o+c);const p=l*l+u*u;if(p>i*i)return null;if(p<=s){const s=Math.abs(e-(n-h)),r=Math.abs(e-(n+h)),a=Math.abs(t-(o-c)),d=Math.abs(t-(o+c)),p=Math.min(s,r,a,d);return p===s?(l=-1,u=0,{nx:l,ny:u,penetration:i+s}):p===r?(l=1,u=0,{nx:l,ny:u,penetration:i+r}):p===a?(l=0,u=-1,{nx:l,ny:u,penetration:i+a}):(l=0,u=1,{nx:l,ny:u,penetration:i+d})}const y=Math.sqrt(p);return{nx:l/y,ny:u/y,penetration:i-y}}function p(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,i,n,o,r){const a=n-e,d=o-t,h=i+r,c=a*a+d*d;if(c>=h*h)return null;if(c<=s)return{nx:1,ny:0,penetration:h};const l=Math.sqrt(c);return{nx:a/l,ny:d/l,penetration:h-l}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return l(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const s=u(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return s?{nx:-s.nx,ny:-s.ny,penetration:s.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?u(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function y(e,t){const i=t.shape;if("aabb"===i.type){if("circle"===e.shape.type)return u(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height);return l(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height)}const n="circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2;return function(e,t,i,n,o,a,d,h=0){const c=a-n,l=d-o,u=c*c+l*l,p=u<=s?0:r(((e-n)*c+(t-o)*l)/u,0,1),y=i+h/2,v=e-(n+c*p),m=t-(o+l*p),f=v*v+m*m;if(f>=y*y)return null;if(f<=s){const e=Math.sqrt(u);return e<=s?{nx:1,ny:0,penetration:y}:{nx:-l/e,ny:c/e,penetration:y}}const g=Math.sqrt(f);return{nx:v/g,ny:m/g,penetration:y-g}}(e.x,e.y,n,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function v(e,t){return`${e}\0${t}`}function m(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function f(e){return{id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,bodyCollisions:e.bodyCollisions,shape:n(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function g(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function x(e){return{id:e.id,shape:o(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:g(e.bodyFilter),index:e.index}}function b(e,t){return Boolean(t?.some(t=>Object.is(e,t)))}function S(e,t){const s=e.bodyFilter;if(!s)return!0;if("function"==typeof s)return s(t);const i=function(e,t){if(!t)return;let s=e;for(const e of t.split(".")){if(null==s||"object"!=typeof s)return;s=s[e]}return s}(t,s.property);return!("equals"in s&&!Object.is(i,s.equals))&&((!("notEquals"in s)||!Object.is(i,s.notEquals))&&(!(s.oneOf&&!b(i,s.oneOf))&&(!s.notOneOf||!b(i,s.notOneOf))))}var w=class{constructor(s={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...t,...s},this.random=e(this.options.seed)}init(s={}){this.options={...t,...s},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const t={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(s,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:n(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))m(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:o(t.shape),bodyFilter:g(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??`spring-${this.nextSpringIndex}`;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,s){const i=this.bodies.get(e);i&&(i.vx+=t/i.mass,i.vy+=s/i.mass,this.wake(i))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const s=this.sortedBodies();for(const e of s)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const i=this.options.maxVelocity;for(const e of s)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,i>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>i){const s=i/t;e.vx*=s,e.vy*=s}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const n=this.bodyPairKeys(s),o=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;e<this.options.collisionIterations;e+=1)this.resolveBodyPairs(s,n,0===e),this.resolveColliders(s,o,0===e);this.updateSensors(s),this.updateSleeping(s,t)}settle(e=1200,t=this.options.fixedDt){let s=0;for(;s<e&&!this.allSleeping();)this.step(t),s+=1;return s}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:n(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(m)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(f),colliders:this.sortedColliders().map(x),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(t){this.options={...t.options,gravity:{...t.options.gravity}},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(t.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const e of t.bodies){const t=f(e);this.bodies.set(t.id,t),this.nextBodyIndex=Math.max(this.nextBodyIndex,t.index+1)}this.nextColliderIndex=0;for(const e of t.colliders){const t=x(e);this.colliders.set(t.id,t),this.nextColliderIndex=Math.max(this.nextColliderIndex,t.index+1)}this.nextSpringIndex=0;for(const e of t.springs){this.springs.set(e.id,{...e,target:{...e.target}});const t=/^spring-(\d+)$/.exec(e.id);t&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(t[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const i=this.bodies.get(t.bodyId);if(!i||i.sleeping)continue;const n="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!n)continue;const o=n.x-i.x,r=n.y-i.y,a=o*o+r*r,d=Math.sqrt(a);if(d<=s)continue;const h=o/d,c=r/d,l="vx"in n?n.vx:0,u="vy"in n?n.vy:0,p=(l-i.vx)*h+(u-i.vy)*c,y=(d-t.restLength)*t.stiffness+p*t.damping;i.vx+=y*h*e/i.mass,i.vy+=y*c*e/i.mass}}resolveBodyPairs(e,t,s){for(const i of t){const[t,n]=i.split(":").map(Number),o=e[t],r=e[n];if(!o||!r)continue;const a=p(o,r);a&&(this.resolveDynamicCollision(o,r,a),s&&this.lastEvents.push({type:"contact",bodyId:o.id,otherId:r.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),s=new Map;for(let i=0;i<e.length;i+=1){if(!1===e[i].bodyCollisions)continue;const n=d(e[i]),o=Math.floor(n.minX/t),r=Math.floor(n.maxX/t),a=Math.floor(n.minY/t),h=Math.floor(n.maxY/t);for(let e=o;e<=r;e+=1)for(let t=a;t<=h;t+=1){const n=`${e}:${t}`,o=s.get(n);o?o.push(i):s.set(n,[i])}}const i=new Set;for(const t of Array.from(s.keys()).sort()){const n=s.get(t)??[];n.sort((e,t)=>e-t);for(let t=0;t<n.length;t+=1)for(let s=t+1;s<n.length;s+=1){const o=n[t],r=n[s];!1!==e[o].bodyCollisions&&!1!==e[r].bodyCollisions&&(c(d(e[o]),d(e[r]))&&i.add(`${o}:${r}`))}}return Array.from(i).sort((e,t)=>{const[s,i]=e.split(":").map(Number),[n,o]=t.split(":").map(Number);return s===n?i-o:s-n})}resolveDynamicCollision(e,t,n){e.sleeping&&this.contactOpposesGravity(n.nx,n.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-n.nx,-n.ny)&&this.supportedThisStep.add(e.id);const o=e.sleeping?0:1/e.mass,r=t.sleeping?0:1/t.mass,a=o+r;if(a<=s)return;const d=Math.max(0,n.penetration-i)/a;e.x-=n.nx*d*o,e.y-=n.ny*d*o,t.x+=n.nx*d*r,t.y+=n.ny*d*r;const h=t.vx-e.vx,c=t.vy-e.vy,l=h*n.nx+c*n.ny;if(l>0)return;const u=Math.abs(l),p=-(1+Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution))*l/a,y=p*n.nx,v=p*n.ny;e.vx-=y*o,e.vy-=v*o,t.vx+=y*r,t.vy+=v*r,this.applyFriction(e,t,n,p,o,r),u>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,n,o,a){const d=-i.ny,h=i.nx,c=(t.vx-e.vx)*d+(t.vy-e.vy)*h,l=o+a;if(Math.abs(c)<=s||l<=s)return;const u=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction))),p=r(-c/l,-n*u,n*u),y=p*d,v=p*h;e.vx-=y*o,e.vy-=v*o,t.vx+=y*a,t.vy+=v*a}resolveColliders(e,t,s){for(const i of e)for(const e of t){if(!S(e,i))continue;if(!c(d(i),h(e)))continue;const t=y(i,e);t&&(this.resolveStaticCollision(i,e,t),this.contactOpposesGravity(t.nx,t.ny)&&this.supportedThisStep.add(i.id),s&&this.lastEvents.push({type:"contact",bodyId:i.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,s){e.x+=s.nx*Math.max(0,s.penetration-i),e.y+=s.ny*Math.max(0,s.penetration-i);const n=e.vx*s.nx+e.vy*s.ny;if(n<0){const i=Math.min(e.restitution??this.options.restitution,t.restitution??this.options.restitution);e.vx-=(1+i)*n*s.nx,e.vy-=(1+i)*n*s.ny;const o=-s.ny,r=s.nx,a=e.vx*o+e.vy*r,d=Math.max(0,Math.min(1,Math.max(e.friction??this.options.friction,t.friction??this.options.friction)));e.vx-=a*o*d,e.vy-=a*r*d}}updateSensors(e){const t=new Set,s=this.sortedColliders().filter(e=>e.sensor);for(const i of e){const e=d(i);for(const n of s){if(!S(n,i))continue;if(!c(e,h(n)))continue;if(!y(i,n))continue;const s=v(n.id,i.id);t.add(s),this.activeSensors.has(s)||this.lastEvents.push({type:"sensor-enter",bodyId:i.id,sensorId:n.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:s,bodyId:i}=m(e);this.lastEvents.push({type:"sensor-exit",bodyId:i,sensorId:s})}this.activeSensors=t}updateSleeping(e,t){const s=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const i of e){const e=Math.sqrt(i.vx*i.vx+i.vy*i.vy),n=Math.sqrt((i.x-i.prevX)*(i.x-i.prevX)+(i.y-i.prevY)*(i.y-i.prevY));!(e<this.options.sleepSpeed&&n<this.options.sleepSpeed*t)||s&&!this.supportedThisStep.has(i.id)?i.sleeping?this.wake(i):i.sleepTime=0:(i.sleepTime+=t,!i.sleeping&&i.sleepTime>=this.options.sleepAfter&&(i.sleeping=!0,i.vx=0,i.vy=0,this.lastEvents.push({type:"sleep",bodyId:i.id})))}}contactOpposesGravity(e,t){const{x:s,y:i}=this.options.gravity,n=Math.hypot(s,i);return n<=1e-9||(e*s+t*i)/n<-.2}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},I=class{constructor(e={}){this.id="builtin",this.capabilities={...(new w).capabilities,engine:"builtin"},this.world=new w(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function B(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):function(e={}){return new I(e)}(t)}var M=["binId","targetBin","category","windowIndex","lane","group"];function O(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function q(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const s=t-e.mean;e.mean+=s/e.count;const i=t-e.mean;e.m2+=s*i}function k(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function T(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:Number.POSITIVE_INFINITY,max:e.count>0?e.max:Number.NEGATIVE_INFINITY}}function C(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function A(e,t,s){return"function"==typeof e?e(t,s):"string"==typeof e?C(t,e):void 0}function D(e){if(null==e)return;const t=String(e);return t.trim()?t:void 0}function R(e){const t=k(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:k(e.x),y:k(e.y),value:t}}var E=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const s=D(A(this.config.binAccessor,e,t))??function(e){for(const t of M){const s=D(C(e,t));if(s)return s}return"sediment"}(e),i=D(A(this.config.labelAccessor,e,t))??s,n=function(e,t,s){if("number"==typeof e)return e;const i="function"==typeof e?e(t,s):"string"==typeof e?C(t,e):1,n="number"==typeof i?i:Number(i);return Number.isFinite(n)?n:1}(this.config.valueAccessor,e,t),o=Math.max(0,Math.floor(this.config.retainBodyIds??12));let r=this.bins.get(s);return r||(r={id:s,label:i,bodyIds:[],x:O(),y:O(),value:O()},this.bins.set(s,r)),r.label=i,r.lastBodyId=e.id,r.lastDatum=e.datum,q(r.x,e.x),q(r.y,e.y),q(r.value,n),o>0&&(r.bodyIds.push(e.id),r.bodyIds.length>o&&(r.bodyIds=r.bodyIds.slice(r.bodyIds.length-o))),R(r)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(R)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:T(t.x),y:T(t.y),value:T(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function N(e){const t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function P(e){const t=Math.max(0,Math.floor(e.liveBodies)),s=Math.max(0,Math.floor(e.queuedBodies??0)),i=t+s,n=N(e.bodyLimit),o=N(e.engineMaxBodiesHint),r=function(e,t,s){if(!1===s)return;const i=N(s?.warnAt);return null!=i?i:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(n,o,e.options),a=null==n?0:Math.max(0,t-n),d=a>0?"overflow":null!=r&&i>=r?"warning":"ok";return{action:"overflow"!==d?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:o,liveBodies:t,overflow:a,projectedBodies:i,queuedBodies:s,state:d,warnAt:r}}var F={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},Y={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function X(e={},t=Y){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function L(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function K(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function H(e,t){const s=e;if(null!=s[t])return s[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function j(e,t={}){const s=K(t.startAt)??0,i=t.pacing??"immediate";if("arrival"===i){const i=e.map((e,s)=>function(e,t,s){return"function"==typeof s?K(s(e,t)):"string"==typeof s?K(H(e,s)):K(e.spawnAt)??K(H(e,"arrivalTime"))??K(H(e,"timestamp"))??K(H(e,"time"))??K(H(e,"eventTime"))}(e,s,t.timeAccessor)),n=i.filter(e=>null!=e),o=n.length>0?Math.min(...n):0,r=K(t.timeScale)??1,a=r>0?r:1;return e.map((e,t)=>{const n=i[t],r=null==n?0:Math.max(0,n-o);return{...L(e),spawnAt:s+r/a}})}if("object"==typeof i){const t=K(i.ratePerSec);if(t&&t>0)return e.map((e,i)=>({...L(e),spawnAt:s+i/t}))}return e.map(e=>({...L(e),spawnAt:s}))}function V(e){return{...L(e),sequence:e.sequence,spawnAt:e.spawnAt}}function $(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function z(e){return!1!==e&&{...e}}function W(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function G(e){return{...e,gravity:{...e.gravity}}}function _(e,t,s,i){if("circle"===e.shape.type){const n=e.x-t,o=e.y-s,r=e.shape.radius+i,a=n*n+o*o;return a<=r*r?a:null}const n=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),o=Math.max(Math.abs(s-e.y)-e.shape.height/2,0),r=n*n+o*o;return r<=i*i?r:null}function U(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}var Q={data:"data",domain:"domain",layout:"layout","scene-geometry":"sceneGeometry","scene-style":"sceneStyle","data-paint":"dataPaint","interaction-paint":"interactionPaint",overlay:"overlay",accessibility:"accessibility",evidence:"evidence"};function J(e,t){const s={...e};for(const e of t){s[Q[e]]++}return s}function Z(e,t,s){const i=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:i,revisions:J(s,i)}}var ee=class{constructor(){this.revisions={data:0,domain:0,layout:0,sceneGeometry:0,sceneStyle:0,dataPaint:0,interactionPaint:0,overlay:0,accessibility:0,evidence:0},this.latest=Z({kind:"initialize"},[],this.revisions),this.listeners=new Set}get last(){return this.latest}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}record(e,t){const s=Z(e,t,this.revisions);this.revisions=s.revisions,this.latest=s;for(const e of[...this.listeners])e();return s}};import{quadtree as te}from"d3-quadtree";var se=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,s,i,n,o=0){const r=this.ensure(e,t);if(!r)return null;let a=null,d=Number.POSITIVE_INFINITY;const h=Math.max(0,o)+this.maxSearchRadius,c=i-h,l=i+h,u=n-h,p=n+h;return r.visit((e,t,r,h,y)=>{if(h<c||t>l||y<u||r>p)return!0;if(e.length)return!1;let v=e;for(;v;){const e=v.data;if(e){const t=_(e,i,n,Math.max(0,o));null!=t&&(t<d||t===d&&s.indexOf(e.id)>s.indexOf(a?.id??""))&&(a=e,d=t)}v=v.next}return!1}),a}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const s=e.readState();return 0===s.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=s.reduce((e,t)=>Math.max(e,function(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}(t)),0),this.tree=te().x(e=>e.x).y(e=>e.y).addAll(s),this.revision=t,this.tree)}};var ie=["data","scene-geometry","data-paint","accessibility","evidence"],ne=["scene-geometry","data-paint","accessibility","evidence"],oe=["overlay","accessibility","evidence"],re=(e,t)=>({retainedData:e,invalidations:t}),ae=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],de=["scene-geometry","data-paint","accessibility","evidence"],he=[],ce={engine:re("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:re("preserve",de),colliders:re("preserve",de),sediment:re("preserve",de),bodyBudget:re("preserve",ae),bodyLimit:re("preserve",ae),eviction:re("preserve",ae),fixedDt:re("preserve",he),maxDeltaSeconds:re("preserve",he),maxSubsteps:re("preserve",he),settleStepLimit:re("preserve",he),timeScale:re("preserve",he),observation:re("preserve",he)},le=re("preserve",ae);function ue(e){let t="preserve";const s=new Set;for(const i of e){const e=ce[i]??le;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)s.add(t)}return{retainedData:t,invalidations:s}}var pe=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function ye(e,t){return e===t||!(!e||!t)&&(e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&pe.every(s=>e[s]===t[s]))}function ve(e,t,s,i){return e||!t?"paused":s||!i?"running":"settled"}function me(e,t,s,i,n,o){const r={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===s)return r;const a=Math.max(0,Math.floor(i));if(!Number.isFinite(a))return r;const d=n.length-a;if(d<=0)return r;const h=function(e,t,s){if("sleeping-first"!==t)return s.slice();const i=new Map(e.readState().map(e=>[e.id,e.sleeping])),n=[],o=[];for(const e of s)i.get(e)?n.push(e):o.push(e);return[...n,...o]}(e,s,n),c=h.slice(0,d);if(0===c.length)return r;const l=function(e,t,s,i){const n=new Map(e.readState().map(e=>[e.id,e])),o=[];for(const e of s){const s=n.get(e);if(!s)continue;const r=t.add(s);r&&(o.push(e),i.emit({type:"physics-sediment",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e,datum:s.datum,x:s.x,y:s.y,binId:r.id,count:r.count,total:r.total}))}return o}(e,t,c,o);e.remove(c);const u=new Set(c);return{evicted:c,sedimented:l,liveBodyOrder:n.filter(e=>!u.has(e))}}var fe=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,s){if(s>0)return void(this.seconds=0);const i=e.readState(this.scratch),n=this.speed*this.speed;let o=!0;for(const e of i)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=n){o=!1;break}this.seconds=o?this.seconds+Math.max(0,t):0}};var ge=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new se,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new ee,this.simulationState="settled",this.visible=!0,this.quiescence=new fe;const{bodyBudget:t,colliders:s,engine:i,kernel:n,observation:o,sediment:r,...a}=e;this.config={...F,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=i,this.observation=X(o),this.sediment=new E(r??!1),this.world=B(i,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),s&&this.world.setColliders($(s))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(s=>"kernel"===s?!ye(e.kernel,t.kernel):e[s]!==t[s])}(e,this.configInput),{colliders:s,bodyBudget:i,engine:n,kernel:o,observation:r,sediment:a,...d}=e;if(this.config={...this.config,...d},void 0!==i&&(this.bodyBudget=i,!1===i&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=B(n,e.options),this.world.restore(e),this.revision+=1}if(o&&!ye(o,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...o,gravity:{...e.options.gravity,...o.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}r&&(this.observation=X(r,this.observation)),this.sediment.updateConfig(a),s&&(this.world.setColliders($(s)),this.revision+=1),this.configInput={...this.configInput,...e};const h=ue(t);this.updateResults.record({kind:"config",keys:t},h.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders($(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},ue(["colliders"]).invalidations)}enqueue(e,t){const s=Array.isArray(e)?e:[e],i=t?j(s,{...t,startAt:t.startAt??this.elapsedSeconds}):s;for(const e of i)this.queue.push({...L(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(W),i.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i.length},i.length?ie:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(L(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},ie)}materializeDueSpawns(){const e=this.revision,t=[],s=[];return this.spawnDue(t,s),0===t.length||(this.observeBodyBudget(s),this.evictOverflow(s),this.syncSimulationState(s),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?ie:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},ie)}tick(e){const t=this.revision,s=[],i=[],n=[],o=[],r=[];if(this.paused||!this.visible){const e=this.result(0,s,i,n,o,r,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(s,r);const d=this.observeBodyBudget(r),h=this.evictOverflow(r);i.push(...h.evicted),n.push(...h.sedimented),this.syncSimulationState(r),this.accumulator+=a;let c=0;for(;this.accumulator>=this.config.fixedDt&&c<this.config.maxSubsteps;){this.world.step(this.config.fixedDt);const e=this.world.events();o.push(...e),this.observeKernelEvents(e,r),this.observeSensorTransitions(r),this.accumulator-=this.config.fixedDt,c+=1}c===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,s.length),(c>0||s.length>0||i.length>0||n.length>0||o.length>0)&&(this.revision+=1);const l=this.result(c,s,i,n,o,r,void 0,d);return this.updateResults.record({kind:"tick",count:c},this.revision!==t?s.length||i.length||n.length?ie:ne:[]),l}settle(e=this.config.settleStepLimit){return this.runSettle(e,!1).steps}settleWithObservations(e=this.config.settleStepLimit){return this.runSettle(e,!0)}settleHost(){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length,atRest:()=>this.atRest(),advanceTime:e=>{this.elapsedSeconds+=e},spawnDue:(e,t)=>this.spawnDue(e,t),observeBodyBudget:e=>this.observeBodyBudget(e),evictOverflow:e=>this.evictOverflow(e),step:e=>this.world.step(e),drainEvents:()=>this.world.events(),observeKernelEvents:(e,t)=>this.observeKernelEvents(e,t),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t){const s=this.revision,i=[],n=[],o=[],r=[],a=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,i,n,o,r,a??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(i,a);const d=this.observeBodyBudget(a),h=this.evictOverflow(a);n.push(...h.evicted),o.push(...h.sedimented),this.syncSimulationState(a),i.length>0&&this.quiescence.reset();const c=t?{spawned:i,evicted:n,sedimented:o,events:r,observations:a}:{spawned:i},{steps:l,budget:u}=function(e,t,s){let i,n=0;for(;n<t&&(e.queueSize()>0||!e.atRest());){e.advanceTime(e.fixedDt);const t=[];if(e.spawnDue(t,s.observations),t.length>0){s.spawned.push(...t),i=e.observeBodyBudget(s.observations);const n=e.evictOverflow(s.observations);s.evicted?.push(...n.evicted),s.sedimented?.push(...n.sedimented)}e.step(e.fixedDt);const o=e.drainEvents();s.events&&(s.events.push(...o),e.observeKernelEvents(o,s.observations),e.observeSensorTransitions(s.observations)),n+=1,e.refreshQuiescence(e.fixedDt,t.length)}return{steps:n,budget:i}}(this.settleHost(),e,c),p=i.length+n.length+o.length>0;(l>0||p||r.length>0)&&(this.revision+=1);const y=this.result(l,i,n,o,r,a??[],void 0,u??d);return this.updateResults.record({kind:"settle",count:l},this.revision===s?[]:p?ie:ne),y}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return function(e,t={}){const{baselineY:s=0,binWidth:i=24,gap:n=2,maxHeight:o=80,value:r="count",x:a}=t,d=Math.max(1,...e.map(e=>e[r]));return e.map((e,t)=>{const h=Math.max(0,e[r]/d*o),c=a?.(e,t)??t*(i+n);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:c,y:s-h,width:i,height:h,meanX:e.x.mean,meanY:e.y.mean}})}(this.readSediment(),e)}hitTest(e,t,s=0){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,s)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:s,chartId:i,...n}=e,o={...n,timestamp:t??this.elapsedSeconds,chartType:s??this.observation.chartType,chartId:i??this.observation.chartId};return this.emitObservation(o),this.updateResults.record({kind:"update",count:1},["evidence"]),o}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?oe:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?oe:[])}remove(e){const t=new Set(e),s=new Set(this.liveBodyOrder),i=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const n=e.filter(e=>s.has(e)||i.has(e));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?ie:[]),n}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},ne),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},ne)}applyImpulse(e,t,s){this.world.applyImpulse(e,t,s),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},ne)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,s,i)=>e.applyImpulse(t,s,i),clear:()=>e.clear(),hitTest:(t,s,i)=>e.hitTest(t,s,i),pause:()=>e.setPaused(!0),push:(t,s)=>e.enqueue(t,s),pushMany:(t,s)=>e.enqueue(t,s),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:z(this.bodyBudget),config:{...this.config,kernel:G(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(V),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:z(e.bodyBudget??{}),kernel:G(e.world.options)},this.bodyBudget=z(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(V).sort(W),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??ve(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},ie)}spawnDue(e,t){for(;this.queue.length>0&&this.queue[0].spawnAt<=this.elapsedSeconds;){const s=this.queue.shift();if(!s)return;this.spawnOne(s,t),e.push(s.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const s=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:s?.datum??e.datum,x:s?.x??e.x,y:s?.y??e.y},t)}result(e,t,s,i,n,o,r,a=this.evaluateBodyBudget()){this.syncSimulationState(o);const d=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:s,events:n,observations:o,queueSize:this.queue.length,revision:this.revision,shouldContinue:r??(this.queue.length>0||!this.atRest()),sleeping:d,sedimented:i,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,s){if(0===t.length)return;const i=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=i.get(e.bodyId);s.emit({type:"physics-settle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,s){const i=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===i.size&&0===t.size)return i;const n=new Map(e.readState().map(e=>[e.id,e])),o=(e,t)=>{const{sensorId:i,bodyId:o}=U(t),r=s.observation.sensors[i],a=n.get(o);s.emit({type:"enter"===e?r?.enterType??"physics-bin-enter":r?.exitType??"physics-bin-exit",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:o,datum:a?.datum,x:a?.x,y:a?.y,sensorId:i,binId:r?.binId??i})};for(const e of Array.from(i).sort())t.has(e)||o("enter",e);for(const e of Array.from(t).sort())i.has(e)||o("exit",e);return i}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const s of e)t.has(U(s).bodyId)&&e.delete(s)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return P({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const s=`${t.state}:${t.action}`;return s===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=s,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=ve(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const s=this.simulationState;this.simulationState=t,function(e,t,s){s.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||s.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,simulationState:t,previousSimulationState:e})}(s,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:s,liveBodyOrder:i}=me(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=i,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:s}}};function xe(e,t){return function(e,t,s=[],i){const n=new Array(t.length),o=new Float32Array(2*t.length),r=new Float32Array(2*t.length),a=new Uint8Array(t.length);return t.forEach((e,t)=>{const s=2*t;n[t]=e.id,o[s]=e.x,o[s+1]=e.y,r[s]=e.vx,r[s+1]=e.vy,a[t]=e.sleeping?1:0}),{bodies:t,ids:n,positions:o,result:e,sediment:s,sleeping:a,snapshot:i,velocities:r}}(t,e.readBodies(),e.readSediment(),e.snapshot())}function be(e){return xe(e,e.tick(0))}var Se=function(){let e=new ge;return{handle(t){switch(t.type){case"init":return e=new ge(t.config),t.snapshot?e.restore(t.snapshot):t.initialSpawns?.length&&e.enqueue(t.initialSpawns,t.initialSpawnPacing),{type:"frame",frame:be(e)};case"configure":return e.updateConfig(t.config),{type:"frame",frame:be(e)};case"enqueue":return e.enqueue(t.spawns,t.pacing),{type:"frame",frame:be(e)};case"tick":return{type:"frame",frame:xe(e,e.tick(t.deltaSeconds))};case"settle":return{type:"frame",frame:xe(e,e.settleWithObservations(t.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:e.snapshot()};case"restore":return e.restore(t.snapshot),{type:"frame",frame:be(e)};case"clear":return e.clear(),{type:"frame",frame:be(e)};case"remove":return{type:"removed",removed:e.remove(t.ids),frame:be(e)};case"applyImpulse":return e.applyImpulse(t.id,t.ix,t.iy),{type:"frame",frame:be(e)};case"setPaused":return e.setPaused(t.paused),{type:"frame",frame:be(e)};case"setVisible":return e.setVisible(t.visible),{type:"frame",frame:be(e)}}}}}();function we(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:{message:String(e)}}self.onmessage=e=>{const t=e.data;try{const e=Se.handle(t.command);self.postMessage({ok:!0,payload:e,requestId:t.requestId},function(e){return"frame"===e.type||"removed"===e.type?[(t=e.frame).positions.buffer,t.velocities.buffer,t.sleeping.buffer]:[];var t}(e))}catch(e){self.postMessage({error:we(e),ok:!1,requestId:t.requestId})}};