@joy-ride/game 0.29.0 → 0.29.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 (48) hide show
  1. package/bookmarklet.d.ts +1 -1
  2. package/bookmarklet.js +1 -1
  3. package/embed-chunks/{CodeBlock-C-uqwCCE.js → CodeBlock-CmdFck30.js} +1 -1
  4. package/embed-chunks/{Documentation-CCpuHmnH.js → Documentation-C5yd8S9T.js} +2 -2
  5. package/embed-chunks/{EmbedPanel-CltTMTEZ.js → EmbedPanel-BDZ9gPAY.js} +1 -1
  6. package/embed-chunks/{JoyRideView-dbTrQ6zf.js → JoyRideView-CGO2LlqF.js} +1 -1
  7. package/embed-chunks/{configuration~index~embed-E9p3ySKG.js → configuration~index~embed-CRXVkf5S.js} +1 -1
  8. package/embed-chunks/configuration~index~embed~bookmarklet-6dUo7fKK.js +1 -0
  9. package/embed-chunks/{runtime~JoyRideView~browser-session-core-hIS-xQed.js → runtime~JoyRideView~browser-session-core-W3T3KGBY.js} +1 -1
  10. package/embed-chunks/{runtime~browser-session-core-DfamcX9U.js → runtime~browser-session-core-ABdeer0k.js} +1 -1
  11. package/embed-chunks/{runtime~index~embed-Bm1M0iiY.js → runtime~index~embed-Cdk1V9Yq.js} +2 -2
  12. package/embed-chunks/{runtime~index~embed~vehicle-popover~browser-session-core~renderer-iEgK-2uE.js → runtime~index~embed~vehicle-popover~browser-session-core~renderer-DKaOSaI2.js} +1 -1
  13. package/embed-chunks/{runtime~vehicle-popover-CA1iUObq.js → runtime~vehicle-popover-B9t-I45z.js} +1 -1
  14. package/embed-chunks/{runtime~vehicle-popover~browser-session-core-B5JA0YNt.js → runtime~vehicle-popover~browser-session-core-hzAmTyN1.js} +1 -1
  15. package/embed-chunks/{runtime~vehicle-popover~browser-session-core~renderer-FYzuLkAN.js → runtime~vehicle-popover~browser-session-core~renderer-DRXQjSAc.js} +1 -1
  16. package/embed-chunks/{runtime~vehicle-popover~renderer-B44auM3E.js → runtime~vehicle-popover~renderer-CFfqUX4J.js} +3 -3
  17. package/embed-chunks/{src-sen5Yp2R.js → src-v40jgxEo.js} +2 -2
  18. package/embed-chunks/{vehicle-catalog~index~embed-CKTjozQr.js → vehicle-catalog~index~embed-CkmzFsdm.js} +1 -1
  19. package/embed-chunks/{vehicle-popover-RZXv8RjT.js → vehicle-popover-Cah1Jwwj.js} +1 -1
  20. package/embed.js +1 -1
  21. package/{index-DztYDfpU.d.ts → index-Cr-53zu5.d.ts} +2 -1
  22. package/index.d.ts +2 -2
  23. package/index.js +1 -1
  24. package/npm-chunks/{Documentation-DjEkQvvy.js → Documentation-C8s_aL0s.js} +2 -2
  25. package/npm-chunks/{EmbedPanel-DBoR1Dci.js → EmbedPanel-a4F6OnOH.js} +1 -1
  26. package/npm-chunks/{JoyRideView-CqVA2IWS.js → JoyRideView-BAXi_AFI.js} +1 -1
  27. package/npm-chunks/{VehicleHint-BaLJr7O5.js → VehicleHint-CS6L9FO9.js} +1 -1
  28. package/npm-chunks/{configuration~react-Wr_iMhZB.js → configuration~react-B3URe5Hp.js} +1 -1
  29. package/npm-chunks/configuration~react~vehicle-popover~JoyRideView~browser-session-core~renderer-BASSGxIF.js +1 -0
  30. package/npm-chunks/{runtime~JoyRideView~browser-session-core-Del73NUd.js → runtime~JoyRideView~browser-session-core-7d-89abo.js} +1 -1
  31. package/npm-chunks/runtime~browser-session-core-CTEOkb8N.js +1 -0
  32. package/npm-chunks/{runtime~react-De_WENZT.js → runtime~react-DuHGu6qC.js} +1 -1
  33. package/npm-chunks/{runtime~react~browser-session-core-DPWW9TnO.js → runtime~react~browser-session-core-BOMyEw_b.js} +1 -1
  34. package/npm-chunks/{runtime~react~vehicle-popover~browser-session-core~renderer-DKpExYhH.js → runtime~react~vehicle-popover~browser-session-core~renderer-5hzldoVR.js} +1 -1
  35. package/npm-chunks/{runtime~vehicle-popover-QsSxwpN_.js → runtime~vehicle-popover-DF_vkfqT.js} +1 -1
  36. package/npm-chunks/{runtime~vehicle-popover~browser-session-core-CrZME-1Y.js → runtime~vehicle-popover~browser-session-core-CDg6b0po.js} +1 -1
  37. package/npm-chunks/{runtime~vehicle-popover~browser-session-core~renderer-L2_7uaz1.js → runtime~vehicle-popover~browser-session-core~renderer-D_NBXTcG.js} +1 -1
  38. package/npm-chunks/{runtime~vehicle-popover~renderer-CTrAfI2e.js → runtime~vehicle-popover~renderer-C7Eq6aHr.js} +3 -3
  39. package/npm-chunks/{theme-CyUONXaD.js → theme-CkSpDTIL.js} +1 -1
  40. package/npm-chunks/{vehicle-catalog~react~browser-session-core-Ck9lXSBn.js → vehicle-catalog~react~browser-session-core-CxP3HQ_B.js} +1 -1
  41. package/npm-chunks/{vehicle-popover-CAG797YN.js → vehicle-popover-CYhUl7Ae.js} +1 -1
  42. package/package.json +1 -1
  43. package/{playground-B7tHL_J3.d.ts → playground-C1crX0w5.d.ts} +0 -5
  44. package/react.d.ts +2 -2
  45. package/react.js +10 -10
  46. package/embed-chunks/configuration~index~embed~bookmarklet-5ym-TX_u.js +0 -1
  47. package/npm-chunks/configuration~react~vehicle-popover~JoyRideView~browser-session-core~renderer-BwD100vD.js +0 -1
  48. package/npm-chunks/runtime~browser-session-core-Cicrs9mu.js +0 -1
