semiotic 3.13.0 → 3.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +53 -41
  2. package/ai/artifact-surface-inventory.json +1 -1
  3. package/ai/dist/mcp-server.js +132 -106
  4. package/ai/reference.md +12 -4
  5. package/ai/schema.json +16 -2
  6. package/ai/surface-manifest.json +1 -1
  7. package/ai/task-packets/compare-category-totals.json +5 -5
  8. package/ai/task-packets/compare-category-totals.md +2 -2
  9. package/ai/task-packets/correct-published-chart.json +5 -5
  10. package/ai/task-packets/correct-published-chart.md +2 -2
  11. package/ai/task-packets/index.json +6 -6
  12. package/ai/task-packets/update-live-chart.json +5 -5
  13. package/ai/task-packets/update-live-chart.md +2 -2
  14. package/dist/{c-CRKR5M42.min.js → c-2M2OPWVA.min.js} +37 -37
  15. package/dist/c-3GIPT46Z.min.js +1 -0
  16. package/dist/c-3UXQGCQT.min.js +1 -0
  17. package/dist/{c-MHNU6KYQ.min.js → c-4P2EM44G.min.js} +3 -3
  18. package/dist/c-4RVDKSMQ.min.js +1 -0
  19. package/dist/{c-6MEEA5VY.min.js → c-4YPPVFZH.min.js} +1 -1
  20. package/dist/{c-6MPP6QF5.min.js → c-62JIVHK5.min.js} +1 -1
  21. package/dist/{c-KYRH3XKJ.min.js → c-6QCSRJSC.min.js} +1 -1
  22. package/dist/c-6WJKNYIG.min.js +1 -0
  23. package/dist/c-7BVQDXFU.min.js +1 -0
  24. package/dist/c-7UN2WUMI.min.js +1 -0
  25. package/dist/c-AQUX6L2O.min.js +1 -0
  26. package/dist/c-BR5QDUCR.min.js +1 -0
  27. package/dist/c-C3YQVUB6.min.js +1 -0
  28. package/dist/{c-RQ2XZHWY.min.js → c-COP4OISO.min.js} +1 -1
  29. package/dist/c-ENRZPF5E.min.js +1 -0
  30. package/dist/c-HBLICBM6.min.js +1 -0
  31. package/dist/{c-EQVM754Z.min.js → c-HGWITEJI.min.js} +1 -1
  32. package/dist/{c-3K2FJDLE.min.js → c-I54V24WG.min.js} +1 -1
  33. package/dist/c-IDCFMBA4.min.js +2 -0
  34. package/dist/{c-TPL7X32J.min.js → c-ISHYKYII.min.js} +1 -1
  35. package/dist/c-KSSS3HSA.min.js +1 -0
  36. package/dist/c-LEICSI5V.min.js +1 -0
  37. package/dist/c-LJ4XY3Z3.min.js +1 -0
  38. package/dist/c-MBE6PPHN.min.js +1 -0
  39. package/dist/c-MOK4RWNO.min.js +1 -0
  40. package/dist/c-N2TVSOYL.min.js +2 -0
  41. package/dist/{c-EAAKQIUZ.min.js → c-NHZ2E3CI.min.js} +1 -1
  42. package/dist/{c-MDY3ULP6.min.js → c-OBA7XSLH.min.js} +1 -1
  43. package/dist/c-OIJL2WZH.min.js +1 -0
  44. package/dist/c-ONOWKUUZ.min.js +1 -0
  45. package/dist/{c-CPJR4LHF.min.js → c-OSLNYZ3Q.min.js} +17 -17
  46. package/dist/c-PBFRYNKM.min.js +1 -0
  47. package/dist/c-QUAEYF34.min.js +1 -0
  48. package/dist/c-RDFFLRKC.min.js +1 -0
  49. package/dist/c-SDGGMIYI.min.js +1 -0
  50. package/dist/c-SQQZPFVY.min.js +1 -0
  51. package/dist/c-SU6Z75M2.min.js +1 -0
  52. package/dist/{c-BWM7MU2Y.min.js → c-SX4TPG3Z.min.js} +1 -1
  53. package/dist/{c-DTYG34WG.min.js → c-VGHU2LTF.min.js} +2 -2
  54. package/dist/c-VLWWXOM5.min.js +1 -0
  55. package/dist/c-VZNIIKL6.min.js +1 -0
  56. package/dist/{c-GBO32OML.min.js → c-W5ATXREF.min.js} +1 -1
  57. package/dist/c-WSWMQDFZ.min.js +1 -0
  58. package/dist/{c-3SDC7AQQ.min.js → c-XM76UG3P.min.js} +1 -1
  59. package/dist/c-XORVM6C5.min.js +1 -0
  60. package/dist/{c-MYRI7NF2.min.js → c-XZJWL7UL.min.js} +1 -1
  61. package/dist/c-Y43GTKGR.min.js +1 -0
  62. package/dist/c-YGTMWEEF.min.js +1 -0
  63. package/dist/c-ZFIURPZA.min.js +1 -0
  64. package/dist/c-ZWJDTDEV.min.js +1 -0
  65. package/dist/c-ZYMXDR42.min.js +1 -0
  66. package/dist/components/ai/chartClinic.d.ts +4 -0
  67. package/dist/components/ai/evaluateChart.d.ts +3 -1
  68. package/dist/components/ai/generativeChart.d.ts +13 -0
  69. package/dist/components/ai/renderEvidenceMemoKey.d.ts +9 -0
  70. package/dist/components/ai/reportRenderError.d.ts +2 -0
  71. package/dist/components/charts/physics/eventDropSources.d.ts +1 -1
  72. package/dist/components/evidence/claimReferences.d.ts +9 -0
  73. package/dist/components/realtime/BinAccumulator.d.ts +5 -0
  74. package/dist/components/recipes/atlas/dependencyEvidence.d.ts +5 -0
  75. package/dist/components/recipes/atlas/support.d.ts +5 -0
  76. package/dist/components/server/staticXYAxisTicks.d.ts +1 -1
  77. package/dist/components/stream/MarginalGraphics.d.ts +4 -2
  78. package/dist/components/stream/PipelineStore.d.ts +6 -18
  79. package/dist/components/stream/axisTickUtils.d.ts +1 -1
  80. package/dist/components/stream/countNoun.d.ts +2 -0
  81. package/dist/components/stream/heatmapBandTicks.d.ts +68 -0
  82. package/dist/components/stream/pipelineDomainResolution.d.ts +52 -3
  83. package/dist/components/stream/renderers/canvasRenderHelpers.d.ts +8 -0
  84. package/dist/components/stream/uniqueRegionLabel.d.ts +6 -0
  85. package/dist/components/stream/xyAxisTicks.d.ts +8 -1
  86. package/dist/components/stream/xyFrameAxisTypes.d.ts +4 -2
  87. package/dist/components/stream/xySceneBuilders/types.d.ts +6 -0
  88. package/dist/geo.min.js +152 -152
  89. package/dist/geo.module.min.js +1 -1
  90. package/dist/network.module.min.js +1 -1
  91. package/dist/ordinal.module.min.js +1 -1
  92. package/dist/physics.module.min.js +1 -1
  93. package/dist/physicsWorker.js +1 -1
  94. package/dist/processSankeyLayoutWorker.js +1 -1
  95. package/dist/semiotic-access.module.min.js +2 -2
  96. package/dist/semiotic-ai-core.min.js +5 -5
  97. package/dist/semiotic-ai-core.module.min.js +4 -4
  98. package/dist/semiotic-ai.module.min.js +2 -2
  99. package/dist/semiotic-artifact.min.js +6 -6
  100. package/dist/semiotic-artifact.module.min.js +2 -2
  101. package/dist/semiotic-atlas-core.min.js +1 -1
  102. package/dist/semiotic-atlas-core.module.min.js +1 -1
  103. package/dist/semiotic-atlas-selection.module.min.js +1 -1
  104. package/dist/semiotic-client-cjs-shared.min.js +1023 -1023
  105. package/dist/semiotic-evidence.min.js +4 -4
  106. package/dist/semiotic-evidence.module.min.js +3 -3
  107. package/dist/semiotic-experimental-auxiliary.module.min.js +1 -1
  108. package/dist/semiotic-experimental-node-auxiliary.module.min.js +1 -1
  109. package/dist/semiotic-experimental-react-shared.module.min.js +1 -1
  110. package/dist/semiotic-experimental-vacp.min.js +1 -1
  111. package/dist/semiotic-experimental-vacp.module.min.js +1 -1
  112. package/dist/semiotic-line.module.min.js +1 -1
  113. package/dist/semiotic-realtime-core.module.min.js +1 -1
  114. package/dist/semiotic-recipes-core-cjs-base.min.js +101 -101
  115. package/dist/semiotic-recipes-core.module.min.js +1 -1
  116. package/dist/semiotic-server-edge-node.module.min.js +3 -3
  117. package/dist/semiotic-server-edge.min.js +397 -397
  118. package/dist/semiotic-server-edge.module.min.js +3 -3
  119. package/dist/semiotic-server-node.min.js +397 -397
  120. package/dist/semiotic-utils-core.min.js +11 -11
  121. package/dist/semiotic-utils-core.module.min.js +3 -3
  122. package/dist/semiotic.module.min.js +1 -1
  123. package/dist/server.min.js +397 -397
  124. package/dist/server.module.min.js +3 -3
  125. package/dist/xy.module.min.js +1 -1
  126. package/package.json +2 -2
  127. package/dist/c-3OBJLOXI.min.js +0 -1
  128. package/dist/c-4VFGNUWG.min.js +0 -1
  129. package/dist/c-5BN7GWJH.min.js +0 -1
  130. package/dist/c-65GMYND6.min.js +0 -1
  131. package/dist/c-AGRMJIUH.min.js +0 -1
  132. package/dist/c-BJKGYOPX.min.js +0 -1
  133. package/dist/c-C332PFY6.min.js +0 -1
  134. package/dist/c-DDZ5TZ7P.min.js +0 -1
  135. package/dist/c-F4DZ3NMI.min.js +0 -1
  136. package/dist/c-GZJ2XEQ5.min.js +0 -1
  137. package/dist/c-HFQ3Z65X.min.js +0 -1
  138. package/dist/c-HNW73MXJ.min.js +0 -1
  139. package/dist/c-HWFZB7SD.min.js +0 -1
  140. package/dist/c-IIV4DB7T.min.js +0 -1
  141. package/dist/c-J2QH3PEI.min.js +0 -1
  142. package/dist/c-JZNWRFVJ.min.js +0 -2
  143. package/dist/c-KHLBCSIO.min.js +0 -1
  144. package/dist/c-L7FQHKGH.min.js +0 -1
  145. package/dist/c-LYPOBMKC.min.js +0 -1
  146. package/dist/c-NGMMPKNJ.min.js +0 -1
  147. package/dist/c-NOME4L5M.min.js +0 -1
  148. package/dist/c-OKIJBK5K.min.js +0 -2
  149. package/dist/c-OXV4W7YX.min.js +0 -1
  150. package/dist/c-P73SQZEP.min.js +0 -1
  151. package/dist/c-PD5EZI24.min.js +0 -1
  152. package/dist/c-RAL7HCTV.min.js +0 -1
  153. package/dist/c-S4OGXAVO.min.js +0 -1
  154. package/dist/c-UWE3VZEO.min.js +0 -1
  155. package/dist/c-VP7WX6QI.min.js +0 -1
  156. package/dist/c-VW7ZSLDC.min.js +0 -1
  157. package/dist/c-WDVYLMCM.min.js +0 -1
  158. package/dist/c-XEACLH4B.min.js +0 -1
  159. package/dist/c-YJDGSPNB.min.js +0 -1
  160. package/dist/c-ZYBEKQCT.min.js +0 -1
