@joy-ride/game 0.27.0 → 0.27.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.
- package/embed-chunks/{CodeBlock-CpSBaaOX.js → CodeBlock-CJRe6lHv.js} +1 -1
- package/embed-chunks/{Documentation-8cbCUZ0p.js → Documentation-DULnk8tf.js} +1 -1
- package/embed-chunks/{EmbedPanel-DCPAjVqp.js → EmbedPanel-D6NV8mze.js} +1 -1
- package/embed-chunks/{JoyRideView-CgMxrhvT.js → JoyRideView-Ob58zdVp.js} +1 -1
- package/embed-chunks/{runtime~browser-session-core-CDPI_Sw8.js → runtime~browser-session-core-BAKqCyId.js} +1 -1
- package/embed-chunks/runtime~index~embed-OYVxs2-3.js +210 -0
- package/embed-chunks/{runtime~vehicle-popover~browser-session-core-0GDQdij8.js → runtime~vehicle-popover~browser-session-core-Duk0oqZL.js} +1 -1
- package/embed-chunks/{src-BJ7McU4o.js → src-Dz21SH_d.js} +2 -2
- package/embed-chunks/{vehicle-catalog~index~embed-DVqfWMzi.js → vehicle-catalog~index~embed-Dpqr1rYZ.js} +1 -1
- package/embed-chunks/{vehicle-popover-zFwrdc1h.js → vehicle-popover-uy2DwcVy.js} +1 -1
- package/embed.js +1 -1
- package/{index-epZszWQ8.d.ts → index-At4NsLPU.d.ts} +7 -7
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/npm-chunks/{Documentation-Cc_tsq8d.js → Documentation-B_Eb81Ol.js} +1 -1
- package/npm-chunks/{EmbedPanel-ByMHNOc2.js → EmbedPanel-Cu4-LaxN.js} +1 -1
- package/npm-chunks/{runtime~browser-session-core-CuS-sVVB.js → runtime~browser-session-core-AEIWcEJB.js} +1 -1
- package/npm-chunks/{runtime~react-DQ3peDbc.js → runtime~react-C9tzIsBm.js} +1 -1
- package/npm-chunks/runtime~react~vehicle-popover~browser-session-core-CdrNmP2l.js +210 -0
- package/npm-chunks/{runtime~vehicle-popover~browser-session-core-DCZajgun.js → runtime~vehicle-popover~browser-session-core-D0thHU3T.js} +1 -1
- package/npm-chunks/vehicle-catalog~react~vehicle-popover~browser-session-core-B042f61I.js +1 -0
- package/npm-chunks/{vehicle-popover-PaJpv-M-.js → vehicle-popover-DErhsXB9.js} +1 -1
- package/package.json +1 -1
- package/react.d.ts +1 -1
- package/react.js +2 -2
- package/embed-chunks/runtime~index~embed-BdtYsSkV.js +0 -210
- package/npm-chunks/runtime~react~vehicle-popover~browser-session-core-CLFQjhrw.js +0 -210
- package/npm-chunks/vehicle-catalog~react~vehicle-popover~browser-session-core-sqHgtPeO.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-XKyaHtl9.js";import{a as t,i as n,l as r,r as i,t as a}from"./runtime~react~browser-session-core-B9a1rLNB.js";import{c as o,i as s}from"./configuration~react~vehicle-popover~EmbedPanel~Documentation~JoyRideView~browser-session-co~fvauaeow-mgPW9A8j.js";import{a as c,i as l,n as u,r as d,t as f}from"./runtime~react~vehicle-popover~browser-session-core-CLFQjhrw.js";import{n as p,t as m}from"./configuration~react~vehicle-popover~JoyRideView~browser-session-core~renderer-CPZkP_Db.js";import{a as h,c as g,l as _,r as v}from"./definitions~react~vehicle-popover~Documentation~JoyRideView~browser-session-core~renderer-BG7sJuWo.js";import{n as y,r as b}from"./definitions~react~vehicle-popover~browser-session-core~renderer-RDNEXk_b.js";import{_ as x,a as S,b as C,c as w,d as T,f as E,g as D,h as O,l as k,m as A,o as j,p as M,r as N,s as P,t as F,v as I,x as L,y as ee}from"./runtime~react~vehicle-popover~browser-session-core~renderer-Dmgs7E8f.js";import{A as te,C as ne,D as R,E as re,O as z,T as ie,a as B,b as ae,d as oe,j as se,k as ce,l as le,n as ue,o as de,p as fe,r as pe,s as me,t as he,u as ge,w as _e}from"./runtime~vehicle-popover~browser-session-core~renderer-EswVyRVp.js";import{n as ve}from"./definitions~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-DcDccU8O.js";import{n as ye,t as be}from"./runtime~vehicle-popover~browser-session-core-DCZajgun.js";import{n as xe}from"./configuration~react~vehicle-popover~EmbedPanel~JoyRideView~browser-session-core~renderer-Bo9KSudc.js";import{n as Se}from"./configuration~react~vehicle-popover~EmbedPanel~JoyRideView~browser-session-core-rFMaxKZs.js";import{t as Ce}from"./runtime~react~JoyRideView~browser-session-core-BRSYGakW.js";import{c as we,l as Te,n as Ee,r as De,s as Oe}from"./definitions~react~browser-session-core-Bc5BhqaX.js";import{r as ke}from"./controls~react~vehicle-popover~JoyRideView~browser-session-core~renderer-Cnf30Q_A.js";import{a as Ae,i as V,n as je,o as Me}from"./controls~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-CoAcght5.js";import{n as Ne,r as Pe,t as Fe}from"./runtime~JoyRideView~browser-session-core-DkTKYWMV.js";var Ie=Object.freeze({speedFactor:.5,rampMs:300,zoomFactor:0,curve:`ease-in-out`}),Le={linear:e=>e,"ease-in":e=>e*e,"ease-out":e=>e*(2-e),"ease-in-out":e=>e*e*(3-2*e)},Re={linear:e=>e*e/2,"ease-in":e=>e*e*e/3,"ease-out":e=>e*e-e*e*e/3,"ease-in-out":e=>e*e*e-e*e*e*e/2},ze=class{settings={...Ie};enabled=!1;speed=1;zoom=1;fromSpeed=1;fromZoom=1;elapsed=0;constructor(e={}){this.configure(e)}get options(){return{...this.settings}}get active(){return this.enabled}get speedFactor(){return this.speed}get zoomFactor(){return this.zoom}configure(e){let t={...this.settings,...e};if(!Number.isFinite(t.speedFactor)||t.speedFactor<=0||t.speedFactor>1)throw RangeError(`Slow-mo speedFactor must be greater than zero and at most one.`);if(!Number.isFinite(t.rampMs)||t.rampMs<0)throw RangeError(`Slow-mo rampMs must be a nonnegative number.`);if(!Number.isFinite(t.zoomFactor)||t.zoomFactor<0||t.zoomFactor>4)throw RangeError(`Slow-mo zoomFactor must be between 0 and 4.`);if(!Object.hasOwn(Le,t.curve))throw TypeError(`Unknown slow-mo curve.`);this.settings=t,this.beginRamp()}setActive(e){this.enabled!==e&&(this.enabled=e,this.beginRamp())}start(){this.setActive(!0)}stop(){this.setActive(!1)}beginRamp(){this.fromSpeed=this.speed,this.fromZoom=this.zoom,this.elapsed=0,this.settings.rampMs||this.advance(0)}advance(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Slow-mo elapsed time must be a nonnegative number.`);let t=this.enabled?this.settings.speedFactor:1,n=this.enabled&&this.settings.zoomFactor||1,r=this.settings.rampMs/1e3;if(!r||this.elapsed>=r)return this.speed=t,this.zoom=n,e*t;let i=this.elapsed/r,a=Math.min(e,r-this.elapsed);this.elapsed+=a;let o=Math.min(1,this.elapsed/r),s=Le[this.settings.curve](o);this.speed=this.fromSpeed+(t-this.fromSpeed)*s,this.zoom=this.fromZoom+(n-this.fromZoom)*s;let c=Re[this.settings.curve](o)-Re[this.settings.curve](i);return a*this.fromSpeed+r*(t-this.fromSpeed)*c+(e-a)*t}reset(){this.enabled=!1,this.speed=this.zoom=this.fromSpeed=this.fromZoom=1,this.elapsed=0}captureState(){return{options:{...this.settings},active:this.enabled,speed:this.speed,zoom:this.zoom,fromSpeed:this.fromSpeed,fromZoom:this.fromZoom,elapsed:this.elapsed}}restoreState(e){this.settings={...e.options},this.enabled=e.active,this.speed=e.speed,this.zoom=e.zoom,this.fromSpeed=e.fromSpeed,this.fromZoom=e.fromZoom,this.elapsed=e.elapsed}},H={radiusPx:92,coreRadiusPx:25,damage:100,impulse:1,ignite:!0};function Be(e=1){let t=Number.isFinite(e)?Math.max(.1,Math.min(3,e)):1;return{radiusPx:Math.max(40,H.radiusPx*t),coreRadiusPx:H.coreRadiusPx*t,damage:H.damage*t,impulse:H.impulse*t,ignite:H.ignite}}function U(e,t,n,r){if(r.width<=0||r.height<=0)return null;let i=0,a=1;for(let o of[`x`,`y`]){let s=t[o]-e[o],c=r[o]-n,l=c+(o===`x`?r.width:r.height)+n*2;if(Math.abs(s)<1e-8){if(e[o]<c||e[o]>l)return null;continue}let u=(c-e[o])/s,d=(l-e[o])/s;if(i=Math.max(i,Math.min(u,d)),a=Math.min(a,Math.max(u,d)),i>a)return null}return i<=1&&a>=0?i:null}var Ve=new WeakMap;function He(e){let t=Ve.get(e);if(t)return t;let n=[],{columns:r,rows:i,solid:a}=e;for(let e=0;e<i;e++)for(let t=0;t<r;t++){let o=e*r+t;a[o]&&(t!==0&&t!==r-1&&e!==0&&e!==i-1&&a[o-1]&&a[o+1]&&a[o-r]&&a[o+r]||n.push(E(2*(t+.5)/r-1,2*(e+.5)/i-1)))}return Ve.set(e,n),n}function Ue(e,t){for(let[n,r]of[[e,t],[t,e]]){let e=n.shape;for(let t of He(n.mask.alpha)){let n=k(e.center,k(T(e.forward,t.x*e.halfLength),T(e.side,t.y*e.halfWidth)));if(re(r.mask.alpha,r.shape,n))return!0}}return!1}function We(e,t){let n=w(e.center,t.center),r=1/0,i=E(1);for(let a of[e.forward,e.side,t.forward,t.side]){let o=e.halfLength*Math.abs(j(a,e.forward))+e.halfWidth*Math.abs(j(a,e.side)),s=t.halfLength*Math.abs(j(a,t.forward))+t.halfWidth*Math.abs(j(a,t.side)),c=j(n,a),l=o+s-Math.abs(c);if(l<=0)return null;l<r&&(r=l,i=T(a,c<0?-1:1))}return{normal:i,depth:r}}function Ge(e,t,n){let{sim:r}=e,i=t.documentScale(),a=E(Math.cos(r.body.angle),-Math.sin(r.body.angle));return{center:k(t.documentPoint(r.body.position),t.carVisualOffset(r)),forward:a,side:E(-a.y,a.x),halfLength:n.lengthM*i/2,halfWidth:n.widthM*i/2}}function Ke(e,t,n,r,i,a){if(e.sim.mode!==`car`||e.sim.car.explodedAt!==null||e.isGhost)return null;let o=Ge(e,t,n),s=U(r,i,a,R(n.alpha,o));if(s===null)return null;let c=w(i,r),l=Math.min(256,Math.max(1,Math.ceil(Math.hypot(c.x,c.y)/Math.max(2,a)))),u=Math.max(0,Math.floor(s*l)-1),d=a>0?[E(),E(a,0),E(-a,0),E(0,a),E(0,-a)]:[E()];for(let e=u;e<=l;e++){let t=k(r,T(c,e/l));if(d.some(e=>re(n.alpha,o,k(t,e))))return t}return null}function qe(e,t,n,r){if(e.length<2)return;let i=t.documentScale(),a=e.filter(e=>e.sim.mode===`car`&&e.sim.car.explodedAt===null&&!e.isGhost).map(e=>{let r=n(e);return{entity:e,mask:r,shape:Ge(e,t,r)}});for(let e=0;e<a.length;e++)for(let n=e+1;n<a.length;n++){let o=a[e],s=a[n],c=We(o.shape,s.shape);if(!c||!Ue(o,s))continue;let l=c.normal,u=E(l.x,-l.y),d=te(o.mask.alpha,o.shape,T(l,-1)),f=te(s.mask.alpha,s.shape,l),p=T(k(d,f),.5),m=t.worldFromDocument(p),h=o.entity.sim.body,g=s.entity.sim.body,_=o.shape,v=s.shape,y=w(m,h.position),b=w(m,g.position),x=j(w(h.velocityAt(m),g.velocityAt(m)),u),C=1/h.mass,D=1/g.mass,O=C+D,A=(c.depth+.5)/i;if(h.position=k(h.position,T(u,A*C/O)),g.position=w(g.position,T(u,A*D/O)),o.shape={...o.shape,center:k(o.shape.center,T(l,(c.depth+.5)*C/O))},s.shape={...s.shape,center:w(s.shape.center,T(l,(c.depth+.5)*D/O))},x>=0)continue;let M=S(y,u),N=S(b,u),P=O+M**2/h.inertia+N**2/g.inertia,F=-(1+(x<-.8?.24:0))*x/P,I=T(u,F);h.impulse(I,m),g.impulse(T(I,-1),m);let L=E(-u.y,u.x),ee=w(h.velocityAt(m),g.velocityAt(m)),ne=S(y,L),R=S(b,L),re=O+ne**2/h.inertia+R**2/g.inertia,z=Math.max(-F*.38,Math.min(F*.38,-j(ee,L)/re)),ie=T(L,z);h.impulse(ie,m),g.impulse(T(ie,-1),m);let B=-x;B<=.8||(o.entity.sim.car.takeImpact(B,h.local(m)),s.entity.sim.car.takeImpact(B,g.local(m)),o.entity.damage.hit(p,l,_,B,i),s.entity.damage.hit(p,T(l,-1),v,B,i),r?.({speedMps:B,point:p,velocity:T(w(h.velocity,g.velocity),i),normal:l,carNormal:se(o.mask.alpha,_,d),pixelsPerMeter:i}))}}function Je(e){if(e.kind===`impact`||e.kind===`scrape`){let{element:t,...n}=e.impact,{element:r,...i}=e;return{...b({...i,impact:n}),element:r,impact:{...b(n),element:t}}}let{element:t,...n}=e;return{...b(n),element:t}}var Ye=class{onObserverError;pending=[];listeners=new Set;draining=!1;constructor(e=e=>console.error(`Joy Ride event observer failed.`,e)){this.onObserverError=e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}captureState(){return this.pending.map(Je)}restoreState(e){this.pending=e.map(Je)}emit(e){this.pending.push(e)}drain(e){if(this.draining||!this.pending.length)return;let t=this.pending;this.pending=[],this.draining=!0;try{for(let n of t){e(n);for(let e of[...this.listeners])if(this.listeners.has(e))try{e(n)}catch(e){try{this.onObserverError(e)}catch(e){console.error(`Joy Ride event observer error reporting failed.`,e)}}}}finally{this.draining=!1}}clear(){this.pending.length=0}},Xe=.15,Ze=class{renderer;id=`liquid`;sampleIntervalSeconds=Xe;receivesOwnSources=!1;elapsed=0;constructor(e){this.renderer=e}sources(){return this.renderer.burningLiquidSources?.()??[]}expose(e,t){e.length?(this.elapsed+=t,!(this.elapsed<Xe)&&(this.renderer.igniteLiquidsFromFire?.(e),this.elapsed%=Xe)):this.elapsed=0}captureState(){return this.elapsed}restoreState(e){if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw Error(`Invalid liquid heat checkpoint`);this.elapsed=e}reset(){this.elapsed=0}},Qe=class{domains;heatClocks=new Map;constructor(e,t){this.domains=[{id:`scene`,sampleIntervalSeconds:1/15,canReceive:()=>e.hasFireTargets?.()??!0,receivesOwnSources:!0,sources:()=>e.burningFireSources?.()??[],expose:(t,n)=>e.exposeToFire?.(t,n)},new Ze(t)]}registerHeatDomain(e){if(this.domains.some(t=>t.id===e.id))throw Error(`Heat domain already registered: ${e.id}`);if(!!e.captureState!=!!e.restoreState)throw Error(`Heat domain checkpoint methods must be paired: ${e.id}`);return this.domains.push(e),this.heatClocks.set(e.id,0),()=>{let t=this.domains.indexOf(e);t>=0&&this.domains.splice(t,1),this.heatClocks.delete(e.id)}}captureState(){return{heat:(e=>e.map(e=>({id:e.id,state:b(e.captureState?.())})))(this.domains),heatClocks:this.domains.map(e=>({id:e.id,elapsed:this.heatClocks.get(e.id)??0}))}}validateState(e){let t=(e,t)=>e.length===t.length&&e.every((e,n)=>e.id===t[n].id);if(!t(e.heat,this.domains)||!t(e.heatClocks,this.domains))throw Error(`Material domain registry changed since the checkpoint`)}restoreState(e){this.validateState(e),this.domains.forEach((t,n)=>t.restoreState?.(b(e.heat[n].state))),this.heatClocks.clear();for(let{id:t,elapsed:n}of e.heatClocks)this.heatClocks.set(t,n)}reset(){this.heatClocks.clear();for(let e of this.domains)e.reset?.()}stepFire(e){let t=[...this.domains],n=t.map(t=>{let n=(this.heatClocks.get(t.id)??0)+e,r=t.sampleIntervalSeconds??0;return r>0&&n+1e-9<r?(this.heatClocks.set(t.id,n),0):(this.heatClocks.set(t.id,r>0?n%r:0),n)}),r=n.map((e,n)=>e>0&&t[n].canReceive?.()!==!1);if(!r.some(Boolean))return;let i=t.map((e,n)=>r.some((e,r)=>e&&(r!==n||t[r].receivesOwnSources))?e.sources().map(fe):[]);t.forEach((e,t)=>{if(!r[t])return;let a=i.flatMap((n,r)=>t===r&&!e.receivesOwnSources?[]:n);e.expose(a,n[t])})}},$e={throttle:0,steer:0,action:!1,boost:!1},et=class{world;state;version=3;disposed=!1;constructor(e,t){this.world=e,this.state=t}get available(){return!this.disposed}restore(){this.world.restoreState(this)}dispose(){this.disposed||(this.disposed=!0,this.state.renderer.dispose(),this.world.releaseCheckpoint(this))}},tt=class{renderer;odometer;sound;overlay;stateParticipants=new Map;registerStateParticipant(e,t){if(this.stateParticipants.has(e))throw Error(`State participant already registered: ${e}`);return this.stateParticipants.set(e,t),()=>this.stateParticipants.delete(e)}slowMo=new ze;events=new Ye;vehicleRegistry=new Map;playerVehicleId=null;collisions;materialInteractions;checkpoints=new Set;flameDamageThisStep=new Map;stepSeconds=1/120;destructionPoints=0;disposed=!1;constructor(e,t,n,r,i,a=new ae,o={}){this.renderer=t,this.odometer=n,this.sound=r,this.overlay=i;let c=Se(o);this.vehicleDestructible=c.vehicleDestructible,this.toolsEnabled=c.toolsEnabled,e&&this.spawnVehicle({id:`player`,sim:e,control:{kind:`player`}}),this.collisions=a,this.materialInteractions=new Qe(a,t),a.setEvents(this.events),a.setAutoPaint?.(o.autoPaint??s.game.autoPaint)}get playerVehicle(){return this.playerVehicleId?this.vehicleRegistry.get(this.playerVehicleId):void 0}get focusVehicle(){return this.playerVehicle??this.vehicleRegistry.values().next().value}get primaryVehicle(){let e=this.focusVehicle;if(!e)throw Error(`Game world has no vehicles`);return e}get sim(){return this.primaryVehicle.sim}get damage(){return this.primaryVehicle.damage}getVehicle(e){return this.vehicleRegistry.get(e)}get cameraVehicle(){return this.focusVehicle}get otherVehicles(){let e=this.focusVehicle;return[...this.vehicleRegistry.values()].filter(t=>t!==e)}get vehicles(){return[...this.vehicleRegistry.values()]}registerHeatDomain(e){return this.materialInteractions.registerHeatDomain(e)}configureVehicle(e,t){let n=this.getVehicle(e);if(!n)return!1;if(t.appearance!==void 0&&![`auto`,`light`,`dark`].includes(t.appearance))throw TypeError(`Unknown vehicle appearance`);let r=t.slots===void 0?void 0:ve(t.slots);return t.preset&&this.collisions.prepare(t.preset),t.preset&&t.preset!==n.sim.car.preset&&n.setPreset(t.preset),t.appearance!==void 0&&(n.appearance=t.appearance),r!==void 0&&(n.slots=r),n===this.focusVehicle&&this.projectFocusVehicle(!!t.preset),!0}projectedSound;projectedPreset;projectFocusVehicle(e=!1){let t=this.focusVehicle;if(!t)return;let n=this.sound(),r=t.sim.car.preset;(n!==this.projectedSound||r!==this.projectedPreset)&&(n.setPreset(r),this.collisions.prepare(r),this.projectedSound=n,this.projectedPreset=r),e&&this.renderer.resetVehicleDamage()}resetEffects(){this.renderer.reset(),this.materialInteractions.reset()}fadeEffects(){this.materialInteractions.reset(),this.renderer.fadeEffects()}resetScene(){this.destructionPoints=0,this.events.clear(),this.collisions.reset?.(),this.fadeEffects();for(let e of this.vehicleRegistry.values())e.restoreHealth()}deformationEnabled=!0;vehicleDestructible=!0;toolsEnabled=!0;setVehicleDestructible(e){this.vehicleDestructible=e;for(let t of this.vehicleRegistry.values())t.sim.car.destructible=e,e||t.restoreHealth()}setToolsEnabled(e){this.toolsEnabled=e;for(let t of this.vehicleRegistry.values())t.setControls(t.controls,t.controlSource,{toolsEnabled:e}),e||t.weapons.reset()}setDeformationEnabled(e){this.deformationEnabled=e;for(let t of this.vehicleRegistry.values())t.damage.setEnabled(e)}spawnVehicle({id:e,sim:t,control:n,label:r=``}){if(this.vehicleRegistry.has(e))throw Error(`Vehicle ${e} already exists`);if(n.kind===`player`&&this.playerVehicle)throw Error(`Game world already has a player vehicle`);let i=new be(e,t);return t.car.destructible=this.vehicleDestructible,this.vehicleDestructible||i.restoreHealth(),i.damage.setEnabled(this.deformationEnabled),i.label=r,i.controlSource=n.kind===`player`?`player`:`scripted`,this.vehicleRegistry.set(e,i),n.kind===`player`&&(this.playerVehicleId=e),this.focusVehicle===i&&this.renderer.bindVehicle(i),i}removeVehicle(e){let t=this.vehicleRegistry.get(e);if(!t)return!1;this.vehicleRegistry.delete(e),this.playerVehicleId===e&&(this.playerVehicleId=null),this.collisions.forgetVehicle(e),this.renderer.forgetVehicle(e),t.dispose();let n=this.focusVehicle;return n&&this.renderer.bindVehicle(n),!0}consumeEvent=e=>{let t=this.sound();switch(e.kind){case`impact`:t.playCrash(e.impact.speedMps),this.renderer.emitSparks(e.impact),this.renderer.emitCrashShake(e.impact.speedMps);break;case`scrape`:this.renderer.emitSparks(e.impact);break;case`crush`:t.playCrush(),this.awardPoints(e.point,e.points);break;case`combustionExplosion`:this.awardPoints(e.point,e.points),t.playCombustibleExplosion(this.overlay?d(e.point,this.renderer.sceneScroll(),this.renderer.viewportSize()):1);break;case`destructibleDestroyed`:this.awardPoints(e.point,e.points)}};awardPoints(e,t){!Number.isFinite(t)||t<=0||(this.destructionPoints+=t,this.renderer.emitPoints(e,t))}get points(){return this.destructionPoints}get totalPoints(){return this.collisions.totalPoints}vehicleProjectileHit(e,t,n,r){let i=null;for(let a of this.vehicleRegistry.values()){if(a===e)continue;let o=Ke(a,this.renderer,this.collisions.vehicleMask(a.sim.car.preset,a.damage),t,n,r);if(!o)continue;let s=P(w(o,t));(!i||s<i.distance)&&(i={vehicle:a,point:o,distance:s})}return i}nearestProjectileTarget(e,t,n,r){let i=this.vehicleProjectileHit(e,t,n,r),a=this.collisions.projectileHit(t,n,r);return i&&(!a||i.distance<P(w(a.point,t)))?{vehicle:i.vehicle,point:i.point,object:null}:a?{vehicle:null,point:a.point,object:a}:null}rocketCollision=(e,t,n,r)=>{this.collisions.setSourceVehicle?.(e.id);let i=this.nearestProjectileTarget(e,t,n,r);if(!i)return null;let a=i.vehicle?i.point:this.collisions.rocketImpact(t,n,r,1,i.object??void 0);if(a){let r=Be(1),o=r.radiusPx;i.vehicle&&this.collisions.applyAreaImpact?.(a,r),r.ignite&&this.renderer.igniteLiquidAt?.(a,this.renderer.documentScale()*2.2);for(let t of this.vehicleRegistry.values()){if(t===e||t.sim.car.explodedAt!==null||t.isGhost)continue;let n=this.renderer.documentPoint(t.sim.body.position),s=P(w(n,a)),c=t===i.vehicle;if(!c&&s>o)continue;let l=c?1:Math.max(.2,1-s/o*.7);t.sim.car.damage(x(`rocket`,e.sim.car.preset)*l*r.damage/100),t.synchronizeLifecycle()}this.renderer.emitRocketExplosionShake(1),this.renderer.emitRocketExplosion(a,w(n,t),1)}return a};bulletCollision=(e,t,n,r)=>{this.collisions.setSourceVehicle?.(e.id);let i=this.nearestProjectileTarget(e,t,n,r);return i?i.vehicle?(i.vehicle.sim.car.damage(x(`bullet`,e.sim.car.preset)),i.vehicle.synchronizeLifecycle(),i.point):this.collisions.bulletImpact(t,n,r,i.object??void 0):null};flameContact=(e,t,n,r,i)=>{this.collisions.setSourceVehicle?.(e.id);let a=this.nearestProjectileTarget(e,t,n,r);if(a?.vehicle){let t=this.flameDamageThisStep.get(a.vehicle.id)??0,n=Math.min(x(`flame`,e.sim.car.preset,i),Math.max(0,D.damagePerSecond*this.stepSeconds-t));return a.vehicle.sim.car.damage(n),this.flameDamageThisStep.set(a.vehicle.id,t+n),a.vehicle.synchronizeLifecycle(),a.point}return this.collisions.flameContact(t,n,r,i,p(e.sim.car.preset))};gunshot=()=>this.sound().playGunshot();rocketLaunch=e=>this.sound().playRocketLaunch(this.overlay?l(this.renderer.vehicleViewportPosition(e),this.renderer.viewportSize(),!1):1);rocketImpact=e=>this.sound().playRocketExplosion(this.overlay?l(this.renderer.vehicleViewportPosition(e),this.renderer.viewportSize(),!1):1);bulletImpact=e=>this.sound().playBulletImpact(this.overlay?l(this.renderer.vehicleViewportPosition(e),this.renderer.viewportSize(),!1):1);step(e={},t){let n=this.focusVehicle;if(!n)return;this.stepSeconds=t,this.flameDamageThisStep.clear(),performance.now();let{renderer:r,collisions:i}=this,a=n.sim,o=this.playerVehicle,s={...a.body.position},c=new Map,u={toolsEnabled:this.toolsEnabled};for(let n of this.vehicleRegistry.values())c.set(n,{...n.sim.body.position}),n.synchronizeLifecycle(),n.setControls(n===o?e.controls??$e:$e,n===o&&e.userDriven?`player`:`scripted`,u),n.step(t,n===o?this.sound().rpm:null,n===o&&e.manualMoved);o&&e.userDriven&&a.mode===`car`&&this.odometer.add(P(w(a.body.position,s)),r.documentScale()),e.afterPhysics?.();let d=this.cameraVehicle?.sim??a,f=this.overlay&&(e.allowFollow?.()??!0)&&P(d.body.velocity)>.1&&r.followDocument(d);if(a.barrier&&!this.overlay){let e={...a.body.velocity};a.contain(r.bounds());let t=P(w(e,a.body.velocity));a.mode===`car`&&a.car.takeImpact(t),this.sound().playCrash(t),r.emitCrashShake(t)}performance.now(),i.beginStep(r,t),performance.now();for(let e of this.vehicleRegistry.values()){let n=e.advanceBurn(t);if(n){let a=r.emitVehicleBurn(e,n,i.vehicleMask(e.sim.car.preset,e.damage),t);a&&this.events.emit({kind:`combustionExplosion`,point:a,points:0})}let a=c.get(e)??e.sim.body.position,o={...e.sim.body.position},s=w(o,a),l=Math.max(.25,e.sim.car.preset.geometry.widthM*.35),u=Math.min(16,Math.max(1,Math.ceil(P(s)/l)));u>1&&(e.sim.body.position={...a});for(let t=1;t<=u;t++){let n={x:a.x+s.x*t/u,y:a.y+s.y*t/u};if(e.sim.body.position={...n},i.stepVehicle(e.sim,r,e===this.cameraVehicle&&e.sim.barrier&&f,e.damage,e.id,e.isGhost),P(w(e.sim.body.position,n))>.02)break}e.synchronizeLifecycle()}if(i.endStep(t),performance.now(),this.vehicleRegistry.size>1){qe(this.vehicles,r,e=>i.vehicleMask(e.sim.car.preset,e.damage),e=>this.events.emit({kind:`impact`,impact:e}));for(let e of this.vehicleRegistry.values())e.synchronizeLifecycle()}this.events.drain(this.consumeEvent),performance.now(),i.stepElementLiquids?.(r,e.manualMoved?this.otherVehicles:[n,...this.otherVehicles],t),r.advanceEffects(n,t,{walls:i.wallRects(),carMask:i.vehicleMask(a.car.preset,n.damage),tirePaintSources:e=>i.tirePaintAt(e),driven:!e.manualMoved,rocketCollision:this.rocketCollision,bulletCollision:this.bulletCollision,onGunshot:this.gunshot,flameContact:this.flameContact,onRocketLaunch:this.rocketLaunch,onRocketImpact:this.rocketImpact,onBulletImpact:this.bulletImpact,maskFor:e=>i.vehicleMask(e.sim.car.preset,e.damage),companions:this.otherVehicles}),performance.now(),this.materialInteractions.stepFire(t);let p=r.rocketFlightPosition,m=this.sound();m.setRocketFlightProximity(p?this.overlay?l(r.vehicleViewportPosition(p),r.viewportSize(),!1):1:0),m.setBurningFireProximity(Math.max(i.burningProximity(r.documentPoint(a.body.position)),a.mode===`car`&&a.car.explodedAt===null?A(a.car.health,a.car.maxHealth):0)),this.events.drain(this.consumeEvent)}advanceTime(e){let t=this.slowMo.advance(e);return this.renderer.setSlowMoZoom(this.slowMo.zoomFactor),this.sound().setTimeScale?.(this.slowMo.speedFactor),t}present(e,t,n,r,i,a,o){let s=this.focusVehicle;if(!s)return;let{renderer:d}=this,f=s.sim;this.projectFocusVehicle();let p=this.playerVehicle?{...n,boost:f.lastInput.boost}:{...s.controls,boost:f.lastInput.boost};if(!document.hidden){let e=this.sound(),n=f.paused?0:P(f.body.velocity),o=f.mode===`car`&&!f.paused&&!s.isGhost?c(f,f.lastInput.action):[];e.setActive(f.mode===`car`&&i),s.isGhost&&e.silenceTires(),e.setGhostMode(!f.paused&&s.isGhost),e.setFlamethrowerFiring(!f.paused&&d.flamethrowerFiring),e.setBoosting(!f.paused&&f.car.boostActive);let m=p.throttle!==0||p.steer!==0||p.action||r;e.setProximity(this.overlay?l(d.vehicleViewportPosition(f.body.position),d.viewportSize(),m):1),e.setMasterVolume(u(a)),performance.now(),e.update(t*this.slowMo.speedFactor,p,n,0,0,f.mode===`car`?f.car.boostCharge:0,o);let h=e.takeExhaustPops();!f.paused&&f.mode===`car`&&d.queueExhaustPops(h)}d.render(s,e,o,this.collisions,this.otherVehicles)}snapshot(){let{sim:e}=this;return{mode:e.mode,presetId:e.car.preset.id,position:{...e.body.position},speed:P(e.body.velocity),angle:e.body.angle,spin:e.body.spin,paused:e.paused,health:e.car.health,maxHealth:e.car.maxHealth,burnStage:e.car.stage,points:this.destructionPoints}}saveState(){if(this.disposed)throw Error(`Game world has been disposed`);let e=[...this.vehicleRegistry.values()].map(e=>e.captureState()),t=this.collisions.captureState(),n=this.odometer.captureState(),r=this.events.captureState(),i=this.renderer.captureState(),a;try{a=new et(this,{extensions:new Map([...this.stateParticipants].map(([e,t])=>[e,b(t.captureState())])),vehicles:e,playerVehicleId:this.playerVehicleId,deformationEnabled:this.deformationEnabled,vehicleDestructible:this.vehicleDestructible,toolsEnabled:this.toolsEnabled,slowMo:this.slowMo.captureState(),collisions:t,odometer:n,events:r,points:this.destructionPoints,renderer:i,materialInteractions:this.materialInteractions.captureState()})}catch(e){throw i.dispose(),e}return this.checkpoints.add(a),a}restoreState(e){if(this.disposed||e.world!==this||!e.available)throw Error(`Checkpoint is unavailable for this game world`);let t=e.state;if(t.vehicles.length!==this.vehicleRegistry.size||t.vehicles.some(e=>!this.vehicleRegistry.has(e.id)))throw Error(`Checkpoint vehicle registry does not match`);this.materialInteractions.validateState(t.materialInteractions),this.deformationEnabled=t.deformationEnabled,this.vehicleDestructible=t.vehicleDestructible,this.toolsEnabled=t.toolsEnabled,this.slowMo.restoreState(t.slowMo),this.sound().setTimeScale?.(this.slowMo.speedFactor),this.destructionPoints=t.points,this.playerVehicleId=t.playerVehicleId;let n=this.focusVehicle;n&&this.renderer.bindVehicle(n),this.renderer.restoreState(t.renderer),this.materialInteractions.restoreState(t.materialInteractions);for(let e of t.vehicles){let t=this.vehicleRegistry.get(e.id);if(!t)throw Error(`Checkpoint vehicle is unavailable`);t.restoreState(e)}n&&this.collisions.prepare(n.sim.car.preset),this.collisions.restoreState(t.collisions),this.odometer.restoreState(t.odometer),this.events.restoreState(t.events);for(let[e,n]of t.extensions){let t=this.stateParticipants.get(e);if(!t)throw Error(`Checkpoint state participant is unavailable: ${e}`);t.restoreState(b(n))}}releaseCheckpoint(e){this.checkpoints.delete(e)}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.checkpoints])e.dispose();this.slowMo.reset(),this.sound().setTimeScale?.(1),this.events.clear(),this.collisions.destroy(),this.renderer.dispose();for(let e of this.vehicleRegistry.values())e.dispose();this.vehicleRegistry.clear(),this.stateParticipants.clear()}}},nt=10,rt=class{active;step;render;stepSeconds;maxSteps;onError;simulationElapsed;frameId=0;running=!1;lastTime=null;accumulator=0;failure=null;constructor(e,t,n,r=1/120,i=12,a=e=>console.error(`Joy Ride stopped after a runtime failure.`,e),o=e=>e){this.active=e,this.step=t,this.render=n,this.stepSeconds=r,this.maxSteps=i,this.onError=a,this.simulationElapsed=o}get status(){return this.failure?`failed`:this.running?`running`:`stopped`}get error(){return this.failure?.error}reset(){this.lastTime=null,this.accumulator=0}advance(e){me();let t=this.lastTime===null?0:Math.max(0,(e-this.lastTime)/1e3),n=Math.min(t,.1);if(this.lastTime=e,this.active()){t>n&&this.simulationElapsed(t-n),this.simulationElapsed(0),this.accumulator+=n;let e=0,r=this.stepSeconds*1e-9,i=performance.now();for(;this.accumulator+r>=this.stepSeconds&&e<this.maxSteps&&(this.step(this.simulationElapsed(this.stepSeconds)),this.accumulator=Math.max(0,this.accumulator-this.stepSeconds),e++,!(e>=2&&performance.now()-i>nt)););if(this.accumulator+r>=this.stepSeconds){let e=this.accumulator-this.accumulator%this.stepSeconds;this.simulationElapsed(e),this.accumulator-=e}}else this.accumulator=0;this.render(e,n)}start(){this.running||(this.failure=null,this.running=!0,this.frameId=requestAnimationFrame(this.onFrame))}stop(){this.running=!1,this.frameId&&cancelAnimationFrame(this.frameId),this.frameId=0,this.reset()}onFrame=e=>{this.frameId=0;try{this.advance(e)}catch(e){this.stop(),this.failure={error:e},this.onError(e);return}this.running&&(this.frameId=requestAnimationFrame(this.onFrame))}};function it(e,t){let n=1/0,r={x:1,y:0};for(let i of[e,t])for(let a=0;a<i.length;a++){let o=i[a],s=i[(a+1)%i.length],c=Math.hypot(s.x-o.x,s.y-o.y);if(c<1e-9)continue;let l={x:-(s.y-o.y)/c,y:(s.x-o.x)/c},u=e.map(e=>e.x*l.x+e.y*l.y),d=t.map(e=>e.x*l.x+e.y*l.y),f=Math.min(...u),p=Math.max(...u),m=Math.min(...d),h=Math.max(...d);if(p<=m||h<=f)return null;let g=p-m,_=h-f,v=Math.min(g,_);v<n&&(n=v,r=g<_?{x:-l.x,y:-l.y}:l)}return Number.isFinite(n)?{normal:r,depth:n}:null}function at(e,t,n,r){let i=r.reduce((e,t,n)=>{let i=r[(n+1)%r.length];return e+t.x*i.y-i.x*t.y},0),a=0,o=1;for(let s=0;s<r.length;s++){let c=r[s],l=r[(s+1)%r.length],u=Math.hypot(l.x-c.x,l.y-c.y);if(u<1e-9)continue;let d=(l.y-c.y)/u*Math.sign(i),f=-(l.x-c.x)/u*Math.sign(i),p=(e.x-c.x)*d+(e.y-c.y)*f-n,m=(t.x-e.x)*d+(t.y-e.y)*f;if(Math.abs(m)<1e-9){if(p>0)return null;continue}let h=-p/m;if(m<0?a=Math.max(a,h):o=Math.min(o,h),a>o)return null}return a<=1&&o>=0?a:null}function W(e,t=0,n=1){let r=Math.max(0,Math.min(1,(e-t)/(n-t)));return 1-r*r*(3-2*r)}var ot=(e,t,n)=>{let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)},st=class{sprites=new WeakMap;colors=new Map;colorCanvas=null;nextPhase=0;get(e,t,n,r,i=!1){if(t>=1)return e;let[a,o,s]=this.rgb(n),c=this.sprites.get(e);if(!c||c.canvas.width!==e.width||c.canvas.height!==e.height){let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height,c={canvas:t,revision:-1,tint:-1,radialStep:-1,phase:this.nextPhase},this.nextPhase=(this.nextPhase+.61803398875)%1,this.sprites.set(e,c)}let l=Math.max(0,Math.min(1,Math.round(t*32+c.phase-.5)/32)),u=Math.round(a*l),d=Math.round(o*l),f=Math.round(s*l),p=u<<16|d<<8|f;if(i||c.revision!==r||c.tint!==p){F(`burn sprite recolors`);let t=c.canvas.getContext(`2d`);t&&(t.clearRect(0,0,e.width,e.height),t.globalCompositeOperation=`source-over`,t.drawImage(e,0,0),t.globalCompositeOperation=`source-in`,t.fillStyle=`rgb(${u} ${d} ${f})`,t.fillRect(0,0,e.width,e.height),t.globalCompositeOperation=`source-over`,c.revision=r,c.tint=p,c.radialStep=-1)}return c.canvas}getRadialBurn(e,t,n){let r=this.sprites.get(e);if(!r||r.canvas.width!==e.width||r.canvas.height!==e.height){let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height,r={canvas:t,revision:-1,tint:-1,radialStep:-1,phase:0},this.sprites.set(e,r)}let i=Math.round(t.age*30);if(r.revision===n&&r.radialStep===i)return r.canvas;let a=r.canvas.getContext(`2d`);if(!a)return e;a.save(),a.clearRect(0,0,e.width,e.height),a.drawImage(e,0,0);let o=e=>{let n=a.createRadialGradient(t.originX,t.originY,0,t.originX,t.originY,Math.max(1,t.farthest));for(let r=0;r<=16;r++){let i=r/16,a=(t.age-i*t.spreadSeconds)/Math.max(.01,t.burnSeconds);n.addColorStop(i,`rgba(0, 0, 0, ${e(a)})`)}return n};return a.globalCompositeOperation=`source-atop`,a.fillStyle=o(e=>ot(.12,.72,e)*.95),a.fillRect(0,0,e.width,e.height),a.globalCompositeOperation=`destination-out`,a.fillStyle=o(e=>1-W(e,.78,1.02)),a.fillRect(0,0,e.width,e.height),a.restore(),r.revision=n,r.radialStep=i,r.tint=-1,r.canvas}bytesFor(e){let t=e&&this.sprites.get(e)?.canvas;return t?t.width*t.height*4:0}clear(){this.sprites=new WeakMap,this.colors.clear(),this.colorCanvas=null,this.nextPhase=0}rgb(e){let t=this.colors.get(e);if(t)return t;let n=this.colorCanvas??=document.createElement(`canvas`);n.width=n.height=1;let r=n.getContext(`2d`,{willReadFrequently:!0});if(!r)return[255,255,255];r.clearRect(0,0,1,1),r.fillStyle=e,r.fillRect(0,0,1,1);let i=r.getImageData(0,0,1,1).data,a=[i[0],i[1],i[2]];return this.colors.set(e,a),a}};function ct(e,t,n,r,i){if(!(r.speedMps>.8))return!1;let a=r.pixelsPerMeter,o=w(r.point,n.center);return e.car.takeImpact(r.speedMps,E(j(o,n.forward)/a,j(o,n.side)/a)),t?.hit(r.point,r.normal,n,r.speedMps,a),i(),!0}var lt=class{sources;cells=new Map;largeSources=[];cellSize=64;constructor(e){this.sources=e;for(let t of e){let e=t.bounds??{x:t.point.x,y:t.point.y,width:0,height:0},n=Math.floor((e.x-t.radiusPx)/this.cellSize),r=Math.floor((e.x+e.width+t.radiusPx)/this.cellSize),i=Math.floor((e.y-t.radiusPx)/this.cellSize),a=Math.floor((e.y+e.height+t.radiusPx)/this.cellSize);if((r-n+1)*(a-i+1)>256)this.largeSources.push(t);else for(let e=i;e<=a;e++)for(let i=n;i<=r;i++){let n=`${i}:${e}`,r=this.cells.get(n)??[];r.push(t),this.cells.set(n,r)}}}*near(e){let t=Math.floor(e.x/this.cellSize),n=Math.floor((e.x+e.width)/this.cellSize),r=Math.floor(e.y/this.cellSize),i=Math.floor((e.y+e.height)/this.cellSize);if((n-t+1)*(i-r+1)>256){for(let t of this.sources)this.overlaps(t,e)&&(yield t);return}let a=new Set;for(let e=r;e<=i;e++)for(let r=t;r<=n;r++)for(let t of this.cells.get(`${r}:${e}`)??[])a.has(t)||(a.add(t),yield t);for(let t of this.largeSources)this.overlaps(t,e)&&(yield t)}overlaps(e,t){let n=e.bounds??{x:e.point.x,y:e.point.y,width:0,height:0},r=e.radiusPx;return n.x-r<=t.x+t.width&&n.x+n.width+r>=t.x&&n.y-r<=t.y+t.height&&n.y+n.height+r>=t.y}},ut=`joy-ride-odometer-v1`,dt=`joy-ride-distance-dpi-v1`,ft=1609.344,pt={screen:96,print:300},mt=.0254;function ht(){try{return typeof window>`u`?null:window.localStorage}catch{return null}}var gt={pixels:0,kilometers:0,miles:0,dpi:pt.print,dpiMode:`print`};function _t(e){if(!e||typeof e!=`object`)return!1;let t=e;return Number.isFinite(t.pixels)&&(t.pixels??-1)>=0}var vt=class{store;total;dirty=!1;mode=`print`;constructor(e=ht()){this.store=e;let t=null;try{t=JSON.parse(this.store?.getItem(ut)??`null`)}catch{}this.total=_t(t)?{pixels:t.pixels}:{pixels:0};try{this.store?.getItem(dt)===`screen`&&(this.mode=`screen`)}catch{}}add(e,t){!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0||(this.total.pixels+=e*t,this.dirty=!0)}reset(){this.total.pixels=0,this.dirty=!0,this.flush()}get dpiMode(){return this.mode}captureState(){return{pixels:this.total.pixels,mode:this.mode}}restoreState(e){if(!Number.isFinite(e.pixels)||e.pixels<0||!(e.mode in pt))throw Error(`Invalid odometer checkpoint`);this.total.pixels=e.pixels,this.mode=e.mode,this.dirty=!0,this.flush();try{this.store?.setItem(dt,this.mode)}catch{}}get dpi(){return pt[this.mode]}cycleDpi(){this.mode=this.mode===`print`?`screen`:`print`;try{this.store?.setItem(dt,this.mode)}catch{}return this.readout}flush(){if(this.dirty)try{this.store?.setItem(ut,JSON.stringify(this.total)),this.dirty=!1}catch{}}get kilometers(){return this.total.pixels/this.dpi*mt/1e3}get miles(){return this.total.pixels/this.dpi*mt/ft}get readout(){return{pixels:this.total.pixels,kilometers:this.kilometers,miles:this.miles,dpi:this.dpi,dpiMode:this.mode}}},yt={quality:(e,t)=>e.setQuality(t),lighting:(e,t)=>e.setVehicleLighting(t??{}),tireSmoke:(e,t)=>e.setTireSmokeEnabled(t),vehicleShadows:(e,t)=>e.setVehicleShadowsEnabled(t),sparks:(e,t)=>e.setSparksEnabled(t),screenShake:(e,t)=>e.setScreenShakeEnabled(t),surfaceTone:(e,t)=>e.setSurfaceTone(t),debug:(e,t)=>e.setDebugEnabled(t),showVehicleMarkers:(e,t)=>e.setShowVehicleMarkers(t),deform:(e,t)=>e.setDeformEnabled(t)};function bt(e,t,n){for(let r of Object.keys(yt))if(!n||t[r]!==n[r]){let n=yt[r];n(e,t[r])}}function G(e,t,n=0){let{halfX:r,halfY:i}=e,a=r.x*i.y-r.y*i.x;if(Math.abs(a)<1e-4)return!1;let o=t.x-e.center.x,s=t.y-e.center.y,c=(o*i.y-s*i.x)/a,l=(s*r.x-o*r.y)/a;return Math.abs(c)<=1+n/Math.max(1,Math.hypot(r.x,r.y))&&Math.abs(l)<=1+n/Math.max(1,Math.hypot(i.x,i.y))}var xt=class{transforms=new WeakMap;transform(e){return this.transforms.has(e)||this.transforms.set(e,St(e)),this.transforms.get(e)}};function St(e){let t=getComputedStyle(e);if(t.visibility===`hidden`||t.display===`none`)return null;let n=new DOMMatrixReadOnly;if(t.rotate&&t.rotate!==`none`){let e=t.rotate.trim().split(/\s+/);if(e.length>1&&e.slice(0,-1).join(` `)!==`z`)return null;let r=e.at(-1),i=parseFloat(r),a=r.endsWith(`grad`)?i*.9:r.endsWith(`rad`)?i*180/Math.PI:r.endsWith(`turn`)?i*360:i;n=n.rotate(a)}if(t.scale&&t.scale!==`none`){let[e,r]=t.scale.split(/\s+/).map(Number);n=n.scale(e,r??e)}return t.transform&&t.transform!==`none`&&(n=n.multiply(new DOMMatrixReadOnly(t.transform))),n.is2D?n:null}function K(e,t){let n=e.getBoundingClientRect();if(!n.width||!n.height)return null;let r=new DOMMatrixReadOnly;for(let n=e;n;n=n.parentElement){let e=t?t.transform(n):St(n);if(!e)return null;r=e.multiply(r)}return{center:{x:n.left+n.width/2,y:n.top+n.height/2},halfX:{x:r.a*e.offsetWidth/2,y:r.b*e.offsetWidth/2},halfY:{x:r.c*e.offsetHeight/2,y:r.d*e.offsetHeight/2}}}var Ct=new WeakMap,wt=[[{x:-.5,y:-.5},{x:.5,y:-.5}],[{x:.5,y:-.5},{x:.5,y:.5}],[{x:.5,y:.5},{x:-.5,y:.5}],[{x:-.5,y:.5},{x:-.5,y:-.5}]];function Tt(e){if(!e)return wt;let t=Ct.get(e);if(t)return t;let n=[],{columns:r,rows:i,solid:a}=e;for(let e=0;e<i;e++)for(let t=0;t<r;t++){if(!a[e*r+t])continue;let o=t/r-.5,s=(t+1)/r-.5,c=e/i-.5,l=(e+1)/i-.5;t&&a[e*r+t-1]||n.push([{x:o,y:c},{x:o,y:l}]),t!==r-1&&a[e*r+t+1]||n.push([{x:s,y:c},{x:s,y:l}]),e&&a[(e-1)*r+t]||n.push([{x:o,y:c},{x:s,y:c}]),e!==i-1&&a[(e+1)*r+t]||n.push([{x:o,y:l},{x:s,y:l}])}return Ct.set(e,n),n}function Et(e,[t,n]){let r=n.x-t.x,i=n.y-t.y,a=Math.max(0,Math.min(1,((e.x-t.x)*r+(e.y-t.y)*i)/Math.max(1e-12,r*r+i*i)));return{x:t.x+r*a,y:t.y+i*a}}var Dt=(e,t)=>e.x*t.y-e.y*t.x;function Ot([e,t],[n,r]){let i={x:t.x-e.x,y:t.y-e.y},a={x:r.x-n.x,y:r.y-n.y},o=Dt(i,a);if(Math.abs(o)<1e-10)return null;let s={x:n.x-e.x,y:n.y-e.y},c=Dt(s,a)/o,l=Dt(s,i)/o;return c>=0&&c<=1&&l>=0&&l<=1?{x:e.x+i.x*c,y:e.y+i.y*c}:null}var kt=e=>[{x:e.center.x-e.halfX.x-e.halfY.x,y:e.center.y-e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x-e.halfY.x,y:e.center.y+e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x+e.halfY.x,y:e.center.y+e.halfX.y+e.halfY.y},{x:e.center.x-e.halfX.x+e.halfY.x,y:e.center.y-e.halfX.y+e.halfY.y}];function At(e,t,n,r){let i=e.pixelsPerMeter??1,a=e.mask?e.mask.lengthM*i:e.lengthPx,o=e.mask?e.mask.widthM*i:e.widthPx,s=n??{position:e.position,angle:e.angle,target:t.center},c=Math.atan2(Math.sin(e.angle-s.angle),Math.cos(e.angle-s.angle)),l=s.target??t.center,u={x:s.position.x-l.x,y:s.position.y-l.y},d={x:e.position.x-t.center.x,y:e.position.y-t.center.y},f=Et({x:0,y:0},[u,d]),p=Math.hypot(a,o)*.5+Math.hypot(t.halfX.x,t.halfX.y)+Math.hypot(t.halfY.x,t.halfY.y);if(Math.hypot(f.x,f.y)>p)return{inside:!1,contact:null};let m=Tt(e.mask?.alpha);function h(n){let r={x:s.position.x+(e.position.x-s.position.x)*n,y:s.position.y+(e.position.y-s.position.y)*n},i=s.angle+c*n,l=Math.cos(i),u=Math.sin(i),d=e=>({x:r.x+l*e.x*a-u*e.y*o,y:r.y+u*e.x*a+l*e.y*o}),f=s.target??t.center,p={...t,center:{x:f.x+(t.center.x-f.x)*n,y:f.y+(t.center.y-f.y)*n}},h=kt(p);if(!it([d({x:-.5,y:-.5}),d({x:.5,y:-.5}),d({x:.5,y:.5}),d({x:-.5,y:.5})],h))return null;let g=null,_=1/0,v=e=>{let t=(e.x-p.center.x)**2+(e.y-p.center.y)**2;t<_&&(g=e,_=t)};for(let e of m){let t=[d(e[0]),d(e[1])];G(p,t[0])&&v(t[0]),G(p,t[1])&&v(t[1]);let n=Et(p.center,t);G(p,n)&&v(n);for(let e=0;e<4;e++){let n=Ot(t,[h[e],h[(e+1)%4]]);n&&v(n)}}if(!g){let t=p.center.x-r.x,n=p.center.y-r.y,i=(l*t+u*n)/a+.5,s=(-u*t+l*n)/o+.5;if(i>=0&&i<1&&s>=0&&s<1){let t=e.mask?.alpha;(!t||t.solid[Math.floor(s*t.rows)*t.columns+Math.floor(i*t.columns)])&&(g=p.center)}}return g?{point:g,center:r,angle:i}:null}let g=h(1),_={x:d.x-u.x,y:d.y-u.y},v=_.x*_.x+_.y*_.y,y=0,b=1;if(v>1e-12){let e=u.x*_.x+u.y*_.y,t=Math.max(0,e*e-v*(u.x*u.x+u.y*u.y-p*p)),n=Math.sqrt(t);y=Math.max(0,(-e-n)/v),b=Math.min(1,(-e+n)/v)}let x=b-y,S=(Math.sqrt(v)+Math.hypot(a,o)*Math.abs(c)*.5)*x,C=Math.max(1,Math.min(o,Math.hypot(t.halfX.x,t.halfX.y)*2,Math.hypot(t.halfY.x,t.halfY.y)*2)/4),w=Math.min(64,Math.max(1,Math.ceil(S/C))),T=h(y),E=y;for(let e=1;!T&&e<=w;e++){let t=y+x*e/w,n=t===1?g:h(t);if(!n)continue;let r=y+x*(e-1)/w,i=t;T=n;for(let e=0;e<7;e++){let e=(r+i)/2,t=h(e);t?(i=e,T=t):r=e}E=i}if(!T)return{inside:!1,contact:null};let D={x:(T.point.x-T.center.x)/i,y:(T.point.y-T.center.y)/i},O={x:e.position.x-s.position.x,y:e.position.y-s.position.y},k=Math.hypot(O.x,O.y),A=e.velocityMps??(k>1e-6?{x:O.x/k*e.speedMps,y:O.y/k*e.speedMps}:{x:Math.cos(e.angle)*e.speedMps,y:Math.sin(e.angle)*e.speedMps}),j=e.angularVelocity??(r>0?c/r:0),M=r>0?{x:(t.center.x-l.x)/(r*i),y:(t.center.y-l.y)/(r*i)}:{x:0,y:0},N={x:M.x-A.x+j*D.y,y:M.y-A.y-j*D.x},P=Math.cos(T.angle),F=Math.sin(T.angle);return{inside:g!==null,contact:{fraction:E,origin:{x:Math.max(-.5,Math.min(.5,(P*D.x+F*D.y)*i/a)),y:Math.max(-.5,Math.min(.5,(F*D.x-P*D.y)*i/o))},angle:Math.atan2(F*N.x-P*N.y,P*N.x+F*N.y),velocity:Math.hypot(N.x,N.y)}}}var jt=(e=``)=>e.split(/\s+/u).filter(Boolean),Mt=class{entries=new Map;apply(e,t,n){let r=this.entries.get(e),{enteredClass:i,dwellingClass:a,successClass:o}=t;if(!r&&!i&&!a&&!o||r?.phase===n&&r.entered===i&&r.dwelling===a&&r.success===o)return;let s=r?.tokens??new Map,c=new Set([...jt(i),...jt(a),...jt(o)]),l=new Set(jt(n===`entered`?i:n===`dwelling`?a:n===`success`?o:``));for(let[t,n]of s)c.has(t)||(this.restoreToken(e,t,n),s.delete(t));for(let t of c){let n=e.classList.contains(t),r=s.get(t)??{original:n,applied:n},i=l.has(t);n!==i&&e.classList.toggle(t,i),r.applied=i,s.set(t,r)}c.size?this.entries.set(e,{phase:n,entered:i,dwelling:a,success:o,tokens:s}):this.entries.delete(e)}restoreToken(e,t,n){let r=e.classList.contains(t);r===n.applied&&r!==n.original&&e.classList.toggle(t,n.original)}restore(e){for(let[t,n]of this.entries.get(e)?.tokens??[])this.restoreToken(e,t,n);this.entries.delete(e)}reset(){for(let e of this.entries.keys())this.restore(e)}captureState(){return b(this.entries)}restoreState(e){this.reset();for(let[t,n]of b(e)){this.entries.set(t,n);for(let[e,r]of n.tokens)t.classList.contains(e)!==r.applied&&t.classList.toggle(e,r.applied)}}},Nt=`input[type="checkbox"],[role="checkbox"],[role="switch"]`;function Pt(e){return e instanceof HTMLInputElement?{checked:e.checked,indeterminate:e.indeterminate}:{aria:e.getAttribute(`aria-checked`)}}function Ft(e,t){`checked`in t&&e instanceof HTMLInputElement?(e.checked=t.checked,e.indeterminate=t.indeterminate):`aria`in t&&(t.aria===null?e.removeAttribute(`aria-checked`):e.setAttribute(`aria-checked`,t.aria))}var It=class{initial=new Map;sync(e){for(let[t,n]of this.initial)e.has(t)||(Ft(t,n),this.initial.delete(t));for(let t of e)this.initial.has(t)||this.initial.set(t,Pt(t))}reset(){for(let[e,t]of this.initial)Ft(e,t)}resetTarget(e){let t=this.initial.get(e);t&&Ft(e,t)}captureState(){return b(new Map([...this.initial].map(([e,t])=>[e,{initial:t,current:Pt(e)}])))}restoreState(e){this.reset(),this.initial.clear();for(let[t,{initial:n,current:r}]of b(e))this.initial.set(t,n),Ft(t,r)}dispose(){this.reset(),this.initial.clear()}},Lt={route:{id:`data-jr-route`,order:`data-jr-route-order`,progress:`data-jr-route-progress`,event:`data-jr-route-event`},objective:{id:`data-jr-objective`,order:`data-jr-objective-order`,progress:`data-jr-objective-progress`,event:`data-jr-objective-event`}},Rt={click:{action:`click`},check:{action:`check`},toggle:{action:`toggle`},pickup:{repeat:`scene`,consume:!0},parking:{when:`stop`,dwellSeconds:.45,maxSpeedMps:.25,containment:`center`}};function zt(e){let t=e.spec.trigger,n=typeof t==`string`?{preset:t}:typeof t==`object`?t:{};return{when:`enter`,action:`event`,repeat:`visit`,vehicles:`player`,...Rt[n.preset??``],...n}}var q=e=>e.spec.stops.map(e=>typeof e==`string`?e:e.target),Bt=()=>({phase:`idle`,inside:!1,departed:!1,qualified:!1,dwell:0,routeDwell:new Map}),J=e=>[{x:e.center.x-e.halfX.x-e.halfY.x,y:e.center.y-e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x-e.halfY.x,y:e.center.y+e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x+e.halfY.x,y:e.center.y+e.halfX.y+e.halfY.y},{x:e.center.x-e.halfX.x+e.halfY.x,y:e.center.y-e.halfX.y+e.halfY.y}];function Vt(e){let t=Math.cos(e.angle),n=Math.sin(e.angle);return{center:e.position,halfX:{x:t*e.lengthPx/2,y:n*e.lengthPx/2},halfY:{x:-n*e.widthPx/2,y:t*e.widthPx/2}}}function Ht(e,t){let n=Math.hypot(e.halfX.x,e.halfX.y),r=Math.hypot(e.halfY.x,e.halfY.y);return{center:e.center,halfX:{x:e.halfX.x*(1+t/n),y:e.halfX.y*(1+t/n)},halfY:{x:e.halfY.x*(1+t/r),y:e.halfY.y*(1+t/r)}}}var Ut=(e,t,n,r,i)=>(!e.requireExit||r)&&(e.when===`stop`?t&&i>=(e.dwellSeconds??.45):n),Wt=(e,t,n,r,i)=>n&&Math.abs(r)<=(t.maxSpeedMps??.25)?e+i:0,Gt=class{registry;measure;publicPosition;localPosition;pickup;awardPoints;stateClasses=new Mt;controls=new It;visits=new Map;credited=new Map;consumed=new Map;visuals=new Map;routes=new Map;reservedObjectives=new Set;declarations=new Map;definitionRoutes=new Set;listeners=new Set;missing=new Set;frameGeometry=null;defaultGeometryFrame;dirty=!0;disposed=!1;unsubscribe;constructor(e,t,n=e=>({...e}),r=e=>({...e}),i,a){this.registry=e,this.measure=t,this.publicPosition=n,this.localPosition=r,this.pickup=i,this.awardPoints=a,this.unsubscribe=e.subscribe(()=>{this.dirty=!0});for(let[t,n]of Object.entries(e.definitions.routes??{}))this.definitionRoutes.add(t),this.route(t,n);for(let[t,n]of Object.entries(e.definitions.objectives??{}))`steps`in n&&(this.definitionRoutes.add(t),this.objective(t,n))}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}beginFrame(){this.disposed||(this.frameGeometry??=new Map,this.frameGeometry.clear(),this.measure||(this.defaultGeometryFrame=new xt))}relocateVehicle(e){for(let t of this.visits.values()){let n=t.get(e);n&&t.set(e,{...n,inside:!1,qualified:!1,position:void 0,angle:void 0,targetPosition:void 0,dwell:0,routeDwell:new Map})}}geometry(e){let t=()=>this.measure?this.measure(e):e instanceof HTMLElement?K(e,this.defaultGeometryFrame):null;return this.frameGeometry?(this.frameGeometry.has(e)||this.frameGeometry.set(e,t()),this.frameGeometry.get(e)):t()}exportRoutes(){if(this.disposed)throw Error(`Playground is disposed`);return Object.fromEntries([...this.routes].filter(([e,t])=>!t.objective&&!t.target&&!this.definitionRoutes.has(e)).map(([e,t])=>[e,structuredClone(t.spec)]))}hasObjective(e){return this.routes.has(e)||this.reservedObjectives.has(e)}reserveObjective(e){if(this.disposed)throw Error(`Playground is disposed`);if(!e.trim())throw Error(`Objective needs an ID`);if(this.hasObjective(e))throw Error(`Objective already exists: ${e}`);this.reservedObjectives.add(e)}releaseObjective(e){this.reservedObjectives.delete(e)}syncObjectives(){this.disposed||this.sync(this.registry.objects.filter(e=>e.spec.enabled!==!1&&e.spec.trigger))}exportObjectives(){return Object.fromEntries([...this.routes].filter(([e,t])=>t.objective&&!t.target&&!this.definitionRoutes.has(e)).map(([e,t])=>{let{stops:n,...r}=t.spec;return[e,{...structuredClone(r),steps:structuredClone(n)}]}))}objective(e,t,n){let{steps:r,...i}=Ee(t),a=this.route(e,{...i,progress:i.progress??`scene`,stops:r},n,!0);return{id:e,get state(){return!a.state.length&&(i.progress??`scene`)===`scene`?Object.freeze([Object.freeze({vehicleId:`scene`,current:0,target:r.length,complete:!1})]):Object.freeze(a.state.map(({vehicleId:e,completed:t,total:n,complete:r})=>Object.freeze({vehicleId:e,current:t,target:n,complete:r})))},reset:()=>a.reset(),dispose:()=>a.dispose()}}emit(e,t,n){let{object:r,...i}=t,a=o({...b(i),...r?{object:r}:{},...`position`in t?{position:this.publicPosition(t.position)}:{}});(n??this.registry.root).dispatchEvent(new CustomEvent(`joyride:${e}`,{bubbles:!0,detail:a}));for(let t of this.listeners)try{t(e,a)}catch(e){this.registry.report(e,n)}}route(e,t,n,r=!1){if(this.disposed)throw Error(`Playground is disposed`);if(!e.trim())throw Error(`Route needs an ID`);if(this.hasObjective(e))throw Error(`Objective already exists: ${e}`);let i=Oe(t),a={id:e,spec:i,target:n,objective:r,visited:new Map,completed:new Set};this.routes.set(e,a);let o=!1;return{id:e,get state(){return[...a.visited].map(([e,t])=>Object.freeze({vehicleId:e,completed:t.size,total:i.stops.length,complete:t.size===i.stops.length}))},reset:()=>{o||this.resetRoute(a)},dispose:()=>{o||this.routes.delete(e),o=!0}}}sync(e){if(!this.dirty)return;this.dirty=!1;let t=[...this.registry.root.querySelectorAll(`[data-jr-route]`)];this.registry.root instanceof Element&&this.registry.root.matches(`[data-jr-route]`)&&t.unshift(this.registry.root),t.push(...[...this.registry.root.querySelectorAll(`[data-jr-objective]`)].filter(e=>e.getAttribute(`data-jr-objective-type`)===null)),this.registry.root instanceof Element&&this.registry.root.matches(`[data-jr-objective]`)&&this.registry.root.getAttribute(`data-jr-objective-type`)===null&&t.unshift(this.registry.root);for(let[e,n]of this.declarations)t.includes(e)||(this.routes.delete(n.id),this.declarations.delete(e),this.missing.delete(n.id));for(let n of t)try{let t=n.getAttribute(`data-jr-objective`)!==null,r=t?Lt.objective:Lt.route,i=n.getAttribute(r.id)??``,a=this.declarations.get(n),o=e.filter(e=>n.contains(e.target)&&(()=>{let t=e.target.closest(`[data-jr-objective]`),r=e.target.closest(`[data-jr-route]`);return(t&&r?t.contains(r)?r:t:t??r)===n})());if(!o.length)continue;let s=o.map(e=>e.id),c=n.getAttribute(r.order)??`ordered`,l=n.getAttribute(r.progress)??(t?`scene`:`vehicle`),u=n.getAttribute(r.event)??void 0,d=a&&this.routes.get(a.id),f=d&&d.visited.size?q(d):s,p=Oe({order:c,progress:l,event:u,stops:f}),m=JSON.stringify({id:i,spec:p});if(a?.signature===m)continue;if(this.hasObjective(i)&&a?.id!==i)throw Error(`Objective already exists: ${i}`);if(a){let e=this.routes.get(a.id);e&&this.resetRoute(e),this.routes.delete(a.id)}this.route(i,p,n,t),this.declarations.set(n,{id:i,signature:m})}catch(e){this.registry.report(e,n)}let n=new Set(e.map(e=>e.target)),r=new Set;for(let t of e){let e=zt(t);if(e.action!==`event`)try{let n=this.actionTarget(t.target,e),i=this.controlTarget(n);i&&r.add(i)}catch(e){this.registry.report(e,t.target)}}this.controls.sync(r);for(let e of this.visits.keys())n.has(e)||(this.visits.delete(e),this.credited.delete(e),this.restore(e))}eligible(e,t,n,r){let i=e.spec.progress===`scene`?`scene`:n.id,a=e.visited.get(i)??new Set,o=q(e);return o.includes(t.id)?o.some(e=>!r.some(t=>t.id===e))?(this.missing.has(e.id)||(this.missing.add(e.id),this.registry.report(Error(`Route ${e.id} is waiting for a missing or disabled stop`),e.target)),!1):(this.missing.delete(e.id),!a.has(t.id)&&(e.spec.order===`any`||o[a.size]===t.id)):!1}step(e,t,n=!0){if(this.disposed)return;let r=Number.isFinite(t)?Math.max(0,t):0,i=this.registry.objects.filter(e=>e.spec.trigger&&e.spec.enabled!==!1);this.sync(i);let a=new Set(e.map(e=>e.id)),o=[];for(let t of i){let i=zt(t),s=t.target;if(!(s instanceof HTMLElement))continue;let c=this.visits.get(s);c||this.visits.set(s,c=new Map);for(let e of c.keys())a.has(e)||c.delete(e);let l=this.geometry(s);for(let a of e){let e=c.get(a.id)??Bt(),u=i.vehicles===`all`||a.player;if(!n||!l||!u||i.suspended){let n={...e,phase:!u||i.suspended||!l?`idle`:e.phase===`dwelling`?`entered`:e.phase,inside:l?e.inside:!1,dwell:0,routeDwell:new Map,position:this.publicPosition(a.position),angle:a.angle,targetPosition:l?this.publicPosition(l.center):void 0};c.set(a.id,n),(n.phase!==e.phase||n.inside!==e.inside)&&this.emit(`trigger:change`,{object:t,vehicle:{id:a.id},position:a.position,speedMps:a.speedMps,state:{inside:n.inside,departed:n.departed,stopped:n.qualified,phase:n.phase}},s);continue}let d=Vt(a),f=J(l),p=e.position&&this.localPosition(e.position),m=i.preset===`pickup`?At(a,l,p?{position:p,angle:e.angle??a.angle,target:e.targetPosition&&this.localPosition(e.targetPosition)}:void 0,r):void 0,h=m&&(!i.containment||i.containment===`overlap`),g=h?m.inside:i.containment===`center`?G(l,a.position):i.containment===`full`?J(d).every(e=>G(l,e)):!!it(J(d),f),_=i.containment===`center`?0:i.containment===`full`?-Math.hypot(a.lengthPx,a.widthPx)/2:a.widthPx/2,v=p&&Math.hypot(a.position.x-p.x,a.position.y-p.y)>.001,y=h?m.contact?.fraction??null:v?at(p,a.position,_,f):null,b=!g&&!e.inside&&y!==null,x=!e.inside&&(g||b),S=i.containment===`center`?!G(l,a.position,i.exitMarginPx??20):!it(J(d),J(Ht(l,i.exitMarginPx??20)));if(e.resetBlocked){S&&c.set(a.id,{...Bt(),departed:!0,position:this.publicPosition(a.position),angle:a.angle,targetPosition:this.publicPosition(l.center)});continue}let C=e.inside?0:y??1,w=m?.contact?.angle??0,T=m?.contact?.velocity??a.speedMps;o.push({object:t,config:i,target:s,vehicle:a,visits:c,previous:e,inside:g,crossed:b,entered:x,outside:S,departed:e.departed||S,arrival:C,pickupAngle:w,pickupSpeed:T,pickupOrigin:m?.contact?.origin,targetPosition:l.center})}}o.sort((e,t)=>e.arrival-t.arrival);for(let e of o){let{object:t,config:n,target:a,vehicle:o,visits:s,previous:c,inside:l,crossed:u,entered:d,outside:f,departed:p}=e,m=[...this.routes.values()].filter(e=>q(e).includes(t.id)),h=Wt(c.dwell,n,l,o.speedMps,r),g={object:t,vehicle:{id:o.id},position:{...o.position},speedMps:o.speedMps,state:{inside:l,departed:p,stopped:c.qualified,phase:d?`entered`:c.phase}};d&&this.emit(`trigger:enter`,g,a);let _=m.filter(e=>this.eligible(e,t,o,i)),v=new Map(c.routeDwell),y=_.filter(e=>{let i=e.spec.stops.find(e=>(typeof e==`string`?e:e.target)===t.id),a=typeof i==`string`?n:{...n,...i},s=Wt(c.routeDwell.get(e.id)??0,a,l,o.speedMps,r);return v.set(e.id,s),Ut(a,l,d,p,s)});for(let e of v.keys())_.some(t=>t.id===e)||v.delete(e);let b=this.credited.get(a)??new Set;this.credited.set(a,b);let x=n.repeat===`scene`?`scene`:o.id,S=n.repeat===`visit`?!c.qualified:!b.has(x),C=!f&&c.qualified,w=!1,T=(m.length?y.length>0:Ut(n,l,d,p,h))&&S;try{let r=!0;if(T&&(r=this.action(a,n),r)){w=!0,b.add(x),C=!f,g.state.stopped=C,g.state.phase=`success`;let r=m.length?y.some(e=>{let r=e.spec.stops.find(e=>(typeof e==`string`?e:e.target)===t.id);return(typeof r==`string`?n.when:r.when??n.when)===`stop`}):n.when===`stop`;n.preset===`pickup`&&t.spec.pickupEffectColor&&this.pickup?.(o.id,{color:t.spec.pickupEffectColor,angle:e.pickupAngle,origin:e.pickupOrigin,velocity:e.pickupSpeed});let i=t.spec.points??0;i>0&&(n.preset===`pickup`||r)&&this.awardPoints?.(this.publicPosition(e.targetPosition),i),this.emit(`trigger:qualify`,g,a),r&&this.emit(`trigger:stop`,g,a),n.event&&this.emit(n.event,g,a),n.consume&&!this.consumed.has(a)&&(this.consumed.set(a,{value:a.style.getPropertyValue(`visibility`),priority:a.style.getPropertyPriority(`visibility`)}),a.style.setProperty(`visibility`,`hidden`))}if(r)for(let e of y)this.credit(e,t,o,g)}catch(e){this.registry.report(e,a)}let E=m.some(e=>e.visited.get(e.spec.progress===`scene`?`scene`:o.id)?.has(t.id)),D=S&&l&&(m.length?_.some(e=>{let r=e.spec.stops.find(e=>(typeof e==`string`?e:e.target)===t.id),i=typeof r==`string`?n:{...n,...r},a=v.get(e.id)??0;return i.when===`stop`&&a>0&&a<(i.dwellSeconds??.45)&&(!i.requireExit||p)}):n.when===`stop`&&h>0&&h<(n.dwellSeconds??.45)&&(!n.requireExit||p)),O=w||E||n.repeat!==`visit`&&b.has(x)||c.phase===`success`&&!d?`success`:D?`dwelling`:l?`entered`:`idle`;g.state.phase=O,(!l&&c.inside||u)&&this.emit(`trigger:leave`,g,a),s.set(o.id,{phase:O,inside:l,departed:p,qualified:C,dwell:h,routeDwell:v,position:this.publicPosition(o.position),angle:o.angle,targetPosition:this.publicPosition(e.targetPosition)}),g.state.stopped=C,(l!==c.inside||p!==c.departed||C!==c.qualified||O!==c.phase)&&this.emit(`trigger:change`,g,a)}let s=new Set;for(let e of this.routes.values())for(let t of e.visited.values())for(let e of t)s.add(e);for(let e of i){let t=e.target;if(!(t instanceof HTMLElement))continue;let n=zt(e),r=[...this.visits.get(t)?.values()??[]],i=s.has(e.id)||n.repeat!==`visit`&&this.credited.get(t)?.size||r.some(e=>e.phase===`success`)?`success`:r.some(e=>e.phase===`dwelling`)?`dwelling`:r.some(e=>e.phase===`entered`)?`entered`:`idle`;this.visual(t,`data-jr-trigger-state`,i),this.visual(t,`data-jr-trigger-departed`,String(r.some(e=>e.departed))),this.stateClasses.apply(t,n,i)}}credit(e,t,n,r){let i=e.spec.progress===`scene`?`scene`:n.id,a=e.visited.get(i)??new Set;a.add(t.id),e.visited.set(i,a);let o=a.size===e.spec.stops.length,s={...r,route:{id:e.id,completed:a.size,total:e.spec.stops.length,complete:o}};this.emit(`route:progress`,s,e.target);let c={...r,objective:{id:e.id,type:`steps`,current:a.size,target:e.spec.stops.length,complete:o}};this.emit(`objective:progress`,c,e.target),o&&!e.completed.has(i)&&(e.completed.add(i),this.emit(`route:complete`,s,e.target),this.emit(`objective:complete`,c,e.target),e.spec.event&&this.emit(e.spec.event,e.objective?c:s,e.target))}actionTarget(e,t){let n=e;if(t.target){let e=[...this.registry.root.querySelectorAll(t.target)];if(this.registry.root instanceof Element&&this.registry.root.matches(t.target)&&e.unshift(this.registry.root),e.length!==1)throw Error(`Trigger action target must resolve to exactly one element`);n=e[0]}if(!(n instanceof HTMLElement))throw Error(`Trigger action target must support native activation`);return n}controlTarget(e){let t=e.matches(`input[type="checkbox"],[role="checkbox"],[role="switch"]`)?e:e.querySelector(Nt);return t instanceof HTMLElement?t:null}action(e,t){if(t.action===`event`)return!0;let n=this.actionTarget(e,t);if(n.matches(`:disabled,[aria-disabled="true"]`))return!1;if(t.action===`click`)return n.click(),!0;let r=this.controlTarget(n);if(!(r instanceof HTMLElement))throw Error(`Checkbox action needs a checkbox or switch target`);if(r.matches(`:disabled,[aria-disabled="true"]`))return!1;let i=r instanceof HTMLInputElement?r.checked:r.getAttribute(`aria-checked`)===`true`;return(t.action===`toggle`||i!==(t.action===`check`))&&r.click(),!0}visual(e,t,n){let r=this.visuals.get(e);r||this.visuals.set(e,r=new Map);let i=r.get(t);i?.applied!==n&&(i?i.applied=n:r.set(t,{original:e.getAttribute(t),applied:n}),e.getAttribute(t)!==n&&e.setAttribute(t,n))}captureState(){return b({visits:this.visits,credited:this.credited,routes:[...this.routes].map(([e,t])=>({id:e,visited:t.visited,completed:t.completed})),consumed:this.consumed,visuals:this.visuals,classes:this.stateClasses.captureState(),controls:this.controls.captureState()})}restoreState(e){let t=b(e);this.reset(),this.visits.clear();for(let[e,n]of t.visits)this.visits.set(e,n);for(let[e,n]of t.credited)this.credited.set(e,n);for(let e of t.routes){let t=this.routes.get(e.id);t&&(t.visited=e.visited,t.completed=e.completed)}for(let[e,n]of t.consumed)this.consumed.set(e,n),e.style.setProperty(`visibility`,`hidden`);for(let[e,n]of t.visuals){this.visuals.set(e,n);for(let[t,r]of n)e.setAttribute(t,r.applied)}this.stateClasses.restoreState(t.classes),this.controls.restoreState(t.controls)}restore(e){if(!(e instanceof HTMLElement))return;this.stateClasses.restore(e);let t=this.consumed.get(e);t&&e.style.visibility===`hidden`&&(t.value?e.style.setProperty(`visibility`,t.value,t.priority):e.style.removeProperty(`visibility`)),this.consumed.delete(e);for(let[t,n]of this.visuals.get(e)??[])e.getAttribute(t)===n.applied&&(n.original===null?e.removeAttribute(t):e.setAttribute(t,n.original));this.visuals.delete(e)}resetRoute(e){e.visited.clear(),e.completed.clear(),this.missing.delete(e.id);for(let t of this.registry.objects)q(e).includes(t.id)&&(this.visits.delete(t.target),this.credited.delete(t.target),this.restore(t.target))}resetObject(e){let t=this.visits.get(e);this.restore(e),this.credited.delete(e);let n=new Map;for(let[e,r]of t??[])r.inside&&n.set(e,{...Bt(),inside:!0,resetBlocked:!0});n.size?this.visits.set(e,n):this.visits.delete(e);let r=this.registry.get(e);if(r?.spec.trigger){let t=this.controlTarget(this.actionTarget(e,zt(r)));t&&this.controls.resetTarget(t)}if(r){for(let e of this.routes.values())if(q(e).includes(r.id)){for(let t of e.visited.values())t.delete(r.id);e.completed.clear(),this.missing.delete(e.id)}}this.frameGeometry?.clear()}reset(){let e=new Map;for(let[t,n]of this.visits){let r=new Map;for(let[e,t]of n)t.inside&&r.set(e,{...Bt(),inside:!0,resetBlocked:!0});r.size&&e.set(t,r)}this.stateClasses.reset(),this.controls.reset(),this.frameGeometry?.clear(),this.defaultGeometryFrame&&=new xt;for(let e of new Set([...this.visits.keys(),...this.consumed.keys(),...this.visuals.keys()]))this.restore(e);this.visits.clear();for(let[t,n]of e)this.visits.set(t,n);this.credited.clear(),this.missing.clear();for(let e of this.routes.values())e.visited.clear(),e.completed.clear()}dispose(){this.disposed||(this.reset(),this.controls.dispose(),this.visits.clear(),this.disposed=!0,this.unsubscribe(),this.routes.clear(),this.reservedObjectives.clear(),this.declarations.clear(),this.definitionRoutes.clear(),this.listeners.clear(),this.frameGeometry=null,this.defaultGeometryFrame=void 0)}},Kt=(e,t)=>e.childNodes.length===1&&e.firstChild===t.node&&t.node.data===t.last,qt=class{registry;values=new Map;disposed=!1;constructor(e){this.registry=e}update(e){if(this.disposed)return;let t=new Set;for(let n of this.registry.objects){let r=n.spec.hud;if(!r||n.spec.enabled===!1)continue;let i=n.target;t.add(i);let a=Jt(r,e),o=this.values.get(i);if(!o||!Kt(i,o)){let e=[...i.childNodes],t=i.ownerDocument.createTextNode(a);i.replaceChildren(t),o={original:e,node:t,last:a},this.values.set(i,o)}else o.last!==a&&(o.node.data=a,o.last=a)}for(let e of this.values.keys())t.has(e)||this.restore(e)}restore(e){let t=this.values.get(e);t&&(Kt(e,t)&&e.replaceChildren(...t.original),this.values.delete(e))}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.values.keys())this.restore(e)}}};function Jt(e,t){let n=e.field===`speed`?t.speedMps:t[e.field];return e.field===`gear`?n==null?`—`:String(n):typeof n!=`number`||!Number.isFinite(n)?`—`:(e.field===`speed`&&(n*=e.unit===`kmh`?3.6:e.unit===`mps`?1:1/.44704),n.toFixed(e.precision??0))}var Yt=class e{registry;zones;entries=new Map;declarations=new Map;dirty=!0;disposed=!1;unsubscribe;unsubscribeZones;constructor(e,t){this.registry=e,this.zones=t,this.unsubscribe=e.subscribe(()=>{this.dirty=!0}),this.unsubscribeZones=t.onEvent((e,t)=>{if(e!==`trigger:qualify`)return;let n=t.object,r=n.spec.trigger;(typeof r==`object`?r.preset:r)===`pickup`&&this.record(`collect`,n,t.vehicle.id)});try{for(let[t,n]of Object.entries(e.definitions.objectives??{}))`type`in n&&this.add(t,n,void 0,!0);this.sync()}catch(e){throw this.dispose(),e}}objective(e,t){if(this.disposed)throw Error(`Playground is disposed`);let n=Ee(t);return`steps`in n?this.zones.objective(e,n):this.add(e,n)}add(t,n,r,i=!1){this.zones.reserveObjective(t);let a={id:t,spec:structuredClone(n),rows:new Map,target:r,definition:i};return this.entries.set(t,a),this.clear(a),{id:t,get state(){return e.state(a)},reset:()=>{this.entries.get(t)===a&&this.clear(a)},dispose:()=>{this.entries.get(t)===a&&this.remove(t)}}}static state(e){return Object.freeze([...e.rows].map(([t,n])=>Object.freeze({vehicleId:t,current:n.current,target:e.spec.type===`score`?e.spec.points:e.spec.count,complete:n.complete})))}clear(e){e.rows.clear(),(e.spec.progress??`scene`)===`scene`&&e.rows.set(`scene`,{current:0,complete:!1,seen:new Set})}remove(e){this.entries.delete(e),this.zones.releaseObjective(e)}sync(){if(!this.dirty||this.disposed)return;this.dirty=!1;let e=[...this.registry.root.querySelectorAll(`[data-jr-objective]`)];this.registry.root instanceof Element&&this.registry.root.matches(`[data-jr-objective]`)&&e.unshift(this.registry.root);let t=e.filter(e=>e.hasAttribute(`data-jr-objective-type`));for(let[e,n]of this.declarations)t.includes(e)||(this.remove(n.id),this.declarations.delete(e));this.zones.syncObjectives();for(let e of t)try{let t=e.getAttribute(`data-jr-objective`)??``,n=e.getAttribute(`data-jr-objective-type`),r=Ee({type:n,...n===`score`?{points:Number(e.getAttribute(`data-jr-objective-points`))}:{count:Number(e.getAttribute(`data-jr-objective-count`))},...e.hasAttribute(`data-jr-objective-targets`)?{targets:e.getAttribute(`data-jr-objective-targets`).split(/[\s,]+/).filter(Boolean)}:{},...e.hasAttribute(`data-jr-objective-progress`)?{progress:e.getAttribute(`data-jr-objective-progress`)}:{},...e.hasAttribute(`data-jr-objective-event`)?{event:e.getAttribute(`data-jr-objective-event`)}:{}}),i=JSON.stringify({id:t,spec:r}),a=this.declarations.get(e);if(a?.signature===i)continue;if(a?.id!==t&&this.zones.hasObjective(t))throw Error(`Objective already exists: ${t}`);a&&this.remove(a.id),this.add(t,r,e),this.declarations.set(e,{id:t,signature:i})}catch(t){this.registry.report(t,e)}}record(e,t,n){if(!(this.disposed||t.spec.enabled===!1))for(let r of[...this.entries.values()]){if(this.entries.get(r.id)!==r)continue;let i=r.spec;if(i.type!==e||i.targets&&!i.targets.includes(t.id))continue;let a=(i.progress??`scene`)===`scene`?`scene`:n;if(!a)continue;let o=r.rows.get(a)??{current:0,complete:!1,seen:new Set};o.complete||o.seen.has(t.id)||(o.seen.add(t.id),o.current=Math.min(i.count,o.current+1),r.rows.set(a,o),this.publish(r,a,o,i.count))}}updateScore(e){if(!this.disposed&&Number.isFinite(e))for(let t of[...this.entries.values()]){if(this.entries.get(t.id)!==t||t.spec.type!==`score`)continue;let n=t.rows.get(`scene`),r=Math.max(0,Math.min(t.spec.points,e));n.complete||r===n.current||(n.current=r,this.publish(t,`scene`,n,t.spec.points))}}publish(e,t,n,r){n.complete=n.current>=r;let i=o({objective:{id:e.id,type:e.spec.type,current:n.current,target:r,complete:n.complete},...t===`scene`?{}:{vehicle:{id:t}}}),a=t=>(e.target??this.registry.root).dispatchEvent(new CustomEvent(`joyride:${t}`,{bubbles:!0,detail:i}));a(`objective:progress`),n.complete&&(a(`objective:complete`),e.spec.event&&a(e.spec.event))}exportObjectives(){if(this.disposed)throw Error(`Playground is disposed`);return{...this.zones.exportObjectives(),...Object.fromEntries([...this.entries].filter(([,e])=>!e.target&&!e.definition).map(([e,t])=>[e,structuredClone(t.spec)]))}}captureState(){return b([...this.entries].map(([e,t])=>({id:e,signature:JSON.stringify(t.spec),rows:t.rows})))}restoreState(e){for(let e of this.entries.values())this.clear(e);for(let t of b(e)){let e=this.entries.get(t.id);e&&JSON.stringify(e.spec)===t.signature&&(e.rows=t.rows)}}reset(){for(let e of this.entries.values())this.clear(e)}dispose(){if(!this.disposed){this.disposed=!0,this.unsubscribe(),this.unsubscribeZones();for(let e of this.entries.keys())this.zones.releaseObjective(e);this.entries.clear(),this.declarations.clear()}}},Xt=class{simulation;project;root;report;applied=new Map;requests=new Set;objects=[];serial=0;nextMeasure=0;disposed=!1;failures=new Map;constructor(e,t,n,r){this.simulation=e,this.project=t,this.root=n,this.report=r}add(e,t={}){if(this.disposed)throw Error(`Playground debris is disposed`);y(t),typeof e==`string`&&this.root.querySelectorAll(e);let n={id:`page-debris-${++this.serial}`,target:typeof e==`string`||e instanceof Element?e:[...e],options:structuredClone(t)};if(typeof n.target!=`string`&&!(n.target instanceof Element)&&[...n.target].some(e=>!(e instanceof Element)))throw TypeError(`Debris targets must be elements`);this.requests.add(n),this.sync(this.objects,!0);let r=()=>!this.disposed&&[...this.requests].some(e=>e.id===n.id);return{id:n.id,reset:()=>{if(r())for(let e of this.applied.values())e.owner===n.id&&e.handle.reset()},gust:e=>{if(r())for(let t of this.applied.values())t.owner===n.id&&t.handle.gust(e)},dispose:()=>{if(r()){for(let e of this.requests)e.id===n.id&&this.requests.delete(e);this.sync(this.objects,!0)}}}}sync(e,t=!1){if(this.disposed)return;let n=performance.now();if(this.objects!==e&&(t=!0),this.objects=e,!t&&n<this.nextMeasure)return;this.nextMeasure=n+200;let r=new Map;for(let t of e){if(t.spec.enabled===!1||!t.target.isConnected||t.spec.debris===!1)continue;let e=t.spec.debris;e&&r.set(t.target,{options:e===!0?{}:e,owner:`html`})}for(let e of this.requests){let t=typeof e.target==`string`?[...this.root instanceof Element&&this.root.matches(e.target)?[this.root]:[],...this.root.querySelectorAll(e.target)]:e.target instanceof Element?[e.target]:e.target;for(let n of t)n.isConnected&&r.set(n,{options:e.options,owner:e.id})}for(let[e,t]of this.applied)r.has(e)||(t.handle.dispose(),this.applied.delete(e),this.failures.delete(e));for(let e of this.failures.keys())r.has(e)||this.failures.delete(e);for(let[e,t]of r){let n=``;try{let r=e.getBoundingClientRect(),i=this.project({x:r.left,y:r.top}),a=this.project({x:r.right,y:r.bottom}),o={x:i.x,y:i.y,width:Math.max(0,a.x-i.x),height:Math.max(0,a.y-i.y)};n=JSON.stringify([t.owner,t.options,...[o.x,o.y,o.width,o.height].map(e=>Math.round(e/4))]);let s=this.applied.get(e);if(s?.signature===n||this.failures.get(e)===n)continue;if(Object.values(o).some(e=>!Number.isFinite(e)))throw RangeError(`Invalid debris source geometry`);if(this.simulation.count-(s?.amount??0)+(t.options.amount??30)>3e3)throw RangeError(`Scene debris budget is 3000 particles`);s?.handle.dispose();let c=this.simulation.scatter(o,t.options);this.failures.delete(e),this.applied.set(e,{signature:n,handle:c,owner:t.owner,amount:t.options.amount??30})}catch(t){this.failures.get(e)!==n&&this.report(t,e),this.failures.set(e,n)}}}gust(e,t){this.applied.get(e)?.handle.gust(t)}reset(e){for(let[t,n]of this.applied)e&&t!==e||n.handle.reset()}captureState(){return{applied:[...this.applied].map(([e,t])=>[e,{...t,handle:t.handle.id}]),requests:[...this.requests],serial:this.serial}}restoreState(e){this.applied.clear();for(let[t,n]of e.applied){let e=this.simulation.get(n.handle);e&&this.applied.set(t,{...n,handle:e})}this.requests=new Set(e.requests),this.serial=Math.max(this.serial,e.serial),this.failures.clear(),this.nextMeasure=0}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.applied.values())e.handle.dispose();this.applied.clear(),this.failures.clear(),this.requests.clear(),this.objects=[]}}};function Zt({id:e,target:t,spec:n}){let r=(t.innerText??t.textContent??``).replace(/\s+/g,` `).trim(),i=t.matches(`img`)?[t]:[...t.querySelectorAll(`img`)],a=i.find(e=>getComputedStyle(e).display!==`none`)??i[0],o=(typeof n.meta?.name==`string`?n.meta.name:``)||t.getAttribute(`aria-label`)||t.getAttribute(`title`)||a?.alt||r||t.id||t.tagName.toLowerCase(),s=[];for(let[e,t]of[[`crushable`,`Crushable`],[`breakable`,`Breakable`],[`burnable`,`Burnable`],[`combustible`,`Combustible`],[`pushable`,`Pushable`],[`solid`,`Wall`],[`liquid`,`Liquid`],[`debris`,`Debris`],[`hud`,`Readout`]])n[e]&&s.push(t);if(n.trigger){let e=typeof n.trigger==`string`?n.trigger:typeof n.trigger==`object`?n.trigger.preset:void 0;s.push(e?e.charAt(0).toUpperCase()+e.slice(1):`Trigger`)}let c=getComputedStyle(t),l=c.backgroundImage?.match(/^url\(["']?(.*?)["']?\)$/)?.[1],u=n.liquid&&typeof n.liquid.color==`string`&&n.liquid.color!==`auto`?n.liquid.color:c.backgroundColor,d,f=t.tagName.toLowerCase()===`svg`?t:t.querySelector(`svg`);if(!a&&f){let e=f.cloneNode(!0);e.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),e.style.opacity=`1`,e.style.color=getComputedStyle(f).color,d=`data:image/svg+xml,${encodeURIComponent(new XMLSerializer().serializeToString(e))}`}let p={image:a?.currentSrc||a?.src||d||l,color:u&&u!==`transparent`&&u!==`rgba(0, 0, 0, 0)`?u:void 0,text:r.slice(0,20)},m=t.getAttribute(`data-jr-crushed`)===null?t.getAttribute(`data-jr-trigger-state`)||(c.visibility===`hidden`?`Hidden`:`Active`):`Crushed`;return Object.freeze({id:e,name:o.slice(0,90),element:`${t.tagName.toLowerCase()}${t.id?`#${t.id}`:t.getAttribute(`data-jr-id`)?`[${t.getAttribute(`data-jr-id`)}]`:``}`,capabilities:Object.freeze(s),preview:Object.freeze(p),state:m,resettable:s.some(e=>![`Wall`,`Texture`,`Readout`].includes(e))})}var Qt=class{registry;renderer;commands;snapshot=Object.freeze([]);notificationQueued=!1;dirty=!0;disposed=!1;listeners=new Set;unsubscribe;constructor(e,t,n){this.registry=e,this.renderer=t,this.commands=n,this.unsubscribe=e.subscribe(this.refresh)}refresh=()=>{this.disposed||(this.dirty=!0,!this.notificationQueued&&this.listeners.size&&(this.notificationQueued=!0,queueMicrotask(()=>{if(this.notificationQueued=!1,!this.disposed)for(let e of this.listeners)e()})))};getSnapshot=()=>{if(!this.dirty||this.disposed)return this.snapshot;let e=this.registry.objects.filter(e=>e.spec.enabled!==!1&&[`crushable`,`breakable`,`burnable`,`combustible`,`pushable`,`solid`,`liquid`,`debris`,`trigger`].some(t=>e.spec[t])).map(Zt);return this.dirty=!1,e.length===this.snapshot.length&&e.every((e,t)=>{let n=this.snapshot[t];return e.id===n.id&&e.name===n.name&&e.element===n.element&&e.state===n.state&&e.capabilities.join(`,`)===n.capabilities.join(`,`)&&e.preview.image===n.preview.image&&e.preview.color===n.preview.color&&e.preview.text===n.preview.text})||(this.snapshot=Object.freeze(e)),this.snapshot};subscribe=e=>(this.listeners.add(e),this.dirty=!0,()=>{this.listeners.delete(e)});getTarget=e=>{if(this.disposed)return null;let t=this.registry.objects.find(t=>t.id===e&&t.spec.enabled!==!1);return t?.target.isConnected?t.target:null};reveal=e=>{let t=this.getTarget(e);return t?(this.renderer.interruptFollow(),t.scrollIntoView({block:`center`,inline:`center`,behavior:`instant`}),this.renderer.flashTargets((e,n)=>{let r=t.getBoundingClientRect(),i=[[r.left,r.top],[r.left+r.width,r.top],[r.left+r.width,r.top+r.height],[r.left,r.top+r.height]].map(([e,t])=>this.renderer.documentFromViewport({x:e,y:t}));e.save(),e.fillStyle=`#fff`,e.beginPath(),i.forEach((t,r)=>r?e.lineTo(t.x-n.x,t.y-n.y):e.moveTo(t.x-n.x,t.y-n.y)),e.closePath(),e.fill(),e.restore()}),!0):!1};reset=e=>{if(this.disposed)return!1;let t=this.commands.reset(e);return this.refresh(),t};remove=e=>{if(this.disposed)return!1;let t=this.commands.remove(e);return this.refresh(),t};dispose(){this.disposed=!0,this.unsubscribe(),this.listeners.clear(),this.snapshot=Object.freeze([])}};function $t(e){switch(e.kind){case`object`:return e.type;case`destructibleDestroyed`:return e.cause??`break`;case`combustionExplosion`:return`explode`;case`crush`:return`crush`;case`impact`:return`hit`;case`scrape`:return null;default:return e}}function en(e,t){let n=$t(t);if(!n)return null;let r=t.element?e.get(t.element):e.objects.find(e=>e.id===t.objectId);if(!r)return null;let i=t.kind===`impact`?t.impact.point:`point`in t?t.point:void 0,a=Object.freeze({object:r,vehicle:t.vehicleId?Object.freeze({id:t.vehicleId}):void 0,point:i&&Object.freeze({...i}),...`points`in t?{points:t.points}:{}});return{name:n,target:r.target,detail:a}}function tn(e,t,n,r){let{sim:i}=e,a=i.car,o=t?.redlineRpm??8e3,s=t?.gear;return{speed:(i.paused?0:P(i.body.velocity))*2.2369362921,rpm:t?.rpm??0,gear:s==null||s===0?`N`:s,maxRpm:Math.ceil(o/1e3)*1e3,redlineRpm:o,hp:a.health,maxHp:a.maxHealth,points:n,totalPoints:r,maxPoints:r??999999}}var nn=class{registry;world;zones;objectives;objects;hud;debrisSources;handles=new Map;ownedVehicles=new Set;removedObjects=new Set;pendingEvents=[];unregister=[];disposed=!1;serial=0;constructor(e,t){this.registry=e,this.world=t,this.zones=new Gt(e,void 0,e=>t.renderer.documentFromViewport(e),e=>t.renderer.viewportFromDocument(e),(e,n)=>t.vehicles.find(t=>t.id===e)?.pickupEffect.trigger(n),(e,n)=>t.awardPoints(e,n));try{this.objectives=new Yt(e,this.zones)}catch(e){throw this.zones.dispose(),e}this.hud=new qt(e),this.debrisSources=new Xt(t.renderer.debris,e=>t.renderer.documentFromViewport(e),e.root,(t,n)=>e.report(t,n)),this.objects=new Qt(e,t.renderer,{reset:e=>this.resetObject(e),remove:e=>this.removeObject(e)});try{this.unregister.push(t.registerStateParticipant(`registry`,e)),this.unregister.push(t.registerStateParticipant(`zones`,this.zones)),this.unregister.push(t.registerStateParticipant(`objectives`,this.objectives)),this.unregister.push(t.registerStateParticipant(`debris-sources`,this.debrisSources)),this.unregister.push(t.registerStateParticipant(`removed-page-objects`,{captureState:()=>new Set(this.removedObjects),restoreState:e=>{this.removedObjects.clear();for(let t of e)this.removedObjects.add(t);this.objects.refresh()}})),this.unregister.push(t.events.subscribe(e=>this.pendingEvents.push(Je(e)))),this.sync()}catch(e){throw this.dispose(),e}}point(e){if(typeof e==`string`){let t=document.querySelector(e);if(!t)throw Error(`Placement target not found: ${e}`);e=t}if(e instanceof Element){if(!e.isConnected)throw Error(`Placement target is not connected`);let t=e.getBoundingClientRect(),n=this.world.renderer.virtualOffset();return{x:t.left+t.width/2+window.scrollX+n.x,y:t.top+t.height/2+window.scrollY+n.y}}if(e){if(!Number.isFinite(e.xPx)||!Number.isFinite(e.yPx))throw RangeError(`Placement must use finite document coordinates`);return{x:e.xPx,y:e.yPx}}let t=this.world.focusVehicle;return t?this.world.renderer.documentPoint(t.sim.body.position):{x:window.scrollX+window.innerWidth/2,y:window.scrollY+window.innerHeight/2}}vehicleConfiguration(e,t){for(let t of Object.keys(e))if(![`id`,`vehicle`,`appearance`,`slots`].includes(t))throw TypeError(`Vehicle configuration does not support ${t}; decorate page elements with ride.bind instead`);if(t&&e.id!==void 0&&e.id!==t.id)throw Error(`A live vehicle ID cannot change`);let n=we(De({vehicle:e.vehicle,...this.registry.vehicleOptions(e.vehicle)},e)),r=t?.sim.car.preset.id===n.vehicle?t.sim.car.preset:this.registry.resolveVehicle(n.vehicle),i=structuredClone(n.slots??{});for(let e of Object.values(i))e&&e.action===`eject`&&(e.liquid=this.registry.resolveLiquid(e.liquid));return{spec:n,preset:r,slots:ve(i)}}applyVehicle(e,t){let{spec:n,preset:r,slots:i}=t;if(!this.world.configureVehicle(e.id,{preset:r===e.sim.car.preset?void 0:r,appearance:n.appearance??`auto`,slots:i}))throw Error(`Vehicle is unavailable`);this.registry.root.dispatchEvent(new CustomEvent(`joyride:vehicle:change`,{bubbles:!0,detail:{vehicle:this.vehicleHandle(e).state}}))}spawnVehicle(e){if(this.disposed)throw Error(`Playground is disposed`);let{at:t,angleDeg:n=0,...r}=e,i=this.vehicleConfiguration(r);if(!Number.isFinite(n))throw RangeError(`Vehicle heading must be finite`);let a=this.point(t),{spec:o,preset:s}=i,c=o.id;if(!c)do c=`jr-vehicle-${++this.serial}`;while(this.world.getVehicle(c));let l=new N;l.setPreset(s);let u=this.world.spawnVehicle({id:c,sim:l,control:{kind:`parked`}});try{return u.sim.body.position=this.world.renderer.worldFromDocument(a),u.sim.body.angle=-n*Math.PI/180,this.ownedVehicles.add(u.id),this.applyVehicle(u,i),this.vehicleHandle(u)}catch(e){throw this.ownedVehicles.delete(u.id),this.handles.delete(u.id),this.world.removeVehicle(u.id),e}}get player(){let e=this.world.playerVehicle;return e?this.vehicleHandle(e):null}getVehicle(e){let t=this.world.getVehicle(e);return t?this.handles.get(t.id)??this.vehicleHandle(t):null}vehicleName(e){try{return this.registry.vehicleName(e.sim.car.preset.id)}catch(n){if(!(n instanceof t))throw n;return e.sim.car.preset.id}}vehicleHandle(e){let t=e.id,n=this.handles.get(t);if(n)return n;let r=!1,i=()=>{let e=this.world.getVehicle(t);if(this.disposed||r||!e)throw Error(`Vehicle is unavailable`);return e},a=()=>{let e=i(),n=structuredClone(e.slots);for(let e of Object.values(n))e&&(e.action===`eject`&&(e.liquid=this.registry.liquidName(e.liquid)),Object.freeze(e));return Object.freeze({id:t,vehicle:this.vehicleName(e),position:Object.freeze({...this.world.renderer.documentPoint(e.sim.body.position)}),speedMps:P(e.sim.body.velocity),health:e.sim.car.health,maxHealth:e.sim.car.maxHealth,appearance:e.appearance,slots:Object.freeze(n)})},o={id:t,get state(){return a()},update:e=>{Te(e);let t=i(),n=e.vehicle===void 0?{vehicle:this.vehicleName(t),appearance:t.appearance,slots:t.slots}:{vehicle:e.vehicle},r=we(De(n,e));this.applyVehicle(t,this.vehicleConfiguration(r,t))},pickupEffect:e=>i().pickupEffect.trigger(e),useSlot:e=>i().useSlot(e),startSlot:e=>i().startSlot(e),stopSlot:e=>i().stopSlot(e),dispose:()=>{r||(r=!0,this.disposed||this.world.removeVehicle(t),this.ownedVehicles.delete(t),this.handles.delete(t))}};return this.handles.set(t,o),o}debris(e,t={}){return this.debrisSources.add(e,t)}resetDebris(e){this.debrisSources.reset(e)}gustDebris(e,t){this.debrisSources.sync(this.registry.objects,!0),this.debrisSources.gust(e,t)}pour(e,t){if(this.disposed)throw Error(`Playground is disposed`);this.world.renderer.addLiquid(this.registry.resolveLiquid(e),{...t,at:this.world.renderer.worldFromDocument(this.point(t.at))})}objective(e,t){return this.objectives.objective(e,t)}route(e,t){return this.zones.route(e,t)}beginFrame(){this.disposed||(this.objectives.sync(),this.zones.beginFrame())}sync(){this.disposed||(this.objectives.sync(),this.debrisSources.sync(this.registry.objects))}step(e,t){this.disposed||(this.zones.step(this.world.vehicles.map(e=>({id:e.id,player:e===this.world.playerVehicle,position:this.world.renderer.viewportFromDocument(this.world.renderer.documentPoint(e.sim.body.position)),speedMps:P(e.sim.body.velocity),velocityMps:{x:e.sim.body.velocity.x,y:-e.sim.body.velocity.y},angle:-e.sim.body.angle,angularVelocity:-e.sim.body.spin,pixelsPerMeter:this.world.renderer.documentScale(),mask:this.world.collisions.vehicleMask(e.sim.car.preset,e.damage),lengthPx:e.sim.car.preset.geometry.lengthM*this.world.renderer.documentScale(),widthPx:e.sim.car.preset.geometry.widthM*this.world.renderer.documentScale()})),e,t),this.flushObjectEvents(),t&&this.objectives.updateScore(this.world.points))}flushObjectEvents(){let e=this.pendingEvents.splice(0);e.length&&this.objects.refresh();for(let t of e){let e=en(this.registry,t);e&&([`crush`,`break`,`ignite`].includes(e.name)&&this.objectives.record(e.name,e.detail.object,e.detail.vehicle?.id),e.target.dispatchEvent(new CustomEvent(`joyride:object:${e.name}`,{bubbles:!0,detail:e.detail})))}}present(e){this.hud.update(e)}resetObject(e){if(this.disposed)return!1;let t=this.registry.objects.find(t=>t.id===e&&t.spec.enabled!==!1);if(!t)return!1;this.world.collisions.resetObject?.(e),this.zones.resetObject(t.target),this.debrisSources.reset(t.target);for(let n=this.pendingEvents.length-1;n>=0;n--)(this.pendingEvents[n].element===t.target||this.pendingEvents[n].objectId===e)&&this.pendingEvents.splice(n,1);return this.objects.refresh(),!0}removeObject(e){if(!this.resetObject(e))return!1;let t=this.registry.objects.find(t=>t.id===e);return this.registry.update(t.target,{enabled:!1}),this.removedObjects.add(t.target),this.sync(),!0}reset(){if(!this.disposed){this.pendingEvents.length=0,this.zones.reset(),this.objectives.reset();for(let e of this.removedObjects)this.registry.get(e)?.spec.enabled===!1&&this.registry.update(e,{enabled:!0});this.removedObjects.clear(),this.sync(),this.world.resetScene(),this.objects.refresh(),this.registry.root.dispatchEvent(new CustomEvent(`joyride:reset`,{bubbles:!0}))}}dispose(){if(!this.disposed){this.disposed=!0,this.objectives.dispose(),this.zones.dispose(),this.hud.dispose(),this.debrisSources.dispose(),this.objects.dispose();for(let e of this.ownedVehicles)this.world.removeVehicle(e);this.ownedVehicles.clear(),this.removedObjects.clear(),this.handles.clear(),this.pendingEvents.length=0;for(let e of this.unregister)e()}}},rn=class{world;page;loop;disposed=!1;resources=new r;constructor(e,t){this.world=e,this.resources.own(()=>e.dispose());try{this.page=t?new nn(t,e):null,this.page&&this.resources.own(()=>this.page.dispose())}catch(e){throw this.resources.dispose(),e}}clock(e,t,n){if(this.disposed)throw Error(`Browser runtime is disposed`);if(this.loop)throw Error(`Browser runtime already has a clock`);return this.loop=new rt(()=>(this.page?.beginFrame(),e()),t,n,1/120,12,e=>{this.page?.registry.report(e);let t=this.world.focusVehicle;t&&this.world.renderer.restorePage(t.sim)},e=>this.world.advanceTime(e)),this.resources.own(()=>this.loop?.stop()),this.loop}dispose(){this.disposed||(this.disposed=!0,this.resources.dispose())}},an=`body[data-jr-virtual-camera]>:not([data-jr-overlay]):not([data-jr-ui]):not([data-jr-touch-controls]):not([data-jr-embed]){translate:var(--joy-ride-scene-x,0px) var(--joy-ride-scene-y,0px)}[data-jr-trigger=parking]{--stop-zone-color:var(--drive-ink,currentColor);box-sizing:border-box;border:2px solid color-mix(in srgb, var(--stop-zone-color) 28%, transparent);background:color-mix(in srgb, var(--stop-zone-color) 3%, transparent);color:color-mix(in srgb, var(--stop-zone-color) 55%, transparent);border-radius:4px;transition:opacity .3s,background .2s}[data-jr-trigger=parking][data-jr-trigger-state=entered],[data-jr-trigger=parking][data-jr-trigger-state=dwelling],[data-jr-trigger=parking][data-jr-trigger-state=success]{background:color-mix(in srgb, var(--stop-zone-color) 8%, transparent)}[data-jr-trigger=parking][data-jr-trigger-reveal=departed]{opacity:0}[data-jr-trigger=parking][data-jr-trigger-reveal=departed][data-jr-trigger-departed=true]:not([data-jr-enabled=false]){opacity:1}@media (prefers-reduced-motion:reduce){[data-jr-trigger=parking]{transition:none}}`;function on(e,t,n,r={x:0,y:0}){let i=Math.max(1,t),a=Math.max(0,e.width*e.height)/(i*i),o=Math.max(.015,Math.min(3,Math.sqrt(a)*.3)),s=Math.hypot(r.x,r.y);return{center:{x:e.x+e.width/2,y:e.y+e.height/2},pixelsPerMetre:i,radiusM:o,amount:Math.max(.003,Math.min(24,a*.4)),color:v(n),age:0,duration:.18+Math.min(.12,o*.04),angle:s>.01?Math.atan2(r.y,r.x):e.x*.17+e.y*.11,drift:s>.01?{x:r.x/s*Math.min(s,3)*.12,y:r.y/s*Math.min(s,3)*.12}:{x:0,y:0}}}var sn=e=>e*e*(3-2*e);function cn(e,t){let n=Math.min(1,e.age/e.duration);e.age=Math.min(e.duration,e.age+Math.max(0,t));let r=e.age/e.duration;if(r<=n)return[];let i=(n+r)*.5,a=e.radiusM*(.14+.86*Math.sqrt(i)),o=e.amount*(sn(r)-sn(n)),s=e.radiusM/e.duration*(1-i)*.8,c=Math.cos(e.angle),l=Math.sin(e.angle);return[[0,0,.64,1],[-.53,.16,.13,.48],[.42,-.38,.1,.42],[.27,.52,.13,.46]].map(([t,n,r,i])=>{let u=t*c-n*l,d=t*l+n*c;return{point:{x:e.center.x+u*a*e.pixelsPerMetre,y:e.center.y+d*a*e.pixelsPerMetre},radiusM:a*i,amount:o*r,color:e.color,flowMps:{x:u*s+e.drift.x,y:d*s+e.drift.y}}})}function ln(e,t,n,r={align:6,meetOrSlice:1}){let i=t/e.width,a=n/e.height;if(r.align===1)return{scaleX:i,scaleY:a,x:-e.x*i,y:-e.y*a};let o=r.align>=2&&r.align<=10?r.align-2:4,s=r.meetOrSlice===2?Math.max(i,a):Math.min(i,a);return{scaleX:s,scaleY:s,x:(t-e.width*s)*(o%3/2)-e.x*s,y:(n-e.height*s)*(Math.floor(o/3)/2)-e.y*s}}function Y(e){if(!e.detached)return e.ink;let t=Math.cos(e.angle),n=Math.sin(e.angle),r=e.ink.width/2,i=e.ink.height/2,a=e.ink.x+r-e.base.x-e.base.width/2,o=e.ink.y+i-e.base.y-e.base.height/2,s=e.base.x+e.base.width/2+e.offset.x+a*t-o*n,c=e.base.y+e.base.height/2+e.offset.y+a*n+o*t,l=Math.abs(t)*r+Math.abs(n)*i,u=Math.abs(n)*r+Math.abs(t)*i;return{x:s-l,y:c-u,width:2*l,height:2*u}}function un(e,t){let{ink:n}=e;if(!e.detached)return n.x<t.x+t.width&&n.x+n.width>t.x&&n.y<t.y+t.height&&n.y+n.height>t.y;let r=e.base.x+e.base.width/2,i=e.base.y+e.base.height/2,a=Math.max(Math.abs(n.x-r),Math.abs(n.x+n.width-r)),o=Math.max(Math.abs(n.y-i),Math.abs(n.y+n.height-i)),s=Math.sqrt(a*a+o*o),c=r+e.offset.x,l=i+e.offset.y;return c-s<t.x+t.width&&c+s>t.x&&l-s<t.y+t.height&&l+s>t.y}function dn(e,t,n,r){let i=k(t,T(e.velocity,-1));e.detached=!0,e.velocity=k(T(e.velocity,.35),k(T(i,.55),T(n,80+Math.min(220,P(i)*.3)))),e.spin=e.spin*.3+r,e.offset=k(e.offset,T(n,2)),e.impactCooldown=.12}function fn(e,t){e.impactCooldown=Math.max(0,e.impactCooldown-t),e.detached&&(e.velocity=T(e.velocity,Math.exp(-1.6*t)),e.offset=k(e.offset,T(e.velocity,t)),e.angle+=e.spin*t,e.spin*=Math.exp(-1.25*t))}function pn(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function mn(e,t,n){let r=-1/0,i=1/0,a={x:0,y:0};for(let o of[`x`,`y`]){let s=n[o],c=s+(o===`x`?n.width:n.height),l=e[o],u=t[o],d=l+(o===`x`?e.width:e.height),f=u+(o===`x`?t.width:t.height);for(let[e,t,n]of[[d-s,f-d,-1],[c-l,l-u,1]]){if(Math.abs(t)<1e-8){if(e<0)return null;continue}let s=-e/t;t>0&&s>r?(r=s,a=o===`x`?{x:n,y:0}:{x:0,y:n}):t<0&&(i=Math.min(i,s))}if(r>i)return null}return r>=0&&r<=1&&r<=i&&i>=0&&(a.x!==0||a.y!==0)?{time:r,normal:a}:null}function hn(e,t){let n=Y(e);if(!pn(n,t))return null;let r=[{amount:t.x-n.x-n.width-.1,normal:{x:-1,y:0}},{amount:t.x+t.width-n.x+.1,normal:{x:1,y:0}},{amount:t.y-n.y-n.height-.1,normal:{x:0,y:-1}},{amount:t.y+t.height-n.y+.1,normal:{x:0,y:1}}].reduce((e,t)=>Math.abs(t.amount)<Math.abs(e.amount)?t:e);return r.normal.x?e.offset.x+=r.amount:e.offset.y+=r.amount,r.normal}function gn(e,t){let n=e.velocity.x*t.x+e.velocity.y*t.y;n>=0||(e.velocity=k(T(e.velocity,.82),T(t,-n*1.1)),e.spin*=-.45)}function _n(e,t,n){if(e.detached)for(let t of n){if(pn(e.ink,t))continue;let n=hn(e,t);n&&gn(e,n)}if(!e.detached||n.length===0){fn(e,t);return}let r=Y(e);fn(e,t);let i=Y(e),a=null;for(let t of n){if(pn(e.ink,t))continue;let n=mn(r,i,t);n&&(!a||n.time<a.time)&&(a={...n,wall:t})}if(a){let t=1-a.time;e.offset.x-=(i.x+i.width/2-r.x-r.width/2)*t,e.offset.y-=(i.y+i.height/2-r.y-r.height/2)*t,hn(e,a.wall),gn(e,a.normal)}for(let t=0;t<3;t++){let t=!1;for(let r of n){if(pn(e.ink,r))continue;let n=hn(e,r);n&&(gn(e,n),t=!0)}if(!t)break}}var vn=new WeakMap;function yn(e){let t=vn.get(e);if(t)return t;let{width:n,height:r,x:i,y:a}=e.source,o=e=>{let t=Math.sin(i*17.13+a*31.71+e*47.29)*43758.5453;return t-Math.floor(t)},s=new Path2D;return s.moveTo(n*(.04+o(1)*.18),r*(.02+o(2)*.08)),s.lineTo(n*(.43+o(3)*.15),r*o(4)*.08),s.lineTo(n*(.82+o(5)*.16),r*(.02+o(6)*.12)),s.lineTo(n*(.9+o(7)*.1),r*(.42+o(8)*.19)),s.lineTo(n*(.78+o(9)*.2),r*(.88+o(10)*.12)),s.lineTo(n*(.36+o(11)*.24),r*(.9+o(12)*.1)),s.lineTo(n*o(13)*.2,r*(.76+o(14)*.2)),s.lineTo(n*o(15)*.1,r*(.29+o(16)*.25)),s.closePath(),vn.set(e,s),s}function bn(e,t){if(t.burnFinished)return;let n=t.ink;if(n.width<=0||n.height<=0)return;let r=t.fragments;if(t.bitmap&&r&&r.length&&Math.abs(t.bitmap.width/2-n.width)<2&&Math.abs(t.bitmap.height/2-n.height)<2&&t.bitmapColor===e.color&&t.bitmapFont===e.font){let e=n.x-(t.fragmentOrigin?.x??n.x),i=n.y-(t.fragmentOrigin?.y??n.y);for(let t of r)t.base.x+=e,t.base.y+=i,t.ink.x+=e,t.ink.y+=i;t.fragmentOrigin=E(n.x,n.y);return}let i=document.createElement(`canvas`);i.width=Math.max(1,Math.ceil(n.width*2)),i.height=Math.max(1,Math.ceil(n.height*2));let a=i.getContext(`2d`,{willReadFrequently:!0});if(!a)return;if(a.save(),a.scale(2,2),e.graphic&&`viewBox`in e.graphic){let t=e.graphic.viewBox.baseVal;if(t.width>0&&t.height>0){let r=ln(t,n.width,n.height,e.graphic.preserveAspectRatio?.baseVal);a.translate(r.x,r.y),a.scale(r.scaleX,r.scaleY);for(let t of e.graphic.querySelectorAll(`path[d]`)){let n=getComputedStyle(t);a.fillStyle=n.fill===`currentcolor`?e.color:n.fill,a.fill(new Path2D(t.getAttribute(`d`)),n.fillRule===`evenodd`?`evenodd`:`nonzero`)}}}else e.graphic?a.drawImage(e.graphic,0,0,n.width,n.height):(a.font=e.font,a.fillStyle=e.color,a.textBaseline=`alphabetic`,a.fillText(t.character,t.base.x-n.x,t.base.y+t.base.height/2+e.baseline-n.y));a.restore();let o=null;try{o=a.getImageData(0,0,i.width,i.height).data}catch(t){if(!e.graphic||`viewBox`in e.graphic)throw t}let s=Math.max(7,Math.min(15,Math.round(n.height*.18)||10)),c=[],l=new Map(r?.map(e=>[`${e.source.x}:${e.source.y}`,e]));for(let e=0;e<n.height;e+=s)for(let t=0;t<n.width;t+=s){let r=Math.min(s,n.width-t),a=Math.min(s,n.height-e),u=!1;for(let n=Math.floor(e*2);n<Math.min(i.height,(e+a)*2)&&!u;n++)for(let e=Math.floor(t*2);e<Math.min(i.width,(t+r)*2);e++)if(!o||o[(n*i.width+e)*4+3]>0){u=!0;break}if(!u)continue;let d={x:n.x+t,y:n.y+e,width:r,height:a},f=l.get(`${t}:${e}`),p=Math.max(1,Math.ceil(r*2)),m=Math.max(1,Math.ceil(a*2)),h=new Uint8Array(p*m);for(let n=0;n<m;n++)for(let r=0;r<p;r++){let a=Math.floor(t*2)+r,s=Math.floor(e*2)+n;a<i.width&&s<i.height&&(h[n*p+r]=o?o[(s*i.width+a)*4+3]:255)}c.push({base:d,ink:{...d},source:{x:t,y:e,width:r,height:a},fireAlpha:h,destroyed:f?.destroyed,burnAmount:f?.burnAmount,burnFinished:f?.burnFinished,damage:f?.damage,bitmap:f?.bitmap,offset:f?.offset??E(),velocity:f?.velocity??E(),angle:f?.angle??0,spin:f?.spin??0,detached:f?.detached??!1,impactCooldown:f?.impactCooldown??0})}t.bitmap=i;let u=document.createElement(`canvas`);u.width=i.width,u.height=i.height,u.getContext(`2d`)?.drawImage(i,0,0);let d=u.getContext(`2d`);for(let e of c)if(e.detached){let t=e.source,n=Math.floor(t.x*2),r=Math.floor(t.y*2);d?.clearRect(n,r,Math.ceil((t.x+t.width)*2)-n,Math.ceil((t.y+t.height)*2)-r)}t.intactBitmap=u,t.fireMaskDirty=!0,t.fragments=c,t.fragmentOrigin=E(n.x,n.y),t.bitmapColor=e.color,t.bitmapFont=e.font}function xn(e,t,n,r,i){if(!t.detached){let n=t.source,r=Math.floor(n.x*2),i=Math.floor(n.y*2);if(e.bitmap){let a=document.createElement(`canvas`);a.width=Math.max(1,Math.ceil(n.width*2)),a.height=Math.max(1,Math.ceil(n.height*2));let o=a.getContext(`2d`);o?.drawImage(e.bitmap,r,i,a.width,a.height,0,0,a.width,a.height),o&&(o.save(),o.globalCompositeOperation=`destination-in`,o.scale(2,2),o.fill(yn(t)),o.restore()),t.bitmap=a}e.intactBitmap?.getContext(`2d`)?.clearRect(r,i,Math.ceil((n.x+n.width)*2)-r,Math.ceil((n.y+n.height)*2)-i),e.fireMaskDirty=!0}dn(t,n,r,i)}function Sn(e,t,n,r){let i=E(t.base.x+t.base.width/2+(t.detached?t.offset.x:0),t.base.y+t.base.height/2+(t.detached?t.offset.y:0)),a=n.x-i.x,o=n.y-i.y,s=Math.cos(t.detached?t.angle:0),c=Math.sin(t.detached?t.angle:0),l=t.source.x+t.source.width/2+a*s+o*c,u=t.source.y+t.source.height/2-a*c+o*s;if(t.fireAlpha){let e=Math.max(1,Math.ceil(t.source.width*2)),n=Math.max(1,Math.ceil(t.source.height*2)),i=1/0,a=0,o=0;for(let r=0;r<n;r+=2)for(let n=0;n<e;n+=2){if(t.fireAlpha[r*e+n]<64)continue;let s=(t.source.x+n/2-l)**2+(t.source.y+r/2-u)**2;s<i&&(i=s,a=n,o=r)}Number.isFinite(i)&&(l=t.source.x+a/2,u=t.source.y+o/2);for(let i=0;i<n;i++)for(let n=0;n<e;n++)(t.source.x+n/2-l)**2+(t.source.y+i/2-u)**2<=r*r&&(t.fireAlpha[i*e+n]=0);t.fireRevision=(t.fireRevision??0)+1}let d=t.detached&&t.bitmap?[t.bitmap]:[e.bitmap,e.intactBitmap];for(let e of d){let n=e?.getContext(`2d`);if(!n)continue;let i=t.detached&&t.bitmap?l-t.source.x:l,a=t.detached&&t.bitmap?u-t.source.y:u;n.save(),n.setTransform?.(1,0,0,1,0,0),n.globalCompositeOperation=`destination-out`,n.beginPath(),n.arc(i*2,a*2,Math.max(1.5,r*2),0,Math.PI*2),n.fill(),n.restore()}return t.detached?t.bitmap&&!t.fireAlpha&&(t.fireRevision=(t.fireRevision??0)+1):e.fireMaskDirty=!0,t.damage=(t.damage??0)+.27+r*.028,!t.fireAlpha&&t.damage>=1||t.fireAlpha?.every(e=>e<32)?(t.destroyed=!0,t.fireAlpha=void 0,t.bitmap=void 0,!0):!1}function Cn(e,t,n){let r=[],i=t.x*.07+t.y*.11,a=e=>n*(.84+.1*Math.sin(e*7+i)+.06*Math.sin(e*17-i*1.7));for(let n of[e.bitmap,e.intactBitmap]){let r=n?.getContext(`2d`);if(r){r.save(),r.setTransform?.(1,0,0,1,0,0),r.globalCompositeOperation=`destination-out`,r.beginPath();for(let n=0;n<64;n++){let i=n*Math.PI*2/64,o=a(i),s=(t.x+Math.cos(i)*o-e.ink.x)*2,c=(t.y+Math.sin(i)*o-e.ink.y)*2;n===0?r.moveTo(s,c):r.lineTo(s,c)}r.closePath(),r.fill(),r.restore()}}e.fireMaskDirty=!0;let o=n*n,s=(n*.68)**2;for(let n of e.fragments??[]){if(n.detached||n.destroyed||!n.fireAlpha)continue;let{base:e}=n,i=Math.max(e.x-t.x,0,t.x-e.x-e.width),c=Math.max(e.y-t.y,0,t.y-e.y-e.height);if(i*i+c*c>=o)continue;let l=Math.max(1,Math.ceil(n.source.width*2)),u=0;for(let r=0;r<n.fireAlpha.length;r++){if(n.fireAlpha[r]<32)continue;let i=e.x+r%l/2-t.x,c=e.y+Math.floor(r/l)/2-t.y,d=i*i+c*c;d<s||d<o&&Math.sqrt(d)<a(Math.atan2(c,i))?n.fireAlpha[r]=0:u++}n.fireRevision=(n.fireRevision??0)+1,u===0&&(n.destroyed=!0,n.fireAlpha=void 0,n.bitmap=void 0,r.push(n))}return r}function X(e){return e.fragments?.length?e.fragments:[e]}function wn(){let e=document.createElement(`span`);return e.dataset.jrTextRun=``,e.style.display=`contents`,e}function Tn(e,t){return{character:e,range:t,base:{x:0,y:0,width:0,height:0},ink:{x:0,y:0,width:0,height:0},offset:E(),velocity:E(),angle:0,spin:0,detached:!1,impactCooldown:0}}function En(e){e.graphic&&e.graphic.style.opacity===`0`&&(e.graphic.style.opacity=e.graphicOpacity??``),e.wrapper.isConnected&&e.wrapper.replaceWith(e.original);for(let t of e.glyphs)t.range.detach()}function Dn(e,t){let n=[],r=new Map,i=e.hud,a=e=>{for(let t=e;t;t=t.parentElement)if(i.has(t))return!0;return!1};for(let[t,n]of[[`pushable`,`pushable`],[`artwork`,`destructible`]])for(let i of e[t]){if(i.closest(`[data-jr-embed]`))continue;let e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT);for(;e.nextNode();){let t=e.currentNode,o=t.parentElement;o&&!a(o)&&t.data.trim()&&o.getClientRects().length&&!o.closest(`[data-jr-embed],[data-jr-text-run],script,style,textarea,select,[contenteditable="true"]`)&&r.set(t,{kind:n,root:i})}}let o=new Intl.Segmenter(void 0,{granularity:`grapheme`});for(let[e,{kind:i,root:a}]of r){if(!e.isConnected)continue;let r=e.parentElement;if(!r)continue;let s=getComputedStyle(r),c=s.font||`${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`,l=t.getContext(`2d`);l&&(l.font=c);let u=l?.measureText(`M`),d=((u?.actualBoundingBoxAscent??parseFloat(s.fontSize)*.8)-(u?.actualBoundingBoxDescent??parseFloat(s.fontSize)*.2))/2,f=wn();e.replaceWith(f),f.append(e);let p=[];for(let{segment:t,index:n}of o.segment(e.data)){if(/^\s+$/u.test(t))continue;let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length);let i=s.textTransform===`uppercase`?t.toLocaleUpperCase():s.textTransform===`lowercase`?t.toLocaleLowerCase():t;p.push(Tn(i,r))}n.push({wrapper:f,original:e,source:e.data,glyphs:p,font:c,color:s.color,baseline:d,letterSpacing:s.letterSpacing,canvasText:!1,kind:i,root:a})}return n}var On=new WeakMap;function kn(e,t=()=>{}){let n=[];if(typeof SVGSVGElement>`u`&&typeof HTMLImageElement>`u`)return n;for(let r of e){let e=[...typeof SVGSVGElement<`u`&&r instanceof SVGSVGElement?[r]:[],...typeof HTMLImageElement<`u`&&r instanceof HTMLImageElement?[r]:[],...r.querySelectorAll(`svg,img`)];for(let i of e){let e=typeof SVGSVGElement<`u`&&i instanceof SVGSVGElement,a=typeof HTMLImageElement<`u`&&i instanceof HTMLImageElement;if(a&&!i.complete){let e=On.get(i);e?e.onReady=t:(On.set(i,{onReady:t}),i.addEventListener(`load`,()=>{On.get(i)?.onReady(),On.delete(i)},{once:!0}))}if(i.closest(`[data-jr-text-run],[data-jr-embed]`)||e&&!i.querySelector(`path[d]`)||a&&(!i.complete||!i.naturalWidth))continue;let o=getComputedStyle(i),s=wn(),c=i.style.opacity;i.style.opacity=`0`,i.replaceWith(s),s.append(i);let l=document.createRange();l.selectNode(i),n.push({wrapper:s,original:i,graphic:i,graphicOpacity:c,source:``,kind:`destructible`,root:r,font:o.font,color:o.color,baseline:0,letterSpacing:`0px`,glyphs:[Tn(``,l)]})}}return n}var An=class{onInvalidate;projection;canvas=document.createElement(`canvas`);layouts=new WeakMap;geometryRevision=0;fontSource=document.fonts;fontMetrics=new Map;fontsChanged=()=>{this.fontMetrics.clear(),this.invalidate(),this.onInvalidate()};constructor(e,t=B){this.onInvalidate=e,this.projection=t,this.fontSource?.addEventListener(`loadingdone`,this.fontsChanged),this.fontSource?.addEventListener(`loadingerror`,this.fontsChanged)}rectInDocument(e,t){return this.projection.viewportRectToDocument(e.getBoundingClientRect(),t)}invalidate(){this.geometryRevision++}clear(){this.layouts=new WeakMap,this.fontMetrics.clear(),this.invalidate()}bounds(e){return this.layouts.get(e)?.rect}dispose(){this.fontSource?.removeEventListener(`loadingdone`,this.fontsChanged),this.fontSource?.removeEventListener(`loadingerror`,this.fontsChanged),this.clear()}measure(e,t,n,r){let i=this.canvas.getContext(`2d`),a=new Map,o=(e,t)=>{if(!e)return``;let n=a.get(e);if(n!==void 0)return n;let r=t??getComputedStyle(e),i=[o(e.parentElement),r.transform,r.rotate,r.scale,r.zoom].join(`|`);return a.set(e,i),i},s=(e,t)=>{let n=`${e}:${t}`,r=this.fontMetrics.get(n);return!r&&i&&(i.font=e,r=i.measureText(t),this.fontMetrics.size>=4096&&this.fontMetrics.clear(),this.fontMetrics.set(n,r)),r};for(let a of e){let e=a.wrapper.parentElement??a.wrapper,c=getComputedStyle(e),l=a.color;a.color=c.color||a.color;let u=c.font||a.font;a.font=u,a.letterSpacing=c.letterSpacing;let d=n(a.root);for(let e of a.glyphs){e.root=a.root,e.breakable=d?!!d.breakable:void 0;let t=e.burnable;if(e.burnable=d?!!d.burnable:void 0,e.burnable===!1&&t!==!1)for(let t of X(e))r(t)}let f=!a.graphic&&e.childNodes?.length===1&&e.firstChild===a.wrapper,p=!a.graphic&&!f?a.wrapper.getClientRects?.():void 0,m=e=>Math.round(e*64)/64,h=p?.length===0?`hidden`:``;if(p?.length)for(let e of p)h+=`${m(e.left-p[0].left)},${m(e.top-p[0].top)},${m(e.width)},${m(e.height)};`;let g=f?this.rectInDocument(e,t):h?this.rectInDocument(a.wrapper,t):void 0,_=g?[this.geometryRevision,u,c.letterSpacing,c.wordSpacing,c.lineHeight,c.textAlign,c.textIndent,c.textTransform,c.whiteSpace,c.writingMode,c.direction,c.fontFeatureSettings,c.transform,c.rotate,c.scale,o(e,c),document.fonts?.status,m(g.width),m(g.height),h].join(`|`):``,v=this.layouts.get(a);if(g&&v?.signature===_){let e=g.x-v.rect.x,t=g.y-v.rect.y;if(v.rect=g,e||t||l!==a.color)for(let n of a.glyphs)n.base.x+=e,n.base.y+=t,n.ink.x+=e,n.ink.y+=t,a.kind===`destructible`&&bn(a,n);continue}g?this.layouts.set(a,{rect:g,signature:_}):this.layouts.delete(a),F(`artwork glyph measures`,a.glyphs.length);let y=s(u,`M`);a.baseline=((y?.actualBoundingBoxAscent??parseFloat(c.fontSize)*.8)-(y?.actualBoundingBoxDescent??0))/2,i&&(i.font=a.font);for(let e of a.glyphs){if(a.graphic){e.base=this.rectInDocument(a.graphic,t),e.ink={...e.base},bn(a,e);continue}let n=e.range.getBoundingClientRect();e.base=this.projection.viewportRectToDocument(n,t);let r=s(a.font,e.character),i=e.base.y+e.base.height/2+a.baseline,o=(r?.actualBoundingBoxLeft??0)+(r?.actualBoundingBoxRight??e.base.width),c=(r?.actualBoundingBoxAscent??e.base.height)+(r?.actualBoundingBoxDescent??0);e.ink=o>0&&c>0?{x:e.base.x-(r?.actualBoundingBoxLeft??0),y:i-(r?.actualBoundingBoxAscent??e.base.height),width:o,height:c}:{...e.base},a.kind===`destructible`&&bn(a,e)}}}};function jn(e){let t=e.tagName.toLowerCase();if(t===`path`){let t=e.getAttribute(`d`);return t?new Path2D(t):null}let n=e.getBBox();if(!n.width||!n.height)return null;let r=new Path2D;if(t===`rect`){let t=e,i=Math.min(n.width/2,t.rx.baseVal.value||t.ry.baseVal.value),a=Math.min(n.height/2,t.ry.baseVal.value||t.rx.baseVal.value);i&&a?r.roundRect(n.x,n.y,n.width,n.height,[{x:i,y:a}]):r.rect(n.x,n.y,n.width,n.height)}else if(t===`circle`||t===`ellipse`)r.ellipse(n.x+n.width/2,n.y+n.height/2,n.width/2,n.height/2,0,0,Math.PI*2);else if(t===`polygon`||t===`polyline`){let t=e.points;if(!t.numberOfItems)return null;let n=t.getItem(0);r.moveTo(n.x,n.y);for(let e=1;e<t.numberOfItems;e++){let n=t.getItem(e);r.lineTo(n.x,n.y)}r.closePath()}else return null;return r}function Mn(e,t,n){if(typeof Path2D>`u`||typeof document>`u`)return null;let r=document.createElement(`canvas`);r.width=n.width,r.height=n.height;let i=r.getContext(`2d`,{willReadFrequently:!0}),a=jn(e),o=e.getScreenCTM();if(!i||!a||!o)return null;i.setTransform(...n.transform);for(let e of t){let t=e.path();if(!t)return null;i.clip(t.outline,t.rule)}let s=new Path2D;s.addPath(a,Pn(o)),i.fill(s,getComputedStyle(e).fillRule);let c=i.getImageData(0,0,n.width,n.height).data,l=new Uint8Array(n.width*n.height);for(let e=0;e<l.length;e++)l[e]=c[e*4+3];return l}var Nn=(e,t)=>({x:e.a*t.x+e.c*t.y+e.e,y:e.b*t.x+e.d*t.y+e.f}),Pn=e=>new DOMMatrix([e.a,e.b,e.c,e.d,e.e,e.f]),Fn=e=>/^url\(\s*["']?#([^"')]+)["']?\s*\)$/.exec(e.trim())?.[1];function In(e,t){let n=Fn(t),r=e.ownerSVGElement,i=n&&[...r?.querySelectorAll(`clipPath`)??[]].find(e=>e.id===n);if(!i)return null;let a=i.getAttribute(`clipPathUnits`)??`userSpaceOnUse`;if(a!==`userSpaceOnUse`&&a!==`objectBoundingBox`)return null;let o=e.getScreenCTM?.();if(!o)return null;let s=o.inverse(),c=a===`objectBoundingBox`?e.getBBox?.():null;if(a===`objectBoundingBox`&&(!c||!c.width||!c.height))return null;let l=[];for(let e of i.querySelectorAll(`*`)){let t=e.tagName.toLowerCase();if(t===`g`)continue;if(![`path`,`rect`,`circle`,`ellipse`,`polygon`,`polyline`].includes(t)||typeof e.isPointInFill!=`function`||typeof e.getScreenCTM!=`function`)return null;let n=getComputedStyle(e);if(n.clipPath!==`none`&&n.clipPath||n.maskImage!==`none`&&n.maskImage)return null;if(n.display===`none`||n.visibility===`hidden`)continue;let r=e.getScreenCTM();if(!r)return null;l.push({element:e,fromOwner:r.inverse().multiply(o),rule:n.clipRule||`nonzero`})}return l.length?{signature:JSON.stringify([i.outerHTML,l.map(({fromOwner:e,rule:t})=>[t,...[e.a,e.b,e.c,e.d,e.e,e.f].map(e=>Math.round(e*1e3)/1e3)])]),path(){let e=l[0].rule;if(l.some(t=>t.rule!==e))return null;let t=new Path2D,n=a===`objectBoundingBox`&&c?new DOMMatrix([c.width,0,0,c.height,c.x,c.y]):new DOMMatrix;for(let e of l){let r=jn(e.element);if(!r)return null;t.addPath(r,Pn(o).multiply(n).multiply(Pn(e.fromOwner).inverse()))}return{outline:t,rule:e}},contains(e){let t=Nn(s,e),n=a===`objectBoundingBox`&&c?{x:(t.x-c.x)/c.width,y:(t.y-c.y)/c.height}:t;return l.some(({element:e,fromOwner:t})=>e.isPointInFill(Nn(t,n)))}}:null}function Ln(e){let t=[];for(let n=e;n;n=n.parentElement){let r=getComputedStyle(n);if(r.maskImage&&r.maskImage!==`none`)return null;let i=r.clipPath;if(i&&i!==`none`){let e=In(n,i);if(!e)return null;t.push(e)}if(n===e.ownerSVGElement)break}return{signature:t.map(e=>e.signature).join(`|`),path:()=>null,contains:e=>t.every(t=>t.contains(e)),rasterize:(e,n)=>Mn(e,t,n)}}var Rn=`joy-ride-auto-paint`,zn=32,Bn=1600,Vn=`[data-jr-embed],[data-jr-ui],[data-jr-overlay],[data-jr-liquid],[data-jr-text-run],[data-jr-auto-paint="false"]`,Hn=new Set([`SCRIPT`,`STYLE`,`LINK`,`META`,`TEMPLATE`,`NOSCRIPT`,`CANVAS`,`IFRAME`,`IMG`,`VIDEO`]);function Un(e,t){let n=document.createElement(`span`).style;return n.cssText=e,t&&(n.removeProperty(`z-index`),n.getPropertyValue(`position`)===`relative`&&n.getPropertyPriority(`position`)===`important`&&n.removeProperty(`position`)),n.cssText}function Wn(e){let t=ue(e);return!t||t.alpha<.65?!1:t.chroma>=.05&&t.lightness>=.2&&t.lightness<=.98}function Gn(e,t,n,r){return e>=8&&t>=8&&e<=Math.min(960,n*.95)&&t<=Math.min(420,r*.65)&&e*t<=Math.min(16e4,n*r*.22)}var Kn=class{onChange;wetColor;root;owned=new Set;verified=new WeakMap;roots=new Set;task=null;timer=null;disposed=!1;geometryRevision=0;observer;resize;constructor(e,t=()=>void 0,n=document){this.onChange=e,this.wetColor=t,this.root=n,this.observer=new MutationObserver(e=>{this.releaseOutsideScope();for(let t of e){let e=t.target instanceof Element?t.target:t.target.parentElement;if(!e)continue;if(e.closest(`defs`)){let t=e.ownerSVGElement;t&&(this.affectsOwned(t)&&this.geometryRevision++,this.enqueue(t));continue}let n=e.closest(Vn);if(n)for(let e of this.owned)n.contains(e)&&this.enqueue(e);else{if(t.type===`attributes`&&t.attributeName===`class`){let n=e=>e.split(/\s+/).filter(e=>e&&e!==`joy-ride-auto-paint`).sort().join(` `);if(n(t.oldValue??``)===n(e.getAttribute(`class`)??``)&&(!this.owned.has(e)||e.classList.contains(`joy-ride-auto-paint`)))continue}t.attributeName===`style`&&this.wetColor(e)&&(e instanceof HTMLElement?e.style.backgroundColor===`transparent`:e instanceof SVGElement&&e.style.fill===`transparent`)||t.attributeName===`style`&&(t.oldValue?.includes(`--joy-ride-z-index`)||e.getAttribute(`style`)?.includes(`--joy-ride-z-index`))&&Un(t.oldValue??``,!0)===Un(e.getAttribute(`style`)??``,!0)||t.type===`childList`&&[...t.addedNodes,...t.removedNodes].every(e=>e instanceof Element&&(e.matches(Vn)||Hn.has(e.tagName)))||(this.affectsOwned(e)&&this.geometryRevision++,this.enqueue(e))}}}),this.resize=new ResizeObserver(e=>{for(let t of e)this.enqueue(t.target)}),this.observer.observe(this.root instanceof Element?this.root:this.root.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:[`class`,`style`,`hidden`,`data-jr-auto-paint`,`data-jr-liquid`,`fill`,`d`,`points`,`x`,`y`,`width`,`height`,`cx`,`cy`,`r`,`rx`,`ry`,`clip-path`,`mask`,`transform`]}),window.addEventListener(`resize`,this.refresh,{passive:!0}),this.root.addEventListener(`load`,this.refresh,!0),this.refresh()}get scopeElement(){return this.root instanceof Element?this.root:this.root.body??this.root.documentElement}contains(e){let t=this.scopeElement;return!!t&&(e===t||t.contains(e))}get elements(){return[...this.owned].filter(e=>e.isConnected&&this.contains(e))}has(e){return this.owned.has(e)}affectsOwned(e){for(let t of this.owned)if(e.contains(t))return!0;return!1}releaseOutsideScope(){let e=!1;for(let t of this.owned)t.isConnected&&this.contains(t)||(this.owned.delete(t),t.classList.remove(Rn),this.resize.unobserve(t),e=!0);e&&this.onChange()}refresh=()=>{let e=this.scopeElement;if(!this.disposed&&e){this.geometryRevision++,this.releaseOutsideScope(),this.roots.clear(),this.task=null;for(let e of this.owned)this.roots.add(e);this.roots.add(e),this.schedule()}};enqueue(e){let t=this.scopeElement;!this.disposed&&t&&this.contains(e)&&!this.roots.has(t)&&(e===t||this.roots.size>64?this.refresh():(this.roots.add(e),this.schedule()))}schedule(){this.timer===null&&(this.timer=window.setTimeout(this.scan,32))}scan=()=>{if(this.timer=null,this.disposed)return;let e=performance.now(),t=new Map,n=0;for(;n++<80&&performance.now()-e<3;){if(!this.task?.node){let e=this.roots.values().next().value;if(!e)break;this.roots.delete(e),this.task={root:e,node:e}}let e=this.task.node,n=!1;if(e.isConnected&&this.contains(e)&&!Hn.has(e.tagName)&&!e.closest(Vn)&&!e.closest(`defs`)){let r=e instanceof HTMLElement,i=typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement,a=e.getBoundingClientRect();n=!0;let o=!1;if((r||i)&&e!==document.body&&e.tagName!==`MAIN`&&Gn(a.width,a.height,innerWidth,innerHeight)&&(!i||a.width>=zn&&a.height>=zn&&a.width*a.height>=Bn)){let t=this.verified.get(e);if(this.owned.has(e)&&t?.revision===this.geometryRevision&&t.width===a.width&&t.height===a.height)o=!0;else{let t=getComputedStyle(e),n=i?t.fill:t.backgroundColor,r=n===`rgba(0, 0, 0, 0)`||n===`transparent`?this.wetColor(e)??n:n;o=t.display!==`none`&&t.visibility===`visible`&&Number(t.opacity)>=.65&&(i||t.backgroundImage===`none`)&&Wn(r)&&(!i||Ln(e)!==null)}o&&this.verified.set(e,{revision:this.geometryRevision,width:a.width,height:a.height})}(this.owned.has(e)||o)&&t.set(e,o)}else this.owned.has(e)&&t.set(e,!1);if(n&&e.firstElementChild)this.task.node=e.firstElementChild;else{let t=e;for(;t&&t!==this.task.root&&!t.nextElementSibling;)t=t.parentElement;this.task.node=t&&t!==this.task.root?t.nextElementSibling:null}}let r=!1;for(let[e,n]of t)n&&!e.classList.contains(`joy-ride-auto-paint`)&&(this.owned.has(e)||this.owned.size<256)?(e.classList.add(Rn),this.owned.add(e),this.resize.observe(e),r=!0):!n&&this.owned.delete(e)&&(this.verified.delete(e),e.classList.remove(Rn),this.resize.unobserve(e),r=!0);r&&this.onChange(),(this.task?.node||this.roots.size)&&this.schedule()};dispose(){this.disposed=!0,this.timer!==null&&window.clearTimeout(this.timer),this.observer.disconnect(),this.resize.disconnect(),window.removeEventListener(`resize`,this.refresh),this.root.removeEventListener(`load`,this.refresh,!0);for(let e of this.owned)e.classList.remove(Rn);this.owned.clear(),this.roots.clear(),this.task=null,this.onChange()}};function qn(e,t,n,r,i){if(C(e.health,e.maxHealth)===`intact`)return;let a=e.rect,o=E(a.x+a.width/2,a.y+a.height/2),s=r??Math.max(D.blastRadiusPx,Math.max(a.width,a.height)*.65+35);if(e.explodedAt!==null&&!e.blastQueued&&(e.blastQueued=!0,n.emitCombustibleExplosion(o,s),i(o)),e.explodedAt!==null){e.blastAge+=t,e.blastAge<D.fireballSeconds&&n.emitSceneFire({key:e,alpha:e.alpha,pixelWidth:e.pixelWidth,pixelHeight:e.pixelHeight,x:a.x,y:a.y,width:a.width,height:a.height,origin:o,farthest:Math.max(1,Math.hypot(a.width,a.height)),...ee(e.blastAge)},t),e.blastAge<.36&&e.blastAge-e.lastBlastEmission>=1/30&&(n.emitCombustibleBlast(o,s,e.blastAge),e.lastBlastEmission=e.blastAge);return}let c=I(e.health,e.maxHealth,a.width,a.height);c&&n.emitSceneFire({key:e,alpha:e.alpha,pixelWidth:e.pixelWidth,pixelHeight:e.pixelHeight,x:a.x,y:a.y,width:a.width,height:a.height,origin:e.origin,farthest:Math.max(1,Math.hypot(a.width,a.height)),...c},t)}var Jn=new Set([`H1`,`H2`,`H3`,`H4`,`H5`,`H6`,`P`,`SPAN`,`STRONG`,`EM`,`A`]);function Yn(e,t,n){let r=Math.max(1,Math.min(1024,Math.ceil(t*2))),i=Math.max(1,Math.min(1024,Math.ceil(n*2))),a=()=>({alpha:new Uint8Array(r*i).fill(255),pixelWidth:r,pixelHeight:i});if(typeof getComputedStyle!=`function`||!Jn.has(e.tagName)||!e.textContent?.trim())return a();let o=getComputedStyle(e).backgroundColor;if(o&&o!==`transparent`&&o!==`rgba(0, 0, 0, 0)`&&o!==`rgb(0 0 0 / 0)`)return a();let s=e.ownerDocument.createElement(`canvas`);s.width=r,s.height=i;let c=s.getContext(`2d`);if(!c)return a();let l=e.getBoundingClientRect(),u=r/Math.max(1,t),d=i/Math.max(1,n);c.textBaseline=`alphabetic`;let f=t=>{if(t.nodeType===Node.TEXT_NODE&&t.textContent){let n=t.parentElement??e,r=getComputedStyle(n),i=parseFloat(r.fontSize)||16,a=parseFloat(r.lineHeight)||i*1.2;c.font=r.font||`${r.fontWeight} ${i}px ${r.fontFamily}`;for(let n=0;n<t.textContent.length;n++){let o=t.textContent[n];if(!o.trim())continue;let s=e.ownerDocument.createRange();s.setStart(t,n),s.setEnd(t,n+1);let f=s.getBoundingClientRect();if(f.width<=0||f.height<=0)continue;let p=i*.22+Math.max(0,a-i)*.5;c.save(),c.scale(u,d),c.fillText(r.textTransform===`uppercase`?o.toUpperCase():o,f.left-l.left,f.bottom-l.top-p),c.restore()}}else for(let e of t.childNodes)f(e)};f(e);let p=c.getImageData(0,0,r,i).data,m=new Uint8Array(r*i),h=0;for(let e=0;e<m.length;e++)m[e]=p[e*4+3],m[e]>32&&h++;return h?{alpha:m,pixelWidth:r,pixelHeight:i}:a()}var Xn=2,Zn=4e6,Qn=24e6,$n=3,er=24,tr=180,nr=e=>!e.detached&&e.base.width>0&&e.base.height>0&&e.offset.x===0&&e.offset.y===0&&e.angle===0,rr=e=>{let t=Math.min(e.ink.x,e.base.x)-Xn,n=Math.min(e.ink.y,e.base.y)-Xn;return{x:t,y:n,width:Math.max(e.ink.x+e.ink.width,e.base.x+e.base.width)+Xn-t,height:Math.max(e.ink.y+e.ink.height,e.base.y+e.base.height)+Xn-n}},ir=(e,t)=>e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y;function ar(e){let t=e.glyphs[0]?.base??{x:0,y:0},n=e.glyphs.length;for(let r of e.glyphs)n=Math.imul(n^Math.round((r.base.x-t.x)*64),2654435761),n=Math.imul(n^Math.round((r.base.y-t.y)*64),2246822519),n=Math.imul(n^Math.round(r.ink.width*64),3266489917);return n}var or=class{layers=new Map;frame=0;builds=0;pixels=0;ratio=1;beginFrame(e){this.frame++,this.builds=0;let t=e.getTransform?.();this.ratio=t?Math.max(.5,Math.min(3,Math.round(Math.hypot(t.a,t.b)*4)/4)):1}draw(e,t,n,r){let i=`${t.font}|${n}|${t.letterSpacing}|${t.baseline}`,a=ar(t),o=this.layers.get(t),s=!o||o.style!==i||o.layout!==a||o.painted.length!==t.glyphs.length;if(s||o.ratio!==this.ratio){if(this.builds<$n){let e=this.build(t,n,i,a,o);if(e)o=e;else if(s)return!1}else if(s)return!1}else this.repair(o,t,n);o.used=this.frame;let c=this.moved(o,t);return e.drawImage(o.canvas,o.x+c.x-r.x,o.y+c.y-r.y,o.width,o.height),!0}endFrame(){for(let[e,t]of this.layers)this.frame-t.used>tr&&this.release(e,t)}clear(){for(let[e,t]of this.layers)this.release(e,t)}get bytes(){return this.pixels*4}moved(e,t){let n=t.glyphs[0]?.base??e.anchor;return{x:n.x-e.anchor.x,y:n.y-e.anchor.y}}release(e,t){this.pixels-=t.canvas.width*t.canvas.height,t.canvas.width=t.canvas.height=0,this.layers.delete(e)}build(e,t,n,r,i){let a=1/0,o=1/0,s=-1/0,c=-1/0;for(let t of e.glyphs){if(t.base.width<=0||t.base.height<=0)continue;let e=rr(t);a=Math.min(a,e.x),o=Math.min(o,e.y),s=Math.max(s,e.x+e.width),c=Math.max(c,e.y+e.height)}if(!(s>a&&c>o))return null;let l=this.ratio,u=Math.floor(a*l)/l,d=Math.floor(o*l)/l,f=Math.ceil((s-u)*l),p=Math.ceil((c-d)*l),m=f*p;if(m>Zn)return null;let h=i?i.canvas.width*i.canvas.height:0;if(this.pixels-h+m>Qn&&!this.evict(m-h,e))return null;let g=i?.canvas??document.createElement(`canvas`),_=i?.context??g.getContext(`2d`);if(!_)return null;this.pixels+=m-h,g.width=f,g.height=p;let v={canvas:g,context:_,style:n,layout:r,anchor:{...e.glyphs[0]?.base??{x:0,y:0}},painted:new Uint8Array(e.glyphs.length),x:u,y:d,width:f/l,height:p/l,ratio:l,used:this.frame};_.setTransform(l,0,0,l,-u*l,-d*l),_.font=e.font,_.fillStyle=t,_.textAlign=`left`,_.textBaseline=`alphabetic`,`letterSpacing`in _&&(_.letterSpacing=e.letterSpacing);for(let t=0;t<e.glyphs.length;t++){let n=e.glyphs[t];nr(n)&&(this.paint(_,e,n),v.painted[t]=1)}return this.layers.set(e,v),this.builds++,F(`text layer builds`),v}repair(e,t,n){let r=0;for(let n=0;n<t.glyphs.length;n++)e.painted[n]!==+!!nr(t.glyphs[n])&&r++;if(!r)return;if(r>er&&this.builds<$n){this.build(t,n,e.style,e.layout,e);return}let i=e.context,a=this.moved(e,t);i.setTransform(e.ratio,0,0,e.ratio,-(e.x+a.x)*e.ratio,-(e.y+a.y)*e.ratio);for(let n=0;n<t.glyphs.length;n++){let r=t.glyphs[n],a=+!!nr(r);if(e.painted[n]===a)continue;let o=rr(r);i.save(),i.beginPath(),i.rect(o.x,o.y,o.width,o.height),i.clip(),i.clearRect(o.x,o.y,o.width,o.height),e.painted[n]=a;for(let n=0;n<t.glyphs.length;n++){let r=t.glyphs[n];e.painted[n]&&ir(o,rr(r))&&this.paint(i,t,r)}i.restore()}F(`text layer repairs`,r)}paint(e,t,n){e.fillText(n.character,n.base.x,n.base.y+n.base.height/2+t.baseline)}evict(e,t){let n=[...this.layers].filter(([e,n])=>e!==t&&n.used<this.frame).sort((e,t)=>e[1].used-t[1].used);for(let[t,r]of n){if(this.pixels+e<=Qn)break;this.release(t,r)}return this.pixels+e<=Qn}},Z=32,Q=64,sr=8,cr=64,lr=192,ur=60,dr=class{colors;canvas=null;context=null;slots=new Map;free=[];rows=0;next=0;frame=0;updates=0;nextPhase=0;constructor(e){this.colors=e}beginFrame(){this.frame++,this.updates=0}prepare(e,t,n){let r=e.bitmap;if(!r||r.width>30||r.height>30)return;let i=this.slots.get(e);if(!i){if(this.updates>=lr)return;let t=this.allocate();if(t===null)return;i={index:t,bitmap:r,revision:-1,tint:-2,phase:this.nextPhase,used:0},this.nextPhase=(this.nextPhase+.61803398875)%1,this.slots.set(e,i)}i.used=this.frame;let a=-1;if(t<1){let[e,r,o]=this.colors.rgb(n),s=Math.max(0,Math.min(1,Math.round(t*32+i.phase-.5)/32));a=Math.round(e*s)<<16|Math.round(r*s)<<8|Math.round(o*s)}let o=e.fireRevision??0;i.bitmap===r&&i.revision===o&&i.tint===a||this.updates>=lr&&i.tint!==-2||(this.paint(i,r,a),i.bitmap=r,i.revision=o,i.tint=a)}draw(e,t){let n=this.slots.get(t);if(!n||n.tint===-2||n.used!==this.frame||n.bitmap!==t.bitmap)return!1;let r=n.index%Q*Z+1,i=Math.floor(n.index/Q)*Z+1;return e.drawImage(this.canvas,r,i,n.bitmap.width,n.bitmap.height,0,0,t.source.width,t.source.height),!0}endFrame(){for(let[e,t]of this.slots)this.frame-t.used>ur&&(this.slots.delete(e),this.free.push(t.index))}clear(){this.slots.clear(),this.free=[],this.next=0,this.rows=0,this.canvas&&(this.canvas.width=this.canvas.height=0),this.canvas=this.context=null}get bytes(){return this.canvas?this.canvas.width*this.canvas.height*4:0}allocate(){let e=this.free.pop();return e===void 0?this.next>=this.rows*Q&&!this.grow()?null:this.next++:e}grow(){if(this.rows>=cr)return!1;let e=Math.min(cr,this.rows+Math.max(sr,this.rows)),t=document.createElement(`canvas`);t.width=2048,t.height=e*Z;let n=t.getContext(`2d`);return n?(this.canvas&&n.drawImage(this.canvas,0,0),this.canvas&&(this.canvas.width=this.canvas.height=0),this.canvas=t,this.context=n,this.rows=e,!0):!1}paint(e,t,n){let r=this.context,i=e.index%Q*Z,a=Math.floor(e.index/Q)*Z;r.save(),r.beginPath(),r.rect(i,a,Z,Z),r.clip(),r.clearRect(i,a,Z,Z),r.drawImage(t,i+1,a+1),n>=0&&(r.globalCompositeOperation=`source-in`,r.fillStyle=`rgb(${n>>16} ${n>>8&255} ${n&255})`,r.fillRect(i,a,Z,Z)),r.restore(),this.updates++,F(`fragment atlas updates`)}},fr=pe;function pr(e){let t=getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`||t.visibility===`collapse`)return null;let n=1;for(let r=e;r;r=r.parentElement){let i=Number.parseFloat((r===e?t:getComputedStyle(r)).opacity);n*=Number.isFinite(i)?i:1}let r=e.style?.getPropertyValue?.(`--splatter-background-color`)?.trim(),i=typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement,a=fr(r||(i?t.fill:t.backgroundColor));return!a||a.alpha<=0||n<=0||!i&&t.backgroundImage!==`none`?null:{color:a.color,opacity:a.alpha*n,distanceM:30,material:_(`paint`)}}function mr(e,t){let n=getComputedStyle(e);if(n.display===`none`||n.visibility===`hidden`||n.visibility===`collapse`)return null;let r=t.kind,i=h[r];if(!i)return null;let a=1;for(let t=e;t;t=t.parentElement){let r=Number.parseFloat((t===e?n:getComputedStyle(t)).opacity);a*=Number.isFinite(r)?r:1}let o=t.color&&t.color!==`auto`?t.color:null,s=typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement,c=o?pe(typeof o==`string`?o:`rgb(${o.join(` `)})`):s||n.backgroundImage===`none`?pe(s?n.fill:n.backgroundColor):null,l=c?.alpha?c:null,u=l?l.color.match(/\d+/g).slice(0,3).map(Number):o&&typeof o==`string`?v(o):i.color,d=Math.max(0,Math.min(1,(t.opacity??1)*a*(l?.alpha??1))),f=t.distanceM??i.treadDistanceM;return{kind:r,color:u,opacity:d,deformation:t.deformation??i.deformation,distanceM:f,paint:i.family===`paint`?{color:`rgb(${u.join(` `)})`,opacity:d,distanceM:f,material:_(r)}:null}}var hr=[`background-color`,`background-image`,`border-top-color`,`border-right-color`,`border-bottom-color`,`border-left-color`],gr=[`fill`],_r=e=>e===`background-image`?`none`:`transparent`,vr=new WeakMap;function yr(e){let t=vr.get(e);if(t){t.users++;return}let n=e.style,r={users:1,position:n.getPropertyValue(`position`),positionPriority:n.getPropertyPriority(`position`),zIndex:n.getPropertyValue(`z-index`),zIndexPriority:n.getPropertyPriority(`z-index`),positioned:getComputedStyle(e).position===`static`};vr.set(e,r),r.positioned&&n.setProperty(`position`,`relative`,`important`),n.setProperty(`z-index`,ke(`foreground`),`important`)}function br(e){let t=vr.get(e);if(!t||--t.users)return;vr.delete(e);let n=e.style;n.getPropertyValue(`z-index`)===ke(`foreground`)&&(t.zIndex?n.setProperty(`z-index`,t.zIndex,t.zIndexPriority):n.removeProperty(`z-index`)),t.positioned&&n.getPropertyValue(`position`)===`relative`&&(t.position?n.setProperty(`position`,t.position,t.positionPriority):n.removeProperty(`position`))}var xr=class{element;authored=new Map;sourceCache=null;paintCache=null;position=null;zIndex=null;positioned=!1;svgHost=null;hiddenProperties;constructor(e){this.element=e;let t=typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement;this.hiddenProperties=t?gr:hr,t?(this.svgHost=e.ownerSVGElement,this.svgHost&&yr(this.svgHost)):(this.position={value:e.style.getPropertyValue(`position`),priority:e.style.getPropertyPriority(`position`)},this.zIndex={value:e.style.getPropertyValue(`z-index`),priority:e.style.getPropertyPriority(`z-index`)},this.positioned=getComputedStyle(e).position===`static`,this.positioned&&e.style.setProperty(`position`,`relative`,`important`),e.style.setProperty(`z-index`,ke(`foreground`),`important`));for(let t of this.hiddenProperties)this.authored.set(t,{value:e.style.getPropertyValue(t),priority:e.style.getPropertyPriority(t)});this.hide()}hide(){for(let e of this.hiddenProperties)this.element.style.setProperty(e,_r(e),`important`)}readSource(e){let t=`${this.styleSignature()}|${JSON.stringify(e)}`;if(this.sourceCache?.signature===t)return this.sourceCache.value;let n=this.withSource(()=>mr(this.element,e));return this.sourceCache={signature:`${this.styleSignature()}|${JSON.stringify(e)}`,value:n},n}readPaintSource(){let e=this.styleSignature();if(this.paintCache?.signature===e)return this.paintCache.value;let t=this.withSource(()=>pr(this.element));return this.paintCache={signature:this.styleSignature(),value:t},t}styleSignature(){let e=``;for(let t=this.element;t;t=t.parentElement)e+=`${t.getAttribute(`class`)}|${t.getAttribute(`style`)}|${t.getAttribute(`fill`)}|`;return e}withSource(e){for(let e of this.hiddenProperties){let t=this.authored.get(e),n=this.element.style.getPropertyValue(e);n!==_r(e)&&(t.value=n,t.priority=this.element.style.getPropertyPriority(e)),t.value?this.element.style.setProperty(e,t.value,t.priority):this.element.style.removeProperty(e)}try{return e()}finally{this.hide()}}dispose(){this.svgHost&&br(this.svgHost),typeof SVGGeometryElement<`u`&&this.element instanceof SVGGeometryElement||(this.element.style.getPropertyValue(`z-index`)===ke(`foreground`)&&(this.zIndex?.value?this.element.style.setProperty(`z-index`,this.zIndex.value,this.zIndex.priority):this.element.style.removeProperty(`z-index`)),this.positioned&&this.element.style.getPropertyValue(`position`)===`relative`&&(this.position?.value?this.element.style.setProperty(`position`,this.position.value,this.position.priority):this.element.style.removeProperty(`position`)));for(let e of this.hiddenProperties){let t=this.authored.get(e);this.element.style.getPropertyValue(e)===_r(e)&&(t.value?this.element.style.setProperty(e,t.value,t.priority):this.element.style.removeProperty(e))}}};function Sr(e,t){let{width:n,height:r,corners:i}=e;if(t.x<0||t.y<0||t.x>n||t.y>r)return!1;for(let e=0;e<4;e++){let a=i[e],o=e===1||e===2?n-t.x:t.x,s=e>=2?r-t.y:t.y;if(a.x>0&&a.y>0&&o<a.x&&s<a.y&&((o-a.x)/a.x)**2+((s-a.y)/a.y)**2>1)return!1}return!0}var Cr=new WeakMap,wr=new WeakMap,Tr=[`d`,`points`,`x`,`y`,`width`,`height`,`cx`,`cy`,`r`,`rx`,`ry`];function Er(e,t,n){let r=n.map(n=>{let[r=`0`,i=r]=n.split(/\s+/),a=(e,t)=>Math.max(0,(parseFloat(e)||0)*(e.endsWith(`%`)?t/100:1));return{x:a(r,e),y:a(i,t)}}),[i,a,o,s]=r,c=Math.min(1,e/Math.max(1,i.x+a.x),e/Math.max(1,s.x+o.x),t/Math.max(1,i.y+s.y),t/Math.max(1,a.y+o.y));return{width:e,height:t,corners:r.map(e=>({x:e.x*c,y:e.y*c}))}}function Dr(e,t,n=B,r){let i=n.viewportRectToDocument(e.getBoundingClientRect(),t);if(!i.width||!i.height)return null;let a=getComputedStyle(e),o=typeof HTMLElement<`u`&&e instanceof HTMLElement?e:null,s=o?.offsetWidth||i.width,c=o?.offsetHeight||i.height,l=o&&typeof DOMMatrixReadOnly<`u`?K(o,r):null,u=l?n.viewportRectToDocument({left:l.center.x,top:l.center.y,width:0,height:0},t):null,d=n.scale,f={shape:Er(s,c,[a.borderTopLeftRadius||`0`,a.borderTopRightRadius||`0`,a.borderBottomRightRadius||`0`,a.borderBottomLeftRadius||`0`]),box:l&&u?{center:{x:u.x,y:u.y},halfX:{x:l.halfX.x/d,y:l.halfX.y/d},halfY:{x:l.halfY.x/d,y:l.halfY.y/d}}:{center:{x:i.x+i.width/2,y:i.y+i.height/2},halfX:{x:i.width/2,y:0},halfY:{x:0,y:i.height/2}}};if(typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement){let t=Ln(e);if(!t)return null;let n=e.getBoundingClientRect(),r=e.getScreenCTM();if(!r||typeof e.isPointInFill!=`function`)return null;let a=r.inverse();f.visibleSignature=t.signature;let o=Math.max(1,Math.ceil(n.width*2)),l=Math.max(1,Math.ceil(n.height*2)),u=JSON.stringify([t.signature,Tr.map(t=>e.getAttribute(t)),getComputedStyle(e).fillRule,o,l,r.a,r.b,r.c,r.d]);f.rasterize=(r,a,o)=>{let s=JSON.stringify([u,r,o,i.width,i.height,Math.round((i.x-a.x)*16),Math.round((i.y-a.y)*16)]),c=wr.get(e);if(c?.signature===s)return c.footprint;let l=r*i.width/(o*n.width),d=r*i.height/(o*n.height),f=r*(.5+(i.x-a.x)/o),p=r*(.5+(i.y-a.y)/o),m=Math.max(0,Math.floor(f)),h=Math.max(0,Math.floor(p)),g=Math.min(r,Math.ceil(f+n.width*l)),_=Math.min(r,Math.ceil(p+n.height*d));if(g<=m||_<=h)return null;let v;try{v=t.rasterize(e,{width:g-m,height:_-h,transform:[l,0,0,d,f-n.left*l-m,p-n.top*d-h]})}catch{return null}if(!v)return null;let y=new Uint8Array(r*r),b=0;for(let e=h;e<_;e++){let t=v.subarray((e-h)*(g-m),(e-h+1)*(g-m));y.set(t,e*r+m);for(let e of t)b+=e/255}let x={mask:y,coverage:b/y.length};return wr.set(e,{signature:s,footprint:x}),F(`svg liquid mask builds`),x};let d;f.contains=r=>{let i=Or(f,r),p=n.left+i.x/s*n.width,m=n.top+i.y/c*n.height;if(d||(d=Cr.get(e),d?.signature!==u&&(d=void 0)),!d){let r=null;try{r=t.rasterize(e,{width:o,height:l,transform:[2,0,0,2,-n.left*2,-n.top*2]})}catch{}d={signature:u,width:o,height:l,alpha:r},Cr.set(e,d),F(`svg collision mask builds`)}if(d.alpha){let e=Math.floor((p-n.left)*2),t=Math.floor((m-n.top)*2);return e>=0&&e<d.width&&t>=0&&t<d.height&&d.alpha[t*d.width+e]>=128}return e.isPointInFill({x:a.a*p+a.c*m+a.e,y:a.b*p+a.d*m+a.f})&&t.contains({x:p,y:m})}}return f}function Or(e,t){let{center:n,halfX:r,halfY:i}=e.box,a=r.x*i.y-r.y*i.x;if(Math.abs(a)<1e-4)return{x:-1/0,y:-1/0};let o=t.x-n.x,s=t.y-n.y;return{x:((o*i.y-s*i.x)/a+1)*e.shape.width/2,y:((s*r.x-o*r.y)/a+1)*e.shape.height/2}}var kr=(e,t)=>e.contains?.(t)??Sr(e.shape,Or(e,t)),Ar=new WeakMap;function jr(e){let t=e.liquidSource,n=e.geometry;if(!t&&!e.source||!n)return null;let r=Ar.get(e),i=e.rect,a=window.devicePixelRatio;if(r?.geometry===n&&r.source===e.source&&r.liquidSource===t&&r.dpr===a&&r.bounds.x===i.x&&r.bounds.y===i.y&&r.bounds.width===i.width&&r.bounds.height===i.height)return r.seed;let o=e.source?.color.match(/[\d.]+/g)?.slice(0,3).map(Number),s=t?.kind??`paint`,c=t?.color??(o?.length===3?o:h.paint.color),l={opacity:t?h[s].alpha*t.opacity:e.source?.opacity??1,deformation:t?.deformation??h.paint.deformation,distanceM:t?.distanceM??e.source?.distanceM??30},u={key:e.element,kind:s,color:c,profile:l,bounds:i,signature:JSON.stringify([s,n.shape,n.box,n.visibleSignature,c,l,a,typeof SVGGeometryElement<`u`&&e.element instanceof SVGGeometryElement?[`d`,`points`,`x`,`y`,`width`,`height`,`cx`,`cy`,`r`,`rx`,`ry`].map(t=>e.element.getAttribute(t)):null]),contains:e=>kr(n,e),rasterize:n.rasterize};return Ar.set(e,{geometry:n,source:e.source,liquidSource:t,dpr:a,bounds:i,seed:u}),F(`liquid seed descriptors`),u}function Mr(e,t){return t.map(t=>{for(let n=e.liquidElements.length-1;n>=0;n--){let{element:r,source:i,geometry:a}=e.liquidElements[n];if(i&&a&&!e.liquidBackings.has(r)&&kr(a,t))return i}return null})}function Nr(e,t,n,r){let i=[];for(let t of e.liquidElements){let e=jr(t);e&&i.push(e)}let a=t.syncElementLiquids(i);for(let[t,n]of e.liquidBackings)a.has(t)||(n.dispose(),e.liquidBackings.delete(t));for(let t of i){if(!a.get(t.key))continue;let n=t.key,r=e.liquidBackings.get(n);r||(r=new xr(n),e.liquidBackings.set(n,r))}}var Pr=new WeakMap,Fr=[`transition`,`transition-property`,`transition-duration`,`transition-timing-function`,`transition-delay`,`transition-behavior`];function Ir(e){let t=Pr.get(e);if(!t){let n=Fr.map(t=>({key:t,value:e.style.getPropertyValue(t),priority:e.style.getPropertyPriority(t)}));e.style.setProperty(`transition`,`none`,`important`),t={count:0,restore(){for(let{key:t,value:r,priority:i}of n)r?e.style.setProperty(t,r,i):e.style.removeProperty(t)}},Pr.set(e,t)}t.count++;let n=!1;return()=>{n||(n=!0,--t.count===0&&(t.restore(),Pr.delete(e)))}}function Lr(e){return e.kind===`pushable`?e.glyphs.some(e=>e.detached||e.offset.x!==0||e.offset.y!==0||e.angle!==0):e.glyphs.some(e=>e.burnFinished||(e.burnAmount??0)>0||e.fireAge!==void 0||e.fragments?.some(e=>e.detached||e.destroyed||e.burnFinished||(e.burnAmount??0)>0||(e.damage??0)>0))}function Rr(e,t){e.canvasText!==t&&(e.canvasText=t,e.wrapper.style.color=t?`transparent`:``,e.wrapper.style.webkitTextFillColor=t?`transparent`:``)}var zr=new Map;function Br(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.max(4,Math.ceil(e.base.height*.4)),a=e.base.width+i*2,o=e.base.height+i*2,s=[e.character,t.font,n,t.letterSpacing,t.baseline,e.base.width,e.base.height,r].join(`|`),c=zr.get(s);if(!c){zr.size>=512&&zr.clear(),c=document.createElement(`canvas`),c.width=Math.max(1,Math.ceil(a*r)),c.height=Math.max(1,Math.ceil(o*r));let l=c.getContext(`2d`);l&&(l.scale(r,r),l.font=t.font,l.fillStyle=n,l.textAlign=`left`,l.textBaseline=`alphabetic`,`letterSpacing`in l&&(l.letterSpacing=t.letterSpacing),l.fillText(e.character,i,i+e.base.height/2+t.baseline)),zr.set(s,c),F(`pushable sprite builds`)}return{sprite:c,width:a,height:o,pad:i}}function Vr(e,t,n,r){let{runs:i,layout:a,burnSprites:o,textLayers:s,fragmentAtlas:c,fade:l}=r;e.save(),s.beginFrame(e);let u={x:t.x-20,y:t.y-20,width:n.width+40,height:n.height+40};c.beginFrame();for(let e of i)if(e.kind===`destructible`){for(let t of e.glyphs)if(!t.burnFinished&&t.bitmap)for(let n of t.fragments??[]){if(!n.detached||n.destroyed||n.burnFinished||!n.bitmap||!un(n,u))continue;let t=n.burnAmount??0;c.prepare(n,t?1-.97*Math.min(1,t/.7):1,e.color)}}let d=e.getTransform?.(),f=e.globalAlpha;e.textAlign=`left`,e.textBaseline=`alphabetic`;for(let r of i){if(!r.graphic){let e=Lr(r);if(Rr(r,e),!e)continue}let i=a(r);if(i&&(i.x+i.width<t.x-20||i.x>t.x+n.width+20||i.y+i.height<t.y-20||i.y>t.y+n.height+20)&&!r.glyphs.some(e=>e.detached||e.fragments?.some(e=>e.detached)))continue;let p=!1;if(r.kind===`pushable`){let n=getComputedStyle(r.wrapper.parentElement??r.wrapper).color||r.color;e.font=r.font,e.fillStyle=n,`letterSpacing`in e&&(e.letterSpacing=r.letterSpacing),p=s.draw(e,r,n,t)}for(let i of r.glyphs){if(r.kind===`destructible`){if(i.burnFinished||!i.bitmap)continue;if(((i.fragments??[]).some(e=>!e.detached&&!e.destroyed&&!e.burnFinished)||r.graphic&&i.fireAge!==void 0&&i.fireAge<(i.fireTotalSeconds??0))&&i.intactBitmap){let a=i.ink;if(a.x+a.width>=t.x-20&&a.x<=t.x+n.width+20&&a.y+a.height>=t.y-20&&a.y<=t.y+n.height+20){let n=i.burnAmount??0;e.save(),r.graphic||(e.globalAlpha*=W(n));let s=r.graphic&&i.fireAge!==void 0&&i.fireOrigin?o.getRadialBurn(i.intactBitmap,{originX:(i.fireOrigin.x-a.x)*i.intactBitmap.width/a.width,originY:(i.fireOrigin.y-a.y)*i.intactBitmap.height/a.height,farthest:Math.hypot(i.intactBitmap.width,i.intactBitmap.height),age:i.fireAge,spreadSeconds:i.fireSpreadSeconds??0,burnSeconds:i.fireBurnSeconds??m.burnSeconds},i.fireMaskRevision??0):n?o.get(i.intactBitmap,1-.97*Math.min(1,n/.7),r.color,i.fireMaskRevision??0,i.fireMaskDirty):i.intactBitmap;e.drawImage(s,a.x-t.x,a.y-t.y,a.width,a.height),e.restore()}}let a=!1;for(let n of i.fragments??[]){if(!n.detached||n.destroyed||n.burnFinished||!un(n,u))continue;let s=n.burnAmount??0,p=W(s),m=1-.97*Math.min(1,s/.7);if(n.bitmap&&d){let i=Math.cos(n.angle),u=Math.sin(n.angle),h=n.base.width/2,g=n.base.height/2,_=n.base.x+n.offset.x-t.x+h,v=n.base.y+n.offset.y-t.y+g,y=_-h*i+g*u,b=v-h*u-g*i;if(e.setTransform(d.a*i+d.c*u,d.b*i+d.d*u,d.c*i-d.a*u,d.d*i-d.b*u,d.a*y+d.c*b+d.e,d.b*y+d.d*b+d.f),e.globalAlpha=f*p*l,a=!0,c.draw(e,n))continue;let x=s?o.get(n.bitmap,m,r.color,n.fireRevision??0):n.bitmap;e.drawImage(x,0,0,n.source.width,n.source.height);continue}let h=i.bitmap,g=s&&h?o.get(h,m,r.color,i.fireMaskRevision??0,i.fireMaskDirty):h;a&&d&&(e.setTransform(d),e.globalAlpha=f,a=!1),e.save(),e.globalAlpha*=p*l,e.translate(n.base.x+n.offset.x-t.x+n.base.width/2,n.base.y+n.offset.y-t.y+n.base.height/2),e.rotate(n.angle),e.translate(-n.base.width/2,-n.base.height/2),e.clip(yn(n));let _=n.source;e.drawImage(g??i.bitmap,_.x*2,_.y*2,_.width*2,_.height*2,0,0,_.width,_.height),e.restore()}a&&d&&(e.setTransform(d),e.globalAlpha=f);continue}if(i.base.width<=0||i.base.height<=0)continue;let a=i.base.x+i.offset.x-t.x,s=i.base.y+i.offset.y-t.y;if(!(a+i.base.width<-40||a>n.width+40||s+i.base.height<-40||s>n.height+40)){if(i.detached){e.save(),e.globalAlpha*=l,e.translate(a+i.base.width/2,s+i.base.height/2),e.rotate(i.angle);let{sprite:t,width:n,height:o,pad:c}=Br(i,r,String(e.fillStyle));e.drawImage(t,-i.base.width/2-c,-i.base.height/2-c,n,o),e.restore()}else p&&nr(i)||e.fillText(i.character,a,s+i.base.height/2+r.baseline)}}}s.endFrame(),c.endFrame(),e.restore()}var $=(e,t)=>e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y;function Hr(e,t,n){e.save(),e.fillStyle=`#fff`;for(let r of n.crushables)r.element instanceof HTMLElement&&n.crushed.has(r.element)||e.fillRect(r.rect.x-t.x,r.rect.y-t.y,r.rect.width,r.rect.height);for(let r of n.combustibles)r.explodedAt===null&&e.fillRect(r.rect.x-t.x,r.rect.y-t.y,r.rect.width,r.rect.height);for(let r of n.runs)if(r.kind===`destructible`){for(let n of r.glyphs)if(!n.burnFinished){(n.fragments??[]).some(e=>!e.detached&&!e.destroyed&&!e.burnFinished)&&n.intactBitmap&&e.drawImage(n.intactBitmap,n.ink.x-t.x,n.ink.y-t.y,n.ink.width,n.ink.height);for(let r of n.fragments??[]){if(!r.detached||r.destroyed||r.burnFinished)continue;let n=Y(r);e.fillRect(n.x-t.x,n.y-t.y,n.width,n.height)}}}e.restore()}function Ur(e,t,n,r){if(typeof HTMLImageElement<`u`){let i=r.projection.scale;for(let a of r.crushed){if(!r.hasCrushedPaint(a))continue;let o=a instanceof HTMLImageElement?[a]:a.querySelectorAll(`img`);for(let s of o){if(!s.complete||!s.naturalWidth)continue;let o=K(s);if(!o)continue;let c=r.projection.viewportRectToDocument({left:o.center.x,top:o.center.y,width:0,height:0},r.offset),l=c.x-t.x,u=c.y-t.y;l<-200||u<-200||l>n.width+200||u>n.height+200||(e.save(),e.globalAlpha=Number(getComputedStyle(a).opacity||1),e.transform(o.halfX.x/i,o.halfX.y/i,o.halfY.x/i,o.halfY.y/i,l,u),e.drawImage(s,-1,-1,2,2),e.restore())}}}Vr(e,t,n,r)}function Wr(e,t,n,r,i,a,o=[]){t.save();let s=(e,n,r,i,a,o,s=!1)=>{if(a<=0||(t.globalAlpha=a,t.fillStyle=`rgba(22, 24, 27, 0.82)`,t.beginPath(),t.roundRect(e,n,r,5,2),t.fill(),t.fillStyle=`#f4f4f5`,s&&(t.globalAlpha=a*(.48+.52*(.5+.5*Math.sin(performance.now()*.012)))),t.beginPath(),t.roundRect(e+1,n+1,(r-2)*Math.max(0,Math.min(1,i)),3,1),t.fill(),!o))return;t.globalAlpha=a,t.font=`600 9px ui-monospace, monospace`,t.textAlign=`left`,t.textBaseline=`middle`;let c=t.measureText(o).width;t.fillStyle=`rgba(22, 24, 27, 0.82)`,t.beginPath(),t.roundRect(e+r+4,n-3,c+8,11,2),t.fill(),t.fillStyle=`#f4f4f5`,t.fillText(o,e+r+8,n+2.5)};for(let t of e.combustibles){if(t.explodedAt!==null||t.health<=0||!t.element.isConnected)continue;let e=t.healthBarAlpha();if(e<=0)continue;let{rect:i}=t,a=Math.min(72,Math.max(36,i.width*.8)),o=i.x+(i.width-a)/2-n.x,c=i.y+i.height+15-n.y;o+a<0||o>r.width||c+5<0||c>r.height||s(o,c,a,t.healthFraction,e,`${Math.ceil(t.health)} HP`)}for(let t of i?[i,...o]:o){let o=t.sim;if(o.mode!==`car`||!a||o.car.explodedAt!==null)continue;let c=e.hoveredVehicleId===t.id,l=k(a.documentPoint(o.body.position),a.carVisualOffset(o)),u=a.documentScale(),d=o.car.preset.geometry,f=(Math.abs(Math.sin(o.body.angle))*d.lengthM+Math.abs(Math.cos(o.body.angle))*d.widthM)*u/2,p=Math.min(72,Math.max(36,d.lengthM*u*.55)),m=l.x-p/2-n.x,h=l.y+f+15-n.y;if(m+p<0||m>r.width||h+5<0||h>r.height)continue;let g=t!==i||t.controlSource!==`player`?o.car.healthBarAlpha():e.showHealthBars?c?1:o.car.healthBarAlpha():0;g>0&&s(m,h,p,o.car.healthFraction,g,`${Math.ceil(o.car.health)} HP`)}t.restore()}function Gr(e,t,n,r){let i=r.sceneScroll(),a=r.viewportSize(),o={x:i.x,y:i.y,width:a.width,height:a.height};t.save(),t.lineWidth=1.5,t.strokeStyle=`rgba(0, 174, 204, 0.55)`,t.setLineDash([8,6]),t.strokeRect(3,3,a.width-6,a.height-6),t.setLineDash([]),t.strokeStyle=`#e69b19`;for(let n of e.walls)$(o,n.rect)&&t.strokeRect(n.rect.x-i.x,n.rect.y-i.y,n.rect.width,n.rect.height);t.strokeStyle=`#00b8a9`,t.fillStyle=`rgba(0,184,169,.12)`,t.font=`10px ui-monospace, monospace`;for(let n of e.liquidElements){if(!n.source||!$(o,n.rect))continue;let{x:r,y:a,width:s,height:c}=n.rect;t.fillRect(r-i.x,a-i.y,s,c),t.strokeRect(r-i.x,a-i.y,s,c),t.fillStyle=`#007f74`,t.fillText(e.autoPaintElements?.includes(n.element)?`AUTO PAINT`:`PAINT`,r-i.x+4,a-i.y+12),t.fillStyle=`rgba(0,184,169,.12)`}t.strokeStyle=`#f47734`;for(let n of e.combustibles)n.explodedAt===null&&$(o,n.rect)&&t.strokeRect(n.rect.x-i.x,n.rect.y-i.y,n.rect.width,n.rect.height);t.strokeStyle=`#bd4add`;for(let n of e.runs)for(let e of n.glyphs){if(e.burnFinished)continue;let r=n.kind===`destructible`?(e.fragments??[]).filter(e=>!e.destroyed&&!e.burnFinished).map(Y):[Y(e)];for(let e of r)$(o,e)&&t.strokeRect(e.x-i.x,e.y-i.y,e.width,e.height)}let s=e.mask,c=r.documentScale(),l=k(r.screen(n.body.position),r.carVisualOffset(n)),u=E(Math.cos(n.body.angle),-Math.sin(n.body.angle)),d=E(-u.y,u.x),f=s.lengthM*c/2,p=s.widthM*c/2,m=(e,t)=>k(l,k(T(u,e),T(d,t))),h=[m(-f,-p),m(f,-p),m(f,p),m(-f,p)];t.strokeStyle=`rgba(0, 174, 204, 0.25)`,t.setLineDash([5,4]),t.beginPath(),h.forEach((e,n)=>n?t.lineTo(e.x,e.y):t.moveTo(e.x,e.y)),t.closePath(),t.stroke(),t.setLineDash([]),t.strokeStyle=`#00d9e8`,t.lineWidth=1.35,t.beginPath();let{columns:g,rows:_,solid:v}=s.alpha,y=(e,n)=>{t.moveTo(e.x,e.y),t.lineTo(n.x,n.y)};for(let e=0;e<_;e++)for(let t=0;t<g;t++){let n=e*g+t;if(!v[n])continue;let r=(2*t/g-1)*f,i=(2*(t+1)/g-1)*f,a=(2*e/_-1)*p,o=(2*(e+1)/_-1)*p;e!==0&&v[n-g]||y(m(r,a),m(i,a)),t!==g-1&&v[n+1]||y(m(i,a),m(i,o)),e!==_-1&&v[n+g]||y(m(i,o),m(r,o)),t!==0&&v[n-1]||y(m(r,o),m(r,a))}t.stroke(),t.restore()}function Kr(e,t,n){if(!e.burning.size&&!e.runs.some(e=>e.graphic&&e.glyphs.some(e=>e.fireAge!==void 0&&e.fireAge<(e.fireTotalSeconds??0))))return;let r=n.sceneFireDue?.(t)??!0,i=new Map;for(let t of e.runs){let n=e.burnLifetime(t.root);if(n!==void 0)for(let e of t.glyphs)for(let t of X(e))i.set(t,n)}for(let[a,o]of[...e.burning]){let s=i.get(a)??e.destructibleBurnSeconds??o.profile.burnSeconds,c=s===1/0,l=c?m.burnSeconds:s;o.age=c?Math.min(o.age+t,l*.42):o.age+t;let u=Math.min(1,o.age/l);if(a.burnAmount=u,u<1&&a.detached&&r){let e=Y(a),r=E(e.x+e.width/2,e.y+e.height/2),i=Math.max(1,Math.ceil(a.source?.width*2||e.width*2)),s=Math.max(1,Math.ceil(a.source?.height*2||e.height*2)),c={key:a,alpha:a.fireAlpha??Uint8Array.of(255),pixelWidth:a.fireAlpha?i:1,pixelHeight:a.fireAlpha?s:1,x:a.base.x+(a.detached?a.offset.x:0),y:a.base.y+(a.detached?a.offset.y:0),width:a.base.width,height:a.base.height,angle:a.detached?a.angle:0,origin:r,age:o.age,farthest:Math.max(1,Math.hypot(e.width,e.height)/2),spreadSeconds:Math.min(.35,o.profile.spreadSeconds*.1),burnSeconds:l,smokeRate:o.profile.smokePerSecond,revision:a.fireRevision};n.emitSceneFire(c,t)}u>=1&&(a.burnFinished=!0,a.fireAlpha=void 0,a.bitmap=void 0,e.burning.delete(a),e.flameExposure.delete(a))}for(let r of e.runs)if(r.kind===`destructible`){for(let i of r.glyphs){let a=X(i),o=a.filter(e=>!e.detached&&!e.destroyed),s=o.find(t=>e.burning.has(t));if((s||r.graphic&&i.fireAge!==void 0)&&i.intactBitmap){let a=s?e.burning.get(s):void 0,c=e.burnLifetime(r.root)??e.destructibleBurnSeconds??a?.profile.burnSeconds??i.fireBurnSeconds??m.burnSeconds,l=c===1/0,u=l?m.burnSeconds:c,d=i.fireSpreadSeconds??(r.graphic?Math.min(.25,(a?.profile.spreadSeconds??m.spreadSeconds)*.1):Math.min(1.2,(a?.profile.spreadSeconds??m.spreadSeconds)*.55)),f=r.graphic?u*1.02+d:u+(a?.profile.spreadSeconds??0)*.7;if(i.fireAge===void 0&&(i.fireBurnSeconds=u,i.fireSpreadSeconds=d,i.fireSmokeRate=a?.profile.smokePerSecond,i.fireTotalSeconds=f),i.fireAge=l?Math.min((i.fireAge??0)+t,f*.42):(i.fireAge??0)+t,i.fireOrigin??=(()=>{let e=s?Y(s):i.ink;return E(e.x+e.width/2,e.y+e.height/2)})(),i.fireMaskBitmap!==i.intactBitmap||i.fireMaskDirty||!i.fireMaskAlpha){let e=i.intactBitmap,t;try{t=e.getContext(`2d`)?.getImageData(0,0,e.width,e.height).data}catch(e){if(!r.graphic||`viewBox`in r.graphic)throw e}if(t||r.graphic&&!(`viewBox`in r.graphic)){let n=new Uint8Array(e.width*e.height);for(let e=0;e<n.length;e++)n[e]=t?t[e*4+3]:255;i.fireMaskAlpha=n,i.fireMaskBitmap=e,i.fireMaskDirty=!1,i.fireMaskRevision=(i.fireMaskRevision??0)+1}}if(i.fireMaskAlpha&&i.fireAge<f&&n.emitSceneFire({key:i,alpha:i.fireMaskAlpha,pixelWidth:i.intactBitmap.width,pixelHeight:i.intactBitmap.height,x:i.ink.x,y:i.ink.y,width:i.ink.width,height:i.ink.height,origin:i.fireOrigin,age:i.fireAge,farthest:Math.max(1,Math.hypot(i.ink.width,i.ink.height)),spreadSeconds:d,burnSeconds:r.graphic?u:f,smokeRate:i.fireSmokeRate??m.smokePerSecond,revision:i.fireMaskRevision},t),r.graphic&&!l&&i.fireAge>=f)for(let t of o)t.burnFinished=!0,e.burning.delete(t),e.flameExposure.delete(t)}else if(i.intactBitmap)i.fireAge!==void 0&&(i.fireAge=void 0,i.fireOrigin=void 0,i.fireMaskAlpha=void 0,i.fireMaskBitmap=void 0,i.fireMaskDirty=!1);else for(let i of o){let a=e.burning.get(i);if(!a||!i.fireAlpha)continue;let o=e.burnLifetime(r.root)??e.destructibleBurnSeconds??a.profile.burnSeconds,s=o===1/0?m.burnSeconds:o;if(a.age>=s)continue;let c=Y(i);n.emitSceneFire({key:i,alpha:i.fireAlpha,pixelWidth:Math.max(1,Math.ceil(i.source.width*2)),pixelHeight:Math.max(1,Math.ceil(i.source.height*2)),x:i.base.x,y:i.base.y,width:i.base.width,height:i.base.height,origin:E(c.x+c.width/2,c.y+c.height/2),age:a.age,farthest:Math.max(1,Math.hypot(c.width,c.height)/2),spreadSeconds:Math.min(.35,a.profile.spreadSeconds*.1),burnSeconds:s,smokeRate:a.profile.smokePerSecond,revision:i.fireRevision},t)}i.burnAmount=r.graphic&&i.fireAge!==void 0?Math.min(1,i.fireAge/Math.max(.01,i.fireTotalSeconds??1)):o.length?o.reduce((e,t)=>e+(t.burnAmount??0),0)/o.length:0,i.burnFinished=a.every(e=>e.destroyed||e.burnFinished)&&!(r.graphic&&i.fireAge!==void 0&&i.fireAge<(i.fireTotalSeconds??0)),i.burnFinished&&(i.bitmap=void 0,i.intactBitmap=void 0,i.fireMaskAlpha=void 0,i.fireMaskBitmap=void 0,i.fireMaskDirty=!1,i.fireMaskRevision=void 0,i.fireOrigin=void 0,i.fireAge=void 0,i.fireBurnSeconds=void 0,i.fireSpreadSeconds=void 0,i.fireSmokeRate=void 0,i.fireTotalSeconds=void 0)}r.root&&r.glyphs.every(e=>e.burnFinished)&&e.burned.add(r.root)}}var qr=class{flameExposure=new Map;flameTouched=new Set;flameGlyphHeat=new Map;flameGlyphTouched=new Set;flameSpreadTouched=new Set;burning=new Map;burned=new Set;spreadElapsed=0;heatBounds=new Map;heatGeneration=0;state(){return{flameExposure:this.flameExposure,flameTouched:this.flameTouched,flameGlyphHeat:this.flameGlyphHeat,flameGlyphTouched:this.flameGlyphTouched,flameSpreadTouched:this.flameSpreadTouched,burning:this.burning,burned:this.burned,spreadElapsed:this.spreadElapsed,heatGeneration:this.heatGeneration}}loadState(e){this.flameExposure=e.flameExposure,this.flameTouched=e.flameTouched,this.flameGlyphHeat=e.flameGlyphHeat,this.flameGlyphTouched=e.flameGlyphTouched,this.flameSpreadTouched=e.flameSpreadTouched,this.burning=e.burning,this.burned=e.burned,this.spreadElapsed=e.spreadElapsed,this.heatGeneration=e.heatGeneration,this.heatBounds.clear()}reset(){this.flameExposure.clear(),this.flameTouched.clear(),this.flameGlyphHeat.clear(),this.flameGlyphTouched.clear(),this.flameSpreadTouched.clear(),this.burning.clear(),this.burned.clear(),this.spreadElapsed=0,this.heatBounds.clear(),this.heatGeneration=0}get measuredBoundsCount(){return this.heatBounds.size}measuredBounds(e){return this.heatBounds.get(e)?.rect}removePiece(e){this.flameExposure.delete(e),this.flameTouched.delete(e),this.flameSpreadTouched.delete(e),this.burning.delete(e),this.heatBounds.delete(e)}extinguishPiece(e){this.burning.delete(e),this.flameExposure.delete(e)}directContact(e,t,n,r,i,a){if(this.burning.has(e))return;this.flameTouched.add(e);let o=(this.flameExposure.get(e)??0)+n;this.flameExposure.set(e,o),t&&(this.flameGlyphTouched.add(t),this.flameGlyphHeat.set(t,(this.flameGlyphHeat.get(t)??0)+n));let s=i(t?.root,r);Math.max(o,t?this.flameGlyphHeat.get(t)??0:0)+1e-6<s.ignitionSeconds||(this.burning.set(e,{age:0,profile:s}),a(t?.root),t&&this.flameGlyphHeat.delete(t))}removeGlyph(e){this.flameGlyphHeat.delete(e),this.flameGlyphTouched.delete(e);for(let t of X(e))this.removePiece(t)}syncBounds(e,t){let n=++this.heatGeneration;for(let r of e)if(t(r))for(let e of r.glyphs)for(let t of X(e))t.destroyed||t.burnFinished||this.heatBounds.set(t,{rect:Y(t),seen:n});for(let[e,t]of this.heatBounds)t.seen!==n&&this.heatBounds.delete(e)}burningSources(){let e=[];for(let[t,n]of this.burning){if(t.destroyed||t.burnFinished)continue;let r=Y(t);e.push({point:E(r.x+r.width/2,r.y+r.height/2),radiusPx:n.profile.spreadRadiusPx,spreadSeconds:n.profile.spreadSeconds,profile:ge(n.profile),bounds:r})}return e}expose(e,t,n,r,i,a){this.syncBounds(n,r);let o=new Map;for(let e of n)for(let t of e.glyphs)for(let e of X(t))o.set(e,t);let s=new Map;for(let[n,r]of this.heatBounds){if(this.burning.has(n))continue;let a=o.get(n);if(!a)continue;let c=i(a.root,m),l=0,u;for(let n of e.near(r.rect)){let e=oe(t,n,r.rect,c.spreadSeconds);e>l&&(l=e,u=n.profile)}l>0&&s.set(n,{heat:l,profile:u})}for(let[e,{heat:t,profile:n}]of s){let r=o.get(e),s=i(r.root,n??m),c=(this.flameExposure.get(e)??0)+t*s.ignitionSeconds;this.flameExposure.set(e,c),this.flameSpreadTouched.add(e),c+1e-6>=s.ignitionSeconds&&(this.burning.set(e,{age:0,profile:s}),a(r.root))}}advance(e,t,n,r,i,a){if(this.spreadElapsed+=e,this.spreadElapsed>=.03333333333333333){let e=this.spreadElapsed;for(let[t,n]of this.flameGlyphHeat){if(this.flameGlyphTouched.has(t))continue;let r=Math.max(0,n-e*.12);r===0||t.burnFinished?this.flameGlyphHeat.delete(t):this.flameGlyphHeat.set(t,r)}this.flameGlyphTouched.clear();for(let[t,n]of this.flameExposure){if(this.flameTouched.has(t)||this.flameSpreadTouched.has(t))continue;let r=Math.max(0,n-e*.2);r===0?this.flameExposure.delete(t):this.flameExposure.set(t,r)}this.flameTouched.clear(),this.flameSpreadTouched.clear(),this.burning.size?this.syncBounds(n,r):this.heatBounds.clear(),this.spreadElapsed=0}Kr({runs:n,burning:this.burning,flameExposure:this.flameExposure,burned:this.burned,burnLifetime:i,destructibleBurnSeconds:a},e,t)}};function Jr(e){return!e||e===`transparent`||/^rgba\([^,]+,[^,]+,[^,]+,\s*0(?:\.0+)?\s*\)$/.test(e)||/^rgba?\([^)]*\/\s*0(?:\.0+)?%?\s*\)$/.test(e)}function Yr(e){return{filled:!!e.backgroundImage&&e.backgroundImage!==`none`||!Jr(e.backgroundColor),border:[[`borderTopWidth`,`borderTopStyle`,`borderTopColor`],[`borderRightWidth`,`borderRightStyle`,`borderRightColor`],[`borderBottomWidth`,`borderBottomStyle`,`borderBottomColor`],[`borderLeftWidth`,`borderLeftStyle`,`borderLeftColor`]].some(([t,n,r])=>parseFloat(e[t])>0&&e[n]!==`none`&&!Jr(e[r]))}}function Xr(e,t,n){let r=Yr(n);if(!r.filled&&!r.border)return null;let i=Math.max(1,Math.min(512,Math.ceil(e.width))),a=Math.max(1,Math.min(512,Math.ceil(e.height))),o=new Uint8Array(i*a),s=[parseFloat(n.borderTopWidth)||0,parseFloat(n.borderRightWidth)||0,parseFloat(n.borderBottomWidth)||0,parseFloat(n.borderLeftWidth)||0];for(let n=0;n<a;n++)for(let c=0;c<i;c++){let l={x:e.x+(c+.5)/i*e.width,y:e.y+(n+.5)/a*e.height};if(kr(t,l)){if(r.filled)o[n*i+c]=255;else{let e=Or(t,l);(e.x<s[3]||e.x>t.shape.width-s[1]||e.y<s[0]||e.y>t.shape.height-s[2])&&(o[n*i+c]=255)}}}return{alpha:o,pixelWidth:i,pixelHeight:a}}var Zr=class{surfaces=new Map;get size(){return this.surfaces.size}captureState(){return[...this.surfaces.values()].map(e=>({...e}))}restoreState(e){this.reset();for(let t of e){let e={...t,alpha:t.alpha.slice()};this.surfaces.set(e.element,e),e.ownedOpacity!==void 0&&(e.element.style.opacity=e.ownedOpacity)}}reset(){for(let e of this.surfaces.values())e.ownedOpacity!==void 0&&e.element.style.opacity===e.ownedOpacity&&(e.element.style.opacity=e.originalOpacity);this.surfaces.clear()}sync(e,t,n){let r=new Set;for(let i of e){if(!(i instanceof HTMLElement)||!i.isConnected)continue;let{rect:e,geometry:a}=t(i);if(!a||e.width<=0||e.height<=0)continue;let o=getComputedStyle(i);if(!Yr(o).filled&&!Yr(o).border)continue;let s=JSON.stringify([e.width,e.height,a.shape,a.box.halfX,a.box.halfY,o.backgroundColor,o.backgroundImage,o.borderTopWidth,o.borderRightWidth,o.borderBottomWidth,o.borderLeftWidth]);r.add(i);let c=this.surfaces.get(i);if(c){if(c.signature!==s){let t=Xr(e,a,o);t&&Object.assign(c,t),c.signature=s}c.origin={x:c.origin.x+e.x-c.rect.x,y:c.origin.y+e.y-c.rect.y},c.rect=e,c.profile=n(i)}else{let t=Xr(e,a,o);if(!t)continue;this.surfaces.set(i,{element:i,rect:e,...t,signature:s,exposure:0,touched:!1,age:null,origin:{x:e.x+e.width/2,y:e.y+e.height/2},profile:n(i),originalOpacity:i.style.opacity,initialOpacity:Number.isFinite(Number(o.opacity))?Number(o.opacity):1})}}for(let[e,t]of this.surfaces)r.has(e)||(t.ownedOpacity!==void 0&&e.style.opacity===t.ownedOpacity&&(e.style.opacity=t.originalOpacity),this.surfaces.delete(e))}burningSources(){let e=[];for(let t of this.surfaces.values()){if(t.age===null||t.age>=t.profile.burnSeconds)continue;let{rect:n,profile:r}=t,i=r.spreadSeconds,a=t.age/Math.max(.01,i)*Math.hypot(n.width,n.height);e.push({point:t.origin,radiusPx:r.spreadRadiusPx,spreadSeconds:r.spreadSeconds,profile:r}),e.push({point:t.origin,bounds:n,radiusPx:r.spreadRadiusPx,spreadSeconds:r.spreadSeconds,profile:r,mask:{alpha:t.alpha,pixelWidth:t.pixelWidth,pixelHeight:t.pixelHeight,origin:t.origin,frontRadius:a}})}return e}expose(e,t,n){for(let r of this.surfaces.values()){if(r.age!==null)continue;let i=0,a=r.origin;for(let n of e.near(r.rect)){let e=oe(t,n,r.rect,r.profile.spreadSeconds);e>i&&(i=e,a=n.point)}i&&(r.touched=!0,r.exposure+=i*r.profile.ignitionSeconds,!(r.exposure+1e-6<r.profile.ignitionSeconds)&&this.ignite(r,a,n))}}ignite(e,t,n){e.age=0,e.origin={x:Math.max(e.rect.x,Math.min(e.rect.x+e.rect.width,t.x)),y:Math.max(e.rect.y,Math.min(e.rect.y+e.rect.height,t.y))},n(e.element)}exposeSegment(e,t,n,r,i){let a=Math.hypot(t.x-e.x,t.y-e.y),o=Math.max(1,Math.ceil(a/Math.max(1,n*.5))),s=new lt(Array.from({length:o+1},(r,i)=>({point:{x:e.x+(t.x-e.x)*i/o,y:e.y+(t.y-e.y)*i/o},radiusPx:n})));for(let e of this.surfaces.values()){if(e.age!==null)continue;let t=0,n=e.origin;for(let r of s.near(e.rect)){let i=oe(1,r,e.rect,1);i>t&&(t=i,n=r.point)}t&&(e.touched=!0,e.exposure+=r*t,e.exposure+1e-6>=e.profile.ignitionSeconds&&this.ignite(e,n,i))}}advance(e,t){for(let n of this.surfaces.values()){if(n.age===null){n.touched||(n.exposure=Math.max(0,n.exposure-e*.2)),n.touched=!1;continue}if(n.age>=n.profile.burnSeconds)continue;n.age+=e;let r=Math.max(.01,n.profile.burnSeconds),i=W(n.age/r,.3,1);(n.ownedOpacity===void 0||n.element.style.opacity===n.ownedOpacity)&&(n.ownedOpacity=String(n.initialOpacity*i),n.element.style.opacity=n.ownedOpacity);let a=n.rect;t.emitSceneFire({key:n,alpha:n.alpha,pixelWidth:n.pixelWidth,pixelHeight:n.pixelHeight,x:a.x,y:a.y,width:a.width,height:a.height,origin:n.origin,age:n.age,farthest:Math.max(1,Math.hypot(a.width,a.height)),spreadSeconds:n.profile.spreadSeconds,burnSeconds:r,smokeRate:n.profile.smokePerSecond},e)}}};function Qr(e,t){if(t.width<=0||t.height<=0)return null;let n=E(t.x+t.width/2,t.y+t.height/2),r=E(e.center.x-n.x,e.center.y-n.y),i=1/0,a=E();for(let n of[e.forward,e.side,E(1,0),E(0,1)]){let o=e.halfLength*Math.abs(j(n,e.forward))+e.halfWidth*Math.abs(j(n,e.side)),s=t.width/2*Math.abs(n.x)+t.height/2*Math.abs(n.y),c=j(r,n),l=o+s-Math.abs(c);if(l<=0)return null;l<i&&(i=l,a=T(n,l*(c<0?-1:1)))}return a}var $r=(e,t)=>e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y,ei=24,ti=(e,t,n)=>e.x<t.x+t.width+n&&e.x+e.width>t.x-n&&e.y<t.y+t.height+n&&e.y+e.height>t.y-n;function ni(e,t,n,r,i,a,o,s,c=()=>void 0){let l={x:n.center.x-n.halfLength-n.halfWidth,y:n.center.y-n.halfLength-n.halfWidth,width:2*(n.halfLength+n.halfWidth),height:2*(n.halfLength+n.halfWidth)};if(a)return;let u=E(e.body.velocity.x*t,-e.body.velocity.y*t),d=(i,a,o)=>{if(a.impactCooldown>0||!un(a,l))return;let c=Y(a);if(!$r(l,c))return;let d=E(c.x+c.width/2,c.y+c.height/2),f=E(d.x-n.center.x,d.y-n.center.y),p=k(u,E(f.y*e.body.spin,-f.x*e.body.spin));if(P(k(p,T(a.velocity,-1)))>t*.7*s(i.root)&&Qr(n,c)&&z(r.alpha,n,c)){let e=E(d.x-n.center.x,d.y-n.center.y),t=P(e)>1?T(e,1/P(e)):n.forward;o.kind===`destructible`?xn(i,a,p,t,(Math.random()-.5)*10):dn(a,p,t,(Math.random()-.5)*10)}};for(let e of i){if(e.root&&o(e)===!1)continue;let t=c(e),n=!t||ti(l,t,ei);for(let t of e.glyphs){if(t.burnFinished||e.kind===`destructible`&&t.breakable===!1)continue;if(e.kind===`pushable`){(n||t.detached)&&d(t,t,e);continue}let r=n&&ti(l,t.ink,2);for(let n of t.fragments??[])!n.destroyed&&!n.burnFinished&&(r||n.detached)&&d(t,n,e)}}}function ri(e){let{shape:t,mask:n,scale:r,projectionScale:i}=e;for(let a of e.targets){let o=a.element,s=Qr(t,a.rect);if(!(o instanceof HTMLElement)||e.crushed.has(o)||!s||!z(n.alpha,t,a.rect))continue;let c=typeof DOMMatrixReadOnly<`u`?K(o):null;if(_e(n.alpha,t,{center:E(a.rect.x+a.rect.width/2,a.rect.y+a.rect.height/2),halfX:c?T(c.halfX,1/i):E(a.rect.width/2,0),halfY:c?T(c.halfY,1/i):E(0,a.rect.height/2)})<.5)continue;let l={scale:o.style.scale,opacity:o.style.opacity,transform:o.style.transform,transition:o.style.transition,transformOrigin:o.style.transformOrigin};e.crushed.set(o,l);let u=e.options(o),d=(u?.crushedClass?.trim().split(/\s+/)??[]).filter(e=>!o.classList.contains(e));if(l.classes=d,d.length&&o.classList.add(...d),o.dataset.jrCrushed=``,o.style.transition=`none`,!u?.crushedClass||u.scale!==void 0){o.style.transformOrigin=`center center`;let e=u?.crushedClass?0:(Math.random()-.5)*14,t=u?.crushedClass?0:(Math.random()-.5)*8,n=u?.scale??.82+Math.random()*.08;o.style.transform=[o.style.transform,`rotate(${e.toFixed(1)}deg) skew(${t.toFixed(1)}deg) scale(${n.toFixed(2)})`].filter(Boolean).join(` `)}if(u?.crushedClass&&u.opacity===void 0||(o.style.opacity=String(u?.opacity??.45)),u?.crushedPaintColor){let t=c?2*Math.hypot(c.halfX.x,c.halfX.y)/i:a.rect.width,n=(c?4*Math.abs(c.halfX.x*c.halfY.y-c.halfX.y*c.halfY.x)/(i*i):a.rect.width*a.rect.height)/Math.max(t,.001),s=on({x:a.rect.x+(a.rect.width-t)/2,y:a.rect.y+(a.rect.height-n)/2,width:t,height:n},r,u.crushedPaintColor,E(e.velocity.x,-e.velocity.y));e.spills.set(o,s),e.emitSpill(s)}l.applied={transformOrigin:o.style.transformOrigin,transition:o.style.transition,transform:o.style.transform,opacity:o.style.opacity},e.onCrush?.(o,e.claimPoints(o,a.points),E(a.rect.x+a.rect.width/2,a.rect.y+a.rect.height/2))}}var ii=(e,t)=>e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y;function ai(e,t,n,r,i){let a=t.impulse,o=t.impulseDirection,s=o?Math.hypot(o.x,o.y):0,c=o&&Number.isFinite(s)&&s>.001?T(o,1/s):null,l=t.radiusPx,u=t.coreRadiusPx;for(let a of r.combustibles){if(a.explodedAt!==null||n.has(a))continue;let r=Math.max(a.rect.x-e.x,0,e.x-a.rect.x-a.rect.width),o=Math.max(a.rect.y-e.y,0,e.y-a.rect.y-a.rect.height),s=Math.hypot(r,o);s<=l&&(n.add(a),i.damageCombustible(a,t.damage/100*Math.max(.2,1-s/l*.7)))}for(let o of r.runs)for(let s of o.glyphs){if(s.burnFinished||n.has(s))continue;let d=Y(s);if(Math.hypot(Math.max(d.x-e.x,0,e.x-d.x-d.width),Math.max(d.y-e.y,0,e.y-d.y-d.height))>l&&!(s.fragments??[]).some(t=>{let n=Y(t);return Math.hypot(Math.max(n.x-e.x,0,e.x-n.x-n.width),Math.max(n.y-e.y,0,e.y-n.y-n.height))<=l}))continue;if(n.add(s),i.notify(`hit`,s.root),s.breakable===!1){if(t.ignite&&s.burnable)for(let e of X(s))!e.burnFinished&&!e.destroyed&&(r.burning.set(e,{age:0,profile:i.burnProfile(s.root,m)}),i.notify(`ignite`,s.root));if(o.kind!==`pushable`)continue}t.damage>0&&o.kind===`destructible`&&ii(s.ink,{x:e.x-u,y:e.y-u,width:u*2,height:u*2})&&i.blastInk(s,e,u);let f=o.kind===`destructible`?(s.fragments??[]).filter(e=>!e.destroyed&&!e.burnFinished):[s];for(let n of f){let d=Y(n),f=E(d.x+d.width/2,d.y+d.height/2),p=E(f.x-e.x,f.y-e.y),h=P(p);if(h>l||t.damage>0&&o.kind===`destructible`&&n.detached&&h<u&&(i.carveInk(s,n,e,u),n.destroyed))continue;let g=c??(h>1?T(p,1/h):E(Math.cos(Math.random()*Math.PI*2),Math.sin(Math.random()*Math.PI*2))),_=Math.max(.15,1-h/l),v=T(g,(140+700*_)*a);if(o.kind===`destructible`){let e=n;t.damage>0&&h<u&&!e.fireAlpha?(e.destroyed=!0,e.bitmap=void 0,r.burning.delete(e),r.flameExposure.delete(e)):(t.impulse>0&&xn(s,e,v,g,(Math.random()-.5)*16),t.ignite&&s.burnable!==!1&&!e.destroyed&&!e.burnFinished&&!r.burning.has(e)&&(r.burning.set(e,{age:0,profile:i.burnProfile(s.root,m)}),i.notify(`ignite`,s.root)))}else t.impulse>0&&dn(n,v,g,(Math.random()-.5)*16)}o.kind===`destructible`&&(s.burnFinished=X(s).every(e=>e.destroyed||e.burnFinished)&&!(o.graphic&&s.fireAge!==void 0),s.burnFinished&&(s.bitmap=void 0,s.intactBitmap=void 0))}}function oi(e,t,n,r){if(!r.fireAlpha||U(e,t,n,Y(r))===null)return null;let i=E(t.x-e.x,t.y-e.y),a=Math.max(1,Math.ceil(P(i)/Math.max(.65,n*.5))),o=E(r.base.x+r.base.width/2+(r.detached?r.offset.x:0),r.base.y+r.base.height/2+(r.detached?r.offset.y:0)),s=Math.cos(r.detached?r.angle:0),c=Math.sin(r.detached?r.angle:0),l=Math.max(1,Math.ceil(r.source.width*2)),u=Math.max(1,Math.ceil(r.source.height*2)),d=Math.max(1,Math.ceil(n*2));for(let t=0;t<=a;t++){let n=t/a,f=k(e,T(i,n)),p=f.x-o.x,m=f.y-o.y,h=Math.round((p*s+m*c+r.source.width/2)*2),g=Math.round((-p*c+m*s+r.source.height/2)*2),_=Math.round(d*.7);for(let[e,t]of[[0,0],[d,0],[-d,0],[0,d],[0,-d],[_,_],[-_,_],[_,-_],[-_,-_]]){let i=h+e,a=g+t;if(i>=0&&a>=0&&i<l&&a<u&&r.fireAlpha[a*l+i]>64)return n}}return null}function si(e,t,n,r,i){let a=null,o=(e,i,o,s)=>{let c=s?.fireAlpha?oi(t,n,r,s):U(t,n,r,e);c!==null&&(!a||c<a.time)&&(a={time:c,kind:i,glyph:o,piece:s})};for(let t of e.walls)o(t.rect,`wall`);for(let i of e.combustibles)if(i.explodedAt===null){let e=U(t,n,r,i.rect);e!==null&&(!a||e<a.time)&&(a={time:e,kind:`combustible`,combustible:i})}for(let a of e.runs)for(let e of a.glyphs)if(!e.burnFinished){if(a.kind===`pushable`)o(Y(e),`pushable`,e);else{let a=U(t,n,r,e.ink)!==null;for(let t of e.fragments??[])t.destroyed||t.burnFinished||i?.has(t)||(a||t.detached)&&o(Y(t),`destructible`,e,t)}}if(!a)return null;let s=a;return{point:k(t,T(E(n.x-t.x,n.y-t.y),s.time)),kind:s.kind,glyph:s.glyph,piece:s.piece,combustible:s.combustible}}var ci=class{onChange;playground;unsubscribe;collection;specs=new WeakMap;selections=new Map;dirty=!0;constructor(e){this.onChange=e}setPlayground(e){this.unsubscribe?.(),this.playground=e,this.collection=void 0,this.invalidate(),this.unsubscribe=e.subscribe(()=>{this.invalidate(),this.onChange()})}invalidate(){this.dirty=!0}specFor(e){if(e)return this.refresh(),this.specs.get(e)}selected(e){return this.refresh(),this.selections.get(e)??[]}dispose(){this.unsubscribe?.(),this.unsubscribe=void 0,this.playground=void 0,this.collection=void 0,this.specs=new WeakMap,this.selections.clear(),this.dirty=!0}refresh(){if(!this.dirty)return;this.dirty=!1;let e=this.playground?.objects;if(this.collection!==e){this.collection=e,this.specs=new WeakMap,this.selections.clear();for(let e of[`solid`,`pushable`,`artwork`,`crushable`,`combustible`,`liquid`])this.selections.set(e,[]);for(let{target:t,spec:n}of e??[])if(this.specs.set(t,n),n.enabled!==!1){(n.breakable||n.burnable&&!n.combustible)&&this.selections.get(`artwork`).push(t),n.solid===!0&&!n.breakable&&!n.combustible&&this.selections.get(`solid`).push(t);for(let e of[`pushable`,`crushable`,`combustible`,`liquid`])n[e]&&this.selections.get(e).push(t)}}}},li=class extends M{element;rect;points;origin;originalOpacity;alpha;pixelWidth;pixelHeight;ownedOpacity;constructor(e,t,n,r,i,a,o=e.style.opacity){super(n),this.element=e,this.rect=t,this.points=r,this.origin=i,this.originalOpacity=o,this.alpha=a.alpha,this.pixelWidth=a.pixelWidth,this.pixelHeight=a.pixelHeight}};function ui(e){let{sim:t,damage:n,shape:r,mask:i,scale:a,viewport:o,walls:s,combustibles:c,onImpact:l,onScrape:u,damageCombustible:d}=e;if(o){let e={left:o.scroll.x+3,top:o.scroll.y+3,right:o.scroll.x+o.width-3,bottom:o.scroll.y+o.height-3},s=R(i.alpha,r),c=[E(s.x<e.left?e.left-s.x:0,0),E(s.x+s.width>e.right?e.right-s.x-s.width:0,0),E(0,s.y<e.top?e.top-s.y:0),E(0,s.y+s.height>e.bottom?e.bottom-s.y-s.height:0)];for(let e of c){if(!e.x&&!e.y)continue;t.body.position.x+=e.x/a,t.body.position.y-=e.y/a,r.center={x:r.center.x+e.x,y:r.center.y+e.y};let o=T(e,1/P(e)),s=E(t.body.velocity.x*a,-t.body.velocity.y*a),c=j(s,o);if(c<0){if(c<-a*.8){let e=te(i.alpha,r,T(o,-1)),u=-c/a;t.car.takeImpact(u,E(j(w(e,r.center),r.forward)/a,j(w(e,r.center),r.side)/a)),n.hit(e,o,r,u,a),l?.({speedMps:u,velocity:s,normal:o,point:e,carNormal:se(i.alpha,r,e),pixelsPerMeter:a})}t.body.velocity.x-=c*o.x/a,t.body.velocity.y+=c*o.y/a,t.body.spin*=.85}}}for(let e=0;e<3;e++){let o=!1;for(let f of s){if(f instanceof li&&f.explodedAt!==null)continue;let s=Qr(r,f.rect);if(!s||!z(i.alpha,r,f.rect))continue;let p=T(s,1/P(s)),m=ie(i.alpha,r,f.rect),h=se(i.alpha,r,m),g={...r},_=ce(i.alpha,r,f.rect,p,P(s)+2),v=T(p,_);t.body.position.x+=v.x/a,t.body.position.y-=v.y/a,r.center={x:r.center.x+v.x,y:r.center.y+v.y};let y=E(t.body.velocity.x*a,-t.body.velocity.y*a),b=j(y,p),x=P(w(y,T(p,b)));if(b<0){if(e===0){let e=-b/a,r=c.get(f.element),i={speedMps:e,velocity:y,normal:p,point:m,carNormal:h,wall:f.rect,element:f.element,pixelsPerMeter:a};ct(t,n,g,i,()=>{r&&d(r,e*D.impactDamagePerMps)})&&l?.(i)}t.body.velocity.x-=b*p.x/a,t.body.velocity.y+=b*p.y/a,t.body.spin*=.85}e===0&&b>=-a*.8&&b<=a*.1&&x>a*2.2&&u?.({speedMps:Math.max(0,-b/a),velocity:y,normal:p,point:m,carNormal:h,wall:f.rect,pixelsPerMeter:a}),o=!0}if(!o)break}}var di=e=>{for(let t=e;t&&t!==document.body;t=t.parentElement){let e=getComputedStyle(t).position;if(e===`fixed`||e===`sticky`)return!0}return!1},fi=class{onImpact;sceneOffset;projection;damage;onCrush;onScrape;onCombustibleExplosion;onDestructibleDestroyed;autoPaint=null;runs=[];walls=[];crushables=[];combustibles=new Map;pointSources=new Map;awardedObjects=new Set;solidObjects=[];showHealthBars=!0;hoveredVehicleId=null;destructibleBurnSeconds;flameDamageThisStep=new Map;stepSeconds=1/60;crushed=new Map;crushSpills=new Map;liquidElements=[];paintTransitions=new Map;liquidBackings=new Map;lastAutoPaintGeometryRevision=-1;dirty=!0;lastScan=-1/0;lastMeasure=-1/0;selection=new ci(()=>{this.dirty=!0,this.lastScan=-1/0});artwork;masks=new ne;preset=null;lettersFadeStartedAt=null;artworkFire=new qr;externalFireElapsed=0;burnSprites=new st;textLayers=new or;fragmentAtlas=new dr(this.burnSprites);burnSurfaces=new Zr;captureState(){let e=new Map;for(let t of[...this.crushed.keys(),...this.combustibles.keys()])t instanceof HTMLElement&&e.set(t,{opacity:t.style.opacity,scale:t.style.scale,transform:t.style.transform,transition:t.style.transition,transformOrigin:t.style.transformOrigin,crushed:`jrCrushed`in t.dataset,crushedClasses:(this.crushed.get(t)?.classes??[]).filter(e=>t.classList.contains(e))});return{data:b({runs:this.runs,walls:this.walls,crushables:this.crushables,combustibles:this.combustibles,pointSources:this.pointSources,awardedObjects:this.awardedObjects,showHealthBars:this.showHealthBars,destructibleBurnSeconds:this.destructibleBurnSeconds,flameDamageThisStep:this.flameDamageThisStep,stepSeconds:this.stepSeconds,crushed:this.crushed,crushSpills:this.crushSpills,liquidElements:this.liquidElements,dirty:this.dirty,lastScan:this.lastScan,lastMeasure:this.lastMeasure,preset:this.preset,lettersFadeStartedAt:this.lettersFadeStartedAt,artworkFire:this.artworkFire.state(),externalFireElapsed:this.externalFireElapsed,sourceVehicleId:this.sourceVehicleId,ignitedRoots:this.ignitedRoots}),automaticPaint:!!this.autoPaint,burnSurfaces:this.burnSurfaces.captureState(),styles:e,at:performance.now()}}restoreState(e){let t=this.captureState();try{this.applyState(e)}catch(e){try{this.applyState(t)}catch(t){throw AggregateError([e,t],`DOM collision checkpoint rollback failed`,{cause:t})}throw e}}applyState(e){let t=b(e.data);this.clearPaintSurfaces(),this.burnSurfaces.reset(),this.restoreCrushables(),this.restoreCombustibles(),this.restoreText(),this.runs=t.runs,this.walls=t.walls,this.crushables=t.crushables,this.combustibles=t.combustibles,this.pointSources=t.pointSources,this.awardedObjects=t.awardedObjects,this.showHealthBars=t.showHealthBars,this.destructibleBurnSeconds=t.destructibleBurnSeconds,this.flameDamageThisStep=t.flameDamageThisStep,this.stepSeconds=t.stepSeconds,this.crushed=t.crushed,this.crushSpills=t.crushSpills,this.liquidElements=t.liquidElements,this.lastAutoPaintGeometryRevision=-1,this.dirty=t.dirty,this.lastScan=t.lastScan,this.lastMeasure=t.lastMeasure,this.preset=t.preset,this.lettersFadeStartedAt=t.lettersFadeStartedAt,this.artworkFire.loadState(t.artworkFire),this.externalFireElapsed=t.externalFireElapsed,this.sourceVehicleId=t.sourceVehicleId,this.ignitedRoots=t.ignitedRoots,this.selection.invalidate(),this.artwork.clear(),this.solidObjects=[],this.burnSprites.clear(),this.textLayers.clear(),this.fragmentAtlas.clear();for(let e of this.runs)!e.wrapper.isConnected&&e.original.isConnected&&e.original.replaceWith(e.wrapper);for(let[t,n]of e.styles)t.style.opacity=n.opacity,t.style.scale=n.scale,t.style.transform=n.transform,t.style.transition=n.transition,t.style.transformOrigin=n.transformOrigin,n.crushed?(t.dataset.jrCrushed=``,n.crushedClasses.length&&t.classList.add(...n.crushedClasses)):delete t.dataset.jrCrushed;this.burnSurfaces.restoreState(e.burnSurfaces),(e.automaticPaint||this.autoPaint)&&(this.autoPaint?.refresh(),this.dirty=!0,this.lastScan=-1/0);let n=performance.now()-e.at;this.lettersFadeStartedAt!==null&&(this.lettersFadeStartedAt+=n),Number.isFinite(this.lastScan)&&(this.lastScan+=n),Number.isFinite(this.lastMeasure)&&(this.lastMeasure+=n);for(let e of this.combustibles.values())e.explodedAt!==null&&(e.explodedAt+=n),Number.isFinite(e.lastBlastEmission)&&(e.lastBlastEmission+=n)}constructor(e,t=()=>E(),n=new ye,r,i,a,o){let s=typeof e==`object`&&e?e:{onImpact:e,sceneOffset:t,damage:n,onCrush:r,onScrape:i,onCombustibleExplosion:a,onDestructibleDestroyed:o};this.onImpact=s.onImpact,this.sceneOffset=s.sceneOffset??(()=>E()),this.damage=s.damage??new ye,this.onCrush=s.onCrush,this.onScrape=s.onScrape,this.onCombustibleExplosion=s.onCombustibleExplosion,this.onDestructibleDestroyed=s.onDestructibleDestroyed,this.projection=s.projection??B,this.artwork=new An(()=>{this.lastMeasure=-1/0,this.dirty=!0,this.lastScan=-1/0},this.projection)}rectInDocument(e,t){return this.projection.viewportRectToDocument(e.getBoundingClientRect(),t)}sourceVehicleId;ignitedRoots=new Set;onObjectEvent;setSourceVehicle(e){this.sourceVehicleId=e}notify(e,t){if(t){if(e===`ignite`){if(this.ignitedRoots.has(t))return;this.ignitedRoots.add(t)}this.onObjectEvent?.(e,t)}}setEvents(e){let t=e=>({element:e,objectId:e?this.selection.playground?.get(e)?.id:void 0,vehicleId:this.sourceVehicleId});this.onObjectEvent=(n,r)=>{let i=this.rectInDocument(r,this.sceneOffset());e.emit({kind:`object`,type:n,point:E(i.x+i.width/2,i.y+i.height/2),...t(r)})},this.onImpact=n=>e.emit({kind:`impact`,impact:n,...t(n.element)}),this.onScrape=n=>e.emit({kind:`scrape`,impact:n,...t(n.element)}),this.onCrush=(n,r,i)=>e.emit({kind:`crush`,points:r,point:i,...t(n)}),this.onCombustibleExplosion=(n,r,i)=>e.emit({kind:`combustionExplosion`,point:n,points:r,...t(i)}),this.onDestructibleDestroyed=(n,r,i,a)=>e.emit({kind:`destructibleDestroyed`,point:n,points:r,cause:a,...t(i)})}prepare(e){this.preset=e,this.masks.forPreset(e)}get totalPoints(){let e=0;for(let t of this.pointSources.values())e+=t;for(let{spec:t}of this.selection.playground?.objects??[]){let n=typeof t.trigger==`object`?t.trigger.preset:t.trigger,r=typeof t.trigger==`object`?t.trigger.when:void 0;t.enabled!==!1&&(n===`pickup`||(r??(n===`parking`?`stop`:`enter`))===`stop`)&&(e+=t.points??0)}return e}pointsFor(e,t){let n=this.specFor(e)?.points??this.pointSources.get(e);return n===void 0&&(n=this.specFor(e)?.points??L(e,t.width,t.height),this.pointSources.set(e,n)),this.pointSources.set(e,n),n}claimPoints(e,t){return this.awardedObjects.has(e)?0:(this.awardedObjects.add(e),this.pointSources.get(e)??t)}setShowHealthBars(e){this.showHealthBars=e}setHoveredVehicle(e){this.hoveredVehicleId=e}forgetVehicle(e){this.hoveredVehicleId===e&&(this.hoveredVehicleId=null)}setDestructibleBurnSeconds(e){this.destructibleBurnSeconds=e===1/0||e!==void 0&&Number.isFinite(e)&&e>0?e:void 0}vehicleMask(e,t=this.damage){return t.maskFor(this.masks.forPreset(e))}get managedBytes(){let e=(this.artworkFire.flameExposure.size+this.artworkFire.burning.size)*48+this.artworkFire.flameGlyphHeat.size*24+this.crushed.size*128;for(let t of this.combustibles.values())e+=192+t.alpha.byteLength;for(let t of this.runs)for(let n of t.glyphs){if(t.kind===`pushable`){e+=128;continue}if(n.burnFinished)continue;let r=n.fragments?.filter(e=>!e.destroyed&&!e.burnFinished)??[];if(r.length){e+=(n.bitmap?.width??0)*(n.bitmap?.height??0)*4,e+=(n.intactBitmap?.width??0)*(n.intactBitmap?.height??0)*4,e+=this.burnSprites.bytesFor(n.intactBitmap),e+=this.burnSprites.bytesFor(n.bitmap);for(let t of r)e+=160+(t.fireAlpha?.byteLength??0)+(t.bitmap?.width??0)*(t.bitmap?.height??0)*4+this.burnSprites.bytesFor(t.bitmap)}}return e+this.textLayers.bytes+this.fragmentAtlas.bytes}wallRects(){return this.walls.map(e=>e.rect)}drawHealthBars(e,t,n,r,i,a=[]){Wr({combustibles:this.combustibles.values(),hoveredVehicleId:this.hoveredVehicleId,showHealthBars:this.showHealthBars},e,t,n,r,i,a)}burningProximity(e){let t=0,n=0,r=0,i=new Set,a=(r,i)=>{let a=Math.hypot(Math.max(r.x-e.x,0,e.x-r.x-r.width),Math.max(r.y-e.y,0,e.y-r.y-r.height)),o=r.width*r.height;t+=o,n+=o*i*Math.max(0,1-a/650)};for(let e of this.runs)if(e.graphic)for(let t of e.glyphs){if(t.fireAge===void 0||t.burnFinished)continue;let e=(t.fireAge-(t.fireSpreadSeconds??0)/2)/Math.max(.01,t.fireBurnSeconds??m.burnSeconds);a(t.ink,W(e,.78,1.02));for(let e of t.fragments??[])e.detached||i.add(e)}for(let e of this.artworkFire.burning.keys())e.destroyed||e.burnFinished||i.has(e)||a(Y(e),W(e.burnAmount??0));for(let t of this.combustibles.values()){if(t.explodedAt!==null||t.health>t.maxHealth*D.smokeFraction)continue;let n=t.rect,i=Math.hypot(Math.max(n.x-e.x,0,e.x-n.x-n.width),Math.max(n.y-e.y,0,e.y-n.y-n.height));r=Math.max(r,A(t.health,t.maxHealth)*Math.max(0,1-i/650))}let o=t?Math.min(.65,Math.max(.1,Math.sqrt(t)/120))*(n/t):0;return Math.max(o,r)}tirePaintAt(e){return Mr(this.liquidStepState(),e)}stepElementLiquids(e,t,n){Nr(this.liquidStepState(),e,t,n)}liquidStepState(){return{liquidElements:this.liquidElements,liquidBackings:this.liquidBackings}}clearPaintTransitions(){for(let e of this.paintTransitions.values())e();this.paintTransitions.clear()}clearPaintSurfaces(){for(let e of this.liquidBackings.values())e.dispose();this.liquidBackings.clear()}fadeLetters(){this.clearPaintSurfaces(),this.restoreCrushables(),this.restoreCombustibles(),this.lettersFadeStartedAt===null&&this.runs.some(e=>e.glyphs.some(e=>e.detached||e.fragments?.some(e=>e.detached)))&&(this.lettersFadeStartedAt=performance.now())}finishLetterReset(e){this.lettersFadeStartedAt===null||he(this.lettersFadeStartedAt,e)>0||(this.restoreText(),this.dirty=!0,this.lastScan=-1/0)}setPlayground(e){let t=!!this.autoPaint;this.autoPaint?.dispose(),this.autoPaint=null,this.selection.setPlayground(e),t&&this.setAutoPaint(!0),this.dirty=!0,this.lastScan=-1/0}specFor(e){return this.selection.specFor(e)}selected(e){return this.selection.selected(e)}burnLifetime(e){let t=this.specFor(e),n=t?.burnable||t?.combustible;return n&&typeof n==`object`?n.burnSeconds:void 0}capabilityOptions(e,t){let n=this.specFor(e)?.[t];return n&&typeof n==`object`?n:void 0}toughness(e){return Math.sqrt((this.capabilityOptions(e,`breakable`)?.health??100)/100)}burnProfile(e,t){return{...m,...t,...this.capabilityOptions(e,`burnable`)}}liquidOptions(e){return this.specFor(e)?.liquid||void 0}setAutoPaint(e){e!==!!this.autoPaint&&(this.autoPaint?.dispose(),this.autoPaint=e?new Kn(()=>{this.dirty=!0},e=>this.liquidBackings.get(e)?.readPaintSource()?.color,this.selection.playground?.root??document):null,this.lastAutoPaintGeometryRevision=-1,this.dirty=!0)}restoreCombustibles(){for(let e of this.combustibles.values())e.ownedOpacity!==void 0&&e.element.style.opacity===e.ownedOpacity&&(e.element.style.opacity=e.originalOpacity);this.combustibles.clear(),this.dirty=!0,this.lastScan=-1/0}restoreCrushable(e){let t=this.crushed.get(e);if(t){for(let n of[`scale`,`opacity`,`transform`,`transition`,`transformOrigin`])t.applied?.[n]!==void 0&&e.style[n]===t.applied[n]&&(e.style[n]=t[n]);for(let n of t.classes??[])e.classList.remove(n);delete e.dataset.jrCrushed,this.crushed.delete(e),this.crushSpills.delete(e)}}restoreCrushables(){this.crushSpills.clear();for(let e of this.crushed.keys())this.restoreCrushable(e)}restoreText(){for(let e of this.runs)En(e);this.runs=[],this.artworkFire.reset(),this.externalFireElapsed=0,this.burnSprites.clear(),this.textLayers.clear(),this.fragmentAtlas.clear(),this.ignitedRoots.clear(),this.lettersFadeStartedAt=null}wrapText(){let e=Dn({pushable:this.selected(`pushable`),artwork:this.selected(`artwork`),hud:new Set(this.selection.playground?.objects.filter(e=>e.spec.hud).map(e=>e.target))},this.artwork.canvas);this.runs.push(...e);for(let t of e)t.kind===`destructible`&&t.root&&this.pointsFor(t.root,this.rectInDocument(t.root,this.sceneOffset()))}wrapGraphics(){let e=kn(this.selected(`artwork`),()=>{this.dirty=!0});this.runs.push(...e);for(let t of e)t.root&&t.graphic&&this.pointsFor(t.root,this.rectInDocument(t.graphic,this.sceneOffset()))}scan(e){if(!this.dirty||e-this.lastScan<250)return;performance.now(),this.lastScan=e,this.dirty=!1;for(let e of this.crushed.keys())e.isConnected||this.restoreCrushable(e);let t=new Set(this.selected(`pushable`)),n=new Set(this.selected(`artwork`));this.runs=this.runs.filter(e=>e.wrapper.isConnected&&(!this.selection.playground||(e.kind===`pushable`?t:n).has(e.root))&&(e.graphic||e.original.data===e.source)?!0:(En(e),!1)),this.wrapText(),this.wrapGraphics(),this.walls=this.selected(`solid`).length?this.selected(`solid`).filter(e=>!e.closest(`[data-jr-embed],[data-jr-text-run]`)).map(e=>({element:e,rect:this.rectInDocument(e,this.sceneOffset()),viewportAnchored:di(e)})):[],this.crushables=this.selected(`crushable`).length?this.selected(`crushable`).filter(e=>e instanceof HTMLElement&&!e.closest(`[data-jr-embed]`)).map(e=>({element:e,rect:this.rectInDocument(e,this.sceneOffset()),points:this.pointsFor(e,this.rectInDocument(e,this.sceneOffset()))})):[];let r=new Set(this.crushables.map(e=>e.element));for(let e of this.crushed.keys())r.has(e)||this.restoreCrushable(e);{let e=new Set;for(let t of this.selected(`combustible`)){if(!(t instanceof HTMLElement)||t.closest(`[data-jr-embed]`))continue;e.add(t);let n=this.combustibles.get(t);if(n){let e=this.specFor(t)?.combustible,r=typeof e==`object`?e.health??D.defaultHealth:D.defaultHealth;r!==n.maxHealth&&(n.health=n.healthFraction*r,n.maxHealth=r),n.points=this.pointsFor(t,this.rectInDocument(t,this.sceneOffset()));let i=this.rectInDocument(t,this.sceneOffset());(i.width!==n.rect.width||i.height!==n.rect.height)&&Object.assign(n,Yn(t,i.width,i.height)),n.origin=k(n.origin,E(i.x-n.rect.x,i.y-n.rect.y)),n.rect=i;continue}let r=this.rectInDocument(t,this.sceneOffset()),i=Yn(t,r.width,r.height),a=-1,o=0;for(let e=0;e<i.alpha.length;e++)i.alpha[e]>=64&&Math.random()*++o<1&&(a=e);let s=a>=0?E(r.x+(a%i.pixelWidth+.5)/i.pixelWidth*r.width,r.y+(Math.floor(a/i.pixelWidth)+.5)/i.pixelHeight*r.height):E(r.x+r.width/2,r.y+r.height/2),c=Math.max(1,this.capabilityOptions(t,`combustible`)?.health??D.defaultHealth);this.combustibles.set(t,new li(t,r,c,this.pointsFor(t,r),s,i))}for(let[t,n]of this.combustibles)e.has(t)||(n.ownedOpacity!==void 0&&n.element.style.opacity===n.ownedOpacity&&(n.element.style.opacity=n.originalOpacity),this.combustibles.delete(t))}let i=[...new Set([...this.selected(`liquid`),...(this.autoPaint?.elements??[]).filter(e=>this.specFor(e)?.enabled!==!1)])],a=new Map(this.liquidElements.map(e=>[e.element,e]));this.liquidElements=i.map(e=>a.get(e)??{element:e,rect:this.rectInDocument(e,this.sceneOffset()),source:null,liquidSource:null,geometry:null});let o=new Set(this.liquidElements.map(e=>e.element));for(let[e,t]of this.paintTransitions)o.has(e)||(t(),this.paintTransitions.delete(e));for(let e of o)e instanceof HTMLElement&&!this.paintTransitions.has(e)&&this.paintTransitions.set(e,Ir(e));for(let[e,t]of this.liquidBackings)o.has(e)||(t.dispose(),this.liquidBackings.delete(e));this.measure(),this.lastMeasure=e}measure(){performance.now();let e=this.sceneOffset(),t=new xt;this.artwork.measure(this.runs,e,e=>this.specFor(e),e=>this.artworkFire.extinguishPiece(e));for(let t of this.walls)t.rect=this.rectInDocument(t.element,e);this.burnSurfaces.sync(this.selected(`artwork`).filter(e=>{let t=this.specFor(e);return!!t?.burnable&&!t.combustible}),n=>({rect:this.rectInDocument(n,e),geometry:Dr(n,e,this.projection,t)}),e=>this.burnProfile(e,m)),performance.now();let n=this.autoPaint?.geometryRevision??-1;for(let r of this.liquidElements){let i=this.rectInDocument(r.element,e),a=this.autoPaint?.has(r.element),o=Math.abs(r.rect.x-i.x)<.5&&Math.abs(r.rect.y-i.y)<.5&&Math.abs(r.rect.width-i.width)<.5&&Math.abs(r.rect.height-i.height)<.5;if(a&&r.geometry&&this.lastAutoPaintGeometryRevision===n&&o)continue;r.rect=i;let s=this.liquidBackings.get(r.element),c=this.liquidOptions(r.element);F(`dom paint geometry measures`),r.geometry=Dr(r.element,e,this.projection,t),r.liquidSource=r.geometry&&c?s?s.readSource(c):mr(r.element,c):null,r.source=r.geometry?c?r.liquidSource?.paint??null:s?s.readPaintSource():pr(r.element):null}this.lastAutoPaintGeometryRevision=n}carveInk(e,t,n,r){Sn(e,t,n,r/this.toughness(e.root))&&this.artworkFire.extinguishPiece(t)}blastInk(e,t,n){for(let r of Cn(e,t,n/this.toughness(e.root)))this.artworkFire.extinguishPiece(r)}flameContact(e,t,n,r,i){let a=w(t,e),o=P(a),s=o>1e-6?T(a,1/o):E(),c=new Set,l=(t,i)=>(this.burnSurfaces.exposeSegment(e,t,n,r,e=>this.notify(`ignite`,e)),i);for(;;){let a=this.firstProjectileHit(e,t,n,c);if(!a)return l(t,null);if(a.combustible)return this.damageCombustible(a.combustible,`flame`,1,r),l(a.point,a.point);let u=a.kind===`destructible`?a.piece:void 0;if(u&&a.glyph?.burnable!==!1&&this.artworkFire.directContact(u,a.glyph,r,i,(e,t)=>this.burnProfile(e,t),e=>this.notify(`ignite`,e)),!u||o<1e-6)return l(a.point,a.point);let d=u.detached?Y(u):a.glyph?.ink??Y(u),f=Math.abs(s.x)*d.width+Math.abs(s.y)*d.height;if(u.detached&&f<=n*2){c.add(u);continue}let p=k(a.point,T(s,Math.min(n*1.5,f*.35)));return l(p,p)}}damageCombustible(e,t,n=1,r=0){if(e.explodedAt!==null||!this.preset)return;let i=x(t,this.preset,r)*n;if(t===`flame`){let t=this.capabilityOptions(e.element,`burnable`)?.ignitionSeconds;t!==void 0&&(i=e.maxHealth*(1-D.ignitionFraction)*r*n/Math.max(.01,t));let a=this.flameDamageThisStep.get(e)??0,o=t===void 0?D.damagePerSecond:e.maxHealth*(1-D.ignitionFraction)/Math.max(.01,t);i=Math.min(i,Math.max(0,o*this.stepSeconds-a)),this.flameDamageThisStep.set(e,a+i)}this.applyCombustibleDamage(e,i)}applyCombustibleDamage(e,t){let n=e.stage;e.damage(t)&&(e.originalOpacity=e.element.style.opacity,e.ownedOpacity=`0`,e.element.style.opacity=`0`),n!==`burning`&&e.stage===`burning`&&this.notify(`ignite`,e.element)}fireRunEligible(e){return e.kind===`destructible`&&(!e.root||this.specFor(e.root)?.burnable!==!1)&&(!this.selection.playground||!!this.specFor(e.root)?.burnable)}burningFireSources(){let e=this.artworkFire.burningSources();for(let t of this.combustibles.values()){if(t.stage!==`burning`)continue;let n=this.burnProfile(t.element,m);e.push(...le(t,ge(n)))}return e.push(...this.burnSurfaces.burningSources()),e}exposeToFire(e,t){if(!e.length||t<=0){this.externalFireElapsed=0;return}if(this.externalFireElapsed+=t,this.externalFireElapsed<.03333333333333333)return;t=this.externalFireElapsed,this.externalFireElapsed=0;let n=new lt(e);this.artworkFire.expose(n,t,this.runs,e=>this.fireRunEligible(e),(e,t)=>this.burnProfile(e,t),e=>this.notify(`ignite`,e));let r=new Map;for(let e of this.combustibles.values()){if(e.stage===`burning`||e.explodedAt!==null)continue;let i=0;for(let r of n.near(e.rect))i=Math.max(i,oe(t,r,e.rect,this.burnProfile(e.element,m).spreadSeconds));i>0&&r.set(e,i)}for(let[e,t]of r)this.applyCombustibleDamage(e,t*e.maxHealth);this.burnSurfaces.expose(n,t,e=>this.notify(`ignite`,e))}advanceBurn(e,t){performance.now(),this.burnSurfaces.advance(e,t);for(let n of this.combustibles.values())qn(n,e,t,this.capabilityOptions(n.element,`combustible`)?.blastRadiusPx,e=>this.onCombustibleExplosion?.(e,this.claimPoints(n.element,n.points),n.element));this.artworkFire.advance(e,t,this.runs,e=>this.fireRunEligible(e),e=>this.burnLifetime(e),this.destructibleBurnSeconds)}emitCrushSpill(e,t,n){for(let r of cn(t,n))e.emitPaint(e.worldFromDocument(r.point),r.radiusM,r.amount,r.color,E(r.flowMps.x,-r.flowMps.y))}advanceCrushSpills(e,t){for(let[n,r]of this.crushSpills)n.isConnected?(this.emitCrushSpill(e,r,t),r.age>=r.duration&&this.crushSpills.delete(n)):this.crushSpills.delete(n)}beginStep(e,t){let n=performance.now();this.stepSeconds=t,this.advanceCrushSpills(e,t),this.flameDamageThisStep.clear(),this.finishLetterReset(n),this.scan(n),n-this.lastMeasure>120&&(this.measure(),this.lastMeasure=n);let r=this.sceneOffset();for(let e of this.walls)e.viewportAnchored&&(e.rect=this.rectInDocument(e.element,r));for(let e of this.combustibles.values())e.stage===`burning`&&this.applyCombustibleDamage(e,O(e.maxHealth,t,this.burnLifetime(e.element)??D.burnDownSeconds));this.advanceBurn(t,e);let i=new Set(this.crushables.map(e=>e.element));this.solidObjects=this.walls.slice();for(let e of this.combustibles.values())e.explodedAt===null&&!i.has(e.element)&&this.solidObjects.push(e)}stepVehicle(e,t,n=!1,r=this.damage,i=`player`,a=!1){if(this.sourceVehicleId=i,e.mode!==`car`||e.car.explodedAt!==null)return;let o=t.documentScale(),s=this.vehicleMask(e.car.preset,r),c=k(t.documentPoint(e.body.position),t.carVisualOffset(e)),l=E(Math.cos(e.body.angle),-Math.sin(e.body.angle)),u={center:c,forward:l,side:E(-l.y,l.x),halfLength:s.lengthM*o/2,halfWidth:s.widthM*o/2};ui({sim:e,damage:r,shape:u,mask:s,scale:o,viewport:n?{scroll:t.sceneScroll(),...t.viewportSize()}:void 0,walls:a?[]:this.solidObjects,combustibles:this.combustibles,onImpact:this.onImpact,onScrape:this.onScrape,damageCombustible:(e,t)=>this.applyCombustibleDamage(e,t)}),!a&&(ri({targets:this.crushables,crushed:this.crushed,spills:this.crushSpills,shape:u,mask:s,scale:o,projectionScale:this.projection.scale,velocity:e.body.velocity,options:e=>this.capabilityOptions(e,`crushable`),claimPoints:(e,t)=>this.claimPoints(e,t),emitSpill:e=>this.emitCrushSpill(t,e,this.stepSeconds),onCrush:this.onCrush}),ni(e,o,u,s,this.runs,this.lettersFadeStartedAt!==null,e=>!e.root||this.specFor(e.root)?.solid!==!1,e=>this.toughness(e),e=>this.artwork.bounds(e)))}endStep(e){performance.now();let t=this.walls.map(e=>e.rect),n=n=>{n.detached?_n(n,e,t):n.impactCooldown>0&&(n.impactCooldown=Math.max(0,n.impactCooldown-e))};for(let e of this.runs)for(let t of e.glyphs)if(!t.burnFinished){if(e.kind===`pushable`)n(t);else for(let e of t.fragments??[])!e.destroyed&&!e.burnFinished&&n(e)}let r=new Map;for(let e of this.runs){let t=e.root;e.kind===`destructible`&&t&&!this.awardedObjects.has(t)&&r.get(t)!==!1&&r.set(t,e.glyphs.every(e=>e.burnFinished||e.fragments?.length&&e.fragments.every(e=>e.destroyed||e.burnFinished)))}for(let[e,t]of r){if(!t)continue;let n=this.rectInDocument(e,this.sceneOffset());this.onDestructibleDestroyed?.(E(n.x+n.width/2,n.y+n.height/2),this.claimPoints(e,this.pointsFor(e,n)),e,this.artworkFire.burned.has(e)?`burnout`:`break`)}}paintTargetMask(e,t){Hr(e,t,{crushables:this.crushables,crushed:this.crushed,combustibles:this.combustibles.values(),runs:this.runs})}step(e,t,n,r=!1,i=this.damage){this.beginStep(t,n),this.stepVehicle(e,t,r,i),this.endStep(n)}firstProjectileHit(e,t,n,r){return this.scan(performance.now()),si({walls:this.walls,combustibles:this.combustibles.values(),runs:this.runs},e,t,n,r)}projectileHit(e,t,n){return this.firstProjectileHit(e,t,n)}bulletImpact(e,t,n,r){let i=r??this.firstProjectileHit(e,t,n);if(!i)return null;if(i.kind===`wall`)return i.point;this.notify(`hit`,i.combustible?.element??i.glyph?.root),i.combustible&&this.damageCombustible(i.combustible,`bullet`);let a=E(t.x-e.x,t.y-e.y),o=P(a),s=o>0?T(a,1/o):E(1,0);return i.kind===`pushable`&&i.glyph&&dn(i.glyph,T(s,260),s,(Math.random()-.5)*5),i.kind===`destructible`&&i.glyph&&i.glyph.breakable!==!1&&i.piece&&this.carveInk(i.glyph,i.piece,k(i.point,T(s,n*.25)),Math.max(4.2,n*1.9)),i.point}rocketImpact(e,t,n,r=1,i){let a=i??this.firstProjectileHit(e,t,n);return a?(a.kind!==`wall`&&this.applyAreaImpact(a.point,Be(r)),a.point):null}applyAreaImpact(e,t,n=new Set){ai(e,t,n,{combustibles:this.combustibles.values(),runs:this.runs,burning:this.artworkFire.burning,flameExposure:this.artworkFire.flameExposure},{damageCombustible:(e,t)=>this.damageCombustible(e,`rocket`,t),notify:(e,t)=>this.notify(e,t),burnProfile:(e,t)=>this.burnProfile(e,t),blastInk:(e,t,n)=>this.blastInk(e,t,n),carveInk:(e,t,n,r)=>this.carveInk(e,t,n,r)})}draw(e,t,n){performance.now(),this.finishLetterReset(performance.now()),Ur(e,t,n,{crushed:this.crushed.keys(),hasCrushedPaint:e=>!!this.capabilityOptions(e,`crushable`)?.crushedPaintColor,projection:this.projection,offset:this.sceneOffset(),runs:this.runs,layout:e=>this.artwork.bounds(e),burnSprites:this.burnSprites,textLayers:this.textLayers,fragmentAtlas:this.fragmentAtlas,fade:he(this.lettersFadeStartedAt,performance.now())})}drawDebug(e,t,n,r=this.damage){Gr({walls:this.walls,liquidElements:this.liquidElements,combustibles:this.combustibles.values(),runs:this.runs,autoPaintElements:this.autoPaint?.elements,mask:this.vehicleMask(t.car.preset,r)},e,t,n)}resetObject(e){let t=this.selection.playground?.objects.find(t=>t.id===e)?.target;if(!t)return!1;this.runs=this.runs.filter(e=>{if(e.root!==t)return!0;for(let t of e.glyphs)this.artworkFire.removeGlyph(t);return En(e),!1}),this.artworkFire.burned.delete(t),this.ignitedRoots.delete(t);let n=this.combustibles.get(t);return n&&(n.ownedOpacity!==void 0&&t instanceof HTMLElement&&t.style.opacity===n.ownedOpacity&&(t.style.opacity=n.originalOpacity),this.flameDamageThisStep.delete(n),this.combustibles.delete(t)),this.liquidBackings.get(t)?.dispose(),this.liquidBackings.delete(t),t instanceof HTMLElement&&(this.restoreCrushable(t),this.crushSpills.delete(t),this.paintTransitions.get(t)?.(),this.paintTransitions.delete(t)),this.awardedObjects.delete(t),this.pointSources.delete(t),this.walls=this.walls.filter(e=>e.element!==t),this.solidObjects=this.solidObjects.filter(e=>e.element!==t),this.crushables=this.crushables.filter(e=>e.element!==t),this.liquidElements=this.liquidElements.filter(e=>e.element!==t),this.artwork.invalidate(),this.dirty=!0,this.lastScan=this.lastMeasure=-1/0,!0}reset(){this.clearPaintSurfaces(),this.clearPaintTransitions(),this.restoreCrushables(),this.restoreCombustibles(),this.restoreText(),this.burnSurfaces.reset(),this.awardedObjects.clear(),this.pointSources.clear(),this.dirty=!0,this.lastScan=-1/0}destroy(){this.artwork.dispose(),this.autoPaint?.dispose(),this.autoPaint=null,this.selection.dispose(),this.clearPaintSurfaces(),this.clearPaintTransitions(),this.restoreCrushables(),this.restoreCombustibles(),this.restoreText(),this.burnSurfaces.reset(),this.walls=[],this.liquidElements=[]}},pi=class{runtime;held=new Set;touch={throttle:0,steer:0,action:!1,boost:!1};arrival=null;arrivalResolve=null;pendingArrival=null;pendingSlotPresses=new Set;ghostPreview=!1;constructor(e){this.runtime=e}get options(){return this.runtime.options()}get world(){return this.runtime.scene()?.world??null}get playground(){return this.runtime.scene()?.playground??null}get simulation(){return this.runtime.scene()?.simulation??null}get renderer(){return this.world?.renderer??null}get collisions(){return this.runtime.scene()?.collisions??null}get odometer(){return this.runtime.scene()?.odometer??null}get sound(){return this.runtime.audio()}resetFrameClock=()=>this.runtime.resetClock();host=(e,...t)=>Ce(this.runtime.report,e,...t);stopArrival=(e=`interrupted`)=>{this.pendingArrival&&=(clearTimeout(this.pendingArrival.timeout),this.pendingArrival.resolve(e),null),this.arrival&&(this.renderer?.setVehicleArrivalOpacity(1),this.arrivalResolve?.(e),this.arrivalResolve=null),this.arrival=null};enterAt=e=>{let t=e.delayMs??0;return!Number.isFinite(t)||t<0?Promise.resolve(`unavailable`):t===0?this.startArrival(e):(this.stopArrival(),new Promise(n=>{let r=setTimeout(()=>{this.pendingArrival=null,this.startArrival(e).then(n)},t);this.pendingArrival={timeout:r,resolve:n}}))};startArrival=e=>{let t=this.simulation,n=this.renderer;if(!t||!n||t.paused||t.mode!==`car`)return Promise.resolve(`unavailable`);let r=i(e,t,n.documentScale());if(!r)return Promise.resolve(`unavailable`);if(window.matchMedia(`(prefers-reduced-motion: reduce)`).matches){let e=this.handle.parkAt({xPx:r.destination.x,yPx:r.destination.y,angleRad:r.headingRad});return Promise.resolve(e?`completed`:`unavailable`)}this.stopArrival(),this.held.clear(),this.touch={throttle:0,steer:0,action:!1,boost:!1},t.body.position=n.worldFromDocument(r.start),t.body.angle=r.headingRad,t.body.velocity=r.velocity,t.body.spin=0,n.interruptFollow();let o=new a(r.fadeDurationSeconds,r.steer,r.serviceBrake);return this.arrival=o,n.beginVehicleArrivalFade(),new Promise(e=>{this.arrivalResolve=e})};paintedCar=(e=this.simulation)=>{let t=this.renderer,n=this.collisions;if(!this.options.overlay||!e||!t||!n||e.mode!==`car`)return null;let r=n.vehicleMask(e.car.preset),i=k(t.documentPoint(e.body.position),t.carVisualOffset(e)),a=E(Math.cos(e.body.angle),-Math.sin(e.body.angle));return{mask:r,shape:{center:i,forward:a,side:E(-a.y,a.x),halfLength:r.lengthM*t.documentScale()/2,halfWidth:r.widthM*t.documentScale()/2}}};carAnchor=()=>{let e=this.paintedCar();if(!e)return null;let t=R(e.mask.alpha,e.shape),n=this.renderer?.virtualOffset()??E(),r=this.renderer?.presentationScale()??1;return{x:(t.x-n.x-window.scrollX)*r+window.scrollX,y:(t.y-n.y-window.scrollY)*r+window.scrollY,width:t.width*r,height:t.height*r}};clearEffects=()=>{this.world?.fadeEffects()};resetScene=()=>{this.playground?this.playground.reset():this.world?.resetScene()};resetDistance=()=>{let e=this.odometer;e&&e.reset()};cycleDistanceDpi=()=>{let e=this.odometer;return e?e.cycleDpi():gt};touchChange=e=>{this.touch=e,!this.options.paused&&(e.throttle||e.steer||e.action||e.boost)&&(this.renderer?.resumeFollow(),this.host(this.options.onDriveInput),this.options.audioEnabled&&(this.host(this.options.onAudioInteraction),this.sound?.start()))};handle={enterAt:this.enterAt,setSlowMo:(e,t)=>{let n=this.world?.slowMo;n&&(t&&n.configure(t),n.setActive(e))},setLighting:e=>{let t=this.renderer;t&&(t.setVehicleLighting(e),this.host(this.options.onLightingChange,t.getVehicleLighting()))},getLighting:()=>this.renderer?.getVehicleLighting()??xe(),toggleLight:e=>{let t=this.renderer;if(t){let n=t.toggleVehicleLight(e);this.host(this.options.onLightingChange,n)}},startAudio:()=>{this.options.audioEnabled&&this.sound?.start()},getVehicle:e=>e?this.world?.getVehicle(e)??null:this.world?.focusVehicle??null,getCarAnchor:this.carAnchor,setPreset:e=>{let t=this.world;t?.playerVehicle&&t.configureVehicle(t.playerVehicle.id,{preset:e})},getPresetId:()=>this.simulation?.car.preset.id??null,getPose:()=>{let e=this.simulation,t=this.renderer;if(!e||!t||e.mode!==`car`)return null;let n=t.documentPoint(e.body.position);return{xPx:n.x,yPx:n.y,angleRad:e.body.angle}},getPathView:()=>{let e=this.simulation,t=this.renderer;if(!e||!t||e.mode!==`car`)return null;let n=t.documentPoint(e.body.position);return{pose:{xPx:n.x,yPx:n.y,angleRad:e.body.angle},pixelsPerMeter:t.documentScale(),sceneScroll:t.sceneScroll()}},clearEffects:this.clearEffects,getPlayground:()=>this.playground,reset:this.resetScene,getDistance:()=>this.odometer?.readout??gt,resetDistance:this.resetDistance,cycleDistanceDpi:this.cycleDistanceDpi,addLiquid:(e,t)=>{let n=this.renderer;if(!n)return!1;let r,i=typeof t.at==`string`?document.querySelector(t.at):t.at;if(!i)return!1;if(i instanceof Element){let e=i.getBoundingClientRect(),t=n.virtualOffset();r={x:e.left+e.width/2+window.scrollX+t.x,y:e.top+e.height/2+window.scrollY+t.y}}else r={x:i.xPx,y:i.yPx};return n.addLiquid(e,{...t,at:n.worldFromDocument(r)}),!0},ejectLiquid:(e=`oil`,t)=>{let n=this.simulation;n&&this.renderer?.ejectLiquid(n,g(e),t?v(t):void 0)},resetTo:e=>{let t=this.simulation,n=this.renderer;return!t||!n||!Number.isFinite(e.xPx)||!Number.isFinite(e.yPx)||e.angleRad!==void 0&&!Number.isFinite(e.angleRad)?!1:(this.stopArrival(),this.world?.resetEffects(),this.world?.focusVehicle?.reset(),this.resetFrameClock(),t.body.position=n.worldFromDocument(E(e.xPx,e.yPx)),t.body.angle=e.angleRad??-Math.PI/2,t.barrier=this.options.overlay&&this.options.viewportWalls,this.held?.clear(),this.sound?.setHorn(!1),!0)},parkAt:e=>{let t=this.simulation,n=this.renderer;if(!t||!n||![e.xPx,e.yPx,e.angleRad].every(Number.isFinite))return!1;this.stopArrival();let r=this.world?.focusVehicle?.id;return r&&this.playground?.zones.relocateVehicle(r),t.body.position=n.worldFromDocument(E(e.xPx,e.yPx)),t.body.angle=e.angleRad,t.body.velocity=E(),t.body.spin=0,this.resetFrameClock(),this.touch={throttle:0,steer:0,action:!1,boost:!1},n.interruptFollow(),!0},saveState:()=>this.world?.saveState()??null,restoreState:e=>{let t=this.world;return!t||e.world!==t||!e.available?!1:(this.stopArrival(),this.held?.clear(),this.touch={throttle:0,steer:0,action:!1,boost:!1},this.sound?.setHorn(!1),this.resetFrameClock(),t.restoreState(e),this.sound?.setPreset(t.sim.car.preset),!0)}};readInput=()=>{let e=Ae(this.held),t=this.touch;return{throttle:t.throttle||e.throttle,steer:t.steer||e.steer,action:t.action||e.action,boost:!!t.boost||!!e.boost,slots:e.slots,slotPresses:[...this.pendingSlotPresses],machineGun:!!e.machineGun,flamethrower:!!e.flamethrower,rocket:!!t.rocket,ghost:!!e.ghost||this.ghostPreview}};keyDown=e=>{let t=this.runtime.scene();if(!t)return;let{simulation:n,world:r,collisions:i}=t,a=r.renderer,o=this.held;if(!(e.defaultPrevented||e.composedPath().some(e=>e instanceof Element&&e.matches(`[data-jr-ui],[data-jr-touch-controls]`)))){if(this.options.paused){let t=e.code===`Space`&&e.target instanceof Element&&!!e.target.closest(`button,a,summary,[role="button"],[role="link"]`);!this.options.onStartRequest||e.metaKey||e.ctrlKey||e.altKey||je(e)||t||!V.has(e.code)&&e.code!==`KeyH`||(e.preventDefault(),o.add(e.code),a.resumeFollow(),e.code===`KeyH`&&n.mode===`car`&&this.sound?.setHorn(!0),this.host(this.options.onStartRequest))}else if(!(e.metaKey||e.ctrlKey||e.altKey||je(e))&&!(e.code===`Space`&&e.target instanceof Element&&e.target.closest(`button,a,summary,[role="button"],[role="link"]`))&&((V.has(e.code)||Me.has(e.code)||e.code===`KeyH`)&&e.preventDefault(),V.has(e.code)&&!o.has(e.code)&&a.resumeFollow(),e.code===`KeyH`&&!o.has(`KeyH`)&&n.mode===`car`&&this.sound?.setHorn(!0),/^Digit[1-9]$/.test(e.code)&&!o.has(e.code)&&this.pendingSlotPresses.add(Number(e.code.slice(-1))),o.add(e.code),(V.has(e.code)||e.code===`KeyH`)&&(V.has(e.code)&&!e.repeat&&n.mode===`car`&&this.host(this.options.onDriveInput),n.mode===`car`&&this.options.audioEnabled&&(this.host(this.options.onAudioInteraction),this.sound?.start())),!e.repeat))switch(e.code){case`KeyV`:r.slowMo.start();break;case`KeyU`:{let e=a.toggleVehicleLight(`underglow`);this.host(this.options.onLightingChange,e);break}case`KeyC`:this.resetScene();break;case`KeyF`:a.flashTargets((e,t)=>i.paintTargetMask(e,t));break;case`KeyP`:n.paused=!n.paused,this.runtime.resetClock();break;case`KeyB`:this.options.overlay||(n.barrier=!n.barrier);break;case`KeyG`:this.options.overlay||(n.gravity=!n.gravity);break;case`KeyZ`:this.options.overlay||(a.deadZone=!a.deadZone);break;case`Escape`:this.host(this.options.onExit)}}};keyUp=e=>{this.held.delete(e.code),e.code===`KeyV`&&this.runtime.scene()?.world.slowMo.stop(),e.code===`KeyH`&&this.sound?.setHorn(!1)};allowFollow=()=>!this.arrival;neutral={throttle:0,steer:0,action:!1,boost:!1};selectInput=(e,t)=>{let n=this.runtime.scene();if(!n)return{controls:this.neutral};let r=n.simulation,i=n.world.renderer,a=this.readInput();(this.arrival||this.pendingArrival)&&(a.throttle!==0||a.steer!==0||a.action||a.boost||a.slots?.length||a.slotPresses?.length||a.machineGun||a.flamethrower||a.rocket||a.ghost&&!this.ghostPreview)&&this.stopArrival();let o=this.arrival,s=!t&&!o&&!this.options.automatedInput,c=this.neutral,l;return t||(o?(c=o.drive(r,i.documentPoint(r.body.position),i.documentScale(),e,e=>i.worldFromDocument(e)),i.setVehicleArrivalOpacity(o.opacity),l=()=>{o.complete&&this.stopArrival(`completed`)}):c=this.options.automatedInput??a),this.ghostPreview&&(c={...c,ghost:!0}),{controls:c,userDriven:s,manualMoved:t,allowFollow:this.allowFollow,afterPhysics:()=>{l?.()}}};get hasArrival(){return this.arrival!==null}get hornHeld(){return this.held.has(`KeyH`)}releaseInput(){this.held.clear(),this.pendingSlotPresses.clear(),this.runtime.scene()?.world.slowMo.stop(),this.sound?.setHorn(!1)}pauseInput(){this.runtime.resetClock(),this.touch={throttle:0,steer:0,action:!1,boost:!1}}beginPlacement(){this.stopArrival(),this.simulation?.resetAtCurrentPose(),this.held.clear(),this.sound?.setHorn(!1)}afterStep(e){e||this.pendingSlotPresses.clear()}presentationInput(){let e=this.world,t=this.simulation;return!e||!t||t.paused?this.neutral:this.arrival||this.options.automatedInput?t.lastInput:this.readInput()}dispose(){this.releaseInput(),this.stopArrival(),this.touch={throttle:0,steer:0,action:!1,boost:!1}}};function mi({canvas:e,sim:t,renderer:n,collisions:r,game:i},a){let o=null,s=null,c=!1,l=0,u=``,d=()=>{if(s?.target)try{s.target.releasePointerCapture(s.pointerId)}catch{}s?.moved&&(t.body.velocity=E(),t.body.spin=0,document.documentElement.style.cursor=u),s=null},f=e=>n.documentFromViewport(E(e.clientX,e.clientY)),p=e=>{if(!a.options().showVehicle)return null;let t=a.paintedCar();if(!t)return null;let n=f(e);return z(t.mask.alpha,t.shape,{x:n.x-2,y:n.y-2,width:4,height:4})?t:null},m=!1,h=``,g=!1,_=null,v=``,y=0,b=null,x=e=>{let t=a.toolbar?.();t&&(t.dataset.visible=e?`true`:`false`,t.inert=!e)},S=()=>{y=0,g&&(document.documentElement.style.cursor=v),g=!1,_=null,r.setHoveredVehicle(null),x(!1)},C=()=>{let e=a.toolbar?.();if(!e||!_)return;let t=a.paintedCar(_.sim);if(!t)return;let r=R(t.mask.alpha,t.shape),i=n.viewportFromDocument(E(r.x+r.width,r.y)),o=i.x,s=i.y,c=e.getBoundingClientRect().width,l=e.getBoundingClientRect().height,u=Math.max(8,Math.min(window.innerWidth-c-8,o+8)),d=Math.max(8,Math.min(window.innerHeight-l-8,s-8));e.style.left=`${u}px`,e.style.top=`${d}px`},D=e=>{b=E(e.clientX,e.clientY);let t=a.toolbar?.();if(s?.moved||a.options().paused||n.vehicleMarkerAt(E(e.clientX,e.clientY))||document.querySelector(`[data-jr-popover-host]`)){y&&window.clearTimeout(y),S();return}let o=!!t&&e.composedPath().includes(t),c=t?.getBoundingClientRect(),l=g&&!!a.options().showToolbar&&!!c&&e.clientX>=c.left-20&&e.clientX<=c.right+20&&e.clientY>=c.top-20&&e.clientY<=c.bottom+20,u=!o&&p(e),d=!!u||o||l;!d&&g?y||=window.setTimeout(S,180):(y&&=(window.clearTimeout(y),0),d&&!g&&(v=document.documentElement.style.cursor,g=!0),d&&!o&&(document.documentElement.style.cursor=`pointer`),x(d&&!!a.options().showToolbar),!(!d||o||l&&!u)&&(_=i.focusVehicle??null,r.setHoveredVehicle(_?.id??null),C()))},O=t=>{let n=e.getBoundingClientRect();return E(t.clientX-n.left,t.clientY-n.top)},A=r=>{if(e.focus(),r.button!==0||t.mode!==`brick`||o)return;let i=O(r),a=t.body.local(n.world(i));Math.abs(a.x)>2||Math.abs(a.y)>1||(o={pointerId:r.pointerId,local:a,start:i,current:i},e.setPointerCapture(r.pointerId))},j=e=>{if(!o||e.pointerId!==o.pointerId)return;o.current=O(e);let n=w(o.current,o.start),r=P(n),i=r>250?T(n,250/r):n;t.brickForce={local:o.local,force:T(E(i.x,-i.y),65)}},M=e=>{o&&e.pointerId===o.pointerId&&(o=null,t.brickForce=null)},N=r=>{if(!a.options().overlay||!a.options().showVehicle||t.mode!==`car`||s||!r.isPrimary||r.button!==0||document.querySelector(`[data-jr-popover-host]`))return;let i=n.vehicleMarkerAt(E(r.clientX,r.clientY));if(!i&&(a.options().paused||!a.options().canPlaceManually||r.target instanceof Element&&r.target.closest(`[data-jr-ui],[data-jr-touch-controls]`)||!p(r)))return;r.preventDefault(),i&&e.focus({preventScroll:!0});let o=f(r),c=n.documentPoint(t.body.position),l=w(o,c),u=Math.atan2(-l.y,l.x);s={pointerId:r.pointerId,target:r.target instanceof Element?r.target:null,startClient:E(r.clientX,r.clientY),grabOffset:i?E():w(c,o),startAngle:t.body.angle,pointerAngle:u,polarRotation:P(l)>20,mode:!i&&r.shiftKey&&P(t.body.velocity)<.45?`rotate`:`move`,moved:!1,marker:i??void 0,lastTime:r.timeStamp}},F=e=>{if(!s||e.pointerId!==s.pointerId)return;let i=w(E(e.clientX,e.clientY),s.startClient);if(!s.moved&&P(i)<5||s.marker&&(s.marker.sim!==t||!a.options().canPlaceManually||a.options().paused))return;if(!s.moved){s.moved=!0,a.beginPlacement(),s.marker?n.interruptFollow():n.resumeFollow(),u=document.documentElement.style.cursor,document.documentElement.style.cursor=`grabbing`,x(!1),s.marker&&(t.body.position=n.worldFromDocument(f(e)),t.body.velocity=E(),t.body.spin=0);try{s.target?.setPointerCapture(e.pointerId)}catch{}}e.preventDefault(),e.stopImmediatePropagation();let o=Math.max(1/120,Math.min(.05,(e.timeStamp-s.lastTime)/1e3||1/120));s.lastTime=e.timeStamp;let c=f(e),l=n.documentScale();if(s.mode===`rotate`){let e=n.documentPoint(t.body.position),l=s.polarRotation?Math.atan2(-(c.y-e.y),c.x-e.x):0,u=s.polarRotation?Math.atan2(Math.sin(l-s.pointerAngle),Math.cos(l-s.pointerAngle)):i.x/80,d=t.body.angle;t.body.angle=s.startAngle+u,t.body.spin=Math.max(-8,Math.min(8,Math.atan2(Math.sin(t.body.angle-d),Math.cos(t.body.angle-d))/o)),r.step(t,n,o,a.options().overlay&&t.barrier)}else{let e=n.documentPoint(t.body.position),i=k(c,s.grabOffset),u=w(i,e),d=r?.vehicleMask(t.car.preset),f=Math.max(6,(d?.widthM??t.car.preset.geometry.widthM)*l/3),p=Math.max(1,Math.ceil(P(u)/f));for(let i=1;i<=p;i++){let s=k(e,T(u,i/p)),c=n.documentPoint(t.body.position);t.body.position=n.worldFromDocument(s);let d=w(s,c),f=E(d.x/l/(o/p),-d.y/l/(o/p)),m=P(f);if(t.body.velocity=m>35?T(f,35/m):f,r.step(t,n,o/p,a.options().overlay&&t.barrier),P(w(n.documentPoint(t.body.position),s))>2)break}}t.body.velocity=E(),t.body.spin=0,s.marker||n.followDocument(t)},I=e=>{if(s&&e.pointerId===s.pointerId){if(s.marker&&!s.moved&&e.type!==`pointercancel`&&(e.preventDefault(),e.stopImmediatePropagation(),n.revealVehicle(s.marker.sim)),s.moved||s.marker){e.preventDefault(),e.stopImmediatePropagation(),c=!0,l&&window.clearTimeout(l),l=window.setTimeout(()=>{c=!1,l=0},0);try{s.target?.releasePointerCapture(e.pointerId)}catch{}}d()}},L=e=>{if(c){c=!1,e.preventDefault(),e.stopImmediatePropagation();return}if(e.target instanceof Element&&e.target.closest(`[data-jr-ui]`)||!a.options().onCarClick)return;let t=p(e);t&&(e.preventDefault(),e.stopPropagation(),a.carClicked(R(t.mask.alpha,t.shape)))},ee=e=>{e.target instanceof Element&&e.target.closest(`[data-jr-touch-controls]`)||n.interruptFollow()};return{get moved(){return!!s?.moved},clear(){d(),t.brickForce=null,o=null},dragArrow(){let e=o?t.body.world(o.local):null;return o&&e?{from:e,to:k(e,w(n.world(o.current),n.world(o.start)))}:null},present(){if(!s?.moved&&b&&!a.options().paused){let e=n.vehicleMarkerAt(b);e&&!g?(m||=(h=document.documentElement.style.cursor,!0),document.documentElement.style.cursor=e.sim===t&&a.options().canPlaceManually?`grab`:`pointer`):m&&=(document.documentElement.style.cursor=h,!1)}if(_&&i.getVehicle(_.id)!==_)S();else if(g&&(a.options().paused||document.querySelector(`[data-jr-popover-host]`)))y&&window.clearTimeout(y),S();else if(g){C();let e=a.toolbar?.(),t=_?a.paintedCar(_.sim):null,n=b,r=n?f({clientX:n.x,clientY:n.y}):null,i=!!t&&!!r&&z(t.mask.alpha,t.shape,{x:r.x-2,y:r.y-2,width:4,height:4}),o=e?.getBoundingClientRect(),s=!!n&&!!o&&n.x>=o.left&&n.x<=o.right&&n.y>=o.top&&n.y<=o.bottom;!i&&!s?y||=window.setTimeout(S,180):y&&=(window.clearTimeout(y),0)}},listen(t){t.listen(window,`pointerdown`,N,!0),t.listen(window,`pointermove`,F,{capture:!0,passive:!1}),t.listen(window,`pointermove`,D,!0),t.listen(window,`pointerup`,I,!0),t.listen(window,`pointercancel`,I,!0),t.listen(window,`click`,L,!0),t.listen(window,`wheel`,ee,{passive:!0}),t.listen(window,`touchmove`,ee,{passive:!0}),t.listen(e,`pointerdown`,A),t.listen(e,`pointermove`,j),t.listen(e,`pointerup`,M),t.listen(e,`pointercancel`,M)},dispose(){d(),t.brickForce=null,o=null,y&&window.clearTimeout(y),l&&window.clearTimeout(l),S(),m&&(document.documentElement.style.cursor=h)}}}function hi(e){for(let t of Object.keys(e))if(!Object.hasOwn(Pe,t))throw TypeError(`Unknown browser session option: ${t}`);let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)),n=Se(t);return{...Ne,...t,...n,initialAngle:e.initialAngle??(e.overlay??Ne.overlay?-Math.PI/2:0)}}function gi(e,t,n){let r={...e,...n},i=hi(r);for(let e of Fe)if(i[e]!==t[e])throw TypeError(`Browser session option ${e} is fixed at mount; create a new session to change it`);return{authored:r,options:i}}function _i(e,t,n){bt(e,t,n),n&&n.showVehicle===t.showVehicle||(e.primaryVehicleVisible=t.showVehicle),n||e.setAbsoluteViewport(),n&&n.screenShakeProfiles===t.screenShakeProfiles||e.setScreenShakeProfiles(t.screenShakeProfiles)}var vi=e({BrowserSessionCore:()=>yi}),yi=class{canvas;presentation;rendering;options;authoredOptions;resources=new r;releaseLayers;disposed=!1;odometer=null;simulation=null;renderer=null;world=null;playground=null;boundSpecs=void 0;bindings=[];collisions=null;sound=null;controller;scene=null;resetFrameClock=()=>{};constructor(e,t={},n,r){this.canvas=e,this.presentation=n,this.rendering=r,this.authoredOptions={...t},this.options=hi(this.authoredOptions),this.controller=new pi({scene:()=>this.scene,options:()=>this.options,audio:()=>this.sound,resetClock:()=>this.resetFrameClock(),report:e=>this.report(e)});try{if(this.resources.own(()=>this.releaseLayers?.()),this.options.overlay){let e=document.createElement(`style`);e.dataset.jrBrowserStyles=``,e.textContent=an,this.resources.own(()=>e.remove()),document.head.append(e);let t=this.rendering.installPageLayers(this.options.foregroundSelector);this.releaseLayers=()=>t.dispose()}let e=this.mount();e&&this.resources.own(e)}catch(e){throw this.dispose(),e}}report=e=>{let t=this.playground?.registry??this.options.playground;t?t.report(e):console.error(`JoyRide host callback failed`,e)};host=(e,...t)=>Ce(this.report,e,...t);get handle(){return this.controller.handle}touchChange=e=>{this.disposed||this.controller.touchChange(e)};update(e){if(this.disposed)throw Error(`Browser session is disposed`);let t=this.options,{authored:n,options:r}=gi(this.authoredOptions,t,e);if(this.authoredOptions=n,this.options=r,t.vehicleDestructible!==this.options.vehicleDestructible&&this.world?.setVehicleDestructible(this.options.vehicleDestructible),t.toolsEnabled!==this.options.toolsEnabled&&this.world?.setToolsEnabled(this.options.toolsEnabled),t.mode!==this.options.mode){let e=this.simulation;e&&this.options.mode&&e.mode!==this.options.mode&&(this.world?.focusVehicle?.setMode(this.options.mode),this.renderer?.reset())}if(t.preset!==this.options.preset){let e=this.world;e?.playerVehicle&&e.configureVehicle(e.playerVehicle.id,{preset:this.options.preset})}if(t.paused!==this.options.paused&&(this.simulation&&(this.simulation.paused=this.options.paused),this.options.paused&&this.controller.pauseInput()),t.paused!==this.options.paused||t.audioEnabled!==this.options.audioEnabled){let e=this.simulation;this.options.paused&&!this.options.audioEnabled&&e&&this.renderer?.restorePage(e)}if(t.overlay!==this.options.overlay||t.viewportWalls!==this.options.viewportWalls){let e=this.world?.playerVehicle;e&&(e.sim.barrier=this.options.overlay&&this.options.viewportWalls)}t.idleSound!==this.options.idleSound&&this.sound?.setIdleSound(this.options.idleSound),t.masterVolume!==this.options.masterVolume&&this.sound?.setMasterVolume(this.options.masterVolume),t.showHealthBars!==this.options.showHealthBars&&this.collisions?.setShowHealthBars(this.options.showHealthBars),t.destructibleBurnSeconds!==this.options.destructibleBurnSeconds&&this.collisions?.setDestructibleBurnSeconds(this.options.destructibleBurnSeconds),t.deform!==this.options.deform&&this.world?.setDeformationEnabled(this.options.deform),this.renderer&&_i(this.renderer,this.options,t),t.audioEnabled!==this.options.audioEnabled&&this.updateAudio(),(t.autoPaint!==this.options.autoPaint||t.overlay!==this.options.overlay)&&this.collisions?.setAutoPaint(this.options.overlay&&this.options.autoPaint),(t.overlay!==this.options.overlay||t.foregroundSelector!==this.options.foregroundSelector)&&(this.releaseLayers?.(),this.releaseLayers=(()=>{if(!this.options.overlay)return;let e=this.rendering.installPageLayers(this.options.foregroundSelector);return()=>e.dispose()})()),t.bindings!==this.options.bindings&&this.replaceBindings()}updateAudio(){let e=this.sound;e&&(this.options.audioEnabled?e.start():this.options.audioEngine?e.setActive(!1):(e.stop(),this.sound=new f(this.simulation?.car.preset??this.options.preset,{idleSound:this.options.idleSound,masterVolume:this.options.masterVolume})))}replaceBindings(){let e=this.playground?.registry;if(!e||this.boundSpecs===this.options.bindings)return;let t=this.boundSpecs;for(let e of this.bindings)e.dispose();try{this.bindings=e.bindAll(this.options.bindings??[]),this.boundSpecs=this.options.bindings}catch(n){this.bindings=e.bindAll(t??[]),e.report(n)}}mount(){let e=this.canvas;if(!e)return;let t=new r,i=()=>t.dispose();try{let r=new N;r.setMode(this.options.mode??this.options.initialMode),r.setPreset(this.options.preset),r.paused=this.options.paused||this.options.initialArrivalPending,r.body.angle=this.options.initialAngle,r.barrier=this.options.overlay&&this.options.viewportWalls;let a=new this.rendering.Renderer(e,this.options.overlay,this.options.quality);this.options.initialArrivalPending&&a.setVehicleArrivalOpacity(0);let o=()=>a.dispose();t.own(o),this.options.initialGroundMarks?.length&&a.seedGroundMarks(this.options.initialGroundMarks),this.options.initialPuddles?.length&&a.setInitialPuddles(this.options.initialPuddles.flatMap(e=>{let t=e.target.current?.getBoundingClientRect();return t?[{kind:e.kind,color:e.color,point:E(t.left+t.width/2+window.scrollX,t.top+t.height/2+window.scrollY),amount:e.amount}]:[]}));let s=new vt;t.own(()=>s.flush()),this.odometer=s;let c=()=>s.flush(),l=0;if(this.options.overlay&&this.options.spawnTarget?.current){let e=this.options.spawnTarget.current.getBoundingClientRect();r.body.position=a.world(E(e.left+e.width/2,e.top+e.height/2))}let u=this.options.audioEngine??new f(this.options.preset,{idleSound:this.options.idleSound,masterVolume:this.options.masterVolume});this.options.audioEngine||t.own(()=>(this.sound??u).stop());let d=new fi({sceneOffset:()=>a.virtualOffset(),projection:a.documentProjection}),p=()=>d.destroy();t.own(p);let m=this.options.overlay?this.options.playground??new n(document,this.options.definitions):null;m&&(this.options.playground||t.own(()=>m.dispose()),d.setPlayground(m),this.bindings=m.bindAll(this.options.bindings??[]),this.boundSpecs=this.options.bindings,t.own(()=>{for(let e of this.bindings)e.dispose();this.bindings=[]}));let h=new tt(r,a,s,()=>this.sound??u,this.options.overlay,d,{vehicleDestructible:this.options.vehicleDestructible,toolsEnabled:this.options.toolsEnabled,autoPaint:this.options.overlay&&this.options.autoPaint});t.disown(o),t.disown(p);let g=new rn(h,m);t.own(()=>g.dispose()),this.world=h;let _=g.page;this.playground=_,this.scene={world:h,playground:_,simulation:r,collisions:d,odometer:s},t.own(()=>this.controller.dispose()),h.setDeformationEnabled(this.options.deform),_i(a,this.options),d.prepare(this.options.preset),d.setShowHealthBars(this.options.showHealthBars),d.setDestructibleBurnSeconds(this.options.destructibleBurnSeconds),u.setIdleSound(this.options.idleSound),u.setMasterVolume(this.options.masterVolume),this.simulation=r,this.renderer=a,this.collisions=d,this.sound=u;let v=mi({canvas:e,sim:r,renderer:a,collisions:d,game:h},{options:()=>this.options,toolbar:()=>this.host(this.presentation.toolbar),paintedCar:this.controller.paintedCar,beginPlacement:()=>this.controller.beginPlacement(),carClicked:e=>this.host(this.options.onCarClick,e)});t.own(()=>v.dispose());let y=0,b=new de,x=g.clock(()=>!r.paused&&!document.hidden,e=>D(e),(e,t)=>O(e,t)),S=()=>{x.reset(),b.reset(),this.controller.releaseInput()};this.resetFrameClock=S;let C=()=>{v.clear(),S()},w=()=>{document.hidden&&(C(),this.sound?.setActive(!1))},T=new ResizeObserver(()=>{if(a.resize(),this.options.overlay&&this.options.spawnTarget?.current&&r.paused&&!this.options.audioEnabled&&!this.controller.hasArrival){let e=this.options.spawnTarget.current.getBoundingClientRect();r.body.position=a.world(E(e.left+e.width/2,e.top+e.height/2))}});t.own(()=>T.disconnect()),T.observe(e),this.options.overlay&&T.observe(document.body),this.options.overlay&&this.options.spawnTarget?.current&&T.observe(this.options.spawnTarget.current);let D=e=>{_?.sync(),h.step(this.controller.selectInput(e,v.moved),e),_?.step(e,!r.paused&&!document.hidden),this.controller.afterStep(v.moved)},O=(e,t)=>{_?.sync(),(r.paused||document.hidden)&&_?.step(0,!1);let n=b.sample(e),i=h.focusVehicle;if(!i)return;let o=tn(i,this.sound,h.points,h.totalPoints);_?.present({fps:n,speedMps:P(i.sim.body.velocity),rpm:o.rpm??0,gear:o.gear??`N`,health:i.sim.car.health,points:h.points});let c=this.controller.presentationInput(),u=v.dragArrow();h.present(e,t,c,this.controller.hornHeld,this.options.audioEnabled,this.options.masterVolume,u),v.present(),document.hidden||a.setCameraFrame(this.host(this.presentation.cameraFrame)??null),e-l>=2e3&&(s.flush(),l=e),this.options.onStateChange&&e-y>100&&(this.host(this.options.onStateChange,h.snapshot()),y=e)};return(this.options.toolsEnabled||this.options.overlay&&document.querySelector(`[data-jr-burnable],[data-jr-combustible]`))&&a.prepareFire(),x.start(),v.listen(t),t.listen(window,`keydown`,this.controller.keyDown),t.listen(window,`keyup`,this.controller.keyUp),t.listen(window,`blur`,C),t.listen(window,`pagehide`,c),t.listen(document,`visibilitychange`,w),m&&queueMicrotask(()=>{this.disposed||this.host(this.options.onReady,h,m)}),()=>{i(),this.playground=null,this.world===h&&(this.world=null),this.sound?.setHorn(!1),s.flush(),this.odometer===s&&(this.odometer=null),this.scene=null,this.resetFrameClock=()=>{},this.simulation=null,this.renderer=null,this.collisions=null,this.sound=null}}catch(e){throw i(),this.world=null,this.playground=null,this.scene=null,this.simulation=null,this.renderer=null,this.collisions=null,this.sound=null,e}}dispose(){this.disposed||(this.disposed=!0,this.resources.dispose())}};export{vi as t};
|
|
1
|
+
import{n as e}from"./rolldown-runtime-XKyaHtl9.js";import{a as t,i as n,l as r,r as i,t as a}from"./runtime~react~browser-session-core-B9a1rLNB.js";import{c as o,i as s}from"./configuration~react~vehicle-popover~EmbedPanel~Documentation~JoyRideView~browser-session-co~fvauaeow-mgPW9A8j.js";import{a as c,i as l,n as u,r as d,t as f}from"./runtime~react~vehicle-popover~browser-session-core-CdrNmP2l.js";import{n as p,t as m}from"./configuration~react~vehicle-popover~JoyRideView~browser-session-core~renderer-CPZkP_Db.js";import{a as h,c as g,l as _,r as v}from"./definitions~react~vehicle-popover~Documentation~JoyRideView~browser-session-core~renderer-BG7sJuWo.js";import{n as y,r as b}from"./definitions~react~vehicle-popover~browser-session-core~renderer-RDNEXk_b.js";import{_ as x,a as S,b as C,c as w,d as T,f as E,g as D,h as O,l as k,m as A,o as j,p as M,r as N,s as P,t as F,v as I,x as L,y as ee}from"./runtime~react~vehicle-popover~browser-session-core~renderer-Dmgs7E8f.js";import{A as te,C as ne,D as R,E as re,O as z,T as ie,a as B,b as ae,d as oe,j as se,k as ce,l as le,n as ue,o as de,p as fe,r as pe,s as me,t as he,u as ge,w as _e}from"./runtime~vehicle-popover~browser-session-core~renderer-EswVyRVp.js";import{n as ve}from"./definitions~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-DcDccU8O.js";import{n as ye,t as be}from"./runtime~vehicle-popover~browser-session-core-D0thHU3T.js";import{n as xe}from"./configuration~react~vehicle-popover~EmbedPanel~JoyRideView~browser-session-core~renderer-Bo9KSudc.js";import{n as Se}from"./configuration~react~vehicle-popover~EmbedPanel~JoyRideView~browser-session-core-rFMaxKZs.js";import{t as Ce}from"./runtime~react~JoyRideView~browser-session-core-BRSYGakW.js";import{c as we,l as Te,n as Ee,r as De,s as Oe}from"./definitions~react~browser-session-core-Bc5BhqaX.js";import{r as ke}from"./controls~react~vehicle-popover~JoyRideView~browser-session-core~renderer-Cnf30Q_A.js";import{a as Ae,i as V,n as je,o as Me}from"./controls~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-CoAcght5.js";import{n as Ne,r as Pe,t as Fe}from"./runtime~JoyRideView~browser-session-core-DkTKYWMV.js";var Ie=Object.freeze({speedFactor:.5,rampMs:300,zoomFactor:0,curve:`ease-in-out`}),Le={linear:e=>e,"ease-in":e=>e*e,"ease-out":e=>e*(2-e),"ease-in-out":e=>e*e*(3-2*e)},Re={linear:e=>e*e/2,"ease-in":e=>e*e*e/3,"ease-out":e=>e*e-e*e*e/3,"ease-in-out":e=>e*e*e-e*e*e*e/2},ze=class{settings={...Ie};enabled=!1;speed=1;zoom=1;fromSpeed=1;fromZoom=1;elapsed=0;constructor(e={}){this.configure(e)}get options(){return{...this.settings}}get active(){return this.enabled}get speedFactor(){return this.speed}get zoomFactor(){return this.zoom}configure(e){let t={...this.settings,...e};if(!Number.isFinite(t.speedFactor)||t.speedFactor<=0||t.speedFactor>1)throw RangeError(`Slow-mo speedFactor must be greater than zero and at most one.`);if(!Number.isFinite(t.rampMs)||t.rampMs<0)throw RangeError(`Slow-mo rampMs must be a nonnegative number.`);if(!Number.isFinite(t.zoomFactor)||t.zoomFactor<0||t.zoomFactor>4)throw RangeError(`Slow-mo zoomFactor must be between 0 and 4.`);if(!Object.hasOwn(Le,t.curve))throw TypeError(`Unknown slow-mo curve.`);this.settings=t,this.beginRamp()}setActive(e){this.enabled!==e&&(this.enabled=e,this.beginRamp())}start(){this.setActive(!0)}stop(){this.setActive(!1)}beginRamp(){this.fromSpeed=this.speed,this.fromZoom=this.zoom,this.elapsed=0,this.settings.rampMs||this.advance(0)}advance(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Slow-mo elapsed time must be a nonnegative number.`);let t=this.enabled?this.settings.speedFactor:1,n=this.enabled&&this.settings.zoomFactor||1,r=this.settings.rampMs/1e3;if(!r||this.elapsed>=r)return this.speed=t,this.zoom=n,e*t;let i=this.elapsed/r,a=Math.min(e,r-this.elapsed);this.elapsed+=a;let o=Math.min(1,this.elapsed/r),s=Le[this.settings.curve](o);this.speed=this.fromSpeed+(t-this.fromSpeed)*s,this.zoom=this.fromZoom+(n-this.fromZoom)*s;let c=Re[this.settings.curve](o)-Re[this.settings.curve](i);return a*this.fromSpeed+r*(t-this.fromSpeed)*c+(e-a)*t}reset(){this.enabled=!1,this.speed=this.zoom=this.fromSpeed=this.fromZoom=1,this.elapsed=0}captureState(){return{options:{...this.settings},active:this.enabled,speed:this.speed,zoom:this.zoom,fromSpeed:this.fromSpeed,fromZoom:this.fromZoom,elapsed:this.elapsed}}restoreState(e){this.settings={...e.options},this.enabled=e.active,this.speed=e.speed,this.zoom=e.zoom,this.fromSpeed=e.fromSpeed,this.fromZoom=e.fromZoom,this.elapsed=e.elapsed}},H={radiusPx:92,coreRadiusPx:25,damage:100,impulse:1,ignite:!0};function Be(e=1){let t=Number.isFinite(e)?Math.max(.1,Math.min(3,e)):1;return{radiusPx:Math.max(40,H.radiusPx*t),coreRadiusPx:H.coreRadiusPx*t,damage:H.damage*t,impulse:H.impulse*t,ignite:H.ignite}}function U(e,t,n,r){if(r.width<=0||r.height<=0)return null;let i=0,a=1;for(let o of[`x`,`y`]){let s=t[o]-e[o],c=r[o]-n,l=c+(o===`x`?r.width:r.height)+n*2;if(Math.abs(s)<1e-8){if(e[o]<c||e[o]>l)return null;continue}let u=(c-e[o])/s,d=(l-e[o])/s;if(i=Math.max(i,Math.min(u,d)),a=Math.min(a,Math.max(u,d)),i>a)return null}return i<=1&&a>=0?i:null}var Ve=new WeakMap;function He(e){let t=Ve.get(e);if(t)return t;let n=[],{columns:r,rows:i,solid:a}=e;for(let e=0;e<i;e++)for(let t=0;t<r;t++){let o=e*r+t;a[o]&&(t!==0&&t!==r-1&&e!==0&&e!==i-1&&a[o-1]&&a[o+1]&&a[o-r]&&a[o+r]||n.push(E(2*(t+.5)/r-1,2*(e+.5)/i-1)))}return Ve.set(e,n),n}function Ue(e,t){for(let[n,r]of[[e,t],[t,e]]){let e=n.shape;for(let t of He(n.mask.alpha)){let n=k(e.center,k(T(e.forward,t.x*e.halfLength),T(e.side,t.y*e.halfWidth)));if(re(r.mask.alpha,r.shape,n))return!0}}return!1}function We(e,t){let n=w(e.center,t.center),r=1/0,i=E(1);for(let a of[e.forward,e.side,t.forward,t.side]){let o=e.halfLength*Math.abs(j(a,e.forward))+e.halfWidth*Math.abs(j(a,e.side)),s=t.halfLength*Math.abs(j(a,t.forward))+t.halfWidth*Math.abs(j(a,t.side)),c=j(n,a),l=o+s-Math.abs(c);if(l<=0)return null;l<r&&(r=l,i=T(a,c<0?-1:1))}return{normal:i,depth:r}}function Ge(e,t,n){let{sim:r}=e,i=t.documentScale(),a=E(Math.cos(r.body.angle),-Math.sin(r.body.angle));return{center:k(t.documentPoint(r.body.position),t.carVisualOffset(r)),forward:a,side:E(-a.y,a.x),halfLength:n.lengthM*i/2,halfWidth:n.widthM*i/2}}function Ke(e,t,n,r,i,a){if(e.sim.mode!==`car`||e.sim.car.explodedAt!==null||e.isGhost)return null;let o=Ge(e,t,n),s=U(r,i,a,R(n.alpha,o));if(s===null)return null;let c=w(i,r),l=Math.min(256,Math.max(1,Math.ceil(Math.hypot(c.x,c.y)/Math.max(2,a)))),u=Math.max(0,Math.floor(s*l)-1),d=a>0?[E(),E(a,0),E(-a,0),E(0,a),E(0,-a)]:[E()];for(let e=u;e<=l;e++){let t=k(r,T(c,e/l));if(d.some(e=>re(n.alpha,o,k(t,e))))return t}return null}function qe(e,t,n,r){if(e.length<2)return;let i=t.documentScale(),a=e.filter(e=>e.sim.mode===`car`&&e.sim.car.explodedAt===null&&!e.isGhost).map(e=>{let r=n(e);return{entity:e,mask:r,shape:Ge(e,t,r)}});for(let e=0;e<a.length;e++)for(let n=e+1;n<a.length;n++){let o=a[e],s=a[n],c=We(o.shape,s.shape);if(!c||!Ue(o,s))continue;let l=c.normal,u=E(l.x,-l.y),d=te(o.mask.alpha,o.shape,T(l,-1)),f=te(s.mask.alpha,s.shape,l),p=T(k(d,f),.5),m=t.worldFromDocument(p),h=o.entity.sim.body,g=s.entity.sim.body,_=o.shape,v=s.shape,y=w(m,h.position),b=w(m,g.position),x=j(w(h.velocityAt(m),g.velocityAt(m)),u),C=1/h.mass,D=1/g.mass,O=C+D,A=(c.depth+.5)/i;if(h.position=k(h.position,T(u,A*C/O)),g.position=w(g.position,T(u,A*D/O)),o.shape={...o.shape,center:k(o.shape.center,T(l,(c.depth+.5)*C/O))},s.shape={...s.shape,center:w(s.shape.center,T(l,(c.depth+.5)*D/O))},x>=0)continue;let M=S(y,u),N=S(b,u),P=O+M**2/h.inertia+N**2/g.inertia,F=-(1+(x<-.8?.24:0))*x/P,I=T(u,F);h.impulse(I,m),g.impulse(T(I,-1),m);let L=E(-u.y,u.x),ee=w(h.velocityAt(m),g.velocityAt(m)),ne=S(y,L),R=S(b,L),re=O+ne**2/h.inertia+R**2/g.inertia,z=Math.max(-F*.38,Math.min(F*.38,-j(ee,L)/re)),ie=T(L,z);h.impulse(ie,m),g.impulse(T(ie,-1),m);let B=-x;B<=.8||(o.entity.sim.car.takeImpact(B,h.local(m)),s.entity.sim.car.takeImpact(B,g.local(m)),o.entity.damage.hit(p,l,_,B,i),s.entity.damage.hit(p,T(l,-1),v,B,i),r?.({speedMps:B,point:p,velocity:T(w(h.velocity,g.velocity),i),normal:l,carNormal:se(o.mask.alpha,_,d),pixelsPerMeter:i}))}}function Je(e){if(e.kind===`impact`||e.kind===`scrape`){let{element:t,...n}=e.impact,{element:r,...i}=e;return{...b({...i,impact:n}),element:r,impact:{...b(n),element:t}}}let{element:t,...n}=e;return{...b(n),element:t}}var Ye=class{onObserverError;pending=[];listeners=new Set;draining=!1;constructor(e=e=>console.error(`Joy Ride event observer failed.`,e)){this.onObserverError=e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}captureState(){return this.pending.map(Je)}restoreState(e){this.pending=e.map(Je)}emit(e){this.pending.push(e)}drain(e){if(this.draining||!this.pending.length)return;let t=this.pending;this.pending=[],this.draining=!0;try{for(let n of t){e(n);for(let e of[...this.listeners])if(this.listeners.has(e))try{e(n)}catch(e){try{this.onObserverError(e)}catch(e){console.error(`Joy Ride event observer error reporting failed.`,e)}}}}finally{this.draining=!1}}clear(){this.pending.length=0}},Xe=.15,Ze=class{renderer;id=`liquid`;sampleIntervalSeconds=Xe;receivesOwnSources=!1;elapsed=0;constructor(e){this.renderer=e}sources(){return this.renderer.burningLiquidSources?.()??[]}expose(e,t){e.length?(this.elapsed+=t,!(this.elapsed<Xe)&&(this.renderer.igniteLiquidsFromFire?.(e),this.elapsed%=Xe)):this.elapsed=0}captureState(){return this.elapsed}restoreState(e){if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw Error(`Invalid liquid heat checkpoint`);this.elapsed=e}reset(){this.elapsed=0}},Qe=class{domains;heatClocks=new Map;constructor(e,t){this.domains=[{id:`scene`,sampleIntervalSeconds:1/15,canReceive:()=>e.hasFireTargets?.()??!0,receivesOwnSources:!0,sources:()=>e.burningFireSources?.()??[],expose:(t,n)=>e.exposeToFire?.(t,n)},new Ze(t)]}registerHeatDomain(e){if(this.domains.some(t=>t.id===e.id))throw Error(`Heat domain already registered: ${e.id}`);if(!!e.captureState!=!!e.restoreState)throw Error(`Heat domain checkpoint methods must be paired: ${e.id}`);return this.domains.push(e),this.heatClocks.set(e.id,0),()=>{let t=this.domains.indexOf(e);t>=0&&this.domains.splice(t,1),this.heatClocks.delete(e.id)}}captureState(){return{heat:(e=>e.map(e=>({id:e.id,state:b(e.captureState?.())})))(this.domains),heatClocks:this.domains.map(e=>({id:e.id,elapsed:this.heatClocks.get(e.id)??0}))}}validateState(e){let t=(e,t)=>e.length===t.length&&e.every((e,n)=>e.id===t[n].id);if(!t(e.heat,this.domains)||!t(e.heatClocks,this.domains))throw Error(`Material domain registry changed since the checkpoint`)}restoreState(e){this.validateState(e),this.domains.forEach((t,n)=>t.restoreState?.(b(e.heat[n].state))),this.heatClocks.clear();for(let{id:t,elapsed:n}of e.heatClocks)this.heatClocks.set(t,n)}reset(){this.heatClocks.clear();for(let e of this.domains)e.reset?.()}stepFire(e){let t=[...this.domains],n=t.map(t=>{let n=(this.heatClocks.get(t.id)??0)+e,r=t.sampleIntervalSeconds??0;return r>0&&n+1e-9<r?(this.heatClocks.set(t.id,n),0):(this.heatClocks.set(t.id,r>0?n%r:0),n)}),r=n.map((e,n)=>e>0&&t[n].canReceive?.()!==!1);if(!r.some(Boolean))return;let i=t.map((e,n)=>r.some((e,r)=>e&&(r!==n||t[r].receivesOwnSources))?e.sources().map(fe):[]);t.forEach((e,t)=>{if(!r[t])return;let a=i.flatMap((n,r)=>t===r&&!e.receivesOwnSources?[]:n);e.expose(a,n[t])})}},$e={throttle:0,steer:0,action:!1,boost:!1},et=class{world;state;version=3;disposed=!1;constructor(e,t){this.world=e,this.state=t}get available(){return!this.disposed}restore(){this.world.restoreState(this)}dispose(){this.disposed||(this.disposed=!0,this.state.renderer.dispose(),this.world.releaseCheckpoint(this))}},tt=class{renderer;odometer;sound;overlay;stateParticipants=new Map;registerStateParticipant(e,t){if(this.stateParticipants.has(e))throw Error(`State participant already registered: ${e}`);return this.stateParticipants.set(e,t),()=>this.stateParticipants.delete(e)}slowMo=new ze;events=new Ye;vehicleRegistry=new Map;playerVehicleId=null;collisions;materialInteractions;checkpoints=new Set;flameDamageThisStep=new Map;stepSeconds=1/120;destructionPoints=0;disposed=!1;constructor(e,t,n,r,i,a=new ae,o={}){this.renderer=t,this.odometer=n,this.sound=r,this.overlay=i;let c=Se(o);this.vehicleDestructible=c.vehicleDestructible,this.toolsEnabled=c.toolsEnabled,e&&this.spawnVehicle({id:`player`,sim:e,control:{kind:`player`}}),this.collisions=a,this.materialInteractions=new Qe(a,t),a.setEvents(this.events),a.setAutoPaint?.(o.autoPaint??s.game.autoPaint)}get playerVehicle(){return this.playerVehicleId?this.vehicleRegistry.get(this.playerVehicleId):void 0}get focusVehicle(){return this.playerVehicle??this.vehicleRegistry.values().next().value}get primaryVehicle(){let e=this.focusVehicle;if(!e)throw Error(`Game world has no vehicles`);return e}get sim(){return this.primaryVehicle.sim}get damage(){return this.primaryVehicle.damage}getVehicle(e){return this.vehicleRegistry.get(e)}get cameraVehicle(){return this.focusVehicle}get otherVehicles(){let e=this.focusVehicle;return[...this.vehicleRegistry.values()].filter(t=>t!==e)}get vehicles(){return[...this.vehicleRegistry.values()]}registerHeatDomain(e){return this.materialInteractions.registerHeatDomain(e)}configureVehicle(e,t){let n=this.getVehicle(e);if(!n)return!1;if(t.appearance!==void 0&&![`auto`,`light`,`dark`].includes(t.appearance))throw TypeError(`Unknown vehicle appearance`);let r=t.slots===void 0?void 0:ve(t.slots);return t.preset&&this.collisions.prepare(t.preset),t.preset&&t.preset!==n.sim.car.preset&&n.setPreset(t.preset),t.appearance!==void 0&&(n.appearance=t.appearance),r!==void 0&&(n.slots=r),n===this.focusVehicle&&this.projectFocusVehicle(!!t.preset),!0}projectedSound;projectedPreset;projectFocusVehicle(e=!1){let t=this.focusVehicle;if(!t)return;let n=this.sound(),r=t.sim.car.preset;(n!==this.projectedSound||r!==this.projectedPreset)&&(n.setPreset(r),this.collisions.prepare(r),this.projectedSound=n,this.projectedPreset=r),e&&this.renderer.resetVehicleDamage()}resetEffects(){this.renderer.reset(),this.materialInteractions.reset()}fadeEffects(){this.materialInteractions.reset(),this.renderer.fadeEffects()}resetScene(){this.destructionPoints=0,this.events.clear(),this.collisions.reset?.(),this.fadeEffects();for(let e of this.vehicleRegistry.values())e.restoreHealth()}deformationEnabled=!0;vehicleDestructible=!0;toolsEnabled=!0;setVehicleDestructible(e){this.vehicleDestructible=e;for(let t of this.vehicleRegistry.values())t.sim.car.destructible=e,e||t.restoreHealth()}setToolsEnabled(e){this.toolsEnabled=e;for(let t of this.vehicleRegistry.values())t.setControls(t.controls,t.controlSource,{toolsEnabled:e}),e||t.weapons.reset()}setDeformationEnabled(e){this.deformationEnabled=e;for(let t of this.vehicleRegistry.values())t.damage.setEnabled(e)}spawnVehicle({id:e,sim:t,control:n,label:r=``}){if(this.vehicleRegistry.has(e))throw Error(`Vehicle ${e} already exists`);if(n.kind===`player`&&this.playerVehicle)throw Error(`Game world already has a player vehicle`);let i=new be(e,t);return t.car.destructible=this.vehicleDestructible,this.vehicleDestructible||i.restoreHealth(),i.damage.setEnabled(this.deformationEnabled),i.label=r,i.controlSource=n.kind===`player`?`player`:`scripted`,this.vehicleRegistry.set(e,i),n.kind===`player`&&(this.playerVehicleId=e),this.focusVehicle===i&&this.renderer.bindVehicle(i),i}removeVehicle(e){let t=this.vehicleRegistry.get(e);if(!t)return!1;this.vehicleRegistry.delete(e),this.playerVehicleId===e&&(this.playerVehicleId=null),this.collisions.forgetVehicle(e),this.renderer.forgetVehicle(e),t.dispose();let n=this.focusVehicle;return n&&this.renderer.bindVehicle(n),!0}consumeEvent=e=>{let t=this.sound();switch(e.kind){case`impact`:t.playCrash(e.impact.speedMps),this.renderer.emitSparks(e.impact),this.renderer.emitCrashShake(e.impact.speedMps);break;case`scrape`:this.renderer.emitSparks(e.impact);break;case`crush`:t.playCrush(),this.awardPoints(e.point,e.points);break;case`combustionExplosion`:this.awardPoints(e.point,e.points),t.playCombustibleExplosion(this.overlay?d(e.point,this.renderer.sceneScroll(),this.renderer.viewportSize()):1);break;case`destructibleDestroyed`:this.awardPoints(e.point,e.points)}};awardPoints(e,t){!Number.isFinite(t)||t<=0||(this.destructionPoints+=t,this.renderer.emitPoints(e,t))}get points(){return this.destructionPoints}get totalPoints(){return this.collisions.totalPoints}vehicleProjectileHit(e,t,n,r){let i=null;for(let a of this.vehicleRegistry.values()){if(a===e)continue;let o=Ke(a,this.renderer,this.collisions.vehicleMask(a.sim.car.preset,a.damage),t,n,r);if(!o)continue;let s=P(w(o,t));(!i||s<i.distance)&&(i={vehicle:a,point:o,distance:s})}return i}nearestProjectileTarget(e,t,n,r){let i=this.vehicleProjectileHit(e,t,n,r),a=this.collisions.projectileHit(t,n,r);return i&&(!a||i.distance<P(w(a.point,t)))?{vehicle:i.vehicle,point:i.point,object:null}:a?{vehicle:null,point:a.point,object:a}:null}rocketCollision=(e,t,n,r)=>{this.collisions.setSourceVehicle?.(e.id);let i=this.nearestProjectileTarget(e,t,n,r);if(!i)return null;let a=i.vehicle?i.point:this.collisions.rocketImpact(t,n,r,1,i.object??void 0);if(a){let r=Be(1),o=r.radiusPx;i.vehicle&&this.collisions.applyAreaImpact?.(a,r),r.ignite&&this.renderer.igniteLiquidAt?.(a,this.renderer.documentScale()*2.2);for(let t of this.vehicleRegistry.values()){if(t===e||t.sim.car.explodedAt!==null||t.isGhost)continue;let n=this.renderer.documentPoint(t.sim.body.position),s=P(w(n,a)),c=t===i.vehicle;if(!c&&s>o)continue;let l=c?1:Math.max(.2,1-s/o*.7);t.sim.car.damage(x(`rocket`,e.sim.car.preset)*l*r.damage/100),t.synchronizeLifecycle()}this.renderer.emitRocketExplosionShake(1),this.renderer.emitRocketExplosion(a,w(n,t),1)}return a};bulletCollision=(e,t,n,r)=>{this.collisions.setSourceVehicle?.(e.id);let i=this.nearestProjectileTarget(e,t,n,r);return i?i.vehicle?(i.vehicle.sim.car.damage(x(`bullet`,e.sim.car.preset)),i.vehicle.synchronizeLifecycle(),i.point):this.collisions.bulletImpact(t,n,r,i.object??void 0):null};flameContact=(e,t,n,r,i)=>{this.collisions.setSourceVehicle?.(e.id);let a=this.nearestProjectileTarget(e,t,n,r);if(a?.vehicle){let t=this.flameDamageThisStep.get(a.vehicle.id)??0,n=Math.min(x(`flame`,e.sim.car.preset,i),Math.max(0,D.damagePerSecond*this.stepSeconds-t));return a.vehicle.sim.car.damage(n),this.flameDamageThisStep.set(a.vehicle.id,t+n),a.vehicle.synchronizeLifecycle(),a.point}return this.collisions.flameContact(t,n,r,i,p(e.sim.car.preset))};gunshot=()=>this.sound().playGunshot();rocketLaunch=e=>this.sound().playRocketLaunch(this.overlay?l(this.renderer.vehicleViewportPosition(e),this.renderer.viewportSize(),!1):1);rocketImpact=e=>this.sound().playRocketExplosion(this.overlay?l(this.renderer.vehicleViewportPosition(e),this.renderer.viewportSize(),!1):1);bulletImpact=e=>this.sound().playBulletImpact(this.overlay?l(this.renderer.vehicleViewportPosition(e),this.renderer.viewportSize(),!1):1);step(e={},t){let n=this.focusVehicle;if(!n)return;this.stepSeconds=t,this.flameDamageThisStep.clear(),performance.now();let{renderer:r,collisions:i}=this,a=n.sim,o=this.playerVehicle,s={...a.body.position},c=new Map,u={toolsEnabled:this.toolsEnabled};for(let n of this.vehicleRegistry.values())c.set(n,{...n.sim.body.position}),n.synchronizeLifecycle(),n.setControls(n===o?e.controls??$e:$e,n===o&&e.userDriven?`player`:`scripted`,u),n.step(t,n===o?this.sound().rpm:null,n===o&&e.manualMoved);o&&e.userDriven&&a.mode===`car`&&this.odometer.add(P(w(a.body.position,s)),r.documentScale()),e.afterPhysics?.();let d=this.cameraVehicle?.sim??a,f=this.overlay&&(e.allowFollow?.()??!0)&&P(d.body.velocity)>.1&&r.followDocument(d);if(a.barrier&&!this.overlay){let e={...a.body.velocity};a.contain(r.bounds());let t=P(w(e,a.body.velocity));a.mode===`car`&&a.car.takeImpact(t),this.sound().playCrash(t),r.emitCrashShake(t)}performance.now(),i.beginStep(r,t),performance.now();for(let e of this.vehicleRegistry.values()){let n=e.advanceBurn(t);if(n){let a=r.emitVehicleBurn(e,n,i.vehicleMask(e.sim.car.preset,e.damage),t);a&&this.events.emit({kind:`combustionExplosion`,point:a,points:0})}let a=c.get(e)??e.sim.body.position,o={...e.sim.body.position},s=w(o,a),l=Math.max(.25,e.sim.car.preset.geometry.widthM*.35),u=Math.min(16,Math.max(1,Math.ceil(P(s)/l)));u>1&&(e.sim.body.position={...a});for(let t=1;t<=u;t++){let n={x:a.x+s.x*t/u,y:a.y+s.y*t/u};if(e.sim.body.position={...n},i.stepVehicle(e.sim,r,e===this.cameraVehicle&&e.sim.barrier&&f,e.damage,e.id,e.isGhost),P(w(e.sim.body.position,n))>.02)break}e.synchronizeLifecycle()}if(i.endStep(t),performance.now(),this.vehicleRegistry.size>1){qe(this.vehicles,r,e=>i.vehicleMask(e.sim.car.preset,e.damage),e=>this.events.emit({kind:`impact`,impact:e}));for(let e of this.vehicleRegistry.values())e.synchronizeLifecycle()}this.events.drain(this.consumeEvent),performance.now(),i.stepElementLiquids?.(r,e.manualMoved?this.otherVehicles:[n,...this.otherVehicles],t),r.advanceEffects(n,t,{walls:i.wallRects(),carMask:i.vehicleMask(a.car.preset,n.damage),tirePaintSources:e=>i.tirePaintAt(e),driven:!e.manualMoved,rocketCollision:this.rocketCollision,bulletCollision:this.bulletCollision,onGunshot:this.gunshot,flameContact:this.flameContact,onRocketLaunch:this.rocketLaunch,onRocketImpact:this.rocketImpact,onBulletImpact:this.bulletImpact,maskFor:e=>i.vehicleMask(e.sim.car.preset,e.damage),companions:this.otherVehicles}),performance.now(),this.materialInteractions.stepFire(t);let p=r.rocketFlightPosition,m=this.sound();m.setRocketFlightProximity(p?this.overlay?l(r.vehicleViewportPosition(p),r.viewportSize(),!1):1:0),m.setBurningFireProximity(Math.max(i.burningProximity(r.documentPoint(a.body.position)),a.mode===`car`&&a.car.explodedAt===null?A(a.car.health,a.car.maxHealth):0)),this.events.drain(this.consumeEvent)}advanceTime(e){let t=this.slowMo.advance(e);return this.renderer.setSlowMoZoom(this.slowMo.zoomFactor),this.sound().setTimeScale?.(this.slowMo.speedFactor),t}present(e,t,n,r,i,a,o){let s=this.focusVehicle;if(!s)return;let{renderer:d}=this,f=s.sim;this.projectFocusVehicle();let p=this.playerVehicle?{...n,boost:f.lastInput.boost}:{...s.controls,boost:f.lastInput.boost};if(!document.hidden){let e=this.sound(),n=f.paused?0:P(f.body.velocity),o=f.mode===`car`&&!f.paused&&!s.isGhost?c(f,f.lastInput.action):[];e.setActive(f.mode===`car`&&i),s.isGhost&&e.silenceTires(),e.setGhostMode(!f.paused&&s.isGhost),e.setFlamethrowerFiring(!f.paused&&d.flamethrowerFiring),e.setBoosting(!f.paused&&f.car.boostActive);let m=p.throttle!==0||p.steer!==0||p.action||r;e.setProximity(this.overlay?l(d.vehicleViewportPosition(f.body.position),d.viewportSize(),m):1),e.setMasterVolume(u(a)),performance.now(),e.update(t*this.slowMo.speedFactor,p,n,0,0,f.mode===`car`?f.car.boostCharge:0,o);let h=e.takeExhaustPops();!f.paused&&f.mode===`car`&&d.queueExhaustPops(h)}d.render(s,e,o,this.collisions,this.otherVehicles)}snapshot(){let{sim:e}=this;return{mode:e.mode,presetId:e.car.preset.id,position:{...e.body.position},speed:P(e.body.velocity),angle:e.body.angle,spin:e.body.spin,paused:e.paused,health:e.car.health,maxHealth:e.car.maxHealth,burnStage:e.car.stage,points:this.destructionPoints}}saveState(){if(this.disposed)throw Error(`Game world has been disposed`);let e=[...this.vehicleRegistry.values()].map(e=>e.captureState()),t=this.collisions.captureState(),n=this.odometer.captureState(),r=this.events.captureState(),i=this.renderer.captureState(),a;try{a=new et(this,{extensions:new Map([...this.stateParticipants].map(([e,t])=>[e,b(t.captureState())])),vehicles:e,playerVehicleId:this.playerVehicleId,deformationEnabled:this.deformationEnabled,vehicleDestructible:this.vehicleDestructible,toolsEnabled:this.toolsEnabled,slowMo:this.slowMo.captureState(),collisions:t,odometer:n,events:r,points:this.destructionPoints,renderer:i,materialInteractions:this.materialInteractions.captureState()})}catch(e){throw i.dispose(),e}return this.checkpoints.add(a),a}restoreState(e){if(this.disposed||e.world!==this||!e.available)throw Error(`Checkpoint is unavailable for this game world`);let t=e.state;if(t.vehicles.length!==this.vehicleRegistry.size||t.vehicles.some(e=>!this.vehicleRegistry.has(e.id)))throw Error(`Checkpoint vehicle registry does not match`);this.materialInteractions.validateState(t.materialInteractions),this.deformationEnabled=t.deformationEnabled,this.vehicleDestructible=t.vehicleDestructible,this.toolsEnabled=t.toolsEnabled,this.slowMo.restoreState(t.slowMo),this.sound().setTimeScale?.(this.slowMo.speedFactor),this.destructionPoints=t.points,this.playerVehicleId=t.playerVehicleId;let n=this.focusVehicle;n&&this.renderer.bindVehicle(n),this.renderer.restoreState(t.renderer),this.materialInteractions.restoreState(t.materialInteractions);for(let e of t.vehicles){let t=this.vehicleRegistry.get(e.id);if(!t)throw Error(`Checkpoint vehicle is unavailable`);t.restoreState(e)}n&&this.collisions.prepare(n.sim.car.preset),this.collisions.restoreState(t.collisions),this.odometer.restoreState(t.odometer),this.events.restoreState(t.events);for(let[e,n]of t.extensions){let t=this.stateParticipants.get(e);if(!t)throw Error(`Checkpoint state participant is unavailable: ${e}`);t.restoreState(b(n))}}releaseCheckpoint(e){this.checkpoints.delete(e)}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.checkpoints])e.dispose();this.slowMo.reset(),this.sound().setTimeScale?.(1),this.events.clear(),this.collisions.destroy(),this.renderer.dispose();for(let e of this.vehicleRegistry.values())e.dispose();this.vehicleRegistry.clear(),this.stateParticipants.clear()}}},nt=10,rt=class{active;step;render;stepSeconds;maxSteps;onError;simulationElapsed;frameId=0;running=!1;lastTime=null;accumulator=0;failure=null;constructor(e,t,n,r=1/120,i=12,a=e=>console.error(`Joy Ride stopped after a runtime failure.`,e),o=e=>e){this.active=e,this.step=t,this.render=n,this.stepSeconds=r,this.maxSteps=i,this.onError=a,this.simulationElapsed=o}get status(){return this.failure?`failed`:this.running?`running`:`stopped`}get error(){return this.failure?.error}reset(){this.lastTime=null,this.accumulator=0}advance(e){me();let t=this.lastTime===null?0:Math.max(0,(e-this.lastTime)/1e3),n=Math.min(t,.1);if(this.lastTime=e,this.active()){t>n&&this.simulationElapsed(t-n),this.simulationElapsed(0),this.accumulator+=n;let e=0,r=this.stepSeconds*1e-9,i=performance.now();for(;this.accumulator+r>=this.stepSeconds&&e<this.maxSteps&&(this.step(this.simulationElapsed(this.stepSeconds)),this.accumulator=Math.max(0,this.accumulator-this.stepSeconds),e++,!(e>=2&&performance.now()-i>nt)););if(this.accumulator+r>=this.stepSeconds){let e=this.accumulator-this.accumulator%this.stepSeconds;this.simulationElapsed(e),this.accumulator-=e}}else this.accumulator=0;this.render(e,n)}start(){this.running||(this.failure=null,this.running=!0,this.frameId=requestAnimationFrame(this.onFrame))}stop(){this.running=!1,this.frameId&&cancelAnimationFrame(this.frameId),this.frameId=0,this.reset()}onFrame=e=>{this.frameId=0;try{this.advance(e)}catch(e){this.stop(),this.failure={error:e},this.onError(e);return}this.running&&(this.frameId=requestAnimationFrame(this.onFrame))}};function it(e,t){let n=1/0,r={x:1,y:0};for(let i of[e,t])for(let a=0;a<i.length;a++){let o=i[a],s=i[(a+1)%i.length],c=Math.hypot(s.x-o.x,s.y-o.y);if(c<1e-9)continue;let l={x:-(s.y-o.y)/c,y:(s.x-o.x)/c},u=e.map(e=>e.x*l.x+e.y*l.y),d=t.map(e=>e.x*l.x+e.y*l.y),f=Math.min(...u),p=Math.max(...u),m=Math.min(...d),h=Math.max(...d);if(p<=m||h<=f)return null;let g=p-m,_=h-f,v=Math.min(g,_);v<n&&(n=v,r=g<_?{x:-l.x,y:-l.y}:l)}return Number.isFinite(n)?{normal:r,depth:n}:null}function at(e,t,n,r){let i=r.reduce((e,t,n)=>{let i=r[(n+1)%r.length];return e+t.x*i.y-i.x*t.y},0),a=0,o=1;for(let s=0;s<r.length;s++){let c=r[s],l=r[(s+1)%r.length],u=Math.hypot(l.x-c.x,l.y-c.y);if(u<1e-9)continue;let d=(l.y-c.y)/u*Math.sign(i),f=-(l.x-c.x)/u*Math.sign(i),p=(e.x-c.x)*d+(e.y-c.y)*f-n,m=(t.x-e.x)*d+(t.y-e.y)*f;if(Math.abs(m)<1e-9){if(p>0)return null;continue}let h=-p/m;if(m<0?a=Math.max(a,h):o=Math.min(o,h),a>o)return null}return a<=1&&o>=0?a:null}function W(e,t=0,n=1){let r=Math.max(0,Math.min(1,(e-t)/(n-t)));return 1-r*r*(3-2*r)}var ot=(e,t,n)=>{let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)},st=class{sprites=new WeakMap;colors=new Map;colorCanvas=null;nextPhase=0;get(e,t,n,r,i=!1){if(t>=1)return e;let[a,o,s]=this.rgb(n),c=this.sprites.get(e);if(!c||c.canvas.width!==e.width||c.canvas.height!==e.height){let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height,c={canvas:t,revision:-1,tint:-1,radialStep:-1,phase:this.nextPhase},this.nextPhase=(this.nextPhase+.61803398875)%1,this.sprites.set(e,c)}let l=Math.max(0,Math.min(1,Math.round(t*32+c.phase-.5)/32)),u=Math.round(a*l),d=Math.round(o*l),f=Math.round(s*l),p=u<<16|d<<8|f;if(i||c.revision!==r||c.tint!==p){F(`burn sprite recolors`);let t=c.canvas.getContext(`2d`);t&&(t.clearRect(0,0,e.width,e.height),t.globalCompositeOperation=`source-over`,t.drawImage(e,0,0),t.globalCompositeOperation=`source-in`,t.fillStyle=`rgb(${u} ${d} ${f})`,t.fillRect(0,0,e.width,e.height),t.globalCompositeOperation=`source-over`,c.revision=r,c.tint=p,c.radialStep=-1)}return c.canvas}getRadialBurn(e,t,n){let r=this.sprites.get(e);if(!r||r.canvas.width!==e.width||r.canvas.height!==e.height){let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height,r={canvas:t,revision:-1,tint:-1,radialStep:-1,phase:0},this.sprites.set(e,r)}let i=Math.round(t.age*30);if(r.revision===n&&r.radialStep===i)return r.canvas;let a=r.canvas.getContext(`2d`);if(!a)return e;a.save(),a.clearRect(0,0,e.width,e.height),a.drawImage(e,0,0);let o=e=>{let n=a.createRadialGradient(t.originX,t.originY,0,t.originX,t.originY,Math.max(1,t.farthest));for(let r=0;r<=16;r++){let i=r/16,a=(t.age-i*t.spreadSeconds)/Math.max(.01,t.burnSeconds);n.addColorStop(i,`rgba(0, 0, 0, ${e(a)})`)}return n};return a.globalCompositeOperation=`source-atop`,a.fillStyle=o(e=>ot(.12,.72,e)*.95),a.fillRect(0,0,e.width,e.height),a.globalCompositeOperation=`destination-out`,a.fillStyle=o(e=>1-W(e,.78,1.02)),a.fillRect(0,0,e.width,e.height),a.restore(),r.revision=n,r.radialStep=i,r.tint=-1,r.canvas}bytesFor(e){let t=e&&this.sprites.get(e)?.canvas;return t?t.width*t.height*4:0}clear(){this.sprites=new WeakMap,this.colors.clear(),this.colorCanvas=null,this.nextPhase=0}rgb(e){let t=this.colors.get(e);if(t)return t;let n=this.colorCanvas??=document.createElement(`canvas`);n.width=n.height=1;let r=n.getContext(`2d`,{willReadFrequently:!0});if(!r)return[255,255,255];r.clearRect(0,0,1,1),r.fillStyle=e,r.fillRect(0,0,1,1);let i=r.getImageData(0,0,1,1).data,a=[i[0],i[1],i[2]];return this.colors.set(e,a),a}};function ct(e,t,n,r,i){if(!(r.speedMps>.8))return!1;let a=r.pixelsPerMeter,o=w(r.point,n.center);return e.car.takeImpact(r.speedMps,E(j(o,n.forward)/a,j(o,n.side)/a)),t?.hit(r.point,r.normal,n,r.speedMps,a),i(),!0}var lt=class{sources;cells=new Map;largeSources=[];cellSize=64;constructor(e){this.sources=e;for(let t of e){let e=t.bounds??{x:t.point.x,y:t.point.y,width:0,height:0},n=Math.floor((e.x-t.radiusPx)/this.cellSize),r=Math.floor((e.x+e.width+t.radiusPx)/this.cellSize),i=Math.floor((e.y-t.radiusPx)/this.cellSize),a=Math.floor((e.y+e.height+t.radiusPx)/this.cellSize);if((r-n+1)*(a-i+1)>256)this.largeSources.push(t);else for(let e=i;e<=a;e++)for(let i=n;i<=r;i++){let n=`${i}:${e}`,r=this.cells.get(n)??[];r.push(t),this.cells.set(n,r)}}}*near(e){let t=Math.floor(e.x/this.cellSize),n=Math.floor((e.x+e.width)/this.cellSize),r=Math.floor(e.y/this.cellSize),i=Math.floor((e.y+e.height)/this.cellSize);if((n-t+1)*(i-r+1)>256){for(let t of this.sources)this.overlaps(t,e)&&(yield t);return}let a=new Set;for(let e=r;e<=i;e++)for(let r=t;r<=n;r++)for(let t of this.cells.get(`${r}:${e}`)??[])a.has(t)||(a.add(t),yield t);for(let t of this.largeSources)this.overlaps(t,e)&&(yield t)}overlaps(e,t){let n=e.bounds??{x:e.point.x,y:e.point.y,width:0,height:0},r=e.radiusPx;return n.x-r<=t.x+t.width&&n.x+n.width+r>=t.x&&n.y-r<=t.y+t.height&&n.y+n.height+r>=t.y}},ut=`joy-ride-odometer-v1`,dt=`joy-ride-distance-dpi-v1`,ft=1609.344,pt={screen:96,print:300},mt=.0254;function ht(){try{return typeof window>`u`?null:window.localStorage}catch{return null}}var gt={pixels:0,kilometers:0,miles:0,dpi:pt.print,dpiMode:`print`};function _t(e){if(!e||typeof e!=`object`)return!1;let t=e;return Number.isFinite(t.pixels)&&(t.pixels??-1)>=0}var vt=class{store;total;dirty=!1;mode=`print`;constructor(e=ht()){this.store=e;let t=null;try{t=JSON.parse(this.store?.getItem(ut)??`null`)}catch{}this.total=_t(t)?{pixels:t.pixels}:{pixels:0};try{this.store?.getItem(dt)===`screen`&&(this.mode=`screen`)}catch{}}add(e,t){!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0||(this.total.pixels+=e*t,this.dirty=!0)}reset(){this.total.pixels=0,this.dirty=!0,this.flush()}get dpiMode(){return this.mode}captureState(){return{pixels:this.total.pixels,mode:this.mode}}restoreState(e){if(!Number.isFinite(e.pixels)||e.pixels<0||!(e.mode in pt))throw Error(`Invalid odometer checkpoint`);this.total.pixels=e.pixels,this.mode=e.mode,this.dirty=!0,this.flush();try{this.store?.setItem(dt,this.mode)}catch{}}get dpi(){return pt[this.mode]}cycleDpi(){this.mode=this.mode===`print`?`screen`:`print`;try{this.store?.setItem(dt,this.mode)}catch{}return this.readout}flush(){if(this.dirty)try{this.store?.setItem(ut,JSON.stringify(this.total)),this.dirty=!1}catch{}}get kilometers(){return this.total.pixels/this.dpi*mt/1e3}get miles(){return this.total.pixels/this.dpi*mt/ft}get readout(){return{pixels:this.total.pixels,kilometers:this.kilometers,miles:this.miles,dpi:this.dpi,dpiMode:this.mode}}},yt={quality:(e,t)=>e.setQuality(t),lighting:(e,t)=>e.setVehicleLighting(t??{}),tireSmoke:(e,t)=>e.setTireSmokeEnabled(t),vehicleShadows:(e,t)=>e.setVehicleShadowsEnabled(t),sparks:(e,t)=>e.setSparksEnabled(t),screenShake:(e,t)=>e.setScreenShakeEnabled(t),surfaceTone:(e,t)=>e.setSurfaceTone(t),debug:(e,t)=>e.setDebugEnabled(t),showVehicleMarkers:(e,t)=>e.setShowVehicleMarkers(t),deform:(e,t)=>e.setDeformEnabled(t)};function bt(e,t,n){for(let r of Object.keys(yt))if(!n||t[r]!==n[r]){let n=yt[r];n(e,t[r])}}function G(e,t,n=0){let{halfX:r,halfY:i}=e,a=r.x*i.y-r.y*i.x;if(Math.abs(a)<1e-4)return!1;let o=t.x-e.center.x,s=t.y-e.center.y,c=(o*i.y-s*i.x)/a,l=(s*r.x-o*r.y)/a;return Math.abs(c)<=1+n/Math.max(1,Math.hypot(r.x,r.y))&&Math.abs(l)<=1+n/Math.max(1,Math.hypot(i.x,i.y))}var xt=class{transforms=new WeakMap;transform(e){return this.transforms.has(e)||this.transforms.set(e,St(e)),this.transforms.get(e)}};function St(e){let t=getComputedStyle(e);if(t.visibility===`hidden`||t.display===`none`)return null;let n=new DOMMatrixReadOnly;if(t.rotate&&t.rotate!==`none`){let e=t.rotate.trim().split(/\s+/);if(e.length>1&&e.slice(0,-1).join(` `)!==`z`)return null;let r=e.at(-1),i=parseFloat(r),a=r.endsWith(`grad`)?i*.9:r.endsWith(`rad`)?i*180/Math.PI:r.endsWith(`turn`)?i*360:i;n=n.rotate(a)}if(t.scale&&t.scale!==`none`){let[e,r]=t.scale.split(/\s+/).map(Number);n=n.scale(e,r??e)}return t.transform&&t.transform!==`none`&&(n=n.multiply(new DOMMatrixReadOnly(t.transform))),n.is2D?n:null}function K(e,t){let n=e.getBoundingClientRect();if(!n.width||!n.height)return null;let r=new DOMMatrixReadOnly;for(let n=e;n;n=n.parentElement){let e=t?t.transform(n):St(n);if(!e)return null;r=e.multiply(r)}return{center:{x:n.left+n.width/2,y:n.top+n.height/2},halfX:{x:r.a*e.offsetWidth/2,y:r.b*e.offsetWidth/2},halfY:{x:r.c*e.offsetHeight/2,y:r.d*e.offsetHeight/2}}}var Ct=new WeakMap,wt=[[{x:-.5,y:-.5},{x:.5,y:-.5}],[{x:.5,y:-.5},{x:.5,y:.5}],[{x:.5,y:.5},{x:-.5,y:.5}],[{x:-.5,y:.5},{x:-.5,y:-.5}]];function Tt(e){if(!e)return wt;let t=Ct.get(e);if(t)return t;let n=[],{columns:r,rows:i,solid:a}=e;for(let e=0;e<i;e++)for(let t=0;t<r;t++){if(!a[e*r+t])continue;let o=t/r-.5,s=(t+1)/r-.5,c=e/i-.5,l=(e+1)/i-.5;t&&a[e*r+t-1]||n.push([{x:o,y:c},{x:o,y:l}]),t!==r-1&&a[e*r+t+1]||n.push([{x:s,y:c},{x:s,y:l}]),e&&a[(e-1)*r+t]||n.push([{x:o,y:c},{x:s,y:c}]),e!==i-1&&a[(e+1)*r+t]||n.push([{x:o,y:l},{x:s,y:l}])}return Ct.set(e,n),n}function Et(e,[t,n]){let r=n.x-t.x,i=n.y-t.y,a=Math.max(0,Math.min(1,((e.x-t.x)*r+(e.y-t.y)*i)/Math.max(1e-12,r*r+i*i)));return{x:t.x+r*a,y:t.y+i*a}}var Dt=(e,t)=>e.x*t.y-e.y*t.x;function Ot([e,t],[n,r]){let i={x:t.x-e.x,y:t.y-e.y},a={x:r.x-n.x,y:r.y-n.y},o=Dt(i,a);if(Math.abs(o)<1e-10)return null;let s={x:n.x-e.x,y:n.y-e.y},c=Dt(s,a)/o,l=Dt(s,i)/o;return c>=0&&c<=1&&l>=0&&l<=1?{x:e.x+i.x*c,y:e.y+i.y*c}:null}var kt=e=>[{x:e.center.x-e.halfX.x-e.halfY.x,y:e.center.y-e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x-e.halfY.x,y:e.center.y+e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x+e.halfY.x,y:e.center.y+e.halfX.y+e.halfY.y},{x:e.center.x-e.halfX.x+e.halfY.x,y:e.center.y-e.halfX.y+e.halfY.y}];function At(e,t,n,r){let i=e.pixelsPerMeter??1,a=e.mask?e.mask.lengthM*i:e.lengthPx,o=e.mask?e.mask.widthM*i:e.widthPx,s=n??{position:e.position,angle:e.angle,target:t.center},c=Math.atan2(Math.sin(e.angle-s.angle),Math.cos(e.angle-s.angle)),l=s.target??t.center,u={x:s.position.x-l.x,y:s.position.y-l.y},d={x:e.position.x-t.center.x,y:e.position.y-t.center.y},f=Et({x:0,y:0},[u,d]),p=Math.hypot(a,o)*.5+Math.hypot(t.halfX.x,t.halfX.y)+Math.hypot(t.halfY.x,t.halfY.y);if(Math.hypot(f.x,f.y)>p)return{inside:!1,contact:null};let m=Tt(e.mask?.alpha);function h(n){let r={x:s.position.x+(e.position.x-s.position.x)*n,y:s.position.y+(e.position.y-s.position.y)*n},i=s.angle+c*n,l=Math.cos(i),u=Math.sin(i),d=e=>({x:r.x+l*e.x*a-u*e.y*o,y:r.y+u*e.x*a+l*e.y*o}),f=s.target??t.center,p={...t,center:{x:f.x+(t.center.x-f.x)*n,y:f.y+(t.center.y-f.y)*n}},h=kt(p);if(!it([d({x:-.5,y:-.5}),d({x:.5,y:-.5}),d({x:.5,y:.5}),d({x:-.5,y:.5})],h))return null;let g=null,_=1/0,v=e=>{let t=(e.x-p.center.x)**2+(e.y-p.center.y)**2;t<_&&(g=e,_=t)};for(let e of m){let t=[d(e[0]),d(e[1])];G(p,t[0])&&v(t[0]),G(p,t[1])&&v(t[1]);let n=Et(p.center,t);G(p,n)&&v(n);for(let e=0;e<4;e++){let n=Ot(t,[h[e],h[(e+1)%4]]);n&&v(n)}}if(!g){let t=p.center.x-r.x,n=p.center.y-r.y,i=(l*t+u*n)/a+.5,s=(-u*t+l*n)/o+.5;if(i>=0&&i<1&&s>=0&&s<1){let t=e.mask?.alpha;(!t||t.solid[Math.floor(s*t.rows)*t.columns+Math.floor(i*t.columns)])&&(g=p.center)}}return g?{point:g,center:r,angle:i}:null}let g=h(1),_={x:d.x-u.x,y:d.y-u.y},v=_.x*_.x+_.y*_.y,y=0,b=1;if(v>1e-12){let e=u.x*_.x+u.y*_.y,t=Math.max(0,e*e-v*(u.x*u.x+u.y*u.y-p*p)),n=Math.sqrt(t);y=Math.max(0,(-e-n)/v),b=Math.min(1,(-e+n)/v)}let x=b-y,S=(Math.sqrt(v)+Math.hypot(a,o)*Math.abs(c)*.5)*x,C=Math.max(1,Math.min(o,Math.hypot(t.halfX.x,t.halfX.y)*2,Math.hypot(t.halfY.x,t.halfY.y)*2)/4),w=Math.min(64,Math.max(1,Math.ceil(S/C))),T=h(y),E=y;for(let e=1;!T&&e<=w;e++){let t=y+x*e/w,n=t===1?g:h(t);if(!n)continue;let r=y+x*(e-1)/w,i=t;T=n;for(let e=0;e<7;e++){let e=(r+i)/2,t=h(e);t?(i=e,T=t):r=e}E=i}if(!T)return{inside:!1,contact:null};let D={x:(T.point.x-T.center.x)/i,y:(T.point.y-T.center.y)/i},O={x:e.position.x-s.position.x,y:e.position.y-s.position.y},k=Math.hypot(O.x,O.y),A=e.velocityMps??(k>1e-6?{x:O.x/k*e.speedMps,y:O.y/k*e.speedMps}:{x:Math.cos(e.angle)*e.speedMps,y:Math.sin(e.angle)*e.speedMps}),j=e.angularVelocity??(r>0?c/r:0),M=r>0?{x:(t.center.x-l.x)/(r*i),y:(t.center.y-l.y)/(r*i)}:{x:0,y:0},N={x:M.x-A.x+j*D.y,y:M.y-A.y-j*D.x},P=Math.cos(T.angle),F=Math.sin(T.angle);return{inside:g!==null,contact:{fraction:E,origin:{x:Math.max(-.5,Math.min(.5,(P*D.x+F*D.y)*i/a)),y:Math.max(-.5,Math.min(.5,(F*D.x-P*D.y)*i/o))},angle:Math.atan2(F*N.x-P*N.y,P*N.x+F*N.y),velocity:Math.hypot(N.x,N.y)}}}var jt=(e=``)=>e.split(/\s+/u).filter(Boolean),Mt=class{entries=new Map;apply(e,t,n){let r=this.entries.get(e),{enteredClass:i,dwellingClass:a,successClass:o}=t;if(!r&&!i&&!a&&!o||r?.phase===n&&r.entered===i&&r.dwelling===a&&r.success===o)return;let s=r?.tokens??new Map,c=new Set([...jt(i),...jt(a),...jt(o)]),l=new Set(jt(n===`entered`?i:n===`dwelling`?a:n===`success`?o:``));for(let[t,n]of s)c.has(t)||(this.restoreToken(e,t,n),s.delete(t));for(let t of c){let n=e.classList.contains(t),r=s.get(t)??{original:n,applied:n},i=l.has(t);n!==i&&e.classList.toggle(t,i),r.applied=i,s.set(t,r)}c.size?this.entries.set(e,{phase:n,entered:i,dwelling:a,success:o,tokens:s}):this.entries.delete(e)}restoreToken(e,t,n){let r=e.classList.contains(t);r===n.applied&&r!==n.original&&e.classList.toggle(t,n.original)}restore(e){for(let[t,n]of this.entries.get(e)?.tokens??[])this.restoreToken(e,t,n);this.entries.delete(e)}reset(){for(let e of this.entries.keys())this.restore(e)}captureState(){return b(this.entries)}restoreState(e){this.reset();for(let[t,n]of b(e)){this.entries.set(t,n);for(let[e,r]of n.tokens)t.classList.contains(e)!==r.applied&&t.classList.toggle(e,r.applied)}}},Nt=`input[type="checkbox"],[role="checkbox"],[role="switch"]`;function Pt(e){return e instanceof HTMLInputElement?{checked:e.checked,indeterminate:e.indeterminate}:{aria:e.getAttribute(`aria-checked`)}}function Ft(e,t){`checked`in t&&e instanceof HTMLInputElement?(e.checked=t.checked,e.indeterminate=t.indeterminate):`aria`in t&&(t.aria===null?e.removeAttribute(`aria-checked`):e.setAttribute(`aria-checked`,t.aria))}var It=class{initial=new Map;sync(e){for(let[t,n]of this.initial)e.has(t)||(Ft(t,n),this.initial.delete(t));for(let t of e)this.initial.has(t)||this.initial.set(t,Pt(t))}reset(){for(let[e,t]of this.initial)Ft(e,t)}resetTarget(e){let t=this.initial.get(e);t&&Ft(e,t)}captureState(){return b(new Map([...this.initial].map(([e,t])=>[e,{initial:t,current:Pt(e)}])))}restoreState(e){this.reset(),this.initial.clear();for(let[t,{initial:n,current:r}]of b(e))this.initial.set(t,n),Ft(t,r)}dispose(){this.reset(),this.initial.clear()}},Lt={route:{id:`data-jr-route`,order:`data-jr-route-order`,progress:`data-jr-route-progress`,event:`data-jr-route-event`},objective:{id:`data-jr-objective`,order:`data-jr-objective-order`,progress:`data-jr-objective-progress`,event:`data-jr-objective-event`}},Rt={click:{action:`click`},check:{action:`check`},toggle:{action:`toggle`},pickup:{repeat:`scene`,consume:!0},parking:{when:`stop`,dwellSeconds:.45,maxSpeedMps:.25,containment:`center`}};function zt(e){let t=e.spec.trigger,n=typeof t==`string`?{preset:t}:typeof t==`object`?t:{};return{when:`enter`,action:`event`,repeat:`visit`,vehicles:`player`,...Rt[n.preset??``],...n}}var q=e=>e.spec.stops.map(e=>typeof e==`string`?e:e.target),Bt=()=>({phase:`idle`,inside:!1,departed:!1,qualified:!1,dwell:0,routeDwell:new Map}),J=e=>[{x:e.center.x-e.halfX.x-e.halfY.x,y:e.center.y-e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x-e.halfY.x,y:e.center.y+e.halfX.y-e.halfY.y},{x:e.center.x+e.halfX.x+e.halfY.x,y:e.center.y+e.halfX.y+e.halfY.y},{x:e.center.x-e.halfX.x+e.halfY.x,y:e.center.y-e.halfX.y+e.halfY.y}];function Vt(e){let t=Math.cos(e.angle),n=Math.sin(e.angle);return{center:e.position,halfX:{x:t*e.lengthPx/2,y:n*e.lengthPx/2},halfY:{x:-n*e.widthPx/2,y:t*e.widthPx/2}}}function Ht(e,t){let n=Math.hypot(e.halfX.x,e.halfX.y),r=Math.hypot(e.halfY.x,e.halfY.y);return{center:e.center,halfX:{x:e.halfX.x*(1+t/n),y:e.halfX.y*(1+t/n)},halfY:{x:e.halfY.x*(1+t/r),y:e.halfY.y*(1+t/r)}}}var Ut=(e,t,n,r,i)=>(!e.requireExit||r)&&(e.when===`stop`?t&&i>=(e.dwellSeconds??.45):n),Wt=(e,t,n,r,i)=>n&&Math.abs(r)<=(t.maxSpeedMps??.25)?e+i:0,Gt=class{registry;measure;publicPosition;localPosition;pickup;awardPoints;stateClasses=new Mt;controls=new It;visits=new Map;credited=new Map;consumed=new Map;visuals=new Map;routes=new Map;reservedObjectives=new Set;declarations=new Map;definitionRoutes=new Set;listeners=new Set;missing=new Set;frameGeometry=null;defaultGeometryFrame;dirty=!0;disposed=!1;unsubscribe;constructor(e,t,n=e=>({...e}),r=e=>({...e}),i,a){this.registry=e,this.measure=t,this.publicPosition=n,this.localPosition=r,this.pickup=i,this.awardPoints=a,this.unsubscribe=e.subscribe(()=>{this.dirty=!0});for(let[t,n]of Object.entries(e.definitions.routes??{}))this.definitionRoutes.add(t),this.route(t,n);for(let[t,n]of Object.entries(e.definitions.objectives??{}))`steps`in n&&(this.definitionRoutes.add(t),this.objective(t,n))}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}beginFrame(){this.disposed||(this.frameGeometry??=new Map,this.frameGeometry.clear(),this.measure||(this.defaultGeometryFrame=new xt))}relocateVehicle(e){for(let t of this.visits.values()){let n=t.get(e);n&&t.set(e,{...n,inside:!1,qualified:!1,position:void 0,angle:void 0,targetPosition:void 0,dwell:0,routeDwell:new Map})}}geometry(e){let t=()=>this.measure?this.measure(e):e instanceof HTMLElement?K(e,this.defaultGeometryFrame):null;return this.frameGeometry?(this.frameGeometry.has(e)||this.frameGeometry.set(e,t()),this.frameGeometry.get(e)):t()}exportRoutes(){if(this.disposed)throw Error(`Playground is disposed`);return Object.fromEntries([...this.routes].filter(([e,t])=>!t.objective&&!t.target&&!this.definitionRoutes.has(e)).map(([e,t])=>[e,structuredClone(t.spec)]))}hasObjective(e){return this.routes.has(e)||this.reservedObjectives.has(e)}reserveObjective(e){if(this.disposed)throw Error(`Playground is disposed`);if(!e.trim())throw Error(`Objective needs an ID`);if(this.hasObjective(e))throw Error(`Objective already exists: ${e}`);this.reservedObjectives.add(e)}releaseObjective(e){this.reservedObjectives.delete(e)}syncObjectives(){this.disposed||this.sync(this.registry.objects.filter(e=>e.spec.enabled!==!1&&e.spec.trigger))}exportObjectives(){return Object.fromEntries([...this.routes].filter(([e,t])=>t.objective&&!t.target&&!this.definitionRoutes.has(e)).map(([e,t])=>{let{stops:n,...r}=t.spec;return[e,{...structuredClone(r),steps:structuredClone(n)}]}))}objective(e,t,n){let{steps:r,...i}=Ee(t),a=this.route(e,{...i,progress:i.progress??`scene`,stops:r},n,!0);return{id:e,get state(){return!a.state.length&&(i.progress??`scene`)===`scene`?Object.freeze([Object.freeze({vehicleId:`scene`,current:0,target:r.length,complete:!1})]):Object.freeze(a.state.map(({vehicleId:e,completed:t,total:n,complete:r})=>Object.freeze({vehicleId:e,current:t,target:n,complete:r})))},reset:()=>a.reset(),dispose:()=>a.dispose()}}emit(e,t,n){let{object:r,...i}=t,a=o({...b(i),...r?{object:r}:{},...`position`in t?{position:this.publicPosition(t.position)}:{}});(n??this.registry.root).dispatchEvent(new CustomEvent(`joyride:${e}`,{bubbles:!0,detail:a}));for(let t of this.listeners)try{t(e,a)}catch(e){this.registry.report(e,n)}}route(e,t,n,r=!1){if(this.disposed)throw Error(`Playground is disposed`);if(!e.trim())throw Error(`Route needs an ID`);if(this.hasObjective(e))throw Error(`Objective already exists: ${e}`);let i=Oe(t),a={id:e,spec:i,target:n,objective:r,visited:new Map,completed:new Set};this.routes.set(e,a);let o=!1;return{id:e,get state(){return[...a.visited].map(([e,t])=>Object.freeze({vehicleId:e,completed:t.size,total:i.stops.length,complete:t.size===i.stops.length}))},reset:()=>{o||this.resetRoute(a)},dispose:()=>{o||this.routes.delete(e),o=!0}}}sync(e){if(!this.dirty)return;this.dirty=!1;let t=[...this.registry.root.querySelectorAll(`[data-jr-route]`)];this.registry.root instanceof Element&&this.registry.root.matches(`[data-jr-route]`)&&t.unshift(this.registry.root),t.push(...[...this.registry.root.querySelectorAll(`[data-jr-objective]`)].filter(e=>e.getAttribute(`data-jr-objective-type`)===null)),this.registry.root instanceof Element&&this.registry.root.matches(`[data-jr-objective]`)&&this.registry.root.getAttribute(`data-jr-objective-type`)===null&&t.unshift(this.registry.root);for(let[e,n]of this.declarations)t.includes(e)||(this.routes.delete(n.id),this.declarations.delete(e),this.missing.delete(n.id));for(let n of t)try{let t=n.getAttribute(`data-jr-objective`)!==null,r=t?Lt.objective:Lt.route,i=n.getAttribute(r.id)??``,a=this.declarations.get(n),o=e.filter(e=>n.contains(e.target)&&(()=>{let t=e.target.closest(`[data-jr-objective]`),r=e.target.closest(`[data-jr-route]`);return(t&&r?t.contains(r)?r:t:t??r)===n})());if(!o.length)continue;let s=o.map(e=>e.id),c=n.getAttribute(r.order)??`ordered`,l=n.getAttribute(r.progress)??(t?`scene`:`vehicle`),u=n.getAttribute(r.event)??void 0,d=a&&this.routes.get(a.id),f=d&&d.visited.size?q(d):s,p=Oe({order:c,progress:l,event:u,stops:f}),m=JSON.stringify({id:i,spec:p});if(a?.signature===m)continue;if(this.hasObjective(i)&&a?.id!==i)throw Error(`Objective already exists: ${i}`);if(a){let e=this.routes.get(a.id);e&&this.resetRoute(e),this.routes.delete(a.id)}this.route(i,p,n,t),this.declarations.set(n,{id:i,signature:m})}catch(e){this.registry.report(e,n)}let n=new Set(e.map(e=>e.target)),r=new Set;for(let t of e){let e=zt(t);if(e.action!==`event`)try{let n=this.actionTarget(t.target,e),i=this.controlTarget(n);i&&r.add(i)}catch(e){this.registry.report(e,t.target)}}this.controls.sync(r);for(let e of this.visits.keys())n.has(e)||(this.visits.delete(e),this.credited.delete(e),this.restore(e))}eligible(e,t,n,r){let i=e.spec.progress===`scene`?`scene`:n.id,a=e.visited.get(i)??new Set,o=q(e);return o.includes(t.id)?o.some(e=>!r.some(t=>t.id===e))?(this.missing.has(e.id)||(this.missing.add(e.id),this.registry.report(Error(`Route ${e.id} is waiting for a missing or disabled stop`),e.target)),!1):(this.missing.delete(e.id),!a.has(t.id)&&(e.spec.order===`any`||o[a.size]===t.id)):!1}step(e,t,n=!0){if(this.disposed)return;let r=Number.isFinite(t)?Math.max(0,t):0,i=this.registry.objects.filter(e=>e.spec.trigger&&e.spec.enabled!==!1);this.sync(i);let a=new Set(e.map(e=>e.id)),o=[];for(let t of i){let i=zt(t),s=t.target;if(!(s instanceof HTMLElement))continue;let c=this.visits.get(s);c||this.visits.set(s,c=new Map);for(let e of c.keys())a.has(e)||c.delete(e);let l=this.geometry(s);for(let a of e){let e=c.get(a.id)??Bt(),u=i.vehicles===`all`||a.player;if(!n||!l||!u||i.suspended){let n={...e,phase:!u||i.suspended||!l?`idle`:e.phase===`dwelling`?`entered`:e.phase,inside:l?e.inside:!1,dwell:0,routeDwell:new Map,position:this.publicPosition(a.position),angle:a.angle,targetPosition:l?this.publicPosition(l.center):void 0};c.set(a.id,n),(n.phase!==e.phase||n.inside!==e.inside)&&this.emit(`trigger:change`,{object:t,vehicle:{id:a.id},position:a.position,speedMps:a.speedMps,state:{inside:n.inside,departed:n.departed,stopped:n.qualified,phase:n.phase}},s);continue}let d=Vt(a),f=J(l),p=e.position&&this.localPosition(e.position),m=i.preset===`pickup`?At(a,l,p?{position:p,angle:e.angle??a.angle,target:e.targetPosition&&this.localPosition(e.targetPosition)}:void 0,r):void 0,h=m&&(!i.containment||i.containment===`overlap`),g=h?m.inside:i.containment===`center`?G(l,a.position):i.containment===`full`?J(d).every(e=>G(l,e)):!!it(J(d),f),_=i.containment===`center`?0:i.containment===`full`?-Math.hypot(a.lengthPx,a.widthPx)/2:a.widthPx/2,v=p&&Math.hypot(a.position.x-p.x,a.position.y-p.y)>.001,y=h?m.contact?.fraction??null:v?at(p,a.position,_,f):null,b=!g&&!e.inside&&y!==null,x=!e.inside&&(g||b),S=i.containment===`center`?!G(l,a.position,i.exitMarginPx??20):!it(J(d),J(Ht(l,i.exitMarginPx??20)));if(e.resetBlocked){S&&c.set(a.id,{...Bt(),departed:!0,position:this.publicPosition(a.position),angle:a.angle,targetPosition:this.publicPosition(l.center)});continue}let C=e.inside?0:y??1,w=m?.contact?.angle??0,T=m?.contact?.velocity??a.speedMps;o.push({object:t,config:i,target:s,vehicle:a,visits:c,previous:e,inside:g,crossed:b,entered:x,outside:S,departed:e.departed||S,arrival:C,pickupAngle:w,pickupSpeed:T,pickupOrigin:m?.contact?.origin,targetPosition:l.center})}}o.sort((e,t)=>e.arrival-t.arrival);for(let e of o){let{object:t,config:n,target:a,vehicle:o,visits:s,previous:c,inside:l,crossed:u,entered:d,outside:f,departed:p}=e,m=[...this.routes.values()].filter(e=>q(e).includes(t.id)),h=Wt(c.dwell,n,l,o.speedMps,r),g={object:t,vehicle:{id:o.id},position:{...o.position},speedMps:o.speedMps,state:{inside:l,departed:p,stopped:c.qualified,phase:d?`entered`:c.phase}};d&&this.emit(`trigger:enter`,g,a);let _=m.filter(e=>this.eligible(e,t,o,i)),v=new Map(c.routeDwell),y=_.filter(e=>{let i=e.spec.stops.find(e=>(typeof e==`string`?e:e.target)===t.id),a=typeof i==`string`?n:{...n,...i},s=Wt(c.routeDwell.get(e.id)??0,a,l,o.speedMps,r);return v.set(e.id,s),Ut(a,l,d,p,s)});for(let e of v.keys())_.some(t=>t.id===e)||v.delete(e);let b=this.credited.get(a)??new Set;this.credited.set(a,b);let x=n.repeat===`scene`?`scene`:o.id,S=n.repeat===`visit`?!c.qualified:!b.has(x),C=!f&&c.qualified,w=!1,T=(m.length?y.length>0:Ut(n,l,d,p,h))&&S;try{let r=!0;if(T&&(r=this.action(a,n),r)){w=!0,b.add(x),C=!f,g.state.stopped=C,g.state.phase=`success`;let r=m.length?y.some(e=>{let r=e.spec.stops.find(e=>(typeof e==`string`?e:e.target)===t.id);return(typeof r==`string`?n.when:r.when??n.when)===`stop`}):n.when===`stop`;n.preset===`pickup`&&t.spec.pickupEffectColor&&this.pickup?.(o.id,{color:t.spec.pickupEffectColor,angle:e.pickupAngle,origin:e.pickupOrigin,velocity:e.pickupSpeed});let i=t.spec.points??0;i>0&&(n.preset===`pickup`||r)&&this.awardPoints?.(this.publicPosition(e.targetPosition),i),this.emit(`trigger:qualify`,g,a),r&&this.emit(`trigger:stop`,g,a),n.event&&this.emit(n.event,g,a),n.consume&&!this.consumed.has(a)&&(this.consumed.set(a,{value:a.style.getPropertyValue(`visibility`),priority:a.style.getPropertyPriority(`visibility`)}),a.style.setProperty(`visibility`,`hidden`))}if(r)for(let e of y)this.credit(e,t,o,g)}catch(e){this.registry.report(e,a)}let E=m.some(e=>e.visited.get(e.spec.progress===`scene`?`scene`:o.id)?.has(t.id)),D=S&&l&&(m.length?_.some(e=>{let r=e.spec.stops.find(e=>(typeof e==`string`?e:e.target)===t.id),i=typeof r==`string`?n:{...n,...r},a=v.get(e.id)??0;return i.when===`stop`&&a>0&&a<(i.dwellSeconds??.45)&&(!i.requireExit||p)}):n.when===`stop`&&h>0&&h<(n.dwellSeconds??.45)&&(!n.requireExit||p)),O=w||E||n.repeat!==`visit`&&b.has(x)||c.phase===`success`&&!d?`success`:D?`dwelling`:l?`entered`:`idle`;g.state.phase=O,(!l&&c.inside||u)&&this.emit(`trigger:leave`,g,a),s.set(o.id,{phase:O,inside:l,departed:p,qualified:C,dwell:h,routeDwell:v,position:this.publicPosition(o.position),angle:o.angle,targetPosition:this.publicPosition(e.targetPosition)}),g.state.stopped=C,(l!==c.inside||p!==c.departed||C!==c.qualified||O!==c.phase)&&this.emit(`trigger:change`,g,a)}let s=new Set;for(let e of this.routes.values())for(let t of e.visited.values())for(let e of t)s.add(e);for(let e of i){let t=e.target;if(!(t instanceof HTMLElement))continue;let n=zt(e),r=[...this.visits.get(t)?.values()??[]],i=s.has(e.id)||n.repeat!==`visit`&&this.credited.get(t)?.size||r.some(e=>e.phase===`success`)?`success`:r.some(e=>e.phase===`dwelling`)?`dwelling`:r.some(e=>e.phase===`entered`)?`entered`:`idle`;this.visual(t,`data-jr-trigger-state`,i),this.visual(t,`data-jr-trigger-departed`,String(r.some(e=>e.departed))),this.stateClasses.apply(t,n,i)}}credit(e,t,n,r){let i=e.spec.progress===`scene`?`scene`:n.id,a=e.visited.get(i)??new Set;a.add(t.id),e.visited.set(i,a);let o=a.size===e.spec.stops.length,s={...r,route:{id:e.id,completed:a.size,total:e.spec.stops.length,complete:o}};this.emit(`route:progress`,s,e.target);let c={...r,objective:{id:e.id,type:`steps`,current:a.size,target:e.spec.stops.length,complete:o}};this.emit(`objective:progress`,c,e.target),o&&!e.completed.has(i)&&(e.completed.add(i),this.emit(`route:complete`,s,e.target),this.emit(`objective:complete`,c,e.target),e.spec.event&&this.emit(e.spec.event,e.objective?c:s,e.target))}actionTarget(e,t){let n=e;if(t.target){let e=[...this.registry.root.querySelectorAll(t.target)];if(this.registry.root instanceof Element&&this.registry.root.matches(t.target)&&e.unshift(this.registry.root),e.length!==1)throw Error(`Trigger action target must resolve to exactly one element`);n=e[0]}if(!(n instanceof HTMLElement))throw Error(`Trigger action target must support native activation`);return n}controlTarget(e){let t=e.matches(`input[type="checkbox"],[role="checkbox"],[role="switch"]`)?e:e.querySelector(Nt);return t instanceof HTMLElement?t:null}action(e,t){if(t.action===`event`)return!0;let n=this.actionTarget(e,t);if(n.matches(`:disabled,[aria-disabled="true"]`))return!1;if(t.action===`click`)return n.click(),!0;let r=this.controlTarget(n);if(!(r instanceof HTMLElement))throw Error(`Checkbox action needs a checkbox or switch target`);if(r.matches(`:disabled,[aria-disabled="true"]`))return!1;let i=r instanceof HTMLInputElement?r.checked:r.getAttribute(`aria-checked`)===`true`;return(t.action===`toggle`||i!==(t.action===`check`))&&r.click(),!0}visual(e,t,n){let r=this.visuals.get(e);r||this.visuals.set(e,r=new Map);let i=r.get(t);i?.applied!==n&&(i?i.applied=n:r.set(t,{original:e.getAttribute(t),applied:n}),e.getAttribute(t)!==n&&e.setAttribute(t,n))}captureState(){return b({visits:this.visits,credited:this.credited,routes:[...this.routes].map(([e,t])=>({id:e,visited:t.visited,completed:t.completed})),consumed:this.consumed,visuals:this.visuals,classes:this.stateClasses.captureState(),controls:this.controls.captureState()})}restoreState(e){let t=b(e);this.reset(),this.visits.clear();for(let[e,n]of t.visits)this.visits.set(e,n);for(let[e,n]of t.credited)this.credited.set(e,n);for(let e of t.routes){let t=this.routes.get(e.id);t&&(t.visited=e.visited,t.completed=e.completed)}for(let[e,n]of t.consumed)this.consumed.set(e,n),e.style.setProperty(`visibility`,`hidden`);for(let[e,n]of t.visuals){this.visuals.set(e,n);for(let[t,r]of n)e.setAttribute(t,r.applied)}this.stateClasses.restoreState(t.classes),this.controls.restoreState(t.controls)}restore(e){if(!(e instanceof HTMLElement))return;this.stateClasses.restore(e);let t=this.consumed.get(e);t&&e.style.visibility===`hidden`&&(t.value?e.style.setProperty(`visibility`,t.value,t.priority):e.style.removeProperty(`visibility`)),this.consumed.delete(e);for(let[t,n]of this.visuals.get(e)??[])e.getAttribute(t)===n.applied&&(n.original===null?e.removeAttribute(t):e.setAttribute(t,n.original));this.visuals.delete(e)}resetRoute(e){e.visited.clear(),e.completed.clear(),this.missing.delete(e.id);for(let t of this.registry.objects)q(e).includes(t.id)&&(this.visits.delete(t.target),this.credited.delete(t.target),this.restore(t.target))}resetObject(e){let t=this.visits.get(e);this.restore(e),this.credited.delete(e);let n=new Map;for(let[e,r]of t??[])r.inside&&n.set(e,{...Bt(),inside:!0,resetBlocked:!0});n.size?this.visits.set(e,n):this.visits.delete(e);let r=this.registry.get(e);if(r?.spec.trigger){let t=this.controlTarget(this.actionTarget(e,zt(r)));t&&this.controls.resetTarget(t)}if(r){for(let e of this.routes.values())if(q(e).includes(r.id)){for(let t of e.visited.values())t.delete(r.id);e.completed.clear(),this.missing.delete(e.id)}}this.frameGeometry?.clear()}reset(){let e=new Map;for(let[t,n]of this.visits){let r=new Map;for(let[e,t]of n)t.inside&&r.set(e,{...Bt(),inside:!0,resetBlocked:!0});r.size&&e.set(t,r)}this.stateClasses.reset(),this.controls.reset(),this.frameGeometry?.clear(),this.defaultGeometryFrame&&=new xt;for(let e of new Set([...this.visits.keys(),...this.consumed.keys(),...this.visuals.keys()]))this.restore(e);this.visits.clear();for(let[t,n]of e)this.visits.set(t,n);this.credited.clear(),this.missing.clear();for(let e of this.routes.values())e.visited.clear(),e.completed.clear()}dispose(){this.disposed||(this.reset(),this.controls.dispose(),this.visits.clear(),this.disposed=!0,this.unsubscribe(),this.routes.clear(),this.reservedObjectives.clear(),this.declarations.clear(),this.definitionRoutes.clear(),this.listeners.clear(),this.frameGeometry=null,this.defaultGeometryFrame=void 0)}},Kt=(e,t)=>e.childNodes.length===1&&e.firstChild===t.node&&t.node.data===t.last,qt=class{registry;values=new Map;disposed=!1;constructor(e){this.registry=e}update(e){if(this.disposed)return;let t=new Set;for(let n of this.registry.objects){let r=n.spec.hud;if(!r||n.spec.enabled===!1)continue;let i=n.target;t.add(i);let a=Jt(r,e),o=this.values.get(i);if(!o||!Kt(i,o)){let e=[...i.childNodes],t=i.ownerDocument.createTextNode(a);i.replaceChildren(t),o={original:e,node:t,last:a},this.values.set(i,o)}else o.last!==a&&(o.node.data=a,o.last=a)}for(let e of this.values.keys())t.has(e)||this.restore(e)}restore(e){let t=this.values.get(e);t&&(Kt(e,t)&&e.replaceChildren(...t.original),this.values.delete(e))}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.values.keys())this.restore(e)}}};function Jt(e,t){let n=e.field===`speed`?t.speedMps:t[e.field];return e.field===`gear`?n==null?`—`:String(n):typeof n!=`number`||!Number.isFinite(n)?`—`:(e.field===`speed`&&(n*=e.unit===`kmh`?3.6:e.unit===`mps`?1:1/.44704),n.toFixed(e.precision??0))}var Yt=class e{registry;zones;entries=new Map;declarations=new Map;dirty=!0;disposed=!1;unsubscribe;unsubscribeZones;constructor(e,t){this.registry=e,this.zones=t,this.unsubscribe=e.subscribe(()=>{this.dirty=!0}),this.unsubscribeZones=t.onEvent((e,t)=>{if(e!==`trigger:qualify`)return;let n=t.object,r=n.spec.trigger;(typeof r==`object`?r.preset:r)===`pickup`&&this.record(`collect`,n,t.vehicle.id)});try{for(let[t,n]of Object.entries(e.definitions.objectives??{}))`type`in n&&this.add(t,n,void 0,!0);this.sync()}catch(e){throw this.dispose(),e}}objective(e,t){if(this.disposed)throw Error(`Playground is disposed`);let n=Ee(t);return`steps`in n?this.zones.objective(e,n):this.add(e,n)}add(t,n,r,i=!1){this.zones.reserveObjective(t);let a={id:t,spec:structuredClone(n),rows:new Map,target:r,definition:i};return this.entries.set(t,a),this.clear(a),{id:t,get state(){return e.state(a)},reset:()=>{this.entries.get(t)===a&&this.clear(a)},dispose:()=>{this.entries.get(t)===a&&this.remove(t)}}}static state(e){return Object.freeze([...e.rows].map(([t,n])=>Object.freeze({vehicleId:t,current:n.current,target:e.spec.type===`score`?e.spec.points:e.spec.count,complete:n.complete})))}clear(e){e.rows.clear(),(e.spec.progress??`scene`)===`scene`&&e.rows.set(`scene`,{current:0,complete:!1,seen:new Set})}remove(e){this.entries.delete(e),this.zones.releaseObjective(e)}sync(){if(!this.dirty||this.disposed)return;this.dirty=!1;let e=[...this.registry.root.querySelectorAll(`[data-jr-objective]`)];this.registry.root instanceof Element&&this.registry.root.matches(`[data-jr-objective]`)&&e.unshift(this.registry.root);let t=e.filter(e=>e.hasAttribute(`data-jr-objective-type`));for(let[e,n]of this.declarations)t.includes(e)||(this.remove(n.id),this.declarations.delete(e));this.zones.syncObjectives();for(let e of t)try{let t=e.getAttribute(`data-jr-objective`)??``,n=e.getAttribute(`data-jr-objective-type`),r=Ee({type:n,...n===`score`?{points:Number(e.getAttribute(`data-jr-objective-points`))}:{count:Number(e.getAttribute(`data-jr-objective-count`))},...e.hasAttribute(`data-jr-objective-targets`)?{targets:e.getAttribute(`data-jr-objective-targets`).split(/[\s,]+/).filter(Boolean)}:{},...e.hasAttribute(`data-jr-objective-progress`)?{progress:e.getAttribute(`data-jr-objective-progress`)}:{},...e.hasAttribute(`data-jr-objective-event`)?{event:e.getAttribute(`data-jr-objective-event`)}:{}}),i=JSON.stringify({id:t,spec:r}),a=this.declarations.get(e);if(a?.signature===i)continue;if(a?.id!==t&&this.zones.hasObjective(t))throw Error(`Objective already exists: ${t}`);a&&this.remove(a.id),this.add(t,r,e),this.declarations.set(e,{id:t,signature:i})}catch(t){this.registry.report(t,e)}}record(e,t,n){if(!(this.disposed||t.spec.enabled===!1))for(let r of[...this.entries.values()]){if(this.entries.get(r.id)!==r)continue;let i=r.spec;if(i.type!==e||i.targets&&!i.targets.includes(t.id))continue;let a=(i.progress??`scene`)===`scene`?`scene`:n;if(!a)continue;let o=r.rows.get(a)??{current:0,complete:!1,seen:new Set};o.complete||o.seen.has(t.id)||(o.seen.add(t.id),o.current=Math.min(i.count,o.current+1),r.rows.set(a,o),this.publish(r,a,o,i.count))}}updateScore(e){if(!this.disposed&&Number.isFinite(e))for(let t of[...this.entries.values()]){if(this.entries.get(t.id)!==t||t.spec.type!==`score`)continue;let n=t.rows.get(`scene`),r=Math.max(0,Math.min(t.spec.points,e));n.complete||r===n.current||(n.current=r,this.publish(t,`scene`,n,t.spec.points))}}publish(e,t,n,r){n.complete=n.current>=r;let i=o({objective:{id:e.id,type:e.spec.type,current:n.current,target:r,complete:n.complete},...t===`scene`?{}:{vehicle:{id:t}}}),a=t=>(e.target??this.registry.root).dispatchEvent(new CustomEvent(`joyride:${t}`,{bubbles:!0,detail:i}));a(`objective:progress`),n.complete&&(a(`objective:complete`),e.spec.event&&a(e.spec.event))}exportObjectives(){if(this.disposed)throw Error(`Playground is disposed`);return{...this.zones.exportObjectives(),...Object.fromEntries([...this.entries].filter(([,e])=>!e.target&&!e.definition).map(([e,t])=>[e,structuredClone(t.spec)]))}}captureState(){return b([...this.entries].map(([e,t])=>({id:e,signature:JSON.stringify(t.spec),rows:t.rows})))}restoreState(e){for(let e of this.entries.values())this.clear(e);for(let t of b(e)){let e=this.entries.get(t.id);e&&JSON.stringify(e.spec)===t.signature&&(e.rows=t.rows)}}reset(){for(let e of this.entries.values())this.clear(e)}dispose(){if(!this.disposed){this.disposed=!0,this.unsubscribe(),this.unsubscribeZones();for(let e of this.entries.keys())this.zones.releaseObjective(e);this.entries.clear(),this.declarations.clear()}}},Xt=class{simulation;project;root;report;applied=new Map;requests=new Set;objects=[];serial=0;nextMeasure=0;disposed=!1;failures=new Map;constructor(e,t,n,r){this.simulation=e,this.project=t,this.root=n,this.report=r}add(e,t={}){if(this.disposed)throw Error(`Playground debris is disposed`);y(t),typeof e==`string`&&this.root.querySelectorAll(e);let n={id:`page-debris-${++this.serial}`,target:typeof e==`string`||e instanceof Element?e:[...e],options:structuredClone(t)};if(typeof n.target!=`string`&&!(n.target instanceof Element)&&[...n.target].some(e=>!(e instanceof Element)))throw TypeError(`Debris targets must be elements`);this.requests.add(n),this.sync(this.objects,!0);let r=()=>!this.disposed&&[...this.requests].some(e=>e.id===n.id);return{id:n.id,reset:()=>{if(r())for(let e of this.applied.values())e.owner===n.id&&e.handle.reset()},gust:e=>{if(r())for(let t of this.applied.values())t.owner===n.id&&t.handle.gust(e)},dispose:()=>{if(r()){for(let e of this.requests)e.id===n.id&&this.requests.delete(e);this.sync(this.objects,!0)}}}}sync(e,t=!1){if(this.disposed)return;let n=performance.now();if(this.objects!==e&&(t=!0),this.objects=e,!t&&n<this.nextMeasure)return;this.nextMeasure=n+200;let r=new Map;for(let t of e){if(t.spec.enabled===!1||!t.target.isConnected||t.spec.debris===!1)continue;let e=t.spec.debris;e&&r.set(t.target,{options:e===!0?{}:e,owner:`html`})}for(let e of this.requests){let t=typeof e.target==`string`?[...this.root instanceof Element&&this.root.matches(e.target)?[this.root]:[],...this.root.querySelectorAll(e.target)]:e.target instanceof Element?[e.target]:e.target;for(let n of t)n.isConnected&&r.set(n,{options:e.options,owner:e.id})}for(let[e,t]of this.applied)r.has(e)||(t.handle.dispose(),this.applied.delete(e),this.failures.delete(e));for(let e of this.failures.keys())r.has(e)||this.failures.delete(e);for(let[e,t]of r){let n=``;try{let r=e.getBoundingClientRect(),i=this.project({x:r.left,y:r.top}),a=this.project({x:r.right,y:r.bottom}),o={x:i.x,y:i.y,width:Math.max(0,a.x-i.x),height:Math.max(0,a.y-i.y)};n=JSON.stringify([t.owner,t.options,...[o.x,o.y,o.width,o.height].map(e=>Math.round(e/4))]);let s=this.applied.get(e);if(s?.signature===n||this.failures.get(e)===n)continue;if(Object.values(o).some(e=>!Number.isFinite(e)))throw RangeError(`Invalid debris source geometry`);if(this.simulation.count-(s?.amount??0)+(t.options.amount??30)>3e3)throw RangeError(`Scene debris budget is 3000 particles`);s?.handle.dispose();let c=this.simulation.scatter(o,t.options);this.failures.delete(e),this.applied.set(e,{signature:n,handle:c,owner:t.owner,amount:t.options.amount??30})}catch(t){this.failures.get(e)!==n&&this.report(t,e),this.failures.set(e,n)}}}gust(e,t){this.applied.get(e)?.handle.gust(t)}reset(e){for(let[t,n]of this.applied)e&&t!==e||n.handle.reset()}captureState(){return{applied:[...this.applied].map(([e,t])=>[e,{...t,handle:t.handle.id}]),requests:[...this.requests],serial:this.serial}}restoreState(e){this.applied.clear();for(let[t,n]of e.applied){let e=this.simulation.get(n.handle);e&&this.applied.set(t,{...n,handle:e})}this.requests=new Set(e.requests),this.serial=Math.max(this.serial,e.serial),this.failures.clear(),this.nextMeasure=0}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.applied.values())e.handle.dispose();this.applied.clear(),this.failures.clear(),this.requests.clear(),this.objects=[]}}};function Zt({id:e,target:t,spec:n}){let r=(t.innerText??t.textContent??``).replace(/\s+/g,` `).trim(),i=t.matches(`img`)?[t]:[...t.querySelectorAll(`img`)],a=i.find(e=>getComputedStyle(e).display!==`none`)??i[0],o=(typeof n.meta?.name==`string`?n.meta.name:``)||t.getAttribute(`aria-label`)||t.getAttribute(`title`)||a?.alt||r||t.id||t.tagName.toLowerCase(),s=[];for(let[e,t]of[[`crushable`,`Crushable`],[`breakable`,`Breakable`],[`burnable`,`Burnable`],[`combustible`,`Combustible`],[`pushable`,`Pushable`],[`solid`,`Wall`],[`liquid`,`Liquid`],[`debris`,`Debris`],[`hud`,`Readout`]])n[e]&&s.push(t);if(n.trigger){let e=typeof n.trigger==`string`?n.trigger:typeof n.trigger==`object`?n.trigger.preset:void 0;s.push(e?e.charAt(0).toUpperCase()+e.slice(1):`Trigger`)}let c=getComputedStyle(t),l=c.backgroundImage?.match(/^url\(["']?(.*?)["']?\)$/)?.[1],u=n.liquid&&typeof n.liquid.color==`string`&&n.liquid.color!==`auto`?n.liquid.color:c.backgroundColor,d,f=t.tagName.toLowerCase()===`svg`?t:t.querySelector(`svg`);if(!a&&f){let e=f.cloneNode(!0);e.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),e.style.opacity=`1`,e.style.color=getComputedStyle(f).color,d=`data:image/svg+xml,${encodeURIComponent(new XMLSerializer().serializeToString(e))}`}let p={image:a?.currentSrc||a?.src||d||l,color:u&&u!==`transparent`&&u!==`rgba(0, 0, 0, 0)`?u:void 0,text:r.slice(0,20)},m=t.getAttribute(`data-jr-crushed`)===null?t.getAttribute(`data-jr-trigger-state`)||(c.visibility===`hidden`?`Hidden`:`Active`):`Crushed`;return Object.freeze({id:e,name:o.slice(0,90),element:`${t.tagName.toLowerCase()}${t.id?`#${t.id}`:t.getAttribute(`data-jr-id`)?`[${t.getAttribute(`data-jr-id`)}]`:``}`,capabilities:Object.freeze(s),preview:Object.freeze(p),state:m,resettable:s.some(e=>![`Wall`,`Texture`,`Readout`].includes(e))})}var Qt=class{registry;renderer;commands;snapshot=Object.freeze([]);notificationQueued=!1;dirty=!0;disposed=!1;listeners=new Set;unsubscribe;constructor(e,t,n){this.registry=e,this.renderer=t,this.commands=n,this.unsubscribe=e.subscribe(this.refresh)}refresh=()=>{this.disposed||(this.dirty=!0,!this.notificationQueued&&this.listeners.size&&(this.notificationQueued=!0,queueMicrotask(()=>{if(this.notificationQueued=!1,!this.disposed)for(let e of this.listeners)e()})))};getSnapshot=()=>{if(!this.dirty||this.disposed)return this.snapshot;let e=this.registry.objects.filter(e=>e.spec.enabled!==!1&&[`crushable`,`breakable`,`burnable`,`combustible`,`pushable`,`solid`,`liquid`,`debris`,`trigger`].some(t=>e.spec[t])).map(Zt);return this.dirty=!1,e.length===this.snapshot.length&&e.every((e,t)=>{let n=this.snapshot[t];return e.id===n.id&&e.name===n.name&&e.element===n.element&&e.state===n.state&&e.capabilities.join(`,`)===n.capabilities.join(`,`)&&e.preview.image===n.preview.image&&e.preview.color===n.preview.color&&e.preview.text===n.preview.text})||(this.snapshot=Object.freeze(e)),this.snapshot};subscribe=e=>(this.listeners.add(e),this.dirty=!0,()=>{this.listeners.delete(e)});getTarget=e=>{if(this.disposed)return null;let t=this.registry.objects.find(t=>t.id===e&&t.spec.enabled!==!1);return t?.target.isConnected?t.target:null};reveal=e=>{let t=this.getTarget(e);return t?(this.renderer.interruptFollow(),t.scrollIntoView({block:`center`,inline:`center`,behavior:`instant`}),this.renderer.flashTargets((e,n)=>{let r=t.getBoundingClientRect(),i=[[r.left,r.top],[r.left+r.width,r.top],[r.left+r.width,r.top+r.height],[r.left,r.top+r.height]].map(([e,t])=>this.renderer.documentFromViewport({x:e,y:t}));e.save(),e.fillStyle=`#fff`,e.beginPath(),i.forEach((t,r)=>r?e.lineTo(t.x-n.x,t.y-n.y):e.moveTo(t.x-n.x,t.y-n.y)),e.closePath(),e.fill(),e.restore()}),!0):!1};reset=e=>{if(this.disposed)return!1;let t=this.commands.reset(e);return this.refresh(),t};remove=e=>{if(this.disposed)return!1;let t=this.commands.remove(e);return this.refresh(),t};dispose(){this.disposed=!0,this.unsubscribe(),this.listeners.clear(),this.snapshot=Object.freeze([])}};function $t(e){switch(e.kind){case`object`:return e.type;case`destructibleDestroyed`:return e.cause??`break`;case`combustionExplosion`:return`explode`;case`crush`:return`crush`;case`impact`:return`hit`;case`scrape`:return null;default:return e}}function en(e,t){let n=$t(t);if(!n)return null;let r=t.element?e.get(t.element):e.objects.find(e=>e.id===t.objectId);if(!r)return null;let i=t.kind===`impact`?t.impact.point:`point`in t?t.point:void 0,a=Object.freeze({object:r,vehicle:t.vehicleId?Object.freeze({id:t.vehicleId}):void 0,point:i&&Object.freeze({...i}),...`points`in t?{points:t.points}:{}});return{name:n,target:r.target,detail:a}}function tn(e,t,n,r){let{sim:i}=e,a=i.car,o=t?.redlineRpm??8e3,s=t?.gear;return{speed:(i.paused?0:P(i.body.velocity))*2.2369362921,rpm:t?.rpm??0,gear:s==null||s===0?`N`:s,maxRpm:Math.ceil(o/1e3)*1e3,redlineRpm:o,hp:a.health,maxHp:a.maxHealth,points:n,totalPoints:r,maxPoints:r??999999}}var nn=class{registry;world;zones;objectives;objects;hud;debrisSources;handles=new Map;ownedVehicles=new Set;removedObjects=new Set;pendingEvents=[];unregister=[];disposed=!1;serial=0;constructor(e,t){this.registry=e,this.world=t,this.zones=new Gt(e,void 0,e=>t.renderer.documentFromViewport(e),e=>t.renderer.viewportFromDocument(e),(e,n)=>t.vehicles.find(t=>t.id===e)?.pickupEffect.trigger(n),(e,n)=>t.awardPoints(e,n));try{this.objectives=new Yt(e,this.zones)}catch(e){throw this.zones.dispose(),e}this.hud=new qt(e),this.debrisSources=new Xt(t.renderer.debris,e=>t.renderer.documentFromViewport(e),e.root,(t,n)=>e.report(t,n)),this.objects=new Qt(e,t.renderer,{reset:e=>this.resetObject(e),remove:e=>this.removeObject(e)});try{this.unregister.push(t.registerStateParticipant(`registry`,e)),this.unregister.push(t.registerStateParticipant(`zones`,this.zones)),this.unregister.push(t.registerStateParticipant(`objectives`,this.objectives)),this.unregister.push(t.registerStateParticipant(`debris-sources`,this.debrisSources)),this.unregister.push(t.registerStateParticipant(`removed-page-objects`,{captureState:()=>new Set(this.removedObjects),restoreState:e=>{this.removedObjects.clear();for(let t of e)this.removedObjects.add(t);this.objects.refresh()}})),this.unregister.push(t.events.subscribe(e=>this.pendingEvents.push(Je(e)))),this.sync()}catch(e){throw this.dispose(),e}}point(e){if(typeof e==`string`){let t=document.querySelector(e);if(!t)throw Error(`Placement target not found: ${e}`);e=t}if(e instanceof Element){if(!e.isConnected)throw Error(`Placement target is not connected`);let t=e.getBoundingClientRect(),n=this.world.renderer.virtualOffset();return{x:t.left+t.width/2+window.scrollX+n.x,y:t.top+t.height/2+window.scrollY+n.y}}if(e){if(!Number.isFinite(e.xPx)||!Number.isFinite(e.yPx))throw RangeError(`Placement must use finite document coordinates`);return{x:e.xPx,y:e.yPx}}let t=this.world.focusVehicle;return t?this.world.renderer.documentPoint(t.sim.body.position):{x:window.scrollX+window.innerWidth/2,y:window.scrollY+window.innerHeight/2}}vehicleConfiguration(e,t){for(let t of Object.keys(e))if(![`id`,`vehicle`,`appearance`,`slots`].includes(t))throw TypeError(`Vehicle configuration does not support ${t}; decorate page elements with ride.bind instead`);if(t&&e.id!==void 0&&e.id!==t.id)throw Error(`A live vehicle ID cannot change`);let n=we(De({vehicle:e.vehicle,...this.registry.vehicleOptions(e.vehicle)},e)),r=t?.sim.car.preset.id===n.vehicle?t.sim.car.preset:this.registry.resolveVehicle(n.vehicle),i=structuredClone(n.slots??{});for(let e of Object.values(i))e&&e.action===`eject`&&(e.liquid=this.registry.resolveLiquid(e.liquid));return{spec:n,preset:r,slots:ve(i)}}applyVehicle(e,t){let{spec:n,preset:r,slots:i}=t;if(!this.world.configureVehicle(e.id,{preset:r===e.sim.car.preset?void 0:r,appearance:n.appearance??`auto`,slots:i}))throw Error(`Vehicle is unavailable`);this.registry.root.dispatchEvent(new CustomEvent(`joyride:vehicle:change`,{bubbles:!0,detail:{vehicle:this.vehicleHandle(e).state}}))}spawnVehicle(e){if(this.disposed)throw Error(`Playground is disposed`);let{at:t,angleDeg:n=0,...r}=e,i=this.vehicleConfiguration(r);if(!Number.isFinite(n))throw RangeError(`Vehicle heading must be finite`);let a=this.point(t),{spec:o,preset:s}=i,c=o.id;if(!c)do c=`jr-vehicle-${++this.serial}`;while(this.world.getVehicle(c));let l=new N;l.setPreset(s);let u=this.world.spawnVehicle({id:c,sim:l,control:{kind:`parked`}});try{return u.sim.body.position=this.world.renderer.worldFromDocument(a),u.sim.body.angle=-n*Math.PI/180,this.ownedVehicles.add(u.id),this.applyVehicle(u,i),this.vehicleHandle(u)}catch(e){throw this.ownedVehicles.delete(u.id),this.handles.delete(u.id),this.world.removeVehicle(u.id),e}}get player(){let e=this.world.playerVehicle;return e?this.vehicleHandle(e):null}getVehicle(e){let t=this.world.getVehicle(e);return t?this.handles.get(t.id)??this.vehicleHandle(t):null}vehicleName(e){try{return this.registry.vehicleName(e.sim.car.preset.id)}catch(n){if(!(n instanceof t))throw n;return e.sim.car.preset.id}}vehicleHandle(e){let t=e.id,n=this.handles.get(t);if(n)return n;let r=!1,i=()=>{let e=this.world.getVehicle(t);if(this.disposed||r||!e)throw Error(`Vehicle is unavailable`);return e},a=()=>{let e=i(),n=structuredClone(e.slots);for(let e of Object.values(n))e&&(e.action===`eject`&&(e.liquid=this.registry.liquidName(e.liquid)),Object.freeze(e));return Object.freeze({id:t,vehicle:this.vehicleName(e),position:Object.freeze({...this.world.renderer.documentPoint(e.sim.body.position)}),speedMps:P(e.sim.body.velocity),health:e.sim.car.health,maxHealth:e.sim.car.maxHealth,appearance:e.appearance,slots:Object.freeze(n)})},o={id:t,get state(){return a()},update:e=>{Te(e);let t=i(),n=e.vehicle===void 0?{vehicle:this.vehicleName(t),appearance:t.appearance,slots:t.slots}:{vehicle:e.vehicle},r=we(De(n,e));this.applyVehicle(t,this.vehicleConfiguration(r,t))},pickupEffect:e=>i().pickupEffect.trigger(e),useSlot:e=>i().useSlot(e),startSlot:e=>i().startSlot(e),stopSlot:e=>i().stopSlot(e),dispose:()=>{r||(r=!0,this.disposed||this.world.removeVehicle(t),this.ownedVehicles.delete(t),this.handles.delete(t))}};return this.handles.set(t,o),o}debris(e,t={}){return this.debrisSources.add(e,t)}resetDebris(e){this.debrisSources.reset(e)}gustDebris(e,t){this.debrisSources.sync(this.registry.objects,!0),this.debrisSources.gust(e,t)}pour(e,t){if(this.disposed)throw Error(`Playground is disposed`);this.world.renderer.addLiquid(this.registry.resolveLiquid(e),{...t,at:this.world.renderer.worldFromDocument(this.point(t.at))})}objective(e,t){return this.objectives.objective(e,t)}route(e,t){return this.zones.route(e,t)}beginFrame(){this.disposed||(this.objectives.sync(),this.zones.beginFrame())}sync(){this.disposed||(this.objectives.sync(),this.debrisSources.sync(this.registry.objects))}step(e,t){this.disposed||(this.zones.step(this.world.vehicles.map(e=>({id:e.id,player:e===this.world.playerVehicle,position:this.world.renderer.viewportFromDocument(this.world.renderer.documentPoint(e.sim.body.position)),speedMps:P(e.sim.body.velocity),velocityMps:{x:e.sim.body.velocity.x,y:-e.sim.body.velocity.y},angle:-e.sim.body.angle,angularVelocity:-e.sim.body.spin,pixelsPerMeter:this.world.renderer.documentScale(),mask:this.world.collisions.vehicleMask(e.sim.car.preset,e.damage),lengthPx:e.sim.car.preset.geometry.lengthM*this.world.renderer.documentScale(),widthPx:e.sim.car.preset.geometry.widthM*this.world.renderer.documentScale()})),e,t),this.flushObjectEvents(),t&&this.objectives.updateScore(this.world.points))}flushObjectEvents(){let e=this.pendingEvents.splice(0);e.length&&this.objects.refresh();for(let t of e){let e=en(this.registry,t);e&&([`crush`,`break`,`ignite`].includes(e.name)&&this.objectives.record(e.name,e.detail.object,e.detail.vehicle?.id),e.target.dispatchEvent(new CustomEvent(`joyride:object:${e.name}`,{bubbles:!0,detail:e.detail})))}}present(e){this.hud.update(e)}resetObject(e){if(this.disposed)return!1;let t=this.registry.objects.find(t=>t.id===e&&t.spec.enabled!==!1);if(!t)return!1;this.world.collisions.resetObject?.(e),this.zones.resetObject(t.target),this.debrisSources.reset(t.target);for(let n=this.pendingEvents.length-1;n>=0;n--)(this.pendingEvents[n].element===t.target||this.pendingEvents[n].objectId===e)&&this.pendingEvents.splice(n,1);return this.objects.refresh(),!0}removeObject(e){if(!this.resetObject(e))return!1;let t=this.registry.objects.find(t=>t.id===e);return this.registry.update(t.target,{enabled:!1}),this.removedObjects.add(t.target),this.sync(),!0}reset(){if(!this.disposed){this.pendingEvents.length=0,this.zones.reset(),this.objectives.reset();for(let e of this.removedObjects)this.registry.get(e)?.spec.enabled===!1&&this.registry.update(e,{enabled:!0});this.removedObjects.clear(),this.sync(),this.world.resetScene(),this.objects.refresh(),this.registry.root.dispatchEvent(new CustomEvent(`joyride:reset`,{bubbles:!0}))}}dispose(){if(!this.disposed){this.disposed=!0,this.objectives.dispose(),this.zones.dispose(),this.hud.dispose(),this.debrisSources.dispose(),this.objects.dispose();for(let e of this.ownedVehicles)this.world.removeVehicle(e);this.ownedVehicles.clear(),this.removedObjects.clear(),this.handles.clear(),this.pendingEvents.length=0;for(let e of this.unregister)e()}}},rn=class{world;page;loop;disposed=!1;resources=new r;constructor(e,t){this.world=e,this.resources.own(()=>e.dispose());try{this.page=t?new nn(t,e):null,this.page&&this.resources.own(()=>this.page.dispose())}catch(e){throw this.resources.dispose(),e}}clock(e,t,n){if(this.disposed)throw Error(`Browser runtime is disposed`);if(this.loop)throw Error(`Browser runtime already has a clock`);return this.loop=new rt(()=>(this.page?.beginFrame(),e()),t,n,1/120,12,e=>{this.page?.registry.report(e);let t=this.world.focusVehicle;t&&this.world.renderer.restorePage(t.sim)},e=>this.world.advanceTime(e)),this.resources.own(()=>this.loop?.stop()),this.loop}dispose(){this.disposed||(this.disposed=!0,this.resources.dispose())}},an=`body[data-jr-virtual-camera]>:not([data-jr-overlay]):not([data-jr-ui]):not([data-jr-touch-controls]):not([data-jr-embed]){translate:var(--joy-ride-scene-x,0px) var(--joy-ride-scene-y,0px)}[data-jr-trigger=parking]{--stop-zone-color:var(--drive-ink,currentColor);box-sizing:border-box;border:2px solid color-mix(in srgb, var(--stop-zone-color) 28%, transparent);background:color-mix(in srgb, var(--stop-zone-color) 3%, transparent);color:color-mix(in srgb, var(--stop-zone-color) 55%, transparent);border-radius:4px;transition:opacity .3s,background .2s}[data-jr-trigger=parking][data-jr-trigger-state=entered],[data-jr-trigger=parking][data-jr-trigger-state=dwelling],[data-jr-trigger=parking][data-jr-trigger-state=success]{background:color-mix(in srgb, var(--stop-zone-color) 8%, transparent)}[data-jr-trigger=parking][data-jr-trigger-reveal=departed]{opacity:0}[data-jr-trigger=parking][data-jr-trigger-reveal=departed][data-jr-trigger-departed=true]:not([data-jr-enabled=false]){opacity:1}@media (prefers-reduced-motion:reduce){[data-jr-trigger=parking]{transition:none}}`;function on(e,t,n,r={x:0,y:0}){let i=Math.max(1,t),a=Math.max(0,e.width*e.height)/(i*i),o=Math.max(.015,Math.min(3,Math.sqrt(a)*.3)),s=Math.hypot(r.x,r.y);return{center:{x:e.x+e.width/2,y:e.y+e.height/2},pixelsPerMetre:i,radiusM:o,amount:Math.max(.003,Math.min(24,a*.4)),color:v(n),age:0,duration:.18+Math.min(.12,o*.04),angle:s>.01?Math.atan2(r.y,r.x):e.x*.17+e.y*.11,drift:s>.01?{x:r.x/s*Math.min(s,3)*.12,y:r.y/s*Math.min(s,3)*.12}:{x:0,y:0}}}var sn=e=>e*e*(3-2*e);function cn(e,t){let n=Math.min(1,e.age/e.duration);e.age=Math.min(e.duration,e.age+Math.max(0,t));let r=e.age/e.duration;if(r<=n)return[];let i=(n+r)*.5,a=e.radiusM*(.14+.86*Math.sqrt(i)),o=e.amount*(sn(r)-sn(n)),s=e.radiusM/e.duration*(1-i)*.8,c=Math.cos(e.angle),l=Math.sin(e.angle);return[[0,0,.64,1],[-.53,.16,.13,.48],[.42,-.38,.1,.42],[.27,.52,.13,.46]].map(([t,n,r,i])=>{let u=t*c-n*l,d=t*l+n*c;return{point:{x:e.center.x+u*a*e.pixelsPerMetre,y:e.center.y+d*a*e.pixelsPerMetre},radiusM:a*i,amount:o*r,color:e.color,flowMps:{x:u*s+e.drift.x,y:d*s+e.drift.y}}})}function ln(e,t,n,r={align:6,meetOrSlice:1}){let i=t/e.width,a=n/e.height;if(r.align===1)return{scaleX:i,scaleY:a,x:-e.x*i,y:-e.y*a};let o=r.align>=2&&r.align<=10?r.align-2:4,s=r.meetOrSlice===2?Math.max(i,a):Math.min(i,a);return{scaleX:s,scaleY:s,x:(t-e.width*s)*(o%3/2)-e.x*s,y:(n-e.height*s)*(Math.floor(o/3)/2)-e.y*s}}function Y(e){if(!e.detached)return e.ink;let t=Math.cos(e.angle),n=Math.sin(e.angle),r=e.ink.width/2,i=e.ink.height/2,a=e.ink.x+r-e.base.x-e.base.width/2,o=e.ink.y+i-e.base.y-e.base.height/2,s=e.base.x+e.base.width/2+e.offset.x+a*t-o*n,c=e.base.y+e.base.height/2+e.offset.y+a*n+o*t,l=Math.abs(t)*r+Math.abs(n)*i,u=Math.abs(n)*r+Math.abs(t)*i;return{x:s-l,y:c-u,width:2*l,height:2*u}}function un(e,t){let{ink:n}=e;if(!e.detached)return n.x<t.x+t.width&&n.x+n.width>t.x&&n.y<t.y+t.height&&n.y+n.height>t.y;let r=e.base.x+e.base.width/2,i=e.base.y+e.base.height/2,a=Math.max(Math.abs(n.x-r),Math.abs(n.x+n.width-r)),o=Math.max(Math.abs(n.y-i),Math.abs(n.y+n.height-i)),s=Math.sqrt(a*a+o*o),c=r+e.offset.x,l=i+e.offset.y;return c-s<t.x+t.width&&c+s>t.x&&l-s<t.y+t.height&&l+s>t.y}function dn(e,t,n,r){let i=k(t,T(e.velocity,-1));e.detached=!0,e.velocity=k(T(e.velocity,.35),k(T(i,.55),T(n,80+Math.min(220,P(i)*.3)))),e.spin=e.spin*.3+r,e.offset=k(e.offset,T(n,2)),e.impactCooldown=.12}function fn(e,t){e.impactCooldown=Math.max(0,e.impactCooldown-t),e.detached&&(e.velocity=T(e.velocity,Math.exp(-1.6*t)),e.offset=k(e.offset,T(e.velocity,t)),e.angle+=e.spin*t,e.spin*=Math.exp(-1.25*t))}function pn(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function mn(e,t,n){let r=-1/0,i=1/0,a={x:0,y:0};for(let o of[`x`,`y`]){let s=n[o],c=s+(o===`x`?n.width:n.height),l=e[o],u=t[o],d=l+(o===`x`?e.width:e.height),f=u+(o===`x`?t.width:t.height);for(let[e,t,n]of[[d-s,f-d,-1],[c-l,l-u,1]]){if(Math.abs(t)<1e-8){if(e<0)return null;continue}let s=-e/t;t>0&&s>r?(r=s,a=o===`x`?{x:n,y:0}:{x:0,y:n}):t<0&&(i=Math.min(i,s))}if(r>i)return null}return r>=0&&r<=1&&r<=i&&i>=0&&(a.x!==0||a.y!==0)?{time:r,normal:a}:null}function hn(e,t){let n=Y(e);if(!pn(n,t))return null;let r=[{amount:t.x-n.x-n.width-.1,normal:{x:-1,y:0}},{amount:t.x+t.width-n.x+.1,normal:{x:1,y:0}},{amount:t.y-n.y-n.height-.1,normal:{x:0,y:-1}},{amount:t.y+t.height-n.y+.1,normal:{x:0,y:1}}].reduce((e,t)=>Math.abs(t.amount)<Math.abs(e.amount)?t:e);return r.normal.x?e.offset.x+=r.amount:e.offset.y+=r.amount,r.normal}function gn(e,t){let n=e.velocity.x*t.x+e.velocity.y*t.y;n>=0||(e.velocity=k(T(e.velocity,.82),T(t,-n*1.1)),e.spin*=-.45)}function _n(e,t,n){if(e.detached)for(let t of n){if(pn(e.ink,t))continue;let n=hn(e,t);n&&gn(e,n)}if(!e.detached||n.length===0){fn(e,t);return}let r=Y(e);fn(e,t);let i=Y(e),a=null;for(let t of n){if(pn(e.ink,t))continue;let n=mn(r,i,t);n&&(!a||n.time<a.time)&&(a={...n,wall:t})}if(a){let t=1-a.time;e.offset.x-=(i.x+i.width/2-r.x-r.width/2)*t,e.offset.y-=(i.y+i.height/2-r.y-r.height/2)*t,hn(e,a.wall),gn(e,a.normal)}for(let t=0;t<3;t++){let t=!1;for(let r of n){if(pn(e.ink,r))continue;let n=hn(e,r);n&&(gn(e,n),t=!0)}if(!t)break}}var vn=new WeakMap;function yn(e){let t=vn.get(e);if(t)return t;let{width:n,height:r,x:i,y:a}=e.source,o=e=>{let t=Math.sin(i*17.13+a*31.71+e*47.29)*43758.5453;return t-Math.floor(t)},s=new Path2D;return s.moveTo(n*(.04+o(1)*.18),r*(.02+o(2)*.08)),s.lineTo(n*(.43+o(3)*.15),r*o(4)*.08),s.lineTo(n*(.82+o(5)*.16),r*(.02+o(6)*.12)),s.lineTo(n*(.9+o(7)*.1),r*(.42+o(8)*.19)),s.lineTo(n*(.78+o(9)*.2),r*(.88+o(10)*.12)),s.lineTo(n*(.36+o(11)*.24),r*(.9+o(12)*.1)),s.lineTo(n*o(13)*.2,r*(.76+o(14)*.2)),s.lineTo(n*o(15)*.1,r*(.29+o(16)*.25)),s.closePath(),vn.set(e,s),s}function bn(e,t){if(t.burnFinished)return;let n=t.ink;if(n.width<=0||n.height<=0)return;let r=t.fragments;if(t.bitmap&&r&&r.length&&Math.abs(t.bitmap.width/2-n.width)<2&&Math.abs(t.bitmap.height/2-n.height)<2&&t.bitmapColor===e.color&&t.bitmapFont===e.font){let e=n.x-(t.fragmentOrigin?.x??n.x),i=n.y-(t.fragmentOrigin?.y??n.y);for(let t of r)t.base.x+=e,t.base.y+=i,t.ink.x+=e,t.ink.y+=i;t.fragmentOrigin=E(n.x,n.y);return}let i=document.createElement(`canvas`);i.width=Math.max(1,Math.ceil(n.width*2)),i.height=Math.max(1,Math.ceil(n.height*2));let a=i.getContext(`2d`,{willReadFrequently:!0});if(!a)return;if(a.save(),a.scale(2,2),e.graphic&&`viewBox`in e.graphic){let t=e.graphic.viewBox.baseVal;if(t.width>0&&t.height>0){let r=ln(t,n.width,n.height,e.graphic.preserveAspectRatio?.baseVal);a.translate(r.x,r.y),a.scale(r.scaleX,r.scaleY);for(let t of e.graphic.querySelectorAll(`path[d]`)){let n=getComputedStyle(t);a.fillStyle=n.fill===`currentcolor`?e.color:n.fill,a.fill(new Path2D(t.getAttribute(`d`)),n.fillRule===`evenodd`?`evenodd`:`nonzero`)}}}else e.graphic?a.drawImage(e.graphic,0,0,n.width,n.height):(a.font=e.font,a.fillStyle=e.color,a.textBaseline=`alphabetic`,a.fillText(t.character,t.base.x-n.x,t.base.y+t.base.height/2+e.baseline-n.y));a.restore();let o=null;try{o=a.getImageData(0,0,i.width,i.height).data}catch(t){if(!e.graphic||`viewBox`in e.graphic)throw t}let s=Math.max(7,Math.min(15,Math.round(n.height*.18)||10)),c=[],l=new Map(r?.map(e=>[`${e.source.x}:${e.source.y}`,e]));for(let e=0;e<n.height;e+=s)for(let t=0;t<n.width;t+=s){let r=Math.min(s,n.width-t),a=Math.min(s,n.height-e),u=!1;for(let n=Math.floor(e*2);n<Math.min(i.height,(e+a)*2)&&!u;n++)for(let e=Math.floor(t*2);e<Math.min(i.width,(t+r)*2);e++)if(!o||o[(n*i.width+e)*4+3]>0){u=!0;break}if(!u)continue;let d={x:n.x+t,y:n.y+e,width:r,height:a},f=l.get(`${t}:${e}`),p=Math.max(1,Math.ceil(r*2)),m=Math.max(1,Math.ceil(a*2)),h=new Uint8Array(p*m);for(let n=0;n<m;n++)for(let r=0;r<p;r++){let a=Math.floor(t*2)+r,s=Math.floor(e*2)+n;a<i.width&&s<i.height&&(h[n*p+r]=o?o[(s*i.width+a)*4+3]:255)}c.push({base:d,ink:{...d},source:{x:t,y:e,width:r,height:a},fireAlpha:h,destroyed:f?.destroyed,burnAmount:f?.burnAmount,burnFinished:f?.burnFinished,damage:f?.damage,bitmap:f?.bitmap,offset:f?.offset??E(),velocity:f?.velocity??E(),angle:f?.angle??0,spin:f?.spin??0,detached:f?.detached??!1,impactCooldown:f?.impactCooldown??0})}t.bitmap=i;let u=document.createElement(`canvas`);u.width=i.width,u.height=i.height,u.getContext(`2d`)?.drawImage(i,0,0);let d=u.getContext(`2d`);for(let e of c)if(e.detached){let t=e.source,n=Math.floor(t.x*2),r=Math.floor(t.y*2);d?.clearRect(n,r,Math.ceil((t.x+t.width)*2)-n,Math.ceil((t.y+t.height)*2)-r)}t.intactBitmap=u,t.fireMaskDirty=!0,t.fragments=c,t.fragmentOrigin=E(n.x,n.y),t.bitmapColor=e.color,t.bitmapFont=e.font}function xn(e,t,n,r,i){if(!t.detached){let n=t.source,r=Math.floor(n.x*2),i=Math.floor(n.y*2);if(e.bitmap){let a=document.createElement(`canvas`);a.width=Math.max(1,Math.ceil(n.width*2)),a.height=Math.max(1,Math.ceil(n.height*2));let o=a.getContext(`2d`);o?.drawImage(e.bitmap,r,i,a.width,a.height,0,0,a.width,a.height),o&&(o.save(),o.globalCompositeOperation=`destination-in`,o.scale(2,2),o.fill(yn(t)),o.restore()),t.bitmap=a}e.intactBitmap?.getContext(`2d`)?.clearRect(r,i,Math.ceil((n.x+n.width)*2)-r,Math.ceil((n.y+n.height)*2)-i),e.fireMaskDirty=!0}dn(t,n,r,i)}function Sn(e,t,n,r){let i=E(t.base.x+t.base.width/2+(t.detached?t.offset.x:0),t.base.y+t.base.height/2+(t.detached?t.offset.y:0)),a=n.x-i.x,o=n.y-i.y,s=Math.cos(t.detached?t.angle:0),c=Math.sin(t.detached?t.angle:0),l=t.source.x+t.source.width/2+a*s+o*c,u=t.source.y+t.source.height/2-a*c+o*s;if(t.fireAlpha){let e=Math.max(1,Math.ceil(t.source.width*2)),n=Math.max(1,Math.ceil(t.source.height*2)),i=1/0,a=0,o=0;for(let r=0;r<n;r+=2)for(let n=0;n<e;n+=2){if(t.fireAlpha[r*e+n]<64)continue;let s=(t.source.x+n/2-l)**2+(t.source.y+r/2-u)**2;s<i&&(i=s,a=n,o=r)}Number.isFinite(i)&&(l=t.source.x+a/2,u=t.source.y+o/2);for(let i=0;i<n;i++)for(let n=0;n<e;n++)(t.source.x+n/2-l)**2+(t.source.y+i/2-u)**2<=r*r&&(t.fireAlpha[i*e+n]=0);t.fireRevision=(t.fireRevision??0)+1}let d=t.detached&&t.bitmap?[t.bitmap]:[e.bitmap,e.intactBitmap];for(let e of d){let n=e?.getContext(`2d`);if(!n)continue;let i=t.detached&&t.bitmap?l-t.source.x:l,a=t.detached&&t.bitmap?u-t.source.y:u;n.save(),n.setTransform?.(1,0,0,1,0,0),n.globalCompositeOperation=`destination-out`,n.beginPath(),n.arc(i*2,a*2,Math.max(1.5,r*2),0,Math.PI*2),n.fill(),n.restore()}return t.detached?t.bitmap&&!t.fireAlpha&&(t.fireRevision=(t.fireRevision??0)+1):e.fireMaskDirty=!0,t.damage=(t.damage??0)+.27+r*.028,!t.fireAlpha&&t.damage>=1||t.fireAlpha?.every(e=>e<32)?(t.destroyed=!0,t.fireAlpha=void 0,t.bitmap=void 0,!0):!1}function Cn(e,t,n){let r=[],i=t.x*.07+t.y*.11,a=e=>n*(.84+.1*Math.sin(e*7+i)+.06*Math.sin(e*17-i*1.7));for(let n of[e.bitmap,e.intactBitmap]){let r=n?.getContext(`2d`);if(r){r.save(),r.setTransform?.(1,0,0,1,0,0),r.globalCompositeOperation=`destination-out`,r.beginPath();for(let n=0;n<64;n++){let i=n*Math.PI*2/64,o=a(i),s=(t.x+Math.cos(i)*o-e.ink.x)*2,c=(t.y+Math.sin(i)*o-e.ink.y)*2;n===0?r.moveTo(s,c):r.lineTo(s,c)}r.closePath(),r.fill(),r.restore()}}e.fireMaskDirty=!0;let o=n*n,s=(n*.68)**2;for(let n of e.fragments??[]){if(n.detached||n.destroyed||!n.fireAlpha)continue;let{base:e}=n,i=Math.max(e.x-t.x,0,t.x-e.x-e.width),c=Math.max(e.y-t.y,0,t.y-e.y-e.height);if(i*i+c*c>=o)continue;let l=Math.max(1,Math.ceil(n.source.width*2)),u=0;for(let r=0;r<n.fireAlpha.length;r++){if(n.fireAlpha[r]<32)continue;let i=e.x+r%l/2-t.x,c=e.y+Math.floor(r/l)/2-t.y,d=i*i+c*c;d<s||d<o&&Math.sqrt(d)<a(Math.atan2(c,i))?n.fireAlpha[r]=0:u++}n.fireRevision=(n.fireRevision??0)+1,u===0&&(n.destroyed=!0,n.fireAlpha=void 0,n.bitmap=void 0,r.push(n))}return r}function X(e){return e.fragments?.length?e.fragments:[e]}function wn(){let e=document.createElement(`span`);return e.dataset.jrTextRun=``,e.style.display=`contents`,e}function Tn(e,t){return{character:e,range:t,base:{x:0,y:0,width:0,height:0},ink:{x:0,y:0,width:0,height:0},offset:E(),velocity:E(),angle:0,spin:0,detached:!1,impactCooldown:0}}function En(e){e.graphic&&e.graphic.style.opacity===`0`&&(e.graphic.style.opacity=e.graphicOpacity??``),e.wrapper.isConnected&&e.wrapper.replaceWith(e.original);for(let t of e.glyphs)t.range.detach()}function Dn(e,t){let n=[],r=new Map,i=e.hud,a=e=>{for(let t=e;t;t=t.parentElement)if(i.has(t))return!0;return!1};for(let[t,n]of[[`pushable`,`pushable`],[`artwork`,`destructible`]])for(let i of e[t]){if(i.closest(`[data-jr-embed]`))continue;let e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT);for(;e.nextNode();){let t=e.currentNode,o=t.parentElement;o&&!a(o)&&t.data.trim()&&o.getClientRects().length&&!o.closest(`[data-jr-embed],[data-jr-text-run],script,style,textarea,select,[contenteditable="true"]`)&&r.set(t,{kind:n,root:i})}}let o=new Intl.Segmenter(void 0,{granularity:`grapheme`});for(let[e,{kind:i,root:a}]of r){if(!e.isConnected)continue;let r=e.parentElement;if(!r)continue;let s=getComputedStyle(r),c=s.font||`${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`,l=t.getContext(`2d`);l&&(l.font=c);let u=l?.measureText(`M`),d=((u?.actualBoundingBoxAscent??parseFloat(s.fontSize)*.8)-(u?.actualBoundingBoxDescent??parseFloat(s.fontSize)*.2))/2,f=wn();e.replaceWith(f),f.append(e);let p=[];for(let{segment:t,index:n}of o.segment(e.data)){if(/^\s+$/u.test(t))continue;let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length);let i=s.textTransform===`uppercase`?t.toLocaleUpperCase():s.textTransform===`lowercase`?t.toLocaleLowerCase():t;p.push(Tn(i,r))}n.push({wrapper:f,original:e,source:e.data,glyphs:p,font:c,color:s.color,baseline:d,letterSpacing:s.letterSpacing,canvasText:!1,kind:i,root:a})}return n}var On=new WeakMap;function kn(e,t=()=>{}){let n=[];if(typeof SVGSVGElement>`u`&&typeof HTMLImageElement>`u`)return n;for(let r of e){let e=[...typeof SVGSVGElement<`u`&&r instanceof SVGSVGElement?[r]:[],...typeof HTMLImageElement<`u`&&r instanceof HTMLImageElement?[r]:[],...r.querySelectorAll(`svg,img`)];for(let i of e){let e=typeof SVGSVGElement<`u`&&i instanceof SVGSVGElement,a=typeof HTMLImageElement<`u`&&i instanceof HTMLImageElement;if(a&&!i.complete){let e=On.get(i);e?e.onReady=t:(On.set(i,{onReady:t}),i.addEventListener(`load`,()=>{On.get(i)?.onReady(),On.delete(i)},{once:!0}))}if(i.closest(`[data-jr-text-run],[data-jr-embed]`)||e&&!i.querySelector(`path[d]`)||a&&(!i.complete||!i.naturalWidth))continue;let o=getComputedStyle(i),s=wn(),c=i.style.opacity;i.style.opacity=`0`,i.replaceWith(s),s.append(i);let l=document.createRange();l.selectNode(i),n.push({wrapper:s,original:i,graphic:i,graphicOpacity:c,source:``,kind:`destructible`,root:r,font:o.font,color:o.color,baseline:0,letterSpacing:`0px`,glyphs:[Tn(``,l)]})}}return n}var An=class{onInvalidate;projection;canvas=document.createElement(`canvas`);layouts=new WeakMap;geometryRevision=0;fontSource=document.fonts;fontMetrics=new Map;fontsChanged=()=>{this.fontMetrics.clear(),this.invalidate(),this.onInvalidate()};constructor(e,t=B){this.onInvalidate=e,this.projection=t,this.fontSource?.addEventListener(`loadingdone`,this.fontsChanged),this.fontSource?.addEventListener(`loadingerror`,this.fontsChanged)}rectInDocument(e,t){return this.projection.viewportRectToDocument(e.getBoundingClientRect(),t)}invalidate(){this.geometryRevision++}clear(){this.layouts=new WeakMap,this.fontMetrics.clear(),this.invalidate()}bounds(e){return this.layouts.get(e)?.rect}dispose(){this.fontSource?.removeEventListener(`loadingdone`,this.fontsChanged),this.fontSource?.removeEventListener(`loadingerror`,this.fontsChanged),this.clear()}measure(e,t,n,r){let i=this.canvas.getContext(`2d`),a=new Map,o=(e,t)=>{if(!e)return``;let n=a.get(e);if(n!==void 0)return n;let r=t??getComputedStyle(e),i=[o(e.parentElement),r.transform,r.rotate,r.scale,r.zoom].join(`|`);return a.set(e,i),i},s=(e,t)=>{let n=`${e}:${t}`,r=this.fontMetrics.get(n);return!r&&i&&(i.font=e,r=i.measureText(t),this.fontMetrics.size>=4096&&this.fontMetrics.clear(),this.fontMetrics.set(n,r)),r};for(let a of e){let e=a.wrapper.parentElement??a.wrapper,c=getComputedStyle(e),l=a.color;a.color=c.color||a.color;let u=c.font||a.font;a.font=u,a.letterSpacing=c.letterSpacing;let d=n(a.root);for(let e of a.glyphs){e.root=a.root,e.breakable=d?!!d.breakable:void 0;let t=e.burnable;if(e.burnable=d?!!d.burnable:void 0,e.burnable===!1&&t!==!1)for(let t of X(e))r(t)}let f=!a.graphic&&e.childNodes?.length===1&&e.firstChild===a.wrapper,p=!a.graphic&&!f?a.wrapper.getClientRects?.():void 0,m=e=>Math.round(e*64)/64,h=p?.length===0?`hidden`:``;if(p?.length)for(let e of p)h+=`${m(e.left-p[0].left)},${m(e.top-p[0].top)},${m(e.width)},${m(e.height)};`;let g=f?this.rectInDocument(e,t):h?this.rectInDocument(a.wrapper,t):void 0,_=g?[this.geometryRevision,u,c.letterSpacing,c.wordSpacing,c.lineHeight,c.textAlign,c.textIndent,c.textTransform,c.whiteSpace,c.writingMode,c.direction,c.fontFeatureSettings,c.transform,c.rotate,c.scale,o(e,c),document.fonts?.status,m(g.width),m(g.height),h].join(`|`):``,v=this.layouts.get(a);if(g&&v?.signature===_){let e=g.x-v.rect.x,t=g.y-v.rect.y;if(v.rect=g,e||t||l!==a.color)for(let n of a.glyphs)n.base.x+=e,n.base.y+=t,n.ink.x+=e,n.ink.y+=t,a.kind===`destructible`&&bn(a,n);continue}g?this.layouts.set(a,{rect:g,signature:_}):this.layouts.delete(a),F(`artwork glyph measures`,a.glyphs.length);let y=s(u,`M`);a.baseline=((y?.actualBoundingBoxAscent??parseFloat(c.fontSize)*.8)-(y?.actualBoundingBoxDescent??0))/2,i&&(i.font=a.font);for(let e of a.glyphs){if(a.graphic){e.base=this.rectInDocument(a.graphic,t),e.ink={...e.base},bn(a,e);continue}let n=e.range.getBoundingClientRect();e.base=this.projection.viewportRectToDocument(n,t);let r=s(a.font,e.character),i=e.base.y+e.base.height/2+a.baseline,o=(r?.actualBoundingBoxLeft??0)+(r?.actualBoundingBoxRight??e.base.width),c=(r?.actualBoundingBoxAscent??e.base.height)+(r?.actualBoundingBoxDescent??0);e.ink=o>0&&c>0?{x:e.base.x-(r?.actualBoundingBoxLeft??0),y:i-(r?.actualBoundingBoxAscent??e.base.height),width:o,height:c}:{...e.base},a.kind===`destructible`&&bn(a,e)}}}};function jn(e){let t=e.tagName.toLowerCase();if(t===`path`){let t=e.getAttribute(`d`);return t?new Path2D(t):null}let n=e.getBBox();if(!n.width||!n.height)return null;let r=new Path2D;if(t===`rect`){let t=e,i=Math.min(n.width/2,t.rx.baseVal.value||t.ry.baseVal.value),a=Math.min(n.height/2,t.ry.baseVal.value||t.rx.baseVal.value);i&&a?r.roundRect(n.x,n.y,n.width,n.height,[{x:i,y:a}]):r.rect(n.x,n.y,n.width,n.height)}else if(t===`circle`||t===`ellipse`)r.ellipse(n.x+n.width/2,n.y+n.height/2,n.width/2,n.height/2,0,0,Math.PI*2);else if(t===`polygon`||t===`polyline`){let t=e.points;if(!t.numberOfItems)return null;let n=t.getItem(0);r.moveTo(n.x,n.y);for(let e=1;e<t.numberOfItems;e++){let n=t.getItem(e);r.lineTo(n.x,n.y)}r.closePath()}else return null;return r}function Mn(e,t,n){if(typeof Path2D>`u`||typeof document>`u`)return null;let r=document.createElement(`canvas`);r.width=n.width,r.height=n.height;let i=r.getContext(`2d`,{willReadFrequently:!0}),a=jn(e),o=e.getScreenCTM();if(!i||!a||!o)return null;i.setTransform(...n.transform);for(let e of t){let t=e.path();if(!t)return null;i.clip(t.outline,t.rule)}let s=new Path2D;s.addPath(a,Pn(o)),i.fill(s,getComputedStyle(e).fillRule);let c=i.getImageData(0,0,n.width,n.height).data,l=new Uint8Array(n.width*n.height);for(let e=0;e<l.length;e++)l[e]=c[e*4+3];return l}var Nn=(e,t)=>({x:e.a*t.x+e.c*t.y+e.e,y:e.b*t.x+e.d*t.y+e.f}),Pn=e=>new DOMMatrix([e.a,e.b,e.c,e.d,e.e,e.f]),Fn=e=>/^url\(\s*["']?#([^"')]+)["']?\s*\)$/.exec(e.trim())?.[1];function In(e,t){let n=Fn(t),r=e.ownerSVGElement,i=n&&[...r?.querySelectorAll(`clipPath`)??[]].find(e=>e.id===n);if(!i)return null;let a=i.getAttribute(`clipPathUnits`)??`userSpaceOnUse`;if(a!==`userSpaceOnUse`&&a!==`objectBoundingBox`)return null;let o=e.getScreenCTM?.();if(!o)return null;let s=o.inverse(),c=a===`objectBoundingBox`?e.getBBox?.():null;if(a===`objectBoundingBox`&&(!c||!c.width||!c.height))return null;let l=[];for(let e of i.querySelectorAll(`*`)){let t=e.tagName.toLowerCase();if(t===`g`)continue;if(![`path`,`rect`,`circle`,`ellipse`,`polygon`,`polyline`].includes(t)||typeof e.isPointInFill!=`function`||typeof e.getScreenCTM!=`function`)return null;let n=getComputedStyle(e);if(n.clipPath!==`none`&&n.clipPath||n.maskImage!==`none`&&n.maskImage)return null;if(n.display===`none`||n.visibility===`hidden`)continue;let r=e.getScreenCTM();if(!r)return null;l.push({element:e,fromOwner:r.inverse().multiply(o),rule:n.clipRule||`nonzero`})}return l.length?{signature:JSON.stringify([i.outerHTML,l.map(({fromOwner:e,rule:t})=>[t,...[e.a,e.b,e.c,e.d,e.e,e.f].map(e=>Math.round(e*1e3)/1e3)])]),path(){let e=l[0].rule;if(l.some(t=>t.rule!==e))return null;let t=new Path2D,n=a===`objectBoundingBox`&&c?new DOMMatrix([c.width,0,0,c.height,c.x,c.y]):new DOMMatrix;for(let e of l){let r=jn(e.element);if(!r)return null;t.addPath(r,Pn(o).multiply(n).multiply(Pn(e.fromOwner).inverse()))}return{outline:t,rule:e}},contains(e){let t=Nn(s,e),n=a===`objectBoundingBox`&&c?{x:(t.x-c.x)/c.width,y:(t.y-c.y)/c.height}:t;return l.some(({element:e,fromOwner:t})=>e.isPointInFill(Nn(t,n)))}}:null}function Ln(e){let t=[];for(let n=e;n;n=n.parentElement){let r=getComputedStyle(n);if(r.maskImage&&r.maskImage!==`none`)return null;let i=r.clipPath;if(i&&i!==`none`){let e=In(n,i);if(!e)return null;t.push(e)}if(n===e.ownerSVGElement)break}return{signature:t.map(e=>e.signature).join(`|`),path:()=>null,contains:e=>t.every(t=>t.contains(e)),rasterize:(e,n)=>Mn(e,t,n)}}var Rn=`joy-ride-auto-paint`,zn=32,Bn=1600,Vn=`[data-jr-embed],[data-jr-ui],[data-jr-overlay],[data-jr-liquid],[data-jr-text-run],[data-jr-auto-paint="false"]`,Hn=new Set([`SCRIPT`,`STYLE`,`LINK`,`META`,`TEMPLATE`,`NOSCRIPT`,`CANVAS`,`IFRAME`,`IMG`,`VIDEO`]);function Un(e,t){let n=document.createElement(`span`).style;return n.cssText=e,t&&(n.removeProperty(`z-index`),n.getPropertyValue(`position`)===`relative`&&n.getPropertyPriority(`position`)===`important`&&n.removeProperty(`position`)),n.cssText}function Wn(e){let t=ue(e);return!t||t.alpha<.65?!1:t.chroma>=.05&&t.lightness>=.2&&t.lightness<=.98}function Gn(e,t,n,r){return e>=8&&t>=8&&e<=Math.min(960,n*.95)&&t<=Math.min(420,r*.65)&&e*t<=Math.min(16e4,n*r*.22)}var Kn=class{onChange;wetColor;root;owned=new Set;verified=new WeakMap;roots=new Set;task=null;timer=null;disposed=!1;geometryRevision=0;observer;resize;constructor(e,t=()=>void 0,n=document){this.onChange=e,this.wetColor=t,this.root=n,this.observer=new MutationObserver(e=>{this.releaseOutsideScope();for(let t of e){let e=t.target instanceof Element?t.target:t.target.parentElement;if(!e)continue;if(e.closest(`defs`)){let t=e.ownerSVGElement;t&&(this.affectsOwned(t)&&this.geometryRevision++,this.enqueue(t));continue}let n=e.closest(Vn);if(n)for(let e of this.owned)n.contains(e)&&this.enqueue(e);else{if(t.type===`attributes`&&t.attributeName===`class`){let n=e=>e.split(/\s+/).filter(e=>e&&e!==`joy-ride-auto-paint`).sort().join(` `);if(n(t.oldValue??``)===n(e.getAttribute(`class`)??``)&&(!this.owned.has(e)||e.classList.contains(`joy-ride-auto-paint`)))continue}t.attributeName===`style`&&this.wetColor(e)&&(e instanceof HTMLElement?e.style.backgroundColor===`transparent`:e instanceof SVGElement&&e.style.fill===`transparent`)||t.attributeName===`style`&&(t.oldValue?.includes(`--joy-ride-z-index`)||e.getAttribute(`style`)?.includes(`--joy-ride-z-index`))&&Un(t.oldValue??``,!0)===Un(e.getAttribute(`style`)??``,!0)||t.type===`childList`&&[...t.addedNodes,...t.removedNodes].every(e=>e instanceof Element&&(e.matches(Vn)||Hn.has(e.tagName)))||(this.affectsOwned(e)&&this.geometryRevision++,this.enqueue(e))}}}),this.resize=new ResizeObserver(e=>{for(let t of e)this.enqueue(t.target)}),this.observer.observe(this.root instanceof Element?this.root:this.root.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:[`class`,`style`,`hidden`,`data-jr-auto-paint`,`data-jr-liquid`,`fill`,`d`,`points`,`x`,`y`,`width`,`height`,`cx`,`cy`,`r`,`rx`,`ry`,`clip-path`,`mask`,`transform`]}),window.addEventListener(`resize`,this.refresh,{passive:!0}),this.root.addEventListener(`load`,this.refresh,!0),this.refresh()}get scopeElement(){return this.root instanceof Element?this.root:this.root.body??this.root.documentElement}contains(e){let t=this.scopeElement;return!!t&&(e===t||t.contains(e))}get elements(){return[...this.owned].filter(e=>e.isConnected&&this.contains(e))}has(e){return this.owned.has(e)}affectsOwned(e){for(let t of this.owned)if(e.contains(t))return!0;return!1}releaseOutsideScope(){let e=!1;for(let t of this.owned)t.isConnected&&this.contains(t)||(this.owned.delete(t),t.classList.remove(Rn),this.resize.unobserve(t),e=!0);e&&this.onChange()}refresh=()=>{let e=this.scopeElement;if(!this.disposed&&e){this.geometryRevision++,this.releaseOutsideScope(),this.roots.clear(),this.task=null;for(let e of this.owned)this.roots.add(e);this.roots.add(e),this.schedule()}};enqueue(e){let t=this.scopeElement;!this.disposed&&t&&this.contains(e)&&!this.roots.has(t)&&(e===t||this.roots.size>64?this.refresh():(this.roots.add(e),this.schedule()))}schedule(){this.timer===null&&(this.timer=window.setTimeout(this.scan,32))}scan=()=>{if(this.timer=null,this.disposed)return;let e=performance.now(),t=new Map,n=0;for(;n++<80&&performance.now()-e<3;){if(!this.task?.node){let e=this.roots.values().next().value;if(!e)break;this.roots.delete(e),this.task={root:e,node:e}}let e=this.task.node,n=!1;if(e.isConnected&&this.contains(e)&&!Hn.has(e.tagName)&&!e.closest(Vn)&&!e.closest(`defs`)){let r=e instanceof HTMLElement,i=typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement,a=e.getBoundingClientRect();n=!0;let o=!1;if((r||i)&&e!==document.body&&e.tagName!==`MAIN`&&Gn(a.width,a.height,innerWidth,innerHeight)&&(!i||a.width>=zn&&a.height>=zn&&a.width*a.height>=Bn)){let t=this.verified.get(e);if(this.owned.has(e)&&t?.revision===this.geometryRevision&&t.width===a.width&&t.height===a.height)o=!0;else{let t=getComputedStyle(e),n=i?t.fill:t.backgroundColor,r=n===`rgba(0, 0, 0, 0)`||n===`transparent`?this.wetColor(e)??n:n;o=t.display!==`none`&&t.visibility===`visible`&&Number(t.opacity)>=.65&&(i||t.backgroundImage===`none`)&&Wn(r)&&(!i||Ln(e)!==null)}o&&this.verified.set(e,{revision:this.geometryRevision,width:a.width,height:a.height})}(this.owned.has(e)||o)&&t.set(e,o)}else this.owned.has(e)&&t.set(e,!1);if(n&&e.firstElementChild)this.task.node=e.firstElementChild;else{let t=e;for(;t&&t!==this.task.root&&!t.nextElementSibling;)t=t.parentElement;this.task.node=t&&t!==this.task.root?t.nextElementSibling:null}}let r=!1;for(let[e,n]of t)n&&!e.classList.contains(`joy-ride-auto-paint`)&&(this.owned.has(e)||this.owned.size<256)?(e.classList.add(Rn),this.owned.add(e),this.resize.observe(e),r=!0):!n&&this.owned.delete(e)&&(this.verified.delete(e),e.classList.remove(Rn),this.resize.unobserve(e),r=!0);r&&this.onChange(),(this.task?.node||this.roots.size)&&this.schedule()};dispose(){this.disposed=!0,this.timer!==null&&window.clearTimeout(this.timer),this.observer.disconnect(),this.resize.disconnect(),window.removeEventListener(`resize`,this.refresh),this.root.removeEventListener(`load`,this.refresh,!0);for(let e of this.owned)e.classList.remove(Rn);this.owned.clear(),this.roots.clear(),this.task=null,this.onChange()}};function qn(e,t,n,r,i){if(C(e.health,e.maxHealth)===`intact`)return;let a=e.rect,o=E(a.x+a.width/2,a.y+a.height/2),s=r??Math.max(D.blastRadiusPx,Math.max(a.width,a.height)*.65+35);if(e.explodedAt!==null&&!e.blastQueued&&(e.blastQueued=!0,n.emitCombustibleExplosion(o,s),i(o)),e.explodedAt!==null){e.blastAge+=t,e.blastAge<D.fireballSeconds&&n.emitSceneFire({key:e,alpha:e.alpha,pixelWidth:e.pixelWidth,pixelHeight:e.pixelHeight,x:a.x,y:a.y,width:a.width,height:a.height,origin:o,farthest:Math.max(1,Math.hypot(a.width,a.height)),...ee(e.blastAge)},t),e.blastAge<.36&&e.blastAge-e.lastBlastEmission>=1/30&&(n.emitCombustibleBlast(o,s,e.blastAge),e.lastBlastEmission=e.blastAge);return}let c=I(e.health,e.maxHealth,a.width,a.height);c&&n.emitSceneFire({key:e,alpha:e.alpha,pixelWidth:e.pixelWidth,pixelHeight:e.pixelHeight,x:a.x,y:a.y,width:a.width,height:a.height,origin:e.origin,farthest:Math.max(1,Math.hypot(a.width,a.height)),...c},t)}var Jn=new Set([`H1`,`H2`,`H3`,`H4`,`H5`,`H6`,`P`,`SPAN`,`STRONG`,`EM`,`A`]);function Yn(e,t,n){let r=Math.max(1,Math.min(1024,Math.ceil(t*2))),i=Math.max(1,Math.min(1024,Math.ceil(n*2))),a=()=>({alpha:new Uint8Array(r*i).fill(255),pixelWidth:r,pixelHeight:i});if(typeof getComputedStyle!=`function`||!Jn.has(e.tagName)||!e.textContent?.trim())return a();let o=getComputedStyle(e).backgroundColor;if(o&&o!==`transparent`&&o!==`rgba(0, 0, 0, 0)`&&o!==`rgb(0 0 0 / 0)`)return a();let s=e.ownerDocument.createElement(`canvas`);s.width=r,s.height=i;let c=s.getContext(`2d`);if(!c)return a();let l=e.getBoundingClientRect(),u=r/Math.max(1,t),d=i/Math.max(1,n);c.textBaseline=`alphabetic`;let f=t=>{if(t.nodeType===Node.TEXT_NODE&&t.textContent){let n=t.parentElement??e,r=getComputedStyle(n),i=parseFloat(r.fontSize)||16,a=parseFloat(r.lineHeight)||i*1.2;c.font=r.font||`${r.fontWeight} ${i}px ${r.fontFamily}`;for(let n=0;n<t.textContent.length;n++){let o=t.textContent[n];if(!o.trim())continue;let s=e.ownerDocument.createRange();s.setStart(t,n),s.setEnd(t,n+1);let f=s.getBoundingClientRect();if(f.width<=0||f.height<=0)continue;let p=i*.22+Math.max(0,a-i)*.5;c.save(),c.scale(u,d),c.fillText(r.textTransform===`uppercase`?o.toUpperCase():o,f.left-l.left,f.bottom-l.top-p),c.restore()}}else for(let e of t.childNodes)f(e)};f(e);let p=c.getImageData(0,0,r,i).data,m=new Uint8Array(r*i),h=0;for(let e=0;e<m.length;e++)m[e]=p[e*4+3],m[e]>32&&h++;return h?{alpha:m,pixelWidth:r,pixelHeight:i}:a()}var Xn=2,Zn=4e6,Qn=24e6,$n=3,er=24,tr=180,nr=e=>!e.detached&&e.base.width>0&&e.base.height>0&&e.offset.x===0&&e.offset.y===0&&e.angle===0,rr=e=>{let t=Math.min(e.ink.x,e.base.x)-Xn,n=Math.min(e.ink.y,e.base.y)-Xn;return{x:t,y:n,width:Math.max(e.ink.x+e.ink.width,e.base.x+e.base.width)+Xn-t,height:Math.max(e.ink.y+e.ink.height,e.base.y+e.base.height)+Xn-n}},ir=(e,t)=>e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y;function ar(e){let t=e.glyphs[0]?.base??{x:0,y:0},n=e.glyphs.length;for(let r of e.glyphs)n=Math.imul(n^Math.round((r.base.x-t.x)*64),2654435761),n=Math.imul(n^Math.round((r.base.y-t.y)*64),2246822519),n=Math.imul(n^Math.round(r.ink.width*64),3266489917);return n}var or=class{layers=new Map;frame=0;builds=0;pixels=0;ratio=1;beginFrame(e){this.frame++,this.builds=0;let t=e.getTransform?.();this.ratio=t?Math.max(.5,Math.min(3,Math.round(Math.hypot(t.a,t.b)*4)/4)):1}draw(e,t,n,r){let i=`${t.font}|${n}|${t.letterSpacing}|${t.baseline}`,a=ar(t),o=this.layers.get(t),s=!o||o.style!==i||o.layout!==a||o.painted.length!==t.glyphs.length;if(s||o.ratio!==this.ratio){if(this.builds<$n){let e=this.build(t,n,i,a,o);if(e)o=e;else if(s)return!1}else if(s)return!1}else this.repair(o,t,n);o.used=this.frame;let c=this.moved(o,t);return e.drawImage(o.canvas,o.x+c.x-r.x,o.y+c.y-r.y,o.width,o.height),!0}endFrame(){for(let[e,t]of this.layers)this.frame-t.used>tr&&this.release(e,t)}clear(){for(let[e,t]of this.layers)this.release(e,t)}get bytes(){return this.pixels*4}moved(e,t){let n=t.glyphs[0]?.base??e.anchor;return{x:n.x-e.anchor.x,y:n.y-e.anchor.y}}release(e,t){this.pixels-=t.canvas.width*t.canvas.height,t.canvas.width=t.canvas.height=0,this.layers.delete(e)}build(e,t,n,r,i){let a=1/0,o=1/0,s=-1/0,c=-1/0;for(let t of e.glyphs){if(t.base.width<=0||t.base.height<=0)continue;let e=rr(t);a=Math.min(a,e.x),o=Math.min(o,e.y),s=Math.max(s,e.x+e.width),c=Math.max(c,e.y+e.height)}if(!(s>a&&c>o))return null;let l=this.ratio,u=Math.floor(a*l)/l,d=Math.floor(o*l)/l,f=Math.ceil((s-u)*l),p=Math.ceil((c-d)*l),m=f*p;if(m>Zn)return null;let h=i?i.canvas.width*i.canvas.height:0;if(this.pixels-h+m>Qn&&!this.evict(m-h,e))return null;let g=i?.canvas??document.createElement(`canvas`),_=i?.context??g.getContext(`2d`);if(!_)return null;this.pixels+=m-h,g.width=f,g.height=p;let v={canvas:g,context:_,style:n,layout:r,anchor:{...e.glyphs[0]?.base??{x:0,y:0}},painted:new Uint8Array(e.glyphs.length),x:u,y:d,width:f/l,height:p/l,ratio:l,used:this.frame};_.setTransform(l,0,0,l,-u*l,-d*l),_.font=e.font,_.fillStyle=t,_.textAlign=`left`,_.textBaseline=`alphabetic`,`letterSpacing`in _&&(_.letterSpacing=e.letterSpacing);for(let t=0;t<e.glyphs.length;t++){let n=e.glyphs[t];nr(n)&&(this.paint(_,e,n),v.painted[t]=1)}return this.layers.set(e,v),this.builds++,F(`text layer builds`),v}repair(e,t,n){let r=0;for(let n=0;n<t.glyphs.length;n++)e.painted[n]!==+!!nr(t.glyphs[n])&&r++;if(!r)return;if(r>er&&this.builds<$n){this.build(t,n,e.style,e.layout,e);return}let i=e.context,a=this.moved(e,t);i.setTransform(e.ratio,0,0,e.ratio,-(e.x+a.x)*e.ratio,-(e.y+a.y)*e.ratio);for(let n=0;n<t.glyphs.length;n++){let r=t.glyphs[n],a=+!!nr(r);if(e.painted[n]===a)continue;let o=rr(r);i.save(),i.beginPath(),i.rect(o.x,o.y,o.width,o.height),i.clip(),i.clearRect(o.x,o.y,o.width,o.height),e.painted[n]=a;for(let n=0;n<t.glyphs.length;n++){let r=t.glyphs[n];e.painted[n]&&ir(o,rr(r))&&this.paint(i,t,r)}i.restore()}F(`text layer repairs`,r)}paint(e,t,n){e.fillText(n.character,n.base.x,n.base.y+n.base.height/2+t.baseline)}evict(e,t){let n=[...this.layers].filter(([e,n])=>e!==t&&n.used<this.frame).sort((e,t)=>e[1].used-t[1].used);for(let[t,r]of n){if(this.pixels+e<=Qn)break;this.release(t,r)}return this.pixels+e<=Qn}},Z=32,Q=64,sr=8,cr=64,lr=192,ur=60,dr=class{colors;canvas=null;context=null;slots=new Map;free=[];rows=0;next=0;frame=0;updates=0;nextPhase=0;constructor(e){this.colors=e}beginFrame(){this.frame++,this.updates=0}prepare(e,t,n){let r=e.bitmap;if(!r||r.width>30||r.height>30)return;let i=this.slots.get(e);if(!i){if(this.updates>=lr)return;let t=this.allocate();if(t===null)return;i={index:t,bitmap:r,revision:-1,tint:-2,phase:this.nextPhase,used:0},this.nextPhase=(this.nextPhase+.61803398875)%1,this.slots.set(e,i)}i.used=this.frame;let a=-1;if(t<1){let[e,r,o]=this.colors.rgb(n),s=Math.max(0,Math.min(1,Math.round(t*32+i.phase-.5)/32));a=Math.round(e*s)<<16|Math.round(r*s)<<8|Math.round(o*s)}let o=e.fireRevision??0;i.bitmap===r&&i.revision===o&&i.tint===a||this.updates>=lr&&i.tint!==-2||(this.paint(i,r,a),i.bitmap=r,i.revision=o,i.tint=a)}draw(e,t){let n=this.slots.get(t);if(!n||n.tint===-2||n.used!==this.frame||n.bitmap!==t.bitmap)return!1;let r=n.index%Q*Z+1,i=Math.floor(n.index/Q)*Z+1;return e.drawImage(this.canvas,r,i,n.bitmap.width,n.bitmap.height,0,0,t.source.width,t.source.height),!0}endFrame(){for(let[e,t]of this.slots)this.frame-t.used>ur&&(this.slots.delete(e),this.free.push(t.index))}clear(){this.slots.clear(),this.free=[],this.next=0,this.rows=0,this.canvas&&(this.canvas.width=this.canvas.height=0),this.canvas=this.context=null}get bytes(){return this.canvas?this.canvas.width*this.canvas.height*4:0}allocate(){let e=this.free.pop();return e===void 0?this.next>=this.rows*Q&&!this.grow()?null:this.next++:e}grow(){if(this.rows>=cr)return!1;let e=Math.min(cr,this.rows+Math.max(sr,this.rows)),t=document.createElement(`canvas`);t.width=2048,t.height=e*Z;let n=t.getContext(`2d`);return n?(this.canvas&&n.drawImage(this.canvas,0,0),this.canvas&&(this.canvas.width=this.canvas.height=0),this.canvas=t,this.context=n,this.rows=e,!0):!1}paint(e,t,n){let r=this.context,i=e.index%Q*Z,a=Math.floor(e.index/Q)*Z;r.save(),r.beginPath(),r.rect(i,a,Z,Z),r.clip(),r.clearRect(i,a,Z,Z),r.drawImage(t,i+1,a+1),n>=0&&(r.globalCompositeOperation=`source-in`,r.fillStyle=`rgb(${n>>16} ${n>>8&255} ${n&255})`,r.fillRect(i,a,Z,Z)),r.restore(),this.updates++,F(`fragment atlas updates`)}},fr=pe;function pr(e){let t=getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`||t.visibility===`collapse`)return null;let n=1;for(let r=e;r;r=r.parentElement){let i=Number.parseFloat((r===e?t:getComputedStyle(r)).opacity);n*=Number.isFinite(i)?i:1}let r=e.style?.getPropertyValue?.(`--splatter-background-color`)?.trim(),i=typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement,a=fr(r||(i?t.fill:t.backgroundColor));return!a||a.alpha<=0||n<=0||!i&&t.backgroundImage!==`none`?null:{color:a.color,opacity:a.alpha*n,distanceM:30,material:_(`paint`)}}function mr(e,t){let n=getComputedStyle(e);if(n.display===`none`||n.visibility===`hidden`||n.visibility===`collapse`)return null;let r=t.kind,i=h[r];if(!i)return null;let a=1;for(let t=e;t;t=t.parentElement){let r=Number.parseFloat((t===e?n:getComputedStyle(t)).opacity);a*=Number.isFinite(r)?r:1}let o=t.color&&t.color!==`auto`?t.color:null,s=typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement,c=o?pe(typeof o==`string`?o:`rgb(${o.join(` `)})`):s||n.backgroundImage===`none`?pe(s?n.fill:n.backgroundColor):null,l=c?.alpha?c:null,u=l?l.color.match(/\d+/g).slice(0,3).map(Number):o&&typeof o==`string`?v(o):i.color,d=Math.max(0,Math.min(1,(t.opacity??1)*a*(l?.alpha??1))),f=t.distanceM??i.treadDistanceM;return{kind:r,color:u,opacity:d,deformation:t.deformation??i.deformation,distanceM:f,paint:i.family===`paint`?{color:`rgb(${u.join(` `)})`,opacity:d,distanceM:f,material:_(r)}:null}}var hr=[`background-color`,`background-image`,`border-top-color`,`border-right-color`,`border-bottom-color`,`border-left-color`],gr=[`fill`],_r=e=>e===`background-image`?`none`:`transparent`,vr=new WeakMap;function yr(e){let t=vr.get(e);if(t){t.users++;return}let n=e.style,r={users:1,position:n.getPropertyValue(`position`),positionPriority:n.getPropertyPriority(`position`),zIndex:n.getPropertyValue(`z-index`),zIndexPriority:n.getPropertyPriority(`z-index`),positioned:getComputedStyle(e).position===`static`};vr.set(e,r),r.positioned&&n.setProperty(`position`,`relative`,`important`),n.setProperty(`z-index`,ke(`foreground`),`important`)}function br(e){let t=vr.get(e);if(!t||--t.users)return;vr.delete(e);let n=e.style;n.getPropertyValue(`z-index`)===ke(`foreground`)&&(t.zIndex?n.setProperty(`z-index`,t.zIndex,t.zIndexPriority):n.removeProperty(`z-index`)),t.positioned&&n.getPropertyValue(`position`)===`relative`&&(t.position?n.setProperty(`position`,t.position,t.positionPriority):n.removeProperty(`position`))}var xr=class{element;authored=new Map;sourceCache=null;paintCache=null;position=null;zIndex=null;positioned=!1;svgHost=null;hiddenProperties;constructor(e){this.element=e;let t=typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement;this.hiddenProperties=t?gr:hr,t?(this.svgHost=e.ownerSVGElement,this.svgHost&&yr(this.svgHost)):(this.position={value:e.style.getPropertyValue(`position`),priority:e.style.getPropertyPriority(`position`)},this.zIndex={value:e.style.getPropertyValue(`z-index`),priority:e.style.getPropertyPriority(`z-index`)},this.positioned=getComputedStyle(e).position===`static`,this.positioned&&e.style.setProperty(`position`,`relative`,`important`),e.style.setProperty(`z-index`,ke(`foreground`),`important`));for(let t of this.hiddenProperties)this.authored.set(t,{value:e.style.getPropertyValue(t),priority:e.style.getPropertyPriority(t)});this.hide()}hide(){for(let e of this.hiddenProperties)this.element.style.setProperty(e,_r(e),`important`)}readSource(e){let t=`${this.styleSignature()}|${JSON.stringify(e)}`;if(this.sourceCache?.signature===t)return this.sourceCache.value;let n=this.withSource(()=>mr(this.element,e));return this.sourceCache={signature:`${this.styleSignature()}|${JSON.stringify(e)}`,value:n},n}readPaintSource(){let e=this.styleSignature();if(this.paintCache?.signature===e)return this.paintCache.value;let t=this.withSource(()=>pr(this.element));return this.paintCache={signature:this.styleSignature(),value:t},t}styleSignature(){let e=``;for(let t=this.element;t;t=t.parentElement)e+=`${t.getAttribute(`class`)}|${t.getAttribute(`style`)}|${t.getAttribute(`fill`)}|`;return e}withSource(e){for(let e of this.hiddenProperties){let t=this.authored.get(e),n=this.element.style.getPropertyValue(e);n!==_r(e)&&(t.value=n,t.priority=this.element.style.getPropertyPriority(e)),t.value?this.element.style.setProperty(e,t.value,t.priority):this.element.style.removeProperty(e)}try{return e()}finally{this.hide()}}dispose(){this.svgHost&&br(this.svgHost),typeof SVGGeometryElement<`u`&&this.element instanceof SVGGeometryElement||(this.element.style.getPropertyValue(`z-index`)===ke(`foreground`)&&(this.zIndex?.value?this.element.style.setProperty(`z-index`,this.zIndex.value,this.zIndex.priority):this.element.style.removeProperty(`z-index`)),this.positioned&&this.element.style.getPropertyValue(`position`)===`relative`&&(this.position?.value?this.element.style.setProperty(`position`,this.position.value,this.position.priority):this.element.style.removeProperty(`position`)));for(let e of this.hiddenProperties){let t=this.authored.get(e);this.element.style.getPropertyValue(e)===_r(e)&&(t.value?this.element.style.setProperty(e,t.value,t.priority):this.element.style.removeProperty(e))}}};function Sr(e,t){let{width:n,height:r,corners:i}=e;if(t.x<0||t.y<0||t.x>n||t.y>r)return!1;for(let e=0;e<4;e++){let a=i[e],o=e===1||e===2?n-t.x:t.x,s=e>=2?r-t.y:t.y;if(a.x>0&&a.y>0&&o<a.x&&s<a.y&&((o-a.x)/a.x)**2+((s-a.y)/a.y)**2>1)return!1}return!0}var Cr=new WeakMap,wr=new WeakMap,Tr=[`d`,`points`,`x`,`y`,`width`,`height`,`cx`,`cy`,`r`,`rx`,`ry`];function Er(e,t,n){let r=n.map(n=>{let[r=`0`,i=r]=n.split(/\s+/),a=(e,t)=>Math.max(0,(parseFloat(e)||0)*(e.endsWith(`%`)?t/100:1));return{x:a(r,e),y:a(i,t)}}),[i,a,o,s]=r,c=Math.min(1,e/Math.max(1,i.x+a.x),e/Math.max(1,s.x+o.x),t/Math.max(1,i.y+s.y),t/Math.max(1,a.y+o.y));return{width:e,height:t,corners:r.map(e=>({x:e.x*c,y:e.y*c}))}}function Dr(e,t,n=B,r){let i=n.viewportRectToDocument(e.getBoundingClientRect(),t);if(!i.width||!i.height)return null;let a=getComputedStyle(e),o=typeof HTMLElement<`u`&&e instanceof HTMLElement?e:null,s=o?.offsetWidth||i.width,c=o?.offsetHeight||i.height,l=o&&typeof DOMMatrixReadOnly<`u`?K(o,r):null,u=l?n.viewportRectToDocument({left:l.center.x,top:l.center.y,width:0,height:0},t):null,d=n.scale,f={shape:Er(s,c,[a.borderTopLeftRadius||`0`,a.borderTopRightRadius||`0`,a.borderBottomRightRadius||`0`,a.borderBottomLeftRadius||`0`]),box:l&&u?{center:{x:u.x,y:u.y},halfX:{x:l.halfX.x/d,y:l.halfX.y/d},halfY:{x:l.halfY.x/d,y:l.halfY.y/d}}:{center:{x:i.x+i.width/2,y:i.y+i.height/2},halfX:{x:i.width/2,y:0},halfY:{x:0,y:i.height/2}}};if(typeof SVGGeometryElement<`u`&&e instanceof SVGGeometryElement){let t=Ln(e);if(!t)return null;let n=e.getBoundingClientRect(),r=e.getScreenCTM();if(!r||typeof e.isPointInFill!=`function`)return null;let a=r.inverse();f.visibleSignature=t.signature;let o=Math.max(1,Math.ceil(n.width*2)),l=Math.max(1,Math.ceil(n.height*2)),u=JSON.stringify([t.signature,Tr.map(t=>e.getAttribute(t)),getComputedStyle(e).fillRule,o,l,r.a,r.b,r.c,r.d]);f.rasterize=(r,a,o)=>{let s=JSON.stringify([u,r,o,i.width,i.height,Math.round((i.x-a.x)*16),Math.round((i.y-a.y)*16)]),c=wr.get(e);if(c?.signature===s)return c.footprint;let l=r*i.width/(o*n.width),d=r*i.height/(o*n.height),f=r*(.5+(i.x-a.x)/o),p=r*(.5+(i.y-a.y)/o),m=Math.max(0,Math.floor(f)),h=Math.max(0,Math.floor(p)),g=Math.min(r,Math.ceil(f+n.width*l)),_=Math.min(r,Math.ceil(p+n.height*d));if(g<=m||_<=h)return null;let v;try{v=t.rasterize(e,{width:g-m,height:_-h,transform:[l,0,0,d,f-n.left*l-m,p-n.top*d-h]})}catch{return null}if(!v)return null;let y=new Uint8Array(r*r),b=0;for(let e=h;e<_;e++){let t=v.subarray((e-h)*(g-m),(e-h+1)*(g-m));y.set(t,e*r+m);for(let e of t)b+=e/255}let x={mask:y,coverage:b/y.length};return wr.set(e,{signature:s,footprint:x}),F(`svg liquid mask builds`),x};let d;f.contains=r=>{let i=Or(f,r),p=n.left+i.x/s*n.width,m=n.top+i.y/c*n.height;if(d||(d=Cr.get(e),d?.signature!==u&&(d=void 0)),!d){let r=null;try{r=t.rasterize(e,{width:o,height:l,transform:[2,0,0,2,-n.left*2,-n.top*2]})}catch{}d={signature:u,width:o,height:l,alpha:r},Cr.set(e,d),F(`svg collision mask builds`)}if(d.alpha){let e=Math.floor((p-n.left)*2),t=Math.floor((m-n.top)*2);return e>=0&&e<d.width&&t>=0&&t<d.height&&d.alpha[t*d.width+e]>=128}return e.isPointInFill({x:a.a*p+a.c*m+a.e,y:a.b*p+a.d*m+a.f})&&t.contains({x:p,y:m})}}return f}function Or(e,t){let{center:n,halfX:r,halfY:i}=e.box,a=r.x*i.y-r.y*i.x;if(Math.abs(a)<1e-4)return{x:-1/0,y:-1/0};let o=t.x-n.x,s=t.y-n.y;return{x:((o*i.y-s*i.x)/a+1)*e.shape.width/2,y:((s*r.x-o*r.y)/a+1)*e.shape.height/2}}var kr=(e,t)=>e.contains?.(t)??Sr(e.shape,Or(e,t)),Ar=new WeakMap;function jr(e){let t=e.liquidSource,n=e.geometry;if(!t&&!e.source||!n)return null;let r=Ar.get(e),i=e.rect,a=window.devicePixelRatio;if(r?.geometry===n&&r.source===e.source&&r.liquidSource===t&&r.dpr===a&&r.bounds.x===i.x&&r.bounds.y===i.y&&r.bounds.width===i.width&&r.bounds.height===i.height)return r.seed;let o=e.source?.color.match(/[\d.]+/g)?.slice(0,3).map(Number),s=t?.kind??`paint`,c=t?.color??(o?.length===3?o:h.paint.color),l={opacity:t?h[s].alpha*t.opacity:e.source?.opacity??1,deformation:t?.deformation??h.paint.deformation,distanceM:t?.distanceM??e.source?.distanceM??30},u={key:e.element,kind:s,color:c,profile:l,bounds:i,signature:JSON.stringify([s,n.shape,n.box,n.visibleSignature,c,l,a,typeof SVGGeometryElement<`u`&&e.element instanceof SVGGeometryElement?[`d`,`points`,`x`,`y`,`width`,`height`,`cx`,`cy`,`r`,`rx`,`ry`].map(t=>e.element.getAttribute(t)):null]),contains:e=>kr(n,e),rasterize:n.rasterize};return Ar.set(e,{geometry:n,source:e.source,liquidSource:t,dpr:a,bounds:i,seed:u}),F(`liquid seed descriptors`),u}function Mr(e,t){return t.map(t=>{for(let n=e.liquidElements.length-1;n>=0;n--){let{element:r,source:i,geometry:a}=e.liquidElements[n];if(i&&a&&!e.liquidBackings.has(r)&&kr(a,t))return i}return null})}function Nr(e,t,n,r){let i=[];for(let t of e.liquidElements){let e=jr(t);e&&i.push(e)}let a=t.syncElementLiquids(i);for(let[t,n]of e.liquidBackings)a.has(t)||(n.dispose(),e.liquidBackings.delete(t));for(let t of i){if(!a.get(t.key))continue;let n=t.key,r=e.liquidBackings.get(n);r||(r=new xr(n),e.liquidBackings.set(n,r))}}var Pr=new WeakMap,Fr=[`transition`,`transition-property`,`transition-duration`,`transition-timing-function`,`transition-delay`,`transition-behavior`];function Ir(e){let t=Pr.get(e);if(!t){let n=Fr.map(t=>({key:t,value:e.style.getPropertyValue(t),priority:e.style.getPropertyPriority(t)}));e.style.setProperty(`transition`,`none`,`important`),t={count:0,restore(){for(let{key:t,value:r,priority:i}of n)r?e.style.setProperty(t,r,i):e.style.removeProperty(t)}},Pr.set(e,t)}t.count++;let n=!1;return()=>{n||(n=!0,--t.count===0&&(t.restore(),Pr.delete(e)))}}function Lr(e){return e.kind===`pushable`?e.glyphs.some(e=>e.detached||e.offset.x!==0||e.offset.y!==0||e.angle!==0):e.glyphs.some(e=>e.burnFinished||(e.burnAmount??0)>0||e.fireAge!==void 0||e.fragments?.some(e=>e.detached||e.destroyed||e.burnFinished||(e.burnAmount??0)>0||(e.damage??0)>0))}function Rr(e,t){e.canvasText!==t&&(e.canvasText=t,e.wrapper.style.color=t?`transparent`:``,e.wrapper.style.webkitTextFillColor=t?`transparent`:``)}var zr=new Map;function Br(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.max(4,Math.ceil(e.base.height*.4)),a=e.base.width+i*2,o=e.base.height+i*2,s=[e.character,t.font,n,t.letterSpacing,t.baseline,e.base.width,e.base.height,r].join(`|`),c=zr.get(s);if(!c){zr.size>=512&&zr.clear(),c=document.createElement(`canvas`),c.width=Math.max(1,Math.ceil(a*r)),c.height=Math.max(1,Math.ceil(o*r));let l=c.getContext(`2d`);l&&(l.scale(r,r),l.font=t.font,l.fillStyle=n,l.textAlign=`left`,l.textBaseline=`alphabetic`,`letterSpacing`in l&&(l.letterSpacing=t.letterSpacing),l.fillText(e.character,i,i+e.base.height/2+t.baseline)),zr.set(s,c),F(`pushable sprite builds`)}return{sprite:c,width:a,height:o,pad:i}}function Vr(e,t,n,r){let{runs:i,layout:a,burnSprites:o,textLayers:s,fragmentAtlas:c,fade:l}=r;e.save(),s.beginFrame(e);let u={x:t.x-20,y:t.y-20,width:n.width+40,height:n.height+40};c.beginFrame();for(let e of i)if(e.kind===`destructible`){for(let t of e.glyphs)if(!t.burnFinished&&t.bitmap)for(let n of t.fragments??[]){if(!n.detached||n.destroyed||n.burnFinished||!n.bitmap||!un(n,u))continue;let t=n.burnAmount??0;c.prepare(n,t?1-.97*Math.min(1,t/.7):1,e.color)}}let d=e.getTransform?.(),f=e.globalAlpha;e.textAlign=`left`,e.textBaseline=`alphabetic`;for(let r of i){if(!r.graphic){let e=Lr(r);if(Rr(r,e),!e)continue}let i=a(r);if(i&&(i.x+i.width<t.x-20||i.x>t.x+n.width+20||i.y+i.height<t.y-20||i.y>t.y+n.height+20)&&!r.glyphs.some(e=>e.detached||e.fragments?.some(e=>e.detached)))continue;let p=!1;if(r.kind===`pushable`){let n=getComputedStyle(r.wrapper.parentElement??r.wrapper).color||r.color;e.font=r.font,e.fillStyle=n,`letterSpacing`in e&&(e.letterSpacing=r.letterSpacing),p=s.draw(e,r,n,t)}for(let i of r.glyphs){if(r.kind===`destructible`){if(i.burnFinished||!i.bitmap)continue;if(((i.fragments??[]).some(e=>!e.detached&&!e.destroyed&&!e.burnFinished)||r.graphic&&i.fireAge!==void 0&&i.fireAge<(i.fireTotalSeconds??0))&&i.intactBitmap){let a=i.ink;if(a.x+a.width>=t.x-20&&a.x<=t.x+n.width+20&&a.y+a.height>=t.y-20&&a.y<=t.y+n.height+20){let n=i.burnAmount??0;e.save(),r.graphic||(e.globalAlpha*=W(n));let s=r.graphic&&i.fireAge!==void 0&&i.fireOrigin?o.getRadialBurn(i.intactBitmap,{originX:(i.fireOrigin.x-a.x)*i.intactBitmap.width/a.width,originY:(i.fireOrigin.y-a.y)*i.intactBitmap.height/a.height,farthest:Math.hypot(i.intactBitmap.width,i.intactBitmap.height),age:i.fireAge,spreadSeconds:i.fireSpreadSeconds??0,burnSeconds:i.fireBurnSeconds??m.burnSeconds},i.fireMaskRevision??0):n?o.get(i.intactBitmap,1-.97*Math.min(1,n/.7),r.color,i.fireMaskRevision??0,i.fireMaskDirty):i.intactBitmap;e.drawImage(s,a.x-t.x,a.y-t.y,a.width,a.height),e.restore()}}let a=!1;for(let n of i.fragments??[]){if(!n.detached||n.destroyed||n.burnFinished||!un(n,u))continue;let s=n.burnAmount??0,p=W(s),m=1-.97*Math.min(1,s/.7);if(n.bitmap&&d){let i=Math.cos(n.angle),u=Math.sin(n.angle),h=n.base.width/2,g=n.base.height/2,_=n.base.x+n.offset.x-t.x+h,v=n.base.y+n.offset.y-t.y+g,y=_-h*i+g*u,b=v-h*u-g*i;if(e.setTransform(d.a*i+d.c*u,d.b*i+d.d*u,d.c*i-d.a*u,d.d*i-d.b*u,d.a*y+d.c*b+d.e,d.b*y+d.d*b+d.f),e.globalAlpha=f*p*l,a=!0,c.draw(e,n))continue;let x=s?o.get(n.bitmap,m,r.color,n.fireRevision??0):n.bitmap;e.drawImage(x,0,0,n.source.width,n.source.height);continue}let h=i.bitmap,g=s&&h?o.get(h,m,r.color,i.fireMaskRevision??0,i.fireMaskDirty):h;a&&d&&(e.setTransform(d),e.globalAlpha=f,a=!1),e.save(),e.globalAlpha*=p*l,e.translate(n.base.x+n.offset.x-t.x+n.base.width/2,n.base.y+n.offset.y-t.y+n.base.height/2),e.rotate(n.angle),e.translate(-n.base.width/2,-n.base.height/2),e.clip(yn(n));let _=n.source;e.drawImage(g??i.bitmap,_.x*2,_.y*2,_.width*2,_.height*2,0,0,_.width,_.height),e.restore()}a&&d&&(e.setTransform(d),e.globalAlpha=f);continue}if(i.base.width<=0||i.base.height<=0)continue;let a=i.base.x+i.offset.x-t.x,s=i.base.y+i.offset.y-t.y;if(!(a+i.base.width<-40||a>n.width+40||s+i.base.height<-40||s>n.height+40)){if(i.detached){e.save(),e.globalAlpha*=l,e.translate(a+i.base.width/2,s+i.base.height/2),e.rotate(i.angle);let{sprite:t,width:n,height:o,pad:c}=Br(i,r,String(e.fillStyle));e.drawImage(t,-i.base.width/2-c,-i.base.height/2-c,n,o),e.restore()}else p&&nr(i)||e.fillText(i.character,a,s+i.base.height/2+r.baseline)}}}s.endFrame(),c.endFrame(),e.restore()}var $=(e,t)=>e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y;function Hr(e,t,n){e.save(),e.fillStyle=`#fff`;for(let r of n.crushables)r.element instanceof HTMLElement&&n.crushed.has(r.element)||e.fillRect(r.rect.x-t.x,r.rect.y-t.y,r.rect.width,r.rect.height);for(let r of n.combustibles)r.explodedAt===null&&e.fillRect(r.rect.x-t.x,r.rect.y-t.y,r.rect.width,r.rect.height);for(let r of n.runs)if(r.kind===`destructible`){for(let n of r.glyphs)if(!n.burnFinished){(n.fragments??[]).some(e=>!e.detached&&!e.destroyed&&!e.burnFinished)&&n.intactBitmap&&e.drawImage(n.intactBitmap,n.ink.x-t.x,n.ink.y-t.y,n.ink.width,n.ink.height);for(let r of n.fragments??[]){if(!r.detached||r.destroyed||r.burnFinished)continue;let n=Y(r);e.fillRect(n.x-t.x,n.y-t.y,n.width,n.height)}}}e.restore()}function Ur(e,t,n,r){if(typeof HTMLImageElement<`u`){let i=r.projection.scale;for(let a of r.crushed){if(!r.hasCrushedPaint(a))continue;let o=a instanceof HTMLImageElement?[a]:a.querySelectorAll(`img`);for(let s of o){if(!s.complete||!s.naturalWidth)continue;let o=K(s);if(!o)continue;let c=r.projection.viewportRectToDocument({left:o.center.x,top:o.center.y,width:0,height:0},r.offset),l=c.x-t.x,u=c.y-t.y;l<-200||u<-200||l>n.width+200||u>n.height+200||(e.save(),e.globalAlpha=Number(getComputedStyle(a).opacity||1),e.transform(o.halfX.x/i,o.halfX.y/i,o.halfY.x/i,o.halfY.y/i,l,u),e.drawImage(s,-1,-1,2,2),e.restore())}}}Vr(e,t,n,r)}function Wr(e,t,n,r,i,a,o=[]){t.save();let s=(e,n,r,i,a,o,s=!1)=>{if(a<=0||(t.globalAlpha=a,t.fillStyle=`rgba(22, 24, 27, 0.82)`,t.beginPath(),t.roundRect(e,n,r,5,2),t.fill(),t.fillStyle=`#f4f4f5`,s&&(t.globalAlpha=a*(.48+.52*(.5+.5*Math.sin(performance.now()*.012)))),t.beginPath(),t.roundRect(e+1,n+1,(r-2)*Math.max(0,Math.min(1,i)),3,1),t.fill(),!o))return;t.globalAlpha=a,t.font=`600 9px ui-monospace, monospace`,t.textAlign=`left`,t.textBaseline=`middle`;let c=t.measureText(o).width;t.fillStyle=`rgba(22, 24, 27, 0.82)`,t.beginPath(),t.roundRect(e+r+4,n-3,c+8,11,2),t.fill(),t.fillStyle=`#f4f4f5`,t.fillText(o,e+r+8,n+2.5)};for(let t of e.combustibles){if(t.explodedAt!==null||t.health<=0||!t.element.isConnected)continue;let e=t.healthBarAlpha();if(e<=0)continue;let{rect:i}=t,a=Math.min(72,Math.max(36,i.width*.8)),o=i.x+(i.width-a)/2-n.x,c=i.y+i.height+15-n.y;o+a<0||o>r.width||c+5<0||c>r.height||s(o,c,a,t.healthFraction,e,`${Math.ceil(t.health)} HP`)}for(let t of i?[i,...o]:o){let o=t.sim;if(o.mode!==`car`||!a||o.car.explodedAt!==null)continue;let c=e.hoveredVehicleId===t.id,l=k(a.documentPoint(o.body.position),a.carVisualOffset(o)),u=a.documentScale(),d=o.car.preset.geometry,f=(Math.abs(Math.sin(o.body.angle))*d.lengthM+Math.abs(Math.cos(o.body.angle))*d.widthM)*u/2,p=Math.min(72,Math.max(36,d.lengthM*u*.55)),m=l.x-p/2-n.x,h=l.y+f+15-n.y;if(m+p<0||m>r.width||h+5<0||h>r.height)continue;let g=t!==i||t.controlSource!==`player`?o.car.healthBarAlpha():e.showHealthBars?c?1:o.car.healthBarAlpha():0;g>0&&s(m,h,p,o.car.healthFraction,g,`${Math.ceil(o.car.health)} HP`)}t.restore()}function Gr(e,t,n,r){let i=r.sceneScroll(),a=r.viewportSize(),o={x:i.x,y:i.y,width:a.width,height:a.height};t.save(),t.lineWidth=1.5,t.strokeStyle=`rgba(0, 174, 204, 0.55)`,t.setLineDash([8,6]),t.strokeRect(3,3,a.width-6,a.height-6),t.setLineDash([]),t.strokeStyle=`#e69b19`;for(let n of e.walls)$(o,n.rect)&&t.strokeRect(n.rect.x-i.x,n.rect.y-i.y,n.rect.width,n.rect.height);t.strokeStyle=`#00b8a9`,t.fillStyle=`rgba(0,184,169,.12)`,t.font=`10px ui-monospace, monospace`;for(let n of e.liquidElements){if(!n.source||!$(o,n.rect))continue;let{x:r,y:a,width:s,height:c}=n.rect;t.fillRect(r-i.x,a-i.y,s,c),t.strokeRect(r-i.x,a-i.y,s,c),t.fillStyle=`#007f74`,t.fillText(e.autoPaintElements?.includes(n.element)?`AUTO PAINT`:`PAINT`,r-i.x+4,a-i.y+12),t.fillStyle=`rgba(0,184,169,.12)`}t.strokeStyle=`#f47734`;for(let n of e.combustibles)n.explodedAt===null&&$(o,n.rect)&&t.strokeRect(n.rect.x-i.x,n.rect.y-i.y,n.rect.width,n.rect.height);t.strokeStyle=`#bd4add`;for(let n of e.runs)for(let e of n.glyphs){if(e.burnFinished)continue;let r=n.kind===`destructible`?(e.fragments??[]).filter(e=>!e.destroyed&&!e.burnFinished).map(Y):[Y(e)];for(let e of r)$(o,e)&&t.strokeRect(e.x-i.x,e.y-i.y,e.width,e.height)}let s=e.mask,c=r.documentScale(),l=k(r.screen(n.body.position),r.carVisualOffset(n)),u=E(Math.cos(n.body.angle),-Math.sin(n.body.angle)),d=E(-u.y,u.x),f=s.lengthM*c/2,p=s.widthM*c/2,m=(e,t)=>k(l,k(T(u,e),T(d,t))),h=[m(-f,-p),m(f,-p),m(f,p),m(-f,p)];t.strokeStyle=`rgba(0, 174, 204, 0.25)`,t.setLineDash([5,4]),t.beginPath(),h.forEach((e,n)=>n?t.lineTo(e.x,e.y):t.moveTo(e.x,e.y)),t.closePath(),t.stroke(),t.setLineDash([]),t.strokeStyle=`#00d9e8`,t.lineWidth=1.35,t.beginPath();let{columns:g,rows:_,solid:v}=s.alpha,y=(e,n)=>{t.moveTo(e.x,e.y),t.lineTo(n.x,n.y)};for(let e=0;e<_;e++)for(let t=0;t<g;t++){let n=e*g+t;if(!v[n])continue;let r=(2*t/g-1)*f,i=(2*(t+1)/g-1)*f,a=(2*e/_-1)*p,o=(2*(e+1)/_-1)*p;e!==0&&v[n-g]||y(m(r,a),m(i,a)),t!==g-1&&v[n+1]||y(m(i,a),m(i,o)),e!==_-1&&v[n+g]||y(m(i,o),m(r,o)),t!==0&&v[n-1]||y(m(r,o),m(r,a))}t.stroke(),t.restore()}function Kr(e,t,n){if(!e.burning.size&&!e.runs.some(e=>e.graphic&&e.glyphs.some(e=>e.fireAge!==void 0&&e.fireAge<(e.fireTotalSeconds??0))))return;let r=n.sceneFireDue?.(t)??!0,i=new Map;for(let t of e.runs){let n=e.burnLifetime(t.root);if(n!==void 0)for(let e of t.glyphs)for(let t of X(e))i.set(t,n)}for(let[a,o]of[...e.burning]){let s=i.get(a)??e.destructibleBurnSeconds??o.profile.burnSeconds,c=s===1/0,l=c?m.burnSeconds:s;o.age=c?Math.min(o.age+t,l*.42):o.age+t;let u=Math.min(1,o.age/l);if(a.burnAmount=u,u<1&&a.detached&&r){let e=Y(a),r=E(e.x+e.width/2,e.y+e.height/2),i=Math.max(1,Math.ceil(a.source?.width*2||e.width*2)),s=Math.max(1,Math.ceil(a.source?.height*2||e.height*2)),c={key:a,alpha:a.fireAlpha??Uint8Array.of(255),pixelWidth:a.fireAlpha?i:1,pixelHeight:a.fireAlpha?s:1,x:a.base.x+(a.detached?a.offset.x:0),y:a.base.y+(a.detached?a.offset.y:0),width:a.base.width,height:a.base.height,angle:a.detached?a.angle:0,origin:r,age:o.age,farthest:Math.max(1,Math.hypot(e.width,e.height)/2),spreadSeconds:Math.min(.35,o.profile.spreadSeconds*.1),burnSeconds:l,smokeRate:o.profile.smokePerSecond,revision:a.fireRevision};n.emitSceneFire(c,t)}u>=1&&(a.burnFinished=!0,a.fireAlpha=void 0,a.bitmap=void 0,e.burning.delete(a),e.flameExposure.delete(a))}for(let r of e.runs)if(r.kind===`destructible`){for(let i of r.glyphs){let a=X(i),o=a.filter(e=>!e.detached&&!e.destroyed),s=o.find(t=>e.burning.has(t));if((s||r.graphic&&i.fireAge!==void 0)&&i.intactBitmap){let a=s?e.burning.get(s):void 0,c=e.burnLifetime(r.root)??e.destructibleBurnSeconds??a?.profile.burnSeconds??i.fireBurnSeconds??m.burnSeconds,l=c===1/0,u=l?m.burnSeconds:c,d=i.fireSpreadSeconds??(r.graphic?Math.min(.25,(a?.profile.spreadSeconds??m.spreadSeconds)*.1):Math.min(1.2,(a?.profile.spreadSeconds??m.spreadSeconds)*.55)),f=r.graphic?u*1.02+d:u+(a?.profile.spreadSeconds??0)*.7;if(i.fireAge===void 0&&(i.fireBurnSeconds=u,i.fireSpreadSeconds=d,i.fireSmokeRate=a?.profile.smokePerSecond,i.fireTotalSeconds=f),i.fireAge=l?Math.min((i.fireAge??0)+t,f*.42):(i.fireAge??0)+t,i.fireOrigin??=(()=>{let e=s?Y(s):i.ink;return E(e.x+e.width/2,e.y+e.height/2)})(),i.fireMaskBitmap!==i.intactBitmap||i.fireMaskDirty||!i.fireMaskAlpha){let e=i.intactBitmap,t;try{t=e.getContext(`2d`)?.getImageData(0,0,e.width,e.height).data}catch(e){if(!r.graphic||`viewBox`in r.graphic)throw e}if(t||r.graphic&&!(`viewBox`in r.graphic)){let n=new Uint8Array(e.width*e.height);for(let e=0;e<n.length;e++)n[e]=t?t[e*4+3]:255;i.fireMaskAlpha=n,i.fireMaskBitmap=e,i.fireMaskDirty=!1,i.fireMaskRevision=(i.fireMaskRevision??0)+1}}if(i.fireMaskAlpha&&i.fireAge<f&&n.emitSceneFire({key:i,alpha:i.fireMaskAlpha,pixelWidth:i.intactBitmap.width,pixelHeight:i.intactBitmap.height,x:i.ink.x,y:i.ink.y,width:i.ink.width,height:i.ink.height,origin:i.fireOrigin,age:i.fireAge,farthest:Math.max(1,Math.hypot(i.ink.width,i.ink.height)),spreadSeconds:d,burnSeconds:r.graphic?u:f,smokeRate:i.fireSmokeRate??m.smokePerSecond,revision:i.fireMaskRevision},t),r.graphic&&!l&&i.fireAge>=f)for(let t of o)t.burnFinished=!0,e.burning.delete(t),e.flameExposure.delete(t)}else if(i.intactBitmap)i.fireAge!==void 0&&(i.fireAge=void 0,i.fireOrigin=void 0,i.fireMaskAlpha=void 0,i.fireMaskBitmap=void 0,i.fireMaskDirty=!1);else for(let i of o){let a=e.burning.get(i);if(!a||!i.fireAlpha)continue;let o=e.burnLifetime(r.root)??e.destructibleBurnSeconds??a.profile.burnSeconds,s=o===1/0?m.burnSeconds:o;if(a.age>=s)continue;let c=Y(i);n.emitSceneFire({key:i,alpha:i.fireAlpha,pixelWidth:Math.max(1,Math.ceil(i.source.width*2)),pixelHeight:Math.max(1,Math.ceil(i.source.height*2)),x:i.base.x,y:i.base.y,width:i.base.width,height:i.base.height,origin:E(c.x+c.width/2,c.y+c.height/2),age:a.age,farthest:Math.max(1,Math.hypot(c.width,c.height)/2),spreadSeconds:Math.min(.35,a.profile.spreadSeconds*.1),burnSeconds:s,smokeRate:a.profile.smokePerSecond,revision:i.fireRevision},t)}i.burnAmount=r.graphic&&i.fireAge!==void 0?Math.min(1,i.fireAge/Math.max(.01,i.fireTotalSeconds??1)):o.length?o.reduce((e,t)=>e+(t.burnAmount??0),0)/o.length:0,i.burnFinished=a.every(e=>e.destroyed||e.burnFinished)&&!(r.graphic&&i.fireAge!==void 0&&i.fireAge<(i.fireTotalSeconds??0)),i.burnFinished&&(i.bitmap=void 0,i.intactBitmap=void 0,i.fireMaskAlpha=void 0,i.fireMaskBitmap=void 0,i.fireMaskDirty=!1,i.fireMaskRevision=void 0,i.fireOrigin=void 0,i.fireAge=void 0,i.fireBurnSeconds=void 0,i.fireSpreadSeconds=void 0,i.fireSmokeRate=void 0,i.fireTotalSeconds=void 0)}r.root&&r.glyphs.every(e=>e.burnFinished)&&e.burned.add(r.root)}}var qr=class{flameExposure=new Map;flameTouched=new Set;flameGlyphHeat=new Map;flameGlyphTouched=new Set;flameSpreadTouched=new Set;burning=new Map;burned=new Set;spreadElapsed=0;heatBounds=new Map;heatGeneration=0;state(){return{flameExposure:this.flameExposure,flameTouched:this.flameTouched,flameGlyphHeat:this.flameGlyphHeat,flameGlyphTouched:this.flameGlyphTouched,flameSpreadTouched:this.flameSpreadTouched,burning:this.burning,burned:this.burned,spreadElapsed:this.spreadElapsed,heatGeneration:this.heatGeneration}}loadState(e){this.flameExposure=e.flameExposure,this.flameTouched=e.flameTouched,this.flameGlyphHeat=e.flameGlyphHeat,this.flameGlyphTouched=e.flameGlyphTouched,this.flameSpreadTouched=e.flameSpreadTouched,this.burning=e.burning,this.burned=e.burned,this.spreadElapsed=e.spreadElapsed,this.heatGeneration=e.heatGeneration,this.heatBounds.clear()}reset(){this.flameExposure.clear(),this.flameTouched.clear(),this.flameGlyphHeat.clear(),this.flameGlyphTouched.clear(),this.flameSpreadTouched.clear(),this.burning.clear(),this.burned.clear(),this.spreadElapsed=0,this.heatBounds.clear(),this.heatGeneration=0}get measuredBoundsCount(){return this.heatBounds.size}measuredBounds(e){return this.heatBounds.get(e)?.rect}removePiece(e){this.flameExposure.delete(e),this.flameTouched.delete(e),this.flameSpreadTouched.delete(e),this.burning.delete(e),this.heatBounds.delete(e)}extinguishPiece(e){this.burning.delete(e),this.flameExposure.delete(e)}directContact(e,t,n,r,i,a){if(this.burning.has(e))return;this.flameTouched.add(e);let o=(this.flameExposure.get(e)??0)+n;this.flameExposure.set(e,o),t&&(this.flameGlyphTouched.add(t),this.flameGlyphHeat.set(t,(this.flameGlyphHeat.get(t)??0)+n));let s=i(t?.root,r);Math.max(o,t?this.flameGlyphHeat.get(t)??0:0)+1e-6<s.ignitionSeconds||(this.burning.set(e,{age:0,profile:s}),a(t?.root),t&&this.flameGlyphHeat.delete(t))}removeGlyph(e){this.flameGlyphHeat.delete(e),this.flameGlyphTouched.delete(e);for(let t of X(e))this.removePiece(t)}syncBounds(e,t){let n=++this.heatGeneration;for(let r of e)if(t(r))for(let e of r.glyphs)for(let t of X(e))t.destroyed||t.burnFinished||this.heatBounds.set(t,{rect:Y(t),seen:n});for(let[e,t]of this.heatBounds)t.seen!==n&&this.heatBounds.delete(e)}burningSources(){let e=[];for(let[t,n]of this.burning){if(t.destroyed||t.burnFinished)continue;let r=Y(t);e.push({point:E(r.x+r.width/2,r.y+r.height/2),radiusPx:n.profile.spreadRadiusPx,spreadSeconds:n.profile.spreadSeconds,profile:ge(n.profile),bounds:r})}return e}expose(e,t,n,r,i,a){this.syncBounds(n,r);let o=new Map;for(let e of n)for(let t of e.glyphs)for(let e of X(t))o.set(e,t);let s=new Map;for(let[n,r]of this.heatBounds){if(this.burning.has(n))continue;let a=o.get(n);if(!a)continue;let c=i(a.root,m),l=0,u;for(let n of e.near(r.rect)){let e=oe(t,n,r.rect,c.spreadSeconds);e>l&&(l=e,u=n.profile)}l>0&&s.set(n,{heat:l,profile:u})}for(let[e,{heat:t,profile:n}]of s){let r=o.get(e),s=i(r.root,n??m),c=(this.flameExposure.get(e)??0)+t*s.ignitionSeconds;this.flameExposure.set(e,c),this.flameSpreadTouched.add(e),c+1e-6>=s.ignitionSeconds&&(this.burning.set(e,{age:0,profile:s}),a(r.root))}}advance(e,t,n,r,i,a){if(this.spreadElapsed+=e,this.spreadElapsed>=.03333333333333333){let e=this.spreadElapsed;for(let[t,n]of this.flameGlyphHeat){if(this.flameGlyphTouched.has(t))continue;let r=Math.max(0,n-e*.12);r===0||t.burnFinished?this.flameGlyphHeat.delete(t):this.flameGlyphHeat.set(t,r)}this.flameGlyphTouched.clear();for(let[t,n]of this.flameExposure){if(this.flameTouched.has(t)||this.flameSpreadTouched.has(t))continue;let r=Math.max(0,n-e*.2);r===0?this.flameExposure.delete(t):this.flameExposure.set(t,r)}this.flameTouched.clear(),this.flameSpreadTouched.clear(),this.burning.size?this.syncBounds(n,r):this.heatBounds.clear(),this.spreadElapsed=0}Kr({runs:n,burning:this.burning,flameExposure:this.flameExposure,burned:this.burned,burnLifetime:i,destructibleBurnSeconds:a},e,t)}};function Jr(e){return!e||e===`transparent`||/^rgba\([^,]+,[^,]+,[^,]+,\s*0(?:\.0+)?\s*\)$/.test(e)||/^rgba?\([^)]*\/\s*0(?:\.0+)?%?\s*\)$/.test(e)}function Yr(e){return{filled:!!e.backgroundImage&&e.backgroundImage!==`none`||!Jr(e.backgroundColor),border:[[`borderTopWidth`,`borderTopStyle`,`borderTopColor`],[`borderRightWidth`,`borderRightStyle`,`borderRightColor`],[`borderBottomWidth`,`borderBottomStyle`,`borderBottomColor`],[`borderLeftWidth`,`borderLeftStyle`,`borderLeftColor`]].some(([t,n,r])=>parseFloat(e[t])>0&&e[n]!==`none`&&!Jr(e[r]))}}function Xr(e,t,n){let r=Yr(n);if(!r.filled&&!r.border)return null;let i=Math.max(1,Math.min(512,Math.ceil(e.width))),a=Math.max(1,Math.min(512,Math.ceil(e.height))),o=new Uint8Array(i*a),s=[parseFloat(n.borderTopWidth)||0,parseFloat(n.borderRightWidth)||0,parseFloat(n.borderBottomWidth)||0,parseFloat(n.borderLeftWidth)||0];for(let n=0;n<a;n++)for(let c=0;c<i;c++){let l={x:e.x+(c+.5)/i*e.width,y:e.y+(n+.5)/a*e.height};if(kr(t,l)){if(r.filled)o[n*i+c]=255;else{let e=Or(t,l);(e.x<s[3]||e.x>t.shape.width-s[1]||e.y<s[0]||e.y>t.shape.height-s[2])&&(o[n*i+c]=255)}}}return{alpha:o,pixelWidth:i,pixelHeight:a}}var Zr=class{surfaces=new Map;get size(){return this.surfaces.size}captureState(){return[...this.surfaces.values()].map(e=>({...e}))}restoreState(e){this.reset();for(let t of e){let e={...t,alpha:t.alpha.slice()};this.surfaces.set(e.element,e),e.ownedOpacity!==void 0&&(e.element.style.opacity=e.ownedOpacity)}}reset(){for(let e of this.surfaces.values())e.ownedOpacity!==void 0&&e.element.style.opacity===e.ownedOpacity&&(e.element.style.opacity=e.originalOpacity);this.surfaces.clear()}sync(e,t,n){let r=new Set;for(let i of e){if(!(i instanceof HTMLElement)||!i.isConnected)continue;let{rect:e,geometry:a}=t(i);if(!a||e.width<=0||e.height<=0)continue;let o=getComputedStyle(i);if(!Yr(o).filled&&!Yr(o).border)continue;let s=JSON.stringify([e.width,e.height,a.shape,a.box.halfX,a.box.halfY,o.backgroundColor,o.backgroundImage,o.borderTopWidth,o.borderRightWidth,o.borderBottomWidth,o.borderLeftWidth]);r.add(i);let c=this.surfaces.get(i);if(c){if(c.signature!==s){let t=Xr(e,a,o);t&&Object.assign(c,t),c.signature=s}c.origin={x:c.origin.x+e.x-c.rect.x,y:c.origin.y+e.y-c.rect.y},c.rect=e,c.profile=n(i)}else{let t=Xr(e,a,o);if(!t)continue;this.surfaces.set(i,{element:i,rect:e,...t,signature:s,exposure:0,touched:!1,age:null,origin:{x:e.x+e.width/2,y:e.y+e.height/2},profile:n(i),originalOpacity:i.style.opacity,initialOpacity:Number.isFinite(Number(o.opacity))?Number(o.opacity):1})}}for(let[e,t]of this.surfaces)r.has(e)||(t.ownedOpacity!==void 0&&e.style.opacity===t.ownedOpacity&&(e.style.opacity=t.originalOpacity),this.surfaces.delete(e))}burningSources(){let e=[];for(let t of this.surfaces.values()){if(t.age===null||t.age>=t.profile.burnSeconds)continue;let{rect:n,profile:r}=t,i=r.spreadSeconds,a=t.age/Math.max(.01,i)*Math.hypot(n.width,n.height);e.push({point:t.origin,radiusPx:r.spreadRadiusPx,spreadSeconds:r.spreadSeconds,profile:r}),e.push({point:t.origin,bounds:n,radiusPx:r.spreadRadiusPx,spreadSeconds:r.spreadSeconds,profile:r,mask:{alpha:t.alpha,pixelWidth:t.pixelWidth,pixelHeight:t.pixelHeight,origin:t.origin,frontRadius:a}})}return e}expose(e,t,n){for(let r of this.surfaces.values()){if(r.age!==null)continue;let i=0,a=r.origin;for(let n of e.near(r.rect)){let e=oe(t,n,r.rect,r.profile.spreadSeconds);e>i&&(i=e,a=n.point)}i&&(r.touched=!0,r.exposure+=i*r.profile.ignitionSeconds,!(r.exposure+1e-6<r.profile.ignitionSeconds)&&this.ignite(r,a,n))}}ignite(e,t,n){e.age=0,e.origin={x:Math.max(e.rect.x,Math.min(e.rect.x+e.rect.width,t.x)),y:Math.max(e.rect.y,Math.min(e.rect.y+e.rect.height,t.y))},n(e.element)}exposeSegment(e,t,n,r,i){let a=Math.hypot(t.x-e.x,t.y-e.y),o=Math.max(1,Math.ceil(a/Math.max(1,n*.5))),s=new lt(Array.from({length:o+1},(r,i)=>({point:{x:e.x+(t.x-e.x)*i/o,y:e.y+(t.y-e.y)*i/o},radiusPx:n})));for(let e of this.surfaces.values()){if(e.age!==null)continue;let t=0,n=e.origin;for(let r of s.near(e.rect)){let i=oe(1,r,e.rect,1);i>t&&(t=i,n=r.point)}t&&(e.touched=!0,e.exposure+=r*t,e.exposure+1e-6>=e.profile.ignitionSeconds&&this.ignite(e,n,i))}}advance(e,t){for(let n of this.surfaces.values()){if(n.age===null){n.touched||(n.exposure=Math.max(0,n.exposure-e*.2)),n.touched=!1;continue}if(n.age>=n.profile.burnSeconds)continue;n.age+=e;let r=Math.max(.01,n.profile.burnSeconds),i=W(n.age/r,.3,1);(n.ownedOpacity===void 0||n.element.style.opacity===n.ownedOpacity)&&(n.ownedOpacity=String(n.initialOpacity*i),n.element.style.opacity=n.ownedOpacity);let a=n.rect;t.emitSceneFire({key:n,alpha:n.alpha,pixelWidth:n.pixelWidth,pixelHeight:n.pixelHeight,x:a.x,y:a.y,width:a.width,height:a.height,origin:n.origin,age:n.age,farthest:Math.max(1,Math.hypot(a.width,a.height)),spreadSeconds:n.profile.spreadSeconds,burnSeconds:r,smokeRate:n.profile.smokePerSecond},e)}}};function Qr(e,t){if(t.width<=0||t.height<=0)return null;let n=E(t.x+t.width/2,t.y+t.height/2),r=E(e.center.x-n.x,e.center.y-n.y),i=1/0,a=E();for(let n of[e.forward,e.side,E(1,0),E(0,1)]){let o=e.halfLength*Math.abs(j(n,e.forward))+e.halfWidth*Math.abs(j(n,e.side)),s=t.width/2*Math.abs(n.x)+t.height/2*Math.abs(n.y),c=j(r,n),l=o+s-Math.abs(c);if(l<=0)return null;l<i&&(i=l,a=T(n,l*(c<0?-1:1)))}return a}var $r=(e,t)=>e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y,ei=24,ti=(e,t,n)=>e.x<t.x+t.width+n&&e.x+e.width>t.x-n&&e.y<t.y+t.height+n&&e.y+e.height>t.y-n;function ni(e,t,n,r,i,a,o,s,c=()=>void 0){let l={x:n.center.x-n.halfLength-n.halfWidth,y:n.center.y-n.halfLength-n.halfWidth,width:2*(n.halfLength+n.halfWidth),height:2*(n.halfLength+n.halfWidth)};if(a)return;let u=E(e.body.velocity.x*t,-e.body.velocity.y*t),d=(i,a,o)=>{if(a.impactCooldown>0||!un(a,l))return;let c=Y(a);if(!$r(l,c))return;let d=E(c.x+c.width/2,c.y+c.height/2),f=E(d.x-n.center.x,d.y-n.center.y),p=k(u,E(f.y*e.body.spin,-f.x*e.body.spin));if(P(k(p,T(a.velocity,-1)))>t*.7*s(i.root)&&Qr(n,c)&&z(r.alpha,n,c)){let e=E(d.x-n.center.x,d.y-n.center.y),t=P(e)>1?T(e,1/P(e)):n.forward;o.kind===`destructible`?xn(i,a,p,t,(Math.random()-.5)*10):dn(a,p,t,(Math.random()-.5)*10)}};for(let e of i){if(e.root&&o(e)===!1)continue;let t=c(e),n=!t||ti(l,t,ei);for(let t of e.glyphs){if(t.burnFinished||e.kind===`destructible`&&t.breakable===!1)continue;if(e.kind===`pushable`){(n||t.detached)&&d(t,t,e);continue}let r=n&&ti(l,t.ink,2);for(let n of t.fragments??[])!n.destroyed&&!n.burnFinished&&(r||n.detached)&&d(t,n,e)}}}function ri(e){let{shape:t,mask:n,scale:r,projectionScale:i}=e;for(let a of e.targets){let o=a.element,s=Qr(t,a.rect);if(!(o instanceof HTMLElement)||e.crushed.has(o)||!s||!z(n.alpha,t,a.rect))continue;let c=typeof DOMMatrixReadOnly<`u`?K(o):null;if(_e(n.alpha,t,{center:E(a.rect.x+a.rect.width/2,a.rect.y+a.rect.height/2),halfX:c?T(c.halfX,1/i):E(a.rect.width/2,0),halfY:c?T(c.halfY,1/i):E(0,a.rect.height/2)})<.5)continue;let l={scale:o.style.scale,opacity:o.style.opacity,transform:o.style.transform,transition:o.style.transition,transformOrigin:o.style.transformOrigin};e.crushed.set(o,l);let u=e.options(o),d=(u?.crushedClass?.trim().split(/\s+/)??[]).filter(e=>!o.classList.contains(e));if(l.classes=d,d.length&&o.classList.add(...d),o.dataset.jrCrushed=``,o.style.transition=`none`,!u?.crushedClass||u.scale!==void 0){o.style.transformOrigin=`center center`;let e=u?.crushedClass?0:(Math.random()-.5)*14,t=u?.crushedClass?0:(Math.random()-.5)*8,n=u?.scale??.82+Math.random()*.08;o.style.transform=[o.style.transform,`rotate(${e.toFixed(1)}deg) skew(${t.toFixed(1)}deg) scale(${n.toFixed(2)})`].filter(Boolean).join(` `)}if(u?.crushedClass&&u.opacity===void 0||(o.style.opacity=String(u?.opacity??.45)),u?.crushedPaintColor){let t=c?2*Math.hypot(c.halfX.x,c.halfX.y)/i:a.rect.width,n=(c?4*Math.abs(c.halfX.x*c.halfY.y-c.halfX.y*c.halfY.x)/(i*i):a.rect.width*a.rect.height)/Math.max(t,.001),s=on({x:a.rect.x+(a.rect.width-t)/2,y:a.rect.y+(a.rect.height-n)/2,width:t,height:n},r,u.crushedPaintColor,E(e.velocity.x,-e.velocity.y));e.spills.set(o,s),e.emitSpill(s)}l.applied={transformOrigin:o.style.transformOrigin,transition:o.style.transition,transform:o.style.transform,opacity:o.style.opacity},e.onCrush?.(o,e.claimPoints(o,a.points),E(a.rect.x+a.rect.width/2,a.rect.y+a.rect.height/2))}}var ii=(e,t)=>e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y;function ai(e,t,n,r,i){let a=t.impulse,o=t.impulseDirection,s=o?Math.hypot(o.x,o.y):0,c=o&&Number.isFinite(s)&&s>.001?T(o,1/s):null,l=t.radiusPx,u=t.coreRadiusPx;for(let a of r.combustibles){if(a.explodedAt!==null||n.has(a))continue;let r=Math.max(a.rect.x-e.x,0,e.x-a.rect.x-a.rect.width),o=Math.max(a.rect.y-e.y,0,e.y-a.rect.y-a.rect.height),s=Math.hypot(r,o);s<=l&&(n.add(a),i.damageCombustible(a,t.damage/100*Math.max(.2,1-s/l*.7)))}for(let o of r.runs)for(let s of o.glyphs){if(s.burnFinished||n.has(s))continue;let d=Y(s);if(Math.hypot(Math.max(d.x-e.x,0,e.x-d.x-d.width),Math.max(d.y-e.y,0,e.y-d.y-d.height))>l&&!(s.fragments??[]).some(t=>{let n=Y(t);return Math.hypot(Math.max(n.x-e.x,0,e.x-n.x-n.width),Math.max(n.y-e.y,0,e.y-n.y-n.height))<=l}))continue;if(n.add(s),i.notify(`hit`,s.root),s.breakable===!1){if(t.ignite&&s.burnable)for(let e of X(s))!e.burnFinished&&!e.destroyed&&(r.burning.set(e,{age:0,profile:i.burnProfile(s.root,m)}),i.notify(`ignite`,s.root));if(o.kind!==`pushable`)continue}t.damage>0&&o.kind===`destructible`&&ii(s.ink,{x:e.x-u,y:e.y-u,width:u*2,height:u*2})&&i.blastInk(s,e,u);let f=o.kind===`destructible`?(s.fragments??[]).filter(e=>!e.destroyed&&!e.burnFinished):[s];for(let n of f){let d=Y(n),f=E(d.x+d.width/2,d.y+d.height/2),p=E(f.x-e.x,f.y-e.y),h=P(p);if(h>l||t.damage>0&&o.kind===`destructible`&&n.detached&&h<u&&(i.carveInk(s,n,e,u),n.destroyed))continue;let g=c??(h>1?T(p,1/h):E(Math.cos(Math.random()*Math.PI*2),Math.sin(Math.random()*Math.PI*2))),_=Math.max(.15,1-h/l),v=T(g,(140+700*_)*a);if(o.kind===`destructible`){let e=n;t.damage>0&&h<u&&!e.fireAlpha?(e.destroyed=!0,e.bitmap=void 0,r.burning.delete(e),r.flameExposure.delete(e)):(t.impulse>0&&xn(s,e,v,g,(Math.random()-.5)*16),t.ignite&&s.burnable!==!1&&!e.destroyed&&!e.burnFinished&&!r.burning.has(e)&&(r.burning.set(e,{age:0,profile:i.burnProfile(s.root,m)}),i.notify(`ignite`,s.root)))}else t.impulse>0&&dn(n,v,g,(Math.random()-.5)*16)}o.kind===`destructible`&&(s.burnFinished=X(s).every(e=>e.destroyed||e.burnFinished)&&!(o.graphic&&s.fireAge!==void 0),s.burnFinished&&(s.bitmap=void 0,s.intactBitmap=void 0))}}function oi(e,t,n,r){if(!r.fireAlpha||U(e,t,n,Y(r))===null)return null;let i=E(t.x-e.x,t.y-e.y),a=Math.max(1,Math.ceil(P(i)/Math.max(.65,n*.5))),o=E(r.base.x+r.base.width/2+(r.detached?r.offset.x:0),r.base.y+r.base.height/2+(r.detached?r.offset.y:0)),s=Math.cos(r.detached?r.angle:0),c=Math.sin(r.detached?r.angle:0),l=Math.max(1,Math.ceil(r.source.width*2)),u=Math.max(1,Math.ceil(r.source.height*2)),d=Math.max(1,Math.ceil(n*2));for(let t=0;t<=a;t++){let n=t/a,f=k(e,T(i,n)),p=f.x-o.x,m=f.y-o.y,h=Math.round((p*s+m*c+r.source.width/2)*2),g=Math.round((-p*c+m*s+r.source.height/2)*2),_=Math.round(d*.7);for(let[e,t]of[[0,0],[d,0],[-d,0],[0,d],[0,-d],[_,_],[-_,_],[_,-_],[-_,-_]]){let i=h+e,a=g+t;if(i>=0&&a>=0&&i<l&&a<u&&r.fireAlpha[a*l+i]>64)return n}}return null}function si(e,t,n,r,i){let a=null,o=(e,i,o,s)=>{let c=s?.fireAlpha?oi(t,n,r,s):U(t,n,r,e);c!==null&&(!a||c<a.time)&&(a={time:c,kind:i,glyph:o,piece:s})};for(let t of e.walls)o(t.rect,`wall`);for(let i of e.combustibles)if(i.explodedAt===null){let e=U(t,n,r,i.rect);e!==null&&(!a||e<a.time)&&(a={time:e,kind:`combustible`,combustible:i})}for(let a of e.runs)for(let e of a.glyphs)if(!e.burnFinished){if(a.kind===`pushable`)o(Y(e),`pushable`,e);else{let a=U(t,n,r,e.ink)!==null;for(let t of e.fragments??[])t.destroyed||t.burnFinished||i?.has(t)||(a||t.detached)&&o(Y(t),`destructible`,e,t)}}if(!a)return null;let s=a;return{point:k(t,T(E(n.x-t.x,n.y-t.y),s.time)),kind:s.kind,glyph:s.glyph,piece:s.piece,combustible:s.combustible}}var ci=class{onChange;playground;unsubscribe;collection;specs=new WeakMap;selections=new Map;dirty=!0;constructor(e){this.onChange=e}setPlayground(e){this.unsubscribe?.(),this.playground=e,this.collection=void 0,this.invalidate(),this.unsubscribe=e.subscribe(()=>{this.invalidate(),this.onChange()})}invalidate(){this.dirty=!0}specFor(e){if(e)return this.refresh(),this.specs.get(e)}selected(e){return this.refresh(),this.selections.get(e)??[]}dispose(){this.unsubscribe?.(),this.unsubscribe=void 0,this.playground=void 0,this.collection=void 0,this.specs=new WeakMap,this.selections.clear(),this.dirty=!0}refresh(){if(!this.dirty)return;this.dirty=!1;let e=this.playground?.objects;if(this.collection!==e){this.collection=e,this.specs=new WeakMap,this.selections.clear();for(let e of[`solid`,`pushable`,`artwork`,`crushable`,`combustible`,`liquid`])this.selections.set(e,[]);for(let{target:t,spec:n}of e??[])if(this.specs.set(t,n),n.enabled!==!1){(n.breakable||n.burnable&&!n.combustible)&&this.selections.get(`artwork`).push(t),n.solid===!0&&!n.breakable&&!n.combustible&&this.selections.get(`solid`).push(t);for(let e of[`pushable`,`crushable`,`combustible`,`liquid`])n[e]&&this.selections.get(e).push(t)}}}},li=class extends M{element;rect;points;origin;originalOpacity;alpha;pixelWidth;pixelHeight;ownedOpacity;constructor(e,t,n,r,i,a,o=e.style.opacity){super(n),this.element=e,this.rect=t,this.points=r,this.origin=i,this.originalOpacity=o,this.alpha=a.alpha,this.pixelWidth=a.pixelWidth,this.pixelHeight=a.pixelHeight}};function ui(e){let{sim:t,damage:n,shape:r,mask:i,scale:a,viewport:o,walls:s,combustibles:c,onImpact:l,onScrape:u,damageCombustible:d}=e;if(o){let e={left:o.scroll.x+3,top:o.scroll.y+3,right:o.scroll.x+o.width-3,bottom:o.scroll.y+o.height-3},s=R(i.alpha,r),c=[E(s.x<e.left?e.left-s.x:0,0),E(s.x+s.width>e.right?e.right-s.x-s.width:0,0),E(0,s.y<e.top?e.top-s.y:0),E(0,s.y+s.height>e.bottom?e.bottom-s.y-s.height:0)];for(let e of c){if(!e.x&&!e.y)continue;t.body.position.x+=e.x/a,t.body.position.y-=e.y/a,r.center={x:r.center.x+e.x,y:r.center.y+e.y};let o=T(e,1/P(e)),s=E(t.body.velocity.x*a,-t.body.velocity.y*a),c=j(s,o);if(c<0){if(c<-a*.8){let e=te(i.alpha,r,T(o,-1)),u=-c/a;t.car.takeImpact(u,E(j(w(e,r.center),r.forward)/a,j(w(e,r.center),r.side)/a)),n.hit(e,o,r,u,a),l?.({speedMps:u,velocity:s,normal:o,point:e,carNormal:se(i.alpha,r,e),pixelsPerMeter:a})}t.body.velocity.x-=c*o.x/a,t.body.velocity.y+=c*o.y/a,t.body.spin*=.85}}}for(let e=0;e<3;e++){let o=!1;for(let f of s){if(f instanceof li&&f.explodedAt!==null)continue;let s=Qr(r,f.rect);if(!s||!z(i.alpha,r,f.rect))continue;let p=T(s,1/P(s)),m=ie(i.alpha,r,f.rect),h=se(i.alpha,r,m),g={...r},_=ce(i.alpha,r,f.rect,p,P(s)+2),v=T(p,_);t.body.position.x+=v.x/a,t.body.position.y-=v.y/a,r.center={x:r.center.x+v.x,y:r.center.y+v.y};let y=E(t.body.velocity.x*a,-t.body.velocity.y*a),b=j(y,p),x=P(w(y,T(p,b)));if(b<0){if(e===0){let e=-b/a,r=c.get(f.element),i={speedMps:e,velocity:y,normal:p,point:m,carNormal:h,wall:f.rect,element:f.element,pixelsPerMeter:a};ct(t,n,g,i,()=>{r&&d(r,e*D.impactDamagePerMps)})&&l?.(i)}t.body.velocity.x-=b*p.x/a,t.body.velocity.y+=b*p.y/a,t.body.spin*=.85}e===0&&b>=-a*.8&&b<=a*.1&&x>a*2.2&&u?.({speedMps:Math.max(0,-b/a),velocity:y,normal:p,point:m,carNormal:h,wall:f.rect,pixelsPerMeter:a}),o=!0}if(!o)break}}var di=e=>{for(let t=e;t&&t!==document.body;t=t.parentElement){let e=getComputedStyle(t).position;if(e===`fixed`||e===`sticky`)return!0}return!1},fi=class{onImpact;sceneOffset;projection;damage;onCrush;onScrape;onCombustibleExplosion;onDestructibleDestroyed;autoPaint=null;runs=[];walls=[];crushables=[];combustibles=new Map;pointSources=new Map;awardedObjects=new Set;solidObjects=[];showHealthBars=!0;hoveredVehicleId=null;destructibleBurnSeconds;flameDamageThisStep=new Map;stepSeconds=1/60;crushed=new Map;crushSpills=new Map;liquidElements=[];paintTransitions=new Map;liquidBackings=new Map;lastAutoPaintGeometryRevision=-1;dirty=!0;lastScan=-1/0;lastMeasure=-1/0;selection=new ci(()=>{this.dirty=!0,this.lastScan=-1/0});artwork;masks=new ne;preset=null;lettersFadeStartedAt=null;artworkFire=new qr;externalFireElapsed=0;burnSprites=new st;textLayers=new or;fragmentAtlas=new dr(this.burnSprites);burnSurfaces=new Zr;captureState(){let e=new Map;for(let t of[...this.crushed.keys(),...this.combustibles.keys()])t instanceof HTMLElement&&e.set(t,{opacity:t.style.opacity,scale:t.style.scale,transform:t.style.transform,transition:t.style.transition,transformOrigin:t.style.transformOrigin,crushed:`jrCrushed`in t.dataset,crushedClasses:(this.crushed.get(t)?.classes??[]).filter(e=>t.classList.contains(e))});return{data:b({runs:this.runs,walls:this.walls,crushables:this.crushables,combustibles:this.combustibles,pointSources:this.pointSources,awardedObjects:this.awardedObjects,showHealthBars:this.showHealthBars,destructibleBurnSeconds:this.destructibleBurnSeconds,flameDamageThisStep:this.flameDamageThisStep,stepSeconds:this.stepSeconds,crushed:this.crushed,crushSpills:this.crushSpills,liquidElements:this.liquidElements,dirty:this.dirty,lastScan:this.lastScan,lastMeasure:this.lastMeasure,preset:this.preset,lettersFadeStartedAt:this.lettersFadeStartedAt,artworkFire:this.artworkFire.state(),externalFireElapsed:this.externalFireElapsed,sourceVehicleId:this.sourceVehicleId,ignitedRoots:this.ignitedRoots}),automaticPaint:!!this.autoPaint,burnSurfaces:this.burnSurfaces.captureState(),styles:e,at:performance.now()}}restoreState(e){let t=this.captureState();try{this.applyState(e)}catch(e){try{this.applyState(t)}catch(t){throw AggregateError([e,t],`DOM collision checkpoint rollback failed`,{cause:t})}throw e}}applyState(e){let t=b(e.data);this.clearPaintSurfaces(),this.burnSurfaces.reset(),this.restoreCrushables(),this.restoreCombustibles(),this.restoreText(),this.runs=t.runs,this.walls=t.walls,this.crushables=t.crushables,this.combustibles=t.combustibles,this.pointSources=t.pointSources,this.awardedObjects=t.awardedObjects,this.showHealthBars=t.showHealthBars,this.destructibleBurnSeconds=t.destructibleBurnSeconds,this.flameDamageThisStep=t.flameDamageThisStep,this.stepSeconds=t.stepSeconds,this.crushed=t.crushed,this.crushSpills=t.crushSpills,this.liquidElements=t.liquidElements,this.lastAutoPaintGeometryRevision=-1,this.dirty=t.dirty,this.lastScan=t.lastScan,this.lastMeasure=t.lastMeasure,this.preset=t.preset,this.lettersFadeStartedAt=t.lettersFadeStartedAt,this.artworkFire.loadState(t.artworkFire),this.externalFireElapsed=t.externalFireElapsed,this.sourceVehicleId=t.sourceVehicleId,this.ignitedRoots=t.ignitedRoots,this.selection.invalidate(),this.artwork.clear(),this.solidObjects=[],this.burnSprites.clear(),this.textLayers.clear(),this.fragmentAtlas.clear();for(let e of this.runs)!e.wrapper.isConnected&&e.original.isConnected&&e.original.replaceWith(e.wrapper);for(let[t,n]of e.styles)t.style.opacity=n.opacity,t.style.scale=n.scale,t.style.transform=n.transform,t.style.transition=n.transition,t.style.transformOrigin=n.transformOrigin,n.crushed?(t.dataset.jrCrushed=``,n.crushedClasses.length&&t.classList.add(...n.crushedClasses)):delete t.dataset.jrCrushed;this.burnSurfaces.restoreState(e.burnSurfaces),(e.automaticPaint||this.autoPaint)&&(this.autoPaint?.refresh(),this.dirty=!0,this.lastScan=-1/0);let n=performance.now()-e.at;this.lettersFadeStartedAt!==null&&(this.lettersFadeStartedAt+=n),Number.isFinite(this.lastScan)&&(this.lastScan+=n),Number.isFinite(this.lastMeasure)&&(this.lastMeasure+=n);for(let e of this.combustibles.values())e.explodedAt!==null&&(e.explodedAt+=n),Number.isFinite(e.lastBlastEmission)&&(e.lastBlastEmission+=n)}constructor(e,t=()=>E(),n=new ye,r,i,a,o){let s=typeof e==`object`&&e?e:{onImpact:e,sceneOffset:t,damage:n,onCrush:r,onScrape:i,onCombustibleExplosion:a,onDestructibleDestroyed:o};this.onImpact=s.onImpact,this.sceneOffset=s.sceneOffset??(()=>E()),this.damage=s.damage??new ye,this.onCrush=s.onCrush,this.onScrape=s.onScrape,this.onCombustibleExplosion=s.onCombustibleExplosion,this.onDestructibleDestroyed=s.onDestructibleDestroyed,this.projection=s.projection??B,this.artwork=new An(()=>{this.lastMeasure=-1/0,this.dirty=!0,this.lastScan=-1/0},this.projection)}rectInDocument(e,t){return this.projection.viewportRectToDocument(e.getBoundingClientRect(),t)}sourceVehicleId;ignitedRoots=new Set;onObjectEvent;setSourceVehicle(e){this.sourceVehicleId=e}notify(e,t){if(t){if(e===`ignite`){if(this.ignitedRoots.has(t))return;this.ignitedRoots.add(t)}this.onObjectEvent?.(e,t)}}setEvents(e){let t=e=>({element:e,objectId:e?this.selection.playground?.get(e)?.id:void 0,vehicleId:this.sourceVehicleId});this.onObjectEvent=(n,r)=>{let i=this.rectInDocument(r,this.sceneOffset());e.emit({kind:`object`,type:n,point:E(i.x+i.width/2,i.y+i.height/2),...t(r)})},this.onImpact=n=>e.emit({kind:`impact`,impact:n,...t(n.element)}),this.onScrape=n=>e.emit({kind:`scrape`,impact:n,...t(n.element)}),this.onCrush=(n,r,i)=>e.emit({kind:`crush`,points:r,point:i,...t(n)}),this.onCombustibleExplosion=(n,r,i)=>e.emit({kind:`combustionExplosion`,point:n,points:r,...t(i)}),this.onDestructibleDestroyed=(n,r,i,a)=>e.emit({kind:`destructibleDestroyed`,point:n,points:r,cause:a,...t(i)})}prepare(e){this.preset=e,this.masks.forPreset(e)}get totalPoints(){let e=0;for(let t of this.pointSources.values())e+=t;for(let{spec:t}of this.selection.playground?.objects??[]){let n=typeof t.trigger==`object`?t.trigger.preset:t.trigger,r=typeof t.trigger==`object`?t.trigger.when:void 0;t.enabled!==!1&&(n===`pickup`||(r??(n===`parking`?`stop`:`enter`))===`stop`)&&(e+=t.points??0)}return e}pointsFor(e,t){let n=this.specFor(e)?.points??this.pointSources.get(e);return n===void 0&&(n=this.specFor(e)?.points??L(e,t.width,t.height),this.pointSources.set(e,n)),this.pointSources.set(e,n),n}claimPoints(e,t){return this.awardedObjects.has(e)?0:(this.awardedObjects.add(e),this.pointSources.get(e)??t)}setShowHealthBars(e){this.showHealthBars=e}setHoveredVehicle(e){this.hoveredVehicleId=e}forgetVehicle(e){this.hoveredVehicleId===e&&(this.hoveredVehicleId=null)}setDestructibleBurnSeconds(e){this.destructibleBurnSeconds=e===1/0||e!==void 0&&Number.isFinite(e)&&e>0?e:void 0}vehicleMask(e,t=this.damage){return t.maskFor(this.masks.forPreset(e))}get managedBytes(){let e=(this.artworkFire.flameExposure.size+this.artworkFire.burning.size)*48+this.artworkFire.flameGlyphHeat.size*24+this.crushed.size*128;for(let t of this.combustibles.values())e+=192+t.alpha.byteLength;for(let t of this.runs)for(let n of t.glyphs){if(t.kind===`pushable`){e+=128;continue}if(n.burnFinished)continue;let r=n.fragments?.filter(e=>!e.destroyed&&!e.burnFinished)??[];if(r.length){e+=(n.bitmap?.width??0)*(n.bitmap?.height??0)*4,e+=(n.intactBitmap?.width??0)*(n.intactBitmap?.height??0)*4,e+=this.burnSprites.bytesFor(n.intactBitmap),e+=this.burnSprites.bytesFor(n.bitmap);for(let t of r)e+=160+(t.fireAlpha?.byteLength??0)+(t.bitmap?.width??0)*(t.bitmap?.height??0)*4+this.burnSprites.bytesFor(t.bitmap)}}return e+this.textLayers.bytes+this.fragmentAtlas.bytes}wallRects(){return this.walls.map(e=>e.rect)}drawHealthBars(e,t,n,r,i,a=[]){Wr({combustibles:this.combustibles.values(),hoveredVehicleId:this.hoveredVehicleId,showHealthBars:this.showHealthBars},e,t,n,r,i,a)}burningProximity(e){let t=0,n=0,r=0,i=new Set,a=(r,i)=>{let a=Math.hypot(Math.max(r.x-e.x,0,e.x-r.x-r.width),Math.max(r.y-e.y,0,e.y-r.y-r.height)),o=r.width*r.height;t+=o,n+=o*i*Math.max(0,1-a/650)};for(let e of this.runs)if(e.graphic)for(let t of e.glyphs){if(t.fireAge===void 0||t.burnFinished)continue;let e=(t.fireAge-(t.fireSpreadSeconds??0)/2)/Math.max(.01,t.fireBurnSeconds??m.burnSeconds);a(t.ink,W(e,.78,1.02));for(let e of t.fragments??[])e.detached||i.add(e)}for(let e of this.artworkFire.burning.keys())e.destroyed||e.burnFinished||i.has(e)||a(Y(e),W(e.burnAmount??0));for(let t of this.combustibles.values()){if(t.explodedAt!==null||t.health>t.maxHealth*D.smokeFraction)continue;let n=t.rect,i=Math.hypot(Math.max(n.x-e.x,0,e.x-n.x-n.width),Math.max(n.y-e.y,0,e.y-n.y-n.height));r=Math.max(r,A(t.health,t.maxHealth)*Math.max(0,1-i/650))}let o=t?Math.min(.65,Math.max(.1,Math.sqrt(t)/120))*(n/t):0;return Math.max(o,r)}tirePaintAt(e){return Mr(this.liquidStepState(),e)}stepElementLiquids(e,t,n){Nr(this.liquidStepState(),e,t,n)}liquidStepState(){return{liquidElements:this.liquidElements,liquidBackings:this.liquidBackings}}clearPaintTransitions(){for(let e of this.paintTransitions.values())e();this.paintTransitions.clear()}clearPaintSurfaces(){for(let e of this.liquidBackings.values())e.dispose();this.liquidBackings.clear()}fadeLetters(){this.clearPaintSurfaces(),this.restoreCrushables(),this.restoreCombustibles(),this.lettersFadeStartedAt===null&&this.runs.some(e=>e.glyphs.some(e=>e.detached||e.fragments?.some(e=>e.detached)))&&(this.lettersFadeStartedAt=performance.now())}finishLetterReset(e){this.lettersFadeStartedAt===null||he(this.lettersFadeStartedAt,e)>0||(this.restoreText(),this.dirty=!0,this.lastScan=-1/0)}setPlayground(e){let t=!!this.autoPaint;this.autoPaint?.dispose(),this.autoPaint=null,this.selection.setPlayground(e),t&&this.setAutoPaint(!0),this.dirty=!0,this.lastScan=-1/0}specFor(e){return this.selection.specFor(e)}selected(e){return this.selection.selected(e)}burnLifetime(e){let t=this.specFor(e),n=t?.burnable||t?.combustible;return n&&typeof n==`object`?n.burnSeconds:void 0}capabilityOptions(e,t){let n=this.specFor(e)?.[t];return n&&typeof n==`object`?n:void 0}toughness(e){return Math.sqrt((this.capabilityOptions(e,`breakable`)?.health??100)/100)}burnProfile(e,t){return{...m,...t,...this.capabilityOptions(e,`burnable`)}}liquidOptions(e){return this.specFor(e)?.liquid||void 0}setAutoPaint(e){e!==!!this.autoPaint&&(this.autoPaint?.dispose(),this.autoPaint=e?new Kn(()=>{this.dirty=!0},e=>this.liquidBackings.get(e)?.readPaintSource()?.color,this.selection.playground?.root??document):null,this.lastAutoPaintGeometryRevision=-1,this.dirty=!0)}restoreCombustibles(){for(let e of this.combustibles.values())e.ownedOpacity!==void 0&&e.element.style.opacity===e.ownedOpacity&&(e.element.style.opacity=e.originalOpacity);this.combustibles.clear(),this.dirty=!0,this.lastScan=-1/0}restoreCrushable(e){let t=this.crushed.get(e);if(t){for(let n of[`scale`,`opacity`,`transform`,`transition`,`transformOrigin`])t.applied?.[n]!==void 0&&e.style[n]===t.applied[n]&&(e.style[n]=t[n]);for(let n of t.classes??[])e.classList.remove(n);delete e.dataset.jrCrushed,this.crushed.delete(e),this.crushSpills.delete(e)}}restoreCrushables(){this.crushSpills.clear();for(let e of this.crushed.keys())this.restoreCrushable(e)}restoreText(){for(let e of this.runs)En(e);this.runs=[],this.artworkFire.reset(),this.externalFireElapsed=0,this.burnSprites.clear(),this.textLayers.clear(),this.fragmentAtlas.clear(),this.ignitedRoots.clear(),this.lettersFadeStartedAt=null}wrapText(){let e=Dn({pushable:this.selected(`pushable`),artwork:this.selected(`artwork`),hud:new Set(this.selection.playground?.objects.filter(e=>e.spec.hud).map(e=>e.target))},this.artwork.canvas);this.runs.push(...e);for(let t of e)t.kind===`destructible`&&t.root&&this.pointsFor(t.root,this.rectInDocument(t.root,this.sceneOffset()))}wrapGraphics(){let e=kn(this.selected(`artwork`),()=>{this.dirty=!0});this.runs.push(...e);for(let t of e)t.root&&t.graphic&&this.pointsFor(t.root,this.rectInDocument(t.graphic,this.sceneOffset()))}scan(e){if(!this.dirty||e-this.lastScan<250)return;performance.now(),this.lastScan=e,this.dirty=!1;for(let e of this.crushed.keys())e.isConnected||this.restoreCrushable(e);let t=new Set(this.selected(`pushable`)),n=new Set(this.selected(`artwork`));this.runs=this.runs.filter(e=>e.wrapper.isConnected&&(!this.selection.playground||(e.kind===`pushable`?t:n).has(e.root))&&(e.graphic||e.original.data===e.source)?!0:(En(e),!1)),this.wrapText(),this.wrapGraphics(),this.walls=this.selected(`solid`).length?this.selected(`solid`).filter(e=>!e.closest(`[data-jr-embed],[data-jr-text-run]`)).map(e=>({element:e,rect:this.rectInDocument(e,this.sceneOffset()),viewportAnchored:di(e)})):[],this.crushables=this.selected(`crushable`).length?this.selected(`crushable`).filter(e=>e instanceof HTMLElement&&!e.closest(`[data-jr-embed]`)).map(e=>({element:e,rect:this.rectInDocument(e,this.sceneOffset()),points:this.pointsFor(e,this.rectInDocument(e,this.sceneOffset()))})):[];let r=new Set(this.crushables.map(e=>e.element));for(let e of this.crushed.keys())r.has(e)||this.restoreCrushable(e);{let e=new Set;for(let t of this.selected(`combustible`)){if(!(t instanceof HTMLElement)||t.closest(`[data-jr-embed]`))continue;e.add(t);let n=this.combustibles.get(t);if(n){let e=this.specFor(t)?.combustible,r=typeof e==`object`?e.health??D.defaultHealth:D.defaultHealth;r!==n.maxHealth&&(n.health=n.healthFraction*r,n.maxHealth=r),n.points=this.pointsFor(t,this.rectInDocument(t,this.sceneOffset()));let i=this.rectInDocument(t,this.sceneOffset());(i.width!==n.rect.width||i.height!==n.rect.height)&&Object.assign(n,Yn(t,i.width,i.height)),n.origin=k(n.origin,E(i.x-n.rect.x,i.y-n.rect.y)),n.rect=i;continue}let r=this.rectInDocument(t,this.sceneOffset()),i=Yn(t,r.width,r.height),a=-1,o=0;for(let e=0;e<i.alpha.length;e++)i.alpha[e]>=64&&Math.random()*++o<1&&(a=e);let s=a>=0?E(r.x+(a%i.pixelWidth+.5)/i.pixelWidth*r.width,r.y+(Math.floor(a/i.pixelWidth)+.5)/i.pixelHeight*r.height):E(r.x+r.width/2,r.y+r.height/2),c=Math.max(1,this.capabilityOptions(t,`combustible`)?.health??D.defaultHealth);this.combustibles.set(t,new li(t,r,c,this.pointsFor(t,r),s,i))}for(let[t,n]of this.combustibles)e.has(t)||(n.ownedOpacity!==void 0&&n.element.style.opacity===n.ownedOpacity&&(n.element.style.opacity=n.originalOpacity),this.combustibles.delete(t))}let i=[...new Set([...this.selected(`liquid`),...(this.autoPaint?.elements??[]).filter(e=>this.specFor(e)?.enabled!==!1)])],a=new Map(this.liquidElements.map(e=>[e.element,e]));this.liquidElements=i.map(e=>a.get(e)??{element:e,rect:this.rectInDocument(e,this.sceneOffset()),source:null,liquidSource:null,geometry:null});let o=new Set(this.liquidElements.map(e=>e.element));for(let[e,t]of this.paintTransitions)o.has(e)||(t(),this.paintTransitions.delete(e));for(let e of o)e instanceof HTMLElement&&!this.paintTransitions.has(e)&&this.paintTransitions.set(e,Ir(e));for(let[e,t]of this.liquidBackings)o.has(e)||(t.dispose(),this.liquidBackings.delete(e));this.measure(),this.lastMeasure=e}measure(){performance.now();let e=this.sceneOffset(),t=new xt;this.artwork.measure(this.runs,e,e=>this.specFor(e),e=>this.artworkFire.extinguishPiece(e));for(let t of this.walls)t.rect=this.rectInDocument(t.element,e);this.burnSurfaces.sync(this.selected(`artwork`).filter(e=>{let t=this.specFor(e);return!!t?.burnable&&!t.combustible}),n=>({rect:this.rectInDocument(n,e),geometry:Dr(n,e,this.projection,t)}),e=>this.burnProfile(e,m)),performance.now();let n=this.autoPaint?.geometryRevision??-1;for(let r of this.liquidElements){let i=this.rectInDocument(r.element,e),a=this.autoPaint?.has(r.element),o=Math.abs(r.rect.x-i.x)<.5&&Math.abs(r.rect.y-i.y)<.5&&Math.abs(r.rect.width-i.width)<.5&&Math.abs(r.rect.height-i.height)<.5;if(a&&r.geometry&&this.lastAutoPaintGeometryRevision===n&&o)continue;r.rect=i;let s=this.liquidBackings.get(r.element),c=this.liquidOptions(r.element);F(`dom paint geometry measures`),r.geometry=Dr(r.element,e,this.projection,t),r.liquidSource=r.geometry&&c?s?s.readSource(c):mr(r.element,c):null,r.source=r.geometry?c?r.liquidSource?.paint??null:s?s.readPaintSource():pr(r.element):null}this.lastAutoPaintGeometryRevision=n}carveInk(e,t,n,r){Sn(e,t,n,r/this.toughness(e.root))&&this.artworkFire.extinguishPiece(t)}blastInk(e,t,n){for(let r of Cn(e,t,n/this.toughness(e.root)))this.artworkFire.extinguishPiece(r)}flameContact(e,t,n,r,i){let a=w(t,e),o=P(a),s=o>1e-6?T(a,1/o):E(),c=new Set,l=(t,i)=>(this.burnSurfaces.exposeSegment(e,t,n,r,e=>this.notify(`ignite`,e)),i);for(;;){let a=this.firstProjectileHit(e,t,n,c);if(!a)return l(t,null);if(a.combustible)return this.damageCombustible(a.combustible,`flame`,1,r),l(a.point,a.point);let u=a.kind===`destructible`?a.piece:void 0;if(u&&a.glyph?.burnable!==!1&&this.artworkFire.directContact(u,a.glyph,r,i,(e,t)=>this.burnProfile(e,t),e=>this.notify(`ignite`,e)),!u||o<1e-6)return l(a.point,a.point);let d=u.detached?Y(u):a.glyph?.ink??Y(u),f=Math.abs(s.x)*d.width+Math.abs(s.y)*d.height;if(u.detached&&f<=n*2){c.add(u);continue}let p=k(a.point,T(s,Math.min(n*1.5,f*.35)));return l(p,p)}}damageCombustible(e,t,n=1,r=0){if(e.explodedAt!==null||!this.preset)return;let i=x(t,this.preset,r)*n;if(t===`flame`){let t=this.capabilityOptions(e.element,`burnable`)?.ignitionSeconds;t!==void 0&&(i=e.maxHealth*(1-D.ignitionFraction)*r*n/Math.max(.01,t));let a=this.flameDamageThisStep.get(e)??0,o=t===void 0?D.damagePerSecond:e.maxHealth*(1-D.ignitionFraction)/Math.max(.01,t);i=Math.min(i,Math.max(0,o*this.stepSeconds-a)),this.flameDamageThisStep.set(e,a+i)}this.applyCombustibleDamage(e,i)}applyCombustibleDamage(e,t){let n=e.stage;e.damage(t)&&(e.originalOpacity=e.element.style.opacity,e.ownedOpacity=`0`,e.element.style.opacity=`0`),n!==`burning`&&e.stage===`burning`&&this.notify(`ignite`,e.element)}fireRunEligible(e){return e.kind===`destructible`&&(!e.root||this.specFor(e.root)?.burnable!==!1)&&(!this.selection.playground||!!this.specFor(e.root)?.burnable)}burningFireSources(){let e=this.artworkFire.burningSources();for(let t of this.combustibles.values()){if(t.stage!==`burning`)continue;let n=this.burnProfile(t.element,m);e.push(...le(t,ge(n)))}return e.push(...this.burnSurfaces.burningSources()),e}exposeToFire(e,t){if(!e.length||t<=0){this.externalFireElapsed=0;return}if(this.externalFireElapsed+=t,this.externalFireElapsed<.03333333333333333)return;t=this.externalFireElapsed,this.externalFireElapsed=0;let n=new lt(e);this.artworkFire.expose(n,t,this.runs,e=>this.fireRunEligible(e),(e,t)=>this.burnProfile(e,t),e=>this.notify(`ignite`,e));let r=new Map;for(let e of this.combustibles.values()){if(e.stage===`burning`||e.explodedAt!==null)continue;let i=0;for(let r of n.near(e.rect))i=Math.max(i,oe(t,r,e.rect,this.burnProfile(e.element,m).spreadSeconds));i>0&&r.set(e,i)}for(let[e,t]of r)this.applyCombustibleDamage(e,t*e.maxHealth);this.burnSurfaces.expose(n,t,e=>this.notify(`ignite`,e))}advanceBurn(e,t){performance.now(),this.burnSurfaces.advance(e,t);for(let n of this.combustibles.values())qn(n,e,t,this.capabilityOptions(n.element,`combustible`)?.blastRadiusPx,e=>this.onCombustibleExplosion?.(e,this.claimPoints(n.element,n.points),n.element));this.artworkFire.advance(e,t,this.runs,e=>this.fireRunEligible(e),e=>this.burnLifetime(e),this.destructibleBurnSeconds)}emitCrushSpill(e,t,n){for(let r of cn(t,n))e.emitPaint(e.worldFromDocument(r.point),r.radiusM,r.amount,r.color,E(r.flowMps.x,-r.flowMps.y))}advanceCrushSpills(e,t){for(let[n,r]of this.crushSpills)n.isConnected?(this.emitCrushSpill(e,r,t),r.age>=r.duration&&this.crushSpills.delete(n)):this.crushSpills.delete(n)}beginStep(e,t){let n=performance.now();this.stepSeconds=t,this.advanceCrushSpills(e,t),this.flameDamageThisStep.clear(),this.finishLetterReset(n),this.scan(n),n-this.lastMeasure>120&&(this.measure(),this.lastMeasure=n);let r=this.sceneOffset();for(let e of this.walls)e.viewportAnchored&&(e.rect=this.rectInDocument(e.element,r));for(let e of this.combustibles.values())e.stage===`burning`&&this.applyCombustibleDamage(e,O(e.maxHealth,t,this.burnLifetime(e.element)??D.burnDownSeconds));this.advanceBurn(t,e);let i=new Set(this.crushables.map(e=>e.element));this.solidObjects=this.walls.slice();for(let e of this.combustibles.values())e.explodedAt===null&&!i.has(e.element)&&this.solidObjects.push(e)}stepVehicle(e,t,n=!1,r=this.damage,i=`player`,a=!1){if(this.sourceVehicleId=i,e.mode!==`car`||e.car.explodedAt!==null)return;let o=t.documentScale(),s=this.vehicleMask(e.car.preset,r),c=k(t.documentPoint(e.body.position),t.carVisualOffset(e)),l=E(Math.cos(e.body.angle),-Math.sin(e.body.angle)),u={center:c,forward:l,side:E(-l.y,l.x),halfLength:s.lengthM*o/2,halfWidth:s.widthM*o/2};ui({sim:e,damage:r,shape:u,mask:s,scale:o,viewport:n?{scroll:t.sceneScroll(),...t.viewportSize()}:void 0,walls:a?[]:this.solidObjects,combustibles:this.combustibles,onImpact:this.onImpact,onScrape:this.onScrape,damageCombustible:(e,t)=>this.applyCombustibleDamage(e,t)}),!a&&(ri({targets:this.crushables,crushed:this.crushed,spills:this.crushSpills,shape:u,mask:s,scale:o,projectionScale:this.projection.scale,velocity:e.body.velocity,options:e=>this.capabilityOptions(e,`crushable`),claimPoints:(e,t)=>this.claimPoints(e,t),emitSpill:e=>this.emitCrushSpill(t,e,this.stepSeconds),onCrush:this.onCrush}),ni(e,o,u,s,this.runs,this.lettersFadeStartedAt!==null,e=>!e.root||this.specFor(e.root)?.solid!==!1,e=>this.toughness(e),e=>this.artwork.bounds(e)))}endStep(e){performance.now();let t=this.walls.map(e=>e.rect),n=n=>{n.detached?_n(n,e,t):n.impactCooldown>0&&(n.impactCooldown=Math.max(0,n.impactCooldown-e))};for(let e of this.runs)for(let t of e.glyphs)if(!t.burnFinished){if(e.kind===`pushable`)n(t);else for(let e of t.fragments??[])!e.destroyed&&!e.burnFinished&&n(e)}let r=new Map;for(let e of this.runs){let t=e.root;e.kind===`destructible`&&t&&!this.awardedObjects.has(t)&&r.get(t)!==!1&&r.set(t,e.glyphs.every(e=>e.burnFinished||e.fragments?.length&&e.fragments.every(e=>e.destroyed||e.burnFinished)))}for(let[e,t]of r){if(!t)continue;let n=this.rectInDocument(e,this.sceneOffset());this.onDestructibleDestroyed?.(E(n.x+n.width/2,n.y+n.height/2),this.claimPoints(e,this.pointsFor(e,n)),e,this.artworkFire.burned.has(e)?`burnout`:`break`)}}paintTargetMask(e,t){Hr(e,t,{crushables:this.crushables,crushed:this.crushed,combustibles:this.combustibles.values(),runs:this.runs})}step(e,t,n,r=!1,i=this.damage){this.beginStep(t,n),this.stepVehicle(e,t,r,i),this.endStep(n)}firstProjectileHit(e,t,n,r){return this.scan(performance.now()),si({walls:this.walls,combustibles:this.combustibles.values(),runs:this.runs},e,t,n,r)}projectileHit(e,t,n){return this.firstProjectileHit(e,t,n)}bulletImpact(e,t,n,r){let i=r??this.firstProjectileHit(e,t,n);if(!i)return null;if(i.kind===`wall`)return i.point;this.notify(`hit`,i.combustible?.element??i.glyph?.root),i.combustible&&this.damageCombustible(i.combustible,`bullet`);let a=E(t.x-e.x,t.y-e.y),o=P(a),s=o>0?T(a,1/o):E(1,0);return i.kind===`pushable`&&i.glyph&&dn(i.glyph,T(s,260),s,(Math.random()-.5)*5),i.kind===`destructible`&&i.glyph&&i.glyph.breakable!==!1&&i.piece&&this.carveInk(i.glyph,i.piece,k(i.point,T(s,n*.25)),Math.max(4.2,n*1.9)),i.point}rocketImpact(e,t,n,r=1,i){let a=i??this.firstProjectileHit(e,t,n);return a?(a.kind!==`wall`&&this.applyAreaImpact(a.point,Be(r)),a.point):null}applyAreaImpact(e,t,n=new Set){ai(e,t,n,{combustibles:this.combustibles.values(),runs:this.runs,burning:this.artworkFire.burning,flameExposure:this.artworkFire.flameExposure},{damageCombustible:(e,t)=>this.damageCombustible(e,`rocket`,t),notify:(e,t)=>this.notify(e,t),burnProfile:(e,t)=>this.burnProfile(e,t),blastInk:(e,t,n)=>this.blastInk(e,t,n),carveInk:(e,t,n,r)=>this.carveInk(e,t,n,r)})}draw(e,t,n){performance.now(),this.finishLetterReset(performance.now()),Ur(e,t,n,{crushed:this.crushed.keys(),hasCrushedPaint:e=>!!this.capabilityOptions(e,`crushable`)?.crushedPaintColor,projection:this.projection,offset:this.sceneOffset(),runs:this.runs,layout:e=>this.artwork.bounds(e),burnSprites:this.burnSprites,textLayers:this.textLayers,fragmentAtlas:this.fragmentAtlas,fade:he(this.lettersFadeStartedAt,performance.now())})}drawDebug(e,t,n,r=this.damage){Gr({walls:this.walls,liquidElements:this.liquidElements,combustibles:this.combustibles.values(),runs:this.runs,autoPaintElements:this.autoPaint?.elements,mask:this.vehicleMask(t.car.preset,r)},e,t,n)}resetObject(e){let t=this.selection.playground?.objects.find(t=>t.id===e)?.target;if(!t)return!1;this.runs=this.runs.filter(e=>{if(e.root!==t)return!0;for(let t of e.glyphs)this.artworkFire.removeGlyph(t);return En(e),!1}),this.artworkFire.burned.delete(t),this.ignitedRoots.delete(t);let n=this.combustibles.get(t);return n&&(n.ownedOpacity!==void 0&&t instanceof HTMLElement&&t.style.opacity===n.ownedOpacity&&(t.style.opacity=n.originalOpacity),this.flameDamageThisStep.delete(n),this.combustibles.delete(t)),this.liquidBackings.get(t)?.dispose(),this.liquidBackings.delete(t),t instanceof HTMLElement&&(this.restoreCrushable(t),this.crushSpills.delete(t),this.paintTransitions.get(t)?.(),this.paintTransitions.delete(t)),this.awardedObjects.delete(t),this.pointSources.delete(t),this.walls=this.walls.filter(e=>e.element!==t),this.solidObjects=this.solidObjects.filter(e=>e.element!==t),this.crushables=this.crushables.filter(e=>e.element!==t),this.liquidElements=this.liquidElements.filter(e=>e.element!==t),this.artwork.invalidate(),this.dirty=!0,this.lastScan=this.lastMeasure=-1/0,!0}reset(){this.clearPaintSurfaces(),this.clearPaintTransitions(),this.restoreCrushables(),this.restoreCombustibles(),this.restoreText(),this.burnSurfaces.reset(),this.awardedObjects.clear(),this.pointSources.clear(),this.dirty=!0,this.lastScan=-1/0}destroy(){this.artwork.dispose(),this.autoPaint?.dispose(),this.autoPaint=null,this.selection.dispose(),this.clearPaintSurfaces(),this.clearPaintTransitions(),this.restoreCrushables(),this.restoreCombustibles(),this.restoreText(),this.burnSurfaces.reset(),this.walls=[],this.liquidElements=[]}},pi=class{runtime;held=new Set;touch={throttle:0,steer:0,action:!1,boost:!1};arrival=null;arrivalResolve=null;pendingArrival=null;pendingSlotPresses=new Set;ghostPreview=!1;constructor(e){this.runtime=e}get options(){return this.runtime.options()}get world(){return this.runtime.scene()?.world??null}get playground(){return this.runtime.scene()?.playground??null}get simulation(){return this.runtime.scene()?.simulation??null}get renderer(){return this.world?.renderer??null}get collisions(){return this.runtime.scene()?.collisions??null}get odometer(){return this.runtime.scene()?.odometer??null}get sound(){return this.runtime.audio()}resetFrameClock=()=>this.runtime.resetClock();host=(e,...t)=>Ce(this.runtime.report,e,...t);stopArrival=(e=`interrupted`)=>{this.pendingArrival&&=(clearTimeout(this.pendingArrival.timeout),this.pendingArrival.resolve(e),null),this.arrival&&(this.renderer?.setVehicleArrivalOpacity(1),this.arrivalResolve?.(e),this.arrivalResolve=null),this.arrival=null};enterAt=e=>{let t=e.delayMs??0;return!Number.isFinite(t)||t<0?Promise.resolve(`unavailable`):t===0?this.startArrival(e):(this.stopArrival(),new Promise(n=>{let r=setTimeout(()=>{this.pendingArrival=null,this.startArrival(e).then(n)},t);this.pendingArrival={timeout:r,resolve:n}}))};startArrival=e=>{let t=this.simulation,n=this.renderer;if(!t||!n||t.paused||t.mode!==`car`)return Promise.resolve(`unavailable`);let r=i(e,t,n.documentScale());if(!r)return Promise.resolve(`unavailable`);if(window.matchMedia(`(prefers-reduced-motion: reduce)`).matches){let e=this.handle.parkAt({xPx:r.destination.x,yPx:r.destination.y,angleRad:r.headingRad});return Promise.resolve(e?`completed`:`unavailable`)}this.stopArrival(),this.held.clear(),this.touch={throttle:0,steer:0,action:!1,boost:!1},t.body.position=n.worldFromDocument(r.start),t.body.angle=r.headingRad,t.body.velocity=r.velocity,t.body.spin=0,n.interruptFollow();let o=new a(r.fadeDurationSeconds,r.steer,r.serviceBrake);return this.arrival=o,n.beginVehicleArrivalFade(),new Promise(e=>{this.arrivalResolve=e})};paintedCar=(e=this.simulation)=>{let t=this.renderer,n=this.collisions;if(!this.options.overlay||!e||!t||!n||e.mode!==`car`)return null;let r=n.vehicleMask(e.car.preset),i=k(t.documentPoint(e.body.position),t.carVisualOffset(e)),a=E(Math.cos(e.body.angle),-Math.sin(e.body.angle));return{mask:r,shape:{center:i,forward:a,side:E(-a.y,a.x),halfLength:r.lengthM*t.documentScale()/2,halfWidth:r.widthM*t.documentScale()/2}}};carAnchor=()=>{let e=this.paintedCar();if(!e)return null;let t=R(e.mask.alpha,e.shape),n=this.renderer?.virtualOffset()??E(),r=this.renderer?.presentationScale()??1;return{x:(t.x-n.x-window.scrollX)*r+window.scrollX,y:(t.y-n.y-window.scrollY)*r+window.scrollY,width:t.width*r,height:t.height*r}};clearEffects=()=>{this.world?.fadeEffects()};resetScene=()=>{this.playground?this.playground.reset():this.world?.resetScene()};resetDistance=()=>{let e=this.odometer;e&&e.reset()};cycleDistanceDpi=()=>{let e=this.odometer;return e?e.cycleDpi():gt};touchChange=e=>{this.touch=e,!this.options.paused&&(e.throttle||e.steer||e.action||e.boost)&&(this.renderer?.resumeFollow(),this.host(this.options.onDriveInput),this.options.audioEnabled&&(this.host(this.options.onAudioInteraction),this.sound?.start()))};handle={enterAt:this.enterAt,setSlowMo:(e,t)=>{let n=this.world?.slowMo;n&&(t&&n.configure(t),n.setActive(e))},setLighting:e=>{let t=this.renderer;t&&(t.setVehicleLighting(e),this.host(this.options.onLightingChange,t.getVehicleLighting()))},getLighting:()=>this.renderer?.getVehicleLighting()??xe(),toggleLight:e=>{let t=this.renderer;if(t){let n=t.toggleVehicleLight(e);this.host(this.options.onLightingChange,n)}},startAudio:()=>{this.options.audioEnabled&&this.sound?.start()},getVehicle:e=>e?this.world?.getVehicle(e)??null:this.world?.focusVehicle??null,getCarAnchor:this.carAnchor,setPreset:e=>{let t=this.world;t?.playerVehicle&&t.configureVehicle(t.playerVehicle.id,{preset:e})},getPresetId:()=>this.simulation?.car.preset.id??null,getPose:()=>{let e=this.simulation,t=this.renderer;if(!e||!t||e.mode!==`car`)return null;let n=t.documentPoint(e.body.position);return{xPx:n.x,yPx:n.y,angleRad:e.body.angle}},getPathView:()=>{let e=this.simulation,t=this.renderer;if(!e||!t||e.mode!==`car`)return null;let n=t.documentPoint(e.body.position);return{pose:{xPx:n.x,yPx:n.y,angleRad:e.body.angle},pixelsPerMeter:t.documentScale(),sceneScroll:t.sceneScroll()}},clearEffects:this.clearEffects,getPlayground:()=>this.playground,reset:this.resetScene,getDistance:()=>this.odometer?.readout??gt,resetDistance:this.resetDistance,cycleDistanceDpi:this.cycleDistanceDpi,addLiquid:(e,t)=>{let n=this.renderer;if(!n)return!1;let r,i=typeof t.at==`string`?document.querySelector(t.at):t.at;if(!i)return!1;if(i instanceof Element){let e=i.getBoundingClientRect(),t=n.virtualOffset();r={x:e.left+e.width/2+window.scrollX+t.x,y:e.top+e.height/2+window.scrollY+t.y}}else r={x:i.xPx,y:i.yPx};return n.addLiquid(e,{...t,at:n.worldFromDocument(r)}),!0},ejectLiquid:(e=`oil`,t)=>{let n=this.simulation;n&&this.renderer?.ejectLiquid(n,g(e),t?v(t):void 0)},resetTo:e=>{let t=this.simulation,n=this.renderer;return!t||!n||!Number.isFinite(e.xPx)||!Number.isFinite(e.yPx)||e.angleRad!==void 0&&!Number.isFinite(e.angleRad)?!1:(this.stopArrival(),this.world?.resetEffects(),this.world?.focusVehicle?.reset(),this.resetFrameClock(),t.body.position=n.worldFromDocument(E(e.xPx,e.yPx)),t.body.angle=e.angleRad??-Math.PI/2,t.barrier=this.options.overlay&&this.options.viewportWalls,this.held?.clear(),this.sound?.setHorn(!1),!0)},parkAt:e=>{let t=this.simulation,n=this.renderer;if(!t||!n||![e.xPx,e.yPx,e.angleRad].every(Number.isFinite))return!1;this.stopArrival();let r=this.world?.focusVehicle?.id;return r&&this.playground?.zones.relocateVehicle(r),t.body.position=n.worldFromDocument(E(e.xPx,e.yPx)),t.body.angle=e.angleRad,t.body.velocity=E(),t.body.spin=0,this.resetFrameClock(),this.touch={throttle:0,steer:0,action:!1,boost:!1},n.interruptFollow(),!0},saveState:()=>this.world?.saveState()??null,restoreState:e=>{let t=this.world;return!t||e.world!==t||!e.available?!1:(this.stopArrival(),this.held?.clear(),this.touch={throttle:0,steer:0,action:!1,boost:!1},this.sound?.setHorn(!1),this.resetFrameClock(),t.restoreState(e),this.sound?.setPreset(t.sim.car.preset),!0)}};readInput=()=>{let e=Ae(this.held),t=this.touch;return{throttle:t.throttle||e.throttle,steer:t.steer||e.steer,action:t.action||e.action,boost:!!t.boost||!!e.boost,slots:e.slots,slotPresses:[...this.pendingSlotPresses],machineGun:!!e.machineGun,flamethrower:!!e.flamethrower,rocket:!!t.rocket,ghost:!!e.ghost||this.ghostPreview}};keyDown=e=>{let t=this.runtime.scene();if(!t)return;let{simulation:n,world:r,collisions:i}=t,a=r.renderer,o=this.held;if(!(e.defaultPrevented||e.composedPath().some(e=>e instanceof Element&&e.matches(`[data-jr-ui],[data-jr-touch-controls]`)))){if(this.options.paused){let t=e.code===`Space`&&e.target instanceof Element&&!!e.target.closest(`button,a,summary,[role="button"],[role="link"]`);!this.options.onStartRequest||e.metaKey||e.ctrlKey||e.altKey||je(e)||t||!V.has(e.code)&&e.code!==`KeyH`||(e.preventDefault(),o.add(e.code),a.resumeFollow(),e.code===`KeyH`&&n.mode===`car`&&this.sound?.setHorn(!0),this.host(this.options.onStartRequest))}else if(!(e.metaKey||e.ctrlKey||e.altKey||je(e))&&!(e.code===`Space`&&e.target instanceof Element&&e.target.closest(`button,a,summary,[role="button"],[role="link"]`))&&((V.has(e.code)||Me.has(e.code)||e.code===`KeyH`)&&e.preventDefault(),V.has(e.code)&&!o.has(e.code)&&a.resumeFollow(),e.code===`KeyH`&&!o.has(`KeyH`)&&n.mode===`car`&&this.sound?.setHorn(!0),/^Digit[1-9]$/.test(e.code)&&!o.has(e.code)&&this.pendingSlotPresses.add(Number(e.code.slice(-1))),o.add(e.code),(V.has(e.code)||e.code===`KeyH`)&&(V.has(e.code)&&!e.repeat&&n.mode===`car`&&this.host(this.options.onDriveInput),n.mode===`car`&&this.options.audioEnabled&&(this.host(this.options.onAudioInteraction),this.sound?.start())),!e.repeat))switch(e.code){case`KeyV`:r.slowMo.start();break;case`KeyU`:{let e=a.toggleVehicleLight(`underglow`);this.host(this.options.onLightingChange,e);break}case`KeyC`:this.resetScene();break;case`KeyF`:a.flashTargets((e,t)=>i.paintTargetMask(e,t));break;case`KeyP`:n.paused=!n.paused,this.runtime.resetClock();break;case`KeyB`:this.options.overlay||(n.barrier=!n.barrier);break;case`KeyG`:this.options.overlay||(n.gravity=!n.gravity);break;case`KeyZ`:this.options.overlay||(a.deadZone=!a.deadZone);break;case`Escape`:this.host(this.options.onExit)}}};keyUp=e=>{this.held.delete(e.code),e.code===`KeyV`&&this.runtime.scene()?.world.slowMo.stop(),e.code===`KeyH`&&this.sound?.setHorn(!1)};allowFollow=()=>!this.arrival;neutral={throttle:0,steer:0,action:!1,boost:!1};selectInput=(e,t)=>{let n=this.runtime.scene();if(!n)return{controls:this.neutral};let r=n.simulation,i=n.world.renderer,a=this.readInput();(this.arrival||this.pendingArrival)&&(a.throttle!==0||a.steer!==0||a.action||a.boost||a.slots?.length||a.slotPresses?.length||a.machineGun||a.flamethrower||a.rocket||a.ghost&&!this.ghostPreview)&&this.stopArrival();let o=this.arrival,s=!t&&!o&&!this.options.automatedInput,c=this.neutral,l;return t||(o?(c=o.drive(r,i.documentPoint(r.body.position),i.documentScale(),e,e=>i.worldFromDocument(e)),i.setVehicleArrivalOpacity(o.opacity),l=()=>{o.complete&&this.stopArrival(`completed`)}):c=this.options.automatedInput??a),this.ghostPreview&&(c={...c,ghost:!0}),{controls:c,userDriven:s,manualMoved:t,allowFollow:this.allowFollow,afterPhysics:()=>{l?.()}}};get hasArrival(){return this.arrival!==null}get hornHeld(){return this.held.has(`KeyH`)}releaseInput(){this.held.clear(),this.pendingSlotPresses.clear(),this.runtime.scene()?.world.slowMo.stop(),this.sound?.setHorn(!1)}pauseInput(){this.runtime.resetClock(),this.touch={throttle:0,steer:0,action:!1,boost:!1}}beginPlacement(){this.stopArrival(),this.simulation?.resetAtCurrentPose(),this.held.clear(),this.sound?.setHorn(!1)}afterStep(e){e||this.pendingSlotPresses.clear()}presentationInput(){let e=this.world,t=this.simulation;return!e||!t||t.paused?this.neutral:this.arrival||this.options.automatedInput?t.lastInput:this.readInput()}dispose(){this.releaseInput(),this.stopArrival(),this.touch={throttle:0,steer:0,action:!1,boost:!1}}};function mi({canvas:e,sim:t,renderer:n,collisions:r,game:i},a){let o=null,s=null,c=!1,l=0,u=``,d=()=>{if(s?.target)try{s.target.releasePointerCapture(s.pointerId)}catch{}s?.moved&&(t.body.velocity=E(),t.body.spin=0,document.documentElement.style.cursor=u),s=null},f=e=>n.documentFromViewport(E(e.clientX,e.clientY)),p=e=>{if(!a.options().showVehicle)return null;let t=a.paintedCar();if(!t)return null;let n=f(e);return z(t.mask.alpha,t.shape,{x:n.x-2,y:n.y-2,width:4,height:4})?t:null},m=!1,h=``,g=!1,_=null,v=``,y=0,b=null,x=e=>{let t=a.toolbar?.();t&&(t.dataset.visible=e?`true`:`false`,t.inert=!e)},S=()=>{y=0,g&&(document.documentElement.style.cursor=v),g=!1,_=null,r.setHoveredVehicle(null),x(!1)},C=()=>{let e=a.toolbar?.();if(!e||!_)return;let t=a.paintedCar(_.sim);if(!t)return;let r=R(t.mask.alpha,t.shape),i=n.viewportFromDocument(E(r.x+r.width,r.y)),o=i.x,s=i.y,c=e.getBoundingClientRect().width,l=e.getBoundingClientRect().height,u=Math.max(8,Math.min(window.innerWidth-c-8,o+8)),d=Math.max(8,Math.min(window.innerHeight-l-8,s-8));e.style.left=`${u}px`,e.style.top=`${d}px`},D=e=>{b=E(e.clientX,e.clientY);let t=a.toolbar?.();if(s?.moved||a.options().paused||n.vehicleMarkerAt(E(e.clientX,e.clientY))||document.querySelector(`[data-jr-popover-host]`)){y&&window.clearTimeout(y),S();return}let o=!!t&&e.composedPath().includes(t),c=t?.getBoundingClientRect(),l=g&&!!a.options().showToolbar&&!!c&&e.clientX>=c.left-20&&e.clientX<=c.right+20&&e.clientY>=c.top-20&&e.clientY<=c.bottom+20,u=!o&&p(e),d=!!u||o||l;!d&&g?y||=window.setTimeout(S,180):(y&&=(window.clearTimeout(y),0),d&&!g&&(v=document.documentElement.style.cursor,g=!0),d&&!o&&(document.documentElement.style.cursor=`pointer`),x(d&&!!a.options().showToolbar),!(!d||o||l&&!u)&&(_=i.focusVehicle??null,r.setHoveredVehicle(_?.id??null),C()))},O=t=>{let n=e.getBoundingClientRect();return E(t.clientX-n.left,t.clientY-n.top)},A=r=>{if(e.focus(),r.button!==0||t.mode!==`brick`||o)return;let i=O(r),a=t.body.local(n.world(i));Math.abs(a.x)>2||Math.abs(a.y)>1||(o={pointerId:r.pointerId,local:a,start:i,current:i},e.setPointerCapture(r.pointerId))},j=e=>{if(!o||e.pointerId!==o.pointerId)return;o.current=O(e);let n=w(o.current,o.start),r=P(n),i=r>250?T(n,250/r):n;t.brickForce={local:o.local,force:T(E(i.x,-i.y),65)}},M=e=>{o&&e.pointerId===o.pointerId&&(o=null,t.brickForce=null)},N=r=>{if(!a.options().overlay||!a.options().showVehicle||t.mode!==`car`||s||!r.isPrimary||r.button!==0||document.querySelector(`[data-jr-popover-host]`))return;let i=n.vehicleMarkerAt(E(r.clientX,r.clientY));if(!i&&(a.options().paused||!a.options().canPlaceManually||r.target instanceof Element&&r.target.closest(`[data-jr-ui],[data-jr-touch-controls]`)||!p(r)))return;r.preventDefault(),i&&e.focus({preventScroll:!0});let o=f(r),c=n.documentPoint(t.body.position),l=w(o,c),u=Math.atan2(-l.y,l.x);s={pointerId:r.pointerId,target:r.target instanceof Element?r.target:null,startClient:E(r.clientX,r.clientY),grabOffset:i?E():w(c,o),startAngle:t.body.angle,pointerAngle:u,polarRotation:P(l)>20,mode:!i&&r.shiftKey&&P(t.body.velocity)<.45?`rotate`:`move`,moved:!1,marker:i??void 0,lastTime:r.timeStamp}},F=e=>{if(!s||e.pointerId!==s.pointerId)return;let i=w(E(e.clientX,e.clientY),s.startClient);if(!s.moved&&P(i)<5||s.marker&&(s.marker.sim!==t||!a.options().canPlaceManually||a.options().paused))return;if(!s.moved){s.moved=!0,a.beginPlacement(),s.marker?n.interruptFollow():n.resumeFollow(),u=document.documentElement.style.cursor,document.documentElement.style.cursor=`grabbing`,x(!1),s.marker&&(t.body.position=n.worldFromDocument(f(e)),t.body.velocity=E(),t.body.spin=0);try{s.target?.setPointerCapture(e.pointerId)}catch{}}e.preventDefault(),e.stopImmediatePropagation();let o=Math.max(1/120,Math.min(.05,(e.timeStamp-s.lastTime)/1e3||1/120));s.lastTime=e.timeStamp;let c=f(e),l=n.documentScale();if(s.mode===`rotate`){let e=n.documentPoint(t.body.position),l=s.polarRotation?Math.atan2(-(c.y-e.y),c.x-e.x):0,u=s.polarRotation?Math.atan2(Math.sin(l-s.pointerAngle),Math.cos(l-s.pointerAngle)):i.x/80,d=t.body.angle;t.body.angle=s.startAngle+u,t.body.spin=Math.max(-8,Math.min(8,Math.atan2(Math.sin(t.body.angle-d),Math.cos(t.body.angle-d))/o)),r.step(t,n,o,a.options().overlay&&t.barrier)}else{let e=n.documentPoint(t.body.position),i=k(c,s.grabOffset),u=w(i,e),d=r?.vehicleMask(t.car.preset),f=Math.max(6,(d?.widthM??t.car.preset.geometry.widthM)*l/3),p=Math.max(1,Math.ceil(P(u)/f));for(let i=1;i<=p;i++){let s=k(e,T(u,i/p)),c=n.documentPoint(t.body.position);t.body.position=n.worldFromDocument(s);let d=w(s,c),f=E(d.x/l/(o/p),-d.y/l/(o/p)),m=P(f);if(t.body.velocity=m>35?T(f,35/m):f,r.step(t,n,o/p,a.options().overlay&&t.barrier),P(w(n.documentPoint(t.body.position),s))>2)break}}t.body.velocity=E(),t.body.spin=0,s.marker||n.followDocument(t)},I=e=>{if(s&&e.pointerId===s.pointerId){if(s.marker&&!s.moved&&e.type!==`pointercancel`&&(e.preventDefault(),e.stopImmediatePropagation(),n.revealVehicle(s.marker.sim)),s.moved||s.marker){e.preventDefault(),e.stopImmediatePropagation(),c=!0,l&&window.clearTimeout(l),l=window.setTimeout(()=>{c=!1,l=0},0);try{s.target?.releasePointerCapture(e.pointerId)}catch{}}d()}},L=e=>{if(c){c=!1,e.preventDefault(),e.stopImmediatePropagation();return}if(e.target instanceof Element&&e.target.closest(`[data-jr-ui]`)||!a.options().onCarClick)return;let t=p(e);t&&(e.preventDefault(),e.stopPropagation(),a.carClicked(R(t.mask.alpha,t.shape)))},ee=e=>{e.target instanceof Element&&e.target.closest(`[data-jr-touch-controls]`)||n.interruptFollow()};return{get moved(){return!!s?.moved},clear(){d(),t.brickForce=null,o=null},dragArrow(){let e=o?t.body.world(o.local):null;return o&&e?{from:e,to:k(e,w(n.world(o.current),n.world(o.start)))}:null},present(){if(!s?.moved&&b&&!a.options().paused){let e=n.vehicleMarkerAt(b);e&&!g?(m||=(h=document.documentElement.style.cursor,!0),document.documentElement.style.cursor=e.sim===t&&a.options().canPlaceManually?`grab`:`pointer`):m&&=(document.documentElement.style.cursor=h,!1)}if(_&&i.getVehicle(_.id)!==_)S();else if(g&&(a.options().paused||document.querySelector(`[data-jr-popover-host]`)))y&&window.clearTimeout(y),S();else if(g){C();let e=a.toolbar?.(),t=_?a.paintedCar(_.sim):null,n=b,r=n?f({clientX:n.x,clientY:n.y}):null,i=!!t&&!!r&&z(t.mask.alpha,t.shape,{x:r.x-2,y:r.y-2,width:4,height:4}),o=e?.getBoundingClientRect(),s=!!n&&!!o&&n.x>=o.left&&n.x<=o.right&&n.y>=o.top&&n.y<=o.bottom;!i&&!s?y||=window.setTimeout(S,180):y&&=(window.clearTimeout(y),0)}},listen(t){t.listen(window,`pointerdown`,N,!0),t.listen(window,`pointermove`,F,{capture:!0,passive:!1}),t.listen(window,`pointermove`,D,!0),t.listen(window,`pointerup`,I,!0),t.listen(window,`pointercancel`,I,!0),t.listen(window,`click`,L,!0),t.listen(window,`wheel`,ee,{passive:!0}),t.listen(window,`touchmove`,ee,{passive:!0}),t.listen(e,`pointerdown`,A),t.listen(e,`pointermove`,j),t.listen(e,`pointerup`,M),t.listen(e,`pointercancel`,M)},dispose(){d(),t.brickForce=null,o=null,y&&window.clearTimeout(y),l&&window.clearTimeout(l),S(),m&&(document.documentElement.style.cursor=h)}}}function hi(e){for(let t of Object.keys(e))if(!Object.hasOwn(Pe,t))throw TypeError(`Unknown browser session option: ${t}`);let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)),n=Se(t);return{...Ne,...t,...n,initialAngle:e.initialAngle??(e.overlay??Ne.overlay?-Math.PI/2:0)}}function gi(e,t,n){let r={...e,...n},i=hi(r);for(let e of Fe)if(i[e]!==t[e])throw TypeError(`Browser session option ${e} is fixed at mount; create a new session to change it`);return{authored:r,options:i}}function _i(e,t,n){bt(e,t,n),n&&n.showVehicle===t.showVehicle||(e.primaryVehicleVisible=t.showVehicle),n||e.setAbsoluteViewport(),n&&n.screenShakeProfiles===t.screenShakeProfiles||e.setScreenShakeProfiles(t.screenShakeProfiles)}var vi=e({BrowserSessionCore:()=>yi}),yi=class{canvas;presentation;rendering;options;authoredOptions;resources=new r;releaseLayers;disposed=!1;odometer=null;simulation=null;renderer=null;world=null;playground=null;boundSpecs=void 0;bindings=[];collisions=null;sound=null;controller;scene=null;resetFrameClock=()=>{};constructor(e,t={},n,r){this.canvas=e,this.presentation=n,this.rendering=r,this.authoredOptions={...t},this.options=hi(this.authoredOptions),this.controller=new pi({scene:()=>this.scene,options:()=>this.options,audio:()=>this.sound,resetClock:()=>this.resetFrameClock(),report:e=>this.report(e)});try{if(this.resources.own(()=>this.releaseLayers?.()),this.options.overlay){let e=document.createElement(`style`);e.dataset.jrBrowserStyles=``,e.textContent=an,this.resources.own(()=>e.remove()),document.head.append(e);let t=this.rendering.installPageLayers(this.options.foregroundSelector);this.releaseLayers=()=>t.dispose()}let e=this.mount();e&&this.resources.own(e)}catch(e){throw this.dispose(),e}}report=e=>{let t=this.playground?.registry??this.options.playground;t?t.report(e):console.error(`JoyRide host callback failed`,e)};host=(e,...t)=>Ce(this.report,e,...t);get handle(){return this.controller.handle}touchChange=e=>{this.disposed||this.controller.touchChange(e)};update(e){if(this.disposed)throw Error(`Browser session is disposed`);let t=this.options,{authored:n,options:r}=gi(this.authoredOptions,t,e);if(this.authoredOptions=n,this.options=r,t.vehicleDestructible!==this.options.vehicleDestructible&&this.world?.setVehicleDestructible(this.options.vehicleDestructible),t.toolsEnabled!==this.options.toolsEnabled&&this.world?.setToolsEnabled(this.options.toolsEnabled),t.mode!==this.options.mode){let e=this.simulation;e&&this.options.mode&&e.mode!==this.options.mode&&(this.world?.focusVehicle?.setMode(this.options.mode),this.renderer?.reset())}if(t.preset!==this.options.preset){let e=this.world;e?.playerVehicle&&e.configureVehicle(e.playerVehicle.id,{preset:this.options.preset})}if(t.paused!==this.options.paused&&(this.simulation&&(this.simulation.paused=this.options.paused),this.options.paused&&this.controller.pauseInput()),t.paused!==this.options.paused||t.audioEnabled!==this.options.audioEnabled){let e=this.simulation;this.options.paused&&!this.options.audioEnabled&&e&&this.renderer?.restorePage(e)}if(t.overlay!==this.options.overlay||t.viewportWalls!==this.options.viewportWalls){let e=this.world?.playerVehicle;e&&(e.sim.barrier=this.options.overlay&&this.options.viewportWalls)}t.idleSound!==this.options.idleSound&&this.sound?.setIdleSound(this.options.idleSound),t.masterVolume!==this.options.masterVolume&&this.sound?.setMasterVolume(this.options.masterVolume),t.showHealthBars!==this.options.showHealthBars&&this.collisions?.setShowHealthBars(this.options.showHealthBars),t.destructibleBurnSeconds!==this.options.destructibleBurnSeconds&&this.collisions?.setDestructibleBurnSeconds(this.options.destructibleBurnSeconds),t.deform!==this.options.deform&&this.world?.setDeformationEnabled(this.options.deform),this.renderer&&_i(this.renderer,this.options,t),t.audioEnabled!==this.options.audioEnabled&&this.updateAudio(),(t.autoPaint!==this.options.autoPaint||t.overlay!==this.options.overlay)&&this.collisions?.setAutoPaint(this.options.overlay&&this.options.autoPaint),(t.overlay!==this.options.overlay||t.foregroundSelector!==this.options.foregroundSelector)&&(this.releaseLayers?.(),this.releaseLayers=(()=>{if(!this.options.overlay)return;let e=this.rendering.installPageLayers(this.options.foregroundSelector);return()=>e.dispose()})()),t.bindings!==this.options.bindings&&this.replaceBindings()}updateAudio(){let e=this.sound;e&&(this.options.audioEnabled?e.start():this.options.audioEngine?e.setActive(!1):(e.stop(),this.sound=new f(this.simulation?.car.preset??this.options.preset,{idleSound:this.options.idleSound,masterVolume:this.options.masterVolume})))}replaceBindings(){let e=this.playground?.registry;if(!e||this.boundSpecs===this.options.bindings)return;let t=this.boundSpecs;for(let e of this.bindings)e.dispose();try{this.bindings=e.bindAll(this.options.bindings??[]),this.boundSpecs=this.options.bindings}catch(n){this.bindings=e.bindAll(t??[]),e.report(n)}}mount(){let e=this.canvas;if(!e)return;let t=new r,i=()=>t.dispose();try{let r=new N;r.setMode(this.options.mode??this.options.initialMode),r.setPreset(this.options.preset),r.paused=this.options.paused||this.options.initialArrivalPending,r.body.angle=this.options.initialAngle,r.barrier=this.options.overlay&&this.options.viewportWalls;let a=new this.rendering.Renderer(e,this.options.overlay,this.options.quality);this.options.initialArrivalPending&&a.setVehicleArrivalOpacity(0);let o=()=>a.dispose();t.own(o),this.options.initialGroundMarks?.length&&a.seedGroundMarks(this.options.initialGroundMarks),this.options.initialPuddles?.length&&a.setInitialPuddles(this.options.initialPuddles.flatMap(e=>{let t=e.target.current?.getBoundingClientRect();return t?[{kind:e.kind,color:e.color,point:E(t.left+t.width/2+window.scrollX,t.top+t.height/2+window.scrollY),amount:e.amount}]:[]}));let s=new vt;t.own(()=>s.flush()),this.odometer=s;let c=()=>s.flush(),l=0;if(this.options.overlay&&this.options.spawnTarget?.current){let e=this.options.spawnTarget.current.getBoundingClientRect();r.body.position=a.world(E(e.left+e.width/2,e.top+e.height/2))}let u=this.options.audioEngine??new f(this.options.preset,{idleSound:this.options.idleSound,masterVolume:this.options.masterVolume});this.options.audioEngine||t.own(()=>(this.sound??u).stop());let d=new fi({sceneOffset:()=>a.virtualOffset(),projection:a.documentProjection}),p=()=>d.destroy();t.own(p);let m=this.options.overlay?this.options.playground??new n(document,this.options.definitions):null;m&&(this.options.playground||t.own(()=>m.dispose()),d.setPlayground(m),this.bindings=m.bindAll(this.options.bindings??[]),this.boundSpecs=this.options.bindings,t.own(()=>{for(let e of this.bindings)e.dispose();this.bindings=[]}));let h=new tt(r,a,s,()=>this.sound??u,this.options.overlay,d,{vehicleDestructible:this.options.vehicleDestructible,toolsEnabled:this.options.toolsEnabled,autoPaint:this.options.overlay&&this.options.autoPaint});t.disown(o),t.disown(p);let g=new rn(h,m);t.own(()=>g.dispose()),this.world=h;let _=g.page;this.playground=_,this.scene={world:h,playground:_,simulation:r,collisions:d,odometer:s},t.own(()=>this.controller.dispose()),h.setDeformationEnabled(this.options.deform),_i(a,this.options),d.prepare(this.options.preset),d.setShowHealthBars(this.options.showHealthBars),d.setDestructibleBurnSeconds(this.options.destructibleBurnSeconds),u.setIdleSound(this.options.idleSound),u.setMasterVolume(this.options.masterVolume),this.simulation=r,this.renderer=a,this.collisions=d,this.sound=u;let v=mi({canvas:e,sim:r,renderer:a,collisions:d,game:h},{options:()=>this.options,toolbar:()=>this.host(this.presentation.toolbar),paintedCar:this.controller.paintedCar,beginPlacement:()=>this.controller.beginPlacement(),carClicked:e=>this.host(this.options.onCarClick,e)});t.own(()=>v.dispose());let y=0,b=new de,x=g.clock(()=>!r.paused&&!document.hidden,e=>D(e),(e,t)=>O(e,t)),S=()=>{x.reset(),b.reset(),this.controller.releaseInput()};this.resetFrameClock=S;let C=()=>{v.clear(),S()},w=()=>{document.hidden&&(C(),this.sound?.setActive(!1))},T=new ResizeObserver(()=>{if(a.resize(),this.options.overlay&&this.options.spawnTarget?.current&&r.paused&&!this.options.audioEnabled&&!this.controller.hasArrival){let e=this.options.spawnTarget.current.getBoundingClientRect();r.body.position=a.world(E(e.left+e.width/2,e.top+e.height/2))}});t.own(()=>T.disconnect()),T.observe(e),this.options.overlay&&T.observe(document.body),this.options.overlay&&this.options.spawnTarget?.current&&T.observe(this.options.spawnTarget.current);let D=e=>{_?.sync(),h.step(this.controller.selectInput(e,v.moved),e),_?.step(e,!r.paused&&!document.hidden),this.controller.afterStep(v.moved)},O=(e,t)=>{_?.sync(),(r.paused||document.hidden)&&_?.step(0,!1);let n=b.sample(e),i=h.focusVehicle;if(!i)return;let o=tn(i,this.sound,h.points,h.totalPoints);_?.present({fps:n,speedMps:P(i.sim.body.velocity),rpm:o.rpm??0,gear:o.gear??`N`,health:i.sim.car.health,points:h.points});let c=this.controller.presentationInput(),u=v.dragArrow();h.present(e,t,c,this.controller.hornHeld,this.options.audioEnabled,this.options.masterVolume,u),v.present(),document.hidden||a.setCameraFrame(this.host(this.presentation.cameraFrame)??null),e-l>=2e3&&(s.flush(),l=e),this.options.onStateChange&&e-y>100&&(this.host(this.options.onStateChange,h.snapshot()),y=e)};return(this.options.toolsEnabled||this.options.overlay&&document.querySelector(`[data-jr-burnable],[data-jr-combustible]`))&&a.prepareFire(),x.start(),v.listen(t),t.listen(window,`keydown`,this.controller.keyDown),t.listen(window,`keyup`,this.controller.keyUp),t.listen(window,`blur`,C),t.listen(window,`pagehide`,c),t.listen(document,`visibilitychange`,w),m&&queueMicrotask(()=>{this.disposed||this.host(this.options.onReady,h,m)}),()=>{i(),this.playground=null,this.world===h&&(this.world=null),this.sound?.setHorn(!1),s.flush(),this.odometer===s&&(this.odometer=null),this.scene=null,this.resetFrameClock=()=>{},this.simulation=null,this.renderer=null,this.collisions=null,this.sound=null}}catch(e){throw i(),this.world=null,this.playground=null,this.scene=null,this.simulation=null,this.renderer=null,this.collisions=null,this.sound=null,e}}dispose(){this.disposed||(this.disposed=!0,this.resources.dispose())}};export{vi as t};
|