@@ -1 +1 @@
1
- import{a as e}from"./definitions~index~embed~bookmarklet~vehicle-popover~Documentation~JoyRideView~browser-sessi~fklztn3g-BG7sJuWo.js";import{r as t}from"./definitions~index~embed~vehicle-popover~browser-session-core~renderer-RDNEXk_b.js";import{i as n,o as r,s as i,u as a}from"./configuration~index~embed~bookmarklet-5ym-TX_u.js";function o(e,t){}function s(e,t=1){}function c(e,t){return{lifetime:{unit:`seconds`,amount:t},intensity:`constant`,modifiers:{driveForce:1.08,grip:1.04},additiveModifiers:{forwardAccelerationMps2:e/Math.max(.1,t)}}}var l={oil:{lifetime:{unit:`distanceM`,amount:e.oil.effectDistanceM},modifiers:{grip:e.oil.minimumGrip}},mud:{lifetime:{unit:`distanceM`,amount:e.mud.effectDistanceM},modifiers:{grip:e.mud.minimumGrip,speed:e.mud.speedFactor,driveForce:e.mud.driveForceFactor}}},u={mud:{grip:e.mud.contactGrip,speed:e.mud.contactSpeedFactor,driveForce:e.mud.contactDriveForceFactor}};function d(e,t=0){let n=e.definition.lifetime.unit===`seconds`?Math.max(0,e.remaining-t):e.remaining,r=Math.min(1,n/e.definition.lifetime.amount);return e.definition.intensity===`constant`?+(n>0):e.definition.intensity===`pulse`?Math.sin(Math.PI*(1-r)):r}var f=class{active=new Map;contacts=new Map;captureState(){return t({active:this.active,contacts:this.contacts})}restoreState(e){let n=t(e);this.active=n.active,this.contacts=n.contacts}setContacts(e,t,n){n.length?this.contacts.set(e,new Map(n.map(e=>[e,t]))):this.contacts.delete(e)}apply(e,t,n){if(t.lifetime.amount<=0)return;let r=this.active.get(e);r||(r=new Map,this.active.set(e,r)),r.set(n??`vehicle`,{remaining:t.lifetime.amount,definition:t})}remaining(e,t){let n=this.active.get(e);return t===void 0?Math.max(0,...[...n?.values()??[]].map(e=>e.remaining)):n?.get(t)?.remaining??0}remove(e){this.active.delete(e)}bonus(e,t,n=4,r=0){if(t===void 0){let t=0;for(let i=0;i<n;i++)t+=this.bonus(e,i,n,r);return t/n}let i=0;for(let n of this.active.values())for(let a of[`vehicle`,t]){let t=n.get(a);i+=(t?.definition.additiveModifiers?.[e]??0)*(t?d(t,r):0)}return i}indicators(){return[...new Set([...this.active.keys(),...this.contacts.keys()])].map(e=>{let t=this.active.get(e),n=Math.max(0,...[...t?.values()??[]].map(e=>Math.min(1,e.remaining/e.definition.lifetime.amount)));return{label:e.charAt(0).toUpperCase()+e.slice(1),fraction:this.contacts.has(e)?1:n}})}factor(e,t,n=4){return this.factorFrom(null,e,t,n)}factorFrom(e,t,n,r=4){if(n===void 0){let n=0;for(let i=0;i<r;i++)n+=this.factorFrom(e,t,i);return n/r}let i=1;for(let[r,a]of this.active)for(let o of[`vehicle`,n]){if(e!==null&&r!==e)continue;let n=a.get(o),s=n?.definition.modifiers[t];if(n&&s!==void 0){let e=d(n);i*=1+(s-1)*e}}for(let[r,a]of this.contacts)for(let o of[`vehicle`,n])(e===null||r===e)&&(i*=a.get(o)?.[t]??1);return i}advance(e,t){for(let[n,r]of this.active){for(let[n,i]of r){let a=i.definition.lifetime.unit===`distanceM`?e:t;i.remaining=Math.max(0,i.remaining-Math.max(0,a)),i.remaining===0&&r.delete(n)}r.size===0&&this.active.delete(n)}}clearTire(e){for(let[t,n]of this.active)n.delete(e),n.size===0&&this.active.delete(t);for(let[t,n]of this.contacts)n.delete(e),n.size===0&&this.contacts.delete(t)}clear(){this.active.clear(),this.contacts.clear()}},p={defaultHealth:100,smokeFraction:.5,smoulderFraction:.35,ignitionFraction:.25,damagePerSecond:48,burnDownSeconds:8,impactDamagePerMps:3.5,explosionSeconds:.8,fireballSeconds:.38,blastRadiusPx:78},m={pixelsPerTenPoints:2500,minimum:10,maximum:1e3};function h(e,t,n){let r=Math.max(0,t)*Math.max(0,n);return E(e,`data-jr-points`,Math.min(m.maximum,Math.max(m.minimum,Math.round(r/m.pixelsPerTenPoints)*10)))}var g=class{maxHealth;health;explodedAt=null;blastQueued=!1;blastAge=0;lastBlastEmission=-1/0;lastDamageAt=-1/0;healthBarShownAt=-1/0;constructor(e=p.defaultHealth){this.maxHealth=e,this.maxHealth=Math.max(1,e),this.health=this.maxHealth}get stage(){return v(this.health,this.maxHealth)}get healthFraction(){return this.health/this.maxHealth}resetBurnable(e=this.maxHealth){let t=this.health!==Math.max(1,e);this.maxHealth=Math.max(1,e),this.health=this.maxHealth,this.explodedAt=null,this.blastQueued=!1,this.blastAge=0,this.lastBlastEmission=-1/0,this.lastDamageAt=t?performance.now():-1/0,this.healthBarShownAt=this.lastDamageAt}damage(e,t=performance.now()){return this.explodedAt!==null||!Number.isFinite(e)||e<=0||(this.health=Math.max(0,this.health-e),t-this.lastDamageAt>=2900&&(this.healthBarShownAt=t),this.lastDamageAt=t,this.health>0)?!1:(this.explodedAt=t,!0)}healthBarAlpha(e=performance.now()){let t=e-this.lastDamageAt;return this.stage===`burning`&&this.health>0?Math.max(0,Math.min(1,(e-this.healthBarShownAt)/120)):t<0||t>=2900?0:Math.min(1,(e-this.healthBarShownAt)/120,(2900-t)/650)}},_={defaultHealth:600,impactThresholdMps:3,impactDamagePerMps:5.5,maxImpactDamageFraction:.3,burningDamagePerSecond:14,respawnSeconds:2.5};function v(e,t){if(e<=0)return`exploded`;let n=e/Math.max(t,.001);return n<=p.ignitionFraction?`burning`:n<=p.smoulderFraction?`smouldering`:n<=p.smokeFraction?`smoking`:`intact`}function y(e,t){let n=e/Math.max(t,.001);return Math.max(0,Math.min(1,(p.smokeFraction-n)/p.smokeFraction))}function b(e,t,n){let r=Math.max(1,Math.min(e,t));return Math.max(13,r*.28)+r*.52*Math.max(0,Math.min(1,n))}function x(e,t,n,r){let i=v(e,t);if(i===`intact`||i===`exploded`)return null;let a=y(e,t),o=i===`burning`?Math.max(0,1-e/Math.max(t*p.ignitionFraction,.001)):0;return{stage:i,age:.19,spreadSeconds:0,burnSeconds:.8,fixedRadius:b(n,r,a),intensity:i===`burning`?.65+o*1.4:0,smokeOnly:i!==`burning`,smokeRate:i===`burning`?10+o*4:18+a*12}}function S(e){return{age:e,spreadSeconds:0,burnSeconds:p.fireballSeconds,blastAge:e,blastSeconds:p.fireballSeconds,smokeRate:12}}function C(e,t){return v(e,t)===`intact`||e<=0?0:.06+y(e,t)*.94}function w(e,t,i=0){let a=p.damagePerSecond;return e===`bullet`?a/(2*n(t).roundsPerSecond):e===`rocket`?a/r(t).roundsPerSecond:a*Math.max(0,i)}function T(e,t,n){return e*p.ignitionFraction*t/n}function E(e,t,n){let r=Number(e.getAttribute(t));return Number.isFinite(r)&&r>=0&&e.hasAttribute(t)?r:n}var D=(e=0,t=0)=>({x:e,y:t}),O=(e,t)=>D(e.x+t.x,e.y+t.y),k=(e,t)=>D(e.x-t.x,e.y-t.y),A=(e,t)=>D(e.x*t,e.y*t),j=(e,t)=>e.x*t.x+e.y*t.y,M=(e,t)=>e.x*t.y-e.y*t.x,N=e=>Math.hypot(e.x,e.y),P=(e,t)=>{let n=Math.cos(t),r=Math.sin(t);return D(e.x*n-e.y*r,e.x*r+e.y*n)},F=(e,t,n)=>Math.max(t,Math.min(n,e)),I=e=>Math.atan2(Math.sin(e),Math.cos(e));function L(e){let t=F(5.8+e.engineForceN/e.massKg*.12,6.5,8.5);return{speed:t,radius:t/F(t*Math.tan(e.maxSteerAngleRad)/e.geometry.wheelbaseM*.62,1.3,1.8)}}var R=class{mass=1e3;inertia=this.mass*20/12;position=D();velocity=D();angle=0;spin=0;force=D();torque=0;captureState(){return t({mass:this.mass,inertia:this.inertia,position:this.position,velocity:this.velocity,angle:this.angle,spin:this.spin,force:this.force,torque:this.torque})}restoreState(e){let n=t(e);this.mass=n.mass,this.inertia=n.inertia,this.position=n.position,this.velocity=n.velocity,this.angle=n.angle,this.spin=n.spin,this.force=n.force,this.torque=n.torque}reset(){this.position=D(),this.velocity=D(),this.angle=0,this.spin=0,this.force=D(),this.torque=0}world(e){return O(this.position,P(e,this.angle))}local(e){return P(k(e,this.position),-this.angle)}velocityAt(e){let t=k(e,this.position);return O(this.velocity,D(-this.spin*t.y,this.spin*t.x))}push(e,t=this.position){this.force=O(this.force,e),this.torque+=M(k(t,this.position),e)}impulse(e,t=this.position){this.velocity=O(this.velocity,A(e,1/this.mass)),this.spin+=M(k(t,this.position),e)/this.inertia}tick(e){this.velocity=O(this.velocity,A(this.force,e/this.mass)),this.spin+=this.torque*e/this.inertia,this.position=O(this.position,A(this.velocity,e)),this.angle+=this.spin*e,this.force=D(),this.torque=0}},z=class extends g{destructible=!0;get stage(){return this.destructible?super.stage:`intact`}damage(e,t=performance.now()){return this.destructible?super.damage(e,t):!1}tires=[];engineForce=0;rollingResistance=0;lateralResistance=0;handbrakeStrength=0;drifting=!1;donuting=!1;burnout=!1;launchSpinSeconds=0;boostCharge=0;boostReady=!1;get boostActive(){return this.statusEffects.remaining(`boost`)>0}burnOriginLocal=D(.7,0);statusEffects=new f;get oilDistanceRemainingM(){return this.statusEffects.remaining(`oil`)}get oilGripFactor(){return this.statusEffects.factorFrom(`oil`,`grip`,void 0,this.tires.length||4)}oilGripFactorFor(e){return this.statusEffects.factorFrom(`oil`,`grip`,e)}coatWithOil(e){if(e===void 0)for(let e=0;e<this.tires.length;e++)this.statusEffects.apply(`oil`,l.oil,e);else e>=0&&e<this.tires.length&&this.statusEffects.apply(`oil`,l.oil,e)}coatWithMud(e){if(e===void 0)for(let e=0;e<this.tires.length;e++)this.statusEffects.apply(`mud`,l.mud,e);else e>=0&&e<this.tires.length&&this.statusEffects.apply(`mud`,l.mud,e)}washWheel(e){e>=0&&e<this.tires.length&&(this.statusEffects.clearTire(e),this.tires[e].heat=0)}advanceOil(e){this.statusEffects.advance(e,0)}frontLoadFraction=.5;slideAngleRad=0;countersteering=!1;driftDirection=0;driftStart=null;donutDirection=0;steeringAngle=0;steeringReferenceSpeed=0;previousVelocity=null;longitudinalAcceleration=0;burnoutSeconds=0;boostChargeSeconds=0;boostUsed=!1;launchPeakRpm=0;launchAssistElapsed=0;launchAssistGainMps=0;preset=a.porsche911997;constructor(){super(_.defaultHealth),this.configure(a.porsche911997)}captureState(){return t({maxHealth:this.maxHealth,health:this.health,explodedAt:this.explodedAt,blastQueued:this.blastQueued,blastAge:this.blastAge,lastBlastEmission:this.lastBlastEmission,lastDamageAt:this.lastDamageAt,healthBarShownAt:this.healthBarShownAt,destructible:this.destructible,tires:this.tires,engineForce:this.engineForce,rollingResistance:this.rollingResistance,lateralResistance:this.lateralResistance,handbrakeStrength:this.handbrakeStrength,drifting:this.drifting,donuting:this.donuting,burnout:this.burnout,launchSpinSeconds:this.launchSpinSeconds,boostCharge:this.boostCharge,boostReady:this.boostReady,burnOriginLocal:this.burnOriginLocal,frontLoadFraction:this.frontLoadFraction,slideAngleRad:this.slideAngleRad,countersteering:this.countersteering,driftDirection:this.driftDirection,driftStart:this.driftStart,donutDirection:this.donutDirection,steeringAngle:this.steeringAngle,steeringReferenceSpeed:this.steeringReferenceSpeed,previousVelocity:this.previousVelocity,longitudinalAcceleration:this.longitudinalAcceleration,burnoutSeconds:this.burnoutSeconds,boostChargeSeconds:this.boostChargeSeconds,boostUsed:this.boostUsed,launchPeakRpm:this.launchPeakRpm,launchAssistElapsed:this.launchAssistElapsed,launchAssistGainMps:this.launchAssistGainMps,statusEffects:this.statusEffects.captureState()})}restoreState(e){let n=t(e);this.maxHealth=n.maxHealth,this.health=n.health,this.explodedAt=n.explodedAt,this.blastQueued=n.blastQueued,this.blastAge=n.blastAge,this.lastBlastEmission=n.lastBlastEmission,this.lastDamageAt=n.lastDamageAt,this.healthBarShownAt=n.healthBarShownAt,this.destructible=n.destructible,this.tires=n.tires,this.engineForce=n.engineForce,this.rollingResistance=n.rollingResistance,this.lateralResistance=n.lateralResistance,this.handbrakeStrength=n.handbrakeStrength,this.drifting=n.drifting,this.donuting=n.donuting,this.burnout=n.burnout,this.launchSpinSeconds=n.launchSpinSeconds,this.boostCharge=n.boostCharge,this.boostReady=n.boostReady,this.burnOriginLocal=n.burnOriginLocal,this.frontLoadFraction=n.frontLoadFraction,this.slideAngleRad=n.slideAngleRad,this.countersteering=n.countersteering,this.driftDirection=n.driftDirection,this.driftStart=n.driftStart,this.donutDirection=n.donutDirection,this.steeringAngle=n.steeringAngle,this.steeringReferenceSpeed=n.steeringReferenceSpeed,this.previousVelocity=n.previousVelocity,this.longitudinalAcceleration=n.longitudinalAcceleration,this.burnoutSeconds=n.burnoutSeconds,this.boostChargeSeconds=n.boostChargeSeconds,this.boostUsed=n.boostUsed,this.launchPeakRpm=n.launchPeakRpm,this.launchAssistElapsed=n.launchAssistElapsed,this.launchAssistGainMps=n.launchAssistGainMps,this.statusEffects.restoreState(n.statusEffects)}takeImpact(e,t=D(.7,0)){let n=this.stage===`burning`,r=Math.max(0,e-_.impactThresholdMps)*_.impactDamagePerMps,i=this.damage(Math.min(r,this.maxHealth*_.maxImpactDamageFraction));return!n&&this.health>0&&this.healthFraction<=p.ignitionFraction&&(this.burnOriginLocal={...t}),i}advanceBurn(e){return this.stage===`burning`&&this.damage(_.burningDamagePerSecond*Math.max(0,e))}configure(e){this.preset=e,this.engineForce=e.engineForceN,this.rollingResistance=e.rollingResistance,this.lateralResistance=e.lateralResistance,this.handbrakeStrength=e.handbrakeStrength;let{geometry:t}=e;this.tires=[{x:t.rearAxleXM??-t.wheelbaseM/2,track:t.rearTrackWidthM??t.trackWidthM,front:!1},{x:t.frontAxleXM??t.wheelbaseM/2,track:t.frontTrackWidthM??t.trackWidthM,front:!0}].flatMap(({x:e,track:t,front:n})=>[-t/2,t/2].map(t=>({local:D(e,t),front:n,angle:0,skidding:!1,lateralSpeed:0,slipSpeedMps:0,wheelSurfaceSpeedMps:0,slip:0,heat:0,spinning:!1,lateralForceN:0,gripUtilization:0}))),this.reset()}reset(){this.resetBurnable(this.preset.health??_.defaultHealth),this.burnOriginLocal=D(.7,0),this.drifting=!1,this.donuting=!1,this.frontLoadFraction=this.preset.frontWeightFraction??.5,this.slideAngleRad=0,this.countersteering=!1,this.driftDirection=0,this.driftStart=null,this.donutDirection=0,this.steeringAngle=0,this.steeringReferenceSpeed=0,this.previousVelocity=null,this.longitudinalAcceleration=0,this.burnout=!1,this.burnoutSeconds=0,this.launchPeakRpm=0,this.boostChargeSeconds=0,this.boostUsed=!1,this.boostCharge=0,this.boostReady=!1,this.launchSpinSeconds=0,this.launchAssistElapsed=0,this.launchAssistGainMps=0,this.statusEffects.clear();for(let e of this.tires)e.angle=0,e.skidding=!1,e.lateralSpeed=0,e.slipSpeedMps=0,e.wheelSurfaceSpeedMps=0,e.slip=0,e.heat=0,e.spinning=!1,e.lateralForceN=0,e.gripUtilization=0}get fastDrifting(){return this.driftDirection!==0}prepareDrift(e,t){let n=N(e.velocity),r=j(e.velocity,P(D(1,0),e.angle)),i=this.preset.drift;this.fastDrifting&&(!t.action||Math.abs(t.steer)<=.2||n<i.entrySpeedMps*.65||t.throttle<=.5)&&(this.driftDirection=0),!this.fastDrifting&&t.action&&Math.abs(t.steer)>.2&&r>i.entrySpeedMps&&t.throttle>.5&&(this.driftDirection=Math.sign(t.steer),this.statusEffects.remove(`boost`)),this.driftStart=this.fastDrifting?{position:{...e.position},velocity:{...e.velocity},angle:e.angle,spin:e.spin}:null}tick(e,t,n,r){this.prepareDrift(e,t);let i=this.fastDrifting?{...t,action:!1}:t;this.tickForces(e,i,n,r)}tickForces(e,t,n,r){let i=this.burnout,a=this.boostReady&&!!t.boost&&!this.boostUsed,o=t.action||(t.brake??0)>.5;if(t.boost||(this.boostUsed=!1),t.boost&&t.throttle>.5&&!o&&!this.fastDrifting?this.boostUsed||(this.boostUsed=!0,this.statusEffects.apply(`boost`,c(this.preset.driveBoost.gainMps,Math.min(this.preset.driveBoost.durationSeconds,2)))):this.statusEffects.remove(`boost`),this.burnout=o&&t.throttle>.5&&N(e.velocity)<1.2,this.burnout){this.burnoutSeconds+=n,this.boostChargeSeconds=t.boost&&!this.boostUsed?this.boostChargeSeconds+n:0;let e=Math.max(.1,this.preset.launch.burnoutRampSeconds);this.boostCharge=F(this.boostChargeSeconds/e,0,1),this.boostReady=this.boostChargeSeconds>=e&&this.burnoutSeconds>=e;let i=Math.max(r??0,this.preset.launch.minRpm*Math.min(1,this.burnoutSeconds/.9));this.launchPeakRpm=Math.max(this.launchPeakRpm,i)}else i&&!o&&t.throttle>.5?(this.burnoutSeconds>=.25&&this.launchPeakRpm>=this.preset.launch.minRpm&&(this.launchAssistGainMps=a?this.preset.launch.boostedBoostMps:this.preset.launch.boostMps,this.launchAssistElapsed=0),this.launchSpinSeconds=a?this.preset.launch.chargedSpinSeconds:.4):this.launchSpinSeconds=Math.max(0,this.launchSpinSeconds-n),this.burnoutSeconds=0,this.launchPeakRpm=0,this.boostChargeSeconds=0,this.boostCharge=0,this.boostReady=!1;let s=P(D(1,0),e.angle),l=Math.max(.1,this.preset.launch.assistDurationSeconds);if(this.launchAssistGainMps>0&&t.throttle>.5&&!o){let t=Math.min(l,this.launchAssistElapsed+n*.5),r=Math.sin(Math.PI*t/l);e.push(A(s,e.mass*this.launchAssistGainMps*Math.PI*r/(2*l))),this.launchAssistElapsed+=n,this.launchAssistElapsed>=l&&(this.launchAssistGainMps=0)}else this.launchAssistGainMps=0;let u=this.statusEffects.bonus(`forwardAccelerationMps2`,void 0,this.tires.length,n*.5);u>0&&t.throttle>.5&&!o&&e.push(A(s,e.mass*u));let d=D(-s.y,s.x),f=N(e.velocity),p=j(e.velocity,s),m=j(e.velocity,d),h=this.previousVelocity===null?0:F(j(k(e.velocity,this.previousVelocity),s)/Math.max(n,1e-4),-16,16);this.previousVelocity={...e.velocity},this.longitudinalAcceleration+=(h-this.longitudinalAcceleration)*(1-Math.exp(-n/.12));let g=this.preset.frontWeightFraction??.5;this.frontLoadFraction=F(g-this.longitudinalAcceleration*.012,.34,.68),this.slideAngleRad=Math.atan2(m,Math.max(2,Math.abs(p)));let _=Math.abs(t.steer),v=t.throttle>.5&&_>.8&&!t.action&&!this.fastDrifting;if(this.donuting?v&&Math.sign(t.steer)===this.donutDirection||(this.donuting=!1,this.donutDirection=0):v&&f<4.5&&(this.donuting=!0,this.donutDirection=Math.sign(t.steer)),this.drifting=this.fastDrifting||this.donuting,this.countersteering=this.fastDrifting&&t.steer*this.driftDirection<0,!this.drifting&&!t.action&&f>4&&p>0){let t=F(Math.abs(this.slideAngleRad)-.05,0,.8);e.spin+=Math.sign(this.slideAngleRad)*t*40*n}let y=t.throttle<0&&j(e.velocity,s)<=0,b=(t.action?.18:1)*(1-F(t.brake??0,0,1));e.push(A(s,t.throttle*b*this.engineForce*this.statusEffects.factor(`driveForce`,void 0,this.tires.length)*(y?this.preset.reversePowerRatio:1))),this.steeringReferenceSpeed=t.steer?Math.max(f,this.steeringReferenceSpeed-8*n):f;let x=Math.atan(this.preset.geometry.wheelbaseM*this.preset.corneringAccelerationMps2/(this.steeringReferenceSpeed**2+16)),S=t.steer*(this.donuting?this.preset.maxSteerAngleRad:Math.min(this.preset.maxSteerAngleRad,x));this.steeringAngle+=(S-this.steeringAngle)*(1-Math.exp(-n/(t.steer?.06:.04)));for(let[r,i]of this.tires.entries()){i.angle=i.front?this.steeringAngle:0;let a=e.world(i.local),o=e.velocityAt(a),s=e.angle+i.angle,c=D(Math.cos(s),Math.sin(s)),l=D(-c.y,c.x),u=j(o,c),d=j(o,l);i.lateralSpeed=Math.abs(d),i.spinning=!i.front&&(this.burnout||this.launchSpinSeconds>0||this.donuting);let p=!i.front&&t.action?Math.abs(u)*.65:0,m=this.burnout?5.2*(.3+.7*F(this.burnoutSeconds/Math.max(.1,this.preset.launch.burnoutRampSeconds),0,1))*(t.boost?1.6:1):5.2;i.wheelSurfaceSpeedMps=i.spinning?u+m:!i.front&&t.action?u*.35:u,i.slipSpeedMps=Math.max(i.lateralSpeed,p,Math.abs(i.wheelSurfaceSpeedMps-u)),i.slip=F((i.slipSpeedMps-.45)/4.8,0,1);let h=F((i.slipSpeedMps-.4)/5.2,0,1),_=h>i.heat?.65:2.2;i.heat+=(h-i.heat)*(1-Math.exp(-n/_));let v=i.front?this.frontLoadFraction:1-this.frontLoadFraction,y=F(v/(i.front?g:1-g),.65,1.35),b=(!i.front&&this.donuting?.5:1)*(1-i.heat*(i.front?.06:.12))*this.statusEffects.factor(`grip`,r),x=this.lateralResistance*(1+Math.min(f,40)/18)*y*b,S=e.mass*this.preset.corneringAccelerationMps2*v*.5*b,C=-x*d,w=F(C,-S,S);i.lateralForceN=w,i.gripUtilization=Math.abs(C)/Math.max(1,S);let T=Math.abs(C)>S*.92,E=i.skidding?1.2:1.8;i.skidding=i.spinning||i.slipSpeedMps>E&&(T||i.lateralSpeed>(i.front?2.8:2.1)||p>2.4);let k=this.rollingResistance*(!i.front&&t.action?1+this.handbrakeStrength*7:1);e.push(O(A(c,-k*u),A(l,w)),a)}}slow(e,t,n){let r=(t.throttle===0?this.preset.coastDecelerationMps2:0)+(t.action?this.preset.handbrakeDecelerationMps2:0),a=N(e.velocity);if(a===0)return;r&&(e.velocity=A(e.velocity,Math.max(0,a-r*n)/a));let o=F(t.brake??0,0,1);if(!o)return;let s=D(Math.cos(e.angle),Math.sin(e.angle)),c=j(e.velocity,s),l=Math.min(Math.abs(c),o*i(this.preset)*Math.max(.35,this.statusEffects.factor(`grip`,void 0,this.tires.length))*n);e.velocity=k(e.velocity,A(s,Math.sign(c)*l))}finishDrift(e,t,n){let r=this.driftStart;if(!this.fastDrifting||!r)return;let i=N(r.velocity),a=F(i/12,.55,1.2),o=this.driftDirection*(.92+.24*a)+F(t.steer,-1,1)*.47;e.spin=r.spin+(o-r.spin)*(1-Math.exp(-12*n)),e.angle=r.angle+e.spin*n;let s=N(e.velocity),c=Math.max(s,i-.5*n),l=Math.atan2(r.velocity.y,r.velocity.x),u=l+F(I(e.angle-this.driftDirection*this.preset.drift.slipAngleRad-l)*(1-Math.exp(-7*n)),-3.5*n,3.5*n);e.velocity=D(Math.cos(u)*c,Math.sin(u)*c),e.position=O(r.position,A(e.velocity,n)),this.slideAngleRad=I(u-e.angle);for(let e of this.tires)e.front||(e.skidding=!0,e.lateralSpeed=c*Math.sin(this.preset.drift.slipAngleRad),e.slipSpeedMps=Math.max(e.slipSpeedMps,e.lateralSpeed),e.slip=F(e.slipSpeedMps/4,0,1),e.heat+=(.8-e.heat)*(1-Math.exp(-2*n)),e.gripUtilization=Math.max(e.gripUtilization,1))}arcadeAssist(e,t,n){let r=N(e.velocity),{speed:i,radius:a}=L(this.preset);if(this.donuting){let t=i*this.statusEffects.factor(`speed`,void 0,this.tires.length),o=Math.atan2(e.velocity.y,e.velocity.x),s=e.angle-this.donutDirection*.22,c=Math.atan2(Math.sin(s-o),Math.cos(s-o))*(1-Math.exp(-n/.11)),l=r+(t-r)*(1-Math.exp(-n/.28));e.velocity=A(D(Math.cos(o+c),Math.sin(o+c)),l),e.spin=this.donutDirection*l/a;return}let o=P(D(1,0),e.angle);if(j(e.velocity,o)<-.35&&t.throttle<0&&!t.action){let i=this.preset.maxReverseSpeedMps??7;r>i&&(e.velocity=A(e.velocity,i/r)),e.spin=-t.steer*Math.min(r,i)/a;let s=A(o,-1),c=Math.atan2(M(s,e.velocity),j(s,e.velocity));e.velocity=P(e.velocity,-F(c,-.45,.45)*(1-Math.exp(-5*n)));return}if(r<2||this.drifting||t.action||j(e.velocity,o)<=0)return;let s=Math.atan2(M(o,e.velocity),j(o,e.velocity)),c=F((r-2)/10,0,1)*(t.steer?4.5:6)*this.statusEffects.factor(`grip`,void 0,this.tires.length),l=-F(s,-.55,.55)*(1-Math.exp(-c*n));e.velocity=P(e.velocity,l),t.steer||(e.spin*=Math.exp(-4.5*n))}},B=class{headAngle=0;appliedForce=D();craft=D(4,0);counterweight=D(-2,0);radius=.9;captureState(){return t({headAngle:this.headAngle,appliedForce:this.appliedForce,craft:this.craft,counterweight:this.counterweight,radius:this.radius})}restoreState(e){let n=t(e);this.headAngle=n.headAngle,this.appliedForce=n.appliedForce,Object.assign(this,{craft:n.craft,counterweight:n.counterweight,radius:n.radius})}reset(){this.headAngle=0,this.appliedForce=D()}tick(e,t,n){this.headAngle+=t.steer*2.5*n;let r=(t.throttle||+!!t.action)*5e3*(t.action?2:1);this.appliedForce=P(D(r,0),this.headAngle),e.push(P(this.appliedForce,e.angle),e.world(this.craft)),e.push(A(e.velocity,-e.mass*.12)),e.spin*=Math.exp(-.35*n)}},V=class{body=new R;car=new z;ship=new B;mode=`car`;gravity=!1;barrier=!1;paused=!1;lastInput={throttle:0,steer:0,action:!1};brickForce=null;captureState(){return{at:performance.now(),preset:t(this.car.preset),simulation:t({mode:this.mode,gravity:this.gravity,barrier:this.barrier,paused:this.paused,lastInput:this.lastInput,brickForce:this.brickForce}),body:this.body.captureState(),car:this.car.captureState(),ship:this.ship.captureState()}}restoreState(e){let n=t(e);this.setPreset(n.preset),this.body.restoreState(n.body),this.car.restoreState(n.car),this.ship.restoreState(n.ship),this.mode=n.simulation.mode,this.gravity=n.simulation.gravity,this.barrier=n.simulation.barrier,this.paused=n.simulation.paused,this.lastInput=n.simulation.lastInput,this.brickForce=n.simulation.brickForce;let r=performance.now()-n.at;this.car.explodedAt!==null&&(this.car.explodedAt+=r),Number.isFinite(this.car.lastBlastEmission)&&(this.car.lastBlastEmission+=r)}setPreset(e){this.car.configure(e),this.mode===`car`&&(this.body.mass=e.massKg,this.body.inertia=e.massKg*(e.geometry.lengthM**2+e.geometry.widthM**2)/12)}setMode(e){this.mode=e,this.body.mass=e===`car`?this.car.preset.massKg:1e3,this.body.inertia=e===`ship`?this.body.mass*(1/3*(1.8**2/18+.8**2/6+16)+2/3*(.9**2/2+4)):this.body.mass*(this.car.preset.geometry.lengthM**2+this.car.preset.geometry.widthM**2)/12,this.car.reset(),this.ship.reset(),this.brickForce=null}reset(){this.body.reset(),this.car.reset(),this.ship.reset(),this.brickForce=null,this.lastInput={throttle:0,steer:0,action:!1}}resetAtCurrentPose(){let e={...this.body.position},t=this.body.angle;this.reset(),this.body.position=e,this.body.angle=t}tick(e,t,n){if(this.paused)return;if(this.mode===`car`&&this.car.explodedAt!==null){this.body.velocity=D(),this.body.spin=0,this.lastInput={throttle:0,steer:0,action:!1,boost:!1};return}this.lastInput={...e};let r=this.body,i={...r.position};if(this.gravity){let e=r.mass*3/30;r.push(D(-e*r.velocity.x,-r.mass*3-e*r.velocity.y))}if(this.mode===`car`&&this.car.tick(r,e,t,n),this.mode===`ship`){let n=r.angle;this.ship.tick(r,e,t),r.tick(t),this.ship.headAngle-=r.angle-n}else if(this.mode===`brick`&&this.brickForce&&r.push(this.brickForce.force,r.world(this.brickForce.local)),r.tick(t),this.mode===`car`){let n=this.car.fastDrifting?{...e,action:!1}:e;this.car.slow(r,n,t),this.car.fastDrifting?this.car.finishDrift(r,e,t):this.car.arcadeAssist(r,n,t);let a=this.car.statusEffects.factor(`speed`,void 0,this.car.tires.length);a<1&&(r.velocity=A(r.velocity,Math.exp(-5*(1-a)*t))),this.car.statusEffects.advance(N(k(r.position,i)),t)}}contain(e){let t=this.body,n=this.mode===`car`?this.car.preset.geometry.lengthM/2:2,r=this.mode===`car`?this.car.preset.geometry.widthM/2:1,i=this.mode===`ship`?[D(1.2,0),D(-.6,-.8),D(-.6,.8)].map(e=>t.world(O(this.ship.craft,P(e,this.ship.headAngle)))):[D(-n,-r),D(n,-r),D(n,r),D(-n,r)].map(e=>t.world(e));this.mode===`ship`&&i.push(t.world(this.ship.counterweight));let a=[[D(1),e.left],[D(-1),-e.right],[D(0,1),e.bottom],[D(0,-1),-e.top]];for(let e=0;e<4;e++)for(let[e,n]of a){let r=i.map(t=>j(t,e)-(this.mode===`ship`?this.ship.radius:0)),a=Math.min(...r),o=n-a;if(o<-1e-8)continue;let s=i[r.indexOf(a)],c=A(e,Math.max(0,o));t.position=O(t.position,c);for(let e of i)e.x+=c.x,e.y+=c.y;let l=O(s,A(e,this.mode===`ship`?-this.ship.radius:0)),u=j(t.velocityAt(l),e);if(u>=0)continue;let d=M(k(l,t.position),e),f=1/t.mass+d*d/t.inertia;t.impulse(A(e,-(1+(u<-.5?.55:0))*u/f),l)}}};export{o as C,s as S,S as _,N as a,_ as b,P as c,g as d,C as f,x as g,w as h,j as i,A as l,p as m,F as n,k as o,T as p,M as r,O as s,V as t,D as u,v,u as x,h as y};
1
+ import{a as e}from"./definitions~index~embed~bookmarklet~vehicle-popover~Documentation~JoyRideView~browser-sessi~fklztn3g-BG7sJuWo.js";import{r as t}from"./definitions~index~embed~vehicle-popover~browser-session-core~renderer-RDNEXk_b.js";import{i as n,o as r,s as i,u as a}from"./configuration~index~embed~bookmarklet-6dUo7fKK.js";function o(e,t){}function s(e,t=1){}function c(e,t){return{lifetime:{unit:`seconds`,amount:t},intensity:`constant`,modifiers:{driveForce:1.08,grip:1.04},additiveModifiers:{forwardAccelerationMps2:e/Math.max(.1,t)}}}var l={oil:{lifetime:{unit:`distanceM`,amount:e.oil.effectDistanceM},modifiers:{grip:e.oil.minimumGrip}},mud:{lifetime:{unit:`distanceM`,amount:e.mud.effectDistanceM},modifiers:{grip:e.mud.minimumGrip,speed:e.mud.speedFactor,driveForce:e.mud.driveForceFactor}}},u={mud:{grip:e.mud.contactGrip,speed:e.mud.contactSpeedFactor,driveForce:e.mud.contactDriveForceFactor}};function d(e,t=0){let n=e.definition.lifetime.unit===`seconds`?Math.max(0,e.remaining-t):e.remaining,r=Math.min(1,n/e.definition.lifetime.amount);return e.definition.intensity===`constant`?+(n>0):e.definition.intensity===`pulse`?Math.sin(Math.PI*(1-r)):r}var f=class{active=new Map;contacts=new Map;captureState(){return t({active:this.active,contacts:this.contacts})}restoreState(e){let n=t(e);this.active=n.active,this.contacts=n.contacts}setContacts(e,t,n){n.length?this.contacts.set(e,new Map(n.map(e=>[e,t]))):this.contacts.delete(e)}apply(e,t,n){if(t.lifetime.amount<=0)return;let r=this.active.get(e);r||(r=new Map,this.active.set(e,r)),r.set(n??`vehicle`,{remaining:t.lifetime.amount,definition:t})}remaining(e,t){let n=this.active.get(e);return t===void 0?Math.max(0,...[...n?.values()??[]].map(e=>e.remaining)):n?.get(t)?.remaining??0}remove(e){this.active.delete(e)}bonus(e,t,n=4,r=0){if(t===void 0){let t=0;for(let i=0;i<n;i++)t+=this.bonus(e,i,n,r);return t/n}let i=0;for(let n of this.active.values())for(let a of[`vehicle`,t]){let t=n.get(a);i+=(t?.definition.additiveModifiers?.[e]??0)*(t?d(t,r):0)}return i}indicators(){return[...new Set([...this.active.keys(),...this.contacts.keys()])].map(e=>{let t=this.active.get(e),n=Math.max(0,...[...t?.values()??[]].map(e=>Math.min(1,e.remaining/e.definition.lifetime.amount)));return{label:e.charAt(0).toUpperCase()+e.slice(1),fraction:this.contacts.has(e)?1:n}})}factor(e,t,n=4){return this.factorFrom(null,e,t,n)}factorFrom(e,t,n,r=4){if(n===void 0){let n=0;for(let i=0;i<r;i++)n+=this.factorFrom(e,t,i);return n/r}let i=1;for(let[r,a]of this.active)for(let o of[`vehicle`,n]){if(e!==null&&r!==e)continue;let n=a.get(o),s=n?.definition.modifiers[t];if(n&&s!==void 0){let e=d(n);i*=1+(s-1)*e}}for(let[r,a]of this.contacts)for(let o of[`vehicle`,n])(e===null||r===e)&&(i*=a.get(o)?.[t]??1);return i}advance(e,t){for(let[n,r]of this.active){for(let[n,i]of r){let a=i.definition.lifetime.unit===`distanceM`?e:t;i.remaining=Math.max(0,i.remaining-Math.max(0,a)),i.remaining===0&&r.delete(n)}r.size===0&&this.active.delete(n)}}clearTire(e){for(let[t,n]of this.active)n.delete(e),n.size===0&&this.active.delete(t);for(let[t,n]of this.contacts)n.delete(e),n.size===0&&this.contacts.delete(t)}clear(){this.active.clear(),this.contacts.clear()}},p={defaultHealth:100,smokeFraction:.5,smoulderFraction:.35,ignitionFraction:.25,damagePerSecond:48,burnDownSeconds:8,impactDamagePerMps:3.5,explosionSeconds:.8,fireballSeconds:.38,blastRadiusPx:78},m={pixelsPerTenPoints:2500,minimum:10,maximum:1e3};function h(e,t,n){let r=Math.max(0,t)*Math.max(0,n);return E(e,`data-jr-points`,Math.min(m.maximum,Math.max(m.minimum,Math.round(r/m.pixelsPerTenPoints)*10)))}var g=class{maxHealth;health;explodedAt=null;blastQueued=!1;blastAge=0;lastBlastEmission=-1/0;lastDamageAt=-1/0;healthBarShownAt=-1/0;constructor(e=p.defaultHealth){this.maxHealth=e,this.maxHealth=Math.max(1,e),this.health=this.maxHealth}get stage(){return v(this.health,this.maxHealth)}get healthFraction(){return this.health/this.maxHealth}resetBurnable(e=this.maxHealth){let t=this.health!==Math.max(1,e);this.maxHealth=Math.max(1,e),this.health=this.maxHealth,this.explodedAt=null,this.blastQueued=!1,this.blastAge=0,this.lastBlastEmission=-1/0,this.lastDamageAt=t?performance.now():-1/0,this.healthBarShownAt=this.lastDamageAt}damage(e,t=performance.now()){return this.explodedAt!==null||!Number.isFinite(e)||e<=0||(this.health=Math.max(0,this.health-e),t-this.lastDamageAt>=2900&&(this.healthBarShownAt=t),this.lastDamageAt=t,this.health>0)?!1:(this.explodedAt=t,!0)}healthBarAlpha(e=performance.now()){let t=e-this.lastDamageAt;return this.stage===`burning`&&this.health>0?Math.max(0,Math.min(1,(e-this.healthBarShownAt)/120)):t<0||t>=2900?0:Math.min(1,(e-this.healthBarShownAt)/120,(2900-t)/650)}},_={defaultHealth:600,impactThresholdMps:3,impactDamagePerMps:5.5,maxImpactDamageFraction:.3,burningDamagePerSecond:14,respawnSeconds:2.5};function v(e,t){if(e<=0)return`exploded`;let n=e/Math.max(t,.001);return n<=p.ignitionFraction?`burning`:n<=p.smoulderFraction?`smouldering`:n<=p.smokeFraction?`smoking`:`intact`}function y(e,t){let n=e/Math.max(t,.001);return Math.max(0,Math.min(1,(p.smokeFraction-n)/p.smokeFraction))}function b(e,t,n){let r=Math.max(1,Math.min(e,t));return Math.max(13,r*.28)+r*.52*Math.max(0,Math.min(1,n))}function x(e,t,n,r){let i=v(e,t);if(i===`intact`||i===`exploded`)return null;let a=y(e,t),o=i===`burning`?Math.max(0,1-e/Math.max(t*p.ignitionFraction,.001)):0;return{stage:i,age:.19,spreadSeconds:0,burnSeconds:.8,fixedRadius:b(n,r,a),intensity:i===`burning`?.65+o*1.4:0,smokeOnly:i!==`burning`,smokeRate:i===`burning`?10+o*4:18+a*12}}function S(e){return{age:e,spreadSeconds:0,burnSeconds:p.fireballSeconds,blastAge:e,blastSeconds:p.fireballSeconds,smokeRate:12}}function C(e,t){return v(e,t)===`intact`||e<=0?0:.06+y(e,t)*.94}function w(e,t,i=0){let a=p.damagePerSecond;return e===`bullet`?a/(2*n(t).roundsPerSecond):e===`rocket`?a/r(t).roundsPerSecond:a*Math.max(0,i)}function T(e,t,n){return e*p.ignitionFraction*t/n}function E(e,t,n){let r=Number(e.getAttribute(t));return Number.isFinite(r)&&r>=0&&e.hasAttribute(t)?r:n}var D=(e=0,t=0)=>({x:e,y:t}),O=(e,t)=>D(e.x+t.x,e.y+t.y),k=(e,t)=>D(e.x-t.x,e.y-t.y),A=(e,t)=>D(e.x*t,e.y*t),j=(e,t)=>e.x*t.x+e.y*t.y,M=(e,t)=>e.x*t.y-e.y*t.x,N=e=>Math.hypot(e.x,e.y),P=(e,t)=>{let n=Math.cos(t),r=Math.sin(t);return D(e.x*n-e.y*r,e.x*r+e.y*n)},F=(e,t,n)=>Math.max(t,Math.min(n,e)),I=e=>Math.atan2(Math.sin(e),Math.cos(e));function L(e){let t=F(5.8+e.engineForceN/e.massKg*.12,6.5,8.5);return{speed:t,radius:t/F(t*Math.tan(e.maxSteerAngleRad)/e.geometry.wheelbaseM*.62,1.3,1.8)}}var R=class{mass=1e3;inertia=this.mass*20/12;position=D();velocity=D();angle=0;spin=0;force=D();torque=0;captureState(){return t({mass:this.mass,inertia:this.inertia,position:this.position,velocity:this.velocity,angle:this.angle,spin:this.spin,force:this.force,torque:this.torque})}restoreState(e){let n=t(e);this.mass=n.mass,this.inertia=n.inertia,this.position=n.position,this.velocity=n.velocity,this.angle=n.angle,this.spin=n.spin,this.force=n.force,this.torque=n.torque}reset(){this.position=D(),this.velocity=D(),this.angle=0,this.spin=0,this.force=D(),this.torque=0}world(e){return O(this.position,P(e,this.angle))}local(e){return P(k(e,this.position),-this.angle)}velocityAt(e){let t=k(e,this.position);return O(this.velocity,D(-this.spin*t.y,this.spin*t.x))}push(e,t=this.position){this.force=O(this.force,e),this.torque+=M(k(t,this.position),e)}impulse(e,t=this.position){this.velocity=O(this.velocity,A(e,1/this.mass)),this.spin+=M(k(t,this.position),e)/this.inertia}tick(e){this.velocity=O(this.velocity,A(this.force,e/this.mass)),this.spin+=this.torque*e/this.inertia,this.position=O(this.position,A(this.velocity,e)),this.angle+=this.spin*e,this.force=D(),this.torque=0}},z=class extends g{destructible=!0;get stage(){return this.destructible?super.stage:`intact`}damage(e,t=performance.now()){return this.destructible?super.damage(e,t):!1}tires=[];engineForce=0;rollingResistance=0;lateralResistance=0;handbrakeStrength=0;drifting=!1;donuting=!1;burnout=!1;launchSpinSeconds=0;boostCharge=0;boostReady=!1;get boostActive(){return this.statusEffects.remaining(`boost`)>0}burnOriginLocal=D(.7,0);statusEffects=new f;get oilDistanceRemainingM(){return this.statusEffects.remaining(`oil`)}get oilGripFactor(){return this.statusEffects.factorFrom(`oil`,`grip`,void 0,this.tires.length||4)}oilGripFactorFor(e){return this.statusEffects.factorFrom(`oil`,`grip`,e)}coatWithOil(e){if(e===void 0)for(let e=0;e<this.tires.length;e++)this.statusEffects.apply(`oil`,l.oil,e);else e>=0&&e<this.tires.length&&this.statusEffects.apply(`oil`,l.oil,e)}coatWithMud(e){if(e===void 0)for(let e=0;e<this.tires.length;e++)this.statusEffects.apply(`mud`,l.mud,e);else e>=0&&e<this.tires.length&&this.statusEffects.apply(`mud`,l.mud,e)}washWheel(e){e>=0&&e<this.tires.length&&(this.statusEffects.clearTire(e),this.tires[e].heat=0)}advanceOil(e){this.statusEffects.advance(e,0)}frontLoadFraction=.5;slideAngleRad=0;countersteering=!1;driftDirection=0;driftStart=null;donutDirection=0;steeringAngle=0;steeringReferenceSpeed=0;previousVelocity=null;longitudinalAcceleration=0;burnoutSeconds=0;boostChargeSeconds=0;boostUsed=!1;launchPeakRpm=0;launchAssistElapsed=0;launchAssistGainMps=0;preset=a.porsche911997;constructor(){super(_.defaultHealth),this.configure(a.porsche911997)}captureState(){return t({maxHealth:this.maxHealth,health:this.health,explodedAt:this.explodedAt,blastQueued:this.blastQueued,blastAge:this.blastAge,lastBlastEmission:this.lastBlastEmission,lastDamageAt:this.lastDamageAt,healthBarShownAt:this.healthBarShownAt,destructible:this.destructible,tires:this.tires,engineForce:this.engineForce,rollingResistance:this.rollingResistance,lateralResistance:this.lateralResistance,handbrakeStrength:this.handbrakeStrength,drifting:this.drifting,donuting:this.donuting,burnout:this.burnout,launchSpinSeconds:this.launchSpinSeconds,boostCharge:this.boostCharge,boostReady:this.boostReady,burnOriginLocal:this.burnOriginLocal,frontLoadFraction:this.frontLoadFraction,slideAngleRad:this.slideAngleRad,countersteering:this.countersteering,driftDirection:this.driftDirection,driftStart:this.driftStart,donutDirection:this.donutDirection,steeringAngle:this.steeringAngle,steeringReferenceSpeed:this.steeringReferenceSpeed,previousVelocity:this.previousVelocity,longitudinalAcceleration:this.longitudinalAcceleration,burnoutSeconds:this.burnoutSeconds,boostChargeSeconds:this.boostChargeSeconds,boostUsed:this.boostUsed,launchPeakRpm:this.launchPeakRpm,launchAssistElapsed:this.launchAssistElapsed,launchAssistGainMps:this.launchAssistGainMps,statusEffects:this.statusEffects.captureState()})}restoreState(e){let n=t(e);this.maxHealth=n.maxHealth,this.health=n.health,this.explodedAt=n.explodedAt,this.blastQueued=n.blastQueued,this.blastAge=n.blastAge,this.lastBlastEmission=n.lastBlastEmission,this.lastDamageAt=n.lastDamageAt,this.healthBarShownAt=n.healthBarShownAt,this.destructible=n.destructible,this.tires=n.tires,this.engineForce=n.engineForce,this.rollingResistance=n.rollingResistance,this.lateralResistance=n.lateralResistance,this.handbrakeStrength=n.handbrakeStrength,this.drifting=n.drifting,this.donuting=n.donuting,this.burnout=n.burnout,this.launchSpinSeconds=n.launchSpinSeconds,this.boostCharge=n.boostCharge,this.boostReady=n.boostReady,this.burnOriginLocal=n.burnOriginLocal,this.frontLoadFraction=n.frontLoadFraction,this.slideAngleRad=n.slideAngleRad,this.countersteering=n.countersteering,this.driftDirection=n.driftDirection,this.driftStart=n.driftStart,this.donutDirection=n.donutDirection,this.steeringAngle=n.steeringAngle,this.steeringReferenceSpeed=n.steeringReferenceSpeed,this.previousVelocity=n.previousVelocity,this.longitudinalAcceleration=n.longitudinalAcceleration,this.burnoutSeconds=n.burnoutSeconds,this.boostChargeSeconds=n.boostChargeSeconds,this.boostUsed=n.boostUsed,this.launchPeakRpm=n.launchPeakRpm,this.launchAssistElapsed=n.launchAssistElapsed,this.launchAssistGainMps=n.launchAssistGainMps,this.statusEffects.restoreState(n.statusEffects)}takeImpact(e,t=D(.7,0)){let n=this.stage===`burning`,r=Math.max(0,e-_.impactThresholdMps)*_.impactDamagePerMps,i=this.damage(Math.min(r,this.maxHealth*_.maxImpactDamageFraction));return!n&&this.health>0&&this.healthFraction<=p.ignitionFraction&&(this.burnOriginLocal={...t}),i}advanceBurn(e){return this.stage===`burning`&&this.damage(_.burningDamagePerSecond*Math.max(0,e))}configure(e){this.preset=e,this.engineForce=e.engineForceN,this.rollingResistance=e.rollingResistance,this.lateralResistance=e.lateralResistance,this.handbrakeStrength=e.handbrakeStrength;let{geometry:t}=e;this.tires=[{x:t.rearAxleXM??-t.wheelbaseM/2,track:t.rearTrackWidthM??t.trackWidthM,front:!1},{x:t.frontAxleXM??t.wheelbaseM/2,track:t.frontTrackWidthM??t.trackWidthM,front:!0}].flatMap(({x:e,track:t,front:n})=>[-t/2,t/2].map(t=>({local:D(e,t),front:n,angle:0,skidding:!1,lateralSpeed:0,slipSpeedMps:0,wheelSurfaceSpeedMps:0,slip:0,heat:0,spinning:!1,lateralForceN:0,gripUtilization:0}))),this.reset()}reset(){this.resetBurnable(this.preset.health??_.defaultHealth),this.burnOriginLocal=D(.7,0),this.drifting=!1,this.donuting=!1,this.frontLoadFraction=this.preset.frontWeightFraction??.5,this.slideAngleRad=0,this.countersteering=!1,this.driftDirection=0,this.driftStart=null,this.donutDirection=0,this.steeringAngle=0,this.steeringReferenceSpeed=0,this.previousVelocity=null,this.longitudinalAcceleration=0,this.burnout=!1,this.burnoutSeconds=0,this.launchPeakRpm=0,this.boostChargeSeconds=0,this.boostUsed=!1,this.boostCharge=0,this.boostReady=!1,this.launchSpinSeconds=0,this.launchAssistElapsed=0,this.launchAssistGainMps=0,this.statusEffects.clear();for(let e of this.tires)e.angle=0,e.skidding=!1,e.lateralSpeed=0,e.slipSpeedMps=0,e.wheelSurfaceSpeedMps=0,e.slip=0,e.heat=0,e.spinning=!1,e.lateralForceN=0,e.gripUtilization=0}get fastDrifting(){return this.driftDirection!==0}prepareDrift(e,t){let n=N(e.velocity),r=j(e.velocity,P(D(1,0),e.angle)),i=this.preset.drift;this.fastDrifting&&(!t.action||Math.abs(t.steer)<=.2||n<i.entrySpeedMps*.65||t.throttle<=.5)&&(this.driftDirection=0),!this.fastDrifting&&t.action&&Math.abs(t.steer)>.2&&r>i.entrySpeedMps&&t.throttle>.5&&(this.driftDirection=Math.sign(t.steer),this.statusEffects.remove(`boost`)),this.driftStart=this.fastDrifting?{position:{...e.position},velocity:{...e.velocity},angle:e.angle,spin:e.spin}:null}tick(e,t,n,r){this.prepareDrift(e,t);let i=this.fastDrifting?{...t,action:!1}:t;this.tickForces(e,i,n,r)}tickForces(e,t,n,r){let i=this.burnout,a=this.boostReady&&!!t.boost&&!this.boostUsed,o=t.action||(t.brake??0)>.5;if(t.boost||(this.boostUsed=!1),t.boost&&t.throttle>.5&&!o&&!this.fastDrifting?this.boostUsed||(this.boostUsed=!0,this.statusEffects.apply(`boost`,c(this.preset.driveBoost.gainMps,Math.min(this.preset.driveBoost.durationSeconds,2)))):this.statusEffects.remove(`boost`),this.burnout=o&&t.throttle>.5&&N(e.velocity)<1.2,this.burnout){this.burnoutSeconds+=n,this.boostChargeSeconds=t.boost&&!this.boostUsed?this.boostChargeSeconds+n:0;let e=Math.max(.1,this.preset.launch.burnoutRampSeconds);this.boostCharge=F(this.boostChargeSeconds/e,0,1),this.boostReady=this.boostChargeSeconds>=e&&this.burnoutSeconds>=e;let i=Math.max(r??0,this.preset.launch.minRpm*Math.min(1,this.burnoutSeconds/.9));this.launchPeakRpm=Math.max(this.launchPeakRpm,i)}else i&&!o&&t.throttle>.5?(this.burnoutSeconds>=.25&&this.launchPeakRpm>=this.preset.launch.minRpm&&(this.launchAssistGainMps=a?this.preset.launch.boostedBoostMps:this.preset.launch.boostMps,this.launchAssistElapsed=0),this.launchSpinSeconds=a?this.preset.launch.chargedSpinSeconds:.4):this.launchSpinSeconds=Math.max(0,this.launchSpinSeconds-n),this.burnoutSeconds=0,this.launchPeakRpm=0,this.boostChargeSeconds=0,this.boostCharge=0,this.boostReady=!1;let s=P(D(1,0),e.angle),l=Math.max(.1,this.preset.launch.assistDurationSeconds);if(this.launchAssistGainMps>0&&t.throttle>.5&&!o){let t=Math.min(l,this.launchAssistElapsed+n*.5),r=Math.sin(Math.PI*t/l);e.push(A(s,e.mass*this.launchAssistGainMps*Math.PI*r/(2*l))),this.launchAssistElapsed+=n,this.launchAssistElapsed>=l&&(this.launchAssistGainMps=0)}else this.launchAssistGainMps=0;let u=this.statusEffects.bonus(`forwardAccelerationMps2`,void 0,this.tires.length,n*.5);u>0&&t.throttle>.5&&!o&&e.push(A(s,e.mass*u));let d=D(-s.y,s.x),f=N(e.velocity),p=j(e.velocity,s),m=j(e.velocity,d),h=this.previousVelocity===null?0:F(j(k(e.velocity,this.previousVelocity),s)/Math.max(n,1e-4),-16,16);this.previousVelocity={...e.velocity},this.longitudinalAcceleration+=(h-this.longitudinalAcceleration)*(1-Math.exp(-n/.12));let g=this.preset.frontWeightFraction??.5;this.frontLoadFraction=F(g-this.longitudinalAcceleration*.012,.34,.68),this.slideAngleRad=Math.atan2(m,Math.max(2,Math.abs(p)));let _=Math.abs(t.steer),v=t.throttle>.5&&_>.8&&!t.action&&!this.fastDrifting;if(this.donuting?v&&Math.sign(t.steer)===this.donutDirection||(this.donuting=!1,this.donutDirection=0):v&&f<4.5&&(this.donuting=!0,this.donutDirection=Math.sign(t.steer)),this.drifting=this.fastDrifting||this.donuting,this.countersteering=this.fastDrifting&&t.steer*this.driftDirection<0,!this.drifting&&!t.action&&f>4&&p>0){let t=F(Math.abs(this.slideAngleRad)-.05,0,.8);e.spin+=Math.sign(this.slideAngleRad)*t*40*n}let y=t.throttle<0&&j(e.velocity,s)<=0,b=(t.action?.18:1)*(1-F(t.brake??0,0,1));e.push(A(s,t.throttle*b*this.engineForce*this.statusEffects.factor(`driveForce`,void 0,this.tires.length)*(y?this.preset.reversePowerRatio:1))),this.steeringReferenceSpeed=t.steer?Math.max(f,this.steeringReferenceSpeed-8*n):f;let x=Math.atan(this.preset.geometry.wheelbaseM*this.preset.corneringAccelerationMps2/(this.steeringReferenceSpeed**2+16)),S=t.steer*(this.donuting?this.preset.maxSteerAngleRad:Math.min(this.preset.maxSteerAngleRad,x));this.steeringAngle+=(S-this.steeringAngle)*(1-Math.exp(-n/(t.steer?.06:.04)));for(let[r,i]of this.tires.entries()){i.angle=i.front?this.steeringAngle:0;let a=e.world(i.local),o=e.velocityAt(a),s=e.angle+i.angle,c=D(Math.cos(s),Math.sin(s)),l=D(-c.y,c.x),u=j(o,c),d=j(o,l);i.lateralSpeed=Math.abs(d),i.spinning=!i.front&&(this.burnout||this.launchSpinSeconds>0||this.donuting);let p=!i.front&&t.action?Math.abs(u)*.65:0,m=this.burnout?5.2*(.3+.7*F(this.burnoutSeconds/Math.max(.1,this.preset.launch.burnoutRampSeconds),0,1))*(t.boost?1.6:1):5.2;i.wheelSurfaceSpeedMps=i.spinning?u+m:!i.front&&t.action?u*.35:u,i.slipSpeedMps=Math.max(i.lateralSpeed,p,Math.abs(i.wheelSurfaceSpeedMps-u)),i.slip=F((i.slipSpeedMps-.45)/4.8,0,1);let h=F((i.slipSpeedMps-.4)/5.2,0,1),_=h>i.heat?.65:2.2;i.heat+=(h-i.heat)*(1-Math.exp(-n/_));let v=i.front?this.frontLoadFraction:1-this.frontLoadFraction,y=F(v/(i.front?g:1-g),.65,1.35),b=(!i.front&&this.donuting?.5:1)*(1-i.heat*(i.front?.06:.12))*this.statusEffects.factor(`grip`,r),x=this.lateralResistance*(1+Math.min(f,40)/18)*y*b,S=e.mass*this.preset.corneringAccelerationMps2*v*.5*b,C=-x*d,w=F(C,-S,S);i.lateralForceN=w,i.gripUtilization=Math.abs(C)/Math.max(1,S);let T=Math.abs(C)>S*.92,E=i.skidding?1.2:1.8;i.skidding=i.spinning||i.slipSpeedMps>E&&(T||i.lateralSpeed>(i.front?2.8:2.1)||p>2.4);let k=this.rollingResistance*(!i.front&&t.action?1+this.handbrakeStrength*7:1);e.push(O(A(c,-k*u),A(l,w)),a)}}slow(e,t,n){let r=(t.throttle===0?this.preset.coastDecelerationMps2:0)+(t.action?this.preset.handbrakeDecelerationMps2:0),a=N(e.velocity);if(a===0)return;r&&(e.velocity=A(e.velocity,Math.max(0,a-r*n)/a));let o=F(t.brake??0,0,1);if(!o)return;let s=D(Math.cos(e.angle),Math.sin(e.angle)),c=j(e.velocity,s),l=Math.min(Math.abs(c),o*i(this.preset)*Math.max(.35,this.statusEffects.factor(`grip`,void 0,this.tires.length))*n);e.velocity=k(e.velocity,A(s,Math.sign(c)*l))}finishDrift(e,t,n){let r=this.driftStart;if(!this.fastDrifting||!r)return;let i=N(r.velocity),a=F(i/12,.55,1.2),o=this.driftDirection*(.92+.24*a)+F(t.steer,-1,1)*.47;e.spin=r.spin+(o-r.spin)*(1-Math.exp(-12*n)),e.angle=r.angle+e.spin*n;let s=N(e.velocity),c=Math.max(s,i-.5*n),l=Math.atan2(r.velocity.y,r.velocity.x),u=l+F(I(e.angle-this.driftDirection*this.preset.drift.slipAngleRad-l)*(1-Math.exp(-7*n)),-3.5*n,3.5*n);e.velocity=D(Math.cos(u)*c,Math.sin(u)*c),e.position=O(r.position,A(e.velocity,n)),this.slideAngleRad=I(u-e.angle);for(let e of this.tires)e.front||(e.skidding=!0,e.lateralSpeed=c*Math.sin(this.preset.drift.slipAngleRad),e.slipSpeedMps=Math.max(e.slipSpeedMps,e.lateralSpeed),e.slip=F(e.slipSpeedMps/4,0,1),e.heat+=(.8-e.heat)*(1-Math.exp(-2*n)),e.gripUtilization=Math.max(e.gripUtilization,1))}arcadeAssist(e,t,n){let r=N(e.velocity),{speed:i,radius:a}=L(this.preset);if(this.donuting){let t=i*this.statusEffects.factor(`speed`,void 0,this.tires.length),o=Math.atan2(e.velocity.y,e.velocity.x),s=e.angle-this.donutDirection*.22,c=Math.atan2(Math.sin(s-o),Math.cos(s-o))*(1-Math.exp(-n/.11)),l=r+(t-r)*(1-Math.exp(-n/.28));e.velocity=A(D(Math.cos(o+c),Math.sin(o+c)),l),e.spin=this.donutDirection*l/a;return}let o=P(D(1,0),e.angle);if(j(e.velocity,o)<-.35&&t.throttle<0&&!t.action){let i=this.preset.maxReverseSpeedMps??7;r>i&&(e.velocity=A(e.velocity,i/r)),e.spin=-t.steer*Math.min(r,i)/a;let s=A(o,-1),c=Math.atan2(M(s,e.velocity),j(s,e.velocity));e.velocity=P(e.velocity,-F(c,-.45,.45)*(1-Math.exp(-5*n)));return}if(r<2||this.drifting||t.action||j(e.velocity,o)<=0)return;let s=Math.atan2(M(o,e.velocity),j(o,e.velocity)),c=F((r-2)/10,0,1)*(t.steer?4.5:6)*this.statusEffects.factor(`grip`,void 0,this.tires.length),l=-F(s,-.55,.55)*(1-Math.exp(-c*n));e.velocity=P(e.velocity,l),t.steer||(e.spin*=Math.exp(-4.5*n))}},B=class{headAngle=0;appliedForce=D();craft=D(4,0);counterweight=D(-2,0);radius=.9;captureState(){return t({headAngle:this.headAngle,appliedForce:this.appliedForce,craft:this.craft,counterweight:this.counterweight,radius:this.radius})}restoreState(e){let n=t(e);this.headAngle=n.headAngle,this.appliedForce=n.appliedForce,Object.assign(this,{craft:n.craft,counterweight:n.counterweight,radius:n.radius})}reset(){this.headAngle=0,this.appliedForce=D()}tick(e,t,n){this.headAngle+=t.steer*2.5*n;let r=(t.throttle||+!!t.action)*5e3*(t.action?2:1);this.appliedForce=P(D(r,0),this.headAngle),e.push(P(this.appliedForce,e.angle),e.world(this.craft)),e.push(A(e.velocity,-e.mass*.12)),e.spin*=Math.exp(-.35*n)}},V=class{body=new R;car=new z;ship=new B;mode=`car`;gravity=!1;barrier=!1;paused=!1;lastInput={throttle:0,steer:0,action:!1};brickForce=null;captureState(){return{at:performance.now(),preset:t(this.car.preset),simulation:t({mode:this.mode,gravity:this.gravity,barrier:this.barrier,paused:this.paused,lastInput:this.lastInput,brickForce:this.brickForce}),body:this.body.captureState(),car:this.car.captureState(),ship:this.ship.captureState()}}restoreState(e){let n=t(e);this.setPreset(n.preset),this.body.restoreState(n.body),this.car.restoreState(n.car),this.ship.restoreState(n.ship),this.mode=n.simulation.mode,this.gravity=n.simulation.gravity,this.barrier=n.simulation.barrier,this.paused=n.simulation.paused,this.lastInput=n.simulation.lastInput,this.brickForce=n.simulation.brickForce;let r=performance.now()-n.at;this.car.explodedAt!==null&&(this.car.explodedAt+=r),Number.isFinite(this.car.lastBlastEmission)&&(this.car.lastBlastEmission+=r)}setPreset(e){this.car.configure(e),this.mode===`car`&&(this.body.mass=e.massKg,this.body.inertia=e.massKg*(e.geometry.lengthM**2+e.geometry.widthM**2)/12)}setMode(e){this.mode=e,this.body.mass=e===`car`?this.car.preset.massKg:1e3,this.body.inertia=e===`ship`?this.body.mass*(1/3*(1.8**2/18+.8**2/6+16)+2/3*(.9**2/2+4)):this.body.mass*(this.car.preset.geometry.lengthM**2+this.car.preset.geometry.widthM**2)/12,this.car.reset(),this.ship.reset(),this.brickForce=null}reset(){this.body.reset(),this.car.reset(),this.ship.reset(),this.brickForce=null,this.lastInput={throttle:0,steer:0,action:!1}}resetAtCurrentPose(){let e={...this.body.position},t=this.body.angle;this.reset(),this.body.position=e,this.body.angle=t}tick(e,t,n){if(this.paused)return;if(this.mode===`car`&&this.car.explodedAt!==null){this.body.velocity=D(),this.body.spin=0,this.lastInput={throttle:0,steer:0,action:!1,boost:!1};return}this.lastInput={...e};let r=this.body,i={...r.position};if(this.gravity){let e=r.mass*3/30;r.push(D(-e*r.velocity.x,-r.mass*3-e*r.velocity.y))}if(this.mode===`car`&&this.car.tick(r,e,t,n),this.mode===`ship`){let n=r.angle;this.ship.tick(r,e,t),r.tick(t),this.ship.headAngle-=r.angle-n}else if(this.mode===`brick`&&this.brickForce&&r.push(this.brickForce.force,r.world(this.brickForce.local)),r.tick(t),this.mode===`car`){let n=this.car.fastDrifting?{...e,action:!1}:e;this.car.slow(r,n,t),this.car.fastDrifting?this.car.finishDrift(r,e,t):this.car.arcadeAssist(r,n,t);let a=this.car.statusEffects.factor(`speed`,void 0,this.car.tires.length);a<1&&(r.velocity=A(r.velocity,Math.exp(-5*(1-a)*t))),this.car.statusEffects.advance(N(k(r.position,i)),t)}}contain(e){let t=this.body,n=this.mode===`car`?this.car.preset.geometry.lengthM/2:2,r=this.mode===`car`?this.car.preset.geometry.widthM/2:1,i=this.mode===`ship`?[D(1.2,0),D(-.6,-.8),D(-.6,.8)].map(e=>t.world(O(this.ship.craft,P(e,this.ship.headAngle)))):[D(-n,-r),D(n,-r),D(n,r),D(-n,r)].map(e=>t.world(e));this.mode===`ship`&&i.push(t.world(this.ship.counterweight));let a=[[D(1),e.left],[D(-1),-e.right],[D(0,1),e.bottom],[D(0,-1),-e.top]];for(let e=0;e<4;e++)for(let[e,n]of a){let r=i.map(t=>j(t,e)-(this.mode===`ship`?this.ship.radius:0)),a=Math.min(...r),o=n-a;if(o<-1e-8)continue;let s=i[r.indexOf(a)],c=A(e,Math.max(0,o));t.position=O(t.position,c);for(let e of i)e.x+=c.x,e.y+=c.y;let l=O(s,A(e,this.mode===`ship`?-this.ship.radius:0)),u=j(t.velocityAt(l),e);if(u>=0)continue;let d=M(k(l,t.position),e),f=1/t.mass+d*d/t.inertia;t.impulse(A(e,-(1+(u<-.5?.55:0))*u/f),l)}}};export{o as C,s as S,S as _,N as a,_ as b,P as c,g as d,C as f,x as g,w as h,j as i,A as l,p as m,F as n,k as o,T as p,M as r,O as s,V as t,D as u,v,u as x,h as y};
@@ -1 +1 @@
1
- import{a as e}from"./configuration~index~embed~bookmarklet-5ym-TX_u.js";function t(t,n){return[{label:`Speed`,read:e=>e.engineForceN/e.rollingResistance},{label:`Acceleration`,read:e=>e.engineForceN/e.massKg},{label:`Handling`,read:t=>t.corneringAccelerationMps2/Math.sqrt(e(t))},{label:`Drift`,read:e=>e.drift.slipAngleRad/e.drift.entrySpeedMps},{label:`Braking`,read:e=>e.handbrakeDecelerationMps2}].map(({label:e,read:r})=>{let i=n.map(r),a=Math.min(...i),o=Math.max(...i),s=o===a?.5:(r(t)-a)/(o-a);return{label:e,value:Math.round(20+s*80)}})}export{t};
1
+ import{a as e}from"./configuration~index~embed~bookmarklet-6dUo7fKK.js";function t(t,n){return[{label:`Speed`,read:e=>e.engineForceN/e.rollingResistance},{label:`Acceleration`,read:e=>e.engineForceN/e.massKg},{label:`Handling`,read:t=>t.corneringAccelerationMps2/Math.sqrt(e(t))},{label:`Drift`,read:e=>e.drift.slipAngleRad/e.drift.entrySpeedMps},{label:`Braking`,read:e=>e.handbrakeDecelerationMps2}].map(({label:e,read:r})=>{let i=n.map(r),a=Math.min(...i),o=Math.max(...i),s=o===a?.5:(r(t)-a)/(o-a);return{label:e,value:Math.round(20+s*80)}})}export{t};
@@ -1 +1 @@
1
- import{a as e,r as t}from"./definitions~index~embed~bookmarklet~vehicle-popover~Documentation~JoyRideView~browser-sessi~fklztn3g-BG7sJuWo.js";import{S as n,b as r,x as i}from"./definitions~index~embed~bookmarklet-CfH2mYuH.js";import{r as a}from"./definitions~index~embed~vehicle-popover~browser-session-core~renderer-RDNEXk_b.js";import{a as o,b as s,c,i as l,l as u,n as d,o as f,s as p,u as m}from"./runtime~index~embed~vehicle-popover~browser-session-core~renderer-iEgK-2uE.js";import{i as h,o as g,r as _}from"./configuration~index~embed~bookmarklet-5ym-TX_u.js";import{n as v,r as y}from"./vehicle-catalog~index~embed-CKTjozQr.js";import{_ as b,g as x,n as ee,v as S,y as te}from"./runtime~vehicle-popover~browser-session-core~renderer-FYzuLkAN.js";function ne(){if(typeof globalThis<`u`)return globalThis;if(typeof self<`u`)return self;if(typeof window<`u`)return window;if(typeof global<`u`)return global}function re(){let e=ne();if(e.__xstate__)return e.__xstate__}var ie=e=>{if(typeof window>`u`)return;let t=re();t&&t.register(e)},ae=class{constructor(e){this._process=e,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(e){let t={value:e,next:null};this._current?(this._last.next=t,this._last=t):(this._current=t,this._last=t,this._active&&this.flush())}flush(){for(;this._current;){let e=this._current;this._process(e.value),this._current=e.next}this._last=null}},oe=``,se=`#`,ce=`*`,le=`xstate.init`,ue=`xstate.stop`;function de(e,t){return{type:`xstate.after.${e}.${t}`}}function C(e,t){return{type:`xstate.done.state.${e}`,output:t}}function fe(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function pe(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function me(e){return{type:le,input:e}}function w(e){setTimeout(()=>{throw e})}var he=typeof Symbol==`function`&&Symbol.observable||`@@observable`;function ge(e,t){let n=ve(e),r=ve(t);return typeof r==`string`?typeof n==`string`&&r===n:typeof n==`string`?n in r:Object.keys(n).every(e=>e in r&&ge(n[e],r[e]))}function _e(e){if(Ce(e))return e;let t=[],n=``;for(let r=0;r<e.length;r++){switch(e.charCodeAt(r)){case 92:n+=e[r+1],r++;continue;case 46:t.push(n),n=``;continue}n+=e[r]}return t.push(n),t}function ve(e){return At(e)?e.value:typeof e==`string`?ye(_e(e)):e}function ye(e){if(e.length===1)return e[0];let t={},n=t;for(let t=0;t<e.length-1;t++)if(t===e.length-2)n[e[t]]=e[t+1];else{let r=n;n={},r[e[t]]=n}return t}function be(e,t){let n={},r=Object.keys(e);for(let i=0;i<r.length;i++){let a=r[i];n[a]=t(e[a],a,e,i)}return n}function xe(e){return Ce(e)?e:[e]}function T(e){return e===void 0?[]:xe(e)}function Se(e,t,n,r){return typeof e==`function`?e({context:t,event:n,self:r}):e}function Ce(e){return Array.isArray(e)}function we(e){return e.type.startsWith(`xstate.error.actor`)}function E(e){return xe(e).map(e=>e===void 0||typeof e==`string`?{target:e}:e)}function Te(e){if(e!==void 0&&e!==oe)return T(e)}function D(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}function Ee(e,t){return`${t}.${e}`}function De(e,t){let n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];let[,r,i]=n,a=e.getStateNodeById(i).config.invoke;return(Array.isArray(a)?a[r]:a).src}function Oe(e,t){if(t===e||t===ce)return!0;if(!t.endsWith(`.*`))return!1;let n=t.split(`.`),r=e.split(`.`);for(let e=0;e<n.length;e++){let t=n[e],i=r[e];if(t===`*`)return e===n.length-1;if(t!==i)return!1}return!0}function ke(e,t){return`${e.sessionId}.${t}`}var Ae=0;function je(e,t){let n=new Map,r=new Map,i=new WeakMap,a=new Set,o={},{clock:s,logger:c}=t,l={schedule:(e,t,n,r,i=Math.random().toString(36).slice(2))=>{let a={source:e,target:t,event:n,delay:r,id:i,startedAt:Date.now()},c=ke(e,i);u._snapshot._scheduledEvents[c]=a;let l=s.setTimeout(()=>{delete o[c],delete u._snapshot._scheduledEvents[c],u._relay(e,t,n)},r);o[c]=l},cancel:(e,t)=>{let n=ke(e,t),r=o[n];delete o[n],delete u._snapshot._scheduledEvents[n],r!==void 0&&s.clearTimeout(r)},cancelAll:e=>{for(let t in u._snapshot._scheduledEvents){let n=u._snapshot._scheduledEvents[t];n.source===e&&l.cancel(e,n.id)}}},u={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Ae++}`,_register:(e,t)=>(n.set(e,t),e),_unregister:e=>{n.delete(e.sessionId);let t=i.get(e);t!==void 0&&(r.delete(t),i.delete(e))},get:e=>r.get(e),getAll:()=>Object.fromEntries(r.entries()),_set:(e,t)=>{let n=r.get(e);if(n&&n!==t)throw Error(`Actor with system ID '${e}' already exists.`);r.set(e,t),i.set(t,e)},inspect:e=>{let t=D(e);return a.add(t),{unsubscribe(){a.delete(t)}}},_sendInspectionEvent:t=>{if(!a.size)return;let n={...t,rootId:e.sessionId};a.forEach(e=>e.next?.(n))},_relay:(e,t,n)=>{u._sendInspectionEvent({type:`@xstate.event`,sourceRef:e,actorRef:t,event:n}),t._send(n)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{let e=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(let t in e){let{source:n,target:r,event:i,delay:a,id:o}=e[t];l.schedule(n,r,i,a,o)}},_clock:s,_logger:c};return u}var Me=!1,O=function(e){return e[e.NotStarted=0]=`NotStarted`,e[e.Running=1]=`Running`,e[e.Stopped=2]=`Stopped`,e}({}),Ne={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1},Pe=class{constructor(e,t){this.logic=e,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new ae(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=O.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];let n={...Ne,...t},{clock:r,logger:i,parent:a,syncSnapshot:o,id:s,systemId:c,inspect:l}=n;this.system=a?a.system:je(this,{clock:r,logger:i}),l&&!a&&this.system.inspect(D(l)),this.sessionId=this.system._bookId(),this.id=s??this.sessionId,this.logger=t?.logger??this.system._logger,this.clock=t?.clock??this.system._clock,this._parent=a,this._syncSnapshot=o,this.options=n,this.src=n.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:e=>{this._deferred.push(e)},system:this.system,stopChild:e=>{if(e._parent!==this)throw Error(`Cannot stop child actor ${e.id} of ${this.id} because it is not a child`);e._stop()},emit:e=>{let t=this.eventListeners.get(e.type),n=this.eventListeners.get(`*`);if(!t&&!n)return;let r=[...t?t.values():[],...n?n.values():[]];for(let t of r)try{t(e)}catch(e){w(e)}},actionExecutor:e=>{let t=()=>{if(this._actorScope.system._sendInspectionEvent({type:`@xstate.action`,actorRef:this,action:{type:e.type,params:e.params}}),!e.exec)return;let t=Me;try{Me=!0,e.exec(e.info,e.params)}finally{Me=t}};this._processingStatus===O.Running?t():this._deferred.push(t)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:`@xstate.actor`,actorRef:this}),c&&(this.systemId=c,this.system._set(c,this)),this._initState(t?.snapshot??t?.state),c&&this._snapshot.status!==`active`&&this.system._unregister(this)}_initState(e){try{this._snapshot=e?this.logic.restoreSnapshot?this.logic.restoreSnapshot(e,this._actorScope):e:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(e){this._snapshot={status:`error`,output:void 0,error:e}}}update(e,t){this._snapshot=e;let n;for(;n=this._deferred.shift();)try{n()}catch(t){this._deferred.length=0,this._snapshot={...e,status:`error`,error:t}}switch(this._snapshot.status){case`active`:for(let t of this.observers)try{t.next?.(e)}catch(e){w(e)}break;case`done`:for(let t of this.observers)try{t.next?.(e)}catch(e){w(e)}this._stopProcedure(),this._complete(),this._doneEvent=fe(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case`error`:this._error(this._snapshot.error)}this.system._sendInspectionEvent({type:`@xstate.snapshot`,actorRef:this,event:t,snapshot:e})}subscribe(e,t,n){let r=D(e,t,n);if(this._processingStatus!==O.Stopped)this.observers.add(r);else switch(this._snapshot.status){case`done`:try{r.complete?.()}catch(e){w(e)}break;case`error`:{let e=this._snapshot.error;if(!r.error)w(e);else try{r.error(e)}catch(e){w(e)}break}}return{unsubscribe:()=>{this.observers.delete(r)}}}on(e,t){let n=this.eventListeners.get(e);n||(n=new Set,this.eventListeners.set(e,n));let r=t.bind(void 0);return n.add(r),{unsubscribe:()=>{n.delete(r)}}}select(e,t=Object.is){return{subscribe:n=>{let r=D(n),i=e(this.getSnapshot());return this.subscribe(n=>{let a=e(n);t(i,a)||(i=a,r.next?.(a))})},get:()=>e(this.getSnapshot())}}start(){if(this._processingStatus===O.Running)return this;this._syncSnapshot&&this.subscribe({next:e=>{e.status===`active`&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:e})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=O.Running;let e=me(this.options.input);switch(this.system._sendInspectionEvent({type:`@xstate.event`,sourceRef:this._parent,actorRef:this,event:e}),this._snapshot.status){case`done`:return this.update(this._snapshot,e),this;case`error`:return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(e){return this._snapshot={...this._snapshot,status:`error`,error:e},this._error(e),this}return this.update(this._snapshot,e),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(e){let t,n;try{t=this.logic.transition(this._snapshot,e,this._actorScope)}catch(e){n={err:e}}if(n){let{err:e}=n;this._snapshot={...this._snapshot,status:`error`,error:e},this._error(e)}else this.update(t,e),e.type===`xstate.stop`&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===O.Stopped?this:(this.mailbox.clear(),this._processingStatus===O.NotStarted?(this._processingStatus=O.Stopped,this):(this.mailbox.enqueue({type:ue}),this))}stop(){if(this._parent)throw Error(`A non-root actor cannot be stopped directly.`);return this._stop()}_complete(){for(let e of this.observers)try{e.complete?.()}catch(e){w(e)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){this._parent||w(e),this.eventListeners.clear();return}let t=!1;for(let n of this.observers){let r=n.error;t||=!r;try{r?.(e)}catch(e){w(e)}}this.observers.clear(),this.eventListeners.clear(),t&&w(e)}_error(e){this._stopProcedure(),this._reportError(e),this._parent&&this.system._relay(this,this._parent,pe(this.id,e))}_stopProcedure(){return this._processingStatus===O.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new ae(this._process.bind(this)),this._processingStatus=O.Stopped,this.system._unregister(this)),this}_send(e){this._processingStatus!==O.Stopped&&this.mailbox.enqueue(e)}send(e){this.system._relay(void 0,this,e)}attachDevTools(){let{devTools:e}=this.options;e&&(typeof e==`function`?e:ie)(this)}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[he](){return this}getSnapshot(){return this._snapshot}};function k(e,...[t]){return new Pe(e,t)}function Fe(e,t,n,r,{sendId:i}){return[t,{sendId:typeof i==`function`?i(n,r):i},void 0]}function Ie(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function Le(e){function t(e,t){}return t.type=`xstate.cancel`,t.sendId=e,t.resolve=Fe,t.execute=Ie,t}function Re(e,t,n,r,{id:i,systemId:a,src:o,input:s,syncSnapshot:c}){let l=typeof o==`string`?De(t.machine,o):o,u=typeof i==`function`?i(n):i,d,f;return l&&(f=typeof s==`function`?s({context:t.context,event:n.event,self:e.self}):s,d=k(l,{id:u,src:o,parent:e.self,syncSnapshot:c,systemId:a,input:f})),[J(t,{children:{...t.children,[u]:d}}),{id:i,systemId:a,actorRef:d,src:o,input:f},void 0]}function ze(e,{actorRef:t}){t&&e.defer(()=>{t._processingStatus!==O.Stopped&&t.start()})}function Be(...[e,{id:t,systemId:n,input:r,syncSnapshot:i=!1}={}]){function a(e,t){}return a.type=`xstate.spawnChild`,a.id=t,a.systemId=n,a.src=e,a.input=r,a.syncSnapshot=i,a.resolve=Re,a.execute=ze,a}function Ve(e,t,n,r,{actorRef:i}){let a=typeof i==`function`?i(n,r):i,o=typeof a==`string`?t.children[a]:a,s=t.children;return o&&(s={...s},delete s[o.id]),[J(t,{children:s}),o,void 0]}function He(e,t){let n=t.getSnapshot();if(n&&`children`in n)for(let t of Object.values(n.children))He(e,t);e.system._unregister(t)}function Ue(e,t){t&&(He(e,t),t._processingStatus===O.Running?e.defer(()=>{e.stopChild(t)}):e.stopChild(t))}function A(e){function t(e,t){}return t.type=`xstate.stopChild`,t.actorRef=e,t.resolve=Ve,t.execute=Ue,t}function We(e,{context:t,event:n},{guards:r}){return r.every(r=>j(r,t,n,e))}function Ge(e){function t(e,t){return!1}return t.check=We,t.guards=e,t}function j(e,t,n,r){let{machine:i}=r,a=typeof e==`function`,o=a?e:i.implementations.guards[typeof e==`string`?e:e.type];if(!a&&!o)throw Error(`Guard '${typeof e==`string`?e:e.type}' is not implemented.'.`);if(typeof o!=`function`)return j(o,t,n,r);let s={context:t,event:n},c=a||typeof e==`string`?void 0:`params`in e?typeof e.params==`function`?e.params({context:t,event:n}):e.params:void 0;return`check`in o?o.check(r,s,o):o(s,c)}function Ke(e){return e.type===`atomic`||e.type===`final`}function M(e){return Object.values(e.states).filter(e=>e.type!==`history`)}function N(e,t){let n=[];if(t===e)return n;let r=e.parent;for(;r&&r!==t;)n.push(r),r=r.parent;return n}function P(e){let t=new Set(e),n=Je(t);for(let e of t)if(e.type===`compound`&&(!n.get(e)||!n.get(e).length))it(e).forEach(e=>t.add(e));else if(e.type===`parallel`){for(let n of M(e))if(n.type!==`history`&&!t.has(n)){let e=it(n);for(let n of e)t.add(n)}}for(let e of t){let n=e.parent;for(;n;)t.add(n),n=n.parent}return t}function qe(e,t){let n=t.get(e);if(!n)return{};if(e.type===`compound`){let e=n[0];if(e){if(Ke(e))return e.key}else return{}}let r={};for(let e of n)r[e.key]=qe(e,t);return r}function Je(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function Ye(e,t){return qe(e,Je(P(t)))}function Xe(e,t){return t.type===`compound`?M(t).some(t=>t.type===`final`&&e.has(t)):t.type===`parallel`?M(t).every(t=>Xe(e,t)):t.type===`final`}var F=e=>e[0]===se;function Ze(e,t){let n=e.transitions.get(t),r=[...e.transitions.keys()].filter(e=>e!==t&&Oe(t,e)).sort((e,t)=>t.length-e.length).flatMap(t=>e.transitions.get(t));return n?[...n,...r]:r}function Qe(e){let t=e.config.after;if(!t)return[];let n=t=>{let n=de(t,e.id),r=n.type;return e.entry.push(Vt(n,{id:r,delay:t})),e.exit.push(Le(r)),r};return Object.keys(t).flatMap(e=>{let r=t[e],i=typeof r==`string`?{target:r}:r,a=Number.isNaN(+e)?e:+e,o=n(a);return T(i).map(e=>({...e,event:o,delay:a}))}).map(t=>{let{delay:n}=t;return{...I(e,t.event,t),delay:n}})}function I(e,t,n){let r=Te(n.target),i=n.reenter??!1,a=nt(e,r),o={...n,actions:T(n.actions),guard:n.guard,target:a,source:e,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${e.id}`,target:a?a.map(e=>`#${e.id}`):void 0})};return o}function $e(e){let t=new Map;if(e.config.on)for(let n of Object.keys(e.config.on)){if(n===``)throw Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let r=e.config.on[n];t.set(n,E(r).map(t=>I(e,n,t)))}if(e.config.onDone){let n=`xstate.done.state.${e.id}`;t.set(n,E(e.config.onDone).map(t=>I(e,n,t)))}for(let n of e.invoke){if(n.onDone){let r=`xstate.done.actor.${n.id}`;t.set(r,E(n.onDone).map(t=>I(e,r,t)))}if(n.onError){let r=`xstate.error.actor.${n.id}`;t.set(r,E(n.onError).map(t=>I(e,r,t)))}if(n.onSnapshot){let r=`xstate.snapshot.${n.id}`;t.set(r,E(n.onSnapshot).map(t=>I(e,r,t)))}}for(let n of e.after){let e=t.get(n.eventType);e||(e=[],t.set(n.eventType,e)),e.push(n)}return t}function et(e){let t=[],n=r=>{Object.values(r).forEach(r=>{if(r.config.route&&r.config.id){let n=r.config.id,i=r.config.route.guard,a=({event:e})=>e.to===`#${n}`,o={...r.config.route,guard:i?Ge([a,i]):a,target:`#${n}`};t.push(I(e,`xstate.route`,o))}r.states&&n(r.states)})};n(e.states),t.length>0&&e.transitions.set(`xstate.route`,t)}function tt(e,t){let n=typeof t==`string`?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw Error(`Initial state node "${t}" not found on parent state node #${e.id}`);let r={source:e,actions:!t||typeof t==`string`?[]:T(t.actions),eventType:null,reenter:!1,target:n?[n]:[],meta:typeof t==`object`?t.meta:void 0,description:typeof t==`object`?t.description:void 0,toJSON:()=>({...r,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return r}function nt(e,t){if(t!==void 0)return t.map(t=>{if(typeof t!=`string`)return t;if(F(t))return e.machine.getStateNodeById(t);let n=t[0]===`.`;if(n&&!e.parent)return z(e,t.slice(1));let r=n?e.key+t:t;if(e.parent)try{return z(e.parent,r)}catch(t){throw Error(`Invalid transition definition for state node '${e.id}':\n${t.message}`)}throw Error(`Invalid target: "${t}" is not a valid target from the root node. Did you mean ".${t}"?`)})}function rt(e){let t=Te(e.config.target);return t?{target:t.map(t=>typeof t==`string`?z(e.parent,t):t)}:e.parent.type===`parallel`?{target:[e.parent]}:e.parent.initial}function L(e){return e.type===`history`}function it(e){let t=at(e);for(let n of t)for(let r of N(n,e))t.add(r);return t}function at(e){let t=new Set;function n(e){if(!t.has(e)){if(t.add(e),e.type===`compound`)n(e.initial.target[0]);else if(e.type===`parallel`)for(let t of M(e))n(t)}}return n(e),t}function R(e,t){if(F(t))return e.machine.getStateNodeById(t);if(!e.states)throw Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);let n=e.states[t];if(!n)throw Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function z(e,t){if(typeof t==`string`&&F(t))try{return e.machine.getStateNodeById(t)}catch{}let n=_e(t).slice(),r=e;for(;n.length;){let e=n.shift();if(!e.length)break;r=R(r,e)}return r}function B(e,t){if(typeof t==`string`){let n=e.states[t];if(!n)throw Error(`State '${t}' does not exist on '${e.id}'`);return[e,n]}let n=Object.keys(t),r=n.map(t=>R(e,t)).filter(Boolean);return[e.machine.root,e].concat(r,n.reduce((n,r)=>{let i=R(e,r);if(!i)return n;let a=B(i,t[r]);return n.concat(a)},[]))}function ot(e,t,n,r){let i=R(e,t).next(n,r);return!i||!i.length?e.next(n,r):i}function st(e,t,n,r){let i=Object.keys(t),a=lt(R(e,i[0]),t[i[0]],n,r);return!a||!a.length?e.next(n,r):a}function ct(e,t,n,r){let i=[];for(let a of Object.keys(t)){let o=t[a];if(!o)continue;let s=lt(R(e,a),o,n,r);s&&i.push(...s)}return i.length?i:e.next(n,r)}function lt(e,t,n,r){return typeof t==`string`?ot(e,t,n,r):Object.keys(t).length===1?st(e,t,n,r):ct(e,t,n,r)}function ut(e){return Object.keys(e.states).map(t=>e.states[t]).filter(e=>e.type===`history`)}function V(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function dt(e,t){let n=new Set(e),r=new Set(t);for(let e of n)if(r.has(e))return!0;for(let e of r)if(n.has(e))return!0;return!1}function ft(e,t,n){let r=new Set;for(let i of e){let e=!1,a=new Set;for(let o of r)if(dt(U([i],t,n),U([o],t,n))){if(V(i.source,o.source))a.add(o);else{e=!0;break}}if(!e){for(let e of a)r.delete(e);r.add(i)}}return Array.from(r)}function pt(e){let[t,...n]=e;for(let e of N(t,void 0))if(n.every(t=>V(t,e)))return e}function H(e,t){if(!e.target)return[];let n=new Set;for(let r of e.target)if(L(r)){if(t[r.id])for(let e of t[r.id])n.add(e);else for(let e of H(rt(r),t))n.add(e)}else n.add(r);return[...n]}function mt(e,t){let n=H(e,t);if(!n)return;if(!e.reenter&&n.every(t=>t===e.source||V(t,e.source)))return e.source;let r=pt(n.concat(e.source));if(r)return r;if(!e.reenter)return e.source.machine.root}function U(e,t,n){let r=new Set;for(let i of e)if(i.target?.length){let e=mt(i,n);i.reenter&&i.source===e&&r.add(e);for(let n of t)V(n,e)&&r.add(n)}return[...r]}function ht(e,t){if(e.length!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function gt(e,t,n,r,i){return _t([{target:[...at(e)],source:e,reenter:!0,actions:[],eventType:null,toJSON:null}],t,n,r,!0,i)}function _t(e,t,n,r,i,a){let o=[];if(!e.length)return[t,o];let s=n.actionExecutor;n.actionExecutor=e=>{o.push(e),s(e)};try{let s=new Set(t._nodes),c=t.historyValue,l=ft(e,s,c),u=t;i||([u,c]=Ct(u,r,n,l,s,c,a,n.actionExecutor)),u=G(u,r,n,l.flatMap(e=>e.actions),a,void 0),u=yt(u,r,n,l,s,a,c,i);let d=[...s];u.status===`done`&&(u=G(u,r,n,d.sort((e,t)=>t.order-e.order).flatMap(e=>e.exit),a,void 0));try{return c===t.historyValue&&ht(t._nodes,s)?[u,o]:[J(u,{_nodes:d,historyValue:c}),o]}catch(e){throw e}}finally{n.actionExecutor=s}}function vt(e,t,n,r,i){if(r.output===void 0)return;let a=C(i.id,i.output!==void 0&&i.parent?Se(i.output,e.context,t,n.self):void 0);return Se(r.output,e.context,a,n.self)}function yt(e,t,n,r,i,a,o,s){let c=e,l=new Set,u=new Set;bt(r,o,u,l),s&&u.add(e.machine.root);let d=new Set;for(let e of[...l].sort((e,t)=>e.order-t.order)){i.add(e);let r=[];r.push(...e.entry);for(let t of e.invoke)r.push(Be(t.src,{...t,syncSnapshot:!!t.onSnapshot}));if(u.has(e)){let t=e.initial.actions;r.push(...t)}if(c=G(c,t,n,r,a,e.invoke.map(e=>e.id)),e.type===`final`){let r=e.parent,o=r?.type===`parallel`?r:r?.parent,s=o||e;for(r?.type===`compound`&&a.push(C(r.id,e.output===void 0?void 0:Se(e.output,c.context,t,n.self)));o?.type===`parallel`&&!d.has(o)&&Xe(i,o);)d.add(o),a.push(C(o.id)),s=o,o=o.parent;if(o)continue;c=J(c,{status:`done`,output:vt(c,t,n,c.machine.root,s)})}}return c}function bt(e,t,n,r){for(let i of e){let e=mt(i,t);for(let a of i.target||[])!L(a)&&(i.source!==a||i.source!==e||i.reenter)&&(r.add(a),n.add(a)),W(a,t,n,r);let a=H(i,t);for(let o of a){let a=N(o,e);e?.type===`parallel`&&a.push(e),xt(r,t,n,a,!i.source.parent&&i.reenter?void 0:e)}}}function W(e,t,n,r){if(L(e)){if(t[e.id]){let i=t[e.id];for(let e of i)r.add(e),W(e,t,n,r);for(let a of i)St(a,e.parent,r,t,n)}else{let i=rt(e);for(let a of i.target)r.add(a),i===e.parent?.initial&&n.add(e.parent),W(a,t,n,r);for(let a of i.target)St(a,e.parent,r,t,n)}}else if(e.type===`compound`){let[i]=e.initial.target;L(i)||(r.add(i),n.add(i)),W(i,t,n,r),St(i,e,r,t,n)}else if(e.type===`parallel`)for(let i of M(e).filter(e=>!L(e)))[...r].some(e=>V(e,i))||(L(i)||(r.add(i),n.add(i)),W(i,t,n,r))}function xt(e,t,n,r,i){for(let a of r)if((!i||V(a,i))&&e.add(a),a.type===`parallel`)for(let r of M(a).filter(e=>!L(e)))[...e].some(e=>V(e,r))||(e.add(r),W(r,t,n,e))}function St(e,t,n,r,i){xt(n,r,i,N(e,t))}function Ct(e,t,n,r,i,a,o,s){let c=e,l=U(r,i,a);l.sort((e,t)=>t.order-e.order);let u;for(let e of l)for(let t of ut(e)){let n;n=t.history===`deep`?t=>Ke(t)&&V(t,e):t=>t.parent===e,u??={...a},u[t.id]=Array.from(i).filter(n)}for(let e of l)c=G(c,t,n,[...e.exit,...e.invoke.map(e=>A(e.id))],o,void 0),i.delete(e);return[c,u||a]}function wt(e,t){return e.implementations.actions[t]}function Tt(e,t,n,r,i,a){let{machine:o}=e,s=e;for(let e of r){let r=typeof e==`function`,c=r?e:wt(o,typeof e==`string`?e:e.type),l={context:s.context,event:t,self:n.self,system:n.system},u=r||typeof e==`string`?void 0:`params`in e?typeof e.params==`function`?e.params({context:s.context,event:t}):e.params:void 0;if(!c||!(`resolve`in c)){n.actionExecutor({type:typeof e==`string`?e:typeof e==`object`?e.type:e.name||`(anonymous)`,info:l,params:u,exec:c});continue}let d=c,[f,p,m]=d.resolve(n,s,l,u,c,i);s=f,`retryResolve`in d&&a?.push([d,p]),`execute`in d&&n.actionExecutor({type:d.type,info:l,params:p,exec:d.execute.bind(null,n,p)}),m&&(s=Tt(s,t,n,m,i,a))}return s}function G(e,t,n,r,i,a){let o=a?[]:void 0,s=Tt(e,t,n,r,{internalQueue:i,deferredActorIds:a},o);return o?.forEach(([e,t])=>{e.retryResolve(n,s,t)}),s}function K(e,t,n,r){let i=e,a=[];function o(e,t,r){n.system._sendInspectionEvent({type:`@xstate.microstep`,actorRef:n.self,event:t,snapshot:e[0],_transitions:r}),a.push(e)}if(t.type===`xstate.stop`)return i=J(Et(i,t,n),{status:`stopped`}),o([i,[]],t,[]),{snapshot:i,microsteps:a};let s=t;if(s.type!==le){let t=s,c=we(t),l=Dt(t,i);if(c&&!l.length)return i=J(Et(i,t,n),{status:`error`,error:t.error}),o([i,[]],t,[]),{snapshot:i,microsteps:a};let u=_t(l,e,n,s,!1,r);i=u[0],o(u,t,l)}let c=!0,l=e.machine.options?.maxIterations??1/0,u=0;for(;i.status===`active`;){if(u++,u>l)throw Error(`Infinite loop detected: the machine has processed more than ${l} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`);let e=c?Ot(i,s):[],t=e.length?i:void 0;if(!e.length){if(!r.length)break;s=r.shift(),e=Dt(s,i)}let a=_t(e,i,n,s,!1,r);i=a[0],c=i!==t,o(a,s,e)}return i.status!==`active`&&Et(i,s,n),{snapshot:i,microsteps:a}}function Et(e,t,n){return G(e,t,n,Object.values(e.children).map(e=>A(e)),[],void 0)}function Dt(e,t){return t.machine.getTransitionData(t,e)}function Ot(e,t){let n=new Set,r=e._nodes.filter(Ke);for(let i of r)loop:for(let r of[i].concat(N(i,void 0)))if(r.always){for(let i of r.always)if(i.guard===void 0||j(i.guard,e.context,t,e)){n.add(i);break loop}}return ft(Array.from(n),new Set(e._nodes),e.historyValue)}function kt(e,t){return Ye(e,[...P(B(e,t))])}function At(e){return!!e&&typeof e==`object`&&`machine`in e&&`value`in e}var jt=function(e){return ge(e,this.value)},Mt=function(e){return this.tags.has(e)},Nt=function(e){let t=this.machine.getTransitionData(this,e);return!!t?.length&&t.some(e=>e.target!==void 0||e.actions.length)},Pt=function(){let{_nodes:e,tags:t,machine:n,getMeta:r,toJSON:i,can:a,hasTag:o,matches:s,...c}=this;return{...c,tags:Array.from(t)}},Ft=function(){return this._nodes.reduce((e,t)=>(t.meta!==void 0&&(e[t.id]=t.meta),e),{})};function q(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:Ye(t.root,e._nodes),tags:new Set(e._nodes.flatMap(e=>e.tags)),children:e.children,historyValue:e.historyValue||{},matches:jt,hasTag:Mt,can:Nt,getMeta:Ft,toJSON:Pt}}function J(e,t={}){return q({...e,...t},e.machine)}function It(e){if(typeof e!=`object`||!e)return{};let t={};for(let n in e){let r=e[n];Array.isArray(r)&&(t[n]=r.map(e=>({id:e.id})))}return t}function Lt(e,t){let{_nodes:n,tags:r,machine:i,children:a,context:o,can:s,hasTag:c,matches:l,getMeta:u,toJSON:d,...f}=e,p={};for(let e in a){let n=a[e];p[e]={snapshot:n.getPersistedSnapshot(t),src:n.src,systemId:n.systemId,syncSnapshot:n._syncSnapshot}}return{...f,context:Rt(o),children:p,historyValue:It(f.historyValue)}}function Rt(e){let t;for(let n in e){let r=e[n];if(r&&typeof r==`object`){if(`sessionId`in r&&`send`in r&&`ref`in r)t??=Array.isArray(e)?e.slice():{...e},t[n]={xstate$$type:1,id:r.id};else{let i=Rt(r);i!==r&&(t??=Array.isArray(e)?e.slice():{...e},t[n]=i)}}}return t??e}function zt(e,t,n,r,{event:i,id:a,delay:o},{internalQueue:s}){let c=t.machine.implementations.delays;if(typeof i==`string`)throw Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);let l=typeof i==`function`?i(n,r):i,u;if(typeof o==`string`){let e=c&&c[o];u=typeof e==`function`?e(n,r):e}else u=typeof o==`function`?o(n,r):o;return typeof u!=`number`&&s.push(l),[t,{event:l,id:a,delay:u},void 0]}function Bt(e,t){let{event:n,delay:r,id:i}=t;typeof r==`number`&&e.defer(()=>{let t=e.self;e.system.scheduler.schedule(t,t,n,r,i)})}function Vt(e,t){function n(e,t){}return n.type=`xstate.raise`,n.event=e,n.id=t?.id,n.delay=t?.delay,n.resolve=zt,n.execute=Bt,n}function Ht(e,{machine:t,context:n},r,i){let a=(a,o)=>{if(typeof a==`string`){let s=De(t,a);if(!s)throw Error(`Actor logic '${a}' not implemented in machine '${t.id}'`);let c=k(s,{id:o?.id,parent:e.self,syncSnapshot:o?.syncSnapshot,input:typeof o?.input==`function`?o.input({context:n,event:r,self:e.self}):o?.input,src:a,systemId:o?.systemId});return i[c.id]=c,c}return k(a,{id:o?.id,parent:e.self,syncSnapshot:o?.syncSnapshot,input:o?.input,src:a,systemId:o?.systemId})};return(t,n)=>{let r=a(t,n);return i[r.id]=r,e.defer(()=>{r._processingStatus!==O.Stopped&&r.start()}),r}}function Ut(e,t,n,r,{assignment:i}){if(!t.context)throw Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");let a={},o={context:t.context,event:n.event,spawn:Ht(e,t,n.event,a),self:e.self,system:e.system},s={};if(typeof i==`function`)s=i(o,r);else for(let e of Object.keys(i)){let t=i[e];s[e]=typeof t==`function`?t(o,r):t}return[J(t,{context:Object.assign({},t.context,s),children:Object.keys(a).length?{...t.children,...a}:t.children}),void 0,void 0]}function Wt(e){function t(e,t){}return t.type=`xstate.assign`,t.assignment=e,t.resolve=Ut,t}var Gt=new WeakMap;function Y(e,t,n){let r=Gt.get(e);return r?t in r||(r[t]=n()):(r={[t]:n()},Gt.set(e,r)),r[t]}var Kt={},X=e=>typeof e==`string`?{type:e}:typeof e==`function`?`resolve`in e?{type:e.type}:{type:e.name}:e,qt=class e{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(`.`),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?`compound`:this.config.history?`history`:`atomic`),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?be(this.config.states,(t,n)=>new e(t,{_parent:this,_key:n,_machine:this.machine})):Kt,this.type===`compound`&&!this.config.initial)throw Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?`shallow`:this.config.history||!1,this.entry=T(this.config.entry).slice(),this.exit=T(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type===`final`||!this.parent?this.config.output:void 0,this.tags=T(t.tags).slice()}_initialize(){this.transitions=$e(this),this.config.always&&(this.always=E(this.config.always).map(e=>I(this,``,e))),Object.keys(this.states).forEach(e=>{this.states[e]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(X),eventType:null,reenter:!1,meta:this.initial.meta,description:this.initial.description,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(X),eventType:null,meta:this.initial.meta,description:this.initial.description})}:void 0,history:this.history,states:be(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(X)})),entry:this.entry.map(X),exit:this.exit.map(X),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Y(this,`invoke`,()=>T(this.config.invoke).map((e,t)=>{let{src:n,systemId:r}=e,i=e.id??Ee(this.id,t),a=typeof n==`string`?n:`xstate.invoke.${Ee(this.id,t)}`;return{...e,src:a,id:i,systemId:r,toJSON(){let{onDone:t,onError:n,...r}=e;return{...r,type:`xstate.invoke`,src:a,id:i}}}}))}get on(){return Y(this,`on`,()=>[...this.transitions].flatMap(([e,t])=>t.map(t=>[e,t])).reduce((e,[t,n])=>(e[t]=e[t]||[],e[t].push(n),e),{}))}get after(){return Y(this,`delayedTransitions`,()=>Qe(this))}get initial(){return Y(this,`initial`,()=>tt(this,this.config.initial))}next(e,t){let n=t.type,r=[],i,a=Y(this,`candidates-${n}`,()=>Ze(this,n));for(let o of a){let{guard:a}=o,s=e.context,c=!1;try{c=!a||j(a,s,t,e)}catch(e){let t=typeof a==`string`?a:typeof a==`object`?a.type:void 0;throw Error(`Unable to evaluate guard ${t?`'${t}' `:``}in transition for event '${n}' in state node '${this.id}':\n${e.message}`)}if(c){r.push(...o.actions),i=o;break}}return i?[i]:void 0}get events(){return Y(this,`events`,()=>{let{states:e}=this,t=new Set(this.ownEvents);if(e)for(let n of Object.keys(e)){let r=e[n];if(r.states)for(let e of r.events)t.add(`${e}`)}return Array.from(t)})}get ownEvents(){let e=Object.keys(Object.fromEntries(this.transitions)),t=new Set(e.filter(e=>this.transitions.get(e).some(e=>!(!e.target&&!e.actions.length&&!e.reenter))));return Array.from(t)}},Jt=class e{constructor(e,t){this.config=e,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=e.id||`(machine)`,this.implementations={actors:t?.actors??{},actions:t?.actions??{},delays:t?.delays??{},guards:t?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new qt(e,{_key:this.id,_machine:this}),this.root._initialize(),et(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){let{actions:n,guards:r,actors:i,delays:a}=this.implementations;return new e(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...a,...t.delays}})}resolveState(e){let t=kt(this.root,e.value),n=P(B(this.root,t));return q({_nodes:[...n],context:e.context||{},children:{},status:Xe(n,this.root)?`done`:e.status||`active`,output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,t,n){return K(e,t,n,[]).snapshot}microstep(e,t,n){return K(e,t,n,[]).microsteps.map(([e])=>e)}getTransitionData(e,t){return lt(this.root,e.value,e,t)||[]}_getPreInitialState(e,t,n){let{context:r}=this.config,i=q({context:typeof r!=`function`&&r?r:{},_nodes:[this.root],children:{},status:`active`},this);return typeof r==`function`?G(i,t,e,[Wt(({spawn:e,event:t,self:n})=>r({spawn:e,input:t.input,self:n}))],n,void 0):i}getInitialSnapshot(e,t){let n=me(t),r=[],i=q({context:typeof this.config.context!=`function`&&this.config.context?this.config.context:{},_nodes:[this.root],children:{},status:`active`},this);try{i=this._getPreInitialState(e,n,r);let[t]=gt(this.root,i,e,n,r),{snapshot:a}=K(t,n,e,r);return a}catch(e){return J(i,{status:`error`,error:e})}}start(e){Object.values(e.children).forEach(e=>{e.getSnapshot().status===`active`&&e.start()})}getStateNodeById(e){let t=_e(e),n=t.slice(1),r=F(t[0])?t[0].slice(1):t[0],i=this.idMap.get(r);if(!i)throw Error(`Child state node '#${r}' does not exist on machine '${this.id}'`);return z(i,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,t){return Lt(e,t)}restoreSnapshot(e,t){let n={},r=e.children;Object.keys(r).forEach(e=>{let i=r[e],a=i.snapshot,o=i.src,s=typeof o==`string`?De(this,o):o;if(!s)return;let c=k(s,{id:e,parent:t.self,syncSnapshot:i.syncSnapshot,snapshot:a,src:o,systemId:i.systemId});n[e]=c});function i(e,t){if(t instanceof qt)return t;try{return e.machine.getStateNodeById(t.id)}catch{}}function a(e,t){if(!t||typeof t!=`object`)return{};let n={};for(let r in t){let a=t[r];for(let t of a){let a=i(e,t);a&&(n[r]??=[],n[r].push(a))}}return n}let o=a(this.root,e.historyValue),s=q({...e,children:n,_nodes:Array.from(P(B(this.root,e.value))),historyValue:o},this),c=new Set;function l(e,t){if(!c.has(e)){c.add(e);for(let n in e){let r=e[n];if(r&&typeof r==`object`){if(`xstate$$type`in r&&r.xstate$$type===1){e[n]=t[r.id];continue}l(r,t)}}}}return l(s.context,n),s}};function Yt(e,t,n,r,{event:i}){return[t,{event:typeof i==`function`?i(n,r):i},void 0]}function Xt(e,{event:t}){e.defer(()=>e.emit(t))}function Zt(e){function t(e,t){}return t.type=`xstate.emit`,t.event=e,t.resolve=Yt,t.execute=Xt,t}var Qt=function(e){return e.Parent=`#_parent`,e.Internal=`#_internal`,e}({});function $t(e,t,n,r,{to:i,event:a,id:o,delay:s},c){let l=t.machine.implementations.delays;if(typeof a==`string`)throw Error(`Only event objects may be used with sendTo; use sendTo({ type: "${a}" }) instead`);let u=typeof a==`function`?a(n,r):a,d;if(typeof s==`string`){let e=l&&l[s];d=typeof e==`function`?e(n,r):e}else d=typeof s==`function`?s(n,r):s;let f=typeof i==`function`?i(n,r):i,p;if(typeof f==`string`){if(p=f===Qt.Parent?e.self._parent:f===Qt.Internal?e.self:f.startsWith(`#_`)?t.children[f.slice(2)]:c.deferredActorIds?.includes(f)?f:t.children[f],!p)throw Error(`Unable to send event to actor '${f}' from machine '${t.machine.id}'.`)}else p=f||e.self;return[t,{to:p,targetId:typeof f==`string`?f:void 0,event:u,id:o,delay:d},void 0]}function en(e,t,n){typeof n.to==`string`&&(n.to=t.children[n.to])}function tn(e,t){e.defer(()=>{let{to:n,event:r,delay:i,id:a}=t;typeof i==`number`?e.system.scheduler.schedule(e.self,n,r,i,a):e.system._relay(e.self,n,r.type===`xstate.error`?pe(e.self.id,r.data):r)})}function nn(e,t,n){function r(e,t){}return r.type=`xstate.sendTo`,r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=$t,r.retryResolve=en,r.execute=tn,r}function rn(e,t){return nn(Qt.Parent,e,t)}function an(e,t,n,r,{collect:i}){let a=[],o=function(e){a.push(e)};return o.assign=(...e)=>{a.push(Wt(...e))},o.cancel=(...e)=>{a.push(Le(...e))},o.raise=(...e)=>{a.push(Vt(...e))},o.sendTo=(...e)=>{a.push(nn(...e))},o.sendParent=(...e)=>{a.push(rn(...e))},o.spawnChild=(...e)=>{a.push(Be(...e))},o.stopChild=(...e)=>{a.push(A(...e))},o.emit=(...e)=>{a.push(Zt(...e))},i({context:n.context,event:n.event,enqueue:o,check:e=>j(e,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,a]}function on(e){function t(e,t){}return t.type=`xstate.enqueueActions`,t.collect=e,t.resolve=an,t}function sn(e,t,n,r,{value:i,label:a}){return[t,{value:typeof i==`function`?i(n,r):i,label:a},void 0]}function cn({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function ln(e=({context:e,event:t})=>({context:e,event:t}),t){function n(e,t){}return n.type=`xstate.log`,n.value=e,n.label=t,n.resolve=sn,n.execute=cn,n}function un(e,t){return new Jt(e,t)}function dn({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:Wt,sendTo:nn,raise:Vt,log:ln,cancel:Le,stopChild:A,enqueueActions:on,emit:Zt,spawnChild:Be,createStateConfig:e=>e,createAction:e=>e,createMachine:a=>un({...a,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:a=>dn({schemas:e,actors:t,actions:{...n,...a.actions},guards:{...r,...a.guards},delays:{...i,...a.delays}})}}var fn=(e,t,n)=>Math.max(t,Math.min(n,e)),pn=class{dents=[];revision=0;enabled=!1;maxDepthM=0;maskCache=new WeakMap;spriteCache=null;captureState(){return a({dents:this.dents,revision:this.revision,enabled:this.enabled,maxDepthM:this.maxDepthM})}restoreState(e){let t=a(e);this.dents=t.dents,this.revision=t.revision,this.enabled=t.enabled,this.maxDepthM=t.maxDepthM,this.maskCache=new WeakMap,this.spriteCache=null}get hasDamage(){return this.enabled&&this.dents.length>0}get geometryRevision(){return this.revision}setEnabled(e){this.enabled!==e&&(this.enabled=e,e||this.reset())}reset(){this.dents=[],this.maxDepthM=0,this.revision++,this.spriteCache=null}hit(e,t,n,r,i){if(!this.enabled||r<=2.5||!Number.isFinite(r))return!1;let a=Math.max(1,i),s=f(e,n.center),c=m(l(s,n.forward)/a,l(s,n.side)/a),d=m(l(t,n.forward),l(t,n.side)),p=o(d);if(p<.001)return!1;let h=fn((r-2.5)/17.5,0,1)**1.5;return this.maxDepthM=Math.min(.25,8/a),this.dents.push({center:c,inward:u(d,1/p),depthM:this.maxDepthM*h,radiusAlongM:.65+h*.5,radiusAcrossM:.55+h*.55}),this.dents.length>12&&this.dents.shift(),this.revision++,this.spriteCache=null,!0}point(e){if(!this.hasDamage)return e;let t=m();for(let n of this.dents){let r=(e.x-n.center.x)/n.radiusAlongM,i=(e.y-n.center.y)/n.radiusAcrossM,a=Math.hypot(r,i);if(a>=1)continue;let o=(1-a*a)**2;t=p(t,u(n.inward,n.depthM*o))}let n=o(t);return n>this.maxDepthM&&(t=u(t,this.maxDepthM/n)),p(e,t)}maskFor(e){if(!this.hasDamage)return e;let t=this.maskCache.get(e);if(t?.revision===this.revision)return t.value;let{columns:n,rows:r,solid:i}=e.alpha,a=new Uint8Array(i.length),o=e.lengthM/n,s=e.widthM/r;for(let t=0;t<r;t++)for(let c=0;c<n;c++){let l=m((c+.5)*o-e.lengthM/2,(t+.5)*s-e.widthM/2),u=l;for(let e=0;e<5;e++)u=p(u,f(l,this.point(u)));let d=Math.floor((u.x/e.lengthM+.5)*n),h=Math.floor((u.y/e.widthM+.5)*r);d>=0&&d<n&&h>=0&&h<r&&(a[t*n+c]=i[h*n+d])}let c={...e,alpha:{columns:n,rows:r,solid:a}};return this.maskCache.set(e,{revision:this.revision,value:c}),c}spriteFor(e,t){if(!this.hasDamage)return null;let n=`${t.source.x}:${t.source.y}:${t.source.width}:${t.source.height}:${t.lengthM}:${t.widthM}`;if(this.spriteCache?.image===e&&this.spriteCache.key===n&&this.spriteCache.revision===this.revision)return this.spriteCache.canvas;let r=document.createElement(`canvas`);r.width=Math.max(1,Math.round(t.source.width)),r.height=Math.max(1,Math.round(t.source.height));let i=r.getContext(`2d`);if(!i)return null;let a=e=>{let n=m((e.x/r.width-.5)*t.lengthM,(e.y/r.height-.5)*t.widthM),i=this.point(n);return m((i.x/t.lengthM+.5)*r.width,(i.y/t.widthM+.5)*r.height)};for(let n=0;n<10;n++)for(let o=0;o<20;o++){let s=o*r.width/20,c=(o+1)*r.width/20,l=n*r.height/10,u=(n+1)*r.height/10,d=m(s,l),f=m(c,l),p=m(s,u),h=m(c,u);this.drawTriangle(i,e,t,[d,f,p],[a(d),a(f),a(p)]),this.drawTriangle(i,e,t,[h,p,f],[a(h),a(p),a(f)])}return this.spriteCache={image:e,key:n,revision:this.revision,canvas:r},r}drawTriangle(e,t,n,r,i){let[a,o,s]=r,[c,l,u]=i,d=o.x-a.x,f=o.y-a.y,p=s.x-a.x,m=s.y-a.y,h=d*m-p*f;if(Math.abs(h)<1e-4)return;let g=l.x-c.x,_=l.y-c.y,v=u.x-c.x,y=u.y-c.y,b=(g*m-v*f)/h,x=(_*m-y*f)/h,ee=(v*d-g*p)/h,S=(y*d-_*p)/h,te=c.x-b*a.x-ee*a.y,ne=c.y-x*a.x-S*a.y;e.save(),e.beginPath(),e.moveTo(c.x,c.y),e.lineTo(l.x,l.y),e.lineTo(u.x,u.y),e.closePath(),e.clip(),e.transform(b,x,ee,S,te,ne),e.drawImage(t,n.source.x,n.source.y,n.source.width,n.source.height,0,0,e.canvas.width,e.canvas.height),e.restore()}},mn=class{random;pulses=[];constructor(e=Math.random){this.random=e}get active(){return this.pulses}trigger({color:e,angle:n,velocity:r,origin:i}){if(!Number.isFinite(n)||!Number.isFinite(r))throw RangeError(`Pickup angle and velocity must be finite`);if(i&&(!Number.isFinite(i.x)||!Number.isFinite(i.y)||Math.abs(i.x)>.5||Math.abs(i.y)>.5))throw RangeError(`Pickup origin must lie within normalized body coordinates [-0.5, 0.5]`);let a=t(e),o=Math.min(1,Math.abs(r)/32);this.pulses.push({color:[a[0]/255,a[1]/255,a[2]/255],angle:Math.atan2(Math.sin(n),Math.cos(n)),strength:o,velocity:Math.abs(r),origin:i?{...i}:null,variation:this.random(),age:0,duration:.38-o*.1}),this.pulses.length>3&&this.pulses.shift()}step(e){if(!(!this.pulses.length||!Number.isFinite(e)||e<=0)){for(let t of this.pulses)t.age+=e;this.pulses=this.pulses.filter(e=>e.age<e.duration)}}reset(){this.pulses=[]}captureState(){return structuredClone(this.pulses)}restoreState(e){this.pulses=structuredClone(e)}},hn=new Map,Z=null;function gn(e){let t=e.match(/^#([\da-f]{3}|[\da-f]{6})$/i)?.[1];if(t){let e=t.length===3?[...t].map(e=>e+e).join(``):t;return[0,2,4].map(t=>parseInt(e.slice(t,t+2),16))}let n=e.match(/^rgba?\(\s*(\d{1,3})[,\s]+(\d{1,3})[,\s]+(\d{1,3})/i);return n?[d(+n[1],0,255),d(+n[2],0,255),d(+n[3],0,255)]:null}function _n(e){let t=gn(e);if(t)return t;if(hn.has(e))return hn.get(e);let n=null;return typeof document<`u`&&(Z??=document.createElement(`canvas`).getContext(`2d`),Z&&(Z.fillStyle=`#010203`,Z.fillStyle=e,Z.fillStyle!==`#010203`&&(n=gn(Z.fillStyle)))),hn.set(e,n),n}var vn=[[0,0],[60,120],[120,180],[240,240],[300,300],[360,360]];function yn(e,t=!1){let n=(e%360+360)%360;for(let e=1;e<vn.length;e++){let[r,i]=vn[e-1],[a,o]=vn[e],s=t?i:r,c=t?o:a;if(n<=c){let e=(n-s)/(c-s);return(t?r+(a-r)*e:i+(o-i)*e)%360}}return 0}function bn([e,t,n]){let r=e/255,i=t/255,a=n/255,o=Math.max(r,i,a),s=Math.min(r,i,a),c=o-s,l=(o+s)/2;if(c===0)return{hue:0,saturation:0,light:l};let u=c/(1-Math.abs(2*l-1));return{hue:((o===r?(i-a)/c%6:o===i?(a-r)/c+2:(r-i)/c+4)*60+360)%360,saturation:u,light:l}}function xn(e,t,n){let r=(1-Math.abs(2*n-1))*t,i=r*(1-Math.abs(e/60%2-1)),a=Math.floor(e/60)%6,o=[[r,i,0],[i,r,0],[0,r,i],[0,i,r],[i,0,r],[r,0,i]][a],s=n-r/2;return`rgb(${o.map(e=>Math.round((e+s)*255)).join(` `)})`}function Sn(e){let t=e.filter(e=>e.strength>0&&_n(e.color));if(!t.length)return e.at(-1)?.color??`rgb(0 0 0)`;if(t.length===1)return`rgb(${_n(t[0].color).join(` `)})`;let n=0,r=0,i=0,a=0,o=0;for(let e of t){let t=bn(_n(e.color)),s=yn(t.hue)*Math.PI/180,c=e.strength*t.saturation;n+=Math.cos(s)*c,r+=Math.sin(s)*c,i+=t.light*e.strength,a+=c,o+=e.strength}return xn(yn((Math.atan2(r,n)*180/Math.PI+360)%360,!0),Math.min(1,a/o),i/o)}var Cn=class{coatings=new Map;previous=new Map;travelM=new Map;previousLayer=new Map;wetPaths=new Map;exits=new Map;sprayRemainder=new Map;marks=[];markCount=0;captureState(){return a({coatings:this.coatings,previous:this.previous,travelM:this.travelM,previousLayer:this.previousLayer,wetPaths:this.wetPaths,exits:this.exits,sprayRemainder:this.sprayRemainder,marks:this.marks,markCount:this.markCount})}restoreState(e){let t=a(e);this.coatings=t.coatings,this.previous=t.previous,this.travelM=t.travelM,this.previousLayer=t.previousLayer,this.wetPaths=t.wetPaths,this.exits=t.exits,this.sprayRemainder=t.sprayRemainder,this.marks.length=0;for(let e of t.marks)this.marks.push(e);this.markCount=t.markCount}get totalMarks(){return this.markCount}get managedBytes(){return this.marks.length*136+this.travelM.size*16+[...this.coatings.values()].reduce((e,t)=>e+t.size*72,0)+this.previous.size*24+this.previousLayer.size*8+[...this.wetPaths.values()].reduce((e,t)=>e+t.marks.length*160,0)+this.exits.size*24+this.sprayRemainder.size*16}reset(){this.travelM.clear(),this.coatings.clear(),this.previous.clear(),this.previousLayer.clear(),this.wetPaths.clear(),this.exits.clear(),this.sprayRemainder.clear(),this.marks.length=0,this.markCount=0}step(e){e.forEach((e,t)=>this.travelM.set(t,(this.travelM.get(t)??0)+Math.max(0,e)));for(let[t,n]of this.coatings){let r=Math.max(0,e[t]??0);for(let[e,t]of n)t.remaining=Math.max(0,t.remaining-r),t.remaining===0&&n.delete(e);n.size===0&&(this.coatings.delete(t),this.previous.delete(t),this.previousLayer.delete(t),this.wetPaths.delete(t),this.exits.delete(t))}}touch(e,t){if(!t||t.opacity<=0||t.distanceM<=0)return;let n=this.coatings.get(e);n||(n=new Map,this.coatings.set(e,n));let r=t.id??t.color,i=n.get(r);if(n.set(r,{...t,opacity:Math.max(i?.opacity??0,d(t.opacity,0,1)),remaining:t.distanceM}),n.size>16){let e=[...n.entries()].filter(([e])=>e!==r).sort((e,t)=>e[1].opacity*e[1].remaining/e[1].distanceM-t[1].opacity*t[1].remaining/t[1].distanceM)[0];e&&n.delete(e[0])}}wash(e,t=[]){let n=this.coatings.get(e);if(n&&t.length){let e=new Set(t.map(e=>e.id??e.color));for(let t of n.keys())e.has(t)||n.delete(t);if(n.size)return}this.coatings.delete(e),this.previous.delete(e),this.previousLayer.delete(e),this.sprayRemainder.delete(e),this.wetPaths.delete(e),this.exits.delete(e)}splatter(t,n,r,i,a,o,s){let c=this.coating(t);if(!c||a<=0||s<=0)return;let l=e.paint.thickness,u=(this.sprayRemainder.get(t)??0)+a*(9+(1-l)*7)*(c.material?.spray??.5),d=Math.min(24,Math.floor(u));this.sprayRemainder.set(t,u-Math.floor(u));for(let e of ee(n,r,i,d,o,l)){let t=1+e.angularity*1.7,n={x:e.x,y:e.y};this.marks.push({from:n,point:n,angle:Math.atan2(r.y,r.x),widthM:e.radius*2*t/(s*.76),color:c.color,opacity:c.opacity*e.opacity,droplet:{aspect:(.5+Math.random()*.45)/t}}),this.markCount++}this.marks.length>3e4&&this.marks.splice(0,1e3)}trackWet(e,t,n,r,i,a=0,s=!1){let c=this.coating(e);if(!c){this.pauseTrack(e);return}let l=this.previous.get(e),u=this.wetPaths.get(e);if(!u||!l||o(f(t,l))>=1.5*i)u={marks:[],distanceM:0},this.wetPaths.set(e,u),s&&(this.marks.push({...c,from:{...t},point:{...t},angle:n,widthM:r,phaseM:this.travelM.get(e)??0,slip:d(a,0,1),overPuddle:!0}),this.markCount++);else{let p=u.marks.at(-1),m=p&&o(f(p.point,p.from))/i<.02,h=m?p.from:l;m&&(u.distanceM-=o(f(p.point,p.from))/i);let g=o(f(t,h))/i,_={...c,from:{...h},point:{...t},angle:n,widthM:r,phaseM:(this.travelM.get(e)??0)-g,slip:d(a,0,1)};m?u.marks[u.marks.length-1]=_:u.marks.push(_),u.distanceM+=g,s&&g>=.02&&(this.marks.push({..._,overPuddle:!0}),this.markCount++,this.marks.length>3e4&&this.marks.splice(0,1e3));let v=Math.max(.5,r*6);for(;u.marks.length>1&&(u.distanceM>v||u.marks.length>128);){let e=u.marks.shift();u.distanceM-=o(f(e.point,e.from))/i}}this.exits.delete(e),this.previous.set(e,{...t}),this.previousLayer.set(e,!1)}pauseTrack(e){this.wetPaths.delete(e),this.exits.delete(e),this.previous.delete(e),this.previousLayer.delete(e)}track(e,t,n,r,i,a=!1,s=0){let c=this.coating(e);if(!c)return;let l=this.previous.get(e),u=l?o(f(t,l)):0,p=this.wetPaths.has(e)||this.exits.has(e)?.01:.05;if(l&&u<p*i)return;let m=l&&u<1.5*i,h=this.wetPaths.get(e);if(h&&m){let t=Math.max(.35,r*(2+4*(c.material?.film??.6))),n=-h.distanceM;for(let e of h.marks){let r=n+o(f(e.point,e.from))/i;this.marks.push({...e,overPuddle:!1,exit:{fromM:n,toM:r,lengthM:t,leadInM:h.distanceM}}),this.markCount++,n=r}this.exits.set(e,{distanceM:0,lengthM:t})}else m||this.exits.delete(e);this.wetPaths.delete(e);let g=this.exits.get(e),_=g&&g.distanceM<g.lengthM?{fromM:g.distanceM,toM:g.distanceM+u/i,lengthM:g.lengthM}:void 0;g&&(g.distanceM+=u/i,g.distanceM>=g.lengthM&&this.exits.delete(e)),this.marks.push({from:m?{...l}:{...t},point:{...t},angle:n,widthM:r,phaseM:(this.travelM.get(e)??0)-(m?o(f(t,l))/i:0),wetness:c.wetness,material:c.material,slip:d(s,0,1),color:c.color,opacity:c.opacity,overPuddle:a,exit:_}),this.markCount++,this.previous.set(e,{...t}),this.previousLayer.set(e,a),this.marks.length>3e4&&this.marks.splice(0,1e3)}coating(e){let t=this.coatings.get(e);if(!t?.size)return null;let n=[...t.values()].map(e=>({color:e.color,strength:e.opacity*d(e.remaining/e.distanceM,0,1)})),r=[...t.values()].sort((e,t)=>t.opacity*t.remaining/t.distanceM-e.opacity*e.remaining/e.distanceM)[0],i=d(r.remaining/r.distanceM,0,1);return{material:r.material,wetness:i,color:Sn(n),opacity:Math.max(...n.map(e=>e.strength))*i**+Math.max(0,(r.material?.drain??1)-1),remaining:Math.max(...[...t.values()].map(e=>e.remaining)),distanceM:Math.max(...[...t.values()].map(e=>e.distanceM))}}},Q={opening:.32,raising:.52,igniting:.48,closing:.36},wn=class{previewOpen=!1;inspecting=!1;phase=`idle`;elapsed=0;held=!1;presetId=null;flights=[];launchClock=0;queuedShots=0;launches=0;ignitionDuration=Q.igniting;captureState(){return a({previewOpen:this.previewOpen,inspecting:this.inspecting,phase:this.phase,elapsed:this.elapsed,held:this.held,presetId:this.presetId,flights:this.flights,launchClock:this.launchClock,queuedShots:this.queuedShots,launches:this.launches,ignitionDuration:this.ignitionDuration})}restoreState(e){let t=a(e);this.previewOpen=t.previewOpen,this.inspecting=t.inspecting,this.phase=t.phase,this.elapsed=t.elapsed,this.held=t.held,this.presetId=t.presetId,this.flights=t.flights,this.launchClock=t.launchClock,this.queuedShots=t.queuedShots,this.launches=t.launches,this.ignitionDuration=t.ignitionDuration}get state(){return this.phase}get projectile(){let e=this.flights[0];return e?{...e,position:{...e.position}}:null}get projectileCount(){return this.flights.length}get managedBytes(){return this.flights.length*64}get launchCount(){return this.launches}reset(){this.previewOpen=!1,this.inspecting=!1,this.phase=`idle`,this.elapsed=0,this.held=!1,this.flights=[],this.launchClock=0,this.queuedShots=0,this.launches=0,this.ignitionDuration=Q.igniting,this.presetId=null}disarm(){this.held=!1,this.queuedShots=0,(this.phase===`opening`||this.phase===`raising`||this.phase===`igniting`)&&this.transition(`closing`)}transition(e){this.phase=e,this.elapsed=0}step(e,t,n,r,i,a,o,s){if(t.mode!==`car`){this.reset();return}if(this.presetId&&this.presetId!==t.car.preset.id&&this.reset(),this.previewOpen){this.inspecting=!0,this.presetId=t.car.preset.id,(this.phase===`idle`||this.phase===`closing`)&&this.transition(`opening`),this.elapsed+=e,this.phase===`opening`&&this.elapsed>=Q.opening&&this.transition(`raising`),this.phase===`raising`&&(this.elapsed=Math.min(this.elapsed,Q.raising));return}this.inspecting&&(this.inspecting=!1,this.transition(`closing`));let f=!!t.lastInput.rocket;f&&!this.held&&(this.queuedShots++,(this.phase===`idle`||this.phase===`closing`)&&(this.presetId=t.car.preset.id,this.transition(`opening`))),this.held=f;let h=g(t.car.preset);if(this.phase===`idle`&&!this.flights.length)return;this.elapsed+=e,this.launchClock+=e;let _=t.car.preset.roofRocket,v=Math.max(1.05,_.sizeM*1.12);if(this.phase===`opening`&&this.elapsed>=Q.opening)this.transition(`raising`);else if(this.phase===`raising`&&this.elapsed>=Q.raising)this.ignitionDuration=Q.igniting,this.transition(`igniting`),s?.(t.body.world(m(_.xM,_.yM)));else if(this.phase===`igniting`&&this.elapsed>=this.ignitionDuration){let e=c(m(1,0),t.body.angle),n=t.body.world(m(_.xM,_.yM));this.flights.push({position:n,angle:t.body.angle,speedMps:h.launchSpeedMps+Math.max(0,l(t.body.velocity,e)),distanceM:0,age:0}),this.launches++,a?.(n),this.queuedShots=Math.max(0,this.queuedShots-1),this.launchClock=0,this.transition(`flying`)}else this.phase===`closing`&&this.elapsed>=Q.closing&&this.transition(`idle`);if(this.phase===`igniting`){let r=d(this.elapsed/Math.min(.27,this.ignitionDuration*.65),0,.9),a=c(m(-1,0),t.body.angle),o=t.body.world(m(_.xM-v*.52,_.yM));n({point:o,flow:u(a,3.5),amount:e*14*r,radiusM:.2}),i?.({from:o,to:o,flow:u(a,12),widthM:.16,intensity:r*.75})}this.phase===`flying`&&(!f&&this.queuedShots===0?this.transition(`closing`):this.launchClock>=Math.max(0,1/h.roundsPerSecond-Math.min(Q.igniting,.7/h.roundsPerSecond))&&(this.ignitionDuration=Math.min(Q.igniting,.7/h.roundsPerSecond),this.transition(`igniting`),s?.(t.body.world(m(_.xM,_.yM)))));for(let t=this.flights.length-1;t>=0;t--){let a=this.flights[t],s=c(m(1,0),a.angle);a.speedMps=Math.min(h.maxSpeedMps,a.speedMps+h.accelerationMps2*e);let l=a.speedMps*e,d=a.position,f=p(d,u(s,l)),g=r?.(d,f,_.sizeM*.18);a.position=g??f,a.distanceM+=l,a.age+=e;let y=p(a.position,u(s,-v*.53)),b=p(d,u(s,-v*.53));if(n({point:y,flow:u(s,-5),amount:e*h.smokePerSecond,radiusM:.2}),i?.({from:b,to:y,flow:u(s,-18),widthM:.13,intensity:.9}),g){o?.(g);for(let e=0;e<7;e++){let t=c(m(1,0),e*Math.PI*2/7);n({point:g,flow:u(t,5.5),amount:.18,radiusM:.22})}this.flights.splice(t,1)}else(a.age>=h.lifetimeSeconds||a.distanceM>100)&&this.flights.splice(t,1)}this.phase===`closing`&&this.elapsed>=Q.closing&&this.transition(`idle`)}get open(){return this.phase===`idle`?0:this.phase===`opening`?d(this.elapsed/Q.opening,0,1):this.phase===`closing`?1-d(this.elapsed/Q.closing,0,1):1}drawMount(e,t,n,r,i,a=1,o){let s=this.open;if(s<=0)return;te();let c=r.roofRocket,l=c.sizeM*i,u=s*s*(3-2*s);e.save(),e.translate(t.x,t.y),e.rotate(-n),e.translate(c.xM*i,-c.yM*i),e.globalAlpha*=a;let f=e.createLinearGradient(0,-l/2,0,l/2);f.addColorStop(0,`#11171b`),f.addColorStop(.45,`#030609`),f.addColorStop(1,`#222a2e`),e.fillStyle=f,e.beginPath(),e.roundRect(-l/2,-l/2,l,l,l*.06),e.fill(),e.strokeStyle=`#525c62`,e.lineWidth=Math.max(.45,i*.018),e.stroke();for(let t of[-1,1]){e.fillStyle=`#687279`,e.fillRect(-l*.42,t*l*.2,l*.84,l*.035),e.fillStyle=`#161d22`,e.fillRect(-l*.34,-l*.28,l*.065,l*.56);let n=l*.5*(1-u*.78),r=t*(l*.25+u*l*.22);if(e.save(),e.translate(0,r),e.shadowColor=`rgba(0,0,0,.55)`,e.shadowBlur=l*.08,e.shadowOffsetY=l*.035,e.fillStyle=c.panelColor,e.beginPath(),e.roundRect(-l/2,-n/2,l,n,l*.035),e.fill(),e.shadowBlur=0,e.shadowOffsetY=0,o){e.save(),e.clip();let r=o.source.x+(c.xM-c.sizeM/2+o.lengthM/2)/o.lengthM*o.source.width,i=o.source.y+(-c.yM+(t<0?-c.sizeM/2:0)+o.widthM/2)/o.widthM*o.source.height;e.drawImage(o.image,r,i,c.sizeM/o.lengthM*o.source.width,c.sizeM/2/o.widthM*o.source.height,-l/2,-n/2,l,n),e.restore()}e.strokeStyle=`rgba(8,13,17,.7)`,e.lineWidth=Math.max(.45,i*.018),e.stroke(),e.restore()}if(this.phase===`raising`||this.phase===`igniting`){let t=this.phase===`igniting`?1:d(this.elapsed/Q.raising,0,1);e.save(),e.globalAlpha*=t,e.scale(.35+t*.65,.35+t*.65),this.drawBody(e,Math.max(1.05,c.sizeM*1.12)*i,1),e.restore()}e.restore()}drawFlight(e,t,n,r,i=1){for(let a of this.flights){let o=t(a.position);e.save(),e.translate(o.x,o.y),e.rotate(-a.angle),e.globalAlpha=i,this.drawBody(e,Math.max(1.05,n.roofRocket.sizeM*1.12)*r,1),e.restore()}}drawBody(e,t,n){if(e.save(),e.globalAlpha*=n,e.shadowColor=`rgba(0,0,0,.5)`,e.shadowBlur=t*.055,e.shadowOffsetY=t*.025,!S(e,`rocket`,-t*.53,0,t*1.06)){let n=e.createLinearGradient(0,-t*.045,0,t*.045);n.addColorStop(0,`#3b454d`),n.addColorStop(.35,`#d8dddc`),n.addColorStop(1,`#3e484f`),e.fillStyle=n,e.beginPath(),e.moveTo(-t*.53,-t*.045),e.lineTo(t*.3,-t*.045),e.lineTo(t*.53,0),e.lineTo(t*.3,t*.045),e.lineTo(-t*.53,t*.045),e.closePath(),e.fill(),e.fillStyle=`#30383e`;for(let n of[-1,1])e.beginPath(),e.moveTo(-t*.48,n*t*.12),e.lineTo(-t*.22,n*t*.04),e.lineTo(-t*.44,n*t*.04),e.closePath(),e.fill()}e.restore()}},Tn=.22,En=.24,Dn=class{phase=`closed`;phaseTime=0;shotClock=0;flashAge=1/0;presetId=null;bullets=[];captureState(){return a({phase:this.phase,phaseTime:this.phaseTime,shotClock:this.shotClock,flashAge:this.flashAge,presetId:this.presetId,bullets:this.bullets})}restoreState(e){let t=a(e);this.phase=t.phase,this.phaseTime=t.phaseTime,this.shotClock=t.shotClock,this.flashAge=t.flashAge,this.presetId=t.presetId,this.bullets=t.bullets}get state(){return this.phase}get openAmount(){return this.open}get projectileCount(){return this.bullets.length}get managedBytes(){return this.bullets.length*56}reset(){this.phase=`closed`,this.phaseTime=0,this.shotClock=0,this.flashAge=1/0,this.presetId=null,this.bullets=[]}step(e,t,n,r,i){if(t.mode!==`car`){this.reset();return}this.presetId&&this.presetId!==t.car.preset.id&&this.reset();let a=h(t.car.preset),o=!!t.lastInput.machineGun;if(o&&(this.phase===`closed`||this.phase===`closing`)){this.presetId=t.car.preset.id;let e=this.open;this.phase=`opening`,this.phaseTime=e*Tn}else if(!o&&(this.phase===`opening`||this.phase===`active`)){let e=this.open;this.phase=`closing`,this.phaseTime=(1-e)*En}if(this.phaseTime+=e,this.flashAge+=e,this.phase===`opening`&&this.phaseTime>=Tn&&(this.phase=`active`,this.phaseTime=0,this.shotClock=1/a.roundsPerSecond),this.phase===`active`){if(o){let n=1/Math.max(1,a.roundsPerSecond);this.shotClock+=e;for(let e=0;this.shotClock>=n&&e<4;e++)this.shotClock-=n,this.fire(t),r?.()}}else this.phase===`closing`&&this.phaseTime>=En&&(this.phase=`closed`,this.phaseTime=0);for(let t=this.bullets.length-1;t>=0;t--){let r=this.bullets[t],o=r.position,s=p(o,u(r.velocity,e)),c=n?.(o,s,.075);r.age+=e,c||r.age>=a.bulletLifetimeSeconds?(c&&i?.(c,r.velocity),this.bullets.splice(t,1)):r.position=s}}fire(e){let t=h(e.car.preset),n=c(m(1,0),e.body.angle);for(let r of[-1,1]){let i=e.body.world(b(e.car.preset,r)),a=p(u(n,t.bulletSpeedMps),e.body.velocityAt(i));this.bullets.push({position:i,velocity:a,age:0})}this.flashAge=0}get open(){return this.phase===`closed`?0:this.phase===`opening`?d(this.phaseTime/Tn,0,1):this.phase===`closing`?1-d(this.phaseTime/En,0,1):1}drawMount(e,t,n,r,i,a=1,o){x(e,t,n,r,i,this.open,`gun`,Math.max(0,1-this.flashAge/.075),a,o)}drawProjectiles(e,t,n,r=1){e.save(),e.lineCap=`round`;for(let i of this.bullets){let a=t(i.position),o=Math.hypot(i.velocity.x,i.velocity.y),s=t(p(i.position,u(i.velocity,-.75/Math.max(1,o)))),c=e.createLinearGradient(s.x,s.y,a.x,a.y);c.addColorStop(0,`rgba(224,153,63,0)`),c.addColorStop(.7,`rgba(224,153,63,.25)`),c.addColorStop(1,`rgba(255,225,157,.7)`),e.globalAlpha=r,e.strokeStyle=c,e.lineWidth=Math.max(.65,n*.025),e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(a.x,a.y),e.stroke();let l=t(p(i.position,u(i.velocity,-.09/Math.max(1,o))));e.strokeStyle=`#fff6d7`,e.lineWidth=Math.max(.55,n*.018),e.beginPath(),e.moveTo(l.x,l.y),e.lineTo(a.x,a.y),e.stroke()}e.restore()}},On=.22,kn=.24,$=1/45,An=class{phase=`closed`;phaseTime=0;emitting=!1;presetId=null;fireClock=0;jets=[];captureState(){return a({phase:this.phase,phaseTime:this.phaseTime,emitting:this.emitting,presetId:this.presetId,fireClock:this.fireClock,jets:this.jets})}restoreState(e){let t=a(e);this.phase=t.phase,this.phaseTime=t.phaseTime,this.emitting=t.emitting,this.presetId=t.presetId,this.fireClock=t.fireClock,this.jets=t.jets}get state(){return this.phase}get firing(){return this.emitting}get openAmount(){return this.open}get managedBytes(){return this.jets.length*64}reset(){this.phase=`closed`,this.phaseTime=0,this.emitting=!1,this.presetId=null,this.fireClock=0,this.jets=[]}step(e,t,n,r,i){if(t.mode!==`car`){(this.phase!==`closed`||this.jets.length)&&this.reset();return}this.presetId&&this.presetId!==t.car.preset.id&&this.reset();let a=!!t.lastInput.flamethrower,o=_(t.car.preset);if(a&&(this.phase===`closed`||this.phase===`closing`)){this.presetId=t.car.preset.id;let e=this.open;this.phase=`opening`,this.phaseTime=e*On}else if(!a&&(this.phase===`opening`||this.phase===`active`)){let e=this.open;this.phase=`closing`,this.phaseTime=(1-e)*kn}if(this.phaseTime+=e,this.phase===`opening`&&this.phaseTime>=On&&(this.phase=`active`,this.phaseTime=0,this.fireClock=$),this.emitting=this.phase===`active`&&a,this.phase===`closing`&&this.phaseTime>=kn&&(this.phase=`closed`,this.phaseTime=0),this.emitting){let r=c(m(1,0),t.body.angle),i=o.rangeM/.3;for(this.fireClock+=e;this.fireClock>=$;){this.fireClock-=$;for(let e of[-1,1]){let n=t.body.world(b(t.car.preset,e));this.jets.push({point:n,velocity:p(u(r,i),u(t.body.velocity,.25)),traveled:0,range:o.rangeM,speed:i,width:o.jetWidthM*o.flowRate})}}for(let i of[-1,1]){let a=t.body.world(b(t.car.preset,i));n({point:p(a,u(r,.06)),flow:u(r,5.5),amount:e*o.smokePerSecond*o.flowRate*.38,radiusM:.12})}}let s=[];for(let t of this.jets){let a=Math.min(t.range-t.traveled,t.speed*e),c=t.point,l=p(c,u(t.velocity,a/t.speed)),d=(t.traveled+a)/t.range,f=t.width*(.65+1.45*d),m=r?.(c,l,Math.max(.3,f*1.25),$*o.flowRate),h=m??l;t.point=h,t.traveled+=a,i?.(c,h,f,t.velocity,d),(d>.62||m)&&n({point:h,flow:u(t.velocity,.42),amount:e*o.smokePerSecond*o.flowRate*(m?.42:.18),radiusM:Math.max(.11,f*.48)}),m?i?.(h,h,f*1.35,t.velocity,d):t.traveled+1e-6<t.range&&s.push(t)}this.jets=s}get open(){return this.phase===`closed`?0:this.phase===`opening`?d(this.phaseTime/On,0,1):this.phase===`closing`?1-d(this.phaseTime/kn,0,1):1}drawMount(e,t,n,r,i,a=1,o){x(e,t,n,r,i,this.open,`flame`,this.phase===`active`?.8:0,a,o)}},jn=class{rocket=new wn;machineGuns=new Dn;flamethrower=new An;reset(){this.rocket.reset(),this.machineGuns.reset(),this.flamethrower.reset()}stopFiring(){this.rocket.disarm()}captureState(){return{rocket:this.rocket.captureState(),machineGuns:this.machineGuns.captureState(),flamethrower:this.flamethrower.captureState()}}restoreState(e){this.rocket.restoreState(e.rocket),this.machineGuns.restoreState(e.machineGuns),this.flamethrower.restoreState(e.flamethrower)}get managedBytes(){return this.rocket.managedBytes+this.machineGuns.managedBytes+this.flamethrower.managedBytes}},Mn=e=>({...e,slots:e.slots?[...e.slots]:void 0,slotPresses:e.slotPresses?[...e.slotPresses]:void 0}),Nn=dn({types:{events:{}}}).createMachine({id:`vehicleLifecycle`,initial:`drivable`,states:{drivable:{on:{DESTROYED:`destroyed`}},destroyed:{on:{RESPAWNED:`drivable`}}}}),Pn=class{id;sim;damage=new pn;weapons=new jn;tirePaint=new Cn;pickupEffect=new mn;lifecycle=k(Nn).start();controls={throttle:0,steer:0,action:!1};controlSource=`player`;label=``;appearance=`auto`;slotConfiguration=r;toolPolicy={};numberedSlots=y(r);slotHeld=new Set;slotPulses=new Set;slotPresses=new Set;blockedSlots=new Set;disposed=!1;previousSlotInput=new Set;activeEmitters=[];get slots(){return this.slotConfiguration}set slots(e){if(this.disposed)throw Error(`Vehicle is disposed.`);let t=i(e);this.clearSlotInput(),this.slotConfiguration=t,this.numberedSlots=y(t,this.toolPolicy)}liquidEmissions(e){return!this.sim.lastInput.eject||this.isGhost||this.lifecycleState!==`drivable`?[]:this.activeEmitters.map(({slot:t,liquid:n,pulse:r,rate:i,amount:a})=>({slot:t,liquid:n,amount:r?a:Math.max(0,e)*i})).filter(e=>e.amount>0)}useSlot(e){let t=n(e);return this.disposed||!this.numberedSlots[t-1]||this.lifecycleState!==`drivable`?!1:(this.slotPulses.add(t),!0)}startSlot(e){let t=n(e);return this.disposed||!this.numberedSlots[t-1]||this.lifecycleState!==`drivable`?!1:(this.slotHeld.has(t)||this.slotPresses.add(t),this.slotHeld.add(t),!0)}stopSlot(e){this.slotHeld.delete(n(e))}clearSlotInput(){this.slotHeld.clear(),this.slotPulses.clear(),this.slotPresses.clear(),this.blockedSlots.clear(),this.previousSlotInput.clear(),this.activeEmitters=[]}resolveSlots(e){let t=new Set((e.slots??[]).map(n)),r=new Set((e.slotPresses??[]).map(n));for(let e of this.blockedSlots)!t.has(e)&&!r.has(e)?this.blockedSlots.delete(e):(t.delete(e),r.delete(e));let i=new Set([...this.slotHeld,...t]),a=new Set([...this.slotPresses,...r]),o=Mn(e);this.activeEmitters=[];for(let{number:e,slot:t}of this.numberedSlots){let n=i.has(e)&&!this.previousSlotInput.has(e),r=this.slotPulses.has(e)||(t.activation===`tap`?n||a.has(e):a.has(e)&&!i.has(e));(r||t.activation!==`tap`&&i.has(e))&&(t.action===`eject`?(o.eject=!0,this.activeEmitters.push({slot:e,liquid:t.liquid,pulse:r,rate:t.rate??6,amount:t.amount??.65})):o[t.action]=!0)}if(e.eject&&!this.activeEmitters.length){for(let{number:e,slot:t}of this.numberedSlots)if(t.action===`eject`){this.activeEmitters.push({slot:e,liquid:t.liquid,pulse:!1,rate:t.rate??6,amount:t.amount??.65});break}}return this.previousSlotInput=i,o}constructor(e,t){this.id=e,this.sim=t}get lifecycleState(){return this.lifecycle.getSnapshot().value}get isGhost(){return this.sim.mode===`car`&&this.lifecycleState===`drivable`&&!!this.controls.ghost}setControls(e,t,r={}){if(r.toolsEnabled!==this.toolPolicy.toolsEnabled){let t=y(this.slotConfiguration,r);if(t.length!==this.numberedSlots.length||t.some(({source:e},t)=>e!==this.numberedSlots[t].source)){this.clearSlotInput();for(let t of[...e.slots??[],...e.slotPresses??[]])this.blockedSlots.add(n(t))}this.toolPolicy=r,this.numberedSlots=t}this.controls=v(this.resolveSlots(e),r.toolsEnabled),this.controlSource=t}step(e,t,n=!1){this.pickupEffect.step(e),n?this.sim.lastInput={throttle:0,steer:0,action:!1,boost:!1}:this.sim.tick(this.lifecycleState===`drivable`?this.controls:{throttle:0,steer:0,action:!1},e,t),this.slotPulses.clear(),this.slotPresses.clear()}synchronizeLifecycle(){let e=this.sim.car.explodedAt!==null;e&&this.lifecycleState===`drivable`?(this.lifecycle.send({type:`DESTROYED`}),this.weapons.stopFiring(),this.clearSlotInput(),this.sim.lastInput={throttle:0,steer:0,action:!1,boost:!1}):!e&&this.lifecycleState===`destroyed`&&this.lifecycle.send({type:`RESPAWNED`})}reset(){this.clearSlotInput(),this.sim.reset(),this.damage.reset(),this.weapons.reset(),this.tirePaint.reset(),this.pickupEffect.reset(),this.synchronizeLifecycle()}restoreHealth(){this.sim.car.resetBurnable(),this.synchronizeLifecycle()}setMode(e){this.clearSlotInput(),this.sim.setMode(e),this.damage.reset(),this.weapons.reset(),this.tirePaint.reset(),this.pickupEffect.reset(),this.synchronizeLifecycle()}setPreset(e){this.clearSlotInput(),this.sim.setPreset(e),this.damage.reset(),this.weapons.reset(),this.tirePaint.reset(),this.pickupEffect.reset(),this.synchronizeLifecycle()}advanceBurn(e){if(this.sim.mode!==`car`)return null;let{car:t}=this.sim;t.advanceBurn(e),this.synchronizeLifecycle();let n=t.stage;if(n===`intact`)return null;let r=!1,i=!1;this.lifecycleState===`destroyed`&&(t.blastQueued||(t.blastQueued=!0,r=!0),t.blastAge+=e,t.blastAge<.36&&t.blastAge-t.lastBlastEmission>=1/30&&(i=!0,t.lastBlastEmission=t.blastAge));let a={stage:n,health:t.health,maxHealth:t.maxHealth,key:t,burnOriginLocal:{...t.burnOriginLocal},blastAge:t.blastAge,explosionStarted:r,blastPulse:i};return this.lifecycleState===`destroyed`&&t.blastAge>=s.respawnSeconds&&(this.sim.resetAtCurrentPose(),this.damage.reset(),this.synchronizeLifecycle()),a}captureState(){return{id:this.id,label:this.label,appearance:this.appearance,slots:structuredClone(this.slots),slotHeld:[...this.slotHeld],slotPulses:[...this.slotPulses],slotPresses:[...this.slotPresses],blockedSlots:[...this.blockedSlots],previousSlotInput:[...this.previousSlotInput],activeEmitters:this.activeEmitters.map(e=>({...e})),simulation:this.sim.captureState(),damage:this.damage.captureState(),weapons:this.weapons.captureState(),tirePaint:this.tirePaint.captureState(),pickupEffect:this.pickupEffect.captureState(),controls:Mn(this.controls),controlSource:this.controlSource,lifecycle:this.lifecycle.getPersistedSnapshot()}}restoreState(e){if(e.id!==this.id)throw Error(`Checkpoint vehicle does not match`);this.label=e.label,this.appearance=e.appearance,this.slots=structuredClone(e.slots),this.slotHeld=new Set(e.slotHeld),this.slotPulses=new Set(e.slotPulses),this.slotPresses=new Set(e.slotPresses),this.blockedSlots=new Set(e.blockedSlots),this.previousSlotInput=new Set(e.previousSlotInput),this.activeEmitters=e.activeEmitters.map(e=>({...e})),this.sim.restoreState(e.simulation),this.damage.restoreState(e.damage),this.weapons.restoreState(e.weapons),this.tirePaint.restoreState(e.tirePaint),this.pickupEffect.restoreState(e.pickupEffect),this.controls=Mn(e.controls),this.controlSource=e.controlSource,this.lifecycle.stop(),this.lifecycle=k(Nn,{snapshot:e.lifecycle}).start()}dispose(){this.disposed=!0,this.pickupEffect.reset(),this.clearSlotInput(),this.lifecycle.stop()}};export{pn as n,Pn as t};
1
+ import{a as e,r as t}from"./definitions~index~embed~bookmarklet~vehicle-popover~Documentation~JoyRideView~browser-sessi~fklztn3g-BG7sJuWo.js";import{S as n,b as r,x as i}from"./definitions~index~embed~bookmarklet-CfH2mYuH.js";import{r as a}from"./definitions~index~embed~vehicle-popover~browser-session-core~renderer-RDNEXk_b.js";import{a as o,b as s,c,i as l,l as u,n as d,o as f,s as p,u as m}from"./runtime~index~embed~vehicle-popover~browser-session-core~renderer-DKaOSaI2.js";import{i as h,o as g,r as _}from"./configuration~index~embed~bookmarklet-6dUo7fKK.js";import{n as v,r as y}from"./vehicle-catalog~index~embed-CkmzFsdm.js";import{_ as b,g as x,n as ee,v as S,y as te}from"./runtime~vehicle-popover~browser-session-core~renderer-DRXQjSAc.js";function ne(){if(typeof globalThis<`u`)return globalThis;if(typeof self<`u`)return self;if(typeof window<`u`)return window;if(typeof global<`u`)return global}function re(){let e=ne();if(e.__xstate__)return e.__xstate__}var ie=e=>{if(typeof window>`u`)return;let t=re();t&&t.register(e)},ae=class{constructor(e){this._process=e,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(e){let t={value:e,next:null};this._current?(this._last.next=t,this._last=t):(this._current=t,this._last=t,this._active&&this.flush())}flush(){for(;this._current;){let e=this._current;this._process(e.value),this._current=e.next}this._last=null}},oe=``,se=`#`,ce=`*`,le=`xstate.init`,ue=`xstate.stop`;function de(e,t){return{type:`xstate.after.${e}.${t}`}}function C(e,t){return{type:`xstate.done.state.${e}`,output:t}}function fe(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function pe(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function me(e){return{type:le,input:e}}function w(e){setTimeout(()=>{throw e})}var he=typeof Symbol==`function`&&Symbol.observable||`@@observable`;function ge(e,t){let n=ve(e),r=ve(t);return typeof r==`string`?typeof n==`string`&&r===n:typeof n==`string`?n in r:Object.keys(n).every(e=>e in r&&ge(n[e],r[e]))}function _e(e){if(Ce(e))return e;let t=[],n=``;for(let r=0;r<e.length;r++){switch(e.charCodeAt(r)){case 92:n+=e[r+1],r++;continue;case 46:t.push(n),n=``;continue}n+=e[r]}return t.push(n),t}function ve(e){return At(e)?e.value:typeof e==`string`?ye(_e(e)):e}function ye(e){if(e.length===1)return e[0];let t={},n=t;for(let t=0;t<e.length-1;t++)if(t===e.length-2)n[e[t]]=e[t+1];else{let r=n;n={},r[e[t]]=n}return t}function be(e,t){let n={},r=Object.keys(e);for(let i=0;i<r.length;i++){let a=r[i];n[a]=t(e[a],a,e,i)}return n}function xe(e){return Ce(e)?e:[e]}function T(e){return e===void 0?[]:xe(e)}function Se(e,t,n,r){return typeof e==`function`?e({context:t,event:n,self:r}):e}function Ce(e){return Array.isArray(e)}function we(e){return e.type.startsWith(`xstate.error.actor`)}function E(e){return xe(e).map(e=>e===void 0||typeof e==`string`?{target:e}:e)}function Te(e){if(e!==void 0&&e!==oe)return T(e)}function D(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}function Ee(e,t){return`${t}.${e}`}function De(e,t){let n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];let[,r,i]=n,a=e.getStateNodeById(i).config.invoke;return(Array.isArray(a)?a[r]:a).src}function Oe(e,t){if(t===e||t===ce)return!0;if(!t.endsWith(`.*`))return!1;let n=t.split(`.`),r=e.split(`.`);for(let e=0;e<n.length;e++){let t=n[e],i=r[e];if(t===`*`)return e===n.length-1;if(t!==i)return!1}return!0}function ke(e,t){return`${e.sessionId}.${t}`}var Ae=0;function je(e,t){let n=new Map,r=new Map,i=new WeakMap,a=new Set,o={},{clock:s,logger:c}=t,l={schedule:(e,t,n,r,i=Math.random().toString(36).slice(2))=>{let a={source:e,target:t,event:n,delay:r,id:i,startedAt:Date.now()},c=ke(e,i);u._snapshot._scheduledEvents[c]=a;let l=s.setTimeout(()=>{delete o[c],delete u._snapshot._scheduledEvents[c],u._relay(e,t,n)},r);o[c]=l},cancel:(e,t)=>{let n=ke(e,t),r=o[n];delete o[n],delete u._snapshot._scheduledEvents[n],r!==void 0&&s.clearTimeout(r)},cancelAll:e=>{for(let t in u._snapshot._scheduledEvents){let n=u._snapshot._scheduledEvents[t];n.source===e&&l.cancel(e,n.id)}}},u={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Ae++}`,_register:(e,t)=>(n.set(e,t),e),_unregister:e=>{n.delete(e.sessionId);let t=i.get(e);t!==void 0&&(r.delete(t),i.delete(e))},get:e=>r.get(e),getAll:()=>Object.fromEntries(r.entries()),_set:(e,t)=>{let n=r.get(e);if(n&&n!==t)throw Error(`Actor with system ID '${e}' already exists.`);r.set(e,t),i.set(t,e)},inspect:e=>{let t=D(e);return a.add(t),{unsubscribe(){a.delete(t)}}},_sendInspectionEvent:t=>{if(!a.size)return;let n={...t,rootId:e.sessionId};a.forEach(e=>e.next?.(n))},_relay:(e,t,n)=>{u._sendInspectionEvent({type:`@xstate.event`,sourceRef:e,actorRef:t,event:n}),t._send(n)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{let e=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(let t in e){let{source:n,target:r,event:i,delay:a,id:o}=e[t];l.schedule(n,r,i,a,o)}},_clock:s,_logger:c};return u}var Me=!1,O=function(e){return e[e.NotStarted=0]=`NotStarted`,e[e.Running=1]=`Running`,e[e.Stopped=2]=`Stopped`,e}({}),Ne={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1},Pe=class{constructor(e,t){this.logic=e,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new ae(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=O.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];let n={...Ne,...t},{clock:r,logger:i,parent:a,syncSnapshot:o,id:s,systemId:c,inspect:l}=n;this.system=a?a.system:je(this,{clock:r,logger:i}),l&&!a&&this.system.inspect(D(l)),this.sessionId=this.system._bookId(),this.id=s??this.sessionId,this.logger=t?.logger??this.system._logger,this.clock=t?.clock??this.system._clock,this._parent=a,this._syncSnapshot=o,this.options=n,this.src=n.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:e=>{this._deferred.push(e)},system:this.system,stopChild:e=>{if(e._parent!==this)throw Error(`Cannot stop child actor ${e.id} of ${this.id} because it is not a child`);e._stop()},emit:e=>{let t=this.eventListeners.get(e.type),n=this.eventListeners.get(`*`);if(!t&&!n)return;let r=[...t?t.values():[],...n?n.values():[]];for(let t of r)try{t(e)}catch(e){w(e)}},actionExecutor:e=>{let t=()=>{if(this._actorScope.system._sendInspectionEvent({type:`@xstate.action`,actorRef:this,action:{type:e.type,params:e.params}}),!e.exec)return;let t=Me;try{Me=!0,e.exec(e.info,e.params)}finally{Me=t}};this._processingStatus===O.Running?t():this._deferred.push(t)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:`@xstate.actor`,actorRef:this}),c&&(this.systemId=c,this.system._set(c,this)),this._initState(t?.snapshot??t?.state),c&&this._snapshot.status!==`active`&&this.system._unregister(this)}_initState(e){try{this._snapshot=e?this.logic.restoreSnapshot?this.logic.restoreSnapshot(e,this._actorScope):e:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(e){this._snapshot={status:`error`,output:void 0,error:e}}}update(e,t){this._snapshot=e;let n;for(;n=this._deferred.shift();)try{n()}catch(t){this._deferred.length=0,this._snapshot={...e,status:`error`,error:t}}switch(this._snapshot.status){case`active`:for(let t of this.observers)try{t.next?.(e)}catch(e){w(e)}break;case`done`:for(let t of this.observers)try{t.next?.(e)}catch(e){w(e)}this._stopProcedure(),this._complete(),this._doneEvent=fe(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case`error`:this._error(this._snapshot.error)}this.system._sendInspectionEvent({type:`@xstate.snapshot`,actorRef:this,event:t,snapshot:e})}subscribe(e,t,n){let r=D(e,t,n);if(this._processingStatus!==O.Stopped)this.observers.add(r);else switch(this._snapshot.status){case`done`:try{r.complete?.()}catch(e){w(e)}break;case`error`:{let e=this._snapshot.error;if(!r.error)w(e);else try{r.error(e)}catch(e){w(e)}break}}return{unsubscribe:()=>{this.observers.delete(r)}}}on(e,t){let n=this.eventListeners.get(e);n||(n=new Set,this.eventListeners.set(e,n));let r=t.bind(void 0);return n.add(r),{unsubscribe:()=>{n.delete(r)}}}select(e,t=Object.is){return{subscribe:n=>{let r=D(n),i=e(this.getSnapshot());return this.subscribe(n=>{let a=e(n);t(i,a)||(i=a,r.next?.(a))})},get:()=>e(this.getSnapshot())}}start(){if(this._processingStatus===O.Running)return this;this._syncSnapshot&&this.subscribe({next:e=>{e.status===`active`&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:e})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=O.Running;let e=me(this.options.input);switch(this.system._sendInspectionEvent({type:`@xstate.event`,sourceRef:this._parent,actorRef:this,event:e}),this._snapshot.status){case`done`:return this.update(this._snapshot,e),this;case`error`:return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(e){return this._snapshot={...this._snapshot,status:`error`,error:e},this._error(e),this}return this.update(this._snapshot,e),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(e){let t,n;try{t=this.logic.transition(this._snapshot,e,this._actorScope)}catch(e){n={err:e}}if(n){let{err:e}=n;this._snapshot={...this._snapshot,status:`error`,error:e},this._error(e)}else this.update(t,e),e.type===`xstate.stop`&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===O.Stopped?this:(this.mailbox.clear(),this._processingStatus===O.NotStarted?(this._processingStatus=O.Stopped,this):(this.mailbox.enqueue({type:ue}),this))}stop(){if(this._parent)throw Error(`A non-root actor cannot be stopped directly.`);return this._stop()}_complete(){for(let e of this.observers)try{e.complete?.()}catch(e){w(e)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){this._parent||w(e),this.eventListeners.clear();return}let t=!1;for(let n of this.observers){let r=n.error;t||=!r;try{r?.(e)}catch(e){w(e)}}this.observers.clear(),this.eventListeners.clear(),t&&w(e)}_error(e){this._stopProcedure(),this._reportError(e),this._parent&&this.system._relay(this,this._parent,pe(this.id,e))}_stopProcedure(){return this._processingStatus===O.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new ae(this._process.bind(this)),this._processingStatus=O.Stopped,this.system._unregister(this)),this}_send(e){this._processingStatus!==O.Stopped&&this.mailbox.enqueue(e)}send(e){this.system._relay(void 0,this,e)}attachDevTools(){let{devTools:e}=this.options;e&&(typeof e==`function`?e:ie)(this)}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[he](){return this}getSnapshot(){return this._snapshot}};function k(e,...[t]){return new Pe(e,t)}function Fe(e,t,n,r,{sendId:i}){return[t,{sendId:typeof i==`function`?i(n,r):i},void 0]}function Ie(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function Le(e){function t(e,t){}return t.type=`xstate.cancel`,t.sendId=e,t.resolve=Fe,t.execute=Ie,t}function Re(e,t,n,r,{id:i,systemId:a,src:o,input:s,syncSnapshot:c}){let l=typeof o==`string`?De(t.machine,o):o,u=typeof i==`function`?i(n):i,d,f;return l&&(f=typeof s==`function`?s({context:t.context,event:n.event,self:e.self}):s,d=k(l,{id:u,src:o,parent:e.self,syncSnapshot:c,systemId:a,input:f})),[J(t,{children:{...t.children,[u]:d}}),{id:i,systemId:a,actorRef:d,src:o,input:f},void 0]}function ze(e,{actorRef:t}){t&&e.defer(()=>{t._processingStatus!==O.Stopped&&t.start()})}function Be(...[e,{id:t,systemId:n,input:r,syncSnapshot:i=!1}={}]){function a(e,t){}return a.type=`xstate.spawnChild`,a.id=t,a.systemId=n,a.src=e,a.input=r,a.syncSnapshot=i,a.resolve=Re,a.execute=ze,a}function Ve(e,t,n,r,{actorRef:i}){let a=typeof i==`function`?i(n,r):i,o=typeof a==`string`?t.children[a]:a,s=t.children;return o&&(s={...s},delete s[o.id]),[J(t,{children:s}),o,void 0]}function He(e,t){let n=t.getSnapshot();if(n&&`children`in n)for(let t of Object.values(n.children))He(e,t);e.system._unregister(t)}function Ue(e,t){t&&(He(e,t),t._processingStatus===O.Running?e.defer(()=>{e.stopChild(t)}):e.stopChild(t))}function A(e){function t(e,t){}return t.type=`xstate.stopChild`,t.actorRef=e,t.resolve=Ve,t.execute=Ue,t}function We(e,{context:t,event:n},{guards:r}){return r.every(r=>j(r,t,n,e))}function Ge(e){function t(e,t){return!1}return t.check=We,t.guards=e,t}function j(e,t,n,r){let{machine:i}=r,a=typeof e==`function`,o=a?e:i.implementations.guards[typeof e==`string`?e:e.type];if(!a&&!o)throw Error(`Guard '${typeof e==`string`?e:e.type}' is not implemented.'.`);if(typeof o!=`function`)return j(o,t,n,r);let s={context:t,event:n},c=a||typeof e==`string`?void 0:`params`in e?typeof e.params==`function`?e.params({context:t,event:n}):e.params:void 0;return`check`in o?o.check(r,s,o):o(s,c)}function Ke(e){return e.type===`atomic`||e.type===`final`}function M(e){return Object.values(e.states).filter(e=>e.type!==`history`)}function N(e,t){let n=[];if(t===e)return n;let r=e.parent;for(;r&&r!==t;)n.push(r),r=r.parent;return n}function P(e){let t=new Set(e),n=Je(t);for(let e of t)if(e.type===`compound`&&(!n.get(e)||!n.get(e).length))it(e).forEach(e=>t.add(e));else if(e.type===`parallel`){for(let n of M(e))if(n.type!==`history`&&!t.has(n)){let e=it(n);for(let n of e)t.add(n)}}for(let e of t){let n=e.parent;for(;n;)t.add(n),n=n.parent}return t}function qe(e,t){let n=t.get(e);if(!n)return{};if(e.type===`compound`){let e=n[0];if(e){if(Ke(e))return e.key}else return{}}let r={};for(let e of n)r[e.key]=qe(e,t);return r}function Je(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function Ye(e,t){return qe(e,Je(P(t)))}function Xe(e,t){return t.type===`compound`?M(t).some(t=>t.type===`final`&&e.has(t)):t.type===`parallel`?M(t).every(t=>Xe(e,t)):t.type===`final`}var F=e=>e[0]===se;function Ze(e,t){let n=e.transitions.get(t),r=[...e.transitions.keys()].filter(e=>e!==t&&Oe(t,e)).sort((e,t)=>t.length-e.length).flatMap(t=>e.transitions.get(t));return n?[...n,...r]:r}function Qe(e){let t=e.config.after;if(!t)return[];let n=t=>{let n=de(t,e.id),r=n.type;return e.entry.push(Vt(n,{id:r,delay:t})),e.exit.push(Le(r)),r};return Object.keys(t).flatMap(e=>{let r=t[e],i=typeof r==`string`?{target:r}:r,a=Number.isNaN(+e)?e:+e,o=n(a);return T(i).map(e=>({...e,event:o,delay:a}))}).map(t=>{let{delay:n}=t;return{...I(e,t.event,t),delay:n}})}function I(e,t,n){let r=Te(n.target),i=n.reenter??!1,a=nt(e,r),o={...n,actions:T(n.actions),guard:n.guard,target:a,source:e,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${e.id}`,target:a?a.map(e=>`#${e.id}`):void 0})};return o}function $e(e){let t=new Map;if(e.config.on)for(let n of Object.keys(e.config.on)){if(n===``)throw Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let r=e.config.on[n];t.set(n,E(r).map(t=>I(e,n,t)))}if(e.config.onDone){let n=`xstate.done.state.${e.id}`;t.set(n,E(e.config.onDone).map(t=>I(e,n,t)))}for(let n of e.invoke){if(n.onDone){let r=`xstate.done.actor.${n.id}`;t.set(r,E(n.onDone).map(t=>I(e,r,t)))}if(n.onError){let r=`xstate.error.actor.${n.id}`;t.set(r,E(n.onError).map(t=>I(e,r,t)))}if(n.onSnapshot){let r=`xstate.snapshot.${n.id}`;t.set(r,E(n.onSnapshot).map(t=>I(e,r,t)))}}for(let n of e.after){let e=t.get(n.eventType);e||(e=[],t.set(n.eventType,e)),e.push(n)}return t}function et(e){let t=[],n=r=>{Object.values(r).forEach(r=>{if(r.config.route&&r.config.id){let n=r.config.id,i=r.config.route.guard,a=({event:e})=>e.to===`#${n}`,o={...r.config.route,guard:i?Ge([a,i]):a,target:`#${n}`};t.push(I(e,`xstate.route`,o))}r.states&&n(r.states)})};n(e.states),t.length>0&&e.transitions.set(`xstate.route`,t)}function tt(e,t){let n=typeof t==`string`?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw Error(`Initial state node "${t}" not found on parent state node #${e.id}`);let r={source:e,actions:!t||typeof t==`string`?[]:T(t.actions),eventType:null,reenter:!1,target:n?[n]:[],meta:typeof t==`object`?t.meta:void 0,description:typeof t==`object`?t.description:void 0,toJSON:()=>({...r,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return r}function nt(e,t){if(t!==void 0)return t.map(t=>{if(typeof t!=`string`)return t;if(F(t))return e.machine.getStateNodeById(t);let n=t[0]===`.`;if(n&&!e.parent)return z(e,t.slice(1));let r=n?e.key+t:t;if(e.parent)try{return z(e.parent,r)}catch(t){throw Error(`Invalid transition definition for state node '${e.id}':\n${t.message}`)}throw Error(`Invalid target: "${t}" is not a valid target from the root node. Did you mean ".${t}"?`)})}function rt(e){let t=Te(e.config.target);return t?{target:t.map(t=>typeof t==`string`?z(e.parent,t):t)}:e.parent.type===`parallel`?{target:[e.parent]}:e.parent.initial}function L(e){return e.type===`history`}function it(e){let t=at(e);for(let n of t)for(let r of N(n,e))t.add(r);return t}function at(e){let t=new Set;function n(e){if(!t.has(e)){if(t.add(e),e.type===`compound`)n(e.initial.target[0]);else if(e.type===`parallel`)for(let t of M(e))n(t)}}return n(e),t}function R(e,t){if(F(t))return e.machine.getStateNodeById(t);if(!e.states)throw Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);let n=e.states[t];if(!n)throw Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function z(e,t){if(typeof t==`string`&&F(t))try{return e.machine.getStateNodeById(t)}catch{}let n=_e(t).slice(),r=e;for(;n.length;){let e=n.shift();if(!e.length)break;r=R(r,e)}return r}function B(e,t){if(typeof t==`string`){let n=e.states[t];if(!n)throw Error(`State '${t}' does not exist on '${e.id}'`);return[e,n]}let n=Object.keys(t),r=n.map(t=>R(e,t)).filter(Boolean);return[e.machine.root,e].concat(r,n.reduce((n,r)=>{let i=R(e,r);if(!i)return n;let a=B(i,t[r]);return n.concat(a)},[]))}function ot(e,t,n,r){let i=R(e,t).next(n,r);return!i||!i.length?e.next(n,r):i}function st(e,t,n,r){let i=Object.keys(t),a=lt(R(e,i[0]),t[i[0]],n,r);return!a||!a.length?e.next(n,r):a}function ct(e,t,n,r){let i=[];for(let a of Object.keys(t)){let o=t[a];if(!o)continue;let s=lt(R(e,a),o,n,r);s&&i.push(...s)}return i.length?i:e.next(n,r)}function lt(e,t,n,r){return typeof t==`string`?ot(e,t,n,r):Object.keys(t).length===1?st(e,t,n,r):ct(e,t,n,r)}function ut(e){return Object.keys(e.states).map(t=>e.states[t]).filter(e=>e.type===`history`)}function V(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function dt(e,t){let n=new Set(e),r=new Set(t);for(let e of n)if(r.has(e))return!0;for(let e of r)if(n.has(e))return!0;return!1}function ft(e,t,n){let r=new Set;for(let i of e){let e=!1,a=new Set;for(let o of r)if(dt(U([i],t,n),U([o],t,n))){if(V(i.source,o.source))a.add(o);else{e=!0;break}}if(!e){for(let e of a)r.delete(e);r.add(i)}}return Array.from(r)}function pt(e){let[t,...n]=e;for(let e of N(t,void 0))if(n.every(t=>V(t,e)))return e}function H(e,t){if(!e.target)return[];let n=new Set;for(let r of e.target)if(L(r)){if(t[r.id])for(let e of t[r.id])n.add(e);else for(let e of H(rt(r),t))n.add(e)}else n.add(r);return[...n]}function mt(e,t){let n=H(e,t);if(!n)return;if(!e.reenter&&n.every(t=>t===e.source||V(t,e.source)))return e.source;let r=pt(n.concat(e.source));if(r)return r;if(!e.reenter)return e.source.machine.root}function U(e,t,n){let r=new Set;for(let i of e)if(i.target?.length){let e=mt(i,n);i.reenter&&i.source===e&&r.add(e);for(let n of t)V(n,e)&&r.add(n)}return[...r]}function ht(e,t){if(e.length!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function gt(e,t,n,r,i){return _t([{target:[...at(e)],source:e,reenter:!0,actions:[],eventType:null,toJSON:null}],t,n,r,!0,i)}function _t(e,t,n,r,i,a){let o=[];if(!e.length)return[t,o];let s=n.actionExecutor;n.actionExecutor=e=>{o.push(e),s(e)};try{let s=new Set(t._nodes),c=t.historyValue,l=ft(e,s,c),u=t;i||([u,c]=Ct(u,r,n,l,s,c,a,n.actionExecutor)),u=G(u,r,n,l.flatMap(e=>e.actions),a,void 0),u=yt(u,r,n,l,s,a,c,i);let d=[...s];u.status===`done`&&(u=G(u,r,n,d.sort((e,t)=>t.order-e.order).flatMap(e=>e.exit),a,void 0));try{return c===t.historyValue&&ht(t._nodes,s)?[u,o]:[J(u,{_nodes:d,historyValue:c}),o]}catch(e){throw e}}finally{n.actionExecutor=s}}function vt(e,t,n,r,i){if(r.output===void 0)return;let a=C(i.id,i.output!==void 0&&i.parent?Se(i.output,e.context,t,n.self):void 0);return Se(r.output,e.context,a,n.self)}function yt(e,t,n,r,i,a,o,s){let c=e,l=new Set,u=new Set;bt(r,o,u,l),s&&u.add(e.machine.root);let d=new Set;for(let e of[...l].sort((e,t)=>e.order-t.order)){i.add(e);let r=[];r.push(...e.entry);for(let t of e.invoke)r.push(Be(t.src,{...t,syncSnapshot:!!t.onSnapshot}));if(u.has(e)){let t=e.initial.actions;r.push(...t)}if(c=G(c,t,n,r,a,e.invoke.map(e=>e.id)),e.type===`final`){let r=e.parent,o=r?.type===`parallel`?r:r?.parent,s=o||e;for(r?.type===`compound`&&a.push(C(r.id,e.output===void 0?void 0:Se(e.output,c.context,t,n.self)));o?.type===`parallel`&&!d.has(o)&&Xe(i,o);)d.add(o),a.push(C(o.id)),s=o,o=o.parent;if(o)continue;c=J(c,{status:`done`,output:vt(c,t,n,c.machine.root,s)})}}return c}function bt(e,t,n,r){for(let i of e){let e=mt(i,t);for(let a of i.target||[])!L(a)&&(i.source!==a||i.source!==e||i.reenter)&&(r.add(a),n.add(a)),W(a,t,n,r);let a=H(i,t);for(let o of a){let a=N(o,e);e?.type===`parallel`&&a.push(e),xt(r,t,n,a,!i.source.parent&&i.reenter?void 0:e)}}}function W(e,t,n,r){if(L(e)){if(t[e.id]){let i=t[e.id];for(let e of i)r.add(e),W(e,t,n,r);for(let a of i)St(a,e.parent,r,t,n)}else{let i=rt(e);for(let a of i.target)r.add(a),i===e.parent?.initial&&n.add(e.parent),W(a,t,n,r);for(let a of i.target)St(a,e.parent,r,t,n)}}else if(e.type===`compound`){let[i]=e.initial.target;L(i)||(r.add(i),n.add(i)),W(i,t,n,r),St(i,e,r,t,n)}else if(e.type===`parallel`)for(let i of M(e).filter(e=>!L(e)))[...r].some(e=>V(e,i))||(L(i)||(r.add(i),n.add(i)),W(i,t,n,r))}function xt(e,t,n,r,i){for(let a of r)if((!i||V(a,i))&&e.add(a),a.type===`parallel`)for(let r of M(a).filter(e=>!L(e)))[...e].some(e=>V(e,r))||(e.add(r),W(r,t,n,e))}function St(e,t,n,r,i){xt(n,r,i,N(e,t))}function Ct(e,t,n,r,i,a,o,s){let c=e,l=U(r,i,a);l.sort((e,t)=>t.order-e.order);let u;for(let e of l)for(let t of ut(e)){let n;n=t.history===`deep`?t=>Ke(t)&&V(t,e):t=>t.parent===e,u??={...a},u[t.id]=Array.from(i).filter(n)}for(let e of l)c=G(c,t,n,[...e.exit,...e.invoke.map(e=>A(e.id))],o,void 0),i.delete(e);return[c,u||a]}function wt(e,t){return e.implementations.actions[t]}function Tt(e,t,n,r,i,a){let{machine:o}=e,s=e;for(let e of r){let r=typeof e==`function`,c=r?e:wt(o,typeof e==`string`?e:e.type),l={context:s.context,event:t,self:n.self,system:n.system},u=r||typeof e==`string`?void 0:`params`in e?typeof e.params==`function`?e.params({context:s.context,event:t}):e.params:void 0;if(!c||!(`resolve`in c)){n.actionExecutor({type:typeof e==`string`?e:typeof e==`object`?e.type:e.name||`(anonymous)`,info:l,params:u,exec:c});continue}let d=c,[f,p,m]=d.resolve(n,s,l,u,c,i);s=f,`retryResolve`in d&&a?.push([d,p]),`execute`in d&&n.actionExecutor({type:d.type,info:l,params:p,exec:d.execute.bind(null,n,p)}),m&&(s=Tt(s,t,n,m,i,a))}return s}function G(e,t,n,r,i,a){let o=a?[]:void 0,s=Tt(e,t,n,r,{internalQueue:i,deferredActorIds:a},o);return o?.forEach(([e,t])=>{e.retryResolve(n,s,t)}),s}function K(e,t,n,r){let i=e,a=[];function o(e,t,r){n.system._sendInspectionEvent({type:`@xstate.microstep`,actorRef:n.self,event:t,snapshot:e[0],_transitions:r}),a.push(e)}if(t.type===`xstate.stop`)return i=J(Et(i,t,n),{status:`stopped`}),o([i,[]],t,[]),{snapshot:i,microsteps:a};let s=t;if(s.type!==le){let t=s,c=we(t),l=Dt(t,i);if(c&&!l.length)return i=J(Et(i,t,n),{status:`error`,error:t.error}),o([i,[]],t,[]),{snapshot:i,microsteps:a};let u=_t(l,e,n,s,!1,r);i=u[0],o(u,t,l)}let c=!0,l=e.machine.options?.maxIterations??1/0,u=0;for(;i.status===`active`;){if(u++,u>l)throw Error(`Infinite loop detected: the machine has processed more than ${l} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`);let e=c?Ot(i,s):[],t=e.length?i:void 0;if(!e.length){if(!r.length)break;s=r.shift(),e=Dt(s,i)}let a=_t(e,i,n,s,!1,r);i=a[0],c=i!==t,o(a,s,e)}return i.status!==`active`&&Et(i,s,n),{snapshot:i,microsteps:a}}function Et(e,t,n){return G(e,t,n,Object.values(e.children).map(e=>A(e)),[],void 0)}function Dt(e,t){return t.machine.getTransitionData(t,e)}function Ot(e,t){let n=new Set,r=e._nodes.filter(Ke);for(let i of r)loop:for(let r of[i].concat(N(i,void 0)))if(r.always){for(let i of r.always)if(i.guard===void 0||j(i.guard,e.context,t,e)){n.add(i);break loop}}return ft(Array.from(n),new Set(e._nodes),e.historyValue)}function kt(e,t){return Ye(e,[...P(B(e,t))])}function At(e){return!!e&&typeof e==`object`&&`machine`in e&&`value`in e}var jt=function(e){return ge(e,this.value)},Mt=function(e){return this.tags.has(e)},Nt=function(e){let t=this.machine.getTransitionData(this,e);return!!t?.length&&t.some(e=>e.target!==void 0||e.actions.length)},Pt=function(){let{_nodes:e,tags:t,machine:n,getMeta:r,toJSON:i,can:a,hasTag:o,matches:s,...c}=this;return{...c,tags:Array.from(t)}},Ft=function(){return this._nodes.reduce((e,t)=>(t.meta!==void 0&&(e[t.id]=t.meta),e),{})};function q(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:Ye(t.root,e._nodes),tags:new Set(e._nodes.flatMap(e=>e.tags)),children:e.children,historyValue:e.historyValue||{},matches:jt,hasTag:Mt,can:Nt,getMeta:Ft,toJSON:Pt}}function J(e,t={}){return q({...e,...t},e.machine)}function It(e){if(typeof e!=`object`||!e)return{};let t={};for(let n in e){let r=e[n];Array.isArray(r)&&(t[n]=r.map(e=>({id:e.id})))}return t}function Lt(e,t){let{_nodes:n,tags:r,machine:i,children:a,context:o,can:s,hasTag:c,matches:l,getMeta:u,toJSON:d,...f}=e,p={};for(let e in a){let n=a[e];p[e]={snapshot:n.getPersistedSnapshot(t),src:n.src,systemId:n.systemId,syncSnapshot:n._syncSnapshot}}return{...f,context:Rt(o),children:p,historyValue:It(f.historyValue)}}function Rt(e){let t;for(let n in e){let r=e[n];if(r&&typeof r==`object`){if(`sessionId`in r&&`send`in r&&`ref`in r)t??=Array.isArray(e)?e.slice():{...e},t[n]={xstate$$type:1,id:r.id};else{let i=Rt(r);i!==r&&(t??=Array.isArray(e)?e.slice():{...e},t[n]=i)}}}return t??e}function zt(e,t,n,r,{event:i,id:a,delay:o},{internalQueue:s}){let c=t.machine.implementations.delays;if(typeof i==`string`)throw Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);let l=typeof i==`function`?i(n,r):i,u;if(typeof o==`string`){let e=c&&c[o];u=typeof e==`function`?e(n,r):e}else u=typeof o==`function`?o(n,r):o;return typeof u!=`number`&&s.push(l),[t,{event:l,id:a,delay:u},void 0]}function Bt(e,t){let{event:n,delay:r,id:i}=t;typeof r==`number`&&e.defer(()=>{let t=e.self;e.system.scheduler.schedule(t,t,n,r,i)})}function Vt(e,t){function n(e,t){}return n.type=`xstate.raise`,n.event=e,n.id=t?.id,n.delay=t?.delay,n.resolve=zt,n.execute=Bt,n}function Ht(e,{machine:t,context:n},r,i){let a=(a,o)=>{if(typeof a==`string`){let s=De(t,a);if(!s)throw Error(`Actor logic '${a}' not implemented in machine '${t.id}'`);let c=k(s,{id:o?.id,parent:e.self,syncSnapshot:o?.syncSnapshot,input:typeof o?.input==`function`?o.input({context:n,event:r,self:e.self}):o?.input,src:a,systemId:o?.systemId});return i[c.id]=c,c}return k(a,{id:o?.id,parent:e.self,syncSnapshot:o?.syncSnapshot,input:o?.input,src:a,systemId:o?.systemId})};return(t,n)=>{let r=a(t,n);return i[r.id]=r,e.defer(()=>{r._processingStatus!==O.Stopped&&r.start()}),r}}function Ut(e,t,n,r,{assignment:i}){if(!t.context)throw Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");let a={},o={context:t.context,event:n.event,spawn:Ht(e,t,n.event,a),self:e.self,system:e.system},s={};if(typeof i==`function`)s=i(o,r);else for(let e of Object.keys(i)){let t=i[e];s[e]=typeof t==`function`?t(o,r):t}return[J(t,{context:Object.assign({},t.context,s),children:Object.keys(a).length?{...t.children,...a}:t.children}),void 0,void 0]}function Wt(e){function t(e,t){}return t.type=`xstate.assign`,t.assignment=e,t.resolve=Ut,t}var Gt=new WeakMap;function Y(e,t,n){let r=Gt.get(e);return r?t in r||(r[t]=n()):(r={[t]:n()},Gt.set(e,r)),r[t]}var Kt={},X=e=>typeof e==`string`?{type:e}:typeof e==`function`?`resolve`in e?{type:e.type}:{type:e.name}:e,qt=class e{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(`.`),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?`compound`:this.config.history?`history`:`atomic`),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?be(this.config.states,(t,n)=>new e(t,{_parent:this,_key:n,_machine:this.machine})):Kt,this.type===`compound`&&!this.config.initial)throw Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?`shallow`:this.config.history||!1,this.entry=T(this.config.entry).slice(),this.exit=T(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type===`final`||!this.parent?this.config.output:void 0,this.tags=T(t.tags).slice()}_initialize(){this.transitions=$e(this),this.config.always&&(this.always=E(this.config.always).map(e=>I(this,``,e))),Object.keys(this.states).forEach(e=>{this.states[e]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(X),eventType:null,reenter:!1,meta:this.initial.meta,description:this.initial.description,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(X),eventType:null,meta:this.initial.meta,description:this.initial.description})}:void 0,history:this.history,states:be(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(X)})),entry:this.entry.map(X),exit:this.exit.map(X),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Y(this,`invoke`,()=>T(this.config.invoke).map((e,t)=>{let{src:n,systemId:r}=e,i=e.id??Ee(this.id,t),a=typeof n==`string`?n:`xstate.invoke.${Ee(this.id,t)}`;return{...e,src:a,id:i,systemId:r,toJSON(){let{onDone:t,onError:n,...r}=e;return{...r,type:`xstate.invoke`,src:a,id:i}}}}))}get on(){return Y(this,`on`,()=>[...this.transitions].flatMap(([e,t])=>t.map(t=>[e,t])).reduce((e,[t,n])=>(e[t]=e[t]||[],e[t].push(n),e),{}))}get after(){return Y(this,`delayedTransitions`,()=>Qe(this))}get initial(){return Y(this,`initial`,()=>tt(this,this.config.initial))}next(e,t){let n=t.type,r=[],i,a=Y(this,`candidates-${n}`,()=>Ze(this,n));for(let o of a){let{guard:a}=o,s=e.context,c=!1;try{c=!a||j(a,s,t,e)}catch(e){let t=typeof a==`string`?a:typeof a==`object`?a.type:void 0;throw Error(`Unable to evaluate guard ${t?`'${t}' `:``}in transition for event '${n}' in state node '${this.id}':\n${e.message}`)}if(c){r.push(...o.actions),i=o;break}}return i?[i]:void 0}get events(){return Y(this,`events`,()=>{let{states:e}=this,t=new Set(this.ownEvents);if(e)for(let n of Object.keys(e)){let r=e[n];if(r.states)for(let e of r.events)t.add(`${e}`)}return Array.from(t)})}get ownEvents(){let e=Object.keys(Object.fromEntries(this.transitions)),t=new Set(e.filter(e=>this.transitions.get(e).some(e=>!(!e.target&&!e.actions.length&&!e.reenter))));return Array.from(t)}},Jt=class e{constructor(e,t){this.config=e,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=e.id||`(machine)`,this.implementations={actors:t?.actors??{},actions:t?.actions??{},delays:t?.delays??{},guards:t?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new qt(e,{_key:this.id,_machine:this}),this.root._initialize(),et(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){let{actions:n,guards:r,actors:i,delays:a}=this.implementations;return new e(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...a,...t.delays}})}resolveState(e){let t=kt(this.root,e.value),n=P(B(this.root,t));return q({_nodes:[...n],context:e.context||{},children:{},status:Xe(n,this.root)?`done`:e.status||`active`,output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,t,n){return K(e,t,n,[]).snapshot}microstep(e,t,n){return K(e,t,n,[]).microsteps.map(([e])=>e)}getTransitionData(e,t){return lt(this.root,e.value,e,t)||[]}_getPreInitialState(e,t,n){let{context:r}=this.config,i=q({context:typeof r!=`function`&&r?r:{},_nodes:[this.root],children:{},status:`active`},this);return typeof r==`function`?G(i,t,e,[Wt(({spawn:e,event:t,self:n})=>r({spawn:e,input:t.input,self:n}))],n,void 0):i}getInitialSnapshot(e,t){let n=me(t),r=[],i=q({context:typeof this.config.context!=`function`&&this.config.context?this.config.context:{},_nodes:[this.root],children:{},status:`active`},this);try{i=this._getPreInitialState(e,n,r);let[t]=gt(this.root,i,e,n,r),{snapshot:a}=K(t,n,e,r);return a}catch(e){return J(i,{status:`error`,error:e})}}start(e){Object.values(e.children).forEach(e=>{e.getSnapshot().status===`active`&&e.start()})}getStateNodeById(e){let t=_e(e),n=t.slice(1),r=F(t[0])?t[0].slice(1):t[0],i=this.idMap.get(r);if(!i)throw Error(`Child state node '#${r}' does not exist on machine '${this.id}'`);return z(i,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,t){return Lt(e,t)}restoreSnapshot(e,t){let n={},r=e.children;Object.keys(r).forEach(e=>{let i=r[e],a=i.snapshot,o=i.src,s=typeof o==`string`?De(this,o):o;if(!s)return;let c=k(s,{id:e,parent:t.self,syncSnapshot:i.syncSnapshot,snapshot:a,src:o,systemId:i.systemId});n[e]=c});function i(e,t){if(t instanceof qt)return t;try{return e.machine.getStateNodeById(t.id)}catch{}}function a(e,t){if(!t||typeof t!=`object`)return{};let n={};for(let r in t){let a=t[r];for(let t of a){let a=i(e,t);a&&(n[r]??=[],n[r].push(a))}}return n}let o=a(this.root,e.historyValue),s=q({...e,children:n,_nodes:Array.from(P(B(this.root,e.value))),historyValue:o},this),c=new Set;function l(e,t){if(!c.has(e)){c.add(e);for(let n in e){let r=e[n];if(r&&typeof r==`object`){if(`xstate$$type`in r&&r.xstate$$type===1){e[n]=t[r.id];continue}l(r,t)}}}}return l(s.context,n),s}};function Yt(e,t,n,r,{event:i}){return[t,{event:typeof i==`function`?i(n,r):i},void 0]}function Xt(e,{event:t}){e.defer(()=>e.emit(t))}function Zt(e){function t(e,t){}return t.type=`xstate.emit`,t.event=e,t.resolve=Yt,t.execute=Xt,t}var Qt=function(e){return e.Parent=`#_parent`,e.Internal=`#_internal`,e}({});function $t(e,t,n,r,{to:i,event:a,id:o,delay:s},c){let l=t.machine.implementations.delays;if(typeof a==`string`)throw Error(`Only event objects may be used with sendTo; use sendTo({ type: "${a}" }) instead`);let u=typeof a==`function`?a(n,r):a,d;if(typeof s==`string`){let e=l&&l[s];d=typeof e==`function`?e(n,r):e}else d=typeof s==`function`?s(n,r):s;let f=typeof i==`function`?i(n,r):i,p;if(typeof f==`string`){if(p=f===Qt.Parent?e.self._parent:f===Qt.Internal?e.self:f.startsWith(`#_`)?t.children[f.slice(2)]:c.deferredActorIds?.includes(f)?f:t.children[f],!p)throw Error(`Unable to send event to actor '${f}' from machine '${t.machine.id}'.`)}else p=f||e.self;return[t,{to:p,targetId:typeof f==`string`?f:void 0,event:u,id:o,delay:d},void 0]}function en(e,t,n){typeof n.to==`string`&&(n.to=t.children[n.to])}function tn(e,t){e.defer(()=>{let{to:n,event:r,delay:i,id:a}=t;typeof i==`number`?e.system.scheduler.schedule(e.self,n,r,i,a):e.system._relay(e.self,n,r.type===`xstate.error`?pe(e.self.id,r.data):r)})}function nn(e,t,n){function r(e,t){}return r.type=`xstate.sendTo`,r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=$t,r.retryResolve=en,r.execute=tn,r}function rn(e,t){return nn(Qt.Parent,e,t)}function an(e,t,n,r,{collect:i}){let a=[],o=function(e){a.push(e)};return o.assign=(...e)=>{a.push(Wt(...e))},o.cancel=(...e)=>{a.push(Le(...e))},o.raise=(...e)=>{a.push(Vt(...e))},o.sendTo=(...e)=>{a.push(nn(...e))},o.sendParent=(...e)=>{a.push(rn(...e))},o.spawnChild=(...e)=>{a.push(Be(...e))},o.stopChild=(...e)=>{a.push(A(...e))},o.emit=(...e)=>{a.push(Zt(...e))},i({context:n.context,event:n.event,enqueue:o,check:e=>j(e,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,a]}function on(e){function t(e,t){}return t.type=`xstate.enqueueActions`,t.collect=e,t.resolve=an,t}function sn(e,t,n,r,{value:i,label:a}){return[t,{value:typeof i==`function`?i(n,r):i,label:a},void 0]}function cn({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function ln(e=({context:e,event:t})=>({context:e,event:t}),t){function n(e,t){}return n.type=`xstate.log`,n.value=e,n.label=t,n.resolve=sn,n.execute=cn,n}function un(e,t){return new Jt(e,t)}function dn({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:Wt,sendTo:nn,raise:Vt,log:ln,cancel:Le,stopChild:A,enqueueActions:on,emit:Zt,spawnChild:Be,createStateConfig:e=>e,createAction:e=>e,createMachine:a=>un({...a,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:a=>dn({schemas:e,actors:t,actions:{...n,...a.actions},guards:{...r,...a.guards},delays:{...i,...a.delays}})}}var fn=(e,t,n)=>Math.max(t,Math.min(n,e)),pn=class{dents=[];revision=0;enabled=!1;maxDepthM=0;maskCache=new WeakMap;spriteCache=null;captureState(){return a({dents:this.dents,revision:this.revision,enabled:this.enabled,maxDepthM:this.maxDepthM})}restoreState(e){let t=a(e);this.dents=t.dents,this.revision=t.revision,this.enabled=t.enabled,this.maxDepthM=t.maxDepthM,this.maskCache=new WeakMap,this.spriteCache=null}get hasDamage(){return this.enabled&&this.dents.length>0}get geometryRevision(){return this.revision}setEnabled(e){this.enabled!==e&&(this.enabled=e,e||this.reset())}reset(){this.dents=[],this.maxDepthM=0,this.revision++,this.spriteCache=null}hit(e,t,n,r,i){if(!this.enabled||r<=2.5||!Number.isFinite(r))return!1;let a=Math.max(1,i),s=f(e,n.center),c=m(l(s,n.forward)/a,l(s,n.side)/a),d=m(l(t,n.forward),l(t,n.side)),p=o(d);if(p<.001)return!1;let h=fn((r-2.5)/17.5,0,1)**1.5;return this.maxDepthM=Math.min(.25,8/a),this.dents.push({center:c,inward:u(d,1/p),depthM:this.maxDepthM*h,radiusAlongM:.65+h*.5,radiusAcrossM:.55+h*.55}),this.dents.length>12&&this.dents.shift(),this.revision++,this.spriteCache=null,!0}point(e){if(!this.hasDamage)return e;let t=m();for(let n of this.dents){let r=(e.x-n.center.x)/n.radiusAlongM,i=(e.y-n.center.y)/n.radiusAcrossM,a=Math.hypot(r,i);if(a>=1)continue;let o=(1-a*a)**2;t=p(t,u(n.inward,n.depthM*o))}let n=o(t);return n>this.maxDepthM&&(t=u(t,this.maxDepthM/n)),p(e,t)}maskFor(e){if(!this.hasDamage)return e;let t=this.maskCache.get(e);if(t?.revision===this.revision)return t.value;let{columns:n,rows:r,solid:i}=e.alpha,a=new Uint8Array(i.length),o=e.lengthM/n,s=e.widthM/r;for(let t=0;t<r;t++)for(let c=0;c<n;c++){let l=m((c+.5)*o-e.lengthM/2,(t+.5)*s-e.widthM/2),u=l;for(let e=0;e<5;e++)u=p(u,f(l,this.point(u)));let d=Math.floor((u.x/e.lengthM+.5)*n),h=Math.floor((u.y/e.widthM+.5)*r);d>=0&&d<n&&h>=0&&h<r&&(a[t*n+c]=i[h*n+d])}let c={...e,alpha:{columns:n,rows:r,solid:a}};return this.maskCache.set(e,{revision:this.revision,value:c}),c}spriteFor(e,t){if(!this.hasDamage)return null;let n=`${t.source.x}:${t.source.y}:${t.source.width}:${t.source.height}:${t.lengthM}:${t.widthM}`;if(this.spriteCache?.image===e&&this.spriteCache.key===n&&this.spriteCache.revision===this.revision)return this.spriteCache.canvas;let r=document.createElement(`canvas`);r.width=Math.max(1,Math.round(t.source.width)),r.height=Math.max(1,Math.round(t.source.height));let i=r.getContext(`2d`);if(!i)return null;let a=e=>{let n=m((e.x/r.width-.5)*t.lengthM,(e.y/r.height-.5)*t.widthM),i=this.point(n);return m((i.x/t.lengthM+.5)*r.width,(i.y/t.widthM+.5)*r.height)};for(let n=0;n<10;n++)for(let o=0;o<20;o++){let s=o*r.width/20,c=(o+1)*r.width/20,l=n*r.height/10,u=(n+1)*r.height/10,d=m(s,l),f=m(c,l),p=m(s,u),h=m(c,u);this.drawTriangle(i,e,t,[d,f,p],[a(d),a(f),a(p)]),this.drawTriangle(i,e,t,[h,p,f],[a(h),a(p),a(f)])}return this.spriteCache={image:e,key:n,revision:this.revision,canvas:r},r}drawTriangle(e,t,n,r,i){let[a,o,s]=r,[c,l,u]=i,d=o.x-a.x,f=o.y-a.y,p=s.x-a.x,m=s.y-a.y,h=d*m-p*f;if(Math.abs(h)<1e-4)return;let g=l.x-c.x,_=l.y-c.y,v=u.x-c.x,y=u.y-c.y,b=(g*m-v*f)/h,x=(_*m-y*f)/h,ee=(v*d-g*p)/h,S=(y*d-_*p)/h,te=c.x-b*a.x-ee*a.y,ne=c.y-x*a.x-S*a.y;e.save(),e.beginPath(),e.moveTo(c.x,c.y),e.lineTo(l.x,l.y),e.lineTo(u.x,u.y),e.closePath(),e.clip(),e.transform(b,x,ee,S,te,ne),e.drawImage(t,n.source.x,n.source.y,n.source.width,n.source.height,0,0,e.canvas.width,e.canvas.height),e.restore()}},mn=class{random;pulses=[];constructor(e=Math.random){this.random=e}get active(){return this.pulses}trigger({color:e,angle:n,velocity:r,origin:i}){if(!Number.isFinite(n)||!Number.isFinite(r))throw RangeError(`Pickup angle and velocity must be finite`);if(i&&(!Number.isFinite(i.x)||!Number.isFinite(i.y)||Math.abs(i.x)>.5||Math.abs(i.y)>.5))throw RangeError(`Pickup origin must lie within normalized body coordinates [-0.5, 0.5]`);let a=t(e),o=Math.min(1,Math.abs(r)/32);this.pulses.push({color:[a[0]/255,a[1]/255,a[2]/255],angle:Math.atan2(Math.sin(n),Math.cos(n)),strength:o,velocity:Math.abs(r),origin:i?{...i}:null,variation:this.random(),age:0,duration:.38-o*.1}),this.pulses.length>3&&this.pulses.shift()}step(e){if(!(!this.pulses.length||!Number.isFinite(e)||e<=0)){for(let t of this.pulses)t.age+=e;this.pulses=this.pulses.filter(e=>e.age<e.duration)}}reset(){this.pulses=[]}captureState(){return structuredClone(this.pulses)}restoreState(e){this.pulses=structuredClone(e)}},hn=new Map,Z=null;function gn(e){let t=e.match(/^#([\da-f]{3}|[\da-f]{6})$/i)?.[1];if(t){let e=t.length===3?[...t].map(e=>e+e).join(``):t;return[0,2,4].map(t=>parseInt(e.slice(t,t+2),16))}let n=e.match(/^rgba?\(\s*(\d{1,3})[,\s]+(\d{1,3})[,\s]+(\d{1,3})/i);return n?[d(+n[1],0,255),d(+n[2],0,255),d(+n[3],0,255)]:null}function _n(e){let t=gn(e);if(t)return t;if(hn.has(e))return hn.get(e);let n=null;return typeof document<`u`&&(Z??=document.createElement(`canvas`).getContext(`2d`),Z&&(Z.fillStyle=`#010203`,Z.fillStyle=e,Z.fillStyle!==`#010203`&&(n=gn(Z.fillStyle)))),hn.set(e,n),n}var vn=[[0,0],[60,120],[120,180],[240,240],[300,300],[360,360]];function yn(e,t=!1){let n=(e%360+360)%360;for(let e=1;e<vn.length;e++){let[r,i]=vn[e-1],[a,o]=vn[e],s=t?i:r,c=t?o:a;if(n<=c){let e=(n-s)/(c-s);return(t?r+(a-r)*e:i+(o-i)*e)%360}}return 0}function bn([e,t,n]){let r=e/255,i=t/255,a=n/255,o=Math.max(r,i,a),s=Math.min(r,i,a),c=o-s,l=(o+s)/2;if(c===0)return{hue:0,saturation:0,light:l};let u=c/(1-Math.abs(2*l-1));return{hue:((o===r?(i-a)/c%6:o===i?(a-r)/c+2:(r-i)/c+4)*60+360)%360,saturation:u,light:l}}function xn(e,t,n){let r=(1-Math.abs(2*n-1))*t,i=r*(1-Math.abs(e/60%2-1)),a=Math.floor(e/60)%6,o=[[r,i,0],[i,r,0],[0,r,i],[0,i,r],[i,0,r],[r,0,i]][a],s=n-r/2;return`rgb(${o.map(e=>Math.round((e+s)*255)).join(` `)})`}function Sn(e){let t=e.filter(e=>e.strength>0&&_n(e.color));if(!t.length)return e.at(-1)?.color??`rgb(0 0 0)`;if(t.length===1)return`rgb(${_n(t[0].color).join(` `)})`;let n=0,r=0,i=0,a=0,o=0;for(let e of t){let t=bn(_n(e.color)),s=yn(t.hue)*Math.PI/180,c=e.strength*t.saturation;n+=Math.cos(s)*c,r+=Math.sin(s)*c,i+=t.light*e.strength,a+=c,o+=e.strength}return xn(yn((Math.atan2(r,n)*180/Math.PI+360)%360,!0),Math.min(1,a/o),i/o)}var Cn=class{coatings=new Map;previous=new Map;travelM=new Map;previousLayer=new Map;wetPaths=new Map;exits=new Map;sprayRemainder=new Map;marks=[];markCount=0;captureState(){return a({coatings:this.coatings,previous:this.previous,travelM:this.travelM,previousLayer:this.previousLayer,wetPaths:this.wetPaths,exits:this.exits,sprayRemainder:this.sprayRemainder,marks:this.marks,markCount:this.markCount})}restoreState(e){let t=a(e);this.coatings=t.coatings,this.previous=t.previous,this.travelM=t.travelM,this.previousLayer=t.previousLayer,this.wetPaths=t.wetPaths,this.exits=t.exits,this.sprayRemainder=t.sprayRemainder,this.marks.length=0;for(let e of t.marks)this.marks.push(e);this.markCount=t.markCount}get totalMarks(){return this.markCount}get managedBytes(){return this.marks.length*136+this.travelM.size*16+[...this.coatings.values()].reduce((e,t)=>e+t.size*72,0)+this.previous.size*24+this.previousLayer.size*8+[...this.wetPaths.values()].reduce((e,t)=>e+t.marks.length*160,0)+this.exits.size*24+this.sprayRemainder.size*16}reset(){this.travelM.clear(),this.coatings.clear(),this.previous.clear(),this.previousLayer.clear(),this.wetPaths.clear(),this.exits.clear(),this.sprayRemainder.clear(),this.marks.length=0,this.markCount=0}step(e){e.forEach((e,t)=>this.travelM.set(t,(this.travelM.get(t)??0)+Math.max(0,e)));for(let[t,n]of this.coatings){let r=Math.max(0,e[t]??0);for(let[e,t]of n)t.remaining=Math.max(0,t.remaining-r),t.remaining===0&&n.delete(e);n.size===0&&(this.coatings.delete(t),this.previous.delete(t),this.previousLayer.delete(t),this.wetPaths.delete(t),this.exits.delete(t))}}touch(e,t){if(!t||t.opacity<=0||t.distanceM<=0)return;let n=this.coatings.get(e);n||(n=new Map,this.coatings.set(e,n));let r=t.id??t.color,i=n.get(r);if(n.set(r,{...t,opacity:Math.max(i?.opacity??0,d(t.opacity,0,1)),remaining:t.distanceM}),n.size>16){let e=[...n.entries()].filter(([e])=>e!==r).sort((e,t)=>e[1].opacity*e[1].remaining/e[1].distanceM-t[1].opacity*t[1].remaining/t[1].distanceM)[0];e&&n.delete(e[0])}}wash(e,t=[]){let n=this.coatings.get(e);if(n&&t.length){let e=new Set(t.map(e=>e.id??e.color));for(let t of n.keys())e.has(t)||n.delete(t);if(n.size)return}this.coatings.delete(e),this.previous.delete(e),this.previousLayer.delete(e),this.sprayRemainder.delete(e),this.wetPaths.delete(e),this.exits.delete(e)}splatter(t,n,r,i,a,o,s){let c=this.coating(t);if(!c||a<=0||s<=0)return;let l=e.paint.thickness,u=(this.sprayRemainder.get(t)??0)+a*(9+(1-l)*7)*(c.material?.spray??.5),d=Math.min(24,Math.floor(u));this.sprayRemainder.set(t,u-Math.floor(u));for(let e of ee(n,r,i,d,o,l)){let t=1+e.angularity*1.7,n={x:e.x,y:e.y};this.marks.push({from:n,point:n,angle:Math.atan2(r.y,r.x),widthM:e.radius*2*t/(s*.76),color:c.color,opacity:c.opacity*e.opacity,droplet:{aspect:(.5+Math.random()*.45)/t}}),this.markCount++}this.marks.length>3e4&&this.marks.splice(0,1e3)}trackWet(e,t,n,r,i,a=0,s=!1){let c=this.coating(e);if(!c){this.pauseTrack(e);return}let l=this.previous.get(e),u=this.wetPaths.get(e);if(!u||!l||o(f(t,l))>=1.5*i)u={marks:[],distanceM:0},this.wetPaths.set(e,u),s&&(this.marks.push({...c,from:{...t},point:{...t},angle:n,widthM:r,phaseM:this.travelM.get(e)??0,slip:d(a,0,1),overPuddle:!0}),this.markCount++);else{let p=u.marks.at(-1),m=p&&o(f(p.point,p.from))/i<.02,h=m?p.from:l;m&&(u.distanceM-=o(f(p.point,p.from))/i);let g=o(f(t,h))/i,_={...c,from:{...h},point:{...t},angle:n,widthM:r,phaseM:(this.travelM.get(e)??0)-g,slip:d(a,0,1)};m?u.marks[u.marks.length-1]=_:u.marks.push(_),u.distanceM+=g,s&&g>=.02&&(this.marks.push({..._,overPuddle:!0}),this.markCount++,this.marks.length>3e4&&this.marks.splice(0,1e3));let v=Math.max(.5,r*6);for(;u.marks.length>1&&(u.distanceM>v||u.marks.length>128);){let e=u.marks.shift();u.distanceM-=o(f(e.point,e.from))/i}}this.exits.delete(e),this.previous.set(e,{...t}),this.previousLayer.set(e,!1)}pauseTrack(e){this.wetPaths.delete(e),this.exits.delete(e),this.previous.delete(e),this.previousLayer.delete(e)}track(e,t,n,r,i,a=!1,s=0){let c=this.coating(e);if(!c)return;let l=this.previous.get(e),u=l?o(f(t,l)):0,p=this.wetPaths.has(e)||this.exits.has(e)?.01:.05;if(l&&u<p*i)return;let m=l&&u<1.5*i,h=this.wetPaths.get(e);if(h&&m){let t=Math.max(.35,r*(2+4*(c.material?.film??.6))),n=-h.distanceM;for(let e of h.marks){let r=n+o(f(e.point,e.from))/i;this.marks.push({...e,overPuddle:!1,exit:{fromM:n,toM:r,lengthM:t,leadInM:h.distanceM}}),this.markCount++,n=r}this.exits.set(e,{distanceM:0,lengthM:t})}else m||this.exits.delete(e);this.wetPaths.delete(e);let g=this.exits.get(e),_=g&&g.distanceM<g.lengthM?{fromM:g.distanceM,toM:g.distanceM+u/i,lengthM:g.lengthM}:void 0;g&&(g.distanceM+=u/i,g.distanceM>=g.lengthM&&this.exits.delete(e)),this.marks.push({from:m?{...l}:{...t},point:{...t},angle:n,widthM:r,phaseM:(this.travelM.get(e)??0)-(m?o(f(t,l))/i:0),wetness:c.wetness,material:c.material,slip:d(s,0,1),color:c.color,opacity:c.opacity,overPuddle:a,exit:_}),this.markCount++,this.previous.set(e,{...t}),this.previousLayer.set(e,a),this.marks.length>3e4&&this.marks.splice(0,1e3)}coating(e){let t=this.coatings.get(e);if(!t?.size)return null;let n=[...t.values()].map(e=>({color:e.color,strength:e.opacity*d(e.remaining/e.distanceM,0,1)})),r=[...t.values()].sort((e,t)=>t.opacity*t.remaining/t.distanceM-e.opacity*e.remaining/e.distanceM)[0],i=d(r.remaining/r.distanceM,0,1);return{material:r.material,wetness:i,color:Sn(n),opacity:Math.max(...n.map(e=>e.strength))*i**+Math.max(0,(r.material?.drain??1)-1),remaining:Math.max(...[...t.values()].map(e=>e.remaining)),distanceM:Math.max(...[...t.values()].map(e=>e.distanceM))}}},Q={opening:.32,raising:.52,igniting:.48,closing:.36},wn=class{previewOpen=!1;inspecting=!1;phase=`idle`;elapsed=0;held=!1;presetId=null;flights=[];launchClock=0;queuedShots=0;launches=0;ignitionDuration=Q.igniting;captureState(){return a({previewOpen:this.previewOpen,inspecting:this.inspecting,phase:this.phase,elapsed:this.elapsed,held:this.held,presetId:this.presetId,flights:this.flights,launchClock:this.launchClock,queuedShots:this.queuedShots,launches:this.launches,ignitionDuration:this.ignitionDuration})}restoreState(e){let t=a(e);this.previewOpen=t.previewOpen,this.inspecting=t.inspecting,this.phase=t.phase,this.elapsed=t.elapsed,this.held=t.held,this.presetId=t.presetId,this.flights=t.flights,this.launchClock=t.launchClock,this.queuedShots=t.queuedShots,this.launches=t.launches,this.ignitionDuration=t.ignitionDuration}get state(){return this.phase}get projectile(){let e=this.flights[0];return e?{...e,position:{...e.position}}:null}get projectileCount(){return this.flights.length}get managedBytes(){return this.flights.length*64}get launchCount(){return this.launches}reset(){this.previewOpen=!1,this.inspecting=!1,this.phase=`idle`,this.elapsed=0,this.held=!1,this.flights=[],this.launchClock=0,this.queuedShots=0,this.launches=0,this.ignitionDuration=Q.igniting,this.presetId=null}disarm(){this.held=!1,this.queuedShots=0,(this.phase===`opening`||this.phase===`raising`||this.phase===`igniting`)&&this.transition(`closing`)}transition(e){this.phase=e,this.elapsed=0}step(e,t,n,r,i,a,o,s){if(t.mode!==`car`){this.reset();return}if(this.presetId&&this.presetId!==t.car.preset.id&&this.reset(),this.previewOpen){this.inspecting=!0,this.presetId=t.car.preset.id,(this.phase===`idle`||this.phase===`closing`)&&this.transition(`opening`),this.elapsed+=e,this.phase===`opening`&&this.elapsed>=Q.opening&&this.transition(`raising`),this.phase===`raising`&&(this.elapsed=Math.min(this.elapsed,Q.raising));return}this.inspecting&&(this.inspecting=!1,this.transition(`closing`));let f=!!t.lastInput.rocket;f&&!this.held&&(this.queuedShots++,(this.phase===`idle`||this.phase===`closing`)&&(this.presetId=t.car.preset.id,this.transition(`opening`))),this.held=f;let h=g(t.car.preset);if(this.phase===`idle`&&!this.flights.length)return;this.elapsed+=e,this.launchClock+=e;let _=t.car.preset.roofRocket,v=Math.max(1.05,_.sizeM*1.12);if(this.phase===`opening`&&this.elapsed>=Q.opening)this.transition(`raising`);else if(this.phase===`raising`&&this.elapsed>=Q.raising)this.ignitionDuration=Q.igniting,this.transition(`igniting`),s?.(t.body.world(m(_.xM,_.yM)));else if(this.phase===`igniting`&&this.elapsed>=this.ignitionDuration){let e=c(m(1,0),t.body.angle),n=t.body.world(m(_.xM,_.yM));this.flights.push({position:n,angle:t.body.angle,speedMps:h.launchSpeedMps+Math.max(0,l(t.body.velocity,e)),distanceM:0,age:0}),this.launches++,a?.(n),this.queuedShots=Math.max(0,this.queuedShots-1),this.launchClock=0,this.transition(`flying`)}else this.phase===`closing`&&this.elapsed>=Q.closing&&this.transition(`idle`);if(this.phase===`igniting`){let r=d(this.elapsed/Math.min(.27,this.ignitionDuration*.65),0,.9),a=c(m(-1,0),t.body.angle),o=t.body.world(m(_.xM-v*.52,_.yM));n({point:o,flow:u(a,3.5),amount:e*14*r,radiusM:.2}),i?.({from:o,to:o,flow:u(a,12),widthM:.16,intensity:r*.75})}this.phase===`flying`&&(!f&&this.queuedShots===0?this.transition(`closing`):this.launchClock>=Math.max(0,1/h.roundsPerSecond-Math.min(Q.igniting,.7/h.roundsPerSecond))&&(this.ignitionDuration=Math.min(Q.igniting,.7/h.roundsPerSecond),this.transition(`igniting`),s?.(t.body.world(m(_.xM,_.yM)))));for(let t=this.flights.length-1;t>=0;t--){let a=this.flights[t],s=c(m(1,0),a.angle);a.speedMps=Math.min(h.maxSpeedMps,a.speedMps+h.accelerationMps2*e);let l=a.speedMps*e,d=a.position,f=p(d,u(s,l)),g=r?.(d,f,_.sizeM*.18);a.position=g??f,a.distanceM+=l,a.age+=e;let y=p(a.position,u(s,-v*.53)),b=p(d,u(s,-v*.53));if(n({point:y,flow:u(s,-5),amount:e*h.smokePerSecond,radiusM:.2}),i?.({from:b,to:y,flow:u(s,-18),widthM:.13,intensity:.9}),g){o?.(g);for(let e=0;e<7;e++){let t=c(m(1,0),e*Math.PI*2/7);n({point:g,flow:u(t,5.5),amount:.18,radiusM:.22})}this.flights.splice(t,1)}else(a.age>=h.lifetimeSeconds||a.distanceM>100)&&this.flights.splice(t,1)}this.phase===`closing`&&this.elapsed>=Q.closing&&this.transition(`idle`)}get open(){return this.phase===`idle`?0:this.phase===`opening`?d(this.elapsed/Q.opening,0,1):this.phase===`closing`?1-d(this.elapsed/Q.closing,0,1):1}drawMount(e,t,n,r,i,a=1,o){let s=this.open;if(s<=0)return;te();let c=r.roofRocket,l=c.sizeM*i,u=s*s*(3-2*s);e.save(),e.translate(t.x,t.y),e.rotate(-n),e.translate(c.xM*i,-c.yM*i),e.globalAlpha*=a;let f=e.createLinearGradient(0,-l/2,0,l/2);f.addColorStop(0,`#11171b`),f.addColorStop(.45,`#030609`),f.addColorStop(1,`#222a2e`),e.fillStyle=f,e.beginPath(),e.roundRect(-l/2,-l/2,l,l,l*.06),e.fill(),e.strokeStyle=`#525c62`,e.lineWidth=Math.max(.45,i*.018),e.stroke();for(let t of[-1,1]){e.fillStyle=`#687279`,e.fillRect(-l*.42,t*l*.2,l*.84,l*.035),e.fillStyle=`#161d22`,e.fillRect(-l*.34,-l*.28,l*.065,l*.56);let n=l*.5*(1-u*.78),r=t*(l*.25+u*l*.22);if(e.save(),e.translate(0,r),e.shadowColor=`rgba(0,0,0,.55)`,e.shadowBlur=l*.08,e.shadowOffsetY=l*.035,e.fillStyle=c.panelColor,e.beginPath(),e.roundRect(-l/2,-n/2,l,n,l*.035),e.fill(),e.shadowBlur=0,e.shadowOffsetY=0,o){e.save(),e.clip();let r=o.source.x+(c.xM-c.sizeM/2+o.lengthM/2)/o.lengthM*o.source.width,i=o.source.y+(-c.yM+(t<0?-c.sizeM/2:0)+o.widthM/2)/o.widthM*o.source.height;e.drawImage(o.image,r,i,c.sizeM/o.lengthM*o.source.width,c.sizeM/2/o.widthM*o.source.height,-l/2,-n/2,l,n),e.restore()}e.strokeStyle=`rgba(8,13,17,.7)`,e.lineWidth=Math.max(.45,i*.018),e.stroke(),e.restore()}if(this.phase===`raising`||this.phase===`igniting`){let t=this.phase===`igniting`?1:d(this.elapsed/Q.raising,0,1);e.save(),e.globalAlpha*=t,e.scale(.35+t*.65,.35+t*.65),this.drawBody(e,Math.max(1.05,c.sizeM*1.12)*i,1),e.restore()}e.restore()}drawFlight(e,t,n,r,i=1){for(let a of this.flights){let o=t(a.position);e.save(),e.translate(o.x,o.y),e.rotate(-a.angle),e.globalAlpha=i,this.drawBody(e,Math.max(1.05,n.roofRocket.sizeM*1.12)*r,1),e.restore()}}drawBody(e,t,n){if(e.save(),e.globalAlpha*=n,e.shadowColor=`rgba(0,0,0,.5)`,e.shadowBlur=t*.055,e.shadowOffsetY=t*.025,!S(e,`rocket`,-t*.53,0,t*1.06)){let n=e.createLinearGradient(0,-t*.045,0,t*.045);n.addColorStop(0,`#3b454d`),n.addColorStop(.35,`#d8dddc`),n.addColorStop(1,`#3e484f`),e.fillStyle=n,e.beginPath(),e.moveTo(-t*.53,-t*.045),e.lineTo(t*.3,-t*.045),e.lineTo(t*.53,0),e.lineTo(t*.3,t*.045),e.lineTo(-t*.53,t*.045),e.closePath(),e.fill(),e.fillStyle=`#30383e`;for(let n of[-1,1])e.beginPath(),e.moveTo(-t*.48,n*t*.12),e.lineTo(-t*.22,n*t*.04),e.lineTo(-t*.44,n*t*.04),e.closePath(),e.fill()}e.restore()}},Tn=.22,En=.24,Dn=class{phase=`closed`;phaseTime=0;shotClock=0;flashAge=1/0;presetId=null;bullets=[];captureState(){return a({phase:this.phase,phaseTime:this.phaseTime,shotClock:this.shotClock,flashAge:this.flashAge,presetId:this.presetId,bullets:this.bullets})}restoreState(e){let t=a(e);this.phase=t.phase,this.phaseTime=t.phaseTime,this.shotClock=t.shotClock,this.flashAge=t.flashAge,this.presetId=t.presetId,this.bullets=t.bullets}get state(){return this.phase}get openAmount(){return this.open}get projectileCount(){return this.bullets.length}get managedBytes(){return this.bullets.length*56}reset(){this.phase=`closed`,this.phaseTime=0,this.shotClock=0,this.flashAge=1/0,this.presetId=null,this.bullets=[]}step(e,t,n,r,i){if(t.mode!==`car`){this.reset();return}this.presetId&&this.presetId!==t.car.preset.id&&this.reset();let a=h(t.car.preset),o=!!t.lastInput.machineGun;if(o&&(this.phase===`closed`||this.phase===`closing`)){this.presetId=t.car.preset.id;let e=this.open;this.phase=`opening`,this.phaseTime=e*Tn}else if(!o&&(this.phase===`opening`||this.phase===`active`)){let e=this.open;this.phase=`closing`,this.phaseTime=(1-e)*En}if(this.phaseTime+=e,this.flashAge+=e,this.phase===`opening`&&this.phaseTime>=Tn&&(this.phase=`active`,this.phaseTime=0,this.shotClock=1/a.roundsPerSecond),this.phase===`active`){if(o){let n=1/Math.max(1,a.roundsPerSecond);this.shotClock+=e;for(let e=0;this.shotClock>=n&&e<4;e++)this.shotClock-=n,this.fire(t),r?.()}}else this.phase===`closing`&&this.phaseTime>=En&&(this.phase=`closed`,this.phaseTime=0);for(let t=this.bullets.length-1;t>=0;t--){let r=this.bullets[t],o=r.position,s=p(o,u(r.velocity,e)),c=n?.(o,s,.075);r.age+=e,c||r.age>=a.bulletLifetimeSeconds?(c&&i?.(c,r.velocity),this.bullets.splice(t,1)):r.position=s}}fire(e){let t=h(e.car.preset),n=c(m(1,0),e.body.angle);for(let r of[-1,1]){let i=e.body.world(b(e.car.preset,r)),a=p(u(n,t.bulletSpeedMps),e.body.velocityAt(i));this.bullets.push({position:i,velocity:a,age:0})}this.flashAge=0}get open(){return this.phase===`closed`?0:this.phase===`opening`?d(this.phaseTime/Tn,0,1):this.phase===`closing`?1-d(this.phaseTime/En,0,1):1}drawMount(e,t,n,r,i,a=1,o){x(e,t,n,r,i,this.open,`gun`,Math.max(0,1-this.flashAge/.075),a,o)}drawProjectiles(e,t,n,r=1){e.save(),e.lineCap=`round`;for(let i of this.bullets){let a=t(i.position),o=Math.hypot(i.velocity.x,i.velocity.y),s=t(p(i.position,u(i.velocity,-.75/Math.max(1,o)))),c=e.createLinearGradient(s.x,s.y,a.x,a.y);c.addColorStop(0,`rgba(224,153,63,0)`),c.addColorStop(.7,`rgba(224,153,63,.25)`),c.addColorStop(1,`rgba(255,225,157,.7)`),e.globalAlpha=r,e.strokeStyle=c,e.lineWidth=Math.max(.65,n*.025),e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(a.x,a.y),e.stroke();let l=t(p(i.position,u(i.velocity,-.09/Math.max(1,o))));e.strokeStyle=`#fff6d7`,e.lineWidth=Math.max(.55,n*.018),e.beginPath(),e.moveTo(l.x,l.y),e.lineTo(a.x,a.y),e.stroke()}e.restore()}},On=.22,kn=.24,$=1/45,An=class{phase=`closed`;phaseTime=0;emitting=!1;presetId=null;fireClock=0;jets=[];captureState(){return a({phase:this.phase,phaseTime:this.phaseTime,emitting:this.emitting,presetId:this.presetId,fireClock:this.fireClock,jets:this.jets})}restoreState(e){let t=a(e);this.phase=t.phase,this.phaseTime=t.phaseTime,this.emitting=t.emitting,this.presetId=t.presetId,this.fireClock=t.fireClock,this.jets=t.jets}get state(){return this.phase}get firing(){return this.emitting}get openAmount(){return this.open}get managedBytes(){return this.jets.length*64}reset(){this.phase=`closed`,this.phaseTime=0,this.emitting=!1,this.presetId=null,this.fireClock=0,this.jets=[]}step(e,t,n,r,i){if(t.mode!==`car`){(this.phase!==`closed`||this.jets.length)&&this.reset();return}this.presetId&&this.presetId!==t.car.preset.id&&this.reset();let a=!!t.lastInput.flamethrower,o=_(t.car.preset);if(a&&(this.phase===`closed`||this.phase===`closing`)){this.presetId=t.car.preset.id;let e=this.open;this.phase=`opening`,this.phaseTime=e*On}else if(!a&&(this.phase===`opening`||this.phase===`active`)){let e=this.open;this.phase=`closing`,this.phaseTime=(1-e)*kn}if(this.phaseTime+=e,this.phase===`opening`&&this.phaseTime>=On&&(this.phase=`active`,this.phaseTime=0,this.fireClock=$),this.emitting=this.phase===`active`&&a,this.phase===`closing`&&this.phaseTime>=kn&&(this.phase=`closed`,this.phaseTime=0),this.emitting){let r=c(m(1,0),t.body.angle),i=o.rangeM/.3;for(this.fireClock+=e;this.fireClock>=$;){this.fireClock-=$;for(let e of[-1,1]){let n=t.body.world(b(t.car.preset,e));this.jets.push({point:n,velocity:p(u(r,i),u(t.body.velocity,.25)),traveled:0,range:o.rangeM,speed:i,width:o.jetWidthM*o.flowRate})}}for(let i of[-1,1]){let a=t.body.world(b(t.car.preset,i));n({point:p(a,u(r,.06)),flow:u(r,5.5),amount:e*o.smokePerSecond*o.flowRate*.38,radiusM:.12})}}let s=[];for(let t of this.jets){let a=Math.min(t.range-t.traveled,t.speed*e),c=t.point,l=p(c,u(t.velocity,a/t.speed)),d=(t.traveled+a)/t.range,f=t.width*(.65+1.45*d),m=r?.(c,l,Math.max(.3,f*1.25),$*o.flowRate),h=m??l;t.point=h,t.traveled+=a,i?.(c,h,f,t.velocity,d),(d>.62||m)&&n({point:h,flow:u(t.velocity,.42),amount:e*o.smokePerSecond*o.flowRate*(m?.42:.18),radiusM:Math.max(.11,f*.48)}),m?i?.(h,h,f*1.35,t.velocity,d):t.traveled+1e-6<t.range&&s.push(t)}this.jets=s}get open(){return this.phase===`closed`?0:this.phase===`opening`?d(this.phaseTime/On,0,1):this.phase===`closing`?1-d(this.phaseTime/kn,0,1):1}drawMount(e,t,n,r,i,a=1,o){x(e,t,n,r,i,this.open,`flame`,this.phase===`active`?.8:0,a,o)}},jn=class{rocket=new wn;machineGuns=new Dn;flamethrower=new An;reset(){this.rocket.reset(),this.machineGuns.reset(),this.flamethrower.reset()}stopFiring(){this.rocket.disarm()}captureState(){return{rocket:this.rocket.captureState(),machineGuns:this.machineGuns.captureState(),flamethrower:this.flamethrower.captureState()}}restoreState(e){this.rocket.restoreState(e.rocket),this.machineGuns.restoreState(e.machineGuns),this.flamethrower.restoreState(e.flamethrower)}get managedBytes(){return this.rocket.managedBytes+this.machineGuns.managedBytes+this.flamethrower.managedBytes}},Mn=e=>({...e,slots:e.slots?[...e.slots]:void 0,slotPresses:e.slotPresses?[...e.slotPresses]:void 0}),Nn=dn({types:{events:{}}}).createMachine({id:`vehicleLifecycle`,initial:`drivable`,states:{drivable:{on:{DESTROYED:`destroyed`}},destroyed:{on:{RESPAWNED:`drivable`}}}}),Pn=class{id;sim;damage=new pn;weapons=new jn;tirePaint=new Cn;pickupEffect=new mn;lifecycle=k(Nn).start();controls={throttle:0,steer:0,action:!1};controlSource=`player`;label=``;appearance=`auto`;slotConfiguration=r;toolPolicy={};numberedSlots=y(r);slotHeld=new Set;slotPulses=new Set;slotPresses=new Set;blockedSlots=new Set;disposed=!1;previousSlotInput=new Set;activeEmitters=[];get slots(){return this.slotConfiguration}set slots(e){if(this.disposed)throw Error(`Vehicle is disposed.`);let t=i(e);this.clearSlotInput(),this.slotConfiguration=t,this.numberedSlots=y(t,this.toolPolicy)}liquidEmissions(e){return!this.sim.lastInput.eject||this.isGhost||this.lifecycleState!==`drivable`?[]:this.activeEmitters.map(({slot:t,liquid:n,pulse:r,rate:i,amount:a})=>({slot:t,liquid:n,amount:r?a:Math.max(0,e)*i})).filter(e=>e.amount>0)}useSlot(e){let t=n(e);return this.disposed||!this.numberedSlots[t-1]||this.lifecycleState!==`drivable`?!1:(this.slotPulses.add(t),!0)}startSlot(e){let t=n(e);return this.disposed||!this.numberedSlots[t-1]||this.lifecycleState!==`drivable`?!1:(this.slotHeld.has(t)||this.slotPresses.add(t),this.slotHeld.add(t),!0)}stopSlot(e){this.slotHeld.delete(n(e))}clearSlotInput(){this.slotHeld.clear(),this.slotPulses.clear(),this.slotPresses.clear(),this.blockedSlots.clear(),this.previousSlotInput.clear(),this.activeEmitters=[]}resolveSlots(e){let t=new Set((e.slots??[]).map(n)),r=new Set((e.slotPresses??[]).map(n));for(let e of this.blockedSlots)!t.has(e)&&!r.has(e)?this.blockedSlots.delete(e):(t.delete(e),r.delete(e));let i=new Set([...this.slotHeld,...t]),a=new Set([...this.slotPresses,...r]),o=Mn(e);this.activeEmitters=[];for(let{number:e,slot:t}of this.numberedSlots){let n=i.has(e)&&!this.previousSlotInput.has(e),r=this.slotPulses.has(e)||(t.activation===`tap`?n||a.has(e):a.has(e)&&!i.has(e));(r||t.activation!==`tap`&&i.has(e))&&(t.action===`eject`?(o.eject=!0,this.activeEmitters.push({slot:e,liquid:t.liquid,pulse:r,rate:t.rate??6,amount:t.amount??.65})):o[t.action]=!0)}if(e.eject&&!this.activeEmitters.length){for(let{number:e,slot:t}of this.numberedSlots)if(t.action===`eject`){this.activeEmitters.push({slot:e,liquid:t.liquid,pulse:!1,rate:t.rate??6,amount:t.amount??.65});break}}return this.previousSlotInput=i,o}constructor(e,t){this.id=e,this.sim=t}get lifecycleState(){return this.lifecycle.getSnapshot().value}get isGhost(){return this.sim.mode===`car`&&this.lifecycleState===`drivable`&&!!this.controls.ghost}setControls(e,t,r={}){if(r.toolsEnabled!==this.toolPolicy.toolsEnabled){let t=y(this.slotConfiguration,r);if(t.length!==this.numberedSlots.length||t.some(({source:e},t)=>e!==this.numberedSlots[t].source)){this.clearSlotInput();for(let t of[...e.slots??[],...e.slotPresses??[]])this.blockedSlots.add(n(t))}this.toolPolicy=r,this.numberedSlots=t}this.controls=v(this.resolveSlots(e),r.toolsEnabled),this.controlSource=t}step(e,t,n=!1){this.pickupEffect.step(e),n?this.sim.lastInput={throttle:0,steer:0,action:!1,boost:!1}:this.sim.tick(this.lifecycleState===`drivable`?this.controls:{throttle:0,steer:0,action:!1},e,t),this.slotPulses.clear(),this.slotPresses.clear()}synchronizeLifecycle(){let e=this.sim.car.explodedAt!==null;e&&this.lifecycleState===`drivable`?(this.lifecycle.send({type:`DESTROYED`}),this.weapons.stopFiring(),this.clearSlotInput(),this.sim.lastInput={throttle:0,steer:0,action:!1,boost:!1}):!e&&this.lifecycleState===`destroyed`&&this.lifecycle.send({type:`RESPAWNED`})}reset(){this.clearSlotInput(),this.sim.reset(),this.damage.reset(),this.weapons.reset(),this.tirePaint.reset(),this.pickupEffect.reset(),this.synchronizeLifecycle()}restoreHealth(){this.sim.car.resetBurnable(),this.synchronizeLifecycle()}setMode(e){this.clearSlotInput(),this.sim.setMode(e),this.damage.reset(),this.weapons.reset(),this.tirePaint.reset(),this.pickupEffect.reset(),this.synchronizeLifecycle()}setPreset(e){this.clearSlotInput(),this.sim.setPreset(e),this.damage.reset(),this.weapons.reset(),this.tirePaint.reset(),this.pickupEffect.reset(),this.synchronizeLifecycle()}advanceBurn(e){if(this.sim.mode!==`car`)return null;let{car:t}=this.sim;t.advanceBurn(e),this.synchronizeLifecycle();let n=t.stage;if(n===`intact`)return null;let r=!1,i=!1;this.lifecycleState===`destroyed`&&(t.blastQueued||(t.blastQueued=!0,r=!0),t.blastAge+=e,t.blastAge<.36&&t.blastAge-t.lastBlastEmission>=1/30&&(i=!0,t.lastBlastEmission=t.blastAge));let a={stage:n,health:t.health,maxHealth:t.maxHealth,key:t,burnOriginLocal:{...t.burnOriginLocal},blastAge:t.blastAge,explosionStarted:r,blastPulse:i};return this.lifecycleState===`destroyed`&&t.blastAge>=s.respawnSeconds&&(this.sim.resetAtCurrentPose(),this.damage.reset(),this.synchronizeLifecycle()),a}captureState(){return{id:this.id,label:this.label,appearance:this.appearance,slots:structuredClone(this.slots),slotHeld:[...this.slotHeld],slotPulses:[...this.slotPulses],slotPresses:[...this.slotPresses],blockedSlots:[...this.blockedSlots],previousSlotInput:[...this.previousSlotInput],activeEmitters:this.activeEmitters.map(e=>({...e})),simulation:this.sim.captureState(),damage:this.damage.captureState(),weapons:this.weapons.captureState(),tirePaint:this.tirePaint.captureState(),pickupEffect:this.pickupEffect.captureState(),controls:Mn(this.controls),controlSource:this.controlSource,lifecycle:this.lifecycle.getPersistedSnapshot()}}restoreState(e){if(e.id!==this.id)throw Error(`Checkpoint vehicle does not match`);this.label=e.label,this.appearance=e.appearance,this.slots=structuredClone(e.slots),this.slotHeld=new Set(e.slotHeld),this.slotPulses=new Set(e.slotPulses),this.slotPresses=new Set(e.slotPresses),this.blockedSlots=new Set(e.blockedSlots),this.previousSlotInput=new Set(e.previousSlotInput),this.activeEmitters=e.activeEmitters.map(e=>({...e})),this.sim.restoreState(e.simulation),this.damage.restoreState(e.damage),this.weapons.restoreState(e.weapons),this.tirePaint.restoreState(e.tirePaint),this.pickupEffect.restoreState(e.pickupEffect),this.controls=Mn(e.controls),this.controlSource=e.controlSource,this.lifecycle.stop(),this.lifecycle=k(Nn,{snapshot:e.lifecycle}).start()}dispose(){this.disposed=!0,this.pickupEffect.reset(),this.clearSlotInput(),this.lifecycle.stop()}};export{pn as n,Pn as t};