@@ -1 +1 @@
1
- function e(e){return{...e,points:e.points.map(e=>({...e}))}}function t(e){if(!Number.isFinite(e.durationSeconds)||e.durationSeconds<=0||!Array.isArray(e.points)||e.points.length<2||e.points.some(e=>!e||!Number.isFinite(e.x)||!Number.isFinite(e.y))||null!=e.elapsedSeconds&&(!Number.isFinite(e.elapsedSeconds)||e.elapsedSeconds<0||e.elapsedSeconds>e.durationSeconds))throw new RangeError("Physics travel requires two finite points, a positive duration and valid elapsed seconds")}function i(e,t){return e&&"object"==typeof e&&"__phase"in e&&e.__phase!==t?{...e,__phase:t}:e}function s(e){return e&&"object"==typeof e&&"late"in e&&e.late?"late":"board"}function n(e){let t=0;for(let i=1;i<e.length;i++)t+=Math.hypot(e[i].x-e[i-1].x,e[i].y-e[i-1].y);return t}function r(e,t){const r=e.travel;if(!r)return!1;const o=Math.min(r.durationSeconds,(r.elapsedSeconds??0)+t);r.elapsedSeconds=o;let a=n(r.points)*o/r.durationSeconds,d=r.points[r.points.length-1];for(let e=1;e<r.points.length;e++){const t=r.points[e-1],i=r.points[e],s=Math.hypot(i.x-t.x,i.y-t.y);if(s>0&&a<s){d={x:t.x+(i.x-t.x)*a/s,y:t.y+(i.y-t.y)*a/s};break}a-=s}if(e.x=d.x,e.y=d.y,e.vx=e.vy=0,o<r.durationSeconds-1e-9)return!1;const h=r.points[r.points.length-1];return e.x=e.prevX=h.x,e.y=e.prevY=h.y,delete e.travel,e.datum=i(e.datum,s(e.datum)),!0}function o(e,t){if(!Number.isFinite(e))throw new RangeError(`${t} must be finite`)}function a(e,t){if(o(e,t),e<=0)throw new RangeError(`${t} must be positive`)}function d(e,t){if(!Array.isArray(e))throw new RangeError(`${t} must be an array`)}function h(e,t){d(e,t);for(const i of e)if("string"!=typeof i)throw new RangeError(`${t} must contain strings`)}function l(e){if(!e||!e.shape||"circle"!==e.shape.type&&"aabb"!==e.shape.type)throw new RangeError("Physics bodies require a circle or aabb shape");const i=`Physics body ${e.id}`;o(e.x,`${i}.x`),o(e.y,`${i}.y`);for(const t of["vx","vy","angle","restitution","friction"])null!=e[t]&&o(e[t],`${i}.${t}`);if(null!=e.mass&&a(e.mass,`${i}.mass`),e.travel&&(t(e.travel),e.fixedPosition))throw new RangeError("Physics travel cannot use fixedPosition");"circle"===e.shape.type?a(e.shape.radius,`${i}.radius`):(a(e.shape.width,`${i}.width`),a(e.shape.height,`${i}.height`))}function c(e){for(const t of["restLength","stiffness","damping"])null!=e[t]&&o(e[t],`Physics spring.${t}`);"point"===e.target.type&&(o(e.target.x,"Physics spring.target.x"),o(e.target.y,"Physics spring.target.y"))}function u(e){l(e),null!=e.spawnAt&&o(e.spawnAt,`Physics body ${e.id}.spawnAt`);for(const t of e.springs??[])c({...t,bodyId:e.id})}function p(e){for(const t of e){if(!t?.shape||"segment"!==t.shape.type&&"aabb"!==t.shape.type)throw new RangeError("Physics colliders require a segment or aabb shape");const e=t.shape;if("segment"===e.type)for(const i of["x1","y1","x2","y2"])o(e[i],`Physics collider ${t.id}.${i}`);else for(const i of["x","y","width","height"])o(e[i],`Physics collider ${t.id}.${i}`);for(const[e,i]of Object.entries(t.shape))"type"!==e&&null!=i&&o(i,`Physics collider ${t.id}.${e}`);for(const e of["restitution","friction"])null!=t[e]&&o(t[e],`Physics collider ${t.id}.${e}`)}}function m(e){for(const[t,i]of Object.entries(e))"gravity"!==t&&null!=i&&o(i,`Physics option ${t}`);e.gravity&&(o(e.gravity.x,"Physics gravity.x"),o(e.gravity.y,"Physics gravity.y"));for(const t of["fixedDt","cellSize"])null!=e[t]&&a(e[t],`Physics option ${t}`);if(null!=e.velocityDamping&&e.velocityDamping<0)throw new RangeError("Physics velocityDamping must be nonnegative")}function f(e){h(e.activeSensors,"Physics activeSensors"),d(e.bodies,"Physics bodies"),d(e.colliders,"Physics colliders"),d(e.springs,"Physics springs"),m(e.options);for(const t of e.bodies){l(t);for(const e of["prevX","prevY","sleepTime","index"])o(t[e],`Physics body ${t.id}.${e}`)}p(e.colliders);for(const t of e.springs)c(t);null!=e.randomState&&o(e.randomState,"Physics randomState")}function v(e){e.kernel&&m(e.kernel),e.viewTransform&&(o(e.viewTransform.x,"Physics viewTransform.x"),o(e.viewTransform.y,"Physics viewTransform.y")),e.colliders&&p(e.colliders),null!=e.fixedDt&&a(e.fixedDt,"Physics fixedDt");for(const t of["maxDeltaSeconds","maxSubsteps","settleStepLimit","timeScale"])if(null!=e[t]&&(o(e[t],`Physics ${t}`),e[t]<0))throw new RangeError(`Physics ${t} must be nonnegative`)}function y(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(i in e!=i in t||!Object.is(e[i],t[i]))return!1;return!0}function g(e,t){return e===t||!(!e||!t||e.length!==t.length)&&e.every((e,i)=>{const s=t[i],n=e.shape,r=s.shape,o="segment"===n.type&&"segment"===r.type?n.x1===r.x1&&n.y1===r.y1&&n.x2===r.x2&&n.y2===r.y2&&(n.thickness??0)===(r.thickness??0):"aabb"===n.type&&"aabb"===r.type&&n.x===r.x&&n.y===r.y&&n.width===r.width&&n.height===r.height;return e.id===s.id&&e.sensor===s.sensor&&e.friction===s.friction&&e.restitution===s.restitution&&function(e,t){return e===t||!(!e||!t||"function"==typeof e||"function"==typeof t)&&e.property===t.property&&"equals"in e=="equals"in t&&"notEquals"in e=="notEquals"in t&&Object.is(e.equals,t.equals)&&Object.is(e.notEquals,t.notEquals)&&y(e.oneOf,t.oneOf)&&y(e.notOneOf,t.notOneOf)}(e.bodyFilter,s.bodyFilter)&&o})}function w(e,t){return Boolean(t?.some(t=>Object.is(e,t)))}function x(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const i=function(e,t){if(!t)return;let i=e;for(const e of t.split(".")){if(null==i||"object"!=typeof i)return;if(!Object.prototype.hasOwnProperty.call(i,e))return;i=i[e]}return i}(e,t.property);return!("equals"in t&&!Object.is(i,t.equals))&&((!("notEquals"in t)||!Object.is(i,t.notEquals))&&(!(t.oneOf&&!w(i,t.oneOf))&&(!t.notOneOf||!w(i,t.notOneOf))))}function b(e){let t=e>>>0;function i(){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}return i.getState=()=>t>>>0,i}function S(e){const t=e.fixedPosition;Number.isFinite(t?.x)&&(e.x=e.prevX=t.x,e.vx=0),Number.isFinite(t?.y)&&(e.y=e.prevY=t.y,e.vy=0)}function M(e){if(!e)return;const t=Number.isFinite(e.x)?e.x:void 0,i=Number.isFinite(e.y)?e.y:void 0;return null==t&&null==i?void 0:{x:t,y:i}}function I(e,t,i){const s="x"===i?"y":"x",n=Math.abs(t[i]-e[i]),r=t[s]-e[s],o=(e,t)=>"circle"===e.shape.type?e.shape.radius:("x"===t?e.shape.width:e.shape.height)/2;let a;if("circle"===e.shape.type&&"circle"===t.shape.type){const i=e.shape.radius+t.shape.radius;a=Math.sqrt(Math.max(0,i*i-n*n))}else if("aabb"===e.shape.type&&"aabb"===t.shape.type)a=o(e,s)+o(t,s);else{const r="circle"===e.shape.type?e:t,d="aabb"===e.shape.type?e:t,h=o(r,i),l=Math.max(0,n-o(d,i));a=o(d,s)+Math.sqrt(Math.max(0,h*h-l*l))}const d=r<0?-1:1;return{nx:"x"===s?d:0,ny:"y"===s?d:0,penetration:Math.max(0,a-Math.abs(r))}}function T(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function k(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 P(t){return{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,bodyCollisions:t.bodyCollisions,...t.travel?{travel:e(t.travel)}:{},...t.fixedPosition?{fixedPosition:M(t.fixedPosition)}:{},shape:T(t.shape),sleeping:t.sleeping,datum:t.datum}}function q(e){return{...P(e),index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function E(e){return e&&"function"!=typeof e?{property:e.property,..."equals"in e?{equals:e.equals}:{},..."notEquals"in e?{notEquals:e.notEquals}:{},oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function A(e){return{id:e.id,shape:k(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:E(e.bodyFilter),index:e.index}}var B=1e-9;function D(e,t,i){let s=i.length>2,n=1/0,r=i[0][0],o=i[0][1],a=1,d=0;for(let h=0;h<i.length;h++){const[l,c]=i[h],[u,p]=i[(h+1)%i.length],m=u-l,f=p-c,v=Math.hypot(m,f);if(v<=B)continue;const y=f/v,g=-m/v;(e-l)*y+(t-c)*g>0&&(s=!1);const w=Math.max(0,Math.min(1,((e-l)*m+(t-c)*f)/(v*v))),x=l+w*m,b=c+w*f,S=(e-x)**2+(t-b)**2;S<n&&(n=S,r=x,o=b,a=y,d=g)}const h=Math.hypot(e-r,t-o);return!s&&h>B&&(a=(e-r)/h,d=(t-o)/h),{distance:s?-h:h,nx:a,ny:d}}function O(e,t,i,s){const n=e.x-e.prevX,r=e.y-e.prevY,o=n*n+r*r;if(o<=1e-18)return null;if(0===i&&!function(e,t){let i=0,s=1;const n=e.x-e.prevX,r=e.y-e.prevY;for(let o=0;o<t.length;o++){const[a,d]=t[o],[h,l]=t[(o+1)%t.length],c=l-d,u=a-h;if(Math.hypot(c,u)<=B)continue;const p=(e.prevX-a)*c+(e.prevY-d)*u,m=n*c+r*u;if(m<0)i=Math.max(i,-p/m);else if(m>0)s=Math.min(s,-p/m);else if(p>=0)return!1;if(i>=s)return!1}return i<s}(e,t))return null;if(D(e.prevX,e.prevY,t).distance<i-s)return null;let a=1/0,d=null;const h=(t,s,o,h,l)=>{if(t<0||t>1||t>a)return;if(t===a&&d&&Math.abs(s)<=Math.abs(d.nx))return;if(n*s+r*o>=0)return;const c=i-((e.x-h)*s+(e.y-l)*o);c<=0||(a=t,d={nx:0===s?0:s,ny:0===o?0:o,penetration:c})};for(let a=0;a<t.length;a++){const[d,l]=t[a],[c,u]=t[(a+1)%t.length],p=c-d,m=u-l,f=Math.hypot(p,m);if(f>B){const t=m/f,o=-p/f,a=n*t+r*o,c=(e.prevX-d)*t+(e.prevY-l)*o-i;if(a<0&&c>=-s){const i=Math.max(0,-c/a),s=((e.prevX+i*n-d)*p+(e.prevY+i*r-l)*m)/f;s>=0&&s<=f&&h(i,t,o,d,l)}}if(i<=0)continue;const v=e.prevX-d,y=e.prevY-l,g=v*n+y*r,w=g*g-o*(v*v+y*y-i*i);if(g>=0||w<0)continue;const x=Math.max(0,(-g-Math.sqrt(w))/o),b=v+x*n,S=y+x*r,M=Math.hypot(b,S);M>B&&h(x,b/M,S/M,d,l)}return d}function R(e,t,i){if("aabb"!==t.type||e.x===e.prevX&&e.y===e.prevY)return null;const s="circle"===e.shape.type?e.shape.radius:0,n=(t.width+("aabb"===e.shape.type?e.shape.width:0))/2,r=(t.height+("aabb"===e.shape.type?e.shape.height:0))/2,o=t.x-n,a=t.x+n,d=t.y-r,h=t.y+r;return Math.max(e.x,e.prevX)+s<o||Math.min(e.x,e.prevX)-s>a||Math.max(e.y,e.prevY)+s<d||Math.min(e.y,e.prevY)-s>h?null:O(e,[[o,d],[a,d],[a,h],[o,h]],s,i)}function C(e,t,i=0,s=!1){const n=function(e,t){let{x1:i,y1:s,x2:n,y2:r}=t;if("circle"===e.shape.type)return[[i,s],[n,r]];(i>n||i===n&&s>r)&&(i=t.x2,s=t.y2,n=t.x1,r=t.y1);const o=e.shape.width/2,a=e.shape.height/2*(r>=s?1:-1),d=[[i-o,s-a],[i+o,s-a],[n+o,r-a],[n+o,r+a],[n-o,r+a],[i-o,s+a]];return a<0?d.reverse():d}(e,t),r=(t.thickness??0)/2+("circle"===e.shape.type?e.shape.radius:0);if(s){const t=O(e,n,r,i);if(t)return t}const o=D(e.x,e.y,n),a=r-o.distance;return a>0?{nx:o.nx,ny:o.ny,penetration:a}:null}function N(e,t){return Math.abs(e.x-t.x)<=t.padding&&Math.abs(e.y-t.y)<=t.padding}function F(e,t){const i=z(e),s=[];for(let e=0;e<t.length;e++)Y(i,t[e].bounds)&&s.push(e);return{bounds:i,indexes:s}}function z(e,t=!0){const i="circle"===e.shape.type?e.shape.radius:e.shape.width/2,s="circle"===e.shape.type?e.shape.radius:e.shape.height/2,n=t?Math.max(.005,Math.min(i,s)):0;return{x:e.x,y:e.y,padding:n,minX:Math.min(e.x,e.prevX)-i-n,minY:Math.min(e.y,e.prevY)-s-n,maxX:Math.max(e.x,e.prevX)+i+n,maxY:Math.max(e.y,e.prevY)+s+n}}function W(e){const t="circle"===e.shape.type?e.shape.radius:e.shape.width/2,i="circle"===e.shape.type?e.shape.radius:e.shape.height/2;return{minX:e.x-t,minY:e.y-i,maxX:e.x+t,maxY:e.y+i}}function $(e){const t=e.shape;if("aabb"===t.type)return W({x:t.x,y:t.y,shape:t});const i=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-i,minY:Math.min(t.y1,t.y2)-i,maxX:Math.max(t.x1,t.x2)+i,maxY:Math.max(t.y1,t.y2)+i}}function Y(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function X(e,t,i={x:0,y:0}){let s=1;const n=e.map(e=>{const t=z(e,!(e.sleeping&&e.x===e.prevX&&e.y===e.prevY));return!1!==e.bodyCollisions&&(s=Math.max(s,t.maxX-t.minX,t.maxY-t.minY)),t}),r=Math.max(1,Math.min(t,s)),o=new Map;for(let t=0;t<e.length;t+=1){if(!1===e[t].bodyCollisions)continue;const i=n[t];i.cellX=Math.floor(i.minX/r),i.cellY=Math.floor(i.minY/r);for(let e=i.cellX;e<=Math.floor(i.maxX/r);e+=1){let s=o.get(e);s||o.set(e,s=new Map);for(let e=i.cellY;e<=Math.floor(i.maxY/r);e+=1){const i=s.get(e);i?i.push(t):s.set(e,[t])}}}const a=[];for(const[e,t]of o)for(const[i,s]of t)for(let t=0;t<s.length;t+=1)for(let r=t+1;r<s.length;r+=1){const o=s[t],d=s[r],h=n[o],l=n[d];e===Math.max(h.cellX,l.cellX)&&i===Math.max(h.cellY,l.cellY)&&(Y(h,l)&&a.push([o,d]))}const d=e.map(e=>e.x*i.x+e.y*i.y);return a.sort(([e,t],[i,s])=>Math.max(d[i],d[s])-Math.max(d[e],d[t])||(e===i?t-s:e-i)),{pairs:a,coversPositions:()=>e.every((e,t)=>!1===e.bodyCollisions||N(e,n[t]))}}function j(e,t){if("circle"!==e.shape.type||"circle"!==t.shape.type)return null;const i=e.shape.radius+t.shape.radius;if(i<=0)return null;const s=t.prevX-e.prevX,n=t.prevY-e.prevY,r=t.x-e.x-s,o=t.y-e.y-n,a=r*r+o*o,d=2*(s*r+n*o),h=s*s+n*n-i*i;if(h<-1e-5||a<=1e-12||d>=0)return null;const l=d*d-4*a*h;if(l<0)return null;const c=(-d-Math.sqrt(l))/(2*a);if(c<0||c>1)return null;const u=(s+c*r)/i,p=(n+c*o)/i,m=i-((t.x-e.x)*u+(t.y-e.y)*p);return m>0?{nx:u,ny:p,penetration:m}:null}var L={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},_=1e-9,K=.005;function V(e,t,i){return Math.max(t,Math.min(i,e))}function U(e,t,i){return Math.min(e??i,t??i)}function H(e,t,i){return V(Math.max(e??i,t??i),0,1)}function G(e){return e<0?-1:1}function Q(e){return e.sleeping&&e.x===e.prevX&&e.y===e.prevY}function J(e,t,i,s,n,r,o,a){const d=n-e,h=(i+o)/2-Math.abs(d);if(h<=0)return null;const l=r-t,c=(s+a)/2-Math.abs(l);return c<=0?null:h<c?{nx:G(d),ny:0,penetration:h}:{nx:0,ny:G(l),penetration:c}}function Z(e,t,i,s,n,r,o){const a=r/2,d=o/2,h=e-V(e,s-a,s+a),l=t-V(t,n-d,n+d),c=h*h+l*l;if(c>i*i)return null;if(c<=_){const r=Math.abs(e-(s-a)),o=Math.abs(e-(s+a)),h=Math.abs(t-(n-d)),l=Math.abs(t-(n+d)),c=Math.min(r,o,h,l);return c===r?{nx:-1,ny:0,penetration:i+r}:c===o?{nx:1,ny:0,penetration:i+o}:c===h?{nx:0,ny:-1,penetration:i+h}:{nx:0,ny:1,penetration:i+l}}const u=Math.sqrt(c);return{nx:h/u,ny:l/u,penetration:i-u}}function ee(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,i,s,n,r){const o=s-e,a=n-t,d=i+r,h=o*o+a*a;if(h>=d*d)return null;if(h<=_)return{nx:1,ny:0,penetration:d};const l=Math.sqrt(h);return{nx:o/l,ny:a/l,penetration:d-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 J(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);const i="circle"===e.shape.type?e:t,s=i===e?t:e;if("circle"!==i.shape.type||"aabb"!==s.shape.type)return null;const n=Z(i.x,i.y,i.shape.radius,s.x,s.y,s.shape.width,s.shape.height);return n&&i===e&&(n.nx=-n.nx,n.ny=-n.ny),n}function te(e,t){const i=t.shape;return"aabb"===i.type?"circle"===e.shape.type?Z(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height):J(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height):C(e,i)}function ie(e,t){return`${e}\0${t}`}function se(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function ne(e,t){return x(t,e.bodyFilter)}var re=class{constructor(e={}){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.supportDependents=new Map,this.supportContactsThisStep=new Set,this.reboundingThisStep=new Set,this.interpenetratingThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,m(e),this.options={...L,...e},this.random=b(this.options.seed)}init(e={}){m(e),this.options={...L,...e},this.random=b(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(t){l(t);const i={id:t.id,x:t.x,y:t.y,prevX:t.x,prevY:t.y,vx:t.vx??0,vy:t.vy??0,angle:t.angle??0,mass:Math.max(_,t.mass??1),bodyCollisions:t.bodyCollisions??!0,...t.fixedPosition?{fixedPosition:M(t.fixedPosition)}:{},...t.travel?{travel:e(t.travel)}:{},shape:T(t.shape),sleeping:!1,datum:t.datum,restitution:t.restitution,friction:t.friction,index:this.nextBodyIndex,sleepTime:0};i.travel&&r(i,0),S(i),this.nextBodyIndex+=1,this.bodies.set(t.id,i)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))se(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){if(p(e),!g(e,this.sortedColliders())){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:k(t.shape),bodyFilter:E(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}}setConstraint(e){c(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,i){if(!Number.isFinite(t)||!Number.isFinite(i))throw new RangeError("Physics impulses must be finite");const s=this.bodies.get(e);s&&(s.vx+=t/s.mass,s.vy+=i/s.mass,S(s),this.wake(s))}step(e=this.options.fixedDt){const t=Number.isFinite(e)?Math.max(0,e):0;if(this.lastEvents=[],0===t)return;this.reboundingThisStep.clear();const i=this.sortedBodies(),s=i.some(e=>e.travel)?i.filter(e=>!e.travel):i;for(const e of i)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const n=this.options.maxVelocity,o=this.options.velocityDamping**(120*t);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*=o,e.vy*=o,S(e),n>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>n){const i=n/t;e.vx*=i,e.vy*=i}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear(),this.supportDependents.clear(),this.supportContactsThisStep.clear(),this.interpenetratingThisStep.clear();const a=this.sortedColliders().filter(e=>!e.sensor).map(e=>({collider:e,bounds:$(e)})),d=a.some(({collider:e})=>e.bodyFilter)?void 0:new Array(s.length),h=new Set,l=new Set;this.resolveColliders(s,a,h,d);const c=d&&s.map(Q);let u=X(s,this.options.cellSize,this.options.gravity);for(let e=0;e<this.options.collisionIterations;e+=1){e>0&&!u.coversPositions()&&(u=X(s,this.options.cellSize,this.options.gravity));const t=this.resolveBodyPairs(s,u.pairs,l,0===e,c),i=this.resolveColliders(s,a,h,d);if(d&&!t&&!i)break}u.coversPositions()||(u=X(s,this.options.cellSize,this.options.gravity));for(const[e,t]of u.pairs){const i=ee(s[e],s[t]);i&&i.penetration>.02&&(this.interpenetratingThisStep.add(s[e].id),this.interpenetratingThisStep.add(s[t].id))}const p=Array.from(this.supportedThisStep);for(let e=0;e<p.length;e+=1)for(const t of this.supportDependents.get(p[e])??[])this.supportedThisStep.has(t)||(this.supportedThisStep.add(t),p.push(t));this.reconcileSupportedVelocity(s,t),this.updateSensors(s),this.updateSleeping(s,t);for(const e of i)r(e,t)&&this.lastEvents.push({type:"travel-end",bodyId:e.id})}settle(e=1200,t=this.options.fixedDt){let i=0;for(;i<e&&!this.allSleeping();)this.step(t),i+=1;return i}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push(P(t));return e}readBody(e){const t=this.bodies.get(e);return t?P(t):void 0}workerSleepTimes(e){return Float32Array.from(e,e=>this.bodies.get(e)?.sleepTime??0)}applyWorkerMotion(e){e.ids.forEach((t,n)=>{const r=this.bodies.get(t);r&&(r.prevX=e.previousPositions?.[2*n]??r.x,r.prevY=e.previousPositions?.[2*n+1]??r.y,r.x=e.positions[2*n],r.y=e.positions[2*n+1],r.vx=e.velocities[2*n],r.vy=e.velocities[2*n+1],r.sleeping=1===e.sleeping[n],r.sleepTime=e.sleepTimes?.[n]??(r.sleeping?this.options.sleepAfter:0),r.travel&&e.travelElapsed&&(r.travel.elapsedSeconds=e.travelElapsed[n]),r.datum=i(r.datum,r.travel?"travel":r.sleeping?"settled":s(r.datum)))}),this.lastEvents=e.result.events,e.state&&(this.activeSensors=new Set(e.state.activeSensorPairs))}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(se)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{randomState:this.random.getState(),options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(q),colliders:this.sortedColliders().map(A),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(e){f(e),this.options={...e.options,gravity:{...e.options.gravity}},this.random=b(e.randomState??this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const t of e.bodies){const e=q(t);S(e),this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(const t of e.colliders){const e=A(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(const t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});const e=/^spring-(\d+)$/.exec(t.id);e&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(e[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<t.id?-1:e.id>t.id?1:0)){const i=this.bodies.get(t.bodyId);if(!i||i.sleeping||i.travel)continue;const s="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!s)continue;const n=s.x-i.x,r=s.y-i.y,o=n*n+r*r,a=Math.sqrt(o);if(a<=_)continue;const d=n/a,h=r/a,l="vx"in s?s.vx:0,c="vy"in s?s.vy:0,u=(l-i.vx)*d+(c-i.vy)*h,p=(a-t.restLength)*t.stiffness+u*t.damping;i.vx+=p*d*e/i.mass,i.vy+=p*h*e/i.mass}}resolveBodyPairs(e,t,i,s,n){let r=!1;for(const[o,a]of t){const t=e[o],d=e[a];if(!t||!d)continue;if(!s&&n?.[o]&&n[a]&&Q(t)&&Q(d)){r=!0;continue}const h=j(t,d)??ee(t,d);if(!h)continue;r=!0,this.resolveDynamicCollision(t,d,h);const l=o*e.length+a;i.has(l)||(i.add(l),this.lastEvents.push({type:"contact",bodyId:t.id,otherId:d.id,sensor:!1}))}return r}resolveDynamicCollision(e,t,i){(e.fixedPosition||t.fixedPosition)&&(!e.sleeping&&null==e.fixedPosition?.x||!t.sleeping&&null==t.fixedPosition?.x?!e.sleeping&&null==e.fixedPosition?.y||!t.sleeping&&null==t.fixedPosition?.y||(i=I(e,t,"y")):i=I(e,t,"x"));const s=this.options.gravity,n=Math.hypot(s.x,s.y),r=this.contactOpposesGravity(i.nx,i.ny,n),o=this.contactOpposesGravity(-i.nx,-i.ny,n);r&&(e.sleeping&&this.supportedThisStep.add(t.id),this.addSupportContact(e.id,t.id)),o&&(t.sleeping&&this.supportedThisStep.add(e.id),this.addSupportContact(t.id,e.id));const a=e.sleeping?0:1/e.mass,d=t.sleeping?0:1/t.mass,h=null==e.fixedPosition?.x?a:0,l=null==e.fixedPosition?.y?a:0,c=null==t.fixedPosition?.x?d:0,u=null==t.fixedPosition?.y?d:0,p=e.fixedPosition||t.fixedPosition?i.nx**2*(h+c)+i.ny**2*(l+u):a+d;if(p<=_)return;const m=this.supportedThisStep.has(e.id)&&r&&!t.sleeping&&!t.fixedPosition,f=this.supportedThisStep.has(t.id)&&o&&!e.sleeping&&!e.fixedPosition,v=n>1,y=v&&m?0:h,g=v&&m?0:l,w=v&&!m&&f?0:c,x=v&&!m&&f?0:u,b=i.nx**2*(y+w)+i.ny**2*(g+x),S=Math.max(0,i.penetration-K)/Math.max(_,b);e.x-=i.nx*S*y,e.y-=i.ny*S*g,t.x+=i.nx*S*w,t.y+=i.ny*S*x,v&&m&&this.supportedThisStep.add(t.id),v&&f&&this.supportedThisStep.add(e.id);const M=t.vx-e.vx,T=t.vy-e.vy,k=M*i.nx+T*i.ny;if(k>0)return;const P=Math.abs(k),q=U(e.restitution,t.restitution,this.options.restitution),E=e.vx*s.x+e.vy*s.y,A=t.vx*s.x+t.vy*s.y,B=-(1+q)*k/p,D=B*i.nx,O=B*i.ny;e.vx-=D*h,e.vy-=O*l,t.vx+=D*c,t.vy+=O*u,this.applyFriction(e,t,i,B,h,l,c,u),q>0&&(E>=0&&e.vx*s.x+e.vy*s.y<0&&this.reboundingThisStep.add(e.id),A>=0&&t.vx*s.x+t.vy*s.y<0&&this.reboundingThisStep.add(t.id)),P>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,s,n,r,o,a){const d=-i.ny,h=i.nx,l=(t.vx-e.vx)*d+(t.vy-e.vy)*h,c=e.fixedPosition||t.fixedPosition?d**2*(n+o)+h**2*(r+a):n+o;if(Math.abs(l)<=_||c<=_)return;const u=H(e.friction,t.friction,this.options.friction),p=V(-l/c,-s*u,s*u),m=p*d,f=p*h;e.vx-=m*n,e.vy-=f*r,t.vx+=m*o,t.vy+=f*a}resolveColliders(e,t,i,s){if(0===t.length)return!1;let n=!1;for(let r=0;r<e.length;r++){const o=e[r];let a=s?.[r];!s||a&&N(o,a.bounds)||(s[r]=a=F(o,t));let d=0;for(;d<(a?a.indexes.length:t.length);){const e=a?a.indexes[d++]:d++,{collider:h,bounds:l}=t[e];if(!ne(h,o))continue;const c="segment"===h.shape.type?C(o,h.shape,.0050000010000000004,!0):R(o,h.shape,.0050000010000000004)??(Y(W(o),l)?te(o,h):null);if(!c)continue;n=!0,this.resolveStaticCollision(o,h,c),this.contactOpposesGravity(c.nx,c.ny)&&this.supportedThisStep.add(o.id);const u=r*t.length+e;if(i.has(u)||(i.add(u),this.lastEvents.push({type:"contact",bodyId:o.id,otherId:h.id,sensor:!1})),a&&s&&!N(o,a.bounds))for(s[r]=a=F(o,t),d=0;d<a.indexes.length&&a.indexes[d]<=e;)d++}}return n}resolveStaticCollision(e,t,i){e.x+=i.nx*Math.max(0,i.penetration-K),e.y+=i.ny*Math.max(0,i.penetration-K);const s=e.vx*i.nx+e.vy*i.ny;if(s<0){const n=U(e.restitution,t.restitution,this.options.restitution),r=this.options.gravity,o=e.vx*r.x+e.vy*r.y;e.vx-=(1+n)*s*i.nx,e.vy-=(1+n)*s*i.ny;const a=-i.ny,d=i.nx,h=e.vx*a+e.vy*d,l=H(e.friction,t.friction,this.options.friction)*-(1+n)*s,c=V(h,-l,l);e.vx-=c*a,e.vy-=c*d,n>0&&o>=0&&e.vx*r.x+e.vy*r.y<0&&this.reboundingThisStep.add(e.id)}S(e)}updateSensors(e){const t=this.sortedColliders().filter(e=>e.sensor);if(0===t.length&&0===this.activeSensors.size)return;const i=new Set;for(const s of e){const e=W(s);for(const n of t){if(!ne(n,s))continue;if(!Y(e,$(n)))continue;if(!te(s,n))continue;const t=ie(n.id,s.id);i.add(t),this.activeSensors.has(t)||this.lastEvents.push({type:"sensor-enter",bodyId:s.id,sensorId:n.id})}}for(const e of Array.from(this.activeSensors).sort()){if(i.has(e))continue;const{sensorId:t,bodyId:s}=se(e);this.lastEvents.push({type:"sensor-exit",bodyId:s,sensorId:t})}this.activeSensors=i}updateSleeping(e,t){const s=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const n of e){const e=Math.sqrt(n.vx*n.vx+n.vy*n.vy),r=Math.sqrt((n.x-n.prevX)*(n.x-n.prevX)+(n.y-n.prevY)*(n.y-n.prevY));!(e<this.options.sleepSpeed&&r<this.options.sleepSpeed*t&&!this.interpenetratingThisStep.has(n.id))||s&&!this.supportedThisStep.has(n.id)?n.sleeping?this.wake(n):n.sleepTime=0:(n.sleepTime+=t,!n.sleeping&&n.sleepTime>=this.options.sleepAfter&&(n.sleeping=!0,n.vx=0,n.vy=0,n.datum=i(n.datum,"settled"),this.lastEvents.push({type:"sleep",bodyId:n.id})))}}addSupportContact(e,t){let i=this.supportDependents.get(e);i?.has(t)||(this.supportContactsThisStep.add(e),this.supportContactsThisStep.add(t),i||(i=new Set,this.supportDependents.set(e,i)),i.add(t))}reconcileSupportedVelocity(e,t){const i=this.options.gravity;if(!(Math.hypot(i.x,i.y)<=1))for(const s of e)!s.sleeping&&this.supportedThisStep.has(s.id)&&this.supportContactsThisStep.has(s.id)&&(this.reboundingThisStep.has(s.id)&&s.vx*i.x+s.vy*i.y<0||(s.vx=(s.x-s.prevX)/t,s.vy=(s.y-s.prevY)/t,S(s)))}contactOpposesGravity(e,t,i){const{x:s,y:n}=this.options.gravity;return i??(i=Math.hypot(s,n)),i<=1e-9||(e*s+t*n)/i<-.2}wake(e){e.travel||(e.datum=i(e.datum,s(e.datum))),e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},oe=class{constructor(e={}){this.id="builtin",this.world=new re(e),this.capabilities={...this.world.capabilities,engine:"builtin"}}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,i){this.world.applyImpulse(e,t,i)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}readBody(e){return this.world.readBody(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)}workerSleepTimes(e){return this.world.workerSleepTimes(e)}applyWorkerMotion(e){this.world.applyWorkerMotion(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function ae(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):function(e={}){return new oe(e)}(t)}var de=["binId","targetBin","category","windowIndex","lane","group"];function he(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function le(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 i=t-e.mean;e.mean+=i/e.count;const s=t-e.mean;e.m2+=i*s}function ce(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 ue(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 pe(e,t){const i=e;if(null!=i[t])return i[t];const s=e.datum;return s&&"object"==typeof s?s[t]:void 0}function me(e,t,i){return"function"==typeof e?e(t,i):"string"==typeof e?pe(t,e):void 0}function fe(e){if(null==e)return;const t=String(e);return t.trim()?t:void 0}function ve(e){const t=ce(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:ce(e.x),y:ce(e.y),value:t}}var ye=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 i=fe(me(this.config.binAccessor,e,t))??function(e){for(const t of de){const i=fe(pe(e,t));if(i)return i}return"sediment"}(e),s=fe(me(this.config.labelAccessor,e,t))??i,n=function(e,t,i){if("number"==typeof e)return e;const s="function"==typeof e?e(t,i):"string"==typeof e?pe(t,e):1,n="number"==typeof s?s:Number(s);return Number.isFinite(n)?n:1}(this.config.valueAccessor,e,t),r=Math.max(0,Math.floor(this.config.retainBodyIds??12));let o=this.bins.get(i);return o||(o={id:i,label:s,bodyIds:[],x:he(),y:he(),value:he()},this.bins.set(i,o)),o.label=s,o.lastBodyId=e.id,o.lastDatum=e.datum,le(o.x,e.x),le(o.y,e.y),le(o.value,n),r>0&&(o.bodyIds.push(e.id),o.bodyIds.length>r&&(o.bodyIds=o.bodyIds.slice(o.bodyIds.length-r))),ve(o)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(ve)}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:ue(t.x),y:ue(t.y),value:ue(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 ge(e){const t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function we(e){const t=Math.max(0,Math.floor(e.liveBodies)),i=Math.max(0,Math.floor(e.queuedBodies??0)),s=t+i,n=ge(e.bodyLimit),r=ge(e.engineMaxBodiesHint),o=function(e,t,i){if(!1===i)return;const s=ge(i?.warnAt);return null!=s?s:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(n,r,e.options),a=null==n?0:Math.max(0,t-n),d=a>0?"overflow":null!=o&&s>=o?"warning":"ok";return{action:"overflow"!==d?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:r,liveBodies:t,overflow:a,projectedBodies:s,queuedBodies:i,state:d,warnAt:o}}var xe={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1,viewTransform:{x:0,y:0}};function be(e,t,i){return{...e,timestamp:e.timestamp??t,chartType:e.chartType??i.chartType,chartId:e.chartId??i.chartId}}var Se={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Me(e={},t=Se){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 Ie(t){return{...t,shape:{...t.shape},...t.travel?{travel:e(t.travel)}:{},...t.fixedPosition?{fixedPosition:{...t.fixedPosition}}:{},datum:t.datum,springs:t.springs?.map(e=>({...e,target:{...e.target}}))}}function Te(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 ke(e,t){const i=e;if(null!=i[t])return i[t];const s=e.datum;return s&&"object"==typeof s?s[t]:void 0}function Pe(e,t={}){const i=Te(t.startAt)??0,s=t.pacing??"immediate";if("arrival"===s){let s=1/0;const n=e.map((e,i)=>{const n=function(e,t,i){return"function"==typeof i?Te(i(e,t)):"string"==typeof i?Te(ke(e,i)):Te(e.spawnAt)??Te(ke(e,"arrivalTime"))??Te(ke(e,"timestamp"))??Te(ke(e,"time"))??Te(ke(e,"eventTime"))}(e,i,t.timeAccessor);return null!=n&&(s=Math.min(s,n)),n}),r=Te(t.timeScale)??1,o=r>0?r:1;return e.map((e,t)=>{const r=n[t],a=null==r?0:Math.max(0,r-s);return{...Ie(e),spawnAt:i+a/o}})}if("object"==typeof s){const t=Te(s.ratePerSec);if(t&&t>0)return e.map((e,s)=>({...Ie(e),spawnAt:i+s/t}))}return e.map(e=>({...Ie(e),spawnAt:i}))}function qe(e){return{...Ie(e),sequence:e.sequence,spawnAt:e.spawnAt}}function Ee(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 Ae(e){return!1!==e&&{...e}}function Be(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function De(e){return{...e,gravity:{...e.gravity}}}function Oe(e,t,i,s){if("circle"===e.shape.type){const n=e.x-t,r=e.y-i,o=e.shape.radius+s,a=n*n+r*r;return a<=o*o?a:null}const n=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),r=Math.max(Math.abs(i-e.y)-e.shape.height/2,0),o=n*n+r*r;return o<=s*s?o:null}function Re(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function Ce(e,t={}){const{idPrefix:i="plot",includeFloor:s=!0,includeCeiling:n=!1,includeLeftWall:r=!0,includeRightWall:o=!0,wallThickness:a=20,floorThickness:d=a}=t,h=[],l=e.x+e.width/2,c=e.y+e.height/2,u=(e,t,s,n,r)=>{h.push({id:`${i}-${e}`,shape:{type:"aabb",x:t,y:s,width:n,height:r}})};return s&&u("floor",l,e.y+e.height+d/2,e.width+2*a,d),n&&u("ceiling",l,e.y-d/2,e.width+2*a,d),r&&u("left-wall",e.x-a/2,c,a,e.height+2*d),o&&u("right-wall",e.x+e.width+a/2,c,a,e.height+2*d),h}var Ne={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 Fe(e,t){const i={...e};for(const e of t){i[Ne[e]]++}return i}function ze(e,t,i){const s=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:s,revisions:Fe(i,s)}}var We=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=ze({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 i=ze(e,t,this.revisions);this.revisions=i.revisions,this.latest=i;for(const e of[...this.listeners])e();return i}};import{quadtree as $e}from"d3-quadtree";var Ye=class{constructor(){this.order=new Map,this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,i,s,n,r=0,o){const a=this.ensure(e,t,i);if(!a)return null;let d=null,h=Number.POSITIVE_INFINITY;const l=Math.max(0,o?.searchRadius??Math.max(0,r)+this.maxSearchRadius),c=s-l,u=s+l,p=n-l,m=n+l;return a.visit((e,t,i,a,l)=>{if(a<c||t>u||l<p||i>m)return!0;if(e.length)return!1;let f=e;for(;f;){const e=f.data;if(e&&(!o?.include||o.include(e))){const t=o?.distanceSquared?o.distanceSquared(e,s,n):Oe(e,s,n,Math.max(0,r));null!=t&&(t<h||t===h&&(this.order.get(e.id)??-1)>(this.order.get(d?.id??"")??-1))&&(d=e,h=t)}f=f.next}return!1}),d}ensure(e,t,i){if(this.tree&&this.revision===t)return this.tree;this.order=new Map(Array.from(i,(e,t)=>[e,t]));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=$e().x(e=>e.x).y(e=>e.y).addAll(s),this.revision=t,this.tree)}};function Xe(e){return{...e,...e.viewTransform&&{viewTransform:{...e.viewTransform}},...e.colliders&&{colliders:Ee(e.colliders)},...e.kernel&&{kernel:{...e.kernel,...e.kernel.gravity&&{gravity:{...e.kernel.gravity}}}}}}var je=["data","scene-geometry","data-paint","accessibility","evidence"],Le=["scene-geometry","data-paint","accessibility","evidence"],_e=["overlay","accessibility","evidence"],Ke=(e,t)=>({retainedData:e,invalidations:t}),Ve=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],Ue=["scene-geometry","data-paint","accessibility","evidence"],He=[],Ge={engine:Ke("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:Ke("preserve",Ue),colliders:Ke("preserve",Ue),sediment:Ke("preserve",Ue),bodyBudget:Ke("preserve",Ve),bodyLimit:Ke("preserve",Ve),eviction:Ke("preserve",Ve),fixedDt:Ke("preserve",He),maxDeltaSeconds:Ke("preserve",He),maxSubsteps:Ke("preserve",He),settleStepLimit:Ke("preserve",He),timeScale:Ke("preserve",He),observation:Ke("preserve",He)},Qe=Ke("preserve",Ve);function Je(e){let t="preserve";const i=new Set;for(const s of e){const e=Object.prototype.hasOwnProperty.call(Ge,s)?Ge[s]:Qe;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)i.add(t)}return{retainedData:t,invalidations:i}}var Ze=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function et(e,t){return e===t||!(!e||!t)&&(e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&Ze.every(i=>e[i]===t[i]))}function tt(e,t){if(e.readBody){if(!t)return t=>e.readBody(t);const i=new Map;for(const s of t)i.has(s)||i.set(s,e.readBody(s));return e=>i.get(e)}const i=new Map(e.readState().map(e=>[e.id,e]));return e=>i.get(e)}function it(e,t){for(const i of e)t.has(Re(i).bodyId)&&e.delete(i)}function st(e,t,i,s){return e||!t?"paused":i||!s?"running":"settled"}var nt=class{constructor(){this.heap=[]}get length(){return this.heap.length}firstArrival(){return this.heap[0]?.spawnAt}lastArrival(){return this.latest}push(e){this.latest=Math.max(this.latest??-1/0,e.spawnAt);let t=this.heap.length;for(this.heap.push(e);t>0;){const i=t-1>>>1;if(Be(this.heap[i],e)<=0)break;this.heap[t]=this.heap[i],t=i}this.heap[t]=e}shift(){const e=this.heap[0],t=this.heap.pop();if(0===this.heap.length)return this.latest=void 0,e;if(!t)return e;let i=0;for(;2*i+1<this.heap.length;){let e=2*i+1;if(e+1<this.heap.length&&Be(this.heap[e+1],this.heap[e])<0&&(e+=1),Be(t,this.heap[e])<=0)break;this.heap[i]=this.heap[e],i=e}return this.heap[i]=t,e}clear(){this.heap=[],this.latest=void 0}remove(e){const t=new Set,i=this.heap.filter(i=>!e.has(i.id)||(t.add(i.id),!1));return t.size&&this.restore(i),t}sorted(){return this.heap.slice().sort(Be)}restore(e){this.clear();for(const t of e)this.push(t)}};var rt={};function ot(e){const t=rt[e];if(!t)throw new Error(`Physics ${e} configuration requires registerPhysicsLivePrograms() from semiotic/physics before a PhysicsPipelineStore is created or restored with it.`);return t}var at=class e{configure(e,t){!1===e.emitters?this.emitters=void 0:e.emitters&&(this.emitters?this.emitters.update(e.emitters):this.emitters=ot("emitters").create(e.emitters)),!1===e.eventDrop?this.eventDrop=void 0:e.eventDrop&&(this.eventDrop?this.eventDrop.update(e.eventDrop,t):this.eventDrop=ot("eventDrop").create(e.eventDrop),t.setColliders(this.eventDrop.colliders()))}backlog(){return Boolean(this.eventDrop?.backlog())}ownsClock(){return Boolean(this.eventDrop||this.emitters?.pending())}pending(){return this.backlog()||Boolean(this.emitters?.pending()||this.eventDrop?.continuous())}snapshot(){return{...this.emitters&&{emitters:this.emitters.snapshot()},...this.eventDrop&&{eventDrop:this.eventDrop.snapshot()}}}static restore(t){const i=new e;return t.emitters&&(i.emitters=ot("emitters").restore(t.emitters)),t.eventDrop&&(i.eventDrop=ot("eventDrop").restore(t.eventDrop)),i}};function dt(e,t,i,s,n,r){const o={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===i)return o;const a=Math.max(0,Math.floor(s));if(!Number.isFinite(a))return o;const d=n.size-a;if(d<=0)return o;const h=function(e,t,i){if("sleeping-first"!==t)return Array.from(i);const s=new Map(e.readState().map(e=>[e.id,e.sleeping])),n=[],r=[];for(const e of i)s.get(e)?n.push(e):r.push(e);return[...n,...r]}(e,i,n),l=h.slice(0,d);if(0===l.length)return o;const c=function(e,t,i,s){if(!t.isEnabled())return[];const n=tt(e,i),r=[];for(const e of i){const i=n(e);if(!i)continue;const o=t.add(i);o&&(r.push(e),s.emit({type:"physics-sediment",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:e,datum:i.datum,x:i.x,y:i.y,binId:o.id,count:o.count,total:o.total}))}return r}(e,t,l,r);e.remove(l);const u=new Set(l);return{evicted:l,sedimented:c,liveBodyOrder:new Set(Array.from(n).filter(e=>!u.has(e)))}}var ht=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,i){if(i>0)return void(this.seconds=0);if(e.allSleeping())return void(this.seconds+=Math.max(0,t));const s=e.readState(this.scratch),n=this.speed*this.speed;let r=!0;for(const e of s){if(e.travel){r=!1;break}if(e.sleeping)continue;const i=e.x-e.prevX,s=e.y-e.prevY;if(e.vx*e.vx+e.vy*e.vy>=n||t>0&&i*i+s*s>=n*t*t){r=!1;break}}this.seconds=r?this.seconds+Math.max(0,t):0}};function lt(e,t,i,s={}){let n,r=0,o=0;const a=t+(s.drainArrivals?Math.max(0,Math.ceil(((e.lastArrival()??e.elapsed())-e.elapsed())/e.fixedDt)):0);for(;r+o<a&&!s.shouldStop?.()&&(!1===s.stopAtRest||e.queueSize()>0||!e.atRest()||s.continueWhile?.());){const t=e.nextArrival(),d=s.skipIdle&&null!=t&&e.atRest()?Math.min(Math.max(0,Math.floor((t-e.elapsed())/e.fixedDt)-1),Math.max(0,a-r-o-1)):0;d>0&&(e.advanceTime(d*e.fixedDt),o+=d),e.step(e.fixedDt),e.advanceTime(e.fixedDt);const h=e.drainEvents();i.events&&(i.events.push(...h),e.observeKernelEvents(h,i.observations),e.observeSensorTransitions(i.observations));const l=[];if(e.spawnDue(l,i.observations),l.length>0){i.spawned.push(...l),n=e.observeBodyBudget(i.observations);const t=e.evictOverflow(i.observations);i.evicted?.push(...t.evicted),i.sedimented?.push(...t.sedimented)}r+=1,e.refreshQuiescence(e.fixedDt,l.length),s.afterStep?.()}return{steps:r,budget:n}}var ct=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new Ye,this.elapsedSeconds=0,this.liveBodyOrder=new Set,this.nextSequence=0,this.paused=!1,this.queue=new nt,this.revision=0,this.observedInitialBoundary=!1,this.updateResults=new We,this.simulationState="settled",this.visible=!0,this.quiescence=new ht,this.programs=new at,v(e);const{bodyBudget:t,colliders:i,engine:s,kernel:n,observation:r,sediment:o,emitters:a,eventDrop:d,...h}=e;this.config={...xe,...h,viewTransform:{...h.viewTransform??xe.viewTransform}},this.configInput=Xe(e),this.bodyBudget=t??{},this.engineInput=s,this.observation=Me(r),this.sediment=new ye(o??!1),this.world=ae(s,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),i&&this.world.setColliders(Ee(i)),this.programs.configure({emitters:a,eventDrop:d},this.world)}updateConfig(e){v(e);const t=function(e,t){return Object.keys(e).filter(i=>"viewTransform"===i?e.viewTransform?.x!==t.viewTransform?.x||e.viewTransform?.y!==t.viewTransform?.y:"colliders"===i?!g(e.colliders,t.colliders):"kernel"===i?!et(e.kernel,t.kernel):e[i]!==t[i])}(e,this.configInput),{colliders:i,bodyBudget:s,engine:n,kernel:r,observation:o,sediment:a,emitters:d,eventDrop:h,...l}=e;if(this.programs.configure({emitters:d,eventDrop:h},this.world),this.config={...this.config,...l,viewTransform:{...l.viewTransform??this.config.viewTransform}},t.includes("eventDrop")&&(this.revision+=1),void 0!==s&&(this.bodyBudget=s,!1===s&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=ae(n,e.options),this.world.restore(e),this.revision+=1}if(r&&!et(r,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...r,gravity:{...e.options.gravity,...r.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}o&&(this.observation=Me(o,this.observation)),this.sediment.updateConfig(a),i&&t.includes("colliders")&&(this.world.setColliders(Ee(i)),this.revision+=1),this.configInput=Xe({...this.configInput,...e});const c=Je(t);this.updateResults.record({kind:"config",keys:t},c.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(Ee(e)),this.configInput={...this.configInput,colliders:Ee(e)},this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},Je(["colliders"]).invalidations)}enqueue(e,t){const i=function(e,t,i,s,n){const r=Array.isArray(t)?t:[t];for(const e of r)u(e);const o=i?Pe(r,{...i,startAt:i.startAt??s}):r;if(i)for(const e of o)u(e);for(const t of o)e.push({...Ie(t),sequence:n++,spawnAt:t.spawnAt??s});return o.length}(this.queue,e,t,this.elapsedSeconds,this.nextSequence);this.nextSequence+=i,i>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i},i?je:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(Ie(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},je)}materializeDueSpawns(){const e=this.revision,t=[],i=[];return this.spawnDue(t,i),0===t.length||(this.observeBodyBudget(i),this.evictOverflow(i),this.syncSimulationState(i),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?je:[])),t}clear(){this.observedInitialBoundary=!1;const{options:e,colliders:t}=this.world.snapshot();this.world.init({...e,fixedDt:this.config.fixedDt}),this.world.setColliders(t),this.activeSensorPairs.clear(),this.liveBodyOrder.clear(),this.queue.clear(),this.accumulator=0,this.elapsedSeconds=0,this.programs=new at,this.programs.configure(this.configInput,this.world),this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},je)}tick(e,t){const i=this.revision,s=[],n=[],r=[],o=[],a=[];if(this.paused||!this.visible){const e=this.result(0,s,n,r,o,a,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const d=Math.max(0,Math.min(Number.isFinite(e)?e:0,this.config.maxDeltaSeconds))*this.config.timeScale;this.spawnDue(s,a);const h=this.observeBodyBudget(a),l=this.evictOverflow(a);n.push(...l.evicted),r.push(...l.sedimented),this.syncSimulationState(a),s.length>0&&this.quiescence.reset(),this.accumulator+=d;const c=this.stepObserver(t,{spawned:s,evicted:n,sedimented:r,events:o,observations:a}),u=d>0?Math.floor((this.accumulator+1e-9*this.config.fixedDt)/this.config.fixedDt):0,{steps:p,budget:m}=lt(this.settleHost(),Math.min(u,this.config.maxSubsteps),{spawned:s,evicted:n,sedimented:r,events:o,observations:a},{stopAtRest:!1,shouldStop:()=>this.paused||!this.visible,afterStep:c});this.accumulator=Math.max(0,this.accumulator-p*this.config.fixedDt),p===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),(p>0||s.length>0||n.length>0||r.length>0||o.length>0)&&(this.revision+=1);const f=this.result(p,s,n,r,o,a,void 0,m??h);return this.updateResults.record({kind:"tick",count:p},this.revision!==i?s.length||n.length||r.length?je:Le:[]),f}settle(e){return this.runSettle(e,!1).steps}settleWithObservations(e,t){return this.runSettle(e,!0,t)}stepObserver(e,t){const i=!this.observedInitialBoundary;return e&&(this.observedInitialBoundary=!0),function(e,t,i=!1){if(!e)return;const s=["spawned","evicted","sedimented","events","observations"],n={spawned:0,evicted:0,sedimented:0,events:0,observations:0},r=r=>{const o=t(r),a={...o};s.forEach(e=>{a[e]=o[e].slice(n[e]),n[e]=o[e].length}),0===r&&!i&&s.every(e=>0===a[e].length)||e.onStep(a)};return r(0),()=>r(1)}(e,e=>(e&&(this.revision+=1),this.result(e,t.spawned,t.evicted,t.sedimented,t.events,t.observations)),i)}settleHost(e=!1){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length+Number(e?this.programs.backlog():this.programs.ownsClock()),atRest:()=>this.atRest(),elapsed:()=>this.elapsedSeconds,nextArrival:()=>this.queue.firstArrival(),lastArrival:()=>function(e,t,i){let s=e;for(const i of t)i.travel&&(s=Math.max(s,e+i.travel.durationSeconds-(i.travel.elapsedSeconds??0)));for(const e of i)s=Math.max(s,e.spawnAt+(e.travel?e.travel.durationSeconds-(e.travel.elapsedSeconds??0):0));return s}(this.elapsedSeconds,this.readBodies(),this.queue.sorted()),advanceTime:t=>{this.elapsedSeconds+=t;const i=this.programs.emitters?.advance(t,e);i?.length&&this.enqueue(i)},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)=>function(e,t,i){const s=t.filter(e=>"sleep"===e.type);if(0===s.length)return;const n=tt(e,s.map(e=>e.bodyId));for(const e of s){const t=n(e.bodyId);i.emit({type:"physics-settle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t)),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t,i){const s=this.revision,n=[],r=[],o=[],a=[],d=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,n,r,o,a,d??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,d);const h=this.observeBodyBudget(d),l=this.evictOverflow(d);r.push(...l.evicted),o.push(...l.sedimented),this.syncSimulationState(d),n.length>0&&this.quiescence.reset();const c=t?{spawned:n,evicted:r,sedimented:o,events:a,observations:d}:{spawned:n},u=this.stepObserver(i,{spawned:n,evicted:r,sedimented:o,events:a,observations:d??[]}),{steps:p,budget:m}=lt(this.settleHost(void 0===e),e??this.config.settleStepLimit,c,{afterStep:u,continueWhile:i?.continueWhile,shouldStop:t?()=>this.paused||!this.visible:void 0,drainArrivals:void 0===e,skipIdle:void 0===e&&!i&&!this.programs.pending()}),f=n.length+r.length+o.length>0;(p>0||f||a.length>0)&&(this.revision+=1);const v=this.result(p,n,r,o,a,d??[],void 0,m??h);return this.updateResults.record({kind:"settle",count:p},this.revision===s?[]:f?je:Le),v}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:i=0,binWidth:s=24,gap:n=2,maxHeight:r=80,value:o="count",x:a}=t,d=e.reduce((e,t)=>Math.max(e,t[o]),1);return e.map((e,t)=>{const h=Math.max(0,e[o]/d*r),l=a?.(e,t)??t*(s+n);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:l,y:i-h,width:s,height:h,meanX:e.x.mean,meanY:e.y.mean}})}(this.readSediment(),e)}hitTest(e,t,i=0,s){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,i,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()||this.programs.pending()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.size}elapsed(){return this.elapsedSeconds}recordObservation(e){const t=be(e,this.elapsedSeconds,this.observation);return this.emitObservation(t),this.updateResults.record({kind:"update",count:1},["evidence"]),t}recordLifecycleObservation(e){return this.updateResults.record({kind:"update",count:1},["evidence"]),be(e,this.elapsedSeconds,this.observation)}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?_e:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?_e:[])}remove(e){const t=new Set(e),i=new Set(this.liveBodyOrder),s=this.queue.remove(t);for(const t of e)this.liveBodyOrder.delete(t);this.world.remove(e),it(this.activeSensorPairs,t);const n=e.filter(e=>i.has(e)||s.has(e));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?je:[]),n}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},Le),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},Le)}applyImpulse(e,t,i){this.world.applyImpulse(e,t,i),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},Le)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,i,s)=>e.applyImpulse(t,i,s),clear:()=>e.clear(),hitTest:(t,i,s)=>e.hitTest(t,i,s),pause:()=>e.setPaused(!0),push:(t,i)=>e.enqueue(t,i),pushMany:(t,i)=>e.enqueue(t,i),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}runtimeState(){return{elapsedSeconds:this.elapsedSeconds,timeScale:this.config.timeScale,fixedDt:this.config.fixedDt,paused:this.paused,visible:this.visible,simulationState:this.simulationState}}eventDropState(){return this.programs.eventDrop?{metadata:this.programs.eventDrop.metadata(),viewTransform:this.programs.eventDrop.viewTransform(),lifecycleEvents:[]}:void 0}viewTransform(){return this.programs.eventDrop?.viewTransform()??{...this.config.viewTransform}}isEventDropLive(){return Boolean(this.programs.eventDrop)}enqueueSequence(){return this.nextSequence}workerLiveDelta(){return this.programs.eventDrop?.drainWorkerDelta()}workerStructure(){return{world:this.world.snapshot(),queue:this.queue.sorted().map(qe),liveBodyOrder:Array.from(this.liveBodyOrder),sediment:this.readSediment()}}workerState(){return{...this.programs.emitters&&{emitterProgress:this.programs.emitters.progress()},nextSequence:this.nextSequence,accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs),elapsedSeconds:this.elapsedSeconds,paused:this.paused,revision:this.revision,simulationState:this.simulationState,visible:this.visible}}workerSleepTimes(e){return this.world.workerSleepTimes?.(e)}applyWorkerFrame(e){if(e.snapshot){const t=this.configInput;return this.restore(e.snapshot),void(this.configInput=t)}if(!e.state||!this.world.applyWorkerMotion)throw new Error("Physics worker motion frame requires a built-in mirror");e.structure?(this.world.restore(e.structure.world),this.queue.restore(e.structure.queue.map(qe)),this.liveBodyOrder=new Set(e.structure.liveBodyOrder),this.sediment.restore(e.structure.sediment),this.bodySpatialIndex=new Ye):e.state.revision===this.revision&&e.state.elapsedSeconds===this.elapsedSeconds||this.world.applyWorkerMotion(e),e.live&&this.programs.eventDrop?.applyWorkerDelta(e.live,this.world);const t=this.simulationState,{emitterProgress:i,...s}=e.state;i&&this.programs.emitters?.restoreProgress(i),Object.assign(this,s,{activeSensorPairs:new Set(e.state.activeSensorPairs)}),this.updateResults.record({kind:"tick"},Le),t!==this.simulationState&&this.observation.onSimulationStateChange?.(this.simulationState,t)}snapshot(){const e=this.world.snapshot();return{...this.workerState(),nextSequence:this.nextSequence,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:Ae(this.bodyBudget),config:{...this.config,viewTransform:{...this.config.viewTransform},kernel:De(e.options)},queue:this.queue.sorted().map(qe),sediment:this.readSediment(),liveBodyOrder:Array.from(this.liveBodyOrder),world:e,...this.programs.snapshot()}}restore(e){!function(e){if(h(e.activeSensorPairs,"Physics activeSensorPairs"),h(e.liveBodyOrder,"Physics liveBodyOrder"),d(e.queue,"Physics queue"),null!=e.sediment){d(e.sediment,"Physics sediment");for(const t of e.sediment){if(!t)throw new RangeError("Physics sediment requires bin records");h(t.bodyIds,"Physics sediment.bodyIds"),o(t.count,"Physics sediment.count");for(const e of["x","y","value"]){const i=t[e];if(!i)throw new RangeError("Physics sediment requires statistics");for(const t of["count","total","mean","min","max","variance"])o(i[t],`Physics sediment.${e}.${t}`)}}}v(e.config),f(e.world);for(const t of e.queue)u(t),o(t.sequence,"Physics queue sequence");if(o(e.elapsedSeconds,"Physics elapsedSeconds"),o(e.accumulator,"Physics accumulator"),null!=e.nextSequence&&(!Number.isSafeInteger(e.nextSequence)||e.nextSequence<0||e.queue.some(t=>t.sequence>=e.nextSequence)))throw new RangeError("Physics nextSequence must exceed queued sequence numbers")}(e);const t=at.restore(e);this.bodySpatialIndex=new Ye,this.programs=t,this.observedInitialBoundary=!1;const i=this.simulationState;Object.assign(this,function(e){const t={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,viewTransform:{...e.config.viewTransform??{x:0,y:0}}};return{config:t,configInput:Xe({...t,bodyBudget:Ae(e.bodyBudget??{}),kernel:De(e.world.options),...e.emitters&&{emitters:e.emitters.options},...e.eventDrop&&{eventDrop:e.eventDrop.config}}),bodyBudget:Ae(e.bodyBudget??{}),activeSensorPairs:new Set(e.activeSensorPairs),accumulator:e.accumulator,elapsedSeconds:e.elapsedSeconds,paused:e.paused,revision:e.revision,visible:e.visible,liveBodyOrder:new Set(e.liveBodyOrder),nextSequence:e.nextSequence??e.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,simulationState:e.simulationState??st(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping))}}(e)),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.queue.restore(e.queue.map(qe)),this.sediment.restore(e.sediment??[]),this.world.restore(e.world),this.updateResults.record({kind:"restore"},je),this.simulationState!==i&&this.observation.onSimulationStateChange?.(this.simulationState,i)}spawnDue(e,t){for(;this.queue.length>0&&this.queue.firstArrival()<=this.elapsedSeconds+1e-9*this.config.fixedDt;){const i=this.queue.shift();if(!i)return;this.spawnOne(i,t),e.push(i.id)}if(this.programs.eventDrop){const e=this.programs.eventDrop.advance(this.world,this.elapsedSeconds);e.length&&this.remove(e);for(const e of this.programs.eventDrop.ledger.drainEvents())this.emitObservation(be(e,this.elapsedSeconds,this.observation),t)}}spawnOne(e,t){this.programs.eventDrop&&(e=this.programs.eventDrop.prepare(e,this.elapsedSeconds)),u(e),this.liveBodyOrder.delete(e.id)&&it(this.activeSensorPairs,new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.add(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});(t||this.observation.onObservation)&&function(e,t,i){const s=tt(e)(t.id);i.emit({type:"physics-spawn",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:t.id,datum:s?.datum??t.datum,x:s?.x??t.x,y:s?.y??t.y})}(this.world,e,this.observationContext(t))}result(e,t,i,s,n,r,o,a=this.evaluateBodyBudget()){this.syncSimulationState(r);const d=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:i,events:n,observations:r,queueSize:this.queue.length,revision:this.revision,shouldContinue:o??(!this.paused&&this.visible&&this.hasPendingWork()),sleeping:d,sedimented:s,spawned:t,steps:e}}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,i){const s=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));let n=s.size!==t.size;if(!n)for(const e of s)if(!t.has(e)){n=!0;break}if(!n)return s;const r=Array.from(s).filter(e=>!t.has(e)).sort(),o=Array.from(t).filter(e=>!s.has(e)).sort(),a=tt(e,[...r,...o].map(e=>Re(e).bodyId)),d=(e,t)=>{const{sensorId:s,bodyId:n}=Re(t),r=i.observation.sensors[s],o=a(n);i.emit({type:"enter"===e?r?.enterType??"physics-bin-enter":r?.exitType??"physics-bin-exit",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:n,datum:o?.datum,x:o?.x,y:o?.y,sensorId:s,binId:r?.binId??s})};for(const e of r)d("enter",e);for(const e of o)d("exit",e);return s}(this.world,this.activeSensorPairs,this.observationContext(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 we({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.size,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();return this.bodyBudgetObservationKey=function(e,t,i,s){if(!t||"ok"===e.state)return"ok";const n=`${e.state}:${e.action}`;return n!==i&&function(e,t){t.emit({type:"overflow"===e.state?"physics-budget-overflow":"physics-budget-warning",timestamp:t.elapsedSeconds,chartType:t.observation.chartType,chartId:t.observation.chartId,budgetAction:e.action,bodyLimit:e.bodyLimit,engineMaxBodiesHint:e.engineMaxBodiesHint,liveBodies:e.liveBodies,overflow:e.overflow,projectedBodies:e.projectedBodies,queuedBodies:e.queuedBodies,warnAt:e.warnAt})}(e,s),n}(t,!1!==this.bodyBudget,this.bodyBudgetObservationKey,this.observationContext(e)),t}syncSimulationState(e){const t=st(this.paused,this.visible,this.queue.length>0||this.programs.pending(),this.atRest());if(t===this.simulationState)return;const i=this.simulationState;this.simulationState=t,function(e,t,i){i.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||i.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,simulationState:t,previousSimulationState:e})}(i,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:i,liveBodyOrder:s}=dt(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=s,it(this.activeSensorPairs,new Set(t))),{evicted:t,sedimented:i}}};var ut=[{weight:.25,min:0,max:0},{weight:.35,min:0,max:2e3},{weight:.2,min:2e3,max:5e3},{weight:.1,min:5e3,max:1e4},{weight:.1,min:1e4,max:15e3}];function pt(e,t){if(!Number.isFinite(e)||e<=0)throw new RangeError(`${t} must be finite and positive`);return e}function mt(e){const{jitter:t}=e.spec;if(!t||"none"===t)return 0;if("function"==typeof t){const i=t(e.random);if(!Number.isFinite(i)||i<0)throw new RangeError("jitter must return a finite nonnegative delay");return i}const i="watermarks"===t?ut:t.buckets;let s=e.random()*i.reduce((e,t)=>e+t.weight,0);for(const t of i)if(s-=t.weight,s<0)return t.min+e.random()*(t.max-t.min);return i[i.length-1].max}function ft(e,t){e.remainingError=0;const i={id:`${e.spec.id}-${e.sequence++}`,source:e.spec.id,eventTime:t-mt(e),arrivalTime:t},s=e.spec.burst;return s?(0===e.burstRemaining&&(e.burstRemaining=s.min+Math.floor(e.random()*(s.max-s.min+1))),e.burstRemaining--,e.remaining=e.burstRemaining>0?s.intraMs:s.gapMs?s.gapMs[0]+e.random()*(s.gapMs[1]-s.gapMs[0]):e.interval):e.remaining=e.interval,i}function vt(e,t){const i=-t-e.remainingError,s=e.remaining+i;e.remainingError=s-e.remaining-i,e.remaining=s}function yt(e,t=1,i={}){const s=function(e,t){const i=new Set;return e.map((e,s)=>{if(!e.id||i.has(e.id))throw new Error("Synthetic source ids must be nonempty and unique");i.add(e.id);const n=pt(e.interval??1e3/pt(e.ratePerSec??1,"ratePerSec"),"interval"),r=e.burst;if(r){if(!Number.isInteger(r.min)||!Number.isInteger(r.max)||r.min<1||r.max<r.min)throw new RangeError("burst bounds must be ordered positive integers");if(pt(r.intraMs,"intraMs"),r.gapMs&&(pt(r.gapMs[0],"gapMs"),pt(r.gapMs[1],"gapMs"),r.gapMs[1]<r.gapMs[0]))throw new RangeError("gapMs must be ordered")}const o=e.jitter;if("object"==typeof o&&(!o.buckets.length||!o.buckets.some(e=>e.weight>0)||o.buckets.some(e=>!Number.isFinite(e.weight)||e.weight<0||!Number.isFinite(e.min)||e.min<0||!Number.isFinite(e.max)||e.max<e.min)))throw new RangeError("jitter buckets require nonnegative finite weights and ordered delays");return{spec:e,random:b(t+2654435769*s),interval:n,remaining:n,remainingError:0,burstRemaining:0,sequence:0}})}(e,t);for(const[e,t]of Object.entries(i))if(void 0!==t&&(!Number.isFinite(t)||t<0))throw new RangeError(`${e} must be finite and nonnegative`);if(void 0!==i.maxEvents&&!Number.isSafeInteger(i.maxEvents))throw new RangeError("maxEvents must be a safe integer");const n=i.durationMs??1/0,r=i.maxEvents??1/0;let o=0,a=0,d=0;const h=()=>0===s.length||a>=n||o>=r;return{getTime:()=>a,getEmittedCount:()=>o,isComplete:h,snapshot:()=>({version:1,time:a,timeError:d,emitted:o,sources:s.map(e=>({id:e.spec.id,randomState:e.random.getState(),remaining:e.remaining,remainingError:e.remainingError,burstRemaining:e.burstRemaining,sequence:e.sequence}))}),restore(e){if(1!==e.version||!Number.isFinite(e.time)||e.time<0||e.time>n||!Number.isFinite(e.timeError)||!Number.isSafeInteger(e.emitted)||e.emitted<0||e.emitted>r||e.sources.length!==s.length||e.sources.some((e,t)=>e.id!==s[t].spec.id||!Number.isInteger(e.randomState)||e.randomState<0||e.randomState>4294967295||!Number.isFinite(e.remaining)||e.remaining<0||!Number.isFinite(e.remainingError)||!Number.isSafeInteger(e.sequence)||e.sequence<0||!Number.isSafeInteger(e.burstRemaining)||e.burstRemaining<0||e.burstRemaining>=(s[t].spec.burst?.max??1))||e.sources.reduce((e,t)=>e+t.sequence,0)!==e.emitted)throw new RangeError("Invalid or incompatible synthetic emitter snapshot");a=e.time,d=e.timeError,o=e.emitted,e.sources.forEach((e,t)=>{const{id:i,randomState:n,...r}=e;Object.assign(s[t],r,{random:b(n)})})},advance(e,t={}){if(!Number.isFinite(e)||e<0)throw new RangeError("deltaMs must be finite and nonnegative");const i=pt(t.rate??1,"rate");if(t.paused||0===e||h())return[];e=Math.min(e,n-a);const l=[],c=s.filter(e=>!1!==t.active?.[e.spec.id]);let u=0,p=0,m=e;for(;m>0;){const t=c.reduce((e,t)=>!e||t.remaining<e.remaining?t:e,void 0),s=t?t.remaining/i:1/0,n=16*Number.EPSILON*Math.max(e,s);if(!t||s-m>n){for(const e of c)vt(e,m*i);break}const d=Math.min(m,Math.max(0,s));for(const e of c)vt(e,d*i);const h=d-p,f=u+h;p=f-u-h,u=f,m=Math.max(0,e-u);const v=a+Math.min(e,u);for(const e of c)if((e===t||e.remaining/i<=n)&&(l.push(ft(e,v)),o++,o>=r))break;if(o>=r){e=u;break}}const f=e-d,v=a+f;return d=v-a-f,a=v,l}}}var gt=class e{constructor(e){this.options=e,this.validate(e),this.emitter=yt(e.sources,e.seed,{durationMs:e.durationMs,maxEvents:e.maxEvents})}validate(e){if(null!=e.originTime&&!Number.isFinite(e.originTime))throw new RangeError("Emitter originTime must be finite");if(null!=e.rate&&(!Number.isFinite(e.rate)||e.rate<=0))throw new RangeError("Emitter rate must be finite and positive");for(const t of e.sources){const i=e.templates[t.id];if(!i)throw new RangeError(`Missing emitter template: ${t.id}`);u({...i,id:t.id})}}update(e){const t=e=>e.map(e=>e.id).join("\0");if(t(e.sources)!==t(this.options.sources))throw new RangeError("Changing emitter sources requires a new run (remount with a new key)");const i={...e,sources:this.options.sources,seed:this.options.seed,durationMs:this.options.durationMs,maxEvents:this.options.maxEvents};this.validate(i),this.options=i}pending(){return!this.options.paused&&!this.emitter.isComplete()&&this.options.sources.some(e=>!1!==this.options.active?.[e.id])}advance(e,t=!1){const i="s"===this.options.timeUnit?.001:1,s=this.options.originTime??0,n=t?{...this.options,paused:!0}:this.options;return this.emitter.advance(1e3*e,n).map(e=>{const t=this.options.templates[e.source];return{...t,id:e.id,datum:{...t.datum,...e,time:s+e.eventTime*i,eventTime:s+e.eventTime*i,arrivalTime:s+e.arrivalTime*i}}})}snapshot(){return{options:{...this.options,active:{...this.options.active},sources:this.options.sources.map(e=>({...e,...e.burst&&{burst:{...e.burst,...e.burst.gapMs&&{gapMs:[...e.burst.gapMs]}}},..."object"==typeof e.jitter&&{jitter:{...e.jitter,buckets:e.jitter.buckets.map(e=>({...e}))}}})),templates:Object.fromEntries(Object.entries(this.options.templates).map(([e,t])=>[e,Ie({...t,id:e})]))},progress:this.progress()}}progress(){return this.emitter.snapshot()}restoreProgress(e){this.emitter.restore(e)}static restore(t){const i=new e(t.options);return i.emitter.restore(t.progress),i}};function wt(e){return{...e,bySource:Object.fromEntries(Object.entries(e.bySource).map(([e,t])=>[e,{...t}]))}}var xt=class{constructor(e,t={},i=[]){if(this.windowSize=e,this.policy=t,this.windows=new Map,this.openWindows=new Set,this.sources=new Map,this.latest=-1/0,this.frontier=-1/0,this.value=-1/0,this.pending=[],!Number.isFinite(e)||e<=0)throw new RangeError("EventDrop windows.size must be a finite positive number");for(const e of i)this.sources.set(e,{latest:-1/0,arrival:-1/0,idle:!1});this.validatePolicy(t)}validatePolicy(e){if("function"!=typeof e){for(const t of["delay","idleTimeout","allowedLateness"]){const i=e[t];if(null!=i&&(!Number.isFinite(i)||i<0))throw new RangeError(`watermark.${t} must be finite and nonnegative`)}if(null!=e.value&&!Number.isFinite(e.value))throw new RangeError("watermark.value must be finite")}}setWatermark(e){this.validatePolicy(e),this.policy=e}getWatermark(){return this.value}getLatestEventTime(){return this.latest}getArrivalFrontier(){return this.frontier}getLedger(){return Array.from(this.windows.values(),wt).sort((e,t)=>e.start-t.start)}drainEvents(){const e=this.pending;return this.pending=[],e}snapshot(){return this.state(this.getLedger())}drainDelta(){const e=Array.from(this.changedWindows??[],e=>wt(this.windows.get(e)));return this.changedWindows=new Set,this.state(e)}state(e){return{windows:e,sources:Array.from(this.sources,([e,t])=>[e,{...t}]),latest:this.latest,frontier:this.frontier,value:this.value,heldBy:this.heldBy}}restore(e){this.applySnapshot(e,!0)}applyDelta(e){this.applySnapshot(e,!1)}applySnapshot(e,t){const i=e=>Number.isFinite(e)||e===-1/0,s=e=>Number.isSafeInteger(e)&&e>=0;if(![e.latest,e.frontier,e.value].every(i)||new Set(e.windows.map(e=>e.windowId)).size!==e.windows.length||new Set(e.sources.map(([e])=>e)).size!==e.sources.length||e.sources.some(([,e])=>!i(e.latest)||!i(e.arrival))||e.windows.some(e=>!Number.isFinite(e.start)||!Number.isFinite(e.end)||e.end<=e.start||!s(e.accepted)||!s(e.late)||Object.values(e.bySource).some(e=>!s(e.accepted)||!s(e.late))||Object.values(e.bySource).reduce((e,t)=>e+t.accepted,0)!==e.accepted||Object.values(e.bySource).reduce((e,t)=>e+t.late,0)!==e.late))throw new RangeError("Invalid EventDrop ledger snapshot");t&&(this.windows.clear(),this.openWindows.clear());for(const t of e.windows){const e=this.windows.get(t.windowId);e&&this.openWindows.delete(e);const i=wt(t);Object.setPrototypeOf(i.bySource,null),this.windows.set(t.windowId,i),i.open&&this.openWindows.add(i)}this.changedWindows?.clear(),this.sources=new Map(e.sources.map(([e,t])=>[e,{...t}])),this.latest=e.latest,this.frontier=e.frontier,this.value=e.value,this.heldBy=e.heldBy,this.pending=[]}advance(e,t="external"){if(!Number.isFinite(e))return;this.frontier=Math.max(this.frontier,e);const i=this.policy;let s;if("function"==typeof i)s=i(this.latest);else if(i.external)s=i.external();else if(null!=i.value)s=i.value;else{let t=this.latest;if(i.perSource){let s;t=1/0;for(const[n,r]of this.sources){Number.isFinite(r.arrival)||(r.arrival=e);const o=null!=i.idleTimeout&&e-r.arrival>=i.idleTimeout;o&&!r.idle&&this.pending.push({type:"physics-source-idle",sourceId:n}),r.idle=o,!o&&r.latest<t&&(t=r.latest,s=n)}s&&s!==this.heldBy&&t<this.latest&&this.pending.push({type:"physics-watermark-held",sourceId:s}),this.heldBy=s,t===1/0&&(t=this.latest)}s=t-(i.delay??this.windowSize)}if(!Number.isFinite(s)||s<=this.value)return;const n=this.value;this.value=s,this.pending.push({type:"physics-watermark-advance",from:n,to:s,cause:t});for(const t of this.openWindows)t.end<=this.value&&this.close(t,e)}close(e,t){this.changedWindows?.add(e.windowId),e.open=!1,e.closedAt=t,e.watermarkAtClose=this.value,this.openWindows.delete(e),this.pending.push({type:"physics-window-close",...wt(e),watermark:this.value})}append(e){var t;const{eventTime:i,arrivalTime:s,source:n=""}=e;if(!Number.isFinite(i)||!Number.isFinite(s))throw new RangeError("Event and arrival times must be finite");if(s<this.frontier)throw new RangeError("Incremental admissions require nondecreasing arrival times");this.latest=Math.max(this.latest,i);const r=this.sources.get(n);this.sources.set(n,{latest:Math.max(r?.latest??-1/0,i),arrival:s,idle:!1}),this.advance(s,"arrival");const o=Math.floor(i/this.windowSize)*this.windowSize,a=o+this.windowSize,d=`${o}-${a}`;let h=this.windows.get(d);h||(h={windowId:d,start:o,end:a,accepted:0,late:0,bySource:Object.create(null),open:!0},this.windows.set(d,h),this.openWindows.add(h),this.pending.push({type:"physics-window-open",windowId:d,start:o,end:a}));const l=e.watermarkAtArrival??this.value,c=a+("function"==typeof this.policy?0:this.policy.allowedLateness??0)<=l,u=(t=h.bySource)[n]??(t[n]={accepted:0,late:0}),p=c?"late":"accepted";return h[p]++,this.changedWindows?.add(d),u[p]++,h.open||c||this.pending.push({type:"physics-window-update",windowId:d,accepted:h.accepted,late:h.late,bySource:wt(h).bySource,watermark:this.value,retractions:1}),h.open&&a<=this.value&&this.close(h,s),{windowId:d,start:o,end:a,late:c,watermarkAtArrival:l}}};import{scaleLinear as bt}from"d3-scale";function St(e,t,i,s){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:i},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...s}}}function Mt(e,t,i){return"function"==typeof i?i(e,t):e[i]}function It(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:null}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function Tt(e){const{windowSize:t,watermark:i,watermarkAtArrivalAccessor:s}=e;if(!(Number.isFinite(t)&&t>0))throw new RangeError("EventDrop windows.size must be a finite positive number");const{rows:n}=function(e,t,i=0){const s=new Set(e.filter(e=>null!=e.id).map(e=>String(e.id))),n=new Map;for(const r of e){let e=null==r.id?`${t}-${i++}`:String(r.id);for(;null==r.id&&s.has(e);)e=`${t}-${i++}`;s.add(e),n.set(e,null==r.id?{...r,id:e}:r)}return{seed:e,rows:Array.from(n.values()),nextId:i}}(e.data,"event"),r=n.flatMap((t,i)=>{const s=It(Mt(t,i,e.timeAccessor));if(null==s)return[];return[{datum:t,index:i,eventTime:s,arrivalTime:It(Mt(t,i,e.arrivalAccessor))??s,watermarkAtArrival:0,late:!1}]}),o="function"==typeof i?null:It(i?.value),a="function"==typeof i?t:It(i?.delay)??t,d=new xt(t,i,e.sourceIds);for(const t of r.slice().sort((e,t)=>e.arrivalTime-t.arrivalTime||e.index-t.index)){const i=s?It(Mt(t.datum,t.index,s)):null,n=d.append({eventTime:t.eventTime,arrivalTime:t.arrivalTime,source:String(Mt(t.datum,t.index,e.sourceAccessor??"source")??""),watermarkAtArrival:i??void 0});t.watermarkAtArrival=n.watermarkAtArrival,t.late=n.late}return{events:r,watermarkValue:r.length?d.getWatermark():o??-a,ledger:d.getLedger(),lifecycleEvents:d.drainEvents()}}import{jsx as kt,jsxs as Pt}from"react/jsx-runtime";function qt(e,i){const s=i.arrival;if(s&&"drop"!==s){if("travel"!==s.mode)throw new RangeError("arrival.mode must be travel");if(null!=s.history&&"present"!==s.history&&"travel"!==s.history)throw new RangeError("arrival.history must be present or travel");for(const e of[s.durationMs,s.speedPxPerSec])if(null!=e&&(!Number.isFinite(e)||e<=0))throw new RangeError("Travel duration and speed must be finite and positive");if(null!=s.durationMs&&null!=s.speedPxPerSec)throw new RangeError("Choose arrival.durationMs or arrival.speedPxPerSec");if(null!=s.path&&"function"!=typeof s.path&&"straight"!==s.path&&"connector"!==s.path)throw new RangeError("arrival.path must be straight, connector or a callback")}const r=new Map(function(e=[],t={},i){if("none"===t.side)return[];const s=e.filter(e=>!1!==e.visible),n=Math.max(48,t.tileSize??80);return s.map((e,r)=>({source:e,x:"top"===t.side?(r+.5)*i[0]/Math.max(1,s.length):n/2,y:"top"===t.side?n/2+24:(r+.5)*i[1]/Math.max(1,s.length)}))}(i.sources,i.sourceRail,i.size).map(({source:e,x:t,y:i})=>[e.id,{x:t,y:i-6}])),o=Number.isFinite(i.timeScale)&&i.timeScale>0?i.timeScale:1,a=[];for(const d of e){const e=d.datum;s&&"drop"!==s&&(e.__phase=e.late?"late":"board");const h=e.windowIndex<i.closedWindowCount,l=(!s||"drop"===s||"travel"!==s.history)&&(h&&!e.late||!h&&e.late);l&&a.push(d);const c=(l?i.firstArrival:e.arrivalTime)*i.secondsPerUnit;d.__eventDropSpawnTime=c;const u=r.get(e.source);if(!s||"drop"===s||!u||l)continue;const p={x:d.x,y:d.y},m="function"==typeof s.path?s.path({...u},{...p}):"connector"===s.path?[u,{x:u.x,y:Math.min(u.y,p.y)-24},{x:p.x,y:Math.min(u.y,p.y)-24},p]:[u,p];if(t({points:m,durationSeconds:1}),m[0].x!==u.x||m[0].y!==u.y||m.at(-1).x!==p.x||m.at(-1).y!==p.y)throw new RangeError("Travel paths must start at the source and end at the board entry");const f=null!=s.speedPxPerSec?Math.max(1/120,n(m)/s.speedPxPerSec):(s.durationMs??800)/1e3;d.travel={points:m.map(e=>({...e})),durationSeconds:f/o,elapsedSeconds:0},d.x=u.x,d.y=u.y,d.__eventDropSpawnTime=c-f,e.__phase="travel"}if(s&&"drop"!==s&&null!=s.speedPxPerSec){const t=e.reduce((e,t)=>Math.max(e,t.travel?.durationSeconds??0),0);for(const i of e)i.travel&&(i.__eventDropSpawnTime+=(i.travel.durationSeconds-t)*o,i.travel.durationSeconds=t)}const d=e.reduce((e,t)=>Math.min(e,t.__eventDropSpawnTime),1/0);for(const e of a)e.__eventDropSpawnTime=d}function Et(e,t,i=!1){const{data:s,timeAccessor:n,arrivalAccessor:r,windows:o,watermark:a,watermarkAtArrivalAccessor:d,ballRadius:h,seed:l,size:c,timeExtent:u,timeScale:p=1}=e,{events:m,watermarkValue:f,ledger:v,lifecycleEvents:y}=t??Tt({data:s,timeAccessor:n,arrivalAccessor:r,watermark:a,watermarkAtArrivalAccessor:d,sourceAccessor:e.sourceAccessor,sourceIds:e.sources?.map(e=>e.id),windowSize:o.size}),g=new Map(v.map(e=>[e.start,e])),w=function(e){const[t,i]=e,s=t<160||i<116,n=s?Math.min(12,Math.max(2,.08*t)):32,r=s?Math.min(8,Math.max(2,.12*i)):24,o=s?r:34;return{width:t,height:i,plot:{x:n,y:r,width:Math.max(1,t-2*n),height:Math.max(1,i-r-o)}}}(c);if(e.sources?.some(e=>!1!==e.visible)&&"none"!==e.sourceRail?.side){const t=Math.max(48,e.sourceRail?.tileSize??80);"top"===e.sourceRail?.side?(w.plot.y+=t,w.plot.height=Math.max(1,w.plot.height-t)):(w.plot.x+=t,w.plot.width=Math.max(1,w.plot.width-t))}let x=m.length?1/0:0,b=m.length?1/0:0,S=m.length?-1/0:o.size;for(const e of m)x=Math.min(x,e.arrivalTime),b=Math.min(b,e.eventTime),S=Math.max(S,e.eventTime);const M=e.timeUnit??(m.some(e=>Math.abs(e.eventTime)>1e5||Math.abs(e.arrivalTime)>1e5)?"ms":"s"),I="ms"===M?.001:1,T=It(u?.[0]),k=It(u?.[1]),P=i?T??b:Math.min(T??b,b),q=i?k??S:Math.max(k??S,S),E=Math.floor(P/o.size)*o.size,A=Math.max(1,Math.ceil((q-E+o.size)/o.size)),B=function(e,t){const i=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:i,height:e.plot.height},windowPlot:{x:e.plot.x+i,y:e.plot.y,width:Math.max(40,e.plot.width-i),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(w,h),D=E+A*o.size,O=bt().domain([E,D]).range([B.windowPlot.x,B.windowPlot.x+B.windowPlot.width]);let R=0;const C=Array.from({length:A},(e,t)=>(E+(t+1)*o.size<=f&&R++,{value:0,secondary:0})),N=[];m.forEach(({datum:t,index:i,eventTime:s,arrivalTime:n,watermarkAtArrival:r,late:a})=>{const d=Math.max(0,Math.min(A-1,Math.floor((s-E)/o.size)));C[d].value+=a?0:1,C[d].secondary+=a?1:0,N.push({id:String(t.id??`event-${i}`),x:Bt(s,d,a,{windowStart:E,windowSize:o.size,gutter:B.gutter,closedWindowCount:R,windowPlot:B.windowPlot,windowCount:A},h),y:w.plot.y+h+2,vx:0,vy:0,mass:1,friction:.02,spawnAt:n,shape:{type:"circle",radius:h},datum:{...t,eventTime:s,arrivalTime:n,windowIndex:d,windowId:`${E+d*o.size}-${E+(d+1)*o.size}`,source:String(Mt(t,i,e.sourceAccessor??"source")??""),watermarkAtArrival:r,late:a}})});const F=w.plot.y+w.plot.height,z=w.plot.y+.28*w.plot.height,W={closedWindowCount:R,gutter:B.gutter,plot:w.plot,windowCount:A,windowPlot:B.windowPlot,windowSize:o.size,windowStart:E},$=function(e,t){const i=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!i)return[];const s=e.windowStart,n=e.windowStart+e.windowCount*e.windowSize,r=bt().domain([s,n]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),o=r(e.windowStart+i*e.windowSize),a=e.windowPlot.x,d=Math.max(18,Math.min(.3*e.windowPlot.height,o-a)),h=t+d,l=e=>o===a?t:h+(e-a)/(o-a)*(t-h),c=[];for(let t=0;t<i;t+=1){const i=e.windowStart+t*e.windowSize,s=i+e.windowSize,n=r(i),o=r(s);c.push({id:`eventdrop-lid-${t}`,windowIndex:t,x1:n,y1:l(n),x2:o,y2:l(o)})}return c}(W,z);for(const e of N){const t=e.datum;e.y=At({...W,lidSegments:$},t.windowIndex,t.late,h)}const Y=function(e){const{count:t,idPrefix:i,wallThickness:s,xScale:n,yBottom:r,yTop:o,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const d=Math.min(r-1,a?.(t)??o),h=Math.max(1,r-d);return{id:`${i}-wall-${t}`,shape:{type:"aabb",x:n(t),y:d+h/2,width:s,height:h}}})}({idPrefix:"eventdrop-window",count:A,xScale:e=>O(E+e*o.size),yTop:B.wallTop,yTopForIndex:e=>{const t=(e=>{if(e<0||e>R)return null;const t=0===e?$[0]?.y1:$[e-1]?.y2??$[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?B.wallTop:t+1.25*h},yBottom:F,wallThickness:6}),X=[...Ce({x:w.plot.x,y:w.plot.y,width:w.plot.width,height:w.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...Y,...$.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*h)},friction:.02,restitution:.01}))];return qt(N,{...e,secondsPerUnit:I,timeScale:p,firstArrival:x,closedWindowCount:R}),{config:St(l,X,"EventDropChart",{friction:.08}),initialSpawns:N,initialSpawnPacing:{pacing:"arrival",timeAccessor:"__eventDropSpawnTime",timeScale:p},projectionRows:C.map((e,t)=>({label:`${E+t*o.size}-${E+(t+1)*o.size}`,value:e.value,secondary:e.secondary,...g.get(E+t*o.size)})),metadata:{kind:"event-drop",closedWindowCount:R,gutter:B.gutter,lidSegments:$,lateCount:C.reduce((e,t)=>e+t.secondary,0),plot:w.plot,windowPlot:B.windowPlot,windowWalls:Y.map(({id:e,shape:t})=>({id:e,x:t.x-t.width/2,y:t.y-t.height/2,width:t.width,height:t.height})),watermarkValue:f,windowCount:A,windowSize:o.size,windowStart:E,ledger:v,lifecycleEvents:y,timeUnit:M,eventTimeFrontier:m.length?S:0,arrivalFrontier:m.reduce((e,t)=>Math.max(e,t.arrivalTime),0)}}}function At(e,t,i,s){const{windowPlot:n,lidSegments:r}=e,o=r[t];return i&&!o?Math.min(n.y+n.height-s,n.y+.48*n.height+2*s+4):!i&&o?Math.min(n.y+n.height-s,Math.max(o.y1,o.y2)+2*s+4):n.y+s+2}function Bt(e,t,i,s,n){const{windowPlot:r,windowCount:o,windowStart:a,windowSize:d}=s;if(i&&t>=s.closedWindowCount)return s.gutter.x+s.gutter.width/2;const h=r.width/o,l=i?r.x:r.x+t*h,c=i?r.x+r.width:l+h,u=Math.min((c-l)/2,n+(i?0:3)),p=r.x+(e-a)/d*h;return Math.max(l+u,Math.min(c-u,p))}var Dt=class e{constructor(e){this.config=e,this.elapsed=0,this.pending=new Map,this.geometryKey="",this.laneWidth=1,this.offset=0,this.bodiesChanged=!1,this.validate(e),this.ledger=new xt(e.windowSize,e.watermark,e.sources?.map(e=>e.id)),this.anchor=e.originTime??0,this.refresh()}validate(e){if(null!=e.originTime&&!Number.isFinite(e.originTime))throw new RangeError("Live originTime must be finite");if(!["now","watermark"].includes(e.live.follow)||!Number.isFinite(e.live.horizon)||e.live.horizon<=0||!Number.isFinite(e.live.retain)||e.live.retain<0)throw new RangeError("live requires follow now/watermark, positive horizon and nonnegative retain")}update(e,t){if(this.validate(e),e.windowSize!==this.config.windowSize)throw new RangeError("Changing live windows.size requires a new run (remount with a new key)");if(e.timeUnit!==this.config.timeUnit||e.originTime!==this.config.originTime)throw new RangeError("Changing live timeUnit or origin requires a new run (remount with a new key)");this.ledger.setWatermark(e.watermark??{});const i=this.layout.metadata,s=this.laneWidth;this.config=e,this.geometryKey="",this.refresh();const n=this.layout.metadata;if(t&&(s!==this.laneWidth||i.plot.y!==n.plot.y||i.plot.height!==n.plot.height||i.windowPlot.x!==n.windowPlot.x)){const e=this.laneWidth/s,r=n.plot.height/i.plot.height,o=t=>({x:n.windowPlot.x+(t.x-i.windowPlot.x)*e,y:n.plot.y+(t.y-i.plot.y)*r}),a=e=>({...e,...o(e),...e.travel&&{travel:{...e.travel,points:e.travel.points.map(o)}}}),d=t.snapshot();t.restore({...d,bodies:d.bodies.map(t=>({...a(t),prevX:o({x:t.prevX,y:t.prevY}).x,prevY:o({x:t.prevX,y:t.prevY}).y,vx:t.vx*e,vy:t.vy*r}))}),this.pending=new Map(Array.from(this.pending,([e,t])=>[e,{...t,spawn:a(t.spawn)}]))}}get unit(){return"ms"===this.config.timeUnit?1e3:1}get now(){return(this.config.originTime??0)+this.elapsed*this.unit}refresh(){const{windowSize:e,live:t,size:i,ballRadius:s,seed:n,sources:r,sourceRail:o,timeUnit:a}=this.config,d=Math.floor((this.anchor-t.retain)/e)*e,h=Math.ceil((t.retain+t.horizon)/e)+1,l=this.ledger.getWatermark(),c=`${d}:${Math.floor(l/e)}`;if(c===this.geometryKey)return;this.geometryKey=c,this.layout=Et({data:[],timeAccessor:"time",arrivalAccessor:"arrivalTime",windows:{size:e},size:i,ballRadius:s,seed:n,sources:r,sourceRail:o,timeUnit:a,timeExtent:[d,d+(h-1)*e]},{events:[],watermarkValue:l,ledger:[],lifecycleEvents:[]},!0);const u=this.layout.metadata;this.laneWidth=u.windowPlot.width/h,this.offset=d/e*this.laneWidth;for(const e of this.layout.config.colliders??[]){const t=e.shape;"segment"===t.type?(t.x1+=this.offset,t.x2+=this.offset):t.x+=this.offset,e.id=`${e.id}:${d}`}}viewTransform(){return{x:-(this.anchor-this.config.live.retain)/this.config.windowSize*this.laneWidth,y:0}}metadata(){const e=this.layout.metadata,t=this.offset+this.viewTransform().x,i=e=>({...e,x:e.x+t});return{...e,plot:i(e.plot),windowPlot:i(e.windowPlot),gutter:i(e.gutter),lidSegments:e.lidSegments.map(e=>({...e,x1:e.x1+t,x2:e.x2+t})),windowWalls:e.windowWalls?.map(i),watermarkValue:this.ledger.getWatermark(),eventTimeFrontier:this.ledger.getLatestEventTime(),arrivalFrontier:this.ledger.getArrivalFrontier(),ledger:this.ledger.getLedger(),lateCount:this.ledger.getLedger().reduce((e,t)=>e+t.late,0)}}colliders(){return this.layout.config.colliders??[]}backlog(){if(this.pending.size>0)return!0;if("watermark"!==this.config.live.follow)return!1;const e=this.ledger.getWatermark();return Number.isFinite(e)&&e-this.anchor>1e-9}continuous(){const e=this.config.watermark;return"now"===this.config.live.follow||"object"==typeof e&&(null!=e.idleTimeout||null!=e.external)}prepare(e,t){this.bodiesChanged=!0;const i=e.datum,s=Number(i.eventTime??i.time);if(!Number.isFinite(s))throw new RangeError("Live EventDrop requires a finite event time");const{windowSize:n,ballRadius:r,arrival:o,sources:a,sourceRail:d,size:h}=this.config,l=this.layout.metadata,c=Math.floor(s/n),u=Math.min(this.laneWidth/2,r+3),p=Math.max(u,Math.min(this.laneWidth-u,(s/n-c)*this.laneWidth)),m={...e,x:l.windowPlot.x+c*this.laneWidth+p,y:l.plot.y+r+2,vx:0,vy:0,datum:{...i,id:e.id,eventTime:s,time:s,arrivalTime:this.now,windowIndex:c,windowId:`${c*n}-${(c+1)*n}`,__phase:"travel",late:!1}},f=this.viewTransform().x;m.x+=f,qt([m],{arrival:o&&"drop"!==o?{...o,history:"travel"}:o,sources:a,sourceRail:d,size:h,secondsPerUnit:1/this.unit,timeScale:1,firstArrival:t,closedWindowCount:0}),m.x-=f,m.travel&&(m.travel.points=m.travel.points.map(e=>({...e,x:e.x-f})));const v=t+(m.travel?.durationSeconds??0);return this.pending.set(m.id,{spawn:m,due:v}),m}advance(e,t){const i=Math.max(0,t-this.elapsed);this.elapsed=t;for(const{spawn:i,due:s}of Array.from(this.pending.values()).filter(e=>e.due<=t+1e-9).sort((e,t)=>e.due-t.due)){this.pending.delete(i.id);const t=i.datum,n=(this.config.originTime??0)+s*this.unit,r=this.ledger.append({eventTime:Number(t.eventTime),arrivalTime:Math.max(n,this.ledger.getArrivalFrontier()),source:String(t.source??"")}),o=e.readBody?.(i.id)??e.readState().find(e=>e.id===i.id);if(o){this.bodiesChanged=!0;const s=this.layout.metadata,a=r.end<=this.ledger.getWatermark(),d=r.late?{x:s.gutter.x+s.gutter.width/2+this.offset,y:s.plot.y+.55*s.plot.height}:{x:i.travel?.points.at(-1)?.x??i.x,y:s.plot.y+s.plot.height*(a?.58:0)+this.config.ballRadius+2};e.spawn({...o,...d,travel:void 0,datum:{...t,...r,arrivalTime:n,__phase:r.late?"late":"board"}})}}this.ledger.advance(this.now);const s="now"===this.config.live.follow?this.now:this.ledger.getWatermark();Number.isFinite(s)&&(this.anchor+=Math.max(0,Math.min(s-this.anchor,this.config.live.horizon*i/2)));const n=this.geometryKey;this.refresh(),n!==this.geometryKey&&e.setColliders(this.colliders());const r=this.anchor-this.config.live.retain,o=e.readState().filter(e=>{if(this.pending.has(e.id))return!1;const t=e.datum;return t.late?Number(t.arrivalTime)<this.now-this.config.windowSize:Math.floor(Number(t.eventTime)/this.config.windowSize)*this.config.windowSize+this.config.windowSize<r}).map(e=>e.id);return this.bodiesChanged||(this.bodiesChanged=o.length>0),o}drainWorkerDelta(){const e={...this.runtimeState(),ledger:this.ledger.drainDelta(),bodiesChanged:this.bodiesChanged};return this.bodiesChanged=!1,e}applyWorkerDelta(e,t){Ot(e),this.ledger.applyDelta(e.ledger);const i=this.geometryKey;this.applyState(e),i!==this.geometryKey&&t.setColliders(this.colliders())}snapshot(){return{config:this.config,ledger:this.ledger.snapshot(),...this.runtimeState()}}runtimeState(){return{anchor:this.anchor,elapsed:this.elapsed,pending:Array.from(this.pending.values(),e=>({due:e.due,spawn:Ie(e.spawn)}))}}static restore(t){Ot(t);const i=new e(t.config);return i.ledger.restore(t.ledger),i.applyState(t),i}applyState(e){this.anchor=e.anchor,this.elapsed=e.elapsed,this.pending=new Map(e.pending.map(e=>[e.spawn.id,{due:e.due,spawn:Ie(e.spawn)}])),this.refresh()}};function Ot(e){if(!Number.isFinite(e.anchor)||!Number.isFinite(e.elapsed)||e.elapsed<0||new Set(e.pending.map(e=>e.spawn.id)).size!==e.pending.length)throw new RangeError("Invalid live EventDrop snapshot");for(const t of e.pending){if(!Number.isFinite(t.due)||t.due<0)throw new RangeError("Invalid live EventDrop handoff");u(t.spawn)}}function Rt(){var e;e={emitters:{create:e=>new gt(e),restore:e=>gt.restore(e)},eventDrop:{create:e=>new Dt(e),restore:e=>Dt.restore(e)}},Object.assign(rt,e)}function Ct(e,t,i=!1){const s=e.workerLiveDelta(),n=s?.bodiesChanged||t.spawned.length||t.evicted.length||t.sedimented.length||t.events.some(e=>"travel-end"===e.type),r=i||!s&&n?e.snapshot():void 0,o=e.readBodies(),a=function(e,t,i=[],s){const n=new Array(t.length),r=new Float32Array(2*t.length),o=new Float32Array(2*t.length),a=new Uint8Array(t.length),d=new Float32Array(2*t.length);return t.forEach((e,t)=>{const i=2*t;n[t]=e.id,r[i]=e.x,r[i+1]=e.y,d[i]=e.prevX,d[i+1]=e.prevY,o[i]=e.vx,o[i+1]=e.vy,a[t]=e.sleeping?1:0}),{bodies:t,ids:n,positions:r,previousPositions:d,result:e,sediment:i,sleeping:a,snapshot:s,velocities:o}}(t,o,[],r);return s&&!r&&(a.live=s,n&&(a.structure=e.workerStructure())),o.some(e=>e.travel)&&(a.travelElapsed=Float64Array.from(o,e=>e.travel?.elapsedSeconds??0)),a.sleepTimes=e.workerSleepTimes(a.ids),a.bodies=[],r||a.structure||(a.ids=[]),a.state=e.workerState(),a}function Nt(e){return Ct(e,e.tick(0),!0)}var Ft=function(){Rt();let e=new ct;return{handle(t){switch(t.type){case"init":return e=new ct(t.config),t.snapshot?e.restore(t.snapshot):t.initialSpawns?.length&&e.enqueue(t.initialSpawns,t.initialSpawnPacing),{type:"frame",frame:Nt(e)};case"configure":return e.updateConfig(t.config),{type:"frame",frame:Nt(e)};case"enqueue":return e.enqueue(t.spawns,t.pacing),{type:"frame",frame:Nt(e)};case"tick":return{type:"frame",frame:Ct(e,e.tick(t.deltaSeconds))};case"settle":return{type:"frame",frame:Ct(e,e.settleWithObservations(t.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:e.snapshot()};case"restore":return e.restore(t.snapshot),{type:"frame",frame:Nt(e)};case"clear":return e.clear(),{type:"frame",frame:Nt(e)};case"remove":return{type:"removed",removed:e.remove(t.ids),frame:Nt(e)};case"applyImpulse":return e.applyImpulse(t.id,t.ix,t.iy),{type:"frame",frame:Nt(e)};case"setPaused":return e.setPaused(t.paused),{type:"frame",frame:Nt(e)};case"setVisible":return e.setVisible(t.visible),{type:"frame",frame:Nt(e)}}}}}();function zt(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=Ft.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,...t.sleepTimes?[t.sleepTimes.buffer]:[],...t.travelElapsed?[t.travelElapsed.buffer]:[],...t.previousPositions?[t.previousPositions.buffer]:[]]:[];var t}(e))}catch(e){self.postMessage({error:zt(e),ok:!1,requestId:t.requestId})}};
1
+ function e(e){return{...e,points:e.points.map(e=>({...e}))}}function t(e){if(!Number.isFinite(e.durationSeconds)||e.durationSeconds<=0||!Array.isArray(e.points)||e.points.length<2||e.points.some(e=>!e||!Number.isFinite(e.x)||!Number.isFinite(e.y))||null!=e.elapsedSeconds&&(!Number.isFinite(e.elapsedSeconds)||e.elapsedSeconds<0||e.elapsedSeconds>e.durationSeconds))throw new RangeError("Physics travel requires two finite points, a positive duration and valid elapsed seconds")}function i(e,t){return e&&"object"==typeof e&&"__phase"in e&&e.__phase!==t?{...e,__phase:t}:e}function s(e){return e&&"object"==typeof e&&"late"in e&&e.late?"late":"board"}function n(e){let t=0;for(let i=1;i<e.length;i++)t+=Math.hypot(e[i].x-e[i-1].x,e[i].y-e[i-1].y);return t}function r(e,t){const r=e.travel;if(!r)return!1;const o=Math.min(r.durationSeconds,(r.elapsedSeconds??0)+t);r.elapsedSeconds=o;let a=n(r.points)*o/r.durationSeconds,d=r.points[r.points.length-1];for(let e=1;e<r.points.length;e++){const t=r.points[e-1],i=r.points[e],s=Math.hypot(i.x-t.x,i.y-t.y);if(s>0&&a<s){d={x:t.x+(i.x-t.x)*a/s,y:t.y+(i.y-t.y)*a/s};break}a-=s}if(e.x=d.x,e.y=d.y,e.vx=e.vy=0,o<r.durationSeconds-1e-9)return!1;const h=r.points[r.points.length-1];return e.x=e.prevX=h.x,e.y=e.prevY=h.y,delete e.travel,e.datum=i(e.datum,s(e.datum)),!0}function o(e,t){if(!Number.isFinite(e))throw new RangeError(`${t} must be finite`)}function a(e,t){if(o(e,t),e<=0)throw new RangeError(`${t} must be positive`)}function d(e,t){if(!Array.isArray(e))throw new RangeError(`${t} must be an array`)}function h(e,t){d(e,t);for(const i of e)if("string"!=typeof i)throw new RangeError(`${t} must contain strings`)}function l(e){if(!e||!e.shape||"circle"!==e.shape.type&&"aabb"!==e.shape.type)throw new RangeError("Physics bodies require a circle or aabb shape");const i=`Physics body ${e.id}`;o(e.x,`${i}.x`),o(e.y,`${i}.y`);for(const t of["vx","vy","angle","restitution","friction"])null!=e[t]&&o(e[t],`${i}.${t}`);if(null!=e.mass&&a(e.mass,`${i}.mass`),e.travel&&(t(e.travel),e.fixedPosition))throw new RangeError("Physics travel cannot use fixedPosition");"circle"===e.shape.type?a(e.shape.radius,`${i}.radius`):(a(e.shape.width,`${i}.width`),a(e.shape.height,`${i}.height`))}function c(e){for(const t of["restLength","stiffness","damping"])null!=e[t]&&o(e[t],`Physics spring.${t}`);"point"===e.target.type&&(o(e.target.x,"Physics spring.target.x"),o(e.target.y,"Physics spring.target.y"))}function u(e){l(e),null!=e.spawnAt&&o(e.spawnAt,`Physics body ${e.id}.spawnAt`);for(const t of e.springs??[])c({...t,bodyId:e.id})}function p(e){for(const t of e){if(!t?.shape||"segment"!==t.shape.type&&"aabb"!==t.shape.type)throw new RangeError("Physics colliders require a segment or aabb shape");const e=t.shape;if("segment"===e.type)for(const i of["x1","y1","x2","y2"])o(e[i],`Physics collider ${t.id}.${i}`);else for(const i of["x","y","width","height"])o(e[i],`Physics collider ${t.id}.${i}`);for(const[e,i]of Object.entries(t.shape))"type"!==e&&null!=i&&o(i,`Physics collider ${t.id}.${e}`);for(const e of["restitution","friction"])null!=t[e]&&o(t[e],`Physics collider ${t.id}.${e}`)}}function m(e){for(const[t,i]of Object.entries(e))"gravity"!==t&&null!=i&&o(i,`Physics option ${t}`);e.gravity&&(o(e.gravity.x,"Physics gravity.x"),o(e.gravity.y,"Physics gravity.y"));for(const t of["fixedDt","cellSize"])null!=e[t]&&a(e[t],`Physics option ${t}`);if(null!=e.velocityDamping&&e.velocityDamping<0)throw new RangeError("Physics velocityDamping must be nonnegative")}function f(e){h(e.activeSensors,"Physics activeSensors"),d(e.bodies,"Physics bodies"),d(e.colliders,"Physics colliders"),d(e.springs,"Physics springs"),m(e.options);for(const t of e.bodies){l(t);for(const e of["prevX","prevY","sleepTime","index"])o(t[e],`Physics body ${t.id}.${e}`)}p(e.colliders);for(const t of e.springs)c(t);null!=e.randomState&&o(e.randomState,"Physics randomState")}function v(e){e.kernel&&m(e.kernel),e.viewTransform&&(o(e.viewTransform.x,"Physics viewTransform.x"),o(e.viewTransform.y,"Physics viewTransform.y")),e.colliders&&p(e.colliders),null!=e.fixedDt&&a(e.fixedDt,"Physics fixedDt");for(const t of["maxDeltaSeconds","maxSubsteps","settleStepLimit","timeScale"])if(null!=e[t]&&(o(e[t],`Physics ${t}`),e[t]<0))throw new RangeError(`Physics ${t} must be nonnegative`)}function y(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(i in e!=i in t||!Object.is(e[i],t[i]))return!1;return!0}function g(e,t){return e===t||!(!e||!t||e.length!==t.length)&&e.every((e,i)=>{const s=t[i],n=e.shape,r=s.shape,o="segment"===n.type&&"segment"===r.type?n.x1===r.x1&&n.y1===r.y1&&n.x2===r.x2&&n.y2===r.y2&&(n.thickness??0)===(r.thickness??0):"aabb"===n.type&&"aabb"===r.type&&n.x===r.x&&n.y===r.y&&n.width===r.width&&n.height===r.height;return e.id===s.id&&e.sensor===s.sensor&&e.friction===s.friction&&e.restitution===s.restitution&&function(e,t){return e===t||!(!e||!t||"function"==typeof e||"function"==typeof t)&&e.property===t.property&&"equals"in e=="equals"in t&&"notEquals"in e=="notEquals"in t&&Object.is(e.equals,t.equals)&&Object.is(e.notEquals,t.notEquals)&&y(e.oneOf,t.oneOf)&&y(e.notOneOf,t.notOneOf)}(e.bodyFilter,s.bodyFilter)&&o})}function w(e,t){return Boolean(t?.some(t=>Object.is(e,t)))}function x(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const i=function(e,t){if(!t)return;let i=e;for(const e of t.split(".")){if(null==i||"object"!=typeof i)return;if(!Object.prototype.hasOwnProperty.call(i,e))return;i=i[e]}return i}(e,t.property);return!("equals"in t&&!Object.is(i,t.equals))&&((!("notEquals"in t)||!Object.is(i,t.notEquals))&&(!(t.oneOf&&!w(i,t.oneOf))&&(!t.notOneOf||!w(i,t.notOneOf))))}function b(e){let t=e>>>0;function i(){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}return i.getState=()=>t>>>0,i}function S(e){const t=e.fixedPosition;Number.isFinite(t?.x)&&(e.x=e.prevX=t.x,e.vx=0),Number.isFinite(t?.y)&&(e.y=e.prevY=t.y,e.vy=0)}function M(e){if(!e)return;const t=Number.isFinite(e.x)?e.x:void 0,i=Number.isFinite(e.y)?e.y:void 0;return null==t&&null==i?void 0:{x:t,y:i}}function I(e,t,i){const s="x"===i?"y":"x",n=Math.abs(t[i]-e[i]),r=t[s]-e[s],o=(e,t)=>"circle"===e.shape.type?e.shape.radius:("x"===t?e.shape.width:e.shape.height)/2;let a;if("circle"===e.shape.type&&"circle"===t.shape.type){const i=e.shape.radius+t.shape.radius;a=Math.sqrt(Math.max(0,i*i-n*n))}else if("aabb"===e.shape.type&&"aabb"===t.shape.type)a=o(e,s)+o(t,s);else{const r="circle"===e.shape.type?e:t,d="aabb"===e.shape.type?e:t,h=o(r,i),l=Math.max(0,n-o(d,i));a=o(d,s)+Math.sqrt(Math.max(0,h*h-l*l))}const d=r<0?-1:1;return{nx:"x"===s?d:0,ny:"y"===s?d:0,penetration:Math.max(0,a-Math.abs(r))}}function T(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function k(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 P(t){return{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,bodyCollisions:t.bodyCollisions,...t.travel?{travel:e(t.travel)}:{},...t.fixedPosition?{fixedPosition:M(t.fixedPosition)}:{},shape:T(t.shape),sleeping:t.sleeping,datum:t.datum}}function q(e){return{...P(e),index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function E(e){return e&&"function"!=typeof e?{property:e.property,..."equals"in e?{equals:e.equals}:{},..."notEquals"in e?{notEquals:e.notEquals}:{},oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function A(e){return{id:e.id,shape:k(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:E(e.bodyFilter),index:e.index}}var B=1e-9;function D(e,t,i){let s=i.length>2,n=1/0,r=i[0][0],o=i[0][1],a=1,d=0;for(let h=0;h<i.length;h++){const[l,c]=i[h],[u,p]=i[(h+1)%i.length],m=u-l,f=p-c,v=Math.hypot(m,f);if(v<=B)continue;const y=f/v,g=-m/v;(e-l)*y+(t-c)*g>0&&(s=!1);const w=Math.max(0,Math.min(1,((e-l)*m+(t-c)*f)/(v*v))),x=l+w*m,b=c+w*f,S=(e-x)**2+(t-b)**2;S<n&&(n=S,r=x,o=b,a=y,d=g)}const h=Math.hypot(e-r,t-o);return!s&&h>B&&(a=(e-r)/h,d=(t-o)/h),{distance:s?-h:h,nx:a,ny:d}}function O(e,t,i,s){const n=e.x-e.prevX,r=e.y-e.prevY,o=n*n+r*r;if(o<=1e-18)return null;if(0===i&&!function(e,t){let i=0,s=1;const n=e.x-e.prevX,r=e.y-e.prevY;for(let o=0;o<t.length;o++){const[a,d]=t[o],[h,l]=t[(o+1)%t.length],c=l-d,u=a-h;if(Math.hypot(c,u)<=B)continue;const p=(e.prevX-a)*c+(e.prevY-d)*u,m=n*c+r*u;if(m<0)i=Math.max(i,-p/m);else if(m>0)s=Math.min(s,-p/m);else if(p>=0)return!1;if(i>=s)return!1}return i<s}(e,t))return null;if(D(e.prevX,e.prevY,t).distance<i-s)return null;let a=1/0,d=null;const h=(t,s,o,h,l)=>{if(t<0||t>1||t>a)return;if(t===a&&d&&Math.abs(s)<=Math.abs(d.nx))return;if(n*s+r*o>=0)return;const c=i-((e.x-h)*s+(e.y-l)*o);c<=0||(a=t,d={nx:0===s?0:s,ny:0===o?0:o,penetration:c})};for(let a=0;a<t.length;a++){const[d,l]=t[a],[c,u]=t[(a+1)%t.length],p=c-d,m=u-l,f=Math.hypot(p,m);if(f>B){const t=m/f,o=-p/f,a=n*t+r*o,c=(e.prevX-d)*t+(e.prevY-l)*o-i;if(a<0&&c>=-s){const i=Math.max(0,-c/a),s=((e.prevX+i*n-d)*p+(e.prevY+i*r-l)*m)/f;s>=0&&s<=f&&h(i,t,o,d,l)}}if(i<=0)continue;const v=e.prevX-d,y=e.prevY-l,g=v*n+y*r,w=g*g-o*(v*v+y*y-i*i);if(g>=0||w<0)continue;const x=Math.max(0,(-g-Math.sqrt(w))/o),b=v+x*n,S=y+x*r,M=Math.hypot(b,S);M>B&&h(x,b/M,S/M,d,l)}return d}function R(e,t,i){if("aabb"!==t.type||e.x===e.prevX&&e.y===e.prevY)return null;const s="circle"===e.shape.type?e.shape.radius:0,n=(t.width+("aabb"===e.shape.type?e.shape.width:0))/2,r=(t.height+("aabb"===e.shape.type?e.shape.height:0))/2,o=t.x-n,a=t.x+n,d=t.y-r,h=t.y+r;return Math.max(e.x,e.prevX)+s<o||Math.min(e.x,e.prevX)-s>a||Math.max(e.y,e.prevY)+s<d||Math.min(e.y,e.prevY)-s>h?null:O(e,[[o,d],[a,d],[a,h],[o,h]],s,i)}function C(e,t,i=0,s=!1){const n=function(e,t){let{x1:i,y1:s,x2:n,y2:r}=t;if("circle"===e.shape.type)return[[i,s],[n,r]];(i>n||i===n&&s>r)&&(i=t.x2,s=t.y2,n=t.x1,r=t.y1);const o=e.shape.width/2,a=e.shape.height/2*(r>=s?1:-1),d=[[i-o,s-a],[i+o,s-a],[n+o,r-a],[n+o,r+a],[n-o,r+a],[i-o,s+a]];return a<0?d.reverse():d}(e,t),r=(t.thickness??0)/2+("circle"===e.shape.type?e.shape.radius:0);if(s){const t=O(e,n,r,i);if(t)return t}const o=D(e.x,e.y,n),a=r-o.distance;return a>0?{nx:o.nx,ny:o.ny,penetration:a}:null}function N(e,t){return Math.abs(e.x-t.x)<=t.padding&&Math.abs(e.y-t.y)<=t.padding}function F(e,t){const i=z(e),s=[];for(let e=0;e<t.length;e++)Y(i,t[e].bounds)&&s.push(e);return{bounds:i,indexes:s}}function z(e,t=!0){const i="circle"===e.shape.type?e.shape.radius:e.shape.width/2,s="circle"===e.shape.type?e.shape.radius:e.shape.height/2,n=t?Math.max(.005,Math.min(i,s)):0;return{x:e.x,y:e.y,padding:n,minX:Math.min(e.x,e.prevX)-i-n,minY:Math.min(e.y,e.prevY)-s-n,maxX:Math.max(e.x,e.prevX)+i+n,maxY:Math.max(e.y,e.prevY)+s+n}}function W(e){const t="circle"===e.shape.type?e.shape.radius:e.shape.width/2,i="circle"===e.shape.type?e.shape.radius:e.shape.height/2;return{minX:e.x-t,minY:e.y-i,maxX:e.x+t,maxY:e.y+i}}function $(e){const t=e.shape;if("aabb"===t.type)return W({x:t.x,y:t.y,shape:t});const i=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-i,minY:Math.min(t.y1,t.y2)-i,maxX:Math.max(t.x1,t.x2)+i,maxY:Math.max(t.y1,t.y2)+i}}function Y(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function X(e,t,i={x:0,y:0}){let s=1;const n=e.map(e=>{const t=z(e,!(e.sleeping&&e.x===e.prevX&&e.y===e.prevY));return!1!==e.bodyCollisions&&(s=Math.max(s,t.maxX-t.minX,t.maxY-t.minY)),t}),r=Math.max(1,Math.min(t,s)),o=new Map;for(let t=0;t<e.length;t+=1){if(!1===e[t].bodyCollisions)continue;const i=n[t];i.cellX=Math.floor(i.minX/r),i.cellY=Math.floor(i.minY/r);for(let e=i.cellX;e<=Math.floor(i.maxX/r);e+=1){let s=o.get(e);s||o.set(e,s=new Map);for(let e=i.cellY;e<=Math.floor(i.maxY/r);e+=1){const i=s.get(e);i?i.push(t):s.set(e,[t])}}}const a=[];for(const[e,t]of o)for(const[i,s]of t)for(let t=0;t<s.length;t+=1)for(let r=t+1;r<s.length;r+=1){const o=s[t],d=s[r],h=n[o],l=n[d];e===Math.max(h.cellX,l.cellX)&&i===Math.max(h.cellY,l.cellY)&&(Y(h,l)&&a.push([o,d]))}const d=e.map(e=>e.x*i.x+e.y*i.y);return a.sort(([e,t],[i,s])=>Math.max(d[i],d[s])-Math.max(d[e],d[t])||(e===i?t-s:e-i)),{pairs:a,coversPositions:()=>e.every((e,t)=>!1===e.bodyCollisions||N(e,n[t]))}}function j(e,t){if("circle"!==e.shape.type||"circle"!==t.shape.type)return null;const i=e.shape.radius+t.shape.radius;if(i<=0)return null;const s=t.prevX-e.prevX,n=t.prevY-e.prevY,r=t.x-e.x-s,o=t.y-e.y-n,a=r*r+o*o,d=2*(s*r+n*o),h=s*s+n*n-i*i;if(h<-1e-5||a<=1e-12||d>=0)return null;const l=d*d-4*a*h;if(l<0)return null;const c=(-d-Math.sqrt(l))/(2*a);if(c<0||c>1)return null;const u=(s+c*r)/i,p=(n+c*o)/i,m=i-((t.x-e.x)*u+(t.y-e.y)*p);return m>0?{nx:u,ny:p,penetration:m}:null}var L={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},_=1e-9,K=.005;function V(e,t,i){return Math.max(t,Math.min(i,e))}function U(e,t,i){return Math.min(e??i,t??i)}function H(e,t,i){return V(Math.max(e??i,t??i),0,1)}function G(e){return e<0?-1:1}function Q(e){return e.sleeping&&e.x===e.prevX&&e.y===e.prevY}function J(e,t,i,s,n,r,o,a){const d=n-e,h=(i+o)/2-Math.abs(d);if(h<=0)return null;const l=r-t,c=(s+a)/2-Math.abs(l);return c<=0?null:h<c?{nx:G(d),ny:0,penetration:h}:{nx:0,ny:G(l),penetration:c}}function Z(e,t,i,s,n,r,o){const a=r/2,d=o/2,h=e-V(e,s-a,s+a),l=t-V(t,n-d,n+d),c=h*h+l*l;if(c>i*i)return null;if(c<=_){const r=Math.abs(e-(s-a)),o=Math.abs(e-(s+a)),h=Math.abs(t-(n-d)),l=Math.abs(t-(n+d)),c=Math.min(r,o,h,l);return c===r?{nx:-1,ny:0,penetration:i+r}:c===o?{nx:1,ny:0,penetration:i+o}:c===h?{nx:0,ny:-1,penetration:i+h}:{nx:0,ny:1,penetration:i+l}}const u=Math.sqrt(c);return{nx:h/u,ny:l/u,penetration:i-u}}function ee(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,i,s,n,r){const o=s-e,a=n-t,d=i+r,h=o*o+a*a;if(h>=d*d)return null;if(h<=_)return{nx:1,ny:0,penetration:d};const l=Math.sqrt(h);return{nx:o/l,ny:a/l,penetration:d-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 J(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);const i="circle"===e.shape.type?e:t,s=i===e?t:e;if("circle"!==i.shape.type||"aabb"!==s.shape.type)return null;const n=Z(i.x,i.y,i.shape.radius,s.x,s.y,s.shape.width,s.shape.height);return n&&i===e&&(n.nx=-n.nx,n.ny=-n.ny),n}function te(e,t){const i=t.shape;return"aabb"===i.type?"circle"===e.shape.type?Z(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height):J(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height):C(e,i)}function ie(e,t){return`${e}\0${t}`}function se(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function ne(e,t){return x(t,e.bodyFilter)}var re=class{constructor(e={}){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.supportDependents=new Map,this.supportContactsThisStep=new Set,this.reboundingThisStep=new Set,this.interpenetratingThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,m(e),this.options={...L,...e},this.random=b(this.options.seed)}init(e={}){m(e),this.options={...L,...e},this.random=b(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(t){l(t);const i={id:t.id,x:t.x,y:t.y,prevX:t.x,prevY:t.y,vx:t.vx??0,vy:t.vy??0,angle:t.angle??0,mass:Math.max(_,t.mass??1),bodyCollisions:t.bodyCollisions??!0,...t.fixedPosition?{fixedPosition:M(t.fixedPosition)}:{},...t.travel?{travel:e(t.travel)}:{},shape:T(t.shape),sleeping:!1,datum:t.datum,restitution:t.restitution,friction:t.friction,index:this.nextBodyIndex,sleepTime:0};i.travel&&r(i,0),S(i),this.nextBodyIndex+=1,this.bodies.set(t.id,i)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))se(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){if(p(e),!g(e,this.sortedColliders())){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:k(t.shape),bodyFilter:E(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}}setConstraint(e){c(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,i){if(!Number.isFinite(t)||!Number.isFinite(i))throw new RangeError("Physics impulses must be finite");const s=this.bodies.get(e);s&&(s.vx+=t/s.mass,s.vy+=i/s.mass,S(s),this.wake(s))}step(e=this.options.fixedDt){const t=Number.isFinite(e)?Math.max(0,e):0;if(this.lastEvents=[],0===t)return;this.reboundingThisStep.clear();const i=this.sortedBodies(),s=i.some(e=>e.travel)?i.filter(e=>!e.travel):i;for(const e of i)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const n=this.options.maxVelocity,o=this.options.velocityDamping**(120*t);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*=o,e.vy*=o,S(e),n>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>n){const i=n/t;e.vx*=i,e.vy*=i}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear(),this.supportDependents.clear(),this.supportContactsThisStep.clear(),this.interpenetratingThisStep.clear();const a=this.sortedColliders().filter(e=>!e.sensor).map(e=>({collider:e,bounds:$(e)})),d=a.some(({collider:e})=>e.bodyFilter)?void 0:new Array(s.length),h=new Set,l=new Set;this.resolveColliders(s,a,h,d);const c=d&&s.map(Q);let u=X(s,this.options.cellSize,this.options.gravity);for(let e=0;e<this.options.collisionIterations;e+=1){e>0&&!u.coversPositions()&&(u=X(s,this.options.cellSize,this.options.gravity));const t=this.resolveBodyPairs(s,u.pairs,l,0===e,c),i=this.resolveColliders(s,a,h,d);if(d&&!t&&!i)break}u.coversPositions()||(u=X(s,this.options.cellSize,this.options.gravity));for(const[e,t]of u.pairs){const i=ee(s[e],s[t]);i&&i.penetration>.02&&(this.interpenetratingThisStep.add(s[e].id),this.interpenetratingThisStep.add(s[t].id))}const p=Array.from(this.supportedThisStep);for(let e=0;e<p.length;e+=1)for(const t of this.supportDependents.get(p[e])??[])this.supportedThisStep.has(t)||(this.supportedThisStep.add(t),p.push(t));this.reconcileSupportedVelocity(s,t),this.updateSensors(s),this.updateSleeping(s,t);for(const e of i)r(e,t)&&this.lastEvents.push({type:"travel-end",bodyId:e.id})}settle(e=1200,t=this.options.fixedDt){let i=0;for(;i<e&&!this.allSleeping();)this.step(t),i+=1;return i}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push(P(t));return e}readBody(e){const t=this.bodies.get(e);return t?P(t):void 0}workerSleepTimes(e){return Float32Array.from(e,e=>this.bodies.get(e)?.sleepTime??0)}applyWorkerMotion(e){e.ids.forEach((t,n)=>{const r=this.bodies.get(t);r&&(r.prevX=e.previousPositions?.[2*n]??r.x,r.prevY=e.previousPositions?.[2*n+1]??r.y,r.x=e.positions[2*n],r.y=e.positions[2*n+1],r.vx=e.velocities[2*n],r.vy=e.velocities[2*n+1],r.sleeping=1===e.sleeping[n],r.sleepTime=e.sleepTimes?.[n]??(r.sleeping?this.options.sleepAfter:0),r.travel&&e.travelElapsed&&(r.travel.elapsedSeconds=e.travelElapsed[n]),r.datum=i(r.datum,r.travel?"travel":r.sleeping?"settled":s(r.datum)))}),this.lastEvents=e.result.events,e.state&&(this.activeSensors=new Set(e.state.activeSensorPairs))}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(se)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{randomState:this.random.getState(),options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(q),colliders:this.sortedColliders().map(A),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(e){f(e),this.options={...e.options,gravity:{...e.options.gravity}},this.random=b(e.randomState??this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(e.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const t of e.bodies){const e=q(t);S(e),this.bodies.set(e.id,e),this.nextBodyIndex=Math.max(this.nextBodyIndex,e.index+1)}this.nextColliderIndex=0;for(const t of e.colliders){const e=A(t);this.colliders.set(e.id,e),this.nextColliderIndex=Math.max(this.nextColliderIndex,e.index+1)}this.nextSpringIndex=0;for(const t of e.springs){this.springs.set(t.id,{...t,target:{...t.target}});const e=/^spring-(\d+)$/.exec(t.id);e&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(e[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<t.id?-1:e.id>t.id?1:0)){const i=this.bodies.get(t.bodyId);if(!i||i.sleeping||i.travel)continue;const s="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!s)continue;const n=s.x-i.x,r=s.y-i.y,o=n*n+r*r,a=Math.sqrt(o);if(a<=_)continue;const d=n/a,h=r/a,l="vx"in s?s.vx:0,c="vy"in s?s.vy:0,u=(l-i.vx)*d+(c-i.vy)*h,p=(a-t.restLength)*t.stiffness+u*t.damping;i.vx+=p*d*e/i.mass,i.vy+=p*h*e/i.mass}}resolveBodyPairs(e,t,i,s,n){let r=!1;for(const[o,a]of t){const t=e[o],d=e[a];if(!t||!d)continue;if(!s&&n?.[o]&&n[a]&&Q(t)&&Q(d)){r=!0;continue}const h=j(t,d)??ee(t,d);if(!h)continue;r=!0,this.resolveDynamicCollision(t,d,h);const l=o*e.length+a;i.has(l)||(i.add(l),this.lastEvents.push({type:"contact",bodyId:t.id,otherId:d.id,sensor:!1}))}return r}resolveDynamicCollision(e,t,i){(e.fixedPosition||t.fixedPosition)&&(!e.sleeping&&null==e.fixedPosition?.x||!t.sleeping&&null==t.fixedPosition?.x?!e.sleeping&&null==e.fixedPosition?.y||!t.sleeping&&null==t.fixedPosition?.y||(i=I(e,t,"y")):i=I(e,t,"x"));const s=this.options.gravity,n=Math.hypot(s.x,s.y),r=this.contactOpposesGravity(i.nx,i.ny,n),o=this.contactOpposesGravity(-i.nx,-i.ny,n);r&&(e.sleeping&&this.supportedThisStep.add(t.id),this.addSupportContact(e.id,t.id)),o&&(t.sleeping&&this.supportedThisStep.add(e.id),this.addSupportContact(t.id,e.id));const a=e.sleeping?0:1/e.mass,d=t.sleeping?0:1/t.mass,h=null==e.fixedPosition?.x?a:0,l=null==e.fixedPosition?.y?a:0,c=null==t.fixedPosition?.x?d:0,u=null==t.fixedPosition?.y?d:0,p=e.fixedPosition||t.fixedPosition?i.nx**2*(h+c)+i.ny**2*(l+u):a+d;if(p<=_)return;const m=this.supportedThisStep.has(e.id)&&r&&!t.sleeping&&!t.fixedPosition,f=this.supportedThisStep.has(t.id)&&o&&!e.sleeping&&!e.fixedPosition,v=n>1,y=v&&m?0:h,g=v&&m?0:l,w=v&&!m&&f?0:c,x=v&&!m&&f?0:u,b=i.nx**2*(y+w)+i.ny**2*(g+x),S=Math.max(0,i.penetration-K)/Math.max(_,b);e.x-=i.nx*S*y,e.y-=i.ny*S*g,t.x+=i.nx*S*w,t.y+=i.ny*S*x,v&&m&&this.supportedThisStep.add(t.id),v&&f&&this.supportedThisStep.add(e.id);const M=t.vx-e.vx,T=t.vy-e.vy,k=M*i.nx+T*i.ny;if(k>0)return;const P=Math.abs(k),q=U(e.restitution,t.restitution,this.options.restitution),E=e.vx*s.x+e.vy*s.y,A=t.vx*s.x+t.vy*s.y,B=-(1+q)*k/p,D=B*i.nx,O=B*i.ny;e.vx-=D*h,e.vy-=O*l,t.vx+=D*c,t.vy+=O*u,this.applyFriction(e,t,i,B,h,l,c,u),q>0&&(E>=0&&e.vx*s.x+e.vy*s.y<0&&this.reboundingThisStep.add(e.id),A>=0&&t.vx*s.x+t.vy*s.y<0&&this.reboundingThisStep.add(t.id)),P>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,s,n,r,o,a){const d=-i.ny,h=i.nx,l=(t.vx-e.vx)*d+(t.vy-e.vy)*h,c=e.fixedPosition||t.fixedPosition?d**2*(n+o)+h**2*(r+a):n+o;if(Math.abs(l)<=_||c<=_)return;const u=H(e.friction,t.friction,this.options.friction),p=V(-l/c,-s*u,s*u),m=p*d,f=p*h;e.vx-=m*n,e.vy-=f*r,t.vx+=m*o,t.vy+=f*a}resolveColliders(e,t,i,s){if(0===t.length)return!1;let n=!1;for(let r=0;r<e.length;r++){const o=e[r];let a=s?.[r];!s||a&&N(o,a.bounds)||(s[r]=a=F(o,t));let d=0;for(;d<(a?a.indexes.length:t.length);){const e=a?a.indexes[d++]:d++,{collider:h,bounds:l}=t[e];if(!ne(h,o))continue;const c="segment"===h.shape.type?C(o,h.shape,.0050000010000000004,!0):R(o,h.shape,.0050000010000000004)??(Y(W(o),l)?te(o,h):null);if(!c)continue;n=!0,this.resolveStaticCollision(o,h,c),this.contactOpposesGravity(c.nx,c.ny)&&this.supportedThisStep.add(o.id);const u=r*t.length+e;if(i.has(u)||(i.add(u),this.lastEvents.push({type:"contact",bodyId:o.id,otherId:h.id,sensor:!1})),a&&s&&!N(o,a.bounds))for(s[r]=a=F(o,t),d=0;d<a.indexes.length&&a.indexes[d]<=e;)d++}}return n}resolveStaticCollision(e,t,i){e.x+=i.nx*Math.max(0,i.penetration-K),e.y+=i.ny*Math.max(0,i.penetration-K);const s=e.vx*i.nx+e.vy*i.ny;if(s<0){const n=U(e.restitution,t.restitution,this.options.restitution),r=this.options.gravity,o=e.vx*r.x+e.vy*r.y;e.vx-=(1+n)*s*i.nx,e.vy-=(1+n)*s*i.ny;const a=-i.ny,d=i.nx,h=e.vx*a+e.vy*d,l=H(e.friction,t.friction,this.options.friction)*-(1+n)*s,c=V(h,-l,l);e.vx-=c*a,e.vy-=c*d,n>0&&o>=0&&e.vx*r.x+e.vy*r.y<0&&this.reboundingThisStep.add(e.id)}S(e)}updateSensors(e){const t=this.sortedColliders().filter(e=>e.sensor);if(0===t.length&&0===this.activeSensors.size)return;const i=new Set;for(const s of e){const e=W(s);for(const n of t){if(!ne(n,s))continue;if(!Y(e,$(n)))continue;if(!te(s,n))continue;const t=ie(n.id,s.id);i.add(t),this.activeSensors.has(t)||this.lastEvents.push({type:"sensor-enter",bodyId:s.id,sensorId:n.id})}}for(const e of Array.from(this.activeSensors).sort()){if(i.has(e))continue;const{sensorId:t,bodyId:s}=se(e);this.lastEvents.push({type:"sensor-exit",bodyId:s,sensorId:t})}this.activeSensors=i}updateSleeping(e,t){const s=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const n of e){const e=Math.sqrt(n.vx*n.vx+n.vy*n.vy),r=Math.sqrt((n.x-n.prevX)*(n.x-n.prevX)+(n.y-n.prevY)*(n.y-n.prevY));!(e<this.options.sleepSpeed&&r<this.options.sleepSpeed*t&&!this.interpenetratingThisStep.has(n.id))||s&&!this.supportedThisStep.has(n.id)?n.sleeping?this.wake(n):n.sleepTime=0:(n.sleepTime+=t,!n.sleeping&&n.sleepTime>=this.options.sleepAfter&&(n.sleeping=!0,n.vx=0,n.vy=0,n.datum=i(n.datum,"settled"),this.lastEvents.push({type:"sleep",bodyId:n.id})))}}addSupportContact(e,t){let i=this.supportDependents.get(e);i?.has(t)||(this.supportContactsThisStep.add(e),this.supportContactsThisStep.add(t),i||(i=new Set,this.supportDependents.set(e,i)),i.add(t))}reconcileSupportedVelocity(e,t){const i=this.options.gravity;if(!(Math.hypot(i.x,i.y)<=1))for(const s of e)!s.sleeping&&this.supportedThisStep.has(s.id)&&this.supportContactsThisStep.has(s.id)&&(this.reboundingThisStep.has(s.id)&&s.vx*i.x+s.vy*i.y<0||(s.vx=(s.x-s.prevX)/t,s.vy=(s.y-s.prevY)/t,S(s)))}contactOpposesGravity(e,t,i){const{x:s,y:n}=this.options.gravity;return i??(i=Math.hypot(s,n)),i<=1e-9||(e*s+t*n)/i<-.2}wake(e){e.travel||(e.datum=i(e.datum,s(e.datum))),e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},oe=class{constructor(e={}){this.id="builtin",this.world=new re(e),this.capabilities={...this.world.capabilities,engine:"builtin"}}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,i){this.world.applyImpulse(e,t,i)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}readBody(e){return this.world.readBody(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)}workerSleepTimes(e){return this.world.workerSleepTimes(e)}applyWorkerMotion(e){this.world.applyWorkerMotion(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function ae(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):function(e={}){return new oe(e)}(t)}var de=["binId","targetBin","category","windowIndex","lane","group"];function he(){return{count:0,total:0,mean:0,m2:0,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY}}function le(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 i=t-e.mean;e.mean+=i/e.count;const s=t-e.mean;e.m2+=i*s}function ce(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 ue(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 pe(e,t){const i=e;if(null!=i[t])return i[t];const s=e.datum;return s&&"object"==typeof s?s[t]:void 0}function me(e,t,i){return"function"==typeof e?e(t,i):"string"==typeof e?pe(t,e):void 0}function fe(e){if(null==e)return;const t=String(e);return t.trim()?t:void 0}function ve(e){const t=ce(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:ce(e.x),y:ce(e.y),value:t}}var ye=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 i=fe(me(this.config.binAccessor,e,t))??function(e){for(const t of de){const i=fe(pe(e,t));if(i)return i}return"sediment"}(e),s=fe(me(this.config.labelAccessor,e,t))??i,n=function(e,t,i){if("number"==typeof e)return e;const s="function"==typeof e?e(t,i):"string"==typeof e?pe(t,e):1,n="number"==typeof s?s:Number(s);return Number.isFinite(n)?n:1}(this.config.valueAccessor,e,t),r=Math.max(0,Math.floor(this.config.retainBodyIds??12));let o=this.bins.get(i);return o||(o={id:i,label:s,bodyIds:[],x:he(),y:he(),value:he()},this.bins.set(i,o)),o.label=s,o.lastBodyId=e.id,o.lastDatum=e.datum,le(o.x,e.x),le(o.y,e.y),le(o.value,n),r>0&&(o.bodyIds.push(e.id),o.bodyIds.length>r&&(o.bodyIds=o.bodyIds.slice(o.bodyIds.length-r))),ve(o)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(ve)}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:ue(t.x),y:ue(t.y),value:ue(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 ge(e){const t=Number(e);if(Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function we(e){const t=Math.max(0,Math.floor(e.liveBodies)),i=Math.max(0,Math.floor(e.queuedBodies??0)),s=t+i,n=ge(e.bodyLimit),r=ge(e.engineMaxBodiesHint),o=function(e,t,i){if(!1===i)return;const s=ge(i?.warnAt);return null!=s?s:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(n,r,e.options),a=null==n?0:Math.max(0,t-n),d=a>0?"overflow":null!=o&&s>=o?"warning":"ok";return{action:"overflow"!==d?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:n,engineMaxBodiesHint:r,liveBodies:t,overflow:a,projectedBodies:s,queuedBodies:i,state:d,warnAt:o}}var xe={bodyLimit:Number.POSITIVE_INFINITY,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1,viewTransform:{x:0,y:0}};function be(e,t,i){return{...e,timestamp:e.timestamp??t,chartType:e.chartType??i.chartType,chartId:e.chartId??i.chartId}}var Se={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function Me(e={},t=Se){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 Ie(t){return{...t,shape:{...t.shape},...t.travel?{travel:e(t.travel)}:{},...t.fixedPosition?{fixedPosition:{...t.fixedPosition}}:{},datum:t.datum,springs:t.springs?.map(e=>({...e,target:{...e.target}}))}}function Te(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 ke(e,t){const i=e;if(null!=i[t])return i[t];const s=e.datum;return s&&"object"==typeof s?s[t]:void 0}function Pe(e,t={}){const i=Te(t.startAt)??0,s=t.pacing??"immediate";if("arrival"===s){let s=1/0;const n=e.map((e,i)=>{const n=function(e,t,i){return"function"==typeof i?Te(i(e,t)):"string"==typeof i?Te(ke(e,i)):Te(e.spawnAt)??Te(ke(e,"arrivalTime"))??Te(ke(e,"timestamp"))??Te(ke(e,"time"))??Te(ke(e,"eventTime"))}(e,i,t.timeAccessor);return null!=n&&(s=Math.min(s,n)),n}),r=Te(t.timeScale)??1,o=r>0?r:1;return e.map((e,t)=>{const r=n[t],a=null==r?0:Math.max(0,r-s);return{...Ie(e),spawnAt:i+a/o}})}if("object"==typeof s){const t=Te(s.ratePerSec);if(t&&t>0)return e.map((e,s)=>({...Ie(e),spawnAt:i+s/t}))}return e.map(e=>({...Ie(e),spawnAt:i}))}function qe(e){return{...Ie(e),sequence:e.sequence,spawnAt:e.spawnAt}}function Ee(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 Ae(e){return!1!==e&&{...e}}function Be(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function De(e){return{...e,gravity:{...e.gravity}}}function Oe(e,t,i,s){if("circle"===e.shape.type){const n=e.x-t,r=e.y-i,o=e.shape.radius+s,a=n*n+r*r;return a<=o*o?a:null}const n=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),r=Math.max(Math.abs(i-e.y)-e.shape.height/2,0),o=n*n+r*r;return o<=s*s?o:null}function Re(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function Ce(e,t={}){const{idPrefix:i="plot",includeFloor:s=!0,includeCeiling:n=!1,includeLeftWall:r=!0,includeRightWall:o=!0,wallThickness:a=20,floorThickness:d=a}=t,h=[],l=e.x+e.width/2,c=e.y+e.height/2,u=(e,t,s,n,r)=>{h.push({id:`${i}-${e}`,shape:{type:"aabb",x:t,y:s,width:n,height:r}})};return s&&u("floor",l,e.y+e.height+d/2,e.width+2*a,d),n&&u("ceiling",l,e.y-d/2,e.width+2*a,d),r&&u("left-wall",e.x-a/2,c,a,e.height+2*d),o&&u("right-wall",e.x+e.width+a/2,c,a,e.height+2*d),h}var Ne={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 Fe(e,t){const i={...e};for(const e of t){i[Ne[e]]++}return i}function ze(e,t,i){const s=new Set(t);return{changeSet:{...e,...e.keys?{keys:[...e.keys]}:{}},changed:s,revisions:Fe(i,s)}}var We=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=ze({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 i=ze(e,t,this.revisions);this.revisions=i.revisions,this.latest=i;for(const e of[...this.listeners])e();return i}};import{quadtree as $e}from"d3-quadtree";var Ye=class{constructor(){this.order=new Map,this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,i,s,n,r=0,o){const a=this.ensure(e,t,i);if(!a)return null;let d=null,h=Number.POSITIVE_INFINITY;const l=Math.max(0,o?.searchRadius??Math.max(0,r)+this.maxSearchRadius),c=s-l,u=s+l,p=n-l,m=n+l;return a.visit((e,t,i,a,l)=>{if(a<c||t>u||l<p||i>m)return!0;if(e.length)return!1;let f=e;for(;f;){const e=f.data;if(e&&(!o?.include||o.include(e))){const t=o?.distanceSquared?o.distanceSquared(e,s,n):Oe(e,s,n,Math.max(0,r));null!=t&&(t<h||t===h&&(this.order.get(e.id)??-1)>(this.order.get(d?.id??"")??-1))&&(d=e,h=t)}f=f.next}return!1}),d}ensure(e,t,i){if(this.tree&&this.revision===t)return this.tree;this.order=new Map(Array.from(i,(e,t)=>[e,t]));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=$e().x(e=>e.x).y(e=>e.y).addAll(s),this.revision=t,this.tree)}};function Xe(e){return{...e,...e.viewTransform&&{viewTransform:{...e.viewTransform}},...e.colliders&&{colliders:Ee(e.colliders)},...e.kernel&&{kernel:{...e.kernel,...e.kernel.gravity&&{gravity:{...e.kernel.gravity}}}}}}var je=["data","scene-geometry","data-paint","accessibility","evidence"],Le=["scene-geometry","data-paint","accessibility","evidence"],_e=["overlay","accessibility","evidence"],Ke=(e,t)=>({retainedData:e,invalidations:t}),Ve=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],Ue=["scene-geometry","data-paint","accessibility","evidence"],He=[],Ge={engine:Ke("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:Ke("preserve",Ue),colliders:Ke("preserve",Ue),sediment:Ke("preserve",Ue),bodyBudget:Ke("preserve",Ve),bodyLimit:Ke("preserve",Ve),eviction:Ke("preserve",Ve),fixedDt:Ke("preserve",He),maxDeltaSeconds:Ke("preserve",He),maxSubsteps:Ke("preserve",He),settleStepLimit:Ke("preserve",He),timeScale:Ke("preserve",He),observation:Ke("preserve",He)},Qe=Ke("preserve",Ve);function Je(e){let t="preserve";const i=new Set;for(const s of e){const e=Object.prototype.hasOwnProperty.call(Ge,s)?Ge[s]:Qe;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)i.add(t)}return{retainedData:t,invalidations:i}}var Ze=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function et(e,t){return e===t||!(!e||!t)&&(e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&Ze.every(i=>e[i]===t[i]))}function tt(e,t){if(e.readBody){if(!t)return t=>e.readBody(t);const i=new Map;for(const s of t)i.has(s)||i.set(s,e.readBody(s));return e=>i.get(e)}const i=new Map(e.readState().map(e=>[e.id,e]));return e=>i.get(e)}function it(e,t){for(const i of e)t.has(Re(i).bodyId)&&e.delete(i)}function st(e,t,i,s){return e||!t?"paused":i||!s?"running":"settled"}var nt=class{constructor(){this.heap=[]}get length(){return this.heap.length}firstArrival(){return this.heap[0]?.spawnAt}lastArrival(){return this.latest}push(e){this.latest=Math.max(this.latest??-1/0,e.spawnAt);let t=this.heap.length;for(this.heap.push(e);t>0;){const i=t-1>>>1;if(Be(this.heap[i],e)<=0)break;this.heap[t]=this.heap[i],t=i}this.heap[t]=e}shift(){const e=this.heap[0],t=this.heap.pop();if(0===this.heap.length)return this.latest=void 0,e;if(!t)return e;let i=0;for(;2*i+1<this.heap.length;){let e=2*i+1;if(e+1<this.heap.length&&Be(this.heap[e+1],this.heap[e])<0&&(e+=1),Be(t,this.heap[e])<=0)break;this.heap[i]=this.heap[e],i=e}return this.heap[i]=t,e}clear(){this.heap=[],this.latest=void 0}remove(e){const t=new Set,i=this.heap.filter(i=>!e.has(i.id)||(t.add(i.id),!1));return t.size&&this.restore(i),t}sorted(){return this.heap.slice().sort(Be)}restore(e){this.clear();for(const t of e)this.push(t)}};var rt={};function ot(e){const t=rt[e];if(!t)throw new Error(`Physics ${e} configuration requires registerPhysicsLivePrograms() from semiotic/physics before a PhysicsPipelineStore is created or restored with it.`);return t}var at=class e{configure(e,t){!1===e.emitters?this.emitters=void 0:e.emitters&&(this.emitters?this.emitters.update(e.emitters):this.emitters=ot("emitters").create(e.emitters)),!1===e.eventDrop?this.eventDrop=void 0:e.eventDrop&&(this.eventDrop?this.eventDrop.update(e.eventDrop,t):this.eventDrop=ot("eventDrop").create(e.eventDrop),t.setColliders(this.eventDrop.colliders()))}backlog(){return Boolean(this.eventDrop?.backlog())}ownsClock(){return Boolean(this.eventDrop||this.emitters?.pending())}pending(){return this.backlog()||Boolean(this.emitters?.pending()||this.eventDrop?.continuous())}snapshot(){return{...this.emitters&&{emitters:this.emitters.snapshot()},...this.eventDrop&&{eventDrop:this.eventDrop.snapshot()}}}static restore(t){const i=new e;return t.emitters&&(i.emitters=ot("emitters").restore(t.emitters)),t.eventDrop&&(i.eventDrop=ot("eventDrop").restore(t.eventDrop)),i}};function dt(e,t,i,s,n,r){const o={evicted:[],sedimented:[],liveBodyOrder:n};if(!1===i)return o;const a=Math.max(0,Math.floor(s));if(!Number.isFinite(a))return o;const d=n.size-a;if(d<=0)return o;const h=function(e,t,i){if("sleeping-first"!==t)return Array.from(i);const s=new Map(e.readState().map(e=>[e.id,e.sleeping])),n=[],r=[];for(const e of i)s.get(e)?n.push(e):r.push(e);return[...n,...r]}(e,i,n),l=h.slice(0,d);if(0===l.length)return o;const c=function(e,t,i,s){if(!t.isEnabled())return[];const n=tt(e,i),r=[];for(const e of i){const i=n(e);if(!i)continue;const o=t.add(i);o&&(r.push(e),s.emit({type:"physics-sediment",timestamp:s.elapsedSeconds,chartType:s.observation.chartType,chartId:s.observation.chartId,bodyId:e,datum:i.datum,x:i.x,y:i.y,binId:o.id,count:o.count,total:o.total}))}return r}(e,t,l,r);e.remove(l);const u=new Set(l);return{evicted:l,sedimented:c,liveBodyOrder:new Set(Array.from(n).filter(e=>!u.has(e)))}}var ht=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,i){if(i>0)return void(this.seconds=0);if(e.allSleeping())return void(this.seconds+=Math.max(0,t));const s=e.readState(this.scratch),n=this.speed*this.speed;let r=!0;for(const e of s){if(e.travel){r=!1;break}if(e.sleeping)continue;const i=e.x-e.prevX,s=e.y-e.prevY;if(e.vx*e.vx+e.vy*e.vy>=n||t>0&&i*i+s*s>=n*t*t){r=!1;break}}this.seconds=r?this.seconds+Math.max(0,t):0}};function lt(e,t,i,s={}){let n,r=0,o=0;const a=t+(s.drainArrivals?Math.max(0,Math.ceil(((e.lastArrival()??e.elapsed())-e.elapsed())/e.fixedDt)):0);for(;r+o<a&&!s.shouldStop?.()&&(!1===s.stopAtRest||e.queueSize()>0||!e.atRest()||s.continueWhile?.());){const t=e.nextArrival(),d=s.skipIdle&&null!=t&&e.atRest()?Math.min(Math.max(0,Math.floor((t-e.elapsed())/e.fixedDt)-1),Math.max(0,a-r-o-1)):0;d>0&&(e.advanceTime(d*e.fixedDt),o+=d),e.step(e.fixedDt),e.advanceTime(e.fixedDt);const h=e.drainEvents();i.events&&(i.events.push(...h),e.observeKernelEvents(h,i.observations),e.observeSensorTransitions(i.observations));const l=[];if(e.spawnDue(l,i.observations),l.length>0){i.spawned.push(...l),n=e.observeBodyBudget(i.observations);const t=e.evictOverflow(i.observations);i.evicted?.push(...t.evicted),i.sedimented?.push(...t.sedimented)}r+=1,e.refreshQuiescence(e.fixedDt,l.length),s.afterStep?.()}return{steps:r,budget:n}}var ct=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new Ye,this.elapsedSeconds=0,this.liveBodyOrder=new Set,this.nextSequence=0,this.paused=!1,this.queue=new nt,this.revision=0,this.observedInitialBoundary=!1,this.updateResults=new We,this.simulationState="settled",this.visible=!0,this.quiescence=new ht,this.programs=new at,v(e);const{bodyBudget:t,colliders:i,engine:s,kernel:n,observation:r,sediment:o,emitters:a,eventDrop:d,...h}=e;this.config={...xe,...h,viewTransform:{...h.viewTransform??xe.viewTransform}},this.configInput=Xe(e),this.bodyBudget=t??{},this.engineInput=s,this.observation=Me(r),this.sediment=new ye(o??!1),this.world=ae(s,{fixedDt:this.config.fixedDt,...n}),this.quiescence.setKernelOptions(n),i&&this.world.setColliders(Ee(i)),this.programs.configure({emitters:a,eventDrop:d},this.world)}updateConfig(e){v(e);const t=function(e,t){return Object.keys(e).filter(i=>"viewTransform"===i?e.viewTransform?.x!==t.viewTransform?.x||e.viewTransform?.y!==t.viewTransform?.y:"colliders"===i?!g(e.colliders,t.colliders):"kernel"===i?!et(e.kernel,t.kernel):e[i]!==t[i])}(e,this.configInput),{colliders:i,bodyBudget:s,engine:n,kernel:r,observation:o,sediment:a,emitters:d,eventDrop:h,...l}=e;if(this.programs.configure({emitters:d,eventDrop:h},this.world),this.config={...this.config,...l,viewTransform:{...l.viewTransform??this.config.viewTransform}},t.includes("eventDrop")&&(this.revision+=1),void 0!==s&&(this.bodyBudget=s,!1===s&&(this.bodyBudgetObservationKey="ok")),n&&n!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=n,this.world=ae(n,e.options),this.world.restore(e),this.revision+=1}if(r&&!et(r,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...r,gravity:{...e.options.gravity,...r.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}o&&(this.observation=Me(o,this.observation)),this.sediment.updateConfig(a),i&&t.includes("colliders")&&(this.world.setColliders(Ee(i)),this.revision+=1),this.configInput=Xe({...this.configInput,...e});const c=Je(t);this.updateResults.record({kind:"config",keys:t},c.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(Ee(e)),this.configInput={...this.configInput,colliders:Ee(e)},this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},Je(["colliders"]).invalidations)}enqueue(e,t){const i=function(e,t,i,s,n){const r=Array.isArray(t)?t:[t];for(const e of r)u(e);const o=i?Pe(r,{...i,startAt:i.startAt??s}):r;if(i)for(const e of o)u(e);for(const t of o)e.push({...Ie(t),sequence:n++,spawnAt:t.spawnAt??s});return o.length}(this.queue,e,t,this.elapsedSeconds,this.nextSequence);this.nextSequence+=i,i>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:i},i?je:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(Ie(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},je)}materializeDueSpawns(){const e=this.revision,t=[],i=[];return this.spawnDue(t,i),0===t.length||(this.observeBodyBudget(i),this.evictOverflow(i),this.syncSimulationState(i),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?je:[])),t}clear(){this.observedInitialBoundary=!1;const{options:e,colliders:t}=this.world.snapshot();this.world.init({...e,fixedDt:this.config.fixedDt}),this.world.setColliders(t),this.activeSensorPairs.clear(),this.liveBodyOrder.clear(),this.queue.clear(),this.accumulator=0,this.elapsedSeconds=0,this.programs=new at,this.programs.configure(this.configInput,this.world),this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},je)}tick(e,t){const i=this.revision,s=[],n=[],r=[],o=[],a=[];if(this.paused||!this.visible){const e=this.result(0,s,n,r,o,a,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const d=Math.max(0,Math.min(Number.isFinite(e)?e:0,this.config.maxDeltaSeconds))*this.config.timeScale;this.spawnDue(s,a);const h=this.observeBodyBudget(a),l=this.evictOverflow(a);n.push(...l.evicted),r.push(...l.sedimented),this.syncSimulationState(a),s.length>0&&this.quiescence.reset(),this.accumulator+=d;const c=this.stepObserver(t,{spawned:s,evicted:n,sedimented:r,events:o,observations:a}),u=d>0?Math.floor((this.accumulator+1e-9*this.config.fixedDt)/this.config.fixedDt):0,{steps:p,budget:m}=lt(this.settleHost(),Math.min(u,this.config.maxSubsteps),{spawned:s,evicted:n,sedimented:r,events:o,observations:a},{stopAtRest:!1,shouldStop:()=>this.paused||!this.visible,afterStep:c});this.accumulator=Math.max(0,this.accumulator-p*this.config.fixedDt),p===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),(p>0||s.length>0||n.length>0||r.length>0||o.length>0)&&(this.revision+=1);const f=this.result(p,s,n,r,o,a,void 0,m??h);return this.updateResults.record({kind:"tick",count:p},this.revision!==i?s.length||n.length||r.length?je:Le:[]),f}settle(e){return this.runSettle(e,!1).steps}settleWithObservations(e,t){return this.runSettle(e,!0,t)}stepObserver(e,t){const i=!this.observedInitialBoundary;return e&&(this.observedInitialBoundary=!0),function(e,t,i=!1){if(!e)return;const s=["spawned","evicted","sedimented","events","observations"],n={spawned:0,evicted:0,sedimented:0,events:0,observations:0},r=r=>{const o=t(r),a={...o};s.forEach(e=>{a[e]=o[e].slice(n[e]),n[e]=o[e].length}),0===r&&!i&&s.every(e=>0===a[e].length)||e.onStep(a)};return r(0),()=>r(1)}(e,e=>(e&&(this.revision+=1),this.result(e,t.spawned,t.evicted,t.sedimented,t.events,t.observations)),i)}settleHost(e=!1){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length+Number(e?this.programs.backlog():this.programs.ownsClock()),atRest:()=>this.atRest(),elapsed:()=>this.elapsedSeconds,nextArrival:()=>this.queue.firstArrival(),lastArrival:()=>function(e,t,i){let s=e;for(const i of t)i.travel&&(s=Math.max(s,e+i.travel.durationSeconds-(i.travel.elapsedSeconds??0)));for(const e of i)s=Math.max(s,e.spawnAt+(e.travel?e.travel.durationSeconds-(e.travel.elapsedSeconds??0):0));return s}(this.elapsedSeconds,this.readBodies(),this.queue.sorted()),advanceTime:t=>{this.elapsedSeconds+=t;const i=this.programs.emitters?.advance(t,e);i?.length&&this.enqueue(i)},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)=>function(e,t,i){const s=t.filter(e=>"sleep"===e.type);if(0===s.length)return;const n=tt(e,s.map(e=>e.bodyId));for(const e of s){const t=n(e.bodyId);i.emit({type:"physics-settle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t)),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t,i){const s=this.revision,n=[],r=[],o=[],a=[],d=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,n,r,o,a,d??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,d);const h=this.observeBodyBudget(d),l=this.evictOverflow(d);r.push(...l.evicted),o.push(...l.sedimented),this.syncSimulationState(d),n.length>0&&this.quiescence.reset();const c=t?{spawned:n,evicted:r,sedimented:o,events:a,observations:d}:{spawned:n},u=this.stepObserver(i,{spawned:n,evicted:r,sedimented:o,events:a,observations:d??[]}),{steps:p,budget:m}=lt(this.settleHost(void 0===e),e??this.config.settleStepLimit,c,{afterStep:u,continueWhile:i?.continueWhile,shouldStop:t?()=>this.paused||!this.visible:void 0,drainArrivals:void 0===e,skipIdle:void 0===e&&!i&&!this.programs.pending()}),f=n.length+r.length+o.length>0;(p>0||f||a.length>0)&&(this.revision+=1);const v=this.result(p,n,r,o,a,d??[],void 0,m??h);return this.updateResults.record({kind:"settle",count:p},this.revision===s?[]:f?je:Le),v}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:i=0,binWidth:s=24,gap:n=2,maxHeight:r=80,value:o="count",x:a}=t,d=e.reduce((e,t)=>Math.max(e,t[o]),1);return e.map((e,t)=>{const h=Math.max(0,e[o]/d*r),l=a?.(e,t)??t*(s+n);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:l,y:i-h,width:s,height:h,meanX:e.x.mean,meanY:e.y.mean}})}(this.readSediment(),e)}hitTest(e,t,i=0,s){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,i,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()||this.programs.pending()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.size}elapsed(){return this.elapsedSeconds}recordObservation(e){const t=be(e,this.elapsedSeconds,this.observation);return this.emitObservation(t),this.updateResults.record({kind:"update",count:1},["evidence"]),t}recordLifecycleObservation(e){return this.updateResults.record({kind:"update",count:1},["evidence"]),be(e,this.elapsedSeconds,this.observation)}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?_e:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?_e:[])}remove(e){const t=new Set(e),i=new Set(this.liveBodyOrder),s=this.queue.remove(t);for(const t of e)this.liveBodyOrder.delete(t);this.world.remove(e),it(this.activeSensorPairs,t);const n=e.filter(e=>i.has(e)||s.has(e));return n.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:n,count:n.length},n.length?je:[]),n}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},Le),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},Le)}applyImpulse(e,t,i){this.world.applyImpulse(e,t,i),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},Le)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,i,s)=>e.applyImpulse(t,i,s),clear:()=>e.clear(),hitTest:(t,i,s)=>e.hitTest(t,i,s),pause:()=>e.setPaused(!0),push:(t,i)=>e.enqueue(t,i),pushMany:(t,i)=>e.enqueue(t,i),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}runtimeState(){return{elapsedSeconds:this.elapsedSeconds,timeScale:this.config.timeScale,fixedDt:this.config.fixedDt,paused:this.paused,visible:this.visible,simulationState:this.simulationState}}eventDropState(){return this.programs.eventDrop?{metadata:this.programs.eventDrop.metadata(),viewTransform:this.programs.eventDrop.viewTransform(),lifecycleEvents:[]}:void 0}viewTransform(){return this.programs.eventDrop?.viewTransform()??{...this.config.viewTransform}}isEventDropLive(){return Boolean(this.programs.eventDrop)}enqueueSequence(){return this.nextSequence}workerLiveDelta(){return this.programs.eventDrop?.drainWorkerDelta()}workerStructure(){return{world:this.world.snapshot(),queue:this.queue.sorted().map(qe),liveBodyOrder:Array.from(this.liveBodyOrder),sediment:this.readSediment()}}workerState(){return{...this.programs.emitters&&{emitterProgress:this.programs.emitters.progress()},nextSequence:this.nextSequence,accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs),elapsedSeconds:this.elapsedSeconds,paused:this.paused,revision:this.revision,simulationState:this.simulationState,visible:this.visible}}workerSleepTimes(e){return this.world.workerSleepTimes?.(e)}applyWorkerFrame(e){if(e.snapshot){const t=this.configInput;return this.restore(e.snapshot),void(this.configInput=t)}if(!e.state||!this.world.applyWorkerMotion)throw new Error("Physics worker motion frame requires a built-in mirror");e.structure?(this.world.restore(e.structure.world),this.queue.restore(e.structure.queue.map(qe)),this.liveBodyOrder=new Set(e.structure.liveBodyOrder),this.sediment.restore(e.structure.sediment),this.bodySpatialIndex=new Ye):e.state.revision===this.revision&&e.state.elapsedSeconds===this.elapsedSeconds||this.world.applyWorkerMotion(e),e.live&&this.programs.eventDrop?.applyWorkerDelta(e.live,this.world);const t=this.simulationState,{emitterProgress:i,...s}=e.state;i&&this.programs.emitters?.restoreProgress(i),Object.assign(this,s,{activeSensorPairs:new Set(e.state.activeSensorPairs)}),this.updateResults.record({kind:"tick"},Le),t!==this.simulationState&&this.observation.onSimulationStateChange?.(this.simulationState,t)}snapshot(){const e=this.world.snapshot();return{...this.workerState(),nextSequence:this.nextSequence,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:Ae(this.bodyBudget),config:{...this.config,viewTransform:{...this.config.viewTransform},kernel:De(e.options)},queue:this.queue.sorted().map(qe),sediment:this.readSediment(),liveBodyOrder:Array.from(this.liveBodyOrder),world:e,...this.programs.snapshot()}}restore(e){!function(e){if(h(e.activeSensorPairs,"Physics activeSensorPairs"),h(e.liveBodyOrder,"Physics liveBodyOrder"),d(e.queue,"Physics queue"),null!=e.sediment){d(e.sediment,"Physics sediment");for(const t of e.sediment){if(!t)throw new RangeError("Physics sediment requires bin records");h(t.bodyIds,"Physics sediment.bodyIds"),o(t.count,"Physics sediment.count");for(const e of["x","y","value"]){const i=t[e];if(!i)throw new RangeError("Physics sediment requires statistics");for(const t of["count","total","mean","min","max","variance"])o(i[t],`Physics sediment.${e}.${t}`)}}}v(e.config),f(e.world);for(const t of e.queue)u(t),o(t.sequence,"Physics queue sequence");if(o(e.elapsedSeconds,"Physics elapsedSeconds"),o(e.accumulator,"Physics accumulator"),null!=e.nextSequence&&(!Number.isSafeInteger(e.nextSequence)||e.nextSequence<0||e.queue.some(t=>t.sequence>=e.nextSequence)))throw new RangeError("Physics nextSequence must exceed queued sequence numbers")}(e);const t=at.restore(e);this.bodySpatialIndex=new Ye,this.programs=t,this.observedInitialBoundary=!1;const i=this.simulationState;Object.assign(this,function(e){const t={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,viewTransform:{...e.config.viewTransform??{x:0,y:0}}};return{config:t,configInput:Xe({...t,bodyBudget:Ae(e.bodyBudget??{}),kernel:De(e.world.options),...e.emitters&&{emitters:e.emitters.options},...e.eventDrop&&{eventDrop:e.eventDrop.config}}),bodyBudget:Ae(e.bodyBudget??{}),activeSensorPairs:new Set(e.activeSensorPairs),accumulator:e.accumulator,elapsedSeconds:e.elapsedSeconds,paused:e.paused,revision:e.revision,visible:e.visible,liveBodyOrder:new Set(e.liveBodyOrder),nextSequence:e.nextSequence??e.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,simulationState:e.simulationState??st(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping))}}(e)),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.queue.restore(e.queue.map(qe)),this.sediment.restore(e.sediment??[]),this.world.restore(e.world),this.updateResults.record({kind:"restore"},je),this.simulationState!==i&&this.observation.onSimulationStateChange?.(this.simulationState,i)}spawnDue(e,t){for(;this.queue.length>0&&this.queue.firstArrival()<=this.elapsedSeconds+1e-9*this.config.fixedDt;){const i=this.queue.shift();if(!i)return;this.spawnOne(i,t),e.push(i.id)}if(this.programs.eventDrop){const e=this.programs.eventDrop.advance(this.world,this.elapsedSeconds);e.length&&this.remove(e);for(const e of this.programs.eventDrop.ledger.drainEvents())this.emitObservation(be(e,this.elapsedSeconds,this.observation),t)}}spawnOne(e,t){this.programs.eventDrop&&(e=this.programs.eventDrop.prepare(e,this.elapsedSeconds)),u(e),this.liveBodyOrder.delete(e.id)&&it(this.activeSensorPairs,new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.add(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});(t||this.observation.onObservation)&&function(e,t,i){const s=tt(e)(t.id);i.emit({type:"physics-spawn",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:t.id,datum:s?.datum??t.datum,x:s?.x??t.x,y:s?.y??t.y})}(this.world,e,this.observationContext(t))}result(e,t,i,s,n,r,o,a=this.evaluateBodyBudget()){this.syncSimulationState(r);const d=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:i,events:n,observations:r,queueSize:this.queue.length,revision:this.revision,shouldContinue:o??(!this.paused&&this.visible&&this.hasPendingWork()),sleeping:d,sedimented:s,spawned:t,steps:e}}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,i){const s=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));let n=s.size!==t.size;if(!n)for(const e of s)if(!t.has(e)){n=!0;break}if(!n)return s;const r=Array.from(s).filter(e=>!t.has(e)).sort(),o=Array.from(t).filter(e=>!s.has(e)).sort(),a=tt(e,[...r,...o].map(e=>Re(e).bodyId)),d=(e,t)=>{const{sensorId:s,bodyId:n}=Re(t),r=i.observation.sensors[s],o=a(n);i.emit({type:"enter"===e?r?.enterType??"physics-bin-enter":r?.exitType??"physics-bin-exit",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:n,datum:o?.datum,x:o?.x,y:o?.y,sensorId:s,binId:r?.binId??s})};for(const e of r)d("enter",e);for(const e of o)d("exit",e);return s}(this.world,this.activeSensorPairs,this.observationContext(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 we({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.size,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();return this.bodyBudgetObservationKey=function(e,t,i,s){if(!t||"ok"===e.state)return"ok";const n=`${e.state}:${e.action}`;return n!==i&&function(e,t){t.emit({type:"overflow"===e.state?"physics-budget-overflow":"physics-budget-warning",timestamp:t.elapsedSeconds,chartType:t.observation.chartType,chartId:t.observation.chartId,budgetAction:e.action,bodyLimit:e.bodyLimit,engineMaxBodiesHint:e.engineMaxBodiesHint,liveBodies:e.liveBodies,overflow:e.overflow,projectedBodies:e.projectedBodies,queuedBodies:e.queuedBodies,warnAt:e.warnAt})}(e,s),n}(t,!1!==this.bodyBudget,this.bodyBudgetObservationKey,this.observationContext(e)),t}syncSimulationState(e){const t=st(this.paused,this.visible,this.queue.length>0||this.programs.pending(),this.atRest());if(t===this.simulationState)return;const i=this.simulationState;this.simulationState=t,function(e,t,i){i.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||i.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,simulationState:t,previousSimulationState:e})}(i,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:i,liveBodyOrder:s}=dt(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=s,it(this.activeSensorPairs,new Set(t))),{evicted:t,sedimented:i}}};var ut=[{weight:.25,min:0,max:0},{weight:.35,min:0,max:2e3},{weight:.2,min:2e3,max:5e3},{weight:.1,min:5e3,max:1e4},{weight:.1,min:1e4,max:15e3}];function pt(e,t){if(!Number.isFinite(e)||e<=0)throw new RangeError(`${t} must be finite and positive`);return e}function mt(e){const{jitter:t}=e.spec;if(!t||"none"===t)return 0;if("function"==typeof t){const i=t(e.random);if(!Number.isFinite(i)||i<0)throw new RangeError("jitter must return a finite nonnegative delay");return i}const i="watermarks"===t?ut:t.buckets;let s=e.random()*i.reduce((e,t)=>e+t.weight,0);for(const t of i)if(s-=t.weight,s<0)return t.min+e.random()*(t.max-t.min);return i[i.length-1].max}function ft(e,t){e.remainingError=0;const i={id:`${e.spec.id}-${e.sequence++}`,source:e.spec.id,eventTime:t-mt(e),arrivalTime:t},s=e.spec.burst;return s?(0===e.burstRemaining&&(e.burstRemaining=s.min+Math.floor(e.random()*(s.max-s.min+1))),e.burstRemaining--,e.remaining=e.burstRemaining>0?s.intraMs:s.gapMs?s.gapMs[0]+e.random()*(s.gapMs[1]-s.gapMs[0]):e.interval):e.remaining=e.interval,i}function vt(e,t){const i=-t-e.remainingError,s=e.remaining+i;e.remainingError=s-e.remaining-i,e.remaining=s}function yt(e,t=1,i={}){const s=function(e,t){const i=new Set;return e.map((e,s)=>{if(!e.id||i.has(e.id))throw new Error("Synthetic source ids must be nonempty and unique");i.add(e.id);const n=pt(e.interval??1e3/pt(e.ratePerSec??1,"ratePerSec"),"interval"),r=e.burst;if(r){if(!Number.isInteger(r.min)||!Number.isInteger(r.max)||r.min<1||r.max<r.min)throw new RangeError("burst bounds must be ordered positive integers");if(pt(r.intraMs,"intraMs"),r.gapMs&&(pt(r.gapMs[0],"gapMs"),pt(r.gapMs[1],"gapMs"),r.gapMs[1]<r.gapMs[0]))throw new RangeError("gapMs must be ordered")}const o=e.jitter;if("object"==typeof o&&(!o.buckets.length||!o.buckets.some(e=>e.weight>0)||o.buckets.some(e=>!Number.isFinite(e.weight)||e.weight<0||!Number.isFinite(e.min)||e.min<0||!Number.isFinite(e.max)||e.max<e.min)))throw new RangeError("jitter buckets require nonnegative finite weights and ordered delays");return{spec:e,random:b(t+2654435769*s),interval:n,remaining:n,remainingError:0,burstRemaining:0,sequence:0}})}(e,t);for(const[e,t]of Object.entries(i))if(void 0!==t&&(!Number.isFinite(t)||t<0))throw new RangeError(`${e} must be finite and nonnegative`);if(void 0!==i.maxEvents&&!Number.isSafeInteger(i.maxEvents))throw new RangeError("maxEvents must be a safe integer");const n=i.durationMs??1/0,r=i.maxEvents??1/0;let o=0,a=0,d=0;const h=()=>0===s.length||a>=n||o>=r;return{getTime:()=>a,getEmittedCount:()=>o,isComplete:h,snapshot:()=>({version:1,time:a,timeError:d,emitted:o,sources:s.map(e=>({id:e.spec.id,randomState:e.random.getState(),remaining:e.remaining,remainingError:e.remainingError,burstRemaining:e.burstRemaining,sequence:e.sequence}))}),restore(e){if(1!==e.version||!Number.isFinite(e.time)||e.time<0||e.time>n||!Number.isFinite(e.timeError)||!Number.isSafeInteger(e.emitted)||e.emitted<0||e.emitted>r||e.sources.length!==s.length||e.sources.some((e,t)=>e.id!==s[t].spec.id||!Number.isInteger(e.randomState)||e.randomState<0||e.randomState>4294967295||!Number.isFinite(e.remaining)||e.remaining<0||!Number.isFinite(e.remainingError)||!Number.isSafeInteger(e.sequence)||e.sequence<0||!Number.isSafeInteger(e.burstRemaining)||e.burstRemaining<0||e.burstRemaining>=(s[t].spec.burst?.max??1))||e.sources.reduce((e,t)=>e+t.sequence,0)!==e.emitted)throw new RangeError("Invalid or incompatible synthetic emitter snapshot");a=e.time,d=e.timeError,o=e.emitted,e.sources.forEach((e,t)=>{const{id:i,randomState:n,...r}=e;Object.assign(s[t],r,{random:b(n)})})},advance(e,t={}){if(!Number.isFinite(e)||e<0)throw new RangeError("deltaMs must be finite and nonnegative");const i=pt(t.rate??1,"rate");if(t.paused||0===e||h())return[];e=Math.min(e,n-a);const l=[],c=s.filter(e=>!1!==t.active?.[e.spec.id]);let u=0,p=0,m=e;for(;m>0;){const t=c.reduce((e,t)=>!e||t.remaining<e.remaining?t:e,void 0),s=t?t.remaining/i:1/0,n=16*Number.EPSILON*Math.max(e,s);if(!t||s-m>n){for(const e of c)vt(e,m*i);break}const d=Math.min(m,Math.max(0,s));for(const e of c)vt(e,d*i);const h=d-p,f=u+h;p=f-u-h,u=f,m=Math.max(0,e-u);const v=a+Math.min(e,u);for(const e of c)if((e===t||e.remaining/i<=n)&&(l.push(ft(e,v)),o++,o>=r))break;if(o>=r){e=u;break}}const f=e-d,v=a+f;return d=v-a-f,a=v,l}}}var gt=class e{constructor(e){this.options=e,this.validate(e),this.emitter=yt(e.sources,e.seed,{durationMs:e.durationMs,maxEvents:e.maxEvents})}validate(e){if(null!=e.originTime&&!Number.isFinite(e.originTime))throw new RangeError("Emitter originTime must be finite");if(null!=e.rate&&(!Number.isFinite(e.rate)||e.rate<=0))throw new RangeError("Emitter rate must be finite and positive");for(const t of e.sources){const i=e.templates[t.id];if(!i)throw new RangeError(`Missing emitter template: ${t.id}`);u({...i,id:t.id})}}update(e){const t=e=>e.map(e=>e.id).join("\0");if(t(e.sources)!==t(this.options.sources))throw new RangeError("Changing emitter sources requires a new run (remount with a new key)");const i={...e,sources:this.options.sources,seed:this.options.seed,durationMs:this.options.durationMs,maxEvents:this.options.maxEvents};this.validate(i),this.options=i}pending(){return!this.options.paused&&!this.emitter.isComplete()&&this.options.sources.some(e=>!1!==this.options.active?.[e.id])}advance(e,t=!1){const i="s"===this.options.timeUnit?.001:1,s=this.options.originTime??0,n=t?{...this.options,paused:!0}:this.options;return this.emitter.advance(1e3*e,n).map(e=>{const t=this.options.templates[e.source];return{...t,id:e.id,datum:{...t.datum,...e,time:s+e.eventTime*i,eventTime:s+e.eventTime*i,arrivalTime:s+e.arrivalTime*i}}})}snapshot(){return{options:{...this.options,active:{...this.options.active},sources:this.options.sources.map(e=>({...e,...e.burst&&{burst:{...e.burst,...e.burst.gapMs&&{gapMs:[...e.burst.gapMs]}}},..."object"==typeof e.jitter&&{jitter:{...e.jitter,buckets:e.jitter.buckets.map(e=>({...e}))}}})),templates:Object.fromEntries(Object.entries(this.options.templates).map(([e,t])=>[e,Ie({...t,id:e})]))},progress:this.progress()}}progress(){return this.emitter.snapshot()}restoreProgress(e){this.emitter.restore(e)}static restore(t){const i=new e(t.options);return i.emitter.restore(t.progress),i}};function wt(e){return{...e,bySource:Object.fromEntries(Object.entries(e.bySource).map(([e,t])=>[e,{...t}]))}}var xt=class{constructor(e,t={},i=[]){if(this.windowSize=e,this.policy=t,this.windows=new Map,this.openWindows=new Set,this.sources=new Map,this.latest=-1/0,this.frontier=-1/0,this.value=-1/0,this.pending=[],!Number.isFinite(e)||e<=0)throw new RangeError("EventDrop windows.size must be a finite positive number");for(const e of i)this.sources.set(e,{latest:-1/0,arrival:-1/0,idle:!1});this.validatePolicy(t)}validatePolicy(e){if("function"!=typeof e){for(const t of["delay","idleTimeout","allowedLateness"]){const i=e[t];if(null!=i&&(!Number.isFinite(i)||i<0))throw new RangeError(`watermark.${t} must be finite and nonnegative`)}if(null!=e.value&&!Number.isFinite(e.value))throw new RangeError("watermark.value must be finite")}}setWatermark(e){this.validatePolicy(e),this.policy=e}getWatermark(){return this.value}getLatestEventTime(){return this.latest}getArrivalFrontier(){return this.frontier}getLedger(){return Array.from(this.windows.values(),wt).sort((e,t)=>e.start-t.start)}drainEvents(){const e=this.pending;return this.pending=[],e}snapshot(){return this.state(this.getLedger())}drainDelta(){const e=Array.from(this.changedWindows??[],e=>wt(this.windows.get(e)));return this.changedWindows=new Set,this.state(e)}state(e){return{windows:e,sources:Array.from(this.sources,([e,t])=>[e,{...t}]),latest:this.latest,frontier:this.frontier,value:this.value,heldBy:this.heldBy}}restore(e){this.applySnapshot(e,!0)}applyDelta(e){this.applySnapshot(e,!1)}applySnapshot(e,t){const i=e=>Number.isFinite(e)||e===-1/0,s=e=>Number.isSafeInteger(e)&&e>=0;if(![e.latest,e.frontier,e.value].every(i)||new Set(e.windows.map(e=>e.windowId)).size!==e.windows.length||new Set(e.sources.map(([e])=>e)).size!==e.sources.length||e.sources.some(([,e])=>!i(e.latest)||!i(e.arrival))||e.windows.some(e=>!Number.isFinite(e.start)||!Number.isFinite(e.end)||e.end<=e.start||!s(e.accepted)||!s(e.late)||Object.values(e.bySource).some(e=>!s(e.accepted)||!s(e.late))||Object.values(e.bySource).reduce((e,t)=>e+t.accepted,0)!==e.accepted||Object.values(e.bySource).reduce((e,t)=>e+t.late,0)!==e.late))throw new RangeError("Invalid EventDrop ledger snapshot");t&&(this.windows.clear(),this.openWindows.clear());for(const t of e.windows){const e=this.windows.get(t.windowId);e&&this.openWindows.delete(e);const i=wt(t);Object.setPrototypeOf(i.bySource,null),this.windows.set(t.windowId,i),i.open&&this.openWindows.add(i)}this.changedWindows?.clear(),this.sources=new Map(e.sources.map(([e,t])=>[e,{...t}])),this.latest=e.latest,this.frontier=e.frontier,this.value=e.value,this.heldBy=e.heldBy,this.pending=[]}advance(e,t="external"){if(!Number.isFinite(e))return;this.frontier=Math.max(this.frontier,e);const i=this.policy;let s;if("function"==typeof i)s=i(this.latest);else if(i.external)s=i.external();else if(null!=i.value)s=i.value;else{let t=this.latest;if(i.perSource){let s;t=1/0;for(const[n,r]of this.sources){Number.isFinite(r.arrival)||(r.arrival=e);const o=null!=i.idleTimeout&&e-r.arrival>=i.idleTimeout;o&&!r.idle&&this.pending.push({type:"physics-source-idle",sourceId:n}),r.idle=o,!o&&r.latest<t&&(t=r.latest,s=n)}s&&s!==this.heldBy&&t<this.latest&&this.pending.push({type:"physics-watermark-held",sourceId:s}),this.heldBy=s,t===1/0&&(t=this.latest)}s=t-(i.delay??this.windowSize)}if(!Number.isFinite(s)||s<=this.value)return;const n=this.value;this.value=s,this.pending.push({type:"physics-watermark-advance",from:n,to:s,cause:t});for(const t of this.openWindows)t.end<=this.value&&this.close(t,e)}close(e,t){this.changedWindows?.add(e.windowId),e.open=!1,e.closedAt=t,e.watermarkAtClose=this.value,this.openWindows.delete(e),this.pending.push({type:"physics-window-close",...wt(e),watermark:this.value})}append(e){var t;const{eventTime:i,arrivalTime:s,source:n=""}=e;if(!Number.isFinite(i)||!Number.isFinite(s))throw new RangeError("Event and arrival times must be finite");if(s<this.frontier)throw new RangeError("Incremental admissions require nondecreasing arrival times");this.latest=Math.max(this.latest,i);const r=this.sources.get(n);this.sources.set(n,{latest:Math.max(r?.latest??-1/0,i),arrival:s,idle:!1}),this.advance(s,"arrival");const o=Math.floor(i/this.windowSize)*this.windowSize,a=o+this.windowSize,d=`${o}-${a}`;let h=this.windows.get(d);h||(h={windowId:d,start:o,end:a,accepted:0,late:0,bySource:Object.create(null),open:!0},this.windows.set(d,h),this.openWindows.add(h),this.pending.push({type:"physics-window-open",windowId:d,start:o,end:a}));const l=e.watermarkAtArrival??this.value,c=a+("function"==typeof this.policy?0:this.policy.allowedLateness??0)<=l,u=(t=h.bySource)[n]??(t[n]={accepted:0,late:0}),p=c?"late":"accepted";return h[p]++,this.changedWindows?.add(d),u[p]++,h.open||c||this.pending.push({type:"physics-window-update",windowId:d,accepted:h.accepted,late:h.late,bySource:wt(h).bySource,watermark:this.value,retractions:1}),h.open&&a<=this.value&&this.close(h,s),{windowId:d,start:o,end:a,late:c,watermarkAtArrival:l}}};import{scaleLinear as bt}from"d3-scale";function St(e,t,i,s){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:i},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...s}}}function Mt(e,t,i){return"function"==typeof i?i(e,t):e[i]}function It(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:null}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function Tt(e){const{windowSize:t,watermark:i,watermarkAtArrivalAccessor:s}=e;if(!(Number.isFinite(t)&&t>0))throw new RangeError("EventDrop windows.size must be a finite positive number");const{rows:n}=function(e,t,i=0){const s=new Set(e.filter(e=>null!=e.id).map(e=>String(e.id))),n=new Map;for(const r of e){let e=null==r.id?`${t}-${i++}`:String(r.id);for(;null==r.id&&s.has(e);)e=`${t}-${i++}`;s.add(e),n.set(e,null==r.id?{...r,id:e}:r)}return{seed:e,rows:Array.from(n.values()),nextId:i}}(e.data,"event"),r=n.flatMap((t,i)=>{const s=It(Mt(t,i,e.timeAccessor));if(null==s)return[];return[{datum:t,index:i,eventTime:s,arrivalTime:It(Mt(t,i,e.arrivalAccessor))??s,watermarkAtArrival:0,late:!1}]}),o="function"==typeof i?null:It(i?.value),a="function"==typeof i?t:It(i?.delay)??t,d=new xt(t,i,e.sourceIds);for(const t of r.slice().sort((e,t)=>e.arrivalTime-t.arrivalTime||e.index-t.index)){const i=s?It(Mt(t.datum,t.index,s)):null,n=d.append({eventTime:t.eventTime,arrivalTime:t.arrivalTime,source:String(Mt(t.datum,t.index,e.sourceAccessor??"source")??""),watermarkAtArrival:i??void 0});t.watermarkAtArrival=n.watermarkAtArrival,t.late=n.late}return{events:r,watermarkValue:r.length?d.getWatermark():o??-a,ledger:d.getLedger(),lifecycleEvents:d.drainEvents()}}import{jsx as kt,jsxs as Pt}from"react/jsx-runtime";function qt(e,i){const s=i.arrival;if(s&&"drop"!==s){if("travel"!==s.mode)throw new RangeError("arrival.mode must be travel");if(null!=s.history&&"present"!==s.history&&"travel"!==s.history)throw new RangeError("arrival.history must be present or travel");for(const e of[s.durationMs,s.speedPxPerSec])if(null!=e&&(!Number.isFinite(e)||e<=0))throw new RangeError("Travel duration and speed must be finite and positive");if(null!=s.durationMs&&null!=s.speedPxPerSec)throw new RangeError("Choose arrival.durationMs or arrival.speedPxPerSec");if(null!=s.path&&"function"!=typeof s.path&&"straight"!==s.path&&"connector"!==s.path)throw new RangeError("arrival.path must be straight, connector or a callback")}const r=new Map(function(e=[],t={},i){if("none"===t.side)return[];const s=e.filter(e=>!1!==e.visible),n=Math.max(48,t.tileSize??80),r=Math.max(1,s.length);return s.map((e,s)=>({source:e,x:"top"===t.side?(s+.5)*i[0]/r:"right"===t.side?i[0]-n/2:n/2,y:"top"===t.side?n/2+24:(s+.5)*i[1]/r}))}(i.sources,i.sourceRail,i.size).map(({source:e,x:t,y:i})=>[e.id,{x:t,y:i-6}])),o=Number.isFinite(i.timeScale)&&i.timeScale>0?i.timeScale:1,a=[];for(const d of e){const e=d.datum;s&&"drop"!==s&&(e.__phase=e.late?"late":"board");const h=e.windowIndex<i.closedWindowCount,l=(!s||"drop"===s||"travel"!==s.history)&&(h&&!e.late||!h&&e.late);l&&a.push(d);const c=(l?i.firstArrival:e.arrivalTime)*i.secondsPerUnit;d.__eventDropSpawnTime=c;const u=r.get(e.source);if(!s||"drop"===s||!u||l)continue;const p={x:d.x,y:d.y},m="function"==typeof s.path?s.path({...u},{...p}):"connector"===s.path?[u,{x:u.x,y:Math.min(u.y,p.y)-24},{x:p.x,y:Math.min(u.y,p.y)-24},p]:[u,p];if(t({points:m,durationSeconds:1}),m[0].x!==u.x||m[0].y!==u.y||m.at(-1).x!==p.x||m.at(-1).y!==p.y)throw new RangeError("Travel paths must start at the source and end at the board entry");const f=null!=s.speedPxPerSec?Math.max(1/120,n(m)/s.speedPxPerSec):(s.durationMs??800)/1e3;d.travel={points:m.map(e=>({...e})),durationSeconds:f/o,elapsedSeconds:0},d.x=u.x,d.y=u.y,d.__eventDropSpawnTime=c-f,e.__phase="travel"}if(s&&"drop"!==s&&null!=s.speedPxPerSec){const t=e.reduce((e,t)=>Math.max(e,t.travel?.durationSeconds??0),0);for(const i of e)i.travel&&(i.__eventDropSpawnTime+=(i.travel.durationSeconds-t)*o,i.travel.durationSeconds=t)}const d=e.reduce((e,t)=>Math.min(e,t.__eventDropSpawnTime),1/0);for(const e of a)e.__eventDropSpawnTime=d}function Et(e,t,i=!1){const{data:s,timeAccessor:n,arrivalAccessor:r,windows:o,watermark:a,watermarkAtArrivalAccessor:d,ballRadius:h,seed:l,size:c,timeExtent:u,timeScale:p=1}=e,{events:m,watermarkValue:f,ledger:v,lifecycleEvents:y}=t??Tt({data:s,timeAccessor:n,arrivalAccessor:r,watermark:a,watermarkAtArrivalAccessor:d,sourceAccessor:e.sourceAccessor,sourceIds:e.sources?.map(e=>e.id),windowSize:o.size}),g=new Map(v.map(e=>[e.start,e])),w=function(e){const[t,i]=e,s=t<160||i<116,n=s?Math.min(12,Math.max(2,.08*t)):32,r=s?Math.min(8,Math.max(2,.12*i)):24,o=s?r:34;return{width:t,height:i,plot:{x:n,y:r,width:Math.max(1,t-2*n),height:Math.max(1,i-r-o)}}}(c);if(e.sources?.some(e=>!1!==e.visible)&&"none"!==e.sourceRail?.side){const t=Math.max(48,e.sourceRail?.tileSize??80);"top"===e.sourceRail?.side?(w.plot.y+=t,w.plot.height=Math.max(1,w.plot.height-t)):("right"===e.sourceRail?.side||(w.plot.x+=t),w.plot.width=Math.max(1,w.plot.width-t))}let x=m.length?1/0:0,b=m.length?1/0:0,S=m.length?-1/0:o.size;for(const e of m)x=Math.min(x,e.arrivalTime),b=Math.min(b,e.eventTime),S=Math.max(S,e.eventTime);const M=e.timeUnit??(m.some(e=>Math.abs(e.eventTime)>1e5||Math.abs(e.arrivalTime)>1e5)?"ms":"s"),I="ms"===M?.001:1,T=It(u?.[0]),k=It(u?.[1]),P=i?T??b:Math.min(T??b,b),q=i?k??S:Math.max(k??S,S),E=Math.floor(P/o.size)*o.size,A=Math.max(1,Math.ceil((q-E+o.size)/o.size)),B=function(e,t){const i=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:i,height:e.plot.height},windowPlot:{x:e.plot.x+i,y:e.plot.y,width:Math.max(40,e.plot.width-i),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(w,h),D=E+A*o.size,O=bt().domain([E,D]).range([B.windowPlot.x,B.windowPlot.x+B.windowPlot.width]);let R=0;const C=Array.from({length:A},(e,t)=>(E+(t+1)*o.size<=f&&R++,{value:0,secondary:0})),N=[];m.forEach(({datum:t,index:i,eventTime:s,arrivalTime:n,watermarkAtArrival:r,late:a})=>{const d=Math.max(0,Math.min(A-1,Math.floor((s-E)/o.size)));C[d].value+=a?0:1,C[d].secondary+=a?1:0,N.push({id:String(t.id??`event-${i}`),x:Bt(s,d,a,{windowStart:E,windowSize:o.size,gutter:B.gutter,closedWindowCount:R,windowPlot:B.windowPlot,windowCount:A},h),y:w.plot.y+h+2,vx:0,vy:0,mass:1,friction:.02,spawnAt:n,shape:{type:"circle",radius:h},datum:{...t,eventTime:s,arrivalTime:n,windowIndex:d,windowId:`${E+d*o.size}-${E+(d+1)*o.size}`,source:String(Mt(t,i,e.sourceAccessor??"source")??""),watermarkAtArrival:r,late:a}})});const F=w.plot.y+w.plot.height,z=w.plot.y+.28*w.plot.height,W={closedWindowCount:R,gutter:B.gutter,plot:w.plot,windowCount:A,windowPlot:B.windowPlot,windowSize:o.size,windowStart:E},$=function(e,t){const i=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!i)return[];const s=e.windowStart,n=e.windowStart+e.windowCount*e.windowSize,r=bt().domain([s,n]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),o=r(e.windowStart+i*e.windowSize),a=e.windowPlot.x,d=Math.max(18,Math.min(.3*e.windowPlot.height,o-a)),h=t+d,l=e=>o===a?t:h+(e-a)/(o-a)*(t-h),c=[];for(let t=0;t<i;t+=1){const i=e.windowStart+t*e.windowSize,s=i+e.windowSize,n=r(i),o=r(s);c.push({id:`eventdrop-lid-${t}`,windowIndex:t,x1:n,y1:l(n),x2:o,y2:l(o)})}return c}(W,z);for(const e of N){const t=e.datum;e.y=At({...W,lidSegments:$},t.windowIndex,t.late,h)}const Y=function(e){const{count:t,idPrefix:i,wallThickness:s,xScale:n,yBottom:r,yTop:o,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const d=Math.min(r-1,a?.(t)??o),h=Math.max(1,r-d);return{id:`${i}-wall-${t}`,shape:{type:"aabb",x:n(t),y:d+h/2,width:s,height:h}}})}({idPrefix:"eventdrop-window",count:A,xScale:e=>O(E+e*o.size),yTop:B.wallTop,yTopForIndex:e=>{const t=(e=>{if(e<0||e>R)return null;const t=0===e?$[0]?.y1:$[e-1]?.y2??$[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?B.wallTop:t+1.25*h},yBottom:F,wallThickness:6}),X=[...Ce({x:w.plot.x,y:w.plot.y,width:w.plot.width,height:w.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...Y,...$.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*h)},friction:.02,restitution:.01}))];return qt(N,{...e,secondsPerUnit:I,timeScale:p,firstArrival:x,closedWindowCount:R}),{config:St(l,X,"EventDropChart",{friction:.08}),initialSpawns:N,initialSpawnPacing:{pacing:"arrival",timeAccessor:"__eventDropSpawnTime",timeScale:p},projectionRows:C.map((e,t)=>({label:`${E+t*o.size}-${E+(t+1)*o.size}`,value:e.value,secondary:e.secondary,...g.get(E+t*o.size)})),metadata:{kind:"event-drop",closedWindowCount:R,gutter:B.gutter,lidSegments:$,lateCount:C.reduce((e,t)=>e+t.secondary,0),plot:w.plot,windowPlot:B.windowPlot,windowWalls:Y.map(({id:e,shape:t})=>({id:e,x:t.x-t.width/2,y:t.y-t.height/2,width:t.width,height:t.height})),watermarkValue:f,windowCount:A,windowSize:o.size,windowStart:E,ledger:v,lifecycleEvents:y,timeUnit:M,eventTimeFrontier:m.length?S:0,arrivalFrontier:m.reduce((e,t)=>Math.max(e,t.arrivalTime),0)}}}function At(e,t,i,s){const{windowPlot:n,lidSegments:r}=e,o=r[t];return i&&!o?Math.min(n.y+n.height-s,n.y+.48*n.height+2*s+4):!i&&o?Math.min(n.y+n.height-s,Math.max(o.y1,o.y2)+2*s+4):n.y+s+2}function Bt(e,t,i,s,n){const{windowPlot:r,windowCount:o,windowStart:a,windowSize:d}=s;if(i&&t>=s.closedWindowCount)return s.gutter.x+s.gutter.width/2;const h=r.width/o,l=i?r.x:r.x+t*h,c=i?r.x+r.width:l+h,u=Math.min((c-l)/2,n+(i?0:3)),p=r.x+(e-a)/d*h;return Math.max(l+u,Math.min(c-u,p))}var Dt=class e{constructor(e){this.config=e,this.elapsed=0,this.pending=new Map,this.geometryKey="",this.laneWidth=1,this.offset=0,this.bodiesChanged=!1,this.validate(e),this.ledger=new xt(e.windowSize,e.watermark,e.sources?.map(e=>e.id)),this.anchor=e.originTime??0,this.refresh()}validate(e){if(null!=e.originTime&&!Number.isFinite(e.originTime))throw new RangeError("Live originTime must be finite");if(!["now","watermark"].includes(e.live.follow)||!Number.isFinite(e.live.horizon)||e.live.horizon<=0||!Number.isFinite(e.live.retain)||e.live.retain<0)throw new RangeError("live requires follow now/watermark, positive horizon and nonnegative retain")}update(e,t){if(this.validate(e),e.windowSize!==this.config.windowSize)throw new RangeError("Changing live windows.size requires a new run (remount with a new key)");if(e.timeUnit!==this.config.timeUnit||e.originTime!==this.config.originTime)throw new RangeError("Changing live timeUnit or origin requires a new run (remount with a new key)");this.ledger.setWatermark(e.watermark??{});const i=this.layout.metadata,s=this.laneWidth;this.config=e,this.geometryKey="",this.refresh();const n=this.layout.metadata;if(t&&(s!==this.laneWidth||i.plot.y!==n.plot.y||i.plot.height!==n.plot.height||i.windowPlot.x!==n.windowPlot.x)){const e=this.laneWidth/s,r=n.plot.height/i.plot.height,o=t=>({x:n.windowPlot.x+(t.x-i.windowPlot.x)*e,y:n.plot.y+(t.y-i.plot.y)*r}),a=e=>({...e,...o(e),...e.travel&&{travel:{...e.travel,points:e.travel.points.map(o)}}}),d=t.snapshot();t.restore({...d,bodies:d.bodies.map(t=>({...a(t),prevX:o({x:t.prevX,y:t.prevY}).x,prevY:o({x:t.prevX,y:t.prevY}).y,vx:t.vx*e,vy:t.vy*r}))}),this.pending=new Map(Array.from(this.pending,([e,t])=>[e,{...t,spawn:a(t.spawn)}]))}}get unit(){return"ms"===this.config.timeUnit?1e3:1}get now(){return(this.config.originTime??0)+this.elapsed*this.unit}refresh(){const{windowSize:e,live:t,size:i,ballRadius:s,seed:n,sources:r,sourceRail:o,timeUnit:a}=this.config,d=Math.floor((this.anchor-t.retain)/e)*e,h=Math.ceil((t.retain+t.horizon)/e)+1,l=this.ledger.getWatermark(),c=`${d}:${Math.floor(l/e)}`;if(c===this.geometryKey)return;this.geometryKey=c,this.layout=Et({data:[],timeAccessor:"time",arrivalAccessor:"arrivalTime",windows:{size:e},size:i,ballRadius:s,seed:n,sources:r,sourceRail:o,timeUnit:a,timeExtent:[d,d+(h-1)*e]},{events:[],watermarkValue:l,ledger:[],lifecycleEvents:[]},!0);const u=this.layout.metadata;this.laneWidth=u.windowPlot.width/h,this.offset=d/e*this.laneWidth;for(const e of this.layout.config.colliders??[]){const t=e.shape;"segment"===t.type?(t.x1+=this.offset,t.x2+=this.offset):t.x+=this.offset,e.id=`${e.id}:${d}`}}viewTransform(){return{x:-(this.anchor-this.config.live.retain)/this.config.windowSize*this.laneWidth,y:0}}metadata(){const e=this.layout.metadata,t=this.offset+this.viewTransform().x,i=e=>({...e,x:e.x+t});return{...e,plot:i(e.plot),windowPlot:i(e.windowPlot),gutter:i(e.gutter),lidSegments:e.lidSegments.map(e=>({...e,x1:e.x1+t,x2:e.x2+t})),windowWalls:e.windowWalls?.map(i),watermarkValue:this.ledger.getWatermark(),eventTimeFrontier:this.ledger.getLatestEventTime(),arrivalFrontier:this.ledger.getArrivalFrontier(),ledger:this.ledger.getLedger(),lateCount:this.ledger.getLedger().reduce((e,t)=>e+t.late,0)}}colliders(){return this.layout.config.colliders??[]}backlog(){if(this.pending.size>0)return!0;if("watermark"!==this.config.live.follow)return!1;const e=this.ledger.getWatermark();return Number.isFinite(e)&&e-this.anchor>1e-9}continuous(){const e=this.config.watermark;return"now"===this.config.live.follow||"object"==typeof e&&(null!=e.idleTimeout||null!=e.external)}prepare(e,t){this.bodiesChanged=!0;const i=e.datum,s=Number(i.eventTime??i.time);if(!Number.isFinite(s))throw new RangeError("Live EventDrop requires a finite event time");const{windowSize:n,ballRadius:r,arrival:o,sources:a,sourceRail:d,size:h}=this.config,l=this.layout.metadata,c=Math.floor(s/n),u=Math.min(this.laneWidth/2,r+3),p=Math.max(u,Math.min(this.laneWidth-u,(s/n-c)*this.laneWidth)),m={...e,x:l.windowPlot.x+c*this.laneWidth+p,y:l.plot.y+r+2,vx:0,vy:0,datum:{...i,id:e.id,eventTime:s,time:s,arrivalTime:this.now,windowIndex:c,windowId:`${c*n}-${(c+1)*n}`,__phase:"travel",late:!1}},f=this.viewTransform().x;m.x+=f,qt([m],{arrival:o&&"drop"!==o?{...o,history:"travel"}:o,sources:a,sourceRail:d,size:h,secondsPerUnit:1/this.unit,timeScale:1,firstArrival:t,closedWindowCount:0}),m.x-=f,m.travel&&(m.travel.points=m.travel.points.map(e=>({...e,x:e.x-f})));const v=t+(m.travel?.durationSeconds??0);return this.pending.set(m.id,{spawn:m,due:v}),m}advance(e,t){const i=Math.max(0,t-this.elapsed);this.elapsed=t;for(const{spawn:i,due:s}of Array.from(this.pending.values()).filter(e=>e.due<=t+1e-9).sort((e,t)=>e.due-t.due)){this.pending.delete(i.id);const t=i.datum,n=(this.config.originTime??0)+s*this.unit,r=this.ledger.append({eventTime:Number(t.eventTime),arrivalTime:Math.max(n,this.ledger.getArrivalFrontier()),source:String(t.source??"")}),o=e.readBody?.(i.id)??e.readState().find(e=>e.id===i.id);if(o){this.bodiesChanged=!0;const s=this.layout.metadata,a=r.end<=this.ledger.getWatermark(),d=r.late?{x:s.gutter.x+s.gutter.width/2+this.offset,y:s.plot.y+.55*s.plot.height}:{x:i.travel?.points.at(-1)?.x??i.x,y:s.plot.y+s.plot.height*(a?.58:0)+this.config.ballRadius+2};e.spawn({...o,...d,travel:void 0,datum:{...t,...r,arrivalTime:n,__phase:r.late?"late":"board"}})}}this.ledger.advance(this.now);const s="now"===this.config.live.follow?this.now:this.ledger.getWatermark();Number.isFinite(s)&&(this.anchor+=Math.max(0,Math.min(s-this.anchor,this.config.live.horizon*i/2)));const n=this.geometryKey;this.refresh(),n!==this.geometryKey&&e.setColliders(this.colliders());const r=this.anchor-this.config.live.retain,o=e.readState().filter(e=>{if(this.pending.has(e.id))return!1;const t=e.datum;return t.late?Number(t.arrivalTime)<this.now-this.config.windowSize:Math.floor(Number(t.eventTime)/this.config.windowSize)*this.config.windowSize+this.config.windowSize<r}).map(e=>e.id);return this.bodiesChanged||(this.bodiesChanged=o.length>0),o}drainWorkerDelta(){const e={...this.runtimeState(),ledger:this.ledger.drainDelta(),bodiesChanged:this.bodiesChanged};return this.bodiesChanged=!1,e}applyWorkerDelta(e,t){Ot(e),this.ledger.applyDelta(e.ledger);const i=this.geometryKey;this.applyState(e),i!==this.geometryKey&&t.setColliders(this.colliders())}snapshot(){return{config:this.config,ledger:this.ledger.snapshot(),...this.runtimeState()}}runtimeState(){return{anchor:this.anchor,elapsed:this.elapsed,pending:Array.from(this.pending.values(),e=>({due:e.due,spawn:Ie(e.spawn)}))}}static restore(t){Ot(t);const i=new e(t.config);return i.ledger.restore(t.ledger),i.applyState(t),i}applyState(e){this.anchor=e.anchor,this.elapsed=e.elapsed,this.pending=new Map(e.pending.map(e=>[e.spawn.id,{due:e.due,spawn:Ie(e.spawn)}])),this.refresh()}};function Ot(e){if(!Number.isFinite(e.anchor)||!Number.isFinite(e.elapsed)||e.elapsed<0||new Set(e.pending.map(e=>e.spawn.id)).size!==e.pending.length)throw new RangeError("Invalid live EventDrop snapshot");for(const t of e.pending){if(!Number.isFinite(t.due)||t.due<0)throw new RangeError("Invalid live EventDrop handoff");u(t.spawn)}}function Rt(){var e;e={emitters:{create:e=>new gt(e),restore:e=>gt.restore(e)},eventDrop:{create:e=>new Dt(e),restore:e=>Dt.restore(e)}},Object.assign(rt,e)}function Ct(e,t,i=!1){const s=e.workerLiveDelta(),n=s?.bodiesChanged||t.spawned.length||t.evicted.length||t.sedimented.length||t.events.some(e=>"travel-end"===e.type),r=i||!s&&n?e.snapshot():void 0,o=e.readBodies(),a=function(e,t,i=[],s){const n=new Array(t.length),r=new Float32Array(2*t.length),o=new Float32Array(2*t.length),a=new Uint8Array(t.length),d=new Float32Array(2*t.length);return t.forEach((e,t)=>{const i=2*t;n[t]=e.id,r[i]=e.x,r[i+1]=e.y,d[i]=e.prevX,d[i+1]=e.prevY,o[i]=e.vx,o[i+1]=e.vy,a[t]=e.sleeping?1:0}),{bodies:t,ids:n,positions:r,previousPositions:d,result:e,sediment:i,sleeping:a,snapshot:s,velocities:o}}(t,o,[],r);return s&&!r&&(a.live=s,n&&(a.structure=e.workerStructure())),o.some(e=>e.travel)&&(a.travelElapsed=Float64Array.from(o,e=>e.travel?.elapsedSeconds??0)),a.sleepTimes=e.workerSleepTimes(a.ids),a.bodies=[],r||a.structure||(a.ids=[]),a.state=e.workerState(),a}function Nt(e){return Ct(e,e.tick(0),!0)}var Ft=function(){Rt();let e=new ct;return{handle(t){switch(t.type){case"init":return e=new ct(t.config),t.snapshot?e.restore(t.snapshot):t.initialSpawns?.length&&e.enqueue(t.initialSpawns,t.initialSpawnPacing),{type:"frame",frame:Nt(e)};case"configure":return e.updateConfig(t.config),{type:"frame",frame:Nt(e)};case"enqueue":return e.enqueue(t.spawns,t.pacing),{type:"frame",frame:Nt(e)};case"tick":return{type:"frame",frame:Ct(e,e.tick(t.deltaSeconds))};case"settle":return{type:"frame",frame:Ct(e,e.settleWithObservations(t.maxSteps))};case"snapshot":return{type:"snapshot",snapshot:e.snapshot()};case"restore":return e.restore(t.snapshot),{type:"frame",frame:Nt(e)};case"clear":return e.clear(),{type:"frame",frame:Nt(e)};case"remove":return{type:"removed",removed:e.remove(t.ids),frame:Nt(e)};case"applyImpulse":return e.applyImpulse(t.id,t.ix,t.iy),{type:"frame",frame:Nt(e)};case"setPaused":return e.setPaused(t.paused),{type:"frame",frame:Nt(e)};case"setVisible":return e.setVisible(t.visible),{type:"frame",frame:Nt(e)}}}}}();function zt(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=Ft.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,...t.sleepTimes?[t.sleepTimes.buffer]:[],...t.travelElapsed?[t.travelElapsed.buffer]:[],...t.previousPositions?[t.previousPositions.buffer]:[]]:[];var t}(e))}catch(e){self.postMessage({error:zt(e),ok:!1,requestId:t.requestId})}};