@joy-ride/game 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/THIRD_PARTY_NOTICES.md +35 -0
- package/bookmarklet.d.ts +1 -1
- package/bookmarklet.js +1 -1
- package/embed-assets/boost-2QB6phrp.opus +0 -0
- package/embed-assets/chevrolet-corvette-c8-z06-top-DTz9k7Fu.webp +0 -0
- package/embed-assets/collision-r7KCgXfr.opus +0 -0
- package/embed-assets/crush-CN-lxC7x.opus +0 -0
- package/embed-assets/explosion-DyvbNXFI.opus +0 -0
- package/embed-assets/ferrari-812-superfast-top-C3DkIkN7.webp +0 -0
- package/embed-assets/fire-BYgTEP5X.opus +0 -0
- package/embed-assets/gunfire-DUWyQGGm.opus +0 -0
- package/embed-assets/mazda-mx5-nd-top-CLqHp7ox.webp +0 -0
- package/embed-assets/mazda-rx7-fd-top-C3bZMAQw.webp +0 -0
- package/embed-assets/mclaren-720s-top-8TdR01SB.webp +0 -0
- package/embed-assets/nissan-gtr-r35-top-DSpGgr3L.webp +0 -0
- package/embed-assets/ram-2500-top-B653eJDL.webp +0 -0
- package/embed-assets/ricochet-BTW-Iqeu.opus +0 -0
- package/embed-assets/tires-B_97_Y5P.opus +0 -0
- package/embed-assets/toyota-gr-corolla-top-B0NnJP3L.webp +0 -0
- package/embed-assets/toyota-supra-a80-top-BjqFr9TR.webp +0 -0
- package/embed-chunks/{CodeBlock-QLZWgPoe.js → CodeBlock-CpSBaaOX.js} +1 -1
- package/embed-chunks/{Documentation-BJMN2wVe.js → Documentation-8cbCUZ0p.js} +2 -2
- package/embed-chunks/{EmbedPanel-sqS3N8pg.js → EmbedPanel-DCPAjVqp.js} +1 -1
- package/embed-chunks/JoyRideView-CgMxrhvT.js +1 -0
- package/embed-chunks/{configuration~index~embed-0luxl74s.js → configuration~index~embed-ynFxJP_I.js} +1 -1
- package/embed-chunks/configuration~index~embed~bookmarklet-BGiS_NuJ.js +1 -0
- package/embed-chunks/{controls~index~embed-B_C92tUz.js → controls~index~embed-CFqR-DAK.js} +1 -1
- package/embed-chunks/{definitions~index~embed-CDMM_m1T.js → definitions~index~embed-CnmHo4Z4.js} +1 -1
- package/embed-chunks/definitions~index~embed~bookmarklet-CfH2mYuH.js +1 -0
- package/embed-chunks/definitions~index~embed~bookmarklet~vehicle-popover~Documentation~JoyRideView~browser-sessi~fklztn3g-BG7sJuWo.js +1 -0
- package/embed-chunks/runtime~JoyRideView~browser-session-core-D5ZWMVDY.js +1 -0
- package/embed-chunks/runtime~browser-session-core-CDPI_Sw8.js +1 -0
- package/embed-chunks/runtime~index~embed-BdtYsSkV.js +210 -0
- package/embed-chunks/{runtime~index~embed~vehicle-popover~browser-session-core~renderer-YuWj6rHi.js → runtime~index~embed~vehicle-popover~browser-session-core~renderer-ZRVlax1L.js} +1 -1
- package/embed-chunks/{runtime~vehicle-popover-vmgt62ll.js → runtime~vehicle-popover-DRMddEZO.js} +1 -1
- package/embed-chunks/runtime~vehicle-popover~browser-session-core-0GDQdij8.js +1 -0
- package/embed-chunks/runtime~vehicle-popover~browser-session-core~renderer-Cf4rBrLo.js +4 -0
- package/embed-chunks/runtime~vehicle-popover~renderer-JCHjG7Oa.js +849 -0
- package/embed-chunks/src-BJ7McU4o.js +2 -0
- package/embed-chunks/vehicle-catalog~index~embed-DVqfWMzi.js +1 -0
- package/embed-chunks/vehicle-popover-zFwrdc1h.js +1 -0
- package/embed.js +1 -1
- package/{index-BqJy85Tu.d.ts → index-epZszWQ8.d.ts} +15 -117
- package/index.d.ts +2 -2
- package/index.js +1 -1
- package/npm-chunks/{Documentation-Nc7GWFnR.js → Documentation-Cc_tsq8d.js} +2 -2
- package/npm-chunks/{EmbedPanel-DRQcCEA1.js → EmbedPanel-ByMHNOc2.js} +1 -1
- package/npm-chunks/JoyRideView-DHvlq6T7.js +1 -0
- package/npm-chunks/{configuration~react-CgNlw0cC.js → configuration~react-CPx5MlF4.js} +1 -1
- package/npm-chunks/{configuration~react~browser-session-core-CyXr42pk.js → configuration~react~browser-session-core-Ca4_fO4n.js} +1 -1
- package/npm-chunks/configuration~react~vehicle-popover~JoyRideView~browser-session-core~renderer-CPZkP_Db.js +1 -0
- package/npm-chunks/{controls~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-CLDwfJ48.js → controls~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-CoAcght5.js} +1 -1
- package/npm-chunks/{definitions~react~browser-session-core-acRq5AYt.js → definitions~react~browser-session-core-Bc5BhqaX.js} +1 -1
- package/npm-chunks/definitions~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-DcDccU8O.js +1 -0
- package/npm-chunks/definitions~react~vehicle-popover~Documentation~JoyRideView~browser-session-core~renderer-BG7sJuWo.js +1 -0
- package/npm-chunks/runtime~JoyRideView~browser-session-core-DkTKYWMV.js +1 -0
- package/npm-chunks/runtime~browser-session-core-CuS-sVVB.js +1 -0
- package/npm-chunks/{runtime~react-Jmjjtxii.js → runtime~react-DQ3peDbc.js} +1 -1
- package/npm-chunks/runtime~react~browser-session-core-B9a1rLNB.js +1 -0
- package/npm-chunks/runtime~react~vehicle-popover~browser-session-core-CLFQjhrw.js +210 -0
- package/npm-chunks/{runtime~react~vehicle-popover~browser-session-core~renderer-Be8cIaU4.js → runtime~react~vehicle-popover~browser-session-core~renderer-Dmgs7E8f.js} +1 -1
- package/npm-chunks/{runtime~vehicle-popover-PLJOXbUU.js → runtime~vehicle-popover-VyqXHkfB.js} +1 -1
- package/npm-chunks/runtime~vehicle-popover~browser-session-core-DCZajgun.js +1 -0
- package/npm-chunks/runtime~vehicle-popover~browser-session-core~renderer-EswVyRVp.js +4 -0
- package/npm-chunks/runtime~vehicle-popover~renderer-4RpQDOHk.js +849 -0
- package/npm-chunks/theme-CjrpDpKE.js +2 -0
- package/npm-chunks/vehicle-catalog~react~browser-session-core-D5_CJzRM.js +1 -0
- package/npm-chunks/vehicle-catalog~react~vehicle-popover~browser-session-core-sqHgtPeO.js +1 -0
- package/npm-chunks/vehicle-popover-PaJpv-M-.js +1 -0
- package/package.json +1 -1
- package/{playground-DrT_x51v.d.ts → playground-BcoLBJrj.d.ts} +13 -70
- package/react.d.ts +2 -2
- package/react.js +2 -2
- package/embed-assets/attractor-B0xCt_Fj.mp3 +0 -0
- package/embed-assets/boost-BLJDRtPH.mp3 +0 -0
- package/embed-assets/bullet-ricochet-1-BKWD_WRI.mp3 +0 -0
- package/embed-assets/bullet-ricochet-2-CmbSTqg5.mp3 +0 -0
- package/embed-assets/bullet-ricochet-3-DV3Th6nn.mp3 +0 -0
- package/embed-assets/burning-fire--0zItqR0.mp3 +0 -0
- package/embed-assets/collision-hard-b_eauD-v.mp3 +0 -0
- package/embed-assets/collision-medium-Bhw86k_p.mp3 +0 -0
- package/embed-assets/collision-soft-DIwEkPCV.mp3 +0 -0
- package/embed-assets/collision-soft-fVT-mQmJ.mp3 +0 -0
- package/embed-assets/combustible-explosion-XvpDzpm9.mp3 +0 -0
- package/embed-assets/crush-BZKARh2Y.mp3 +0 -0
- package/embed-assets/electric-bolt-Cg9Fmi6S.mp3 +0 -0
- package/embed-assets/electric-charge-zw1IjLo4.mp3 +0 -0
- package/embed-assets/electric-gt-top-DTcvEjMR.webp +0 -0
- package/embed-assets/flamethrower-B5pUrS5p.mp3 +0 -0
- package/embed-assets/ghost-mode-B33_bxYX.mp3 +0 -0
- package/embed-assets/machine-gun-C4ag4X6T.mp3 +0 -0
- package/embed-assets/rocket-explosion-DKnN7_wY.mp3 +0 -0
- package/embed-assets/rocket-launch-C-Yvbb7P.mp3 +0 -0
- package/embed-assets/tire-screech-DEsAg1CH.mp3 +0 -0
- package/embed-chunks/JoyRideView-DaI5oip_.js +0 -1
- package/embed-chunks/configuration~index~embed~bookmarklet-BH7GyoGh.js +0 -1
- package/embed-chunks/definitions~index~embed~bookmarklet-BfjknPZN.js +0 -1
- package/embed-chunks/definitions~index~embed~bookmarklet~vehicle-popover~Documentation~JoyRideView~browser-sessi~fklztn3g-Dt96jol6.js +0 -1
- package/embed-chunks/runtime~JoyRideView~browser-session-core-Bkk9BE6P.js +0 -1
- package/embed-chunks/runtime~browser-session-core-COeP2p6D.js +0 -1
- package/embed-chunks/runtime~index~embed-cWNM8Fsj.js +0 -210
- package/embed-chunks/runtime~vehicle-popover~browser-session-core-CjXpkmYi.js +0 -1
- package/embed-chunks/runtime~vehicle-popover~browser-session-core~renderer-CLLM7CAb.js +0 -4
- package/embed-chunks/runtime~vehicle-popover~renderer-Cx3wjyMH.js +0 -1077
- package/embed-chunks/src-rpwqYZr-.js +0 -2
- package/embed-chunks/vehicle-catalog~index~embed-CZzI6C0M.js +0 -1
- package/embed-chunks/vehicle-popover-C34y-W5W.js +0 -1
- package/npm-chunks/JoyRideView-B3g_Yxhd.js +0 -1
- package/npm-chunks/configuration~react~vehicle-popover~JoyRideView~browser-session-core~renderer-B70Mpi9X.js +0 -1
- package/npm-chunks/definitions~react~vehicle-popover~Documentation~JoyRideView~browser-session-core-BZJqthWX.js +0 -1
- package/npm-chunks/definitions~react~vehicle-popover~Documentation~JoyRideView~browser-session-core~renderer-Dt96jol6.js +0 -1
- package/npm-chunks/runtime~JoyRideView~browser-session-core-CBQyAv9f.js +0 -1
- package/npm-chunks/runtime~browser-session-core-CuLU4VUg.js +0 -1
- package/npm-chunks/runtime~react~browser-session-core-n5P8q7G8.js +0 -1
- package/npm-chunks/runtime~react~vehicle-popover~browser-session-core-BzXBN4rK.js +0 -210
- package/npm-chunks/runtime~vehicle-popover~browser-session-core-Ce3U7qky.js +0 -1
- package/npm-chunks/runtime~vehicle-popover~browser-session-core~renderer-jVG7K050.js +0 -4
- package/npm-chunks/runtime~vehicle-popover~renderer-Dmf1M43y.js +0 -1077
- package/npm-chunks/theme-C4ZE2-nQ.js +0 -2
- package/npm-chunks/vehicle-catalog~react~browser-session-core-BzB5J-Lm.js +0 -1
- package/npm-chunks/vehicle-catalog~react~vehicle-popover~browser-session-core-CX066OIY.js +0 -1
- package/npm-chunks/vehicle-popover-DAESh8qQ.js +0 -1
|
@@ -1,1077 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-XKyaHtl9.js";import{a as t,c as n,i as r,l as i,o as a,r as o,s,u as c}from"./definitions~index~embed~bookmarklet~vehicle-popover~Documentation~JoyRideView~browser-sessi~fklztn3g-Dt96jol6.js";import{r as l}from"./controls~index~embed-B_C92tUz.js";import{r as u,t as d}from"./definitions~index~embed~vehicle-popover~browser-session-core~renderer-RDNEXk_b.js";import{S as f,_ as p,a as m,c as h,g,i as _,l as v,m as y,n as b,o as x,s as S,u as C,x as w}from"./runtime~index~embed~vehicle-popover~browser-session-core~renderer-YuWj6rHi.js";import{i as T}from"./configuration~index~embed~bookmarklet~vehicle-popover~EmbedPanel~Documentation~JoyRideView~~n76yhyet-mgPW9A8j.js";import{n as ee,t as E}from"./configuration~index~embed~bookmarklet~vehicle-popover~EmbedPanel~JoyRideView~browser-sessio~iaaa3ndj-DLfKTakR.js";import{c as D,n as te}from"./configuration~index~embed~bookmarklet-BH7GyoGh.js";import{A as ne,B as re,C as O,F as ie,S as ae,V as k,b as oe,c as se,d as ce,h as le,j as ue,u as de,v as fe,w as pe,x as me,y as he}from"./runtime~vehicle-popover~browser-session-core~renderer-CLLM7CAb.js";var A=[`low`,`medium`,`high`],ge=1e3/60,_e=2e3,ve=8,ye=2e3,be=1e4,xe=12e4,Se=5e3,Ce=class{cap=A.length-1;misses=[];lastTime=null;lastChange=-1/0;lastStepUp=-1/0;stepUpDelay=be;get limit(){return A[this.cap]}apply(e){return A[Math.min(A.indexOf(e),this.cap)]}sample(e,t,n,r){let i=this.lastTime;if(this.lastTime=e,i===null)return!1;let a=e-i;if(!(a>0)||a>250)return!1;for(a>ge*1.5&&t<ge*.8&&n&&this.misses.push(e);this.misses.length&&e-this.misses[0]>_e;)this.misses.shift();if(e-this.lastChange<ye)return!1;let o=A.indexOf(r);return this.misses.length>=ve&&Math.min(this.cap,o)>0?(e-this.lastStepUp<Se&&(this.stepUpDelay=Math.min(xe,this.stepUpDelay*2)),this.cap=Math.min(this.cap,o)-1,this.changed(e),!0):n&&this.cap<o&&!this.misses.length&&e-this.lastChange>=this.stepUpDelay?(this.cap++,this.lastStepUp=e,this.changed(e),!0):!1}restoreLimit(e){this.cap=e?Math.max(0,A.indexOf(e)):A.length-1,this.misses=[],this.lastTime=null}reset(){this.cap=A.length-1,this.misses=[],this.lastTime=null,this.lastChange=this.lastStepUp=-1/0,this.stepUpDelay=be}changed(e){this.lastChange=e,this.misses=[]}};function we(e,t,n){let r=e.size,i=r*.74,a=0,o=0,s=0;for(let c=0;c<6;c++){let l=t*(c+.5)/6*2,u=n*(c+.5)/6*2,d=e.curlX*l*l*l+e.twist*n*2*l*l,f=e.curlY*u*u*u-e.twist*t*1.3*u*u;a+=Math.cos(d)*r*t/6,o+=Math.cos(f)*i*n/6,s+=Math.sin(d)*r*t/6+Math.sin(f)*i*n/6}let c=Math.max(0,t+n-.62);s+=c*c*r*(.35+e.fold);let l=Math.cos(e.tilt),u=Math.sin(e.tilt);return{x:a,y:o*l-s*u,z:o*u+s*l}}var Te=(e,t)=>{let n=Math.imul((e|0)&15^Math.imul(t+17,374761393),668265263);return n=Math.imul(n^n>>>13,1274126177),((n^n>>>16)>>>0)/4294967296},Ee=new Map,De=new Map;function Oe(e){let t=Ee.get(e);if(t)return t;let n=e.replace(/^#/,``),r=/^[\da-f]{3}$/i.test(n)?[...n].map(e=>e+e).join(``):n,i=/^[\da-f]{6}$/i.test(r)?[0,2,4].map(e=>parseInt(r.slice(e,e+2),16)):e.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/)?.slice(1,4).map(Number)??[195,190,174];return Ee.size>=128&&Ee.delete(Ee.keys().next().value),Ee.set(e,i),i}function ke(e,t){let n=Math.round(t),r=`${e}:${n}`,i=De.get(r);if(i)return i;let a=`rgb(${Oe(e).map(e=>Math.max(0,Math.min(255,e+n))).join(` `)})`;return De.size>=512&&De.delete(De.keys().next().value),De.set(r,a),a}function Ae(e,t){e.beginPath(),t.forEach(([t,n],r)=>{r?e.lineTo(t,n):e.moveTo(t,n)}),e.closePath()}function je(e,t,n){let r=Math.max(0,t.z),i=1+Math.min(.65,r/90);e.save(),e.translate(t.x+r*.13,t.y+r*.1),e.rotate(t.angle),e.fillStyle=`#000`,e.globalAlpha=t.opacity*(n?.12:.15)/(1+r/26),e.beginPath(),e.ellipse(0,0,t.size*.46*i,t.size*.27*i,0,0,Math.PI*2),e.fill(),r<5&&(e.globalAlpha*=(1-r/5)*.6,e.beginPath(),e.ellipse(0,0,t.size*.36,t.size*.19,0,0,Math.PI*2),e.fill()),e.restore()}function Me(e,t){let n=[];for(let e=0;e<=2;e++)n.push(Array.from({length:9},(n,r)=>we(t,r/8-.5,e/2-.5)));let r=t.z<.5?Math.max(0,-Math.min(...n.flat().map(e=>e.z))):0,i=e=>[e.x,e.y-(e.z+r)*.48],a=[];for(let e=0;e<2;e++)for(let t=0;t<8;t++){let r=n[e][t],i=n[e][t+1],o=n[e+1][t+1],s=n[e+1][t],c=i.x-r.x,l=i.y-r.y,u=i.z-r.z,d=s.x-r.x,f=s.y-r.y,p=s.z-r.z,m=l*p-u*f,h=u*d-c*p,g=c*f-l*d,_=Math.max(.001,Math.hypot(m,h,g)),v=g+h*.48>0,y=(m*-.35+h*-.45+Math.abs(g)*.7)/_;a.push({a:r,b:i,c:o,d:s,col:t,row:e,front:v,light:y,depth:(r.z+i.z+o.z+s.z)/4})}a.sort((e,t)=>e.depth-t.depth);for(let n of a){let{a:r,b:a,c:o,d:s,front:c,light:l,row:u,col:d}=n;if(Ae(e,[i(r),i(a),i(o),i(s)]),e.fillStyle=ke(t.color,(c?0:-32)+(l-.7)*45),e.fill(),c&&d>0&&d<(u===0?6:8)&&u<3){e.strokeStyle=ke(t.color,-100),e.lineWidth=t.size*(u===0?.027:.013);let n=i({x:(r.x+s.x)*.5,y:(r.y+s.y)*.5,z:(r.z+s.z)*.5}),c=i({x:(a.x+o.x)*.5,y:(a.y+o.y)*.5,z:(a.z+o.z)*.5});if(e.beginPath(),e.moveTo(...n),e.lineTo(...c),e.stroke(),u>0){let t=i({x:r.x*.2+s.x*.8,y:r.y*.2+s.y*.8,z:r.z*.2+s.z*.8}),n=i({x:a.x*.2+o.x*.8,y:a.y*.2+o.y*.8,z:a.z*.2+o.z*.8});e.beginPath(),e.moveTo(...t),e.lineTo(...n),e.stroke()}}}}function Ne(e,t){let n=t.size,r=t.size*(.35+Te(t.seed,61)*.2),i=Math.cos(t.tilt);if(e.scale(1,Math.abs(i)<.08?.08:i),e.beginPath(),e.moveTo(-n*.48,0),e.bezierCurveTo(-n*.15,-r*.7,n*.18,-r*.6,n*.5,-r*.08),e.bezierCurveTo(n*.12,r*.65,-n*.25,r*.45,-n*.48,0),e.fillStyle=ke(t.color,i<0?14:0),e.fill(),e.beginPath(),e.moveTo(-n*.48,0),e.bezierCurveTo(-n*.15,-r*.7,n*.18,-r*.6,n*.5,-r*.08),e.quadraticCurveTo(0,-r*t.fold*.2,-n*.48,0),e.fillStyle=ke(t.color,-13-t.fold*9),e.fill(),e.strokeStyle=ke(t.color,-35),e.lineWidth=.45,e.globalAlpha*=.55,e.beginPath(),e.moveTo(-n*.63,r*.08),e.quadraticCurveTo(-n*.08,-r*t.fold*.2,n*.46,-r*.07),e.stroke(),n>10){e.lineWidth=.3;for(let t of[-.18,.08])e.beginPath(),e.moveTo(n*t,0),e.lineTo(n*(t+.1),-r*.3),e.moveTo(n*t,0),e.lineTo(n*(t-.03),r*.28),e.stroke()}}var Pe=new Map,Fe=0,Ie=0,Le=()=>({sprites:Pe.size,bytes:Fe});function Re(e,t){t.kind===`paper`?Me(e,t):t.kind===`leaf`&&Ne(e,t)}function ze(e){if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(e,e);if(typeof document>`u`||typeof HTMLCanvasElement>`u`)return null;let t=document.createElement(`canvas`);return!(t instanceof HTMLCanvasElement)||!t.getContext?null:(t.width=t.height=e,t)}function Be(e,t,n){if(t.z>.1||Math.abs(t.vz)>.1||Math.hypot(t.vx,t.vy)>.75||t.kind===`paper`&&Math.abs(t.curlVelocityX)+Math.abs(t.curlVelocityY)+Math.abs(t.twistVelocity)>.03)return!1;let r=Math.max(4,Math.round(t.size/4)*4),i=Math.round(t.fold*5)/5,a=Math.cos(t.tilt)<0?4:0,o=a*Math.PI/4;if(Math.abs(Math.sin(t.tilt))>.015)return!1;let s=Math.round(t.curlX*4)/4,c=Math.round(t.curlY*4)/4,l=Math.round(t.twist*4)/4,u=`${s}:${c}:${l}:${t.kind}:${t.seed&15}:${t.color}:${r}:${i}:${a}:${n}`,d=Pe.get(u),f={...t,size:r,fold:i,tilt:o,curlX:s,curlY:c,twist:l,opacity:1};if(!d){let e=r*1.4+4,t=Math.ceil(e*n),i=t*t*4;if(Pe.size>=128||Fe+i>8388608){for(let[e,t]of Pe)if(!(Ie-t.used<120)&&(Pe.delete(e),`close`in t.canvas&&t.canvas.close(),Fe-=t.bytes,Pe.size<128&&Fe+i<=8388608))break}if(Pe.size<128&&Fe+i<=8388608){let r=ze(t),a=r?.getContext(`2d`);r&&a&&(a.scale(n,n),a.translate(e/2,e/2),Re(a,f),d={canvas:`transferToImageBitmap`in r?r.transferToImageBitmap():r,extent:e,bytes:i,used:Ie},Pe.set(u,d),Fe+=i)}}return e.scale(t.size/r,t.size/r),d?(d.used=Ie,e.drawImage(d.canvas,-d.extent/2,-d.extent/2,d.extent,d.extent)):(e.save(),Re(e,f),e.restore()),!0}function Ve(e,t,n,r,i=`ground`){i===`ground`&&Ie++;let a=e.getTransform(),o=Math.min(8,Math.max(1,Math.ceil(Math.hypot(a.a,a.b)))),s=n.x+n.width,c=n.y+n.height;for(let a of t){if(a.opacity<=0)continue;let t=a.size+Math.max(0,a.z)*.35;a.x+t<n.x||a.x-t>s||a.y+t<n.y||a.y-t>c||(i===`ground`&&je(e,a,r),i===`ground`==a.z<4&&(e.save(),e.translate(a.x,a.y-Math.max(0,a.z)*.22),e.rotate(a.angle),e.globalAlpha=a.opacity,Be(e,a,o)||Re(e,a),e.restore()))}}function He(e){let{tireLengthM:t,tireWidthM:n}=e.geometry;return e.image?{length:t*(e.image.wheelVisualScale?.length??.64),width:n*(e.image.wheelVisualScale?.width??.82)}:{length:t,width:n}}function Ue(e,t,n,r,i){let a=k(t,e.naturalWidth,e.naturalHeight),o=Math.min(1,512/Math.max(a.source.width,a.source.height)),s=document.createElement(`canvas`);s.width=Math.max(1,Math.round(a.source.width*o)),s.height=Math.max(1,Math.round(a.source.height*o));let c=s.getContext(`2d`);if(!c)return null;n?c.drawImage(n,0,0,s.width,s.height):c.drawImage(e,a.source.x,a.source.y,a.source.width,a.source.height,0,0,s.width,s.height),c.globalCompositeOperation=`source-in`,c.fillStyle=`#101916`,c.fillRect(0,0,s.width,s.height);let l=`filter`in c,u=e=>{let t=Math.ceil(e*4),n=a.lengthM*r,o=a.widthM*r,c=document.createElement(`canvas`);c.width=Math.max(1,Math.ceil((n+t*2)*i)),c.height=Math.max(1,Math.ceil((o+t*2)*i));let u=c.getContext(`2d`);if(!u)return null;let d=c.width*2;return l?u.filter=`blur(${e*i}px)`:(u.shadowColor=`#101916`,u.shadowBlur=e*i*2,u.shadowOffsetX=d),u.drawImage(s,t*i-(l?0:d),t*i,n*i,o*i),{canvas:c,padding:t}};return{soft:u(6),close:u(1.5),pixelsPerMeter:r,lengthM:a.lengthM,widthM:a.widthM}}var We={width:56,height:56},Ge=8,Ke=10,qe=6;function Je(e,t,n=Ge){let{width:r,height:i}=We,a=r/2,o=i/2,s=e.x-t.width/2,c=e.y-t.height/2,l=Math.hypot(s,c)||1,u={x:s/l,y:c/l},d=Math.max(0,t.width/2-a-Ke-Ge),f=Math.max(0,t.height/2-o-Ke-(c<0?n:Ge)),p=Math.min(Math.abs(s)?d/Math.abs(s):1/0,Math.abs(c)?f/Math.abs(c):1/0),m={x:t.width/2+s*(Number.isFinite(p)?p:0),y:t.height/2+c*(Number.isFinite(p)?p:0)},h={x:u.x*a,y:u.y*o},g={x:h.x+u.x*Ke,y:h.y+u.y*Ke},_=Math.sqrt((r/2)**2-qe**2),v={x:u.x*_,y:u.y*_};return{center:m,direction:u,edge:h,tip:g,left:{x:v.x-u.y*qe,y:v.y+u.x*qe},right:{x:v.x+u.y*qe,y:v.y-u.x*qe},width:r,height:i}}var Ye=5120,Xe=5121,Ze=5122,Qe=5123,$e=5124,et=5125,tt=5126,nt=32819,rt=32820,it=33635,at=5131,ot=33640,st=35899,ct=35902,lt=36269,ut=34042,dt={};{let e=dt;e[Ye]=Int8Array,e[Xe]=Uint8Array,e[Ze]=Int16Array,e[Qe]=Uint16Array,e[$e]=Int32Array,e[et]=Uint32Array,e[tt]=Float32Array,e[nt]=Uint16Array,e[rt]=Uint16Array,e[it]=Uint16Array,e[at]=Uint16Array,e[ot]=Uint32Array,e[st]=Uint32Array,e[ct]=Uint32Array,e[lt]=Uint32Array,e[ut]=Uint32Array}function ft(...e){console.error(...e)}var pt=new Map;function mt(e,t){if(!e||typeof e!=`object`)return!1;let n=pt.get(t);n||(n=new WeakMap,pt.set(t,n));let r=n.get(e);if(r===void 0){let i=Object.prototype.toString.call(e);r=i.substring(8,i.length-1)===t,n.set(e,r)}return r}function ht(e,t){return typeof WebGLBuffer<`u`&&mt(t,`WebGLBuffer`)}function gt(e,t){return typeof WebGLTexture<`u`&&mt(t,`WebGLTexture`)}function _t(e,t){return typeof WebGLSampler<`u`&&mt(t,`WebGLSampler`)}var vt=35044,yt=34962;function bt(e,t,n,r,i){e.bindBuffer(t,n),e.bufferData(t,r,i||vt)}function xt(e,t,n,r){if(ht(e,t))return t;n||=yt;let i=e.createBuffer();return bt(e,n,i,t,r),i}function St(e){return!!e.texStorage2D}var Ct=function(){let e={},t={};function n(n){let r=n.constructor.name;if(!e[r]){for(let e in n)if(typeof n[e]==`number`){let r=t[n[e]];t[n[e]]=r?`${r} | ${e}`:e}e[r]=!0}}return function(e,r){return n(e),t[r]||(typeof r==`number`?`0x${r.toString(16)}`:r)}}();new Uint8Array([128,192,255,255]);var wt=6406,j=6407,M=6408,Tt=6409,Et=6410,Dt=6402,Ot=34041,kt=3553,At=34067,jt=32879,Mt=35866,Nt=34069,Pt=10241,Ft=10240,It=10242,Lt=10243,Rt=32882,zt=33082,Bt=33083,Vt=33084,Ht=33085,Ut=34892,Wt=34893,Gt=37443,Kt=37441,qt=37440,Jt=33321,Yt=36756,Xt=33325,Zt=33326,Qt=33330,$t=33329,en=33338,tn=33337,nn=33340,rn=33339,an=33323,on=36757,sn=33327,cn=33328,ln=33336,un=33335,dn=33332,fn=33331,pn=33334,mn=33333,hn=32849,gn=35905,_n=36194,vn=36758,yn=35898,bn=35901,xn=34843,Sn=34837,Cn=36221,wn=36239,Tn=36215,En=36233,Dn=36209,On=36227,kn=32856,An=35907,jn=36759,Mn=32855,Nn=32854,Pn=32857,Fn=34842,In=34836,Ln=36220,Rn=36238,zn=36975,Bn=36214,Vn=36232,Hn=36226,Un=36208,Wn=33189,Gn=33190,Kn=36012,qn=36013,Jn=35056,Yn=5120,N=5121,Xn=5122,Zn=5123,Qn=5124,$n=5125,P=5126,er=32819,tr=32820,nr=33635,F=5131,rr=36193,ir=33640,ar=35899,or=35902,sr=36269,cr=34042,lr=33319,ur=33320,dr=6403,fr=36244,pr=36248,I=36249,mr=33776,hr=33777,gr=33778,_r=33779,vr=35916,yr=35917,br=35918,xr=35919,Sr=36196,Cr=37488,wr=37489,Tr=37490,Er=37491,Dr=37492,Or=37493,kr=37494,Ar=37495,jr=37496,Mr=37497,Nr=35840,Pr=35841,Fr=35842,Ir=35843,Lr=37808,Rr=37809,zr=37810,Br=37811,Vr=37812,Hr=37813,Ur=37814,Wr=37815,Gr=37816,Kr=37817,qr=37818,Jr=37819,Yr=37820,Xr=37821,Zr=37840,Qr=37841,$r=37842,ei=37843,ti=37844,ni=37845,ri=37846,ii=37847,ai=37848,oi=37849,si=37850,ci=37851,li=37852,ui=37853,di=36492,fi=36493,pi=36494,mi=36495,hi=36283,gi=36284,_i=36285,vi=36286,yi={};{let e=yi;e[wt]={numColorComponents:1},e[Tt]={numColorComponents:1},e[Et]={numColorComponents:2},e[j]={numColorComponents:3},e[M]={numColorComponents:4},e[dr]={numColorComponents:1},e[fr]={numColorComponents:1},e[lr]={numColorComponents:2},e[ur]={numColorComponents:2},e[j]={numColorComponents:3},e[pr]={numColorComponents:3},e[M]={numColorComponents:4},e[I]={numColorComponents:4},e[Dt]={numColorComponents:1},e[Ot]={numColorComponents:2}}var bi;function xi(e){if(!bi){let e={};e[wt]={textureFormat:wt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[N,F,rr,P]},e[Tt]={textureFormat:Tt,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1,2,2,4],type:[N,F,rr,P]},e[Et]={textureFormat:Et,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2,4,4,8],type:[N,F,rr,P]},e[j]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,6,6,12,2],type:[N,F,rr,P,nr]},e[M]={textureFormat:M,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,8,8,16,2,2],type:[N,F,rr,P,er,tr]},e[Dt]={textureFormat:Dt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[$n,Zn]},e[Jt]={textureFormat:dr,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[1],type:[N]},e[Yt]={textureFormat:dr,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[1],type:[Yn]},e[Xt]={textureFormat:dr,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4,2],type:[P,F]},e[Zt]={textureFormat:dr,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[4],type:[P]},e[Qt]={textureFormat:fr,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[N]},e[$t]={textureFormat:fr,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[1],type:[Yn]},e[dn]={textureFormat:fr,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Zn]},e[fn]={textureFormat:fr,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Xn]},e[pn]={textureFormat:fr,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[$n]},e[mn]={textureFormat:fr,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Qn]},e[an]={textureFormat:lr,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[2],type:[N]},e[on]={textureFormat:lr,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[2],type:[Yn]},e[sn]={textureFormat:lr,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[8,4],type:[P,F]},e[cn]={textureFormat:lr,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[8],type:[P]},e[ln]={textureFormat:ur,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[N]},e[un]={textureFormat:ur,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2],type:[Yn]},e[en]={textureFormat:ur,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Zn]},e[tn]={textureFormat:ur,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Xn]},e[nn]={textureFormat:ur,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[$n]},e[rn]={textureFormat:ur,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Qn]},e[hn]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3],type:[N]},e[gn]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[N]},e[_n]={textureFormat:j,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[3,2],type:[N,nr]},e[vn]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[3],type:[Yn]},e[yn]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[P,F,ar]},e[bn]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6,4],type:[P,F,or]},e[xn]={textureFormat:j,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[12,6],type:[P,F]},e[Sn]={textureFormat:j,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[P]},e[Cn]={textureFormat:pr,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[N]},e[wn]={textureFormat:pr,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[3],type:[Yn]},e[Tn]={textureFormat:pr,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[Zn]},e[En]={textureFormat:pr,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[6],type:[Xn]},e[Dn]={textureFormat:pr,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[$n]},e[On]={textureFormat:pr,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[12],type:[Qn]},e[kn]={textureFormat:M,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[N]},e[An]={textureFormat:M,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[N]},e[jn]={textureFormat:M,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[4],type:[Yn]},e[Mn]={textureFormat:M,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2,4],type:[N,tr,ir]},e[Nn]={textureFormat:M,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4,2],type:[N,er]},e[Pn]={textureFormat:M,colorRenderable:!0,textureFilterable:!0,bytesPerElement:[4],type:[ir]},e[Fn]={textureFormat:M,colorRenderable:!1,textureFilterable:!0,bytesPerElement:[16,8],type:[P,F]},e[In]={textureFormat:M,colorRenderable:!1,textureFilterable:!1,bytesPerElement:[16],type:[P]},e[Ln]={textureFormat:I,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[N]},e[Rn]={textureFormat:I,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[Yn]},e[zn]={textureFormat:I,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[ir]},e[Bn]={textureFormat:I,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Zn]},e[Vn]={textureFormat:I,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[8],type:[Xn]},e[Hn]={textureFormat:I,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[Qn]},e[Un]={textureFormat:I,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[16],type:[$n]},e[Wn]={textureFormat:Dt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[2,4],type:[Zn,$n]},e[Gn]={textureFormat:Dt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[$n]},e[Kn]={textureFormat:Dt,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[P]},e[Jn]={textureFormat:Ot,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[cr]},e[qn]={textureFormat:Ot,colorRenderable:!0,textureFilterable:!1,bytesPerElement:[4],type:[sr]},Object.keys(e).forEach(function(t){let n=e[t];n.bytesPerElementMap={},n.bytesPerElement.forEach(function(e,t){let r=n.type[t];n.bytesPerElementMap[r]=e})});let t={bytes:8,width:4,height:4},n={bytes:16,width:4,height:4};e[mr]={textureFormat:mr,colorRenderable:!1,textureFilterable:!0,block:t},e[hr]={textureFormat:hr,colorRenderable:!1,textureFilterable:!0,block:t},e[gr]={textureFormat:gr,colorRenderable:!1,textureFilterable:!0,block:n},e[_r]={textureFormat:_r,colorRenderable:!1,textureFilterable:!0,block:n},e[vr]={textureFormat:vr,colorRenderable:!1,textureFilterable:!0,block:t},e[yr]={textureFormat:yr,colorRenderable:!1,textureFilterable:!0,block:t},e[br]={textureFormat:br,colorRenderable:!1,textureFilterable:!0,block:n},e[xr]={textureFormat:xr,colorRenderable:!1,textureFilterable:!0,block:n},e[Sr]={textureFormat:Sr,colorRenderable:!1,textureFilterable:!0,block:t},e[Cr]={textureFormat:Cr,colorRenderable:!1,textureFilterable:!0,block:t},e[wr]={textureFormat:wr,colorRenderable:!1,textureFilterable:!0,block:t},e[Tr]={textureFormat:Tr,colorRenderable:!1,textureFilterable:!0,block:n},e[Er]={textureFormat:Er,colorRenderable:!1,textureFilterable:!0,block:n},e[Dr]={textureFormat:Dr,colorRenderable:!1,textureFilterable:!0,block:t},e[Or]={textureFormat:Or,colorRenderable:!1,textureFilterable:!0,block:t},e[kr]={textureFormat:kr,colorRenderable:!1,textureFilterable:!0,block:t},e[Ar]={textureFormat:Ar,colorRenderable:!1,textureFilterable:!0,block:t},e[jr]={textureFormat:jr,colorRenderable:!1,textureFilterable:!0,block:n},e[Mr]={textureFormat:Mr,colorRenderable:!1,textureFilterable:!0,block:n},e[Nr]={textureFormat:Nr,colorRenderable:!1,textureFilterable:!0,block:{bytes:32,width:8,height:8}},e[Pr]={textureFormat:Pr,colorRenderable:!1,textureFilterable:!0,block:{bytes:32,width:16,height:8}},e[Fr]={textureFormat:Fr,colorRenderable:!1,textureFilterable:!0,block:{bytes:32,width:8,height:8}},e[Ir]={textureFormat:Ir,colorRenderable:!1,textureFilterable:!0,block:{bytes:32,width:16,height:8}},e[Lr]={textureFormat:Lr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:4,height:4}},e[Rr]={textureFormat:Rr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:5,height:4}},e[zr]={textureFormat:zr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:5,height:5}},e[Br]={textureFormat:Br,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:6,height:5}},e[Vr]={textureFormat:Vr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:6,height:6}},e[Hr]={textureFormat:Hr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:5}},e[Ur]={textureFormat:Ur,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:6}},e[Wr]={textureFormat:Wr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:8}},e[Gr]={textureFormat:Gr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:5}},e[Kr]={textureFormat:Kr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:6}},e[qr]={textureFormat:qr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:8}},e[Jr]={textureFormat:Jr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:10}},e[Yr]={textureFormat:Yr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:12,height:10}},e[Xr]={textureFormat:Xr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:12,height:12}},e[Zr]={textureFormat:Zr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:4,height:4}},e[Qr]={textureFormat:Qr,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:5,height:4}},e[$r]={textureFormat:$r,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:5,height:5}},e[ei]={textureFormat:ei,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:6,height:5}},e[ti]={textureFormat:ti,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:6,height:6}},e[ni]={textureFormat:ni,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:5}},e[ri]={textureFormat:ri,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:6}},e[ii]={textureFormat:ii,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:8,height:8}},e[ai]={textureFormat:ai,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:5}},e[oi]={textureFormat:oi,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:6}},e[si]={textureFormat:si,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:8}},e[ci]={textureFormat:ci,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:10,height:10}},e[li]={textureFormat:li,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:12,height:10}},e[ui]={textureFormat:ui,colorRenderable:!1,textureFilterable:!0,block:{bytes:16,width:12,height:12}},e[di]={textureFormat:di,colorRenderable:!1,textureFilterable:!0,block:n},e[fi]={textureFormat:fi,colorRenderable:!1,textureFilterable:!0,block:n},e[pi]={textureFormat:pi,colorRenderable:!1,textureFilterable:!0,block:n},e[mi]={textureFormat:mi,colorRenderable:!1,textureFilterable:!0,block:n},e[hi]={textureFormat:hi,colorRenderable:!1,textureFilterable:!0,block:t},e[gi]={textureFormat:gi,colorRenderable:!1,textureFilterable:!0,block:t},e[_i]={textureFormat:_i,colorRenderable:!1,textureFilterable:!0,block:t},e[vi]={textureFormat:vi,colorRenderable:!1,textureFilterable:!0,block:t},bi=e}let t=bi[e];if(!t)throw Error(`unknown internal format`);return t}function Si(e){let t=xi(e);if(!t)throw Error(`unknown internal format`);return{format:t.textureFormat,type:t.type?.[0]??N}}function Ci(e,t,n){let r,i,a;t.colorspaceConversion!==void 0&&(r=e.getParameter(Gt),e.pixelStorei(Gt,t.colorspaceConversion)),t.premultiplyAlpha!==void 0&&(i=e.getParameter(Kt),e.pixelStorei(Kt,t.premultiplyAlpha)),t.flipY!==void 0&&(a=e.getParameter(qt),e.pixelStorei(qt,t.flipY)),n(),r!==void 0&&e.pixelStorei(Gt,r),i!==void 0&&e.pixelStorei(Kt,i),a!==void 0&&e.pixelStorei(qt,a)}function wi(e,t,n,r){r.minMag&&(n.call(e,t,Pt,r.minMag),n.call(e,t,Ft,r.minMag)),r.min&&n.call(e,t,Pt,r.min),r.mag&&n.call(e,t,Ft,r.mag),r.wrap&&(n.call(e,t,It,r.wrap),n.call(e,t,Lt,r.wrap),(t===jt||_t(e,t))&&n.call(e,t,Rt,r.wrap)),r.wrapR&&n.call(e,t,Rt,r.wrapR),r.wrapS&&n.call(e,t,It,r.wrapS),r.wrapT&&n.call(e,t,Lt,r.wrapT),r.minLod!==void 0&&n.call(e,t,zt,r.minLod),r.maxLod!==void 0&&n.call(e,t,Bt,r.maxLod),r.baseLevel!==void 0&&n.call(e,t,Vt,r.baseLevel),r.maxLevel!==void 0&&n.call(e,t,Ht,r.maxLevel),r.compareFunc!==void 0&&n.call(e,t,Wt,r.compareFunc),r.compareMode!==void 0&&n.call(e,t,Ut,r.compareMode)}function Ti(e,t,n){let r=n.target||kt;e.bindTexture(r,t),wi(e,r,e.texParameteri,n)}function Ei(e,t,n){let r=n.target||kt;e.bindTexture(r,t);let i=n.level||0,a=n.internalFormat||n.format||M,o=Si(a),s=n.format||o.format,c=n.type||o.type;Ci(e,n,()=>{if(r===At)for(let t=0;t<6;++t)e.texImage2D(Nt+t,i,a,n.width,n.height,0,s,c,null);else r===jt||r===Mt?e.texImage3D(r,i,a,n.width,n.height,n.depth,0,s,c,null):e.texImage2D(r,i,a,n.width,n.height,0,s,c,null)})}var Di=ft;function Oi(e){return typeof document<`u`&&document.getElementById?document.getElementById(e):null}var ki=33984,Ai=34962,ji=34963,Mi=35713,Ni=35714,Pi=35632,Fi=35633,Ii=35981,Li=35718,Ri=35721,zi=35971,Bi=35382,Vi=35396,Hi=35398,Ui=35392,Wi=35395,Gi=5126,Ki=35664,qi=35665,Ji=35666,Yi=5124,Xi=35667,Zi=35668,Qi=35669,$i=35670,ea=35671,ta=35672,na=35673,ra=35674,ia=35675,aa=35676,oa=35678,sa=35680,ca=35679,la=35682,ua=35685,da=35686,fa=35687,pa=35688,ma=35689,ha=35690,ga=36289,_a=36292,va=36293,ya=5125,ba=36294,xa=36295,Sa=36296,Ca=36298,wa=36299,Ta=36300,Ea=36303,Da=36306,Oa=36307,ka=36308,Aa=36311,ja=3553,Ma=34067,Na=32879,Pa=35866,L={};function Fa(e,t){return L[t].bindPoint}function Ia(e,t){return function(n){e.uniform1f(t,n)}}function La(e,t){return function(n){e.uniform1fv(t,n)}}function Ra(e,t){return function(n){e.uniform2fv(t,n)}}function za(e,t){return function(n){e.uniform3fv(t,n)}}function Ba(e,t){return function(n){e.uniform4fv(t,n)}}function Va(e,t){return function(n){e.uniform1i(t,n)}}function Ha(e,t){return function(n){e.uniform1iv(t,n)}}function Ua(e,t){return function(n){e.uniform2iv(t,n)}}function Wa(e,t){return function(n){e.uniform3iv(t,n)}}function Ga(e,t){return function(n){e.uniform4iv(t,n)}}function Ka(e,t){return function(n){e.uniform1ui(t,n)}}function qa(e,t){return function(n){e.uniform1uiv(t,n)}}function Ja(e,t){return function(n){e.uniform2uiv(t,n)}}function Ya(e,t){return function(n){e.uniform3uiv(t,n)}}function Xa(e,t){return function(n){e.uniform4uiv(t,n)}}function Za(e,t){return function(n){e.uniformMatrix2fv(t,!1,n)}}function Qa(e,t){return function(n){e.uniformMatrix3fv(t,!1,n)}}function $a(e,t){return function(n){e.uniformMatrix4fv(t,!1,n)}}function eo(e,t){return function(n){e.uniformMatrix2x3fv(t,!1,n)}}function to(e,t){return function(n){e.uniformMatrix3x2fv(t,!1,n)}}function no(e,t){return function(n){e.uniformMatrix2x4fv(t,!1,n)}}function ro(e,t){return function(n){e.uniformMatrix4x2fv(t,!1,n)}}function io(e,t){return function(n){e.uniformMatrix3x4fv(t,!1,n)}}function ao(e,t){return function(n){e.uniformMatrix4x3fv(t,!1,n)}}function R(e,t,n,r){let i=Fa(e,t);return St(e)?function(t){let a,o;!t||gt(e,t)?(a=t,o=null):(a=t.texture,o=t.sampler),e.uniform1i(r,n),e.activeTexture(ki+n),e.bindTexture(i,a),e.bindSampler(n,o)}:function(t){e.uniform1i(r,n),e.activeTexture(ki+n),e.bindTexture(i,t)}}function z(e,t,n,r,i){let a=Fa(e,t),o=new Int32Array(i);for(let e=0;e<i;++e)o[e]=n+e;return St(e)?function(t){e.uniform1iv(r,o),t.forEach(function(t,r){e.activeTexture(ki+o[r]);let i,s;!t||gt(e,t)?(i=t,s=null):(i=t.texture,s=t.sampler),e.bindSampler(n,s),e.bindTexture(a,i)})}:function(t){e.uniform1iv(r,o),t.forEach(function(t,n){e.activeTexture(ki+o[n]),e.bindTexture(a,t)})}}L[Gi]={Type:Float32Array,size:4,setter:Ia,arraySetter:La},L[Ki]={Type:Float32Array,size:8,setter:Ra,cols:2},L[qi]={Type:Float32Array,size:12,setter:za,cols:3},L[Ji]={Type:Float32Array,size:16,setter:Ba,cols:4},L[Yi]={Type:Int32Array,size:4,setter:Va,arraySetter:Ha},L[Xi]={Type:Int32Array,size:8,setter:Ua,cols:2},L[Zi]={Type:Int32Array,size:12,setter:Wa,cols:3},L[Qi]={Type:Int32Array,size:16,setter:Ga,cols:4},L[ya]={Type:Uint32Array,size:4,setter:Ka,arraySetter:qa},L[ba]={Type:Uint32Array,size:8,setter:Ja,cols:2},L[xa]={Type:Uint32Array,size:12,setter:Ya,cols:3},L[Sa]={Type:Uint32Array,size:16,setter:Xa,cols:4},L[$i]={Type:Uint32Array,size:4,setter:Va,arraySetter:Ha},L[ea]={Type:Uint32Array,size:8,setter:Ua,cols:2},L[ta]={Type:Uint32Array,size:12,setter:Wa,cols:3},L[na]={Type:Uint32Array,size:16,setter:Ga,cols:4},L[ra]={Type:Float32Array,size:32,setter:Za,rows:2,cols:2},L[ia]={Type:Float32Array,size:48,setter:Qa,rows:3,cols:3},L[aa]={Type:Float32Array,size:64,setter:$a,rows:4,cols:4},L[ua]={Type:Float32Array,size:32,setter:eo,rows:2,cols:3},L[da]={Type:Float32Array,size:32,setter:no,rows:2,cols:4},L[fa]={Type:Float32Array,size:48,setter:to,rows:3,cols:2},L[pa]={Type:Float32Array,size:48,setter:io,rows:3,cols:4},L[ma]={Type:Float32Array,size:64,setter:ro,rows:4,cols:2},L[ha]={Type:Float32Array,size:64,setter:ao,rows:4,cols:3},L[oa]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:ja},L[sa]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Ma},L[ca]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Na},L[la]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:ja},L[ga]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Pa},L[_a]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Pa},L[va]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Ma},L[Ca]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:ja},L[wa]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Na},L[Ta]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Ma},L[Ea]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Pa},L[Da]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:ja},L[Oa]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Na},L[ka]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Ma},L[Aa]={Type:null,size:0,setter:R,arraySetter:z,bindPoint:Pa};function oo(e,t){return function(n){if(n.value)switch(e.disableVertexAttribArray(t),n.value.length){case 4:e.vertexAttrib4fv(t,n.value);break;case 3:e.vertexAttrib3fv(t,n.value);break;case 2:e.vertexAttrib2fv(t,n.value);break;case 1:e.vertexAttrib1fv(t,n.value);break;default:throw Error(`the length of a float constant value must be between 1 and 4!`)}else e.bindBuffer(Ai,n.buffer),e.enableVertexAttribArray(t),e.vertexAttribPointer(t,n.numComponents||n.size,n.type||Gi,n.normalize||!1,n.stride||0,n.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,n.divisor||0)}}function so(e,t){return function(n){if(n.value){if(e.disableVertexAttribArray(t),n.value.length===4)e.vertexAttrib4iv(t,n.value);else throw Error(`The length of an integer constant value must be 4!`)}else e.bindBuffer(Ai,n.buffer),e.enableVertexAttribArray(t),e.vertexAttribIPointer(t,n.numComponents||n.size,n.type||Yi,n.stride||0,n.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,n.divisor||0)}}function co(e,t){return function(n){if(n.value){if(e.disableVertexAttribArray(t),n.value.length===4)e.vertexAttrib4uiv(t,n.value);else throw Error(`The length of an unsigned integer constant value must be 4!`)}else e.bindBuffer(Ai,n.buffer),e.enableVertexAttribArray(t),e.vertexAttribIPointer(t,n.numComponents||n.size,n.type||ya,n.stride||0,n.offset||0),e.vertexAttribDivisor&&e.vertexAttribDivisor(t,n.divisor||0)}}function lo(e,t,n){let r=n.size,i=n.count;return function(n){e.bindBuffer(Ai,n.buffer);let a=n.size||n.numComponents||r,o=a/i,s=n.type||Gi,c=L[s].size*a,l=n.normalize||!1,u=n.offset||0,d=c/i;for(let r=0;r<i;++r)e.enableVertexAttribArray(t+r),e.vertexAttribPointer(t+r,o,s,l,c,u+d*r),e.vertexAttribDivisor&&e.vertexAttribDivisor(t+r,n.divisor||0)}}var B={};B[Gi]={size:4,setter:oo},B[Ki]={size:8,setter:oo},B[qi]={size:12,setter:oo},B[Ji]={size:16,setter:oo},B[Yi]={size:4,setter:so},B[Xi]={size:8,setter:so},B[Zi]={size:12,setter:so},B[Qi]={size:16,setter:so},B[ya]={size:4,setter:co},B[ba]={size:8,setter:co},B[xa]={size:12,setter:co},B[Sa]={size:16,setter:co},B[$i]={size:4,setter:so},B[ea]={size:8,setter:so},B[ta]={size:12,setter:so},B[na]={size:16,setter:so},B[ra]={size:4,setter:lo,count:2},B[ia]={size:9,setter:lo,count:3},B[aa]={size:16,setter:lo,count:4};var uo=/ERROR:\s*\d+:(\d+)/gi;function fo(e,t=``,n=0){let r=[...t.matchAll(uo)],i=new Map(r.map((e,n)=>{let i=parseInt(e[1]),a=r[n+1],o=a?a.index:t.length,s=t.substring(e.index,o);return[i-1,s]}));return e.split(`
|
|
2
|
-
`).map((e,t)=>{let r=i.get(t);return`${t+1+n}: ${e}${r?`\n\n^^^ ${r}`:``}`}).join(`
|
|
3
|
-
`)}var po=/^[ \t]*\n/;function mo(e){let t=0;return po.test(e)&&(t=1,e=e.replace(po,``)),{lineOffset:t,shaderSource:e}}function ho(e,t,n,r){if(r||=Di,!e.getShaderParameter(n,Mi)){let i=e.getShaderInfoLog(n),{lineOffset:a,shaderSource:o}=mo(e.getShaderSource(n)),s=`${fo(o,i,a)}\nError compiling ${Ct(e,t)}: ${i}`;return r(s),s}return``}function go(e,t,n){let r,i,a;if(typeof t==`function`&&(n=t,t=void 0),typeof e==`function`)n=e,e=void 0;else if(e&&!Array.isArray(e)){let t=e;n=t.errorCallback,e=t.attribLocations,r=t.transformFeedbackVaryings,i=t.transformFeedbackMode,a=t.callback}let o=n||Di,s=[],c={errorCallback(e,...t){s.push(e),o(e,...t)},transformFeedbackVaryings:r,transformFeedbackMode:i,callback:a,errors:s};{let n={};Array.isArray(e)?e.forEach(function(e,r){n[e]=t?t[r]:r}):n=e||{},c.attribLocations=n}return c}var _o=[`VERTEX_SHADER`,`FRAGMENT_SHADER`];function vo(e,t){if(t.indexOf(`frag`)>=0)return Pi;if(t.indexOf(`vert`)>=0)return Fi}function yo(e,t,n){let r=e.getAttachedShaders(t);for(let t of r)n.has(t)||e.deleteShader(t);e.deleteProgram(t)}var bo=(e=0)=>new Promise(t=>setTimeout(t,e));function xo(e,t,n){let r=e.createProgram(),{attribLocations:i,transformFeedbackVaryings:a,transformFeedbackMode:o}=go(n);for(let n=0;n<t.length;++n){let i=t[n];if(typeof i==`string`){let t=Oi(i),r=t?t.text:i,a=e[_o[n]];t&&t.type&&(a=vo(e,t.type)||a),i=e.createShader(a),e.shaderSource(i,mo(r).shaderSource),e.compileShader(i)}e.attachShader(r,i)}Object.entries(i).forEach(([t,n])=>e.bindAttribLocation(r,n,t));{let t=a;t&&(t.attribs&&(t=t.attribs),Array.isArray(t)||(t=Object.keys(t)),e.transformFeedbackVaryings(r,t,o||Ii))}return e.linkProgram(r),r}function So(e,t,n,r,i){let a=go(n,r,i),o=new Set(t),s=xo(e,t,a);function c(e,t){let n=wo(e,t,a.errorCallback);return n&&yo(e,t,o),n}if(a.callback)Co(e,s).then(()=>{let t=c(e,s);a.callback(t,t?void 0:s)});else return c(e,s)?void 0:s}async function Co(e,t){let n=e.getExtension(`KHR_parallel_shader_compile`),r=n?(e,t)=>e.getProgramParameter(t,n.COMPLETION_STATUS_KHR):()=>!0,i=0;do await bo(i),i=1e3/60;while(!r(e,t))}function wo(e,t,n){if(n||=Di,!e.getProgramParameter(t,Ni)){let r=e.getProgramInfoLog(t);return n(`Error in program linking: ${r}`),`${r}\n${e.getAttachedShaders(t).map(t=>ho(e,e.getShaderParameter(t,e.SHADER_TYPE),t,n)).filter(e=>e).join(`
|
|
4
|
-
`)}`}}function To(e,t,n,r,i){return So(e,t,n,r,i)}function Eo(e){let t=e.name;return t.startsWith(`gl_`)||t.startsWith(`webgl_`)}var Do=/(\.|\[|]|\w+)/g,Oo=e=>e>=`0`&&e<=`9`;function ko(e,t,n,r){let i=e.split(Do).filter(e=>e!==``),a=0,o=``;for(;;){let e=i[a++];o+=e;let s=Oo(e[0]),c=s?parseInt(e):e;if(s&&(o+=i[a++]),a===i.length){n[c]=t;break}{let e=i[a++],t=e===`[`,s=n[c]||(t?[]:{});n[c]=s,n=s,r[o]=r[o]||function(e){return function(t){No(e,t)}}(s),o+=e}}}function Ao(e,t){let n=0;function r(t,r,i){let a=r.name.endsWith(`[0]`),o=r.type,s=L[o];if(!s)throw Error(`unknown type: 0x${o.toString(16)}`);let c;if(s.bindPoint){let t=n;n+=r.size,c=a?s.arraySetter(e,o,t,i,r.size):s.setter(e,o,t,i,r.size)}else c=s.arraySetter&&a?s.arraySetter(e,i):s.setter(e,i);return c.location=i,c}let i={},a={},o=e.getProgramParameter(t,Li);for(let n=0;n<o;++n){let o=e.getActiveUniform(t,n);if(Eo(o))continue;let s=o.name;s.endsWith(`[0]`)&&(s=s.substr(0,s.length-3));let c=e.getUniformLocation(t,o.name);if(c){let e=r(t,o,c);i[s]=e,ko(s,e,a,i)}}return i}function jo(e,t){let n={},r=e.getProgramParameter(t,zi);for(let i=0;i<r;++i){let r=e.getTransformFeedbackVarying(t,i);n[r.name]={index:i,type:r.type,size:r.size}}return n}function Mo(e,t){let n=e.getProgramParameter(t,Li),r=[],i=[];for(let a=0;a<n;++a){i.push(a),r.push({});let n=e.getActiveUniform(t,a);r[a].name=n.name}[[`UNIFORM_TYPE`,`type`],[`UNIFORM_SIZE`,`size`],[`UNIFORM_BLOCK_INDEX`,`blockNdx`],[`UNIFORM_OFFSET`,`offset`]].forEach(function(n){let a=n[0],o=n[1];e.getActiveUniforms(t,i,e[a]).forEach(function(e,t){r[t][o]=e})});let a={},o=e.getProgramParameter(t,Bi);for(let n=0;n<o;++n){let r=e.getActiveUniformBlockName(t,n),i={index:e.getUniformBlockIndex(t,r),usedByVertexShader:e.getActiveUniformBlockParameter(t,n,Vi),usedByFragmentShader:e.getActiveUniformBlockParameter(t,n,Hi),size:e.getActiveUniformBlockParameter(t,n,Ui),uniformIndices:e.getActiveUniformBlockParameter(t,n,Wi)};i.used=i.usedByVertexShader||i.usedByFragmentShader,a[r]=i}return{blockSpecs:a,uniformData:r}}function No(e,t){for(let n in t){let r=e[n];typeof r==`function`?r(t[n]):No(e[n],t[n])}}function Po(e,...t){let n=e.uniformSetters||e,r=t.length;for(let e=0;e<r;++e){let r=t[e];if(Array.isArray(r)){let e=r.length;for(let t=0;t<e;++t)Po(n,r[t])}else for(let e in r){let t=n[e];t&&t(r[e])}}}function Fo(e,t){let n={},r=e.getProgramParameter(t,Ri);for(let i=0;i<r;++i){let r=e.getActiveAttrib(t,i);if(Eo(r))continue;let a=e.getAttribLocation(t,r.name),o=B[r.type],s=o.setter(e,a,o);s.location=a,n[r.name]=s}return n}function Io(e,t){for(let n in t){let r=e[n];r&&r(t[n])}}function Lo(e,t,n){n.vertexArrayObject?e.bindVertexArray(n.vertexArrayObject):(Io(t.attribSetters||t,n.attribs),n.indices&&e.bindBuffer(ji,n.indices))}function Ro(e,t){let n=Ao(e,t),r=Fo(e,t),i={program:t,uniformSetters:n,attribSetters:r,uniformLocations:Object.fromEntries(Object.entries(n).map(([e,t])=>[e,t.location])),attribLocations:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t.location]))};return St(e)&&(i.uniformBlockSpec=Mo(e,t),i.transformFeedbackInfo=jo(e,t)),i}var zo=36160,Bo=6402,Vo=33190,Ho=36012,Uo=35056,Wo=36013,Go=32854,Ko=32855,qo=36194,Jo=33189,Yo=6401,Xo=36168,Zo=34041,Qo=36096,$o=36128,es=33306,V={};V[Zo]=es,V[Yo]=$o,V[Xo]=$o,V[Bo]=Qo,V[Jo]=Qo,V[Vo]=Qo,V[Ho]=Qo,V[Uo]=es,V[Wo]=es;var ts={};ts[Go]=!0,ts[Ko]=!0,ts[qo]=!0,ts[Zo]=!0,ts[Jo]=!0,ts[Yo]=!0,ts[Xo]=!0;function ns(e,t,n){n||=zo,t?(e.bindFramebuffer(n,t.framebuffer),e.viewport(0,0,t.width,t.height)):(e.bindFramebuffer(n,null),e.viewport(0,0,e.drawingBufferWidth,e.drawingBufferHeight))}var rs=new WeakMap;function is(e,t,n,r){let i=[],a=To(e,[t,n],{errorCallback:e=>i.push(e)});if(!a)throw Error(`${r} shader: ${i.join(`
|
|
5
|
-
`)||`Unable to link program`}`);let o=e.getAttachedShaders(a)??[];try{return rs.set(a,Ro(e,a)),a}catch(t){throw e.deleteProgram(a),t}finally{for(let t of o)e.deleteShader(t)}}function as(e){let t=rs.get(e);if(!t)throw Error(`GPU program is not initialized or has been disposed`);return t}function H(e,t){return as(e).uniformLocations[t.replace(/\[0\]$/,``)]??null}function os(e,t){return as(e).attribLocations[t]??-1}function ss(e,t){Po(as(e),t)}function cs(e,t,n){Lo(e,as(t),{attribs:n,numElements:0})}function ls(e,t,n=e.STATIC_DRAW){let r=xt(e,t,e.ARRAY_BUFFER,n);if(!r)throw Error(`Unable to allocate GPU vertex buffer`);return r}function U(e,t){rs.delete(t),e.deleteProgram(t)}function us(e,t,n,r,i,a,o){let s=e.createTexture(),c=e.createFramebuffer();if(!s||!c)throw e.deleteTexture(s),e.deleteFramebuffer(c),Error(`Unable to allocate ${o}`);try{if(Ei(e,s,{width:t,height:n,internalFormat:r,format:e.RGBA,type:i}),Ti(e,s,{minMag:a,wrap:e.CLAMP_TO_EDGE}),e.bindFramebuffer(e.FRAMEBUFFER,c),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE)throw Error(`${o} framebuffer is incomplete`);return{texture:s,framebuffer:c}}catch(t){throw e.deleteTexture(s),e.deleteFramebuffer(c),t}}function ds(e,t,n,r){ns(e,t?{framebuffer:t.framebuffer,attachments:[t.texture],width:n,height:r}:null)}var fs=`#version 300 es
|
|
6
|
-
precision highp float;
|
|
7
|
-
out vec2 uv;
|
|
8
|
-
void main() {
|
|
9
|
-
vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
|
|
10
|
-
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
|
|
11
|
-
uv = vec2(p.x, 1.0 - p.y);
|
|
12
|
-
}`,ps=`#version 300 es
|
|
13
|
-
precision highp float;
|
|
14
|
-
in vec2 uv;
|
|
15
|
-
out vec4 color;
|
|
16
|
-
uniform sampler2D sprite;
|
|
17
|
-
uniform sampler2D bloom;
|
|
18
|
-
uniform vec4 size;
|
|
19
|
-
uniform vec4 directionTime[3];
|
|
20
|
-
uniform vec4 tint[3];
|
|
21
|
-
uniform vec4 contact[3];
|
|
22
|
-
vec4 bodyAt(vec2 uv) {
|
|
23
|
-
vec4 body = texture(sprite, uv);
|
|
24
|
-
return vec4(body.rgb * body.a, body.a);
|
|
25
|
-
}
|
|
26
|
-
void main() {
|
|
27
|
-
vec2 pixel = 1.0 / vec2(textureSize(sprite, 0));
|
|
28
|
-
vec2 p = (uv / pixel - size.z - size.xy * 0.5) / size.x;
|
|
29
|
-
vec2 offset = vec2(0.0);
|
|
30
|
-
vec3 light = vec3(0.0);
|
|
31
|
-
vec3 coating = vec3(0.0);
|
|
32
|
-
float coverage = 0.0;
|
|
33
|
-
vec2 smear = vec2(0.0);
|
|
34
|
-
float deformationWeight = 0.0;
|
|
35
|
-
for (int i = 0; i < 3; i++) {
|
|
36
|
-
if (float(i) >= size.w) break;
|
|
37
|
-
vec2 axis = directionTime[i].xy;
|
|
38
|
-
float age = directionTime[i].z, strength = directionTime[i].w;
|
|
39
|
-
float variation = tint[i].w;
|
|
40
|
-
vec2 aspect = size.xy / size.x;
|
|
41
|
-
float rayDistance = min(0.5 / max(abs(axis.x), 0.0001), aspect.y * 0.5 / max(abs(axis.y), 0.0001));
|
|
42
|
-
// With no supplied contact, intersect the incoming path with the body bounds.
|
|
43
|
-
vec2 origin = mix(-axis * rayDistance, contact[i].xy * aspect, contact[i].z);
|
|
44
|
-
vec2 delta = p - origin;
|
|
45
|
-
float radius = length(delta);
|
|
46
|
-
vec2 normal = delta / max(radius, 0.025);
|
|
47
|
-
// A single expanding wave, with a coherent optical irregularity unique to this impact.
|
|
48
|
-
float grain = sin(p.x * 19.0 + variation * 23.0) * sin(p.y * 27.0 - variation * 17.0);
|
|
49
|
-
float travel = age * max(1.8, min(5.0, contact[i].w * 2.2));
|
|
50
|
-
float distance = radius - travel + grain * 0.018;
|
|
51
|
-
float width = 0.15 + variation * 0.045;
|
|
52
|
-
float shell = exp(-pow(distance / width, 2.0));
|
|
53
|
-
float arrival = 1.0 - smoothstep(-width, width, distance);
|
|
54
|
-
float envelope = smoothstep(0.0, 0.035, age) * (1.0 - smoothstep(0.28, 1.0, age));
|
|
55
|
-
float film = (arrival * 0.88 + shell * 0.25) * envelope;
|
|
56
|
-
float coat = film * (0.94 + grain * 0.06);
|
|
57
|
-
vec2 opticalScale = size.x * pixel;
|
|
58
|
-
// Refraction changes the RGBA silhouette only near the moving wave, never squeezing the car.
|
|
59
|
-
float pressure = shell * envelope * (0.010 + strength * 0.012) * (0.85 + variation * 0.3);
|
|
60
|
-
offset += (normal + axis * 0.12) * pressure * opticalScale;
|
|
61
|
-
deformationWeight += envelope;
|
|
62
|
-
smear += (normal * shell + axis * arrival * 0.25) * envelope * (0.006 + strength * 0.004) * opticalScale;
|
|
63
|
-
coating += tint[i].rgb * coat;
|
|
64
|
-
coverage += coat;
|
|
65
|
-
light += tint[i].rgb * (film * 0.34 + shell * envelope * 0.18)
|
|
66
|
-
+ mix(tint[i].rgb, vec3(1.0), 0.2) * shell * envelope * 0.08;
|
|
67
|
-
}
|
|
68
|
-
// Reserve enough transparent space for the entire displaced silhouette, even on overlap.
|
|
69
|
-
offset /= max(1.0, deformationWeight);
|
|
70
|
-
smear /= max(1.0, deformationWeight);
|
|
71
|
-
vec2 aspect = size.x * pixel;
|
|
72
|
-
offset *= min(1.0, 0.16 / max(0.0001, length(offset / aspect)));
|
|
73
|
-
smear *= min(1.0, 0.04 / max(0.0001, length(smear / aspect)));
|
|
74
|
-
vec4 warped = bodyAt(uv + offset);
|
|
75
|
-
vec2 crossSmear = vec2(-smear.y * pixel.x / pixel.y, smear.x * pixel.y / pixel.x) * 0.7;
|
|
76
|
-
vec4 blurred = warped * 0.4 + (bodyAt(uv + offset + smear)
|
|
77
|
-
+ bodyAt(uv + offset - smear) + bodyAt(uv + offset + crossSmear)
|
|
78
|
-
+ bodyAt(uv + offset - crossSmear)) * 0.15;
|
|
79
|
-
vec3 straight = blurred.rgb / max(blurred.a, 0.0001);
|
|
80
|
-
vec4 red = texture(sprite, uv + offset * 1.15);
|
|
81
|
-
vec4 blue = texture(sprite, uv + offset * 0.85);
|
|
82
|
-
vec3 refracted = mix(straight, vec3(
|
|
83
|
-
mix(straight.r, red.r, smoothstep(0.05, 0.8, red.a)), straight.g,
|
|
84
|
-
mix(straight.b, blue.b, smoothstep(0.05, 0.8, blue.a))), 0.18);
|
|
85
|
-
vec3 surfaceTint = coating / max(coverage, 0.001);
|
|
86
|
-
vec3 shieldSurface = refracted * (surfaceTint * 0.8 + 0.12) + surfaceTint * 0.17;
|
|
87
|
-
vec3 colored = mix(refracted, shieldSurface, min(0.88, coverage));
|
|
88
|
-
// Cached Gaussian coverage creates a continuous soft field, without extracting a contour.
|
|
89
|
-
float softCoverage = texture(bloom, uv + offset).a;
|
|
90
|
-
// Color and opacity use the same displaced coordinates: the actual body changes shape.
|
|
91
|
-
float bodyAlpha = blurred.a;
|
|
92
|
-
float glowAlpha = softCoverage * min(0.32, coverage * 0.28);
|
|
93
|
-
float alpha = bodyAlpha + glowAlpha * (1.0 - bodyAlpha);
|
|
94
|
-
vec3 body = (colored + light) * bodyAlpha;
|
|
95
|
-
vec3 glow = surfaceTint * glowAlpha * (1.0 - bodyAlpha);
|
|
96
|
-
color = vec4(min(body + glow, vec3(alpha)), alpha);
|
|
97
|
-
}`,ms=class{canvas=document.createElement(`canvas`);capture=document.createElement(`canvas`);bloomCapture=document.createElement(`canvas`);materials=new Map;gl=null;program=null;initialized=!1;disposed=!1;failedSources=new WeakSet;size=new Float32Array(4);directions=new Float32Array(12);colors=new Float32Array(12);contacts=new Float32Array(12);padding=64;onLost=e=>{e.preventDefault(),this.materials.clear(),this.program=null};onRestored=()=>{!this.disposed&&this.gl&&(this.program=is(this.gl,fs,ps,`Pickup refraction`))};initialize(){if(this.initialized=!0,this.gl=this.canvas.getContext(`webgl2`,{alpha:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!0,antialias:!1,depth:!1,stencil:!1}),this.gl){try{this.program=is(this.gl,fs,ps,`Pickup refraction`)}catch{this.gl=null;return}this.canvas.addEventListener(`webglcontextlost`,this.onLost),this.canvas.addEventListener(`webglcontextrestored`,this.onRestored)}}destroyMaterial(e){this.gl?.deleteTexture(e.texture),this.gl?.deleteTexture(e.bloomTexture)}clearMaterials(){for(let e of this.materials.values())this.destroyMaterial(e);this.materials.clear()}draw(e,t,n,r,i,a,o,s,c=4.5){if(!s.length||this.disposed||this.failedSources.has(n)||(this.initialized||this.initialize(),!this.gl||!this.program))return!1;let l=Math.max(16,Math.round(272*a/Math.max(a,o))),u=Math.max(16,Math.round(272*o/Math.max(a,o))),d=this.materials.get(t);if(d&&(d.source!==n||d.revision!==i||d.width!==l||d.height!==u)&&(this.destroyMaterial(d),this.materials.delete(t),d=void 0),!d){if(this.materials.size>=8){let e=this.materials.keys().next().value;this.destroyMaterial(this.materials.get(e)),this.materials.delete(e)}this.capture.width=l+this.padding*2,this.capture.height=u+this.padding*2;let e=this.capture.getContext(`2d`);if(!e)return!1;e.drawImage(n,r.x,r.y,r.width,r.height,this.padding,this.padding,l,u),this.bloomCapture.width=this.capture.width,this.bloomCapture.height=this.capture.height;let a=this.bloomCapture.getContext(`2d`);if(!a)return!1;if(typeof a.filter==`string`)a.filter=`blur(8px)`,a.drawImage(this.capture,0,0);else{let e=this.bloomCapture.width*2;a.shadowColor=`#ffffff`,a.shadowBlur=16,a.shadowOffsetX=e,a.drawImage(this.capture,-e,0)}try{d=this.upload(n,i,l,u)}catch{return this.failedSources.add(n),!1}this.materials.set(t,d),f(`pickup sprite uploads`)}let p=l+this.padding*2,m=u+this.padding*2;(this.canvas.width!==p||this.canvas.height!==m)&&(this.canvas.width=p,this.canvas.height=m),this.size.set([l,u,this.padding,Math.min(3,s.length)]);for(let e=0;e<Math.min(3,s.length);e++){let t=s[e];this.directions.set([Math.cos(t.angle),-Math.sin(t.angle),t.age/t.duration,t.strength],e*4),this.colors.set([...t.color,t.variation],e*4),this.contacts.set([t.origin?.x??0,-(t.origin?.y??0),+!!t.origin,t.velocity*t.duration/c],e*4)}let h=this.gl;h.viewport(0,0,p,m),h.useProgram(this.program),ss(this.program,{sprite:d.texture,bloom:d.bloomTexture,size:this.size,directionTime:this.directions,tint:this.colors,contact:this.contacts}),h.drawArrays(h.TRIANGLES,0,3);let g=this.padding*a/l,_=this.padding*o/u;return e.drawImage(this.canvas,-a/2-g,-o/2-_,a+g*2,o+_*2),f(`pickup shader passes`),f(`composited megapixels`,p*m/1e6),!0}upload(e,t,n,r){let i=this.gl,a=[];try{for(let e of[this.capture,this.bloomCapture]){let t=i.createTexture();if(!t)throw Error(`Unable to allocate pickup material`);a.push(t),i.bindTexture(i.TEXTURE_2D,t),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!1),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,e)}let[o,s]=a;return{source:e,revision:t,width:n,height:r,texture:o,bloomTexture:s}}catch(e){for(let e of a)i.deleteTexture(e);throw e}}reset(){this.clearMaterials()}dispose(){this.disposed=!0,this.clearMaterials(),this.canvas.removeEventListener(`webglcontextlost`,this.onLost),this.canvas.removeEventListener(`webglcontextrestored`,this.onRestored),this.gl&&this.program&&U(this.gl,this.program),this.gl=null,this.program=null}},hs=8;function gs(e,t,n){let r=n*.45,i=0;for(let n=0;n<8;n++){let n=i+1;if(n>=r)break;let a=new Set,o=i;for(let i of e.elementsFromPoint(t,n))for(let e=i;e;e=e.parentElement){if(a.has(e))continue;a.add(e);let t=getComputedStyle(e);if(t.position!==`fixed`&&t.position!==`sticky`||t.visibility===`hidden`||t.opacity===`0`)continue;let i=e.getBoundingClientRect();i.top<=n&&i.bottom>n&&i.bottom<r&&(o=Math.max(o,i.bottom))}if(o<=i)break;i=o}return i+hs}var _s=class{camera;constructor(e){this.camera=e}pickupLayer=null;dispose(){this.pickupLayer?.dispose()}captureState(){return u({previousCarVelocity:this.previousCarVelocity,poseOffset:this.poseOffset,poseVelocity:this.poseVelocity,poseForce:this.poseForce,wheelPhase:this.wheelPhase})}restoreState(e){let t=u(e);this.previousCarVelocity=t.previousCarVelocity,this.poseOffset=t.poseOffset,this.poseVelocity=t.poseVelocity,this.poseForce=t.poseForce,this.wheelPhase=t.wheelPhase,this.clearMaterials()}clearMaterials(){this.pickupLayer?.reset(),this.carImages.clear(),this.pickupFallbacks=new WeakMap,this.pristineShadows=new WeakMap,this.deformedShadows=new WeakMap}reset(){this.pickupLayer?.reset(),this.markers=[],this.previousCarVelocity=null,this.poseOffset=C(),this.poseVelocity=C(),this.poseForce=C(),this.wheelPhase=[0,0,0,0]}carImages=new Map;pickupFallbacks=new WeakMap;pristineShadows=new WeakMap;deformedShadows=new WeakMap;previousCarVelocity=null;poseOffset=C();poseVelocity=C();poseForce=C();wheelPhase=[0,0,0,0];carVisualOffset(e){return v(h(C(this.poseOffset.x,-this.poseOffset.y),-e.body.angle),this.camera.zoom)}updateCarPose(e,t){if(e.mode!==`car`){this.previousCarVelocity=null,this.poseOffset=C(),this.poseVelocity=C(),this.poseForce=C();return}let n=e.body.velocity,r=this.previousCarVelocity?v(x(n,this.previousCarVelocity),1/Math.max(t,1e-4)):C();this.previousCarVelocity={...n};let i=h(r,-e.body.angle),a=1-Math.exp(-t/.11);this.poseForce=S(this.poseForce,v(x(C(b(i.x,-15,15),b(i.y,-15,15)),this.poseForce),a));let o=C(b(-this.poseForce.x*.006,-.055,.055),0);this.poseVelocity=S(this.poseVelocity,v(x(v(x(o,this.poseOffset),65),v(this.poseVelocity,15)),t)),this.poseOffset=S(this.poseOffset,v(this.poseVelocity,t)),e.car.tires.forEach((n,r)=>{this.wheelPhase[r]=(this.wheelPhase[r]+t*Math.abs(n.wheelSurfaceSpeedMps)/Math.max(.18,e.car.preset.geometry.tireLengthM*.45))%1})}line(e,t,n,r,i=1){let a=this.camera.screen(t),o=this.camera.screen(n);e.strokeStyle=r,e.lineWidth=i,e.beginPath(),e.moveTo(a.x,a.y),e.lineTo(o.x,o.y),e.stroke()}outline(e,t,n){e.beginPath(),t.forEach((t,n)=>{let r=this.camera.screen(t);n?e.lineTo(r.x,r.y):e.moveTo(r.x,r.y)}),e.closePath(),e.fillStyle=`${n}15`,e.fill(),e.strokeStyle=n,e.lineWidth=2,e.stroke()}imageFor(e){let t=e.image?.src;if(!t)return null;let n=this.carImages.get(t);return n||(n=new Image,n.crossOrigin=`anonymous`,n.src=t,this.carImages.set(t,n)),n.complete&&n.naturalWidth?n:null}imageLoadState(e){let t=e.image?.src;return!t||this.imageFor(e)?`ready`:this.carImages.get(t)?.complete?`failed`:`loading`}markers=[];markerInset={x:NaN,scrollX:NaN,scrollY:NaN,width:NaN,height:NaN,at:0,value:8};topMarkerInset(e){if(!this.camera.overlay||e.y>=this.camera.height/2)return 8;let t=this.camera.regionScale,n=b(Je(e,this.camera).center.x*t,1,window.innerWidth-1),r=performance.now(),i=this.markerInset;return(r-i.at>200||Math.abs(n-i.x)>24||i.scrollX!==window.scrollX||i.scrollY!==window.scrollY||i.width!==window.innerWidth||i.height!==window.innerHeight)&&(this.markerInset={x:n,scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight,at:r,value:gs(document,n,window.innerHeight)}),this.markerInset.value/t}markerAt(e){return[...this.markers].reverse().find(t=>Math.hypot(e.x-t.x,e.y-t.y)<=t.width/2+3)?.vehicle??null}drawVehicleMarkers(e,t,n){if(this.markers=[],n)for(let n of t){let{sim:r}=n;if(r.mode!==`car`||r.car.explodedAt!==null)continue;let i=S(this.camera.screen(r.body.position),n===t[0]?this.carVisualOffset(r):C()),a=Math.max(r.car.preset.geometry.lengthM,r.car.preset.geometry.widthM)*this.camera.zoom*.5;if(i.x+a>=0&&i.x-a<=this.camera.width&&i.y+a>=0&&i.y-a<=this.camera.height)continue;let o=Je(i,this.camera,this.topMarkerInset(i)),{width:s,height:c}=o,{x:l,y:u}=o.center;this.markers.push({vehicle:n,x:l,y:u,width:s,height:c}),e.save(),e.translate(l,u),e.shadowColor=`#00000030`,e.shadowBlur=10,e.shadowOffsetY=2,e.fillStyle=`#ffffff`,e.beginPath(),e.arc(0,0,s/2,0,Math.PI*2),e.fill(),e.shadowColor=`transparent`,e.strokeStyle=`#19212640`,e.lineWidth=1,e.stroke();let d=this.imageFor(r.car.preset);if(e.save(),e.rotate(-r.body.angle),d){let t=k(r.car.preset,d.naturalWidth,d.naturalHeight),n=35*t.widthM/t.lengthM;e.drawImage(d,t.source.x,t.source.y,t.source.width,t.source.height,-35/2,-n/2,35,n)}else e.fillStyle=`#192126`,e.beginPath(),e.roundRect(-13,-5,26,10,5),e.fill();e.restore();let{left:f,right:p,tip:m}=o;e.fillStyle=`#ffffff`,e.beginPath(),e.moveTo(f.x,f.y),e.lineTo(m.x,m.y),e.lineTo(p.x,p.y),e.closePath(),e.fill(),e.strokeStyle=`#19212640`,e.lineWidth=1,e.beginPath(),e.moveTo(f.x,f.y),e.lineTo(m.x,m.y),e.lineTo(p.x,p.y),e.stroke(),e.restore()}}shadowFor(e,t,n){let r=this.imageFor(e);if(!r)return null;let i=k(e,r.naturalWidth,r.naturalHeight),a=t?.spriteFor(r,i)??null,o=Math.max(1,Math.round(this.camera.zoom/2)*2),s=`${JSON.stringify(e.image?.crop)}|${e.image?.scale}|${e.geometry.lengthM}:${e.geometry.widthM}|${o}:${n}`;if(t&&a){let i=`${s}|${t.geometryRevision}`,c=this.deformedShadows.get(t);if(c?.image===r&&c.key===i)return c.shadow;f(`shadow rebuilds`);let l=Ue(r,e,a,o,n);return this.deformedShadows.set(t,{image:r,key:i,shadow:l}),l}let c=this.pristineShadows.get(r);c||(c=new Map,this.pristineShadows.set(r,c));let l=c.get(s);return l||(f(`shadow rebuilds`),l=Ue(r,e,a,o,n),c.set(s,l),c.size>12&&c.delete(c.keys().next().value)),l}vehicleBodyPath(e,t,n,r,i){if(!i?.hasDamage){e.roundRect(-t/2,-n/2,t,n,r);return}let a=Math.min(r,n/2),o=[{x:t/2-a,y:-n/2+a,start:-Math.PI/2},{x:t/2-a,y:n/2-a,start:0},{x:-t/2+a,y:n/2-a,start:Math.PI/2},{x:-t/2+a,y:-n/2+a,start:Math.PI}],s=!0;for(let t of o)for(let n=0;n<=8;n++){let r=t.start+n*Math.PI/16,o=C(t.x+Math.cos(r)*a,t.y+Math.sin(r)*a),c=i.point(v(o,1/this.camera.zoom)),l=c.x*this.camera.zoom,u=c.y*this.camera.zoom;s?(e.moveTo(l,u),s=!1):e.lineTo(l,u)}e.closePath()}carGround(e,t,n,r,i){performance.now();let a=t.body,o=t.car.preset.geometry,s=this.camera.screen(a.position),c=o.lengthM*this.camera.zoom,l=o.widthM*this.camera.zoom,u=b(m(this.poseForce)/13,0,1),d=e.globalAlpha;e.save(),e.translate(s.x,s.y),e.rotate(-a.angle),e.save(),e.translate(-this.poseOffset.x*this.camera.zoom*.2+2,this.poseOffset.y*this.camera.zoom*.2+4);let p=i?this.shadowFor(t.car.preset,n,r):null;if(p){let t=p.lengthM*this.camera.zoom,n=p.widthM*this.camera.zoom,r=this.camera.zoom/p.pixelsPerMeter,i=(i,a)=>{let o=i.padding*r;f(`shadow composites`),e.drawImage(i.canvas,-t/2-o,-n/2+a-o,t+o*2,n+o*2)};e.globalAlpha=d*(.43+u*.05),p.soft&&i(p.soft,3),e.globalAlpha=d*.14,p.close&&i(p.close,2)}else if(i){e.fillStyle=`rgba(13, 20, 20, ${.18+u*.045})`,e.shadowColor=`rgba(8, 14, 16, 0.43)`,e.shadowBlur=12+u*5,e.shadowOffsetY=2,e.beginPath();let r=t.car.preset.visual,i=r?l*.86:l*.84,a=r?r.shape===`suv`?9:r.shape===`supercar`?24:19:l*.34;this.vehicleBodyPath(e,r?c:c*.96,i,a,n),e.fill()}e.restore(),t.car.tires.forEach((n,r)=>{let i=He(t.car.preset),o=i.length*this.camera.zoom,s=i.width*this.camera.zoom;e.save(),e.translate(n.local.x*this.camera.zoom,-n.local.y*this.camera.zoom),e.rotate(-n.angle),e.fillStyle=`#121719`,e.beginPath(),e.roundRect(-o/2,-s/2,o,s,Math.min(3.5,s*.33)),e.fill(),e.save(),e.beginPath(),e.roundRect(-o/2+1,-s/2+1,o-2,s-2,Math.min(3,s*.3)),e.clip();let c=this.wheelPhase[r]??0,l=n.spinning?1:b(m(a.velocity)/24,0,.65),u=Math.max(4.2,o/4);e.strokeStyle=n.spinning?`rgba(170, 181, 178, 0.38)`:`rgba(125, 139, 137, 0.34)`,e.lineWidth=n.spinning?2:1.25;for(let t=-3;t<=4;t++){let n=t*u+c*u;e.beginPath(),e.moveTo(n-l*2,-s*.31),e.lineTo(n+l*2,s*.31),e.stroke()}l>.2&&(e.fillStyle=`rgba(137, 150, 147, ${.08+l*.1})`,e.fillRect(-o*.4,-s*.09,o*.8,s*.18)),e.restore(),e.strokeStyle=`rgba(6, 10, 11, 0.8)`,e.lineWidth=1.2,e.beginPath(),e.roundRect(-o/2,-s/2,o,s,Math.min(3.5,s*.33)),e.stroke(),e.restore()}),e.restore()}car(e,t,n,r,i,a){let o=n.car.preset,s=o.geometry,c=this.imageFor(o);if(a&&!this.pickupLayer&&(this.pickupLayer=new ms),c){let n=this.camera.screen(t.position),s=k(o,c.naturalWidth,c.naturalHeight),l=r?.spriteFor(c,s);if(e.save(),e.translate(n.x,n.y),e.rotate(-t.angle),pe(e,o,this.camera.zoom,s.lengthM,s.widthM,i,a?.pickupEffect.active.length?s.lengthM*.25:0),a?.pickupEffect.active.length&&this.pickupLayer?.draw(e,a,l??c,l?{x:0,y:0,width:l.width,height:l.height}:s.source,`${r?.geometryRevision??0}:${JSON.stringify(s.source)}`,s.lengthM*this.camera.zoom,s.widthM*this.camera.zoom,a.pickupEffect.active,s.lengthM)){e.restore();return}l?e.drawImage(l,-s.lengthM*this.camera.zoom/2,-s.widthM*this.camera.zoom/2,s.lengthM*this.camera.zoom,s.widthM*this.camera.zoom):e.drawImage(c,s.source.x,s.source.y,s.source.width,s.source.height,-s.lengthM*this.camera.zoom/2,-s.widthM*this.camera.zoom/2,s.lengthM*this.camera.zoom,s.widthM*this.camera.zoom),f(`vehicle sprites`),e.restore();return}if(a?.pickupEffect.active.length){let c=s.lengthM*this.camera.zoom,l=s.widthM*this.camera.zoom,u=`${o.id}:${this.camera.zoom}:${r?.geometryRevision??0}:${JSON.stringify(o.visual)}`,d=this.pickupFallbacks.get(a);if(!d||d.revision!==u){let e=document.createElement(`canvas`),o=384/Math.max(c,l);e.width=Math.max(1,Math.ceil(c*o)),e.height=Math.max(1,Math.ceil(l*o));let s=e.getContext(`2d`);if(s){let o=this.camera.screen(t.position);s.scale(e.width/c,e.height/l),s.translate(c/2,l/2),s.rotate(t.angle),s.translate(-o.x,-o.y),this.car(s,t,n,r,i),d={revision:u,canvas:e},this.pickupFallbacks.set(a,d)}}if(d){let n=this.camera.screen(t.position);e.save(),e.translate(n.x,n.y),e.rotate(-t.angle);let r=this.pickupLayer?.draw(e,a,d.canvas,{x:0,y:0,width:d.canvas.width,height:d.canvas.height},u,c,l,a.pickupEffect.active,s.lengthM);if(e.restore(),r)return}}if(o.visual){this.styledCar(e,t,n,r);return}let l=s.lengthM/2,u=s.widthM/2,d=[C(-l,-u),C(l,-u),C(l,u),C(-l,u)].map(e=>t.world(e));this.outline(e,d,`#8ce6c5`),this.line(e,t.world(C(s.wheelbaseM/4,-s.trackWidthM/2)),t.world(C(s.wheelbaseM/4,s.trackWidthM/2)),`#8ce6c5`,2),this.center(e,t,`#8ce6c5`)}exhaustOutlets(e){let t=e.car.preset,n=this.imageFor(t),r=n?k(t,n.naturalWidth,n.naturalHeight).lengthM:t.geometry.lengthM,i=t.exhaust.layout,a=t.geometry.widthM*.3;return(i===`left-right`?[-a,a]:i===`left`?[-a]:i===`right`?[a]:[0]).map(e=>C(-r/2-.025,e))}exhaust(e,t){let n=this.camera.screen(t.body.position);e.save(),e.translate(n.x,n.y),e.rotate(-t.body.angle);let r=this.exhaustOutlets(t);for(let t of r)e.fillStyle=`rgba(25, 31, 33, 0.62)`,e.beginPath(),e.ellipse(t.x*this.camera.zoom,-t.y*this.camera.zoom,Math.max(1.3,this.camera.zoom*.065),Math.max(1.2,this.camera.zoom*.055),0,0,Math.PI*2),e.fill();e.restore()}styledCar(e,t,n,r){let{geometry:i,visual:a}=n.car.preset;if(!a)return;let o=this.camera.screen(t.position),s=i.lengthM*this.camera.zoom,c=i.widthM*this.camera.zoom*.86,l=a.shape===`suv`?9:a.shape===`supercar`?24:19;e.save(),e.translate(o.x,o.y),e.rotate(-t.angle),e.beginPath(),this.vehicleBodyPath(e,s,c,l,r),e.fillStyle=a.color,e.fill(),e.strokeStyle=`rgba(18, 29, 27, 0.72)`,e.lineWidth=2,e.stroke(),e.fillStyle=`rgba(16, 32, 36, 0.8)`;let u=s*(a.shape===`suv`?.52:a.shape===`supercar`?.32:.4),d=c*(a.shape===`suv`?.72:.64),f=a.shape===`supercar`?-s*.08:-s*.015;e.beginPath(),e.roundRect(f-u/2,-d/2,u,d,a.shape===`suv`?7:14),e.fill(),e.strokeStyle=`rgba(235, 245, 241, 0.58)`,e.lineWidth=2,e.beginPath(),e.moveTo(f+u*.16,-d/2+3),e.lineTo(f+u*.16,d/2-3),e.stroke(),e.fillStyle=`rgba(255, 246, 205, 0.9)`;let p=D(n.car.preset);for(let t of[-1,1])e.beginPath(),e.ellipse(p.headlights.xM*this.camera.zoom,t*p.headlights.yM*this.camera.zoom,4,3,0,0,Math.PI*2),e.fill();e.fillStyle=`rgba(139, 28, 21, 0.88)`;for(let t of[-1,1])e.fillRect(p.taillights.xM*this.camera.zoom-2,t*p.taillights.yM*this.camera.zoom-3,4,6);e.restore()}ship(e,t,n){let r=n.ship,i=r.craft,a=t.world(r.counterweight);this.line(e,t.world(S(r.counterweight,C(r.radius))),t.world(S(i,C(-.6))),`#ff6262`,2);let o=this.camera.screen(a);e.beginPath(),e.arc(o.x,o.y,r.radius*this.camera.zoom,0,Math.PI*2),e.fillStyle=`#ff626215`,e.fill(),e.strokeStyle=`#ff6262`,e.lineWidth=2,e.stroke();let s=[C(1.2),C(-.6,-.8),C(-.6,.8)].map(e=>t.world(S(i,h(e,r.headAngle))));this.outline(e,s,`#ff6262`),this.center(e,t,`#ff6262`)}brick(e,t){this.outline(e,[C(-2,-1),C(2,-1),C(2,1),C(-2,1)].map(e=>t.world(e)),`#f6bd79`),this.center(e,t,`#f6bd79`)}center(e,t,n){let r=this.camera.screen(t.position);e.fillStyle=n,e.beginPath(),e.arc(r.x,r.y,3,0,Math.PI*2),e.fill(),!this.camera.overlay&&m(t.velocity)>.1&&this.line(e,t.position,S(t.position,v(t.velocity,.35)),`#658da0`)}},vs=.055,ys=e=>{let t=Math.sin(e*127.1+311.7)*43758.5453;return t-Math.floor(t)};function bs(e,t,n){if(!Number.isFinite(n)||n<=0)return[];let r=Math.min(e.age,e.duration*.8),i=e.age-n,a=i<=1e-7?0:Math.floor((i+1e-7)/vs)+1,o=Math.floor((r+1e-7)/vs);if(a>o)return[];let s={x:Math.cos(e.angle),y:Math.sin(e.angle)},c=Math.min(t.lengthM/(2*Math.max(1e-4,Math.abs(s.x))),t.widthM/(2*Math.max(1e-4,Math.abs(s.y)))),l=e.origin?{x:e.origin.x*t.lengthM,y:e.origin.y*t.widthM}:{x:-s.x*c,y:-s.y*c},u=Math.max(1.8,Math.min(5,e.velocity*e.duration/t.lengthM*2.2)),d=Math.hypot(t.lengthM*.5+Math.abs(l.x),t.widthM*.5+Math.abs(l.y)),f=[];for(let n=a;n<=o;n++){let r=n*vs/e.duration*u*t.lengthM;for(let i=0;i<2;i++){let a=e.variation*1999+n*83+i*257,o,s=1/0,c=Math.min(r,d)*Math.sqrt(ys(a+9));for(let e=0;e<32;e++){let n=ys(a+e*2+1),i=ys(a+e*2+2),u=t.alpha;if(u&&!u.solid[Math.floor(i*u.rows)*u.columns+Math.floor(n*u.columns)])continue;let d={x:(n-.5)*t.lengthM,y:(.5-i)*t.widthM},f=Math.hypot(d.x-l.x,d.y-l.y);if(f>r+t.lengthM*.17)continue;let p=Math.abs(f-c);p<s&&(s=p,o=d)}o&&f.push(o)}}return f}function xs(e,t,n){return n?C(n.x+n.width/2,n.y+n.height/2):C(e/2,t/2)}function Ss(e,t,n){let r=xs(e,t,n);return Math.ceil(2*Math.hypot(Math.max(r.x,e-r.x),Math.max(r.y,t-r.y)))}function Cs(e,t,n,r){return S(n,h(x(e,t),r))}function ws(e,t,n,r){return S(t,h(x(e,n),-r))}function Ts(e,t,n){return v(C(e,t),n/2)}function Es(e,t,n,r){return e+Math.atan2(Math.sin(t-e),Math.cos(t-e))*(r<=0?1:1-Math.exp(-Math.max(0,n)/r))}function Ds(e,t,n){return{x:e.x<n?e.x-n:e.x>t.width-n?e.x-(t.width-n):0,y:e.y<n?e.y-n:e.y>t.height-n?e.y-(t.height-n):0}}function Os(e,t,n){let r=Math.min(Math.max(1,t.width-32)/Math.max(1,e.width+160),Math.max(1,t.height-32)/Math.max(1,e.height+160));return Math.max(.1,Math.min(3,n??r))}function ks(e,t){let n=null;for(let r of e){let e=r.bounds;t.x<e.x||t.y<e.y||t.x>=e.x+e.width||t.y>=e.y+e.height||(!n||n.element.contains(r.element)||!r.element.contains(n.element)&&e.width*e.height<n.bounds.width*n.bounds.height)&&(n=r)}return n}var As=class{projection;regions=[];measuredAt=-1/0;constructor(e=me){this.projection=e}at(e,t,n){return n-this.measuredAt>120&&(this.measuredAt=n,this.regions=Array.from(document.querySelectorAll(`[data-jr-camera],[data-jr-camera-zoom]`)).filter(e=>!e.closest(`[data-jr-ui],[data-jr-overlay]`)).flatMap(e=>{let n=e.getAttribute(`data-jr-camera`);if(n!==null&&n!==`fixed`&&n!==`follow`)return[];let r=this.projection.viewportRectToDocument(e.getBoundingClientRect(),t);if(r.width<=0||r.height<=0)return[];let i=e.getAttribute(`data-jr-camera-zoom`),a=i?.trim()?Number(i):NaN;return n===null&&(!Number.isFinite(a)||a<=0)?[]:[{element:e,bounds:r,fixed:n===`fixed`,zoom:Number.isFinite(a)&&a>0?a:void 0}]})),ks(this.regions.filter(e=>e.element.isConnected),e)}reset(){this.regions=[],this.measuredAt=-1/0}},js=class{overlay;canvasWorld;requestResize;constructor(e,t,n){this.overlay=e,this.canvasWorld=t,this.requestResize=n,e&&(this.originScroll=C(window.scrollX,window.scrollY),this.observedScroll={...this.originScroll},this.pageSize={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight})}resize(){this.requestResize()}get pixelSpace(){return this.overlay||this.canvasWorld}get timeSeconds(){return this.lastFrame/1e3}rebaseTime(e){this.lastFrame=e}captureState(){return u({outputWidth:this.outputWidth,outputHeight:this.outputHeight,cameraRotation:this.cameraRotation,cameraLock:this.cameraLock,cameraSmoothing:this.cameraSmoothing,cameraLockInitialized:this.cameraLockInitialized,width:this.width,height:this.height,dpr:this.dpr,smokeMargin:this.smokeMargin,regionScale:this.regionScale,canvasWorldScale:this.canvasWorldScale,cameraFrame:this.cameraFrame,camera:this.camera,zoom:this.zoom,baseZoom:this.baseZoom,slowMoScale:this.slowMoScale,zoomAnchor:this.zoomAnchor,pageSize:this.pageSize,lastFrame:this.lastFrame,originScroll:this.originScroll,observedScroll:this.observedScroll,virtualScroll:this.virtualScroll,followInterrupted:this.followInterrupted,deadZone:this.deadZone})}restoreState(e){let t=u(e);this.vehicleReveal=null,this.outputWidth=t.outputWidth,this.outputHeight=t.outputHeight,this.cameraRotation=t.cameraRotation,this.cameraLock=t.cameraLock,this.cameraSmoothing=t.cameraSmoothing,this.cameraLockInitialized=t.cameraLockInitialized,this.width=t.width,this.height=t.height,this.dpr=t.dpr,this.smokeMargin=t.smokeMargin,this.regionScale=t.regionScale,this.canvasWorldScale=t.canvasWorldScale,this.cameraFrame=t.cameraFrame,this.camera=t.camera,this.zoom=t.zoom,this.baseZoom=t.baseZoom,this.slowMoScale=t.slowMoScale,this.zoomAnchor=t.zoomAnchor,this.pageSize=t.pageSize,this.lastFrame=t.lastFrame,this.originScroll=t.originScroll,this.observedScroll=t.observedScroll,this.virtualScroll=t.virtualScroll,this.followInterrupted=t.followInterrupted,this.deadZone=t.deadZone}restorePresentation(){this.setVirtualScroll({...this.virtualScroll}),this.overlay&&(window.scrollTo(this.observedScroll.x,this.observedScroll.y),ae(),this.resize(),this.cameraRegions.reset(),this.activeCameraRegion||this.regionScale!==1?this.pageScene.apply(this.regionScale,this.sceneScroll()):this.pageScene.clear())}reset(){this.vehicleReveal=null,this.camera=C(),this.cameraLockInitialized=!1,this.slowMoZoom=1,this.zoomAnchor=C(),this.overlay&&(this.pageSize={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight}),this.pageScene.clear(),this.activeCameraRegion=null,this.cameraRegions.reset(),this.regionScale=this.canvasWorld?this.canvasWorldScale:1,this.resize(),this.setVirtualScroll(C())}vehicleReveal=null;revealVehicle(e,t=550){this.overlay&&(this.syncScroll(),this.followInterrupted=!0,this.vehicleReveal={sim:e,start:this.sceneScroll(),started:null,duration:t})}advanceVehicleReveal(e,t){let n=this.vehicleReveal;if(!n)return;n.started??=e;let r=n.duration<=0?1:b((e-n.started)/n.duration,0,1),i=r*r*(3-2*r),a=x(this.documentPoint(n.sim.body.position),C(this.width/2,this.height/2));!this.virtualScroll.x&&a.x>=-this.width/2&&a.x<=this.pageSize.width-this.width/2&&(a.x=b(a.x,0,Math.max(0,this.pageSize.width-this.width))),!this.virtualScroll.y&&a.y>=-this.height/2&&a.y<=this.pageSize.height-this.height/2&&(a.y=b(a.y,0,Math.max(0,this.pageSize.height-this.height))),this.moveSceneTo(S(n.start,v(x(a,n.start),i))),r===1&&(this.vehicleReveal=null,n.sim===t&&(this.followInterrupted=!1))}resetFollow(){this.vehicleReveal=null,this.overlay&&(this.originScroll=C(window.scrollX,window.scrollY),this.observedScroll={...this.originScroll},this.followInterrupted=!1)}dispose(){this.vehicleReveal=null,this.pageScene.clear(),this.setVirtualScroll(C()),ae()}resizeLayout(e,t,n){this.outputWidth=e,this.outputHeight=t;let r=this.canvasWorld&&this.cameraLock,i=r?Ss(e,t,this.cameraFrame):0,a=(r?i:e)/this.regionScale,o=(r?i:t)/this.regionScale;this.overlay&&this.width>1&&(a!==this.width||o!==this.height)&&(this.originScroll.x+=(this.width-a)/2,this.originScroll.y+=(this.height-o)/2),this.width=a,this.height=o;let s=Math.min(e,t);this.baseZoom=this.canvasWorld?28:this.overlay?Math.max(14,Math.min(28,s/11)):Math.max(1,Math.min(s<600?32:28,(s-32)/10,s/25)),this.zoom=this.baseZoom*(this.canvasWorld||this.overlay?1:this.slowMoZoom),this.overlay&&this.regionScale===1&&!this.virtualScroll.x&&!this.virtualScroll.y&&(this.pageSize={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight}),this.smokeMargin=this.canvasWorld?96/this.regionScale:this.pixelSpace?Math.min(112,Math.max(72,Math.min(this.width,this.height)*.1)):0;let c=this.width*this.height;this.dpr=Math.min(2*(this.canvasWorld?this.regionScale:1),n*this.regionScale,Math.sqrt(24e6/c),16384/Math.max(this.width,this.height))}outputWidth=1;outputHeight=1;cameraRotation=0;cameraLock=!1;cameraSmoothing=.25;cameraLockInitialized=!1;width=1;height=1;dpr=1;smokeMargin=0;pageScene=new oe;cameraRegions=new As(this.pageScene);get documentProjection(){return this.pageScene}activeCameraRegion=null;regionScale=1;canvasWorldScale=1;cameraFrame=null;camera=C();zoom=28;baseZoom=28;slowMoScale=1;get slowMoZoom(){return this.slowMoScale??1}set slowMoZoom(e){this.slowMoScale=e}zoomAnchor=C();pageSize={width:1,height:1};lastFrame=0;originScroll=C();observedScroll=C();virtualScroll=C();followInterrupted=!1;deadZone=!0;screen(e){return C(this.width/2+(e.x-this.camera.x)*this.zoom,this.height/2-(e.y-this.camera.y)*this.zoom)}world(e){return C(this.camera.x+(e.x-this.width/2)/this.zoom,this.camera.y-(e.y-this.height/2)/this.zoom)}vehicleViewportPosition(e){return this.overlay&&this.syncScroll(),this.screen(e)}sceneScroll(){return this.canvasWorld?C(this.camera.x*28-this.width/2,-this.camera.y*28-this.height/2):S(O(),this.virtualScroll)}virtualOffset(){return{...this.virtualScroll}}documentPoint(e){return this.canvasWorld?ue(e):(this.overlay&&this.syncScroll(),S(this.screen(e),this.sceneScroll()))}worldFromDocument(e){return this.canvasWorld?ne(e):(this.overlay&&this.syncScroll(),this.world(x(e,this.sceneScroll())))}documentScale(){return this.canvasWorld?28:this.zoom}particlePoint(e){return this.pixelSpace?this.documentPoint(e):{...e}}particleScale(){return this.pixelSpace?this.documentScale():1}viewportSize(){return{width:this.width,height:this.height}}presentationScale(){return this.regionScale}setCanvasWorldScale(e,t=1.5){if(!this.canvasWorld)return;this.canvasWorldScale=Math.max(.2,Math.min(Math.max(.2,Math.min(4,Number.isFinite(t)?t:1.5)),Number.isFinite(e)?e:1));let n=this.canvasWorldScale*this.slowMoZoom;this.regionScale!==n&&(this.regionScale=n,this.resize())}setCameraFrame(e){this.cameraFrame=e,this.canvasWorld&&this.cameraLock&&this.resize()}setCameraLock(e){this.canvasWorld&&this.cameraLock!==e&&(this.cameraLock=e,this.cameraLockInitialized=!1,e||(this.cameraRotation=0),this.resize())}viewportFromDocument(e){let t=v(x(e,this.sceneScroll()),this.regionScale);return this.canvasWorld&&this.cameraLock?Cs(t,Ts(this.width,this.height,this.regionScale),xs(this.outputWidth,this.outputHeight,this.cameraFrame),this.cameraRotation):t}documentFromViewport(e){let t=this.canvasWorld&&this.cameraLock?ws(e,Ts(this.width,this.height,this.regionScale),xs(this.outputWidth,this.outputHeight,this.cameraFrame),this.cameraRotation):e;return S(v(t,1/this.regionScale),this.sceneScroll())}bounds(){this.overlay&&this.syncScroll();let e=this.width/(2*this.zoom)-3/this.zoom,t=this.height/(2*this.zoom)-3/this.zoom;return{left:this.camera.x-e,right:this.camera.x+e,bottom:this.camera.y-t,top:this.camera.y+t}}setVirtualScroll(e){if(!this.overlay)return;this.virtualScroll=C(Math.abs(e.x)<.01?0:e.x,Math.abs(e.y)<.01?0:e.y);let t=document.body;this.virtualScroll.x||this.virtualScroll.y?(t.dataset.jrVirtualCamera===void 0&&(t.dataset.jrVirtualCamera=``),t.style.setProperty(`--joy-ride-scene-x`,`${-this.virtualScroll.x}px`),t.style.setProperty(`--joy-ride-scene-y`,`${-this.virtualScroll.y}px`)):(t.dataset.jrVirtualCamera!==void 0&&delete t.dataset.jrVirtualCamera,t.style.removeProperty(`--joy-ride-scene-x`),t.style.removeProperty(`--joy-ride-scene-y`))}syncScroll(e=!1){let t=C(O().x,O().y);if(!e){let e=x(t,this.observedScroll);m(e)>.5&&(this.followInterrupted=!0)}this.observedScroll=t,(this.activeCameraRegion||this.regionScale!==1)&&this.pageScene?.apply(this.regionScale,this.sceneScroll());let n=S(t,this.virtualScroll);this.camera=C((n.x-this.originScroll.x-this.zoomAnchor.x*(this.baseZoom-this.zoom))/this.zoom,-(n.y-this.originScroll.y+this.zoomAnchor.y*(this.baseZoom-this.zoom))/this.zoom)}resumeFollow(){this.vehicleReveal=null,this.overlay&&(this.syncScroll(),this.followInterrupted=!1)}interruptFollow(){this.vehicleReveal=null,this.overlay&&(this.followInterrupted=!0)}restorePage(e){if(!this.overlay||!this.virtualScroll.x&&!this.virtualScroll.y&&!this.activeCameraRegion&&this.regionScale===1)return!1;this.syncScroll(!0);let t=v(this.screen(e.body.position),this.regionScale??1);return(this.activeCameraRegion||this.regionScale!==1)&&(this.slowMoZoom=1,this.pageScene.clear(),this.activeCameraRegion=null,this.regionScale=1,this.resize()),this.setVirtualScroll(C()),this.syncScroll(!0),e.body.position=this.world(t),!0}followDocument(e){if(!this.overlay)return!1;if(this.vehicleReveal||this.activeCameraRegion?.fixed)return!0;if(this.zoomAnchor={...e.body.position},this.syncScroll(),this.followInterrupted)return!1;let t=this.screen(e.body.position),n=Math.max(e.car.preset.geometry.lengthM*this.zoom/2+12,Math.min(this.width,this.height)*.25),r=Ds(t,{width:this.width,height:this.height},n);if(r.x||r.y){if(e.barrier)window.scrollBy({left:r.x,top:r.y,behavior:`instant`}),ae();else{let e=C(r.x*this.virtualScroll.x<0?Math.sign(r.x)*Math.min(Math.abs(r.x),Math.abs(this.virtualScroll.x)):0,r.y*this.virtualScroll.y<0?Math.sign(r.y)*Math.min(Math.abs(r.y),Math.abs(this.virtualScroll.y)):0);this.setVirtualScroll(S(this.virtualScroll,e));let t=x(r,e),n=O();(t.x||t.y)&&(window.scrollBy({left:t.x,top:t.y,behavior:`instant`}),ae());let i=x(O(),n);this.setVirtualScroll(S(this.virtualScroll,x(t,i)))}}return this.syncScroll(!0),!0}moveSceneTo(e){window.scrollBy({left:e.x-O().x,top:e.y-O().y,behavior:`instant`}),ae(),this.setVirtualScroll(C(e.x-O().x,e.y-O().y)),this.syncScroll(!0)}updateCameraRegion(e,t){let n=this.cameraFrame??{x:0,y:0,width:window.innerWidth,height:window.innerHeight},r=this.activeCameraRegion!==null&&!e,i=e!==null&&this.activeCameraRegion?.element!==e.element,a=(e?e.fixed?Os(e.bounds,n,e.zoom):Math.max(.1,Math.min(3,e.zoom??1)):1)*this.slowMoZoom,o=this.regionScale,s=v(x(t,this.sceneScroll()),o);if(this.activeCameraRegion=e,r&&this.pageScene.clear(),Math.abs(a-this.regionScale)>1e-4&&(this.regionScale=a,this.resize()),e?.fixed){this.zoom=this.baseZoom;let t=e.bounds;this.moveSceneTo(C(t.x+t.width/2-(n.x+n.width/2)/this.regionScale,t.y+t.height/2-(n.y+n.height/2)/this.regionScale))}else(r||i)&&(this.followInterrupted=!1,this.moveSceneTo(C(t.x-this.width/2,t.y-this.height/2)));!e?.fixed&&!r&&!i&&Math.abs(a-o)>1e-4&&this.moveSceneTo(x(t,v(s,1/a))),e||a!==1?this.pageScene.apply(this.regionScale,this.sceneScroll()):this.pageScene.clear()}cameraStep(e,t){let n=this.lastFrame?b((t-this.lastFrame)/1e3,0,.1):1/60;this.lastFrame=t;let r=e.body;if(this.canvasWorld){if(this.cameraLock){let e=r.angle-Math.PI/2,t=!this.cameraLockInitialized||m(x(r.position,this.camera))>40;this.cameraRotation=t?e:Es(this.cameraRotation,e,n,this.cameraSmoothing),t&&(this.camera={...r.position}),this.cameraLockInitialized=!0}else this.cameraRotation=0}let i=C(this.width/2+r.position.x*this.baseZoom+this.originScroll.x,this.height/2-r.position.y*this.baseZoom+this.originScroll.y),a=this.overlay?this.cameraRegions.at(i,this.virtualScroll,t):null;this.overlay&&this.updateCameraRegion(a,i);let o=this.zoom;if(this.canvasWorld){let e=this.canvasWorldScale*this.slowMoZoom;Math.abs(this.regionScale-e)>1e-4&&(this.regionScale=e,this.resize()),this.zoom=this.baseZoom}else this.zoom=this.baseZoom*(this.overlay?1:this.slowMoZoom);if(this.overlay){this.zoomAnchor={...r.position},this.syncScroll(),this.advanceVehicleReveal(t,e);return}if(e.barrier)return;let s=o/this.zoom;if(this.camera=C(r.position.x-(r.position.x-this.camera.x)*s,r.position.y-(r.position.y-this.camera.y)*s),this.canvasWorld&&this.cameraLock){let e=this.cameraSmoothing<=0?1:1-Math.exp(-n/this.cameraSmoothing);this.camera=S(this.camera,v(x(r.position,this.camera),e));return}if(!this.deadZone){let e=this.canvasWorld&&!this.cameraLock?this.cameraFrame:null;this.camera=e?C(r.position.x-((e.x+e.width/2)/this.regionScale-this.width/2)/this.zoom,r.position.y+((e.y+e.height/2)/this.regionScale-this.height/2)/this.zoom):{...r.position};return}let c=this.width*.18/this.zoom,l=this.height*.18/this.zoom,u=C(r.position.x-b(r.position.x-this.camera.x,-c,c),r.position.y-b(r.position.y-this.camera.y,-l,l));this.camera=S(this.camera,v(x(u,this.camera),1-Math.exp(-16*n)))}},Ms=class{canvas;camera;overlay;canvasWorld;sceneCanvas=null;sceneContext;documentOrigin={x:0,y:0};originalPosition;constructor(e,t,n,r){this.canvas=e,this.camera=t,this.overlay=n,this.canvasWorld=r;let i=e.getContext(`2d`);if(!i)throw Error(`Joy Ride requires a 2D canvas context.`);this.sceneContext=i,this.originalPosition={position:e.style.position,left:e.style.left,top:e.style.top,translate:e.style.translate}}setAbsoluteViewport(){this.overlay&&(this.canvas.style.position=`absolute`,this.measureDocumentOrigin(),this.place())}measureDocumentOrigin(){if(!this.overlay)return;if(!this.canvas.offsetParent){this.documentOrigin={x:0,y:0};return}let e=this.canvas.offsetParent,t=e.getBoundingClientRect(),n=O();this.documentOrigin={x:t.left+n.x+e.clientLeft,y:t.top+n.y+e.clientTop}}place(){if(!this.overlay)return;let e=O();this.canvas.style.left!==`0px`&&(this.canvas.style.left=`0px`),this.canvas.style.top!==`0px`&&(this.canvas.style.top=`0px`);let t=`${e.x-this.documentOrigin.x}px ${e.y-this.documentOrigin.y}px`;this.canvas.style.translate!==t&&(this.canvas.style.translate=t)}get context(){return this.sceneContext}resize(){let e=Math.max(1,this.overlay?window.innerWidth:this.canvas.clientWidth),t=Math.max(1,this.overlay?window.innerHeight:this.canvas.clientHeight),n=e/this.camera.regionScale!==this.camera.width||t/this.camera.regionScale!==this.camera.height;this.camera.resizeLayout(e,t,window.devicePixelRatio||1);let r=this.canvasWorld&&this.camera.cameraLock;r?(this.sceneCanvas??=document.createElement(`canvas`),this.sceneContext=this.sceneCanvas.getContext(`2d`)):this.sceneCanvas&&(this.sceneContext=this.canvas.getContext(`2d`)),this.overlay&&(n||this.canvas.style.width!==`${this.camera.width}px`)&&(this.canvas.style.width=`${this.camera.width}px`,this.canvas.style.height=`${this.camera.height}px`,this.canvas.style.transformOrigin=`0 0`,this.canvas.style.scale=String(this.camera.regionScale));let i=Math.round(this.camera.width*this.camera.dpr),a=Math.round(this.camera.height*this.camera.dpr),o=r?this.sceneCanvas:this.canvas;if((o.width!==i||o.height!==a)&&(o.width=i,o.height=a),r){let n=this.camera.dpr/this.camera.regionScale,r=Math.round(e*n),i=Math.round(t*n);this.canvas.width!==r&&(this.canvas.width=r),this.canvas.height!==i&&(this.canvas.height=i)}return this.sceneContext.setTransform(this.camera.dpr,0,0,this.camera.dpr,0,0),this.measureDocumentOrigin(),this.canvasWorld?this.camera.dpr:void 0}clear(){this.place(),this.sceneContext.setTransform(this.camera.dpr,0,0,this.camera.dpr,0,0),this.sceneContext.clearRect(0,0,this.camera.width,this.camera.height)}presentLockedCamera(){if(!this.canvasWorld||!this.camera.cameraLock||!this.sceneCanvas)return;let e=this.canvas.getContext(`2d`),t=this.camera.dpr/this.camera.regionScale,n=xs(this.camera.outputWidth,this.camera.outputHeight,this.camera.cameraFrame);e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,this.canvas.width,this.canvas.height),e.save(),e.translate(n.x*t,n.y*t),e.rotate(this.camera.cameraRotation),e.drawImage(this.sceneCanvas,-this.sceneCanvas.width/2,-this.sceneCanvas.height/2),e.restore()}dispose(){this.sceneCanvas&&=(this.sceneCanvas.width=1,this.sceneCanvas.height=1,null),this.canvas.style.scale=``,this.canvas.style.transformOrigin=``,this.overlay&&(this.canvas.style.position=this.originalPosition.position,this.canvas.style.left=this.originalPosition.left,this.canvas.style.top=this.originalPosition.top,this.canvas.style.translate=this.originalPosition.translate)}},Ns=class{frameRate=new he;captureState(){return this.frameRate.captureState()}restoreState(e){this.frameRate.restoreState(e)}draw(e,t,n,r,i){let a=e,o=t.body,s=this.frameRate.sample(n);a.save();let c=He(t.car.preset);for(let e of t.car.tires){let t=r(o.world(e.local));a.strokeStyle=e.front?`#00dcff`:`#ffae31`,a.lineWidth=2;let n=[C(-c.length/2,-c.width/2),C(c.length/2,-c.width/2),C(c.length/2,c.width/2),C(-c.length/2,c.width/2)].map(t=>r(o.world(S(e.local,h(t,e.angle)))));a.beginPath(),n.forEach((e,t)=>t?a.lineTo(e.x,e.y):a.moveTo(e.x,e.y)),a.closePath(),a.stroke(),a.beginPath(),a.arc(t.x,t.y,4,0,Math.PI*2),a.stroke(),a.beginPath(),a.moveTo(t.x-7,t.y),a.lineTo(t.x+7,t.y),a.moveTo(t.x,t.y-7),a.lineTo(t.x,t.y+7),a.stroke(),a.font=`bold 10px ui-monospace, SFMono-Regular, monospace`,a.fillStyle=e.front?`#007e91`:`#895000`,a.fillText(`${e.front?`F`:`R`}${e.local.y>0?`L`:`R`}${e.skidding?` SKID`:``}`,t.x+8,t.y-8)}let l=r(o.position),u=(e,t,n)=>{let r=S(l,v(e,n));a.strokeStyle=t,a.fillStyle=t,a.lineWidth=2.5,a.beginPath(),a.moveTo(l.x,l.y),a.lineTo(r.x,r.y),a.stroke();let i=Math.atan2(e.y,e.x);a.beginPath(),a.moveTo(r.x,r.y),a.lineTo(r.x-Math.cos(i-.5)*9,r.y-Math.sin(i-.5)*9),a.lineTo(r.x-Math.cos(i+.5)*9,r.y-Math.sin(i+.5)*9),a.closePath(),a.fill()};u(C(Math.cos(o.angle),-Math.sin(o.angle)),`#00c4df`,67);let d=m(o.velocity);d>.2&&u(C(o.velocity.x/d,-o.velocity.y/d),`#f05bd6`,48+Math.min(32,d));let f=Math.atan2(o.velocity.y,o.velocity.x),p=Math.atan2(Math.sin(o.angle-f),Math.cos(o.angle-f)),g=Math.max(...t.car.tires.filter(e=>e.front).map(e=>e.gripUtilization)),_=Math.max(...t.car.tires.filter(e=>!e.front).map(e=>e.gripUtilization)),y=t.car.tires.map(e=>`${e.front?`F`:`R`}${e.local.y>0?`L`:`R`} ${e.slipSpeedMps.toFixed(1)}${e.skidding?`*`:``}`).join(` `),b=[`${t.car.preset.name} · ${(d*3.6).toFixed(0)} km/h · ${Math.round(s)} FPS`,`input T ${t.lastInput.throttle} S ${t.lastInput.steer} brake ${Number(t.lastInput.action)}`,`body ${Math.round(o.angle*180/Math.PI)}° travel ${Math.round(f*180/Math.PI)}° slip ${Math.round(p*180/Math.PI)}°`,`front load ${(t.car.frontLoadFraction*100).toFixed(0)}% burnout ${Number(t.car.burnout)} charge ${t.car.boostCharge.toFixed(2)}`,`grip use F ${g.toFixed(2)} R ${_.toFixed(2)} drift ${Number(t.car.drifting)} donut ${Number(t.car.donuting)}`,`drift ${Number(t.car.fastDrifting)} countersteer ${Number(t.car.countersteering)}`,`roof rocket ${i.rocketState}`,`side guns ${i.gunState} · ${i.bulletCount} bullets`,`tire slip m/s ${y}`,`fluid ${i.fluidEngine} ${i.quality} ${i.fluidCols}×${i.fluidRows}`,`shared fire ${i.fireCols}×${i.fireRows} · ${i.groundedFireCount} grounded sources`,`cyan = nose/shape pink = travel amber = walls`,`wheel cyan = front wheel amber = rear violet = letters`];a.fillStyle=`rgba(10, 21, 24, 0.87)`,a.fillRect(12,88,Math.min(430,i.width-24),b.length*18+18),a.font=`12px ui-monospace, SFMono-Regular, monospace`,a.fillStyle=`#f1f5f3`,b.forEach((e,t)=>a.fillText(e,22,110+t*18)),a.restore()}},W=1024,Ps=Math.PI*2,Fs=Array.from({length:W},(e,t)=>({x:Math.cos(t/W*Ps),y:Math.sin(t/W*Ps)}));function Is(e,t,n){return n.filter(n=>{let r=Math.max(n.x-e.x,0,e.x-n.x-n.width),i=Math.max(n.y-e.y,0,e.y-n.y-n.height);return n.width>0&&n.height>0&&r*r+i*i<=t*t})}function Ls(e,t,n){let r=Math.abs(t.x)<1e-8,i=Math.abs(t.y)<1e-8;if(r&&(e.x<n.x||e.x>n.x+n.width)||i&&(e.y<n.y||e.y>n.y+n.height))return 1/0;let a=r?-1/0:(n.x-e.x)/t.x,o=r?1/0:(n.x+n.width-e.x)/t.x,s=i?-1/0:(n.y-e.y)/t.y,c=i?1/0:(n.y+n.height-e.y)/t.y,l=Math.max(0,Math.min(a,o),Math.min(s,c));return l<=Math.min(Math.max(a,o),Math.max(s,c))?l:1/0}function Rs(e,t,n){let r=Is(e,t,n);if(!r.length)return;let i=new Float32Array(W);for(let n=0;n<i.length;n++){let a=t;for(let t of r)a=Math.min(a,Ls(e,Fs[n],t));i[n]=a/t}return{range:t,distances:i}}function zs(e,t,n,r){for(let i of Is(t,n,r)){if(t.x>=i.x&&t.x<=i.x+i.width&&t.y>=i.y&&t.y<=i.y+i.height){e.beginPath(),e.clip();return}let r=[{x:i.x,y:i.y},{x:i.x+i.width,y:i.y},{x:i.x+i.width,y:i.y+i.height},{x:i.x,y:i.y+i.height}],a=e=>{let r=1+n*4/Math.max(.001,Math.hypot(e.x-t.x,e.y-t.y));return{x:t.x+(e.x-t.x)*r,y:t.y+(e.y-t.y)*r}};for(let i=0;i<r.length;i++){let o=r[i],s=r[(i+1)%r.length];if((s.x-o.x)*(t.y-o.y)-(s.y-o.y)*(t.x-o.x)>=0)continue;let c=a(o),l=a(s);e.beginPath(),e.rect(t.x-n,t.y-n,n*2,n*2),e.moveTo(o.x,o.y),e.lineTo(s.x,s.y),e.lineTo(l.x,l.y),e.lineTo(c.x,c.y),e.closePath(),e.clip(`evenodd`)}}}var Bs=[.82,.91,1],Vs=[1,.045,.018],Hs=e=>Math.max(0,Math.min(1,e));function Us(e){let t=/^#([\da-f]{6})$/i.exec(e);if(!t)return[.4,.9,1];let n=parseInt(t[1],16);return[(n>>16)/255,(n>>8&255)/255,(n&255)/255]}function Ws(e,t,n){let r=Math.cos(e.angle),i=Math.sin(e.angle);return{x:e.center.x+r*t-i*n,y:e.center.y+i*t+r*n}}var Gs=class{sprites=new WeakMap;halos=new WeakMap;beam=null;sprite(e){let t=e.image;if(!t||!t.complete||!t.naturalWidth)return null;let n=e.source??{x:0,y:0,width:t.naturalWidth,height:t.naturalHeight},r=e.mounts.taillights.map(t=>`${Math.round(t.x/e.width*1e4)},${Math.round(t.y/e.height*1e4)}`).join(`;`),i=`${n.x},${n.y},${n.width},${n.height}|${r}`,a=this.sprites.get(t);if(a||(a=new Map,this.sprites.set(t,a)),a.has(i))return a.get(i)??null;let o=document.createElement(`canvas`);o.width=192,o.height=Math.max(24,Math.round(192*n.height/n.width));let s=o.getContext(`2d`,{willReadFrequently:!0});if(!s)return a.set(i,null),null;s.drawImage(t,n.x,n.y,n.width,n.height,0,0,o.width,o.height);let c;try{c=s.getImageData(0,0,o.width,o.height)}catch{return a.set(i,null),null}let l=s.createImageData(o.width,o.height),u=0;for(let t=0;t<o.height;t++)for(let n=0;n<o.width;n++){let r=(t*o.width+n)*4,i=c.data[r],a=c.data[r+1],s=c.data[r+2],d=c.data[r+3];n<o.width*.27&&i>100&&i>a*1.6&&i>s*1.5&&d>100&&e.mounts.taillights.some(r=>{let i=n-(.5+r.x/e.width)*o.width,a=t-(.5+r.y/e.height)*o.height;return i*i+a*a<(o.height*.18)**2})&&(l.data[r]=255,l.data[r+1]=22,l.data[r+2]=5,l.data[r+3]=Math.min(235,d),u++),c.data[r]=255,c.data[r+1]=255,c.data[r+2]=255,c.data[r+3]=d>90?255:0}s.putImageData(c,0,0);let d=null;u>1&&u<o.width*o.height*.055&&(d=document.createElement(`canvas`),d.width=o.width,d.height=o.height,d.getContext(`2d`)?.putImageData(l,0,0));let f={silhouette:o,brakes:d};return a.size>=8&&a.clear(),a.set(i,f),f}halo(e,t){let n=this.halos.get(e);n||(n=new Map,this.halos.set(e,n));let r=n.get(t);if(r)return r;let i=document.createElement(`canvas`);i.width=e.width+64,i.height=e.height+64;let a=i.getContext(`2d`);a.drawImage(e,32,32),a.globalCompositeOperation=`source-in`,a.fillStyle=t,a.fillRect(0,0,i.width,i.height),a.globalCompositeOperation=`source-over`;let o=document.createElement(`canvas`);o.width=i.width,o.height=i.height,o.getContext(`2d`).drawImage(i,0,0),a.clearRect(0,0,i.width,i.height),a.filter=`blur(14px)`,a.globalAlpha=.92,a.drawImage(o,-2,-5,o.width+4,o.height+10),a.filter=`blur(7px)`,a.globalAlpha=.9,a.drawImage(o,0,0),a.filter=`blur(3px)`,a.globalAlpha=.8,a.strokeStyle=t,a.lineWidth=3,a.lineCap=`round`;for(let t of[-1,1])a.beginPath(),a.moveTo(32+e.width*.18,32+e.height*(.5+t*.34)),a.lineTo(32+e.width*.82,32+e.height*(.5+t*.34)),a.stroke();return a.filter=`none`,a.globalAlpha=1,n.size>8&&n.clear(),n.set(t,i),i}beamImage(){if(this.beam)return this.beam;let e=document.createElement(`canvas`);e.width=256,e.height=128;let t=e.getContext(`2d`),n=t.createImageData(e.width,e.height);for(let t=0;t<e.height;t++)for(let r=0;r<e.width;r++){let i=r/e.width,a=(t/e.height-.5)*2,o=.035+i*.94,s=Hs((1-i)/.4),c=Math.exp(-a*a/(o*o))*s*s*(3-2*s),l=(t*e.width+r)*4;n.data[l]=210,n.data[l+1]=230,n.data[l+2]=255,n.data[l+3]=Math.round(c*255)}return t.putImageData(n,0,0),this.beam=e,e}clip(e,t,n,r){t.walls?.length&&(e.rotate(-t.angle),e.translate(-t.center.x,-t.center.y),zs(e,Ws(t,n.x,n.y),r,t.walls),e.translate(t.center.x,t.center.y),e.rotate(t.angle))}ground(e,t){let n=t.opacity??1,r=t.options.brakeLights?Hs(t.braking):0;if(!(n<=0||t.width<=0)){if(e.save(),e.translate(t.center.x,t.center.y),e.rotate(t.angle),e.globalCompositeOperation=`screen`,t.dark&&t.options.underglow&&t.options.underglowOpacity>0){e.save(),this.clip(e,t,{x:0,y:0},t.width*1.5);let r=this.sprite(t);if(e.globalAlpha=Hs(t.options.underglowOpacity)*n,r){let n=this.halo(r.silhouette,t.options.underglow),i=32/r.silhouette.width*t.width,a=32/r.silhouette.height*t.height;e.drawImage(n,-t.width/2-i,-t.height/2-a,t.width+i*2,t.height+a*2)}else e.shadowColor=t.options.underglow,e.shadowBlur=t.height*.5,e.fillStyle=t.options.underglow,e.beginPath(),e.roundRect(-t.width*.43,-t.height*.38,t.width*.86,t.height*.76,t.height*.22),e.fill(),e.shadowBlur=0;e.restore()}if(t.dark&&t.options.headlights)for(let r of t.mounts.headlights)e.save(),this.clip(e,t,r,t.width*6.2),e.globalAlpha=.085*n,e.drawImage(this.beamImage(),r.x,r.y-t.width*.68,t.width*5.7,t.width*1.36),e.restore();if(t.dark&&t.options.taillights||r>0){let i=r;for(let{x:r,y:a}of t.mounts.taillights){let o=t.height*(.48+i*.38);e.save(),this.clip(e,t,{x:r,y:a},o),e.globalAlpha=.1;let s=e.createRadialGradient(r,a,0,r,a,o),c=(t.dark?.12+i*.19:i*.13)*n;s.addColorStop(0,`rgba(255,30,8,${c})`),s.addColorStop(1,`rgba(255,20,4,0)`),e.fillStyle=s,e.fillRect(r-o,a-o,o*2,o*2),e.restore()}}e.restore()}}glints(e,t){e.save(),e.translate(t.center.x,t.center.y),e.rotate(t.angle),e.globalCompositeOperation=`screen`;let n=t.opacity??1,r=t.options.brakeLights?Hs(t.braking):0;if(r>0){let i=this.sprite(t)?.brakes;i&&(e.globalAlpha=r*n*(t.dark?.9:.52),e.shadowColor=`#ff250d`,e.shadowBlur=t.height*(t.dark?.16:.055),e.drawImage(i,-t.width/2,-t.height/2,t.width,t.height))}for(let i of[!0,!1])if(!(i?!(t.dark&&t.options.headlights):!(t.dark&&t.options.taillights||r>0)))for(let a of t.mounts[i?`headlights`:`taillights`]){e.save(),e.globalAlpha=n*(i?.75:t.dark?.34+r*.6:r*.45);let o=t.height*(i?.15:.12);this.clip(e,t,a,o);let s=e.createRadialGradient(a.x,a.y,0,a.x,a.y,o);s.addColorStop(0,i?`#e6f1ffd9`:`#ff3518c0`),s.addColorStop(.28,i?`#c1dcff70`:`#ff230760`),s.addColorStop(1,i?`#c1dcff00`:`#ff230700`),e.fillStyle=s,e.beginPath(),e.arc(a.x,a.y,o,0,Math.PI*2),e.fill(),e.restore()}e.restore()}smokeLights(e){let t=[],n={x:Math.cos(e.angle),y:Math.sin(e.angle)},r=e.opacity??1,i=e.options.brakeLights?Hs(e.braking):0;if(e.dark&&e.options.headlights)for(let i of e.mounts.headlights)t.push({point:Ws(e,i.x,i.y),direction:n,color:Bs,range:e.width*6.2,radius:e.height*.075,spread:.14,intensity:1.7*r});if(e.dark&&e.options.taillights||i>0)for(let a of e.mounts.taillights)t.push({point:Ws(e,a.x,a.y),direction:{x:-n.x,y:-n.y},color:Vs,range:e.width*(i>0?1.6:.9),radius:e.height*.15,spread:.46,intensity:r*(e.dark?.24+i*.85:i*.42)});if(e.dark&&e.options.underglow&&e.options.underglowOpacity>0)for(let n of[-.27,0,.27])t.push({point:Ws(e,e.width*n,0),direction:{x:0,y:0},color:Us(e.options.underglow),range:e.height,radius:e.height*.8,spread:0,intensity:r*e.options.underglowOpacity*.8});return t.map(t=>{let n=Rs(t.point,Math.max(t.range,t.radius*4),e.walls??[]);return n?{...t,shadow:n}:t})}},Ks={light:{ink:`#161c17`,alphaScale:1},dark:{ink:`#a9adb0`,alphaScale:1.7}};function qs(e){let t=e.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i);if(!t)return!1;let[,n,r,i]=t.map(Number);return n*.2126+r*.7152+i*.0722<112}function Js(e){let t=0,n=0,r=0,i=0;for(let a of e.layers){let e=`layers`in a?Js(a):[a.color[0]*a.alpha,a.color[1]*a.alpha,a.color[2]*a.alpha,a.alpha];if(t+=(1-i)*e[0],n+=(1-i)*e[1],r+=(1-i)*e[2],i+=(1-i)*e[3],i>=.9999)break}return[t*e.opacity,n*e.opacity,r*e.opacity,i*e.opacity]}function Ys(e,t=!1){let n={opacity:1,layers:[]},r=new Map,i=new Map,a=e=>{let t=r.get(e);return t||(t=getComputedStyle(e),r.set(e,t)),t},o=e=>{let t=i.get(e);if(t)return t;let r=e.parentElement?o(e.parentElement):n,s=Number.parseFloat(a(e).opacity),c=Number.isFinite(s)?Math.max(0,Math.min(1,s)):1,l=r;return c<1&&(l={opacity:c,layers:[]},r.layers.push(l)),i.set(e,l),l};for(let t of document.elementsFromPoint(e.x,e.y)){if(!(t instanceof HTMLElement)||t.closest(`[data-jr-overlay],[data-jr-embed],[data-jr-touch-controls]`))continue;let e=fe(a(t).backgroundColor);if(!e||e.alpha<=0)continue;let n=e.color.match(/[\d.]+/g).slice(0,3).map(Number);o(t).layers.push({color:n,alpha:e.alpha})}let[s,c,l,u]=Js(n);if(u<=0)return null;let d=t?0:255;return qs(`rgb(${s+d*(1-u)} ${c+d*(1-u)} ${l+d*(1-u)})`)}var Xs=class{resolve;samples=new WeakMap;constructor(e=Ys){this.resolve=e}at(e,t,n,r=performance.now()){let i=this.samples.get(e);if(i&&i.fallback===n&&r-i.at<80&&Math.hypot(t.x-i.x,t.y-i.y)<48)return i.dark;let a=this.resolve(t,n)??n;return this.samples.set(e,{x:t.x,y:t.y,at:r,dark:a,fallback:n}),a}},Zs=64,Qs=e=>e.width>0&&e.height>0&&e.width<=64&&e.height<=64&&e.pixelWidth<=128&&e.pixelHeight<=128&&e.fixedRadius===void 0&&e.blastAge===void 0&&!e.smokeOnly,$s=class{groups=new Map;combine(e,t,n){let r=e.filter(Qs);if(r.length<Zs)return[...e];let i=Math.ceil(t/2),a=Math.ceil(n/2),o=e.filter(e=>!Qs(e)),s=new Map;for(let e of r){let t=Math.max(0,Math.min(.999,e.age/Math.max(.01,e.burnSeconds))),n=Math.floor(t*4),r=s.get(n)??[];r.push(e),s.set(n,r)}for(let[e,r]of s){let s=this.groups.get(e);s&&s.alpha.length===i*a||(s={key:{},alpha:new Uint8Array(i*a),revision:0},this.groups.set(e,s)),s.alpha.fill(0);let c=!1;for(let e of r)c=this.rasterize(s.alpha,i,a,e,t,n)||c;if(!c)continue;s.revision++;let l=r.reduce((e,t)=>e+t.age/Math.max(.01,t.burnSeconds),0)/r.length;o.push({key:s.key,alpha:s.alpha,pixelWidth:i,pixelHeight:a,x:0,y:0,width:t,height:n,origin:{x:t/2,y:n/2},age:l,farthest:Math.max(t,n),spreadSeconds:0,burnSeconds:1,smokeRate:r.reduce((e,t)=>e+(t.smokeRate??13),0)/r.length,revision:s.revision})}return o}rasterize(e,t,n,r,i,a){let o=t/i,s=n/a,c=r.x+r.width/2,l=r.y+r.height/2,u=Math.cos(r.angle??0),d=Math.sin(r.angle??0),f=Math.hypot(r.width,r.height)/2,p=Math.max(0,Math.floor((c-f)*o)),m=Math.min(t-1,Math.ceil((c+f)*o)),h=Math.max(0,Math.floor((l-f)*s)),g=Math.min(n-1,Math.ceil((l+f)*s)),_=!1;for(let n=h;n<=g;n++){let i=(n+.5)/s-l;for(let a=p;a<=m;a++){let s=(a+.5)/o-c,l=s*u+i*d+r.width/2,f=-s*d+i*u+r.height/2;if(l<0||l>=r.width||f<0||f>=r.height)continue;let p=Math.floor(l/r.width*r.pixelWidth),m=Math.floor(f/r.height*r.pixelHeight),h=Math.round((r.alpha[m*r.pixelWidth+p]??0)*(r.intensity??1)),g=n*t+a;h>e[g]&&(e[g]=h),_||=h>0}}return _}},ec=class{points=[];get count(){return this.points.length}get managedBytes(){return this.points.length*40}captureState(){return{points:this.points.map(({point:e,...t})=>({point:{...e},...t})),dispose:()=>void 0}}restoreState(e){this.points=e?.points.map(({point:e,...t})=>({point:{...e},...t}))??[]}reset(){this.points=[]}dispose(){this.reset()}ignite(e,t,n,r,i){let a=x(t,e),o=Math.max(1,Math.ceil(m(a)/Math.max(1,i)));for(let t=1;t<=o;t++)this.points.push({point:S(e,v(a,t/o)),width:n,age:0,lifetime:r});this.points.length>1200&&this.points.splice(0,this.points.length-1200)}step(e){let t=0;for(let n of this.points)n.age+=e,n.age<n.lifetime&&(this.points[t++]=n);this.points.length=t}stamps(){return this.points.map(({point:e,width:t,age:n,lifetime:r})=>({point:e,radius:Math.max(5,t*.8),progress:.42,flow:C(0,-25),strength:Math.max(0,1-(n/r)**2)*1.85,stir:!1}))}emberSource(){if(!this.points.length)return null;let e=this.points[Math.floor(Math.random()*this.points.length)];return{point:e.point,radius:e.width*.42,heat:Math.max(0,1-(e.age/e.lifetime)**2)}}},tc=3.2;function nc(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}function rc(e){return{dissipation:.55+2.3*nc(1.35,2.65,e),opacity:1-nc(2.25,tc,e)}}var ic=class{gl;width;height;texture;framebuffer;disposed=!1;constructor(e,t,n,r,i,a){this.gl=e,this.width=n,this.height=r;let o=e.createTexture(),s=e.createFramebuffer();if(!o||!s)throw o&&e.deleteTexture(o),s&&e.deleteFramebuffer(s),Error(`Unable to allocate GPU checkpoint`);this.texture=o,this.framebuffer=s;let c=e.getParameter(e.READ_FRAMEBUFFER_BINDING),l=e.getParameter(e.DRAW_FRAMEBUFFER_BINDING),u=e.getParameter(e.TEXTURE_BINDING_2D);try{if(e.bindTexture(e.TEXTURE_2D,o),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,i,n,r,0,e.RGBA,a,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,s),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,o,0),e.checkFramebufferStatus(e.DRAW_FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE)throw Error(`GPU checkpoint target is incomplete`);if(e.bindFramebuffer(e.READ_FRAMEBUFFER,t),e.blitFramebuffer(0,0,n,r,0,0,n,r,e.COLOR_BUFFER_BIT,e.NEAREST),e.getError()!==e.NO_ERROR)throw Error(`GPU checkpoint copy failed`)}catch(t){throw e.deleteFramebuffer(s),e.deleteTexture(o),t}finally{e.bindFramebuffer(e.READ_FRAMEBUFFER,c),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,l),e.bindTexture(e.TEXTURE_2D,u)}}restore(e,t=this.width,n=this.height){if(this.disposed)throw Error(`GPU checkpoint has been disposed`);let r=this.gl,i=r.getParameter(r.READ_FRAMEBUFFER_BINDING),a=r.getParameter(r.DRAW_FRAMEBUFFER_BINDING);try{if(r.bindFramebuffer(r.READ_FRAMEBUFFER,this.framebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,e),r.blitFramebuffer(0,0,this.width,this.height,0,0,t,n,r.COLOR_BUFFER_BIT,r.NEAREST),r.getError()!==r.NO_ERROR)throw Error(`GPU checkpoint restore failed`)}finally{r.bindFramebuffer(r.READ_FRAMEBUFFER,i),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,a)}}dispose(){this.disposed||(this.disposed=!0,this.gl.deleteFramebuffer(this.framebuffer),this.gl.deleteTexture(this.texture))}},ac=`
|
|
98
|
-
uniform int vehicleLightCount;
|
|
99
|
-
uniform vec4 vehicleLightPosition[12];
|
|
100
|
-
uniform vec4 vehicleLightShape[12];
|
|
101
|
-
uniform vec4 vehicleLightColor[12];
|
|
102
|
-
uniform sampler2D vehicleLightShadows;
|
|
103
|
-
vec3 scatterVehicleLight(vec3 baseColor, float density, vec2 canvasPoint, bool dark) {
|
|
104
|
-
if (vehicleLightCount == 0) return baseColor;
|
|
105
|
-
vec3 radiance = vec3(0.0);
|
|
106
|
-
vec2 slope = vec2(dFdx(density), -dFdy(density));
|
|
107
|
-
vec3 normal = normalize(vec3(-slope * 8.0, 0.7));
|
|
108
|
-
for (int i = 0; i < 12; i++) {
|
|
109
|
-
if (i >= vehicleLightCount) break;
|
|
110
|
-
vec2 offset = canvasPoint - vehicleLightPosition[i].xy;
|
|
111
|
-
vec2 direction = vehicleLightShape[i].xy;
|
|
112
|
-
float radius = max(1.0, vehicleLightPosition[i].w);
|
|
113
|
-
float strength;
|
|
114
|
-
if (dot(direction, direction) < 0.1) {
|
|
115
|
-
strength = exp(-dot(offset, offset) / (radius * radius));
|
|
116
|
-
} else {
|
|
117
|
-
float along = dot(offset, direction);
|
|
118
|
-
float distance = along / max(1.0, vehicleLightPosition[i].z);
|
|
119
|
-
float across = dot(offset, vec2(-direction.y, direction.x));
|
|
120
|
-
float beamWidth = radius + max(0.0, along) * vehicleLightShape[i].z;
|
|
121
|
-
strength = exp(-across * across / (beamWidth * beamWidth));
|
|
122
|
-
strength *= step(0.0, along) * (1.0 - smoothstep(0.64, 1.0, distance));
|
|
123
|
-
strength *= 1.0 - clamp(distance, 0.0, 1.0) * 0.42;
|
|
124
|
-
}
|
|
125
|
-
if (strength < 0.0001) continue;
|
|
126
|
-
if (vehicleLightShape[i].w > 0.0) {
|
|
127
|
-
float ray = fract(atan(offset.y, offset.x) / 6.28318530718 + 1.0) * ${W}.0;
|
|
128
|
-
float row = (float(i) + 0.5) / 12.0;
|
|
129
|
-
float a = texture(vehicleLightShadows, vec2((floor(ray) + 0.5) / ${W}.0, row)).r;
|
|
130
|
-
float b = texture(vehicleLightShadows, vec2((mod(floor(ray) + 1.0, ${W}.0) + 0.5) / ${W}.0, row)).r;
|
|
131
|
-
float reach = min(a, b) * vehicleLightShape[i].w;
|
|
132
|
-
strength *= step(0.001, reach) * (1.0 - smoothstep(max(0.0, reach - 1.0), max(0.001, reach), length(offset)));
|
|
133
|
-
}
|
|
134
|
-
// Curling edges face the source differently as the smoke moves.
|
|
135
|
-
vec2 towardLight = -offset / max(1.0, length(offset));
|
|
136
|
-
float facing = max(0.0, dot(normal, normalize(vec3(towardLight * 0.65, 0.75))));
|
|
137
|
-
float edge = clamp(length(slope) * 18.0, 0.0, 1.0);
|
|
138
|
-
strength *= 0.72 + facing * 0.28 + edge * 0.32;
|
|
139
|
-
radiance += vehicleLightColor[i].rgb * strength * vehicleLightColor[i].a;
|
|
140
|
-
}
|
|
141
|
-
float illumination = max(radiance.r, max(radiance.g, radiance.b));
|
|
142
|
-
// Toggling a source must not change smoke outside its finite light field.
|
|
143
|
-
vec3 ambient = baseColor;
|
|
144
|
-
// Thin edges transmit light; dense centers retain their volume and texture.
|
|
145
|
-
float transmission = 1.0 / (1.0 + max(0.0, density) * 0.11);
|
|
146
|
-
vec3 lit = radiance / max(illumination, 0.0001);
|
|
147
|
-
// White particles retain a neutral component under colored light. This
|
|
148
|
-
// avoids turning the entire dense plume into a flat, saturated red decal.
|
|
149
|
-
float chroma = max(lit.r, max(lit.g, lit.b)) - min(lit.r, min(lit.g, lit.b));
|
|
150
|
-
lit = mix(lit, vec3(1.0), chroma * 0.24);
|
|
151
|
-
float scattering = 1.0 - exp(-illumination * transmission * 1.28);
|
|
152
|
-
return mix(ambient, lit, scattering * 0.65) + radiance * 0.045 * transmission;
|
|
153
|
-
}
|
|
154
|
-
`,oc=[214,216,215].map(e=>e/255),sc={low:{simulation:96,dye:512,iterations:8},medium:{simulation:160,dye:960,iterations:14},high:{simulation:320,dye:1536,iterations:22}},cc=`#version 300 es
|
|
155
|
-
in vec2 aPosition;
|
|
156
|
-
out vec2 vUv;
|
|
157
|
-
void main() { vUv = aPosition * 0.5 + 0.5; gl_Position = vec4(aPosition, 0.0, 1.0); }`,G=`#version 300 es
|
|
158
|
-
precision highp float;
|
|
159
|
-
in vec2 vUv;
|
|
160
|
-
out vec4 color;
|
|
161
|
-
`,lc=`#version 300 es
|
|
162
|
-
in vec4 aStamp;
|
|
163
|
-
in float aStrength;
|
|
164
|
-
uniform vec2 canvasSize, dyeSize;
|
|
165
|
-
out float strength;
|
|
166
|
-
out float progress;
|
|
167
|
-
void main() {
|
|
168
|
-
gl_Position = vec4(aStamp.xy / canvasSize * vec2(2.0, -2.0)
|
|
169
|
-
+ vec2(-1.0, 1.0), 0.0, 1.0);
|
|
170
|
-
gl_PointSize = max(1.0, aStamp.z * 2.0 * dyeSize.x / canvasSize.x);
|
|
171
|
-
strength = aStrength * (1.0 - aStamp.w * 0.32);
|
|
172
|
-
progress = aStamp.w;
|
|
173
|
-
}`,uc=`#version 300 es
|
|
174
|
-
precision highp float;
|
|
175
|
-
in float strength;
|
|
176
|
-
in float progress;
|
|
177
|
-
uniform bool agePalette;
|
|
178
|
-
out vec4 color;
|
|
179
|
-
void main() {
|
|
180
|
-
vec2 point = gl_PointCoord * 2.0 - 1.0;
|
|
181
|
-
float angle = atan(point.y, point.x);
|
|
182
|
-
float contour = 1.0 + 0.08 * sin(angle * 5.0 + progress * 19.0)
|
|
183
|
-
+ 0.045 * sin(angle * 11.0 - progress * 31.0);
|
|
184
|
-
float radius = dot(point, point) / (contour * contour);
|
|
185
|
-
float outer = 1.0 - smoothstep(0.48, 0.88, radius);
|
|
186
|
-
float middle = 1.0 - smoothstep(0.18, 0.62, radius);
|
|
187
|
-
float core = 1.0 - smoothstep(0.035, 0.34, radius);
|
|
188
|
-
if (agePalette) {
|
|
189
|
-
float fuel = outer * strength * 1.15;
|
|
190
|
-
// The weapon advances each fuel parcel across its range in about 0.3 s.
|
|
191
|
-
// Seed that travel age at the GPU stamp, then let the shared solver carry
|
|
192
|
-
// and age it. Fresh emission stays blue at the nozzle, not at the far tip.
|
|
193
|
-
color = vec4(fuel, fuel * progress * 0.3, fuel * progress, 0.0);
|
|
194
|
-
} else {
|
|
195
|
-
color = vec4(outer * strength * 0.65,
|
|
196
|
-
middle * strength * 1.55,
|
|
197
|
-
core * strength * 2.2, 0.0);
|
|
198
|
-
}
|
|
199
|
-
}`,dc=`
|
|
200
|
-
uniform sampler2D uWalls;
|
|
201
|
-
uniform bool hasWalls;
|
|
202
|
-
bool isWall(vec2 uv) {
|
|
203
|
-
if (!hasWalls) return false;
|
|
204
|
-
return texture(uWalls, clamp(uv, vec2(0.0), vec2(1.0))).r > 0.5;
|
|
205
|
-
}`,fc={silhouette:`${G}
|
|
206
|
-
uniform sampler2D uTarget, uSilhouette;
|
|
207
|
-
uniform vec2 size, center, forward, halfSize;
|
|
208
|
-
uniform float amount, time;
|
|
209
|
-
uniform bool imageMask;
|
|
210
|
-
float noise(vec2 p) {
|
|
211
|
-
vec2 cell = floor(p), f = fract(p);
|
|
212
|
-
f = f * f * (3.0 - 2.0 * f);
|
|
213
|
-
vec4 n = fract(sin(vec4(dot(cell, vec2(127.1, 311.7)),
|
|
214
|
-
dot(cell + vec2(1.0, 0.0), vec2(127.1, 311.7)),
|
|
215
|
-
dot(cell + vec2(0.0, 1.0), vec2(127.1, 311.7)),
|
|
216
|
-
dot(cell + 1.0, vec2(127.1, 311.7)))) * 43758.5453);
|
|
217
|
-
return mix(mix(n.x, n.y, f.x), mix(n.z, n.w, f.x), f.y);
|
|
218
|
-
}
|
|
219
|
-
void main() {
|
|
220
|
-
vec2 offset = vec2(vUv.x, 1.0 - vUv.y) * size - center;
|
|
221
|
-
vec2 local = vec2(dot(offset, forward), dot(offset, vec2(-forward.y, forward.x)));
|
|
222
|
-
vec2 uv = local / (halfSize * 2.0) + 0.5;
|
|
223
|
-
vec4 source = texture(uSilhouette, clamp(uv, 0.0, 1.0));
|
|
224
|
-
float alpha = imageMask ? smoothstep(0.25, 0.8, source.a) : source.r;
|
|
225
|
-
float structure = imageMask ? 0.3 + (1.0 - dot(source.rgb, vec3(0.2126, 0.7152, 0.0722))) * 1.6 : 1.0;
|
|
226
|
-
alpha *= step(0.0, uv.x) * step(uv.x, 1.0) * step(0.0, uv.y) * step(uv.y, 1.0);
|
|
227
|
-
float detail = noise(local * 0.14 + vec2(time * 0.7, -time * 1.3));
|
|
228
|
-
color = texture(uTarget, vUv) + vec4(alpha * amount * structure * (0.75 + detail * 0.3), 0.0, 0.0, 0.0);
|
|
229
|
-
}`,copy:`${G}
|
|
230
|
-
uniform sampler2D uTexture;
|
|
231
|
-
void main() { color = texture(uTexture, vUv); }`,addFlame:`${G}
|
|
232
|
-
uniform sampler2D uTarget, uSource;
|
|
233
|
-
void main() { color = texture(uTarget, vUv) + texture(uSource, vUv); }`,splat:`${G}
|
|
234
|
-
uniform sampler2D uTarget;
|
|
235
|
-
uniform vec2 point, size;
|
|
236
|
-
uniform vec4 value;
|
|
237
|
-
uniform float radius;
|
|
238
|
-
void main() {
|
|
239
|
-
vec2 p = (vUv - point) * size;
|
|
240
|
-
color = texture(uTarget, vUv) + value * exp(-dot(p, p) / max(radius * radius, 1.0));
|
|
241
|
-
}`,splatBatch:`${G}
|
|
242
|
-
uniform sampler2D uTarget;
|
|
243
|
-
uniform vec2 size;
|
|
244
|
-
uniform int count;
|
|
245
|
-
uniform vec4 stamps[16];
|
|
246
|
-
uniform vec4 values[16];
|
|
247
|
-
void main() {
|
|
248
|
-
vec4 contribution = vec4(0.0);
|
|
249
|
-
for (int i = 0; i < 16; i++) {
|
|
250
|
-
if (i >= count) break;
|
|
251
|
-
vec2 p = (vUv - stamps[i].xy) * size;
|
|
252
|
-
contribution += values[i] * exp(-dot(p, p) / max(stamps[i].z * stamps[i].z, 1.0));
|
|
253
|
-
}
|
|
254
|
-
color = texture(uTarget, vUv) + contribution;
|
|
255
|
-
}`,splatSegment:`${G}
|
|
256
|
-
uniform sampler2D uTarget;
|
|
257
|
-
uniform vec2 start, end, size, radii;
|
|
258
|
-
uniform vec4 value;
|
|
259
|
-
void main() {
|
|
260
|
-
vec2 pixel = vUv * size;
|
|
261
|
-
vec2 a = start * size, b = end * size;
|
|
262
|
-
vec2 axis = b - a;
|
|
263
|
-
float along = clamp(dot(pixel - a, axis) / max(dot(axis, axis), 1.0), 0.0, 1.0);
|
|
264
|
-
float radius = mix(radii.x, radii.y, along);
|
|
265
|
-
vec2 offset = pixel - mix(a, b, along);
|
|
266
|
-
color = texture(uTarget, vUv) + value *
|
|
267
|
-
exp(-dot(offset, offset) / max(radius * radius, 1.0));
|
|
268
|
-
}`,inkFlame:`${G}
|
|
269
|
-
uniform sampler2D uInk;
|
|
270
|
-
uniform vec2 uCanvasSize, uInkOrigin, uInkSize, uIgnition;
|
|
271
|
-
uniform float uTime, uDt;
|
|
272
|
-
void main() {
|
|
273
|
-
vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
|
|
274
|
-
vec2 uv = (point - uInkOrigin) / uInkSize;
|
|
275
|
-
if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
|
|
276
|
-
color = vec4(0.0); return;
|
|
277
|
-
}
|
|
278
|
-
// Uint8Array rows are uploaded top-first into texture row zero.
|
|
279
|
-
float ink = texture(uInk, uv).r;
|
|
280
|
-
vec2 local = point - uInkOrigin;
|
|
281
|
-
float irregularity = sin(local.x * 0.105 + local.y * 0.21) * 0.095 +
|
|
282
|
-
sin(local.x * 0.27 - local.y * 0.09) * 0.055;
|
|
283
|
-
float arrival = max(0.0, max(0.0, local.x - uIgnition.x) / 88.0 + irregularity);
|
|
284
|
-
float age = uTime - arrival;
|
|
285
|
-
float burning = smoothstep(-0.06, 0.12, age) *
|
|
286
|
-
(1.0 - smoothstep(0.35, 0.75, age));
|
|
287
|
-
float smoking = smoothstep(0.15, 0.36, age) *
|
|
288
|
-
(1.0 - smoothstep(0.85, 1.28, age));
|
|
289
|
-
float variation = 0.90 + 0.10 * sin(point.y * 0.19 + uTime * 7.0);
|
|
290
|
-
float above = texture(uInk, vec2(uv.x, uv.y - 2.5 / uInkSize.y)).r;
|
|
291
|
-
float upperEdge = max(0.0, ink - above);
|
|
292
|
-
float fire = (ink * 0.30 + upperEdge * 1.55) * burning * variation * uDt * 5.2;
|
|
293
|
-
color = vec4(fire * 0.75, fire * 1.4, fire * 1.9,
|
|
294
|
-
ink * smoking * uDt * 4.8);
|
|
295
|
-
}`,inkFlow:`${G}
|
|
296
|
-
uniform sampler2D uVelocity;
|
|
297
|
-
uniform vec2 uCanvasSize, uCellSize, uInkOrigin, uInkSize;
|
|
298
|
-
uniform float uTime, uDt, uIgnitionX;
|
|
299
|
-
void main() {
|
|
300
|
-
vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
|
|
301
|
-
vec2 local = point - uInkOrigin;
|
|
302
|
-
float front = min(uInkSize.x, uIgnitionX + uTime * 88.0);
|
|
303
|
-
float widthGate = smoothstep(-24.0, 10.0, local.x) *
|
|
304
|
-
(1.0 - smoothstep(front - 12.0, front + 38.0, local.x));
|
|
305
|
-
float heightGate = exp(-pow((local.y - uInkSize.y * 0.38) / 65.0, 2.0));
|
|
306
|
-
float envelope = widthGate * heightGate;
|
|
307
|
-
float curl = sin(local.x * 0.086 - uTime * 3.1) *
|
|
308
|
-
cos(local.y * 0.092 + uTime * 2.4);
|
|
309
|
-
vec2 flow = vec2(25.0 * curl + 12.0 * sin(local.y * 0.14 - uTime * 3.8),
|
|
310
|
-
-94.0 - 24.0 * sin(local.x * 0.11 + uTime * 2.7));
|
|
311
|
-
vec2 velocity = texture(uVelocity, vUv).xy +
|
|
312
|
-
vec2(flow.x / uCellSize.x, -flow.y / uCellSize.y) * uDt * 0.52 * envelope;
|
|
313
|
-
color = vec4(velocity, 0.0, 1.0);
|
|
314
|
-
}`,sceneInkFlame:`${G}
|
|
315
|
-
uniform sampler2D uInk;
|
|
316
|
-
uniform vec2 uCanvasSize, uOrigin;
|
|
317
|
-
uniform vec4 uRect;
|
|
318
|
-
uniform float uAngle, uAge, uFarthest, uSpreadSeconds, uBurnSeconds;
|
|
319
|
-
uniform float uDt, uSmokeRate, uTime, uIntensity, uFixedRadius, uSmokeOnly;
|
|
320
|
-
uniform float uBlastAge, uBlastSeconds;
|
|
321
|
-
uniform bool uAgePalette;
|
|
322
|
-
void main() {
|
|
323
|
-
vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
|
|
324
|
-
vec2 center = uRect.xy + uRect.zw * 0.5;
|
|
325
|
-
vec2 offset = point - center;
|
|
326
|
-
float c = cos(uAngle), s = sin(uAngle);
|
|
327
|
-
vec2 local = vec2(offset.x * c + offset.y * s,
|
|
328
|
-
-offset.x * s + offset.y * c) + uRect.zw * 0.5;
|
|
329
|
-
vec2 uv = local / uRect.zw;
|
|
330
|
-
if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
|
|
331
|
-
color = vec4(0.0); return;
|
|
332
|
-
}
|
|
333
|
-
float ink = texture(uInk, uv).r;
|
|
334
|
-
float arrival = uFixedRadius > 0.0
|
|
335
|
-
? step(uFixedRadius, distance(point, uOrigin)) * 999.0
|
|
336
|
-
: distance(point, uOrigin) / max(uFarthest, 1.0) * uSpreadSeconds;
|
|
337
|
-
float progress = (uAge - arrival) / max(uBurnSeconds, 0.01);
|
|
338
|
-
float burning = smoothstep(0.0, 0.06, progress) *
|
|
339
|
-
(1.0 - smoothstep(0.78, 1.02, progress));
|
|
340
|
-
float smoking = smoothstep(0.12, 0.32, progress) *
|
|
341
|
-
(1.0 - smoothstep(0.90, 1.08, progress));
|
|
342
|
-
float above = texture(uInk, vec2(uv.x,
|
|
343
|
-
uv.y - 2.5 / max(uRect.w, 1.0))).r;
|
|
344
|
-
float upperEdge = max(0.0, ink - above);
|
|
345
|
-
float variation = 0.90 + 0.10 * sin(point.y * 0.19 + uTime * 7.0);
|
|
346
|
-
if (uBlastAge >= 0.0) {
|
|
347
|
-
float envelope = 1.0 - smoothstep(uBlastSeconds * 0.28,
|
|
348
|
-
uBlastSeconds, uBlastAge);
|
|
349
|
-
float flash = 1.0 - smoothstep(0.04, 0.17, uBlastAge);
|
|
350
|
-
float fire = (ink * 0.85 + upperEdge * 0.5) * envelope *
|
|
351
|
-
(1.0 + flash * 0.55) * variation * uDt * 38.0;
|
|
352
|
-
if (uAgePalette) {
|
|
353
|
-
float fuel = fire * 2.0;
|
|
354
|
-
float smoke = ink * envelope * uDt * 7.0 * 0.3;
|
|
355
|
-
color = vec4(fuel, fuel * 0.23, fuel * 0.55, smoke);
|
|
356
|
-
return;
|
|
357
|
-
}
|
|
358
|
-
color = vec4(fire * 0.85, fire * 1.5, fire * 2.15,
|
|
359
|
-
ink * envelope * uDt * 7.0);
|
|
360
|
-
return;
|
|
361
|
-
}
|
|
362
|
-
float fire = (ink * 0.30 + upperEdge * 1.55) * burning * variation * uDt * 5.2 * uIntensity * (1.0 - uSmokeOnly);
|
|
363
|
-
if (uAgePalette) {
|
|
364
|
-
// Keep smoke in alpha so it cannot age and desaturate nearby live fire.
|
|
365
|
-
// All four channels still ride the same velocity field and solve.
|
|
366
|
-
float fuel = (ink * 0.14 + upperEdge * 1.55) * burning * variation *
|
|
367
|
-
uDt * 5.2 * uIntensity * 4.0 * (1.0 - uSmokeOnly);
|
|
368
|
-
float smokePresence = mix(smoking, max(smoking, smoothstep(0.02, 0.12, progress)), uSmokeOnly);
|
|
369
|
-
float smoke = ink * smokePresence * uDt * 4.8 * uSmokeRate * mix(0.08, 0.8, uSmokeOnly);
|
|
370
|
-
color = vec4(fuel, fuel * 0.24, fuel * 0.55, smoke);
|
|
371
|
-
return;
|
|
372
|
-
}
|
|
373
|
-
color = vec4(fire * 0.75, fire * 1.4, fire * 1.9,
|
|
374
|
-
ink * smoking * uDt * 4.8 * uSmokeRate);
|
|
375
|
-
}`,sceneFlow:`${G}
|
|
376
|
-
uniform sampler2D uVelocity, uDye;
|
|
377
|
-
uniform vec2 uCanvasSize, uCellSize;
|
|
378
|
-
uniform float uTime, uDt;
|
|
379
|
-
void main() {
|
|
380
|
-
vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
|
|
381
|
-
vec4 dye = max(texture(uDye, vUv), vec4(0.0));
|
|
382
|
-
float heat = dot(dye.rgb, vec3(0.28, 0.22, 0.18));
|
|
383
|
-
float activity = 1.0 - exp(-(heat + dye.a * 1.4) * 3.0);
|
|
384
|
-
float eddy = sin(point.x * 0.086 - uTime * 3.1) *
|
|
385
|
-
cos(point.y * 0.092 + uTime * 2.4);
|
|
386
|
-
vec2 flow = vec2(42.0 * eddy + 12.0 * sin(point.y * 0.14 - uTime * 3.8),
|
|
387
|
-
-310.0 - 78.0 * clamp(heat, 0.0, 1.0));
|
|
388
|
-
vec2 velocity = texture(uVelocity, vUv).xy +
|
|
389
|
-
vec2(flow.x / uCellSize.x, -flow.y / uCellSize.y) * uDt * 0.85 * activity;
|
|
390
|
-
color = vec4(velocity, 0.0, 1.0);
|
|
391
|
-
}`,radialBlast:`${G}
|
|
392
|
-
uniform sampler2D uVelocity;
|
|
393
|
-
uniform vec2 uCanvasSize, uCellSize, uCenter;
|
|
394
|
-
uniform float uRadius;
|
|
395
|
-
void main() {
|
|
396
|
-
vec2 point = vec2(vUv.x, 1.0 - vUv.y) * uCanvasSize;
|
|
397
|
-
vec2 offset = point - uCenter;
|
|
398
|
-
float distanceFromCenter = length(offset);
|
|
399
|
-
float envelope = 1.0 - smoothstep(uRadius * 0.18, uRadius, distanceFromCenter);
|
|
400
|
-
vec2 direction = offset / max(distanceFromCenter, 1.0);
|
|
401
|
-
vec2 impulse = direction * min(uRadius, 180.0) * 2.4 * envelope;
|
|
402
|
-
vec2 velocity = texture(uVelocity, vUv).xy +
|
|
403
|
-
vec2(impulse.x / uCellSize.x, -impulse.y / uCellSize.y);
|
|
404
|
-
color = vec4(velocity, 0.0, 1.0);
|
|
405
|
-
}`,flameSource:`${G}
|
|
406
|
-
uniform sampler2D uTarget;
|
|
407
|
-
uniform vec2 start, end, size;
|
|
408
|
-
uniform vec3 radii, strengths;
|
|
409
|
-
uniform float time;
|
|
410
|
-
void main() {
|
|
411
|
-
vec2 pixel = vUv * size;
|
|
412
|
-
vec2 a = start * size, b = end * size;
|
|
413
|
-
vec2 axis = b - a;
|
|
414
|
-
float along = clamp(dot(pixel - a, axis) / max(dot(axis, axis), 1.0), 0.0, 1.0);
|
|
415
|
-
vec2 side = normalize(vec2(-axis.y, axis.x) + vec2(0.0001));
|
|
416
|
-
float tip = along * along;
|
|
417
|
-
float weave = tip * (4.0 * sin(along * 12.0 - time * 7.0)
|
|
418
|
-
+ 1.5 * sin(along * 27.0 + time * 5.0));
|
|
419
|
-
vec2 offset = pixel - mix(a, b, along) - side * weave;
|
|
420
|
-
float edge = mix(1.0, 1.0 + 0.23 * sin(along * 24.0 - time * 8.0)
|
|
421
|
-
+ 0.12 * sin(along * 39.0 + time * 6.0), tip);
|
|
422
|
-
float fade = 1.0 - smoothstep(0.93, 1.0, along);
|
|
423
|
-
vec3 radius = max(mix(vec3(7.0, 5.0, 3.0), radii, along) * edge,
|
|
424
|
-
vec3(1.0));
|
|
425
|
-
vec3 density = strengths * fade * exp(-dot(offset, offset) / (radius * radius));
|
|
426
|
-
color = texture(uTarget, vUv) + vec4(density, 0.0);
|
|
427
|
-
}`,flameEddies:`${G}
|
|
428
|
-
uniform sampler2D uTarget;
|
|
429
|
-
uniform vec2 start, end, size, cellSize;
|
|
430
|
-
uniform float time, dt;
|
|
431
|
-
void main() {
|
|
432
|
-
vec2 pixel = vec2(vUv.x, 1.0 - vUv.y) * size;
|
|
433
|
-
vec2 axis = end - start;
|
|
434
|
-
vec2 side = normalize(vec2(-axis.y, axis.x) + vec2(0.0001));
|
|
435
|
-
vec2 centerA = mix(start, end, 0.72) + side * sin(time * 5.2) * 7.0;
|
|
436
|
-
vec2 centerB = mix(start, end, 0.92) - side * cos(time * 4.1) * 9.0;
|
|
437
|
-
vec2 a = pixel - centerA, b = pixel - centerB;
|
|
438
|
-
float falloffA = exp(-dot(a, a) / (34.0 * 34.0));
|
|
439
|
-
float falloffB = exp(-dot(b, b) / (29.0 * 29.0));
|
|
440
|
-
vec2 spin = vec2(-a.y, a.x) * falloffA * 0.14
|
|
441
|
-
- vec2(-b.y, b.x) * falloffB * 0.17;
|
|
442
|
-
vec2 velocity = texture(uTarget, vUv).xy
|
|
443
|
-
+ vec2(spin.x / cellSize.x, -spin.y / cellSize.y) * dt;
|
|
444
|
-
color = vec4(velocity, 0.0, 0.0);
|
|
445
|
-
}`,body:`${G}
|
|
446
|
-
uniform sampler2D uVelocity;
|
|
447
|
-
uniform vec2 size, texelSize, center, forward, halfSize, motion;
|
|
448
|
-
uniform float spin, bodyInfluence;
|
|
449
|
-
void main() {
|
|
450
|
-
vec2 pixel = vec2(vUv.x, 1.0 - vUv.y) * size;
|
|
451
|
-
vec2 offset = pixel - center;
|
|
452
|
-
vec2 side = vec2(-forward.y, forward.x);
|
|
453
|
-
float along = dot(offset, forward);
|
|
454
|
-
float across = dot(offset, side);
|
|
455
|
-
float longPart = along / max(halfSize.x, 1.0);
|
|
456
|
-
float sidePart = across / max(halfSize.y, 1.0);
|
|
457
|
-
// Rounded body envelope keeps smoke moving around the vehicle.
|
|
458
|
-
float shape = sqrt(pow(abs(longPart), 4.0) + sidePart * sidePart);
|
|
459
|
-
vec2 cellSize = size * texelSize;
|
|
460
|
-
vec2 existing = texture(uVelocity, vUv).xy * cellSize;
|
|
461
|
-
if (shape > 1.75) { color = vec4(existing / cellSize, 0.0, 1.0); return; }
|
|
462
|
-
vec2 moving = motion + vec2(-offset.y, offset.x) * spin;
|
|
463
|
-
if (shape < 1.0) {
|
|
464
|
-
color = vec4(mix(existing, moving, bodyInfluence) / cellSize, 0.0, 1.0);
|
|
465
|
-
return;
|
|
466
|
-
}
|
|
467
|
-
vec2 gradient = forward * (4.0 * longPart * abs(longPart) * abs(longPart) / max(halfSize.x, 1.0))
|
|
468
|
-
+ side * (2.0 * sidePart / max(halfSize.y, 1.0));
|
|
469
|
-
vec2 normal = normalize(gradient + vec2(0.00001));
|
|
470
|
-
float speed = length(motion) + abs(spin) * halfSize.y * 0.4;
|
|
471
|
-
float frontPush = max(dot(moving, normal), 0.0) * 0.55;
|
|
472
|
-
float sidePush = speed * 0.18;
|
|
473
|
-
vec2 wake = along < 0.0 ? moving * 0.14 : vec2(0.0);
|
|
474
|
-
vec2 target = moving * 0.24 + normal * (frontPush + sidePush) + wake;
|
|
475
|
-
float influence = 1.0 - smoothstep(1.0, 1.75, shape);
|
|
476
|
-
vec2 nextVelocity = mix(existing, target, influence * 0.78 * bodyInfluence);
|
|
477
|
-
color = vec4(nextVelocity / cellSize, 0.0, 1.0);
|
|
478
|
-
}`,align:`${G}
|
|
479
|
-
uniform sampler2D uSource;
|
|
480
|
-
uniform vec2 size, oldOrigin, nextOrigin, oldScale, nextScale;
|
|
481
|
-
void main() {
|
|
482
|
-
vec2 nextPixel = vec2(vUv.x, 1.0 - vUv.y) * size;
|
|
483
|
-
vec2 physical = (nextPixel - nextOrigin) / nextScale;
|
|
484
|
-
vec2 oldPixel = oldOrigin + physical * oldScale;
|
|
485
|
-
vec2 uv = vec2(oldPixel.x / size.x, 1.0 - oldPixel.y / size.y);
|
|
486
|
-
color = uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0
|
|
487
|
-
? vec4(0.0) : texture(uSource, uv);
|
|
488
|
-
}`,clear:`${G}
|
|
489
|
-
uniform sampler2D uTexture;
|
|
490
|
-
uniform float value;
|
|
491
|
-
void main() { color = texture(uTexture, vUv) * value; }`,curl:`${G}
|
|
492
|
-
uniform sampler2D uVelocity;
|
|
493
|
-
uniform vec2 texelSize;
|
|
494
|
-
void main() {
|
|
495
|
-
float l = texture(uVelocity, vUv - vec2(texelSize.x, 0.0)).y;
|
|
496
|
-
float r = texture(uVelocity, vUv + vec2(texelSize.x, 0.0)).y;
|
|
497
|
-
float t = texture(uVelocity, vUv + vec2(0.0, texelSize.y)).x;
|
|
498
|
-
float b = texture(uVelocity, vUv - vec2(0.0, texelSize.y)).x;
|
|
499
|
-
color = vec4(0.5 * (r - l - t + b), 0.0, 0.0, 1.0);
|
|
500
|
-
}`,vorticity:`${G}
|
|
501
|
-
uniform sampler2D uVelocity, uCurl;
|
|
502
|
-
uniform vec2 texelSize;
|
|
503
|
-
uniform float curl, dt;
|
|
504
|
-
void main() {
|
|
505
|
-
float l = texture(uCurl, vUv - vec2(texelSize.x, 0.0)).x;
|
|
506
|
-
float r = texture(uCurl, vUv + vec2(texelSize.x, 0.0)).x;
|
|
507
|
-
float t = texture(uCurl, vUv + vec2(0.0, texelSize.y)).x;
|
|
508
|
-
float b = texture(uCurl, vUv - vec2(0.0, texelSize.y)).x;
|
|
509
|
-
float c = texture(uCurl, vUv).x;
|
|
510
|
-
vec2 force = 0.5 * vec2(abs(t) - abs(b), abs(r) - abs(l));
|
|
511
|
-
force = force / (length(force) + 0.0001) * curl * c;
|
|
512
|
-
force.y *= -1.0;
|
|
513
|
-
vec2 velocity = clamp(texture(uVelocity, vUv).xy + force * dt, vec2(-1000.0), vec2(1000.0));
|
|
514
|
-
color = vec4(velocity, 0.0, 1.0);
|
|
515
|
-
}`,divergence:`${G}${dc}
|
|
516
|
-
uniform sampler2D uVelocity;
|
|
517
|
-
uniform vec2 texelSize;
|
|
518
|
-
void main() {
|
|
519
|
-
if (isWall(vUv)) { color = vec4(0.0); return; }
|
|
520
|
-
vec2 c = texture(uVelocity, vUv).xy;
|
|
521
|
-
float l = texture(uVelocity, vUv - vec2(texelSize.x, 0.0)).x;
|
|
522
|
-
float r = texture(uVelocity, vUv + vec2(texelSize.x, 0.0)).x;
|
|
523
|
-
float t = texture(uVelocity, vUv + vec2(0.0, texelSize.y)).y;
|
|
524
|
-
float b = texture(uVelocity, vUv - vec2(0.0, texelSize.y)).y;
|
|
525
|
-
if (vUv.x < texelSize.x) l = -c.x;
|
|
526
|
-
if (vUv.x > 1.0 - texelSize.x) r = -c.x;
|
|
527
|
-
if (vUv.y > 1.0 - texelSize.y) t = -c.y;
|
|
528
|
-
if (vUv.y < texelSize.y) b = -c.y;
|
|
529
|
-
if (isWall(vUv - vec2(texelSize.x, 0.0))) l = -c.x;
|
|
530
|
-
if (isWall(vUv + vec2(texelSize.x, 0.0))) r = -c.x;
|
|
531
|
-
if (isWall(vUv + vec2(0.0, texelSize.y))) t = -c.y;
|
|
532
|
-
if (isWall(vUv - vec2(0.0, texelSize.y))) b = -c.y;
|
|
533
|
-
color = vec4(0.5 * (r - l + t - b), 0.0, 0.0, 1.0);
|
|
534
|
-
}`,pressure:`${G}${dc}
|
|
535
|
-
uniform sampler2D uPressure, uDivergence;
|
|
536
|
-
uniform vec2 texelSize;
|
|
537
|
-
void main() {
|
|
538
|
-
if (isWall(vUv)) { color = vec4(0.0); return; }
|
|
539
|
-
float p = texture(uPressure, vUv).x;
|
|
540
|
-
float l = texture(uPressure, vUv - vec2(texelSize.x, 0.0)).x;
|
|
541
|
-
float r = texture(uPressure, vUv + vec2(texelSize.x, 0.0)).x;
|
|
542
|
-
float t = texture(uPressure, vUv + vec2(0.0, texelSize.y)).x;
|
|
543
|
-
float b = texture(uPressure, vUv - vec2(0.0, texelSize.y)).x;
|
|
544
|
-
if (isWall(vUv - vec2(texelSize.x, 0.0))) l = p;
|
|
545
|
-
if (isWall(vUv + vec2(texelSize.x, 0.0))) r = p;
|
|
546
|
-
if (isWall(vUv + vec2(0.0, texelSize.y))) t = p;
|
|
547
|
-
if (isWall(vUv - vec2(0.0, texelSize.y))) b = p;
|
|
548
|
-
float divergence = texture(uDivergence, vUv).x;
|
|
549
|
-
color = vec4((l + r + t + b - divergence) * 0.25, 0.0, 0.0, 1.0);
|
|
550
|
-
}`,gradient:`${G}${dc}
|
|
551
|
-
uniform sampler2D uPressure, uVelocity;
|
|
552
|
-
uniform vec2 texelSize;
|
|
553
|
-
void main() {
|
|
554
|
-
if (isWall(vUv)) { color = vec4(0.0); return; }
|
|
555
|
-
float p = texture(uPressure, vUv).x;
|
|
556
|
-
float l = texture(uPressure, vUv - vec2(texelSize.x, 0.0)).x;
|
|
557
|
-
float r = texture(uPressure, vUv + vec2(texelSize.x, 0.0)).x;
|
|
558
|
-
float t = texture(uPressure, vUv + vec2(0.0, texelSize.y)).x;
|
|
559
|
-
float b = texture(uPressure, vUv - vec2(0.0, texelSize.y)).x;
|
|
560
|
-
if (isWall(vUv - vec2(texelSize.x, 0.0))) l = p;
|
|
561
|
-
if (isWall(vUv + vec2(texelSize.x, 0.0))) r = p;
|
|
562
|
-
if (isWall(vUv + vec2(0.0, texelSize.y))) t = p;
|
|
563
|
-
if (isWall(vUv - vec2(0.0, texelSize.y))) b = p;
|
|
564
|
-
vec2 velocity = texture(uVelocity, vUv).xy - vec2(r - l, t - b);
|
|
565
|
-
if (isWall(vUv - vec2(texelSize.x, 0.0))) velocity.x = max(velocity.x, 0.0);
|
|
566
|
-
if (isWall(vUv + vec2(texelSize.x, 0.0))) velocity.x = min(velocity.x, 0.0);
|
|
567
|
-
if (isWall(vUv + vec2(0.0, texelSize.y))) velocity.y = min(velocity.y, 0.0);
|
|
568
|
-
if (isWall(vUv - vec2(0.0, texelSize.y))) velocity.y = max(velocity.y, 0.0);
|
|
569
|
-
color = vec4(velocity, 0.0, 1.0);
|
|
570
|
-
}`,advection:`${G}${dc}
|
|
571
|
-
uniform sampler2D uVelocity, uSource;
|
|
572
|
-
uniform vec2 velocityTexel, sourceTexel;
|
|
573
|
-
uniform vec4 dissipation;
|
|
574
|
-
uniform float dt;
|
|
575
|
-
uniform bool ageDye;
|
|
576
|
-
vec4 bilerp(sampler2D image, vec2 uv, vec2 texel) {
|
|
577
|
-
vec2 st = uv / texel - 0.5;
|
|
578
|
-
vec2 base = floor(st), fraction = fract(st);
|
|
579
|
-
vec4 a = texture(image, (base + vec2(0.5, 0.5)) * texel);
|
|
580
|
-
vec4 b = texture(image, (base + vec2(1.5, 0.5)) * texel);
|
|
581
|
-
vec4 c = texture(image, (base + vec2(0.5, 1.5)) * texel);
|
|
582
|
-
vec4 d = texture(image, (base + vec2(1.5, 1.5)) * texel);
|
|
583
|
-
return mix(mix(a, b, fraction.x), mix(c, d, fraction.x), fraction.y);
|
|
584
|
-
}
|
|
585
|
-
void main() {
|
|
586
|
-
if (isWall(vUv)) { color = vec4(0.0); return; }
|
|
587
|
-
vec2 velocity = bilerp(uVelocity, vUv, velocityTexel).xy;
|
|
588
|
-
vec2 coord = vUv - dt * velocity * velocityTexel;
|
|
589
|
-
if (isWall(coord) || isWall(mix(vUv, coord, 0.5))) coord = vUv;
|
|
590
|
-
color = bilerp(uSource, coord, sourceTexel) / (vec4(1.0) + dissipation * dt);
|
|
591
|
-
if (ageDye) {
|
|
592
|
-
color.g += color.r * dt;
|
|
593
|
-
float fuel = color.r;
|
|
594
|
-
float age = color.g / max(fuel, 0.0001);
|
|
595
|
-
float burned = fuel * smoothstep(0.5, 0.85, age) * min(dt * 3.2, 1.0);
|
|
596
|
-
color.rgb *= (fuel - burned) / max(fuel, 0.0001);
|
|
597
|
-
color.a += burned * 0.65;
|
|
598
|
-
}
|
|
599
|
-
}`,display:`${G}${dc}
|
|
600
|
-
uniform sampler2D uDye;
|
|
601
|
-
uniform vec3 smokeColor;
|
|
602
|
-
uniform bool flamePalette, darkBackground, agePalette;
|
|
603
|
-
uniform vec2 flameOrigin, size;
|
|
604
|
-
uniform float lifecycleOpacity;
|
|
605
|
-
${ac}
|
|
606
|
-
void main() {
|
|
607
|
-
vec2 dyeSize = vec2(textureSize(uDye, 0));
|
|
608
|
-
vec2 pixel = vUv * dyeSize - 0.5;
|
|
609
|
-
vec2 base = floor(pixel);
|
|
610
|
-
vec2 fraction = fract(pixel);
|
|
611
|
-
vec2 low = (base + 0.5) / dyeSize;
|
|
612
|
-
vec2 high = (base + 1.5) / dyeSize;
|
|
613
|
-
vec4 material = mix(
|
|
614
|
-
mix(texture(uDye, vec2(low.x, low.y)), texture(uDye, vec2(high.x, low.y)), fraction.x),
|
|
615
|
-
mix(texture(uDye, vec2(low.x, high.y)), texture(uDye, vec2(high.x, high.y)), fraction.x),
|
|
616
|
-
fraction.y);
|
|
617
|
-
material = isWall(vUv) ? vec4(0.0) : max(material, vec4(0.0));
|
|
618
|
-
vec3 density = material.rgb;
|
|
619
|
-
if (!flamePalette) {
|
|
620
|
-
// Unlit tire smoke reads as grey volume at night; beams supply localized brightness.
|
|
621
|
-
vec3 ambientSmoke = smokeColor * (darkBackground ? 0.52 : 1.0);
|
|
622
|
-
vec3 litSmoke = scatterVehicleLight(ambientSmoke, density.r, vec2(vUv.x, 1.0 - vUv.y) * size, darkBackground);
|
|
623
|
-
color = vec4(litSmoke, min(1.0 - exp(-density.r * 0.9), 0.82));
|
|
624
|
-
return;
|
|
625
|
-
}
|
|
626
|
-
if (agePalette) {
|
|
627
|
-
// R is fuel, G its weighted age, B its travel, and A is separate smoke.
|
|
628
|
-
// Burning fuel remains colored even while smoke overlaps it.
|
|
629
|
-
float age = clamp(material.g / max(material.r, 0.0001), 0.0, 1.5);
|
|
630
|
-
float travel = clamp(material.b / max(material.r, 0.0001), 0.0, 1.0);
|
|
631
|
-
float visible = smoothstep(0.045, 0.7, material.r);
|
|
632
|
-
float hotCore = smoothstep(0.2, 1.0, material.r) *
|
|
633
|
-
smoothstep(0.045, 0.12, age) * (1.0 - smoothstep(0.43, 0.7, age));
|
|
634
|
-
vec3 blue = darkBackground ? vec3(0.17, 0.65, 1.0) : vec3(0.07, 0.38, 0.82);
|
|
635
|
-
vec3 rim = darkBackground ? vec3(0.88, 0.20, 0.035) : vec3(0.77, 0.17, 0.025);
|
|
636
|
-
vec3 orange = darkBackground ? vec3(1.0, 0.56, 0.065) : vec3(0.94, 0.42, 0.025);
|
|
637
|
-
vec3 yellow = darkBackground ? vec3(1.0, 0.84, 0.28) : vec3(1.0, 0.72, 0.13);
|
|
638
|
-
vec3 ash = darkBackground ? vec3(0.37, 0.30, 0.27) : vec3(0.30, 0.26, 0.24);
|
|
639
|
-
ash = scatterVehicleLight(ash, material.a, vec2(vUv.x, 1.0 - vUv.y) * size, darkBackground);
|
|
640
|
-
vec3 rgb = mix(rim, orange, smoothstep(0.06, 0.42, material.r));
|
|
641
|
-
rgb = mix(rgb, yellow, hotCore * 0.88);
|
|
642
|
-
rgb = mix(rgb, vec3(1.0, 0.96, 0.76), hotCore * hotCore * 0.52);
|
|
643
|
-
float fresh = 1.0 - smoothstep(0.035, 0.20, travel);
|
|
644
|
-
rgb = mix(rgb, blue, fresh);
|
|
645
|
-
float ignition = smoothstep(0.012, 0.055, age);
|
|
646
|
-
float cooling = 1.0 - smoothstep(0.7, 1.1, age);
|
|
647
|
-
float nozzleAlpha = mix(0.22, 1.0, smoothstep(0.015, 0.12, travel));
|
|
648
|
-
float bodyAlpha = min(0.95, visible * 1.15) * ignition * cooling * nozzleAlpha;
|
|
649
|
-
bodyAlpha *= lifecycleOpacity;
|
|
650
|
-
float smokeAlpha = min(0.42, 1.0 - exp(-material.a * 0.48)) * lifecycleOpacity;
|
|
651
|
-
|
|
652
|
-
// A small halo comes from neighboring *burning* fluid. The same field
|
|
653
|
-
// supplies it, with no blur target or extra simulation/render pass.
|
|
654
|
-
vec2 nearX = vec2(11.0, 0.0) / size;
|
|
655
|
-
vec2 nearY = vec2(0.0, 11.0) / size;
|
|
656
|
-
vec2 farX = vec2(21.0, 0.0) / size;
|
|
657
|
-
vec2 farY = vec2(0.0, 21.0) / size;
|
|
658
|
-
vec4 nearFuel = (texture(uDye, vUv + nearX) + texture(uDye, vUv - nearX)
|
|
659
|
-
+ texture(uDye, vUv + nearY) + texture(uDye, vUv - nearY)) * 0.25;
|
|
660
|
-
vec4 farFuel = (texture(uDye, vUv + farX) + texture(uDye, vUv - farX)
|
|
661
|
-
+ texture(uDye, vUv + farY) + texture(uDye, vUv - farY)) * 0.25;
|
|
662
|
-
vec4 glowField = mix(nearFuel, farFuel, 0.4);
|
|
663
|
-
float glowAge = glowField.g / max(glowField.r, 0.0001);
|
|
664
|
-
float glowTravel = glowField.b / max(glowField.r, 0.0001);
|
|
665
|
-
float burning = smoothstep(0.04, 0.11, glowAge) *
|
|
666
|
-
(1.0 - smoothstep(0.52, 0.82, glowAge));
|
|
667
|
-
float haloAlpha = (1.0 - exp(-glowField.r * 0.68)) * burning * 0.33;
|
|
668
|
-
haloAlpha *= 1.0 - smoothstep(0.06, 0.48, material.r);
|
|
669
|
-
haloAlpha *= lifecycleOpacity;
|
|
670
|
-
vec3 haloRgb = mix(orange, blue,
|
|
671
|
-
(1.0 - smoothstep(0.02, 0.25, glowTravel)) * 0.7);
|
|
672
|
-
float litAlpha = bodyAlpha + haloAlpha * (1.0 - bodyAlpha);
|
|
673
|
-
vec3 lit = (rgb * bodyAlpha + haloRgb * haloAlpha * (1.0 - bodyAlpha)) /
|
|
674
|
-
max(litAlpha, 0.0001);
|
|
675
|
-
float alpha = litAlpha + smokeAlpha * (1.0 - litAlpha);
|
|
676
|
-
color = vec4((lit * litAlpha + ash * smokeAlpha * (1.0 - litAlpha)) /
|
|
677
|
-
max(alpha, 0.0001), alpha);
|
|
678
|
-
return;
|
|
679
|
-
}
|
|
680
|
-
vec3 rim = darkBackground ? vec3(0.92, 0.28, 0.025) : vec3(0.85, 0.25, 0.015);
|
|
681
|
-
vec3 orange = darkBackground ? vec3(1.0, 0.55, 0.045) : vec3(0.98, 0.44, 0.015);
|
|
682
|
-
vec3 hot = darkBackground ? vec3(1.0, 0.87, 0.35) : vec3(1.0, 0.77, 0.19);
|
|
683
|
-
vec3 rgb = mix(rim, orange, smoothstep(0.04, 0.35, density.g));
|
|
684
|
-
rgb = mix(rgb, hot, smoothstep(0.1, 0.62, density.b));
|
|
685
|
-
rgb = mix(rgb, vec3(1.0, 0.97, 0.82),
|
|
686
|
-
smoothstep(0.75, 1.65, density.b) * 0.72);
|
|
687
|
-
float ignition = 1.0 - smoothstep(8.0, 32.0,
|
|
688
|
-
length(vUv * size - flameOrigin));
|
|
689
|
-
rgb = mix(rgb, vec3(0.28, 0.65, 1.0), ignition * 0.68);
|
|
690
|
-
float heat = dot(density, vec3(0.8, 1.0, 1.25));
|
|
691
|
-
float flameAlpha = smoothstep(0.1, 0.43, heat) *
|
|
692
|
-
min(0.98, 0.7 + heat * 0.17);
|
|
693
|
-
float smokeAlpha = min(1.0 - exp(-material.a * 0.82), 0.72) * (1.0 - flameAlpha);
|
|
694
|
-
float alpha = flameAlpha + smokeAlpha;
|
|
695
|
-
vec3 smoke = darkBackground ? vec3(0.57, 0.58, 0.57) : vec3(0.39, 0.40, 0.39);
|
|
696
|
-
smoke = scatterVehicleLight(smoke, material.a, vec2(vUv.x, 1.0 - vUv.y) * size, darkBackground);
|
|
697
|
-
color = vec4((rgb * flameAlpha + smoke * smokeAlpha) / max(alpha, 0.0001),
|
|
698
|
-
alpha * lifecycleOpacity);
|
|
699
|
-
}`},pc=class{quality;tint;vorticity;flamePalette;flameSmokeTail;ghostField;agePalette;batchStamps=new Float32Array(64);batchValues=new Float32Array(64);canvas=document.createElement(`canvas`);gl;programs={};quad;positions={};lightPositions=new Float32Array(48);lightShapes=new Float32Array(48);lightColors=new Float32Array(48);lightDepths=new Float32Array(W*12);lightDepthTexture=null;silhouettes=new Map;flameStampProgram=null;flameStampBuffer=null;flameSource=null;flameInk=null;sceneInk=new Map;flameStampData=new Float32Array(10240);simulation;dyeSize;velocity;dye;pressure;curl;divergence;wallTexture=null;wallPixels=new Uint8Array;wallNext=new Uint8Array;hasWalls=!1;allSurfaces=[];width=1;height=1;pixelRatio=1;presentationPixelRatio;view=null;active=!1;sceneFireActive=!1;radialBlasts=[];idle=0;lost=!1;flameOrigin={x:0,y:0};gpuTimer=null;beginGpu(e){}endGpu(){this.gpuTimer?.end()}captureState(){if(this.lost)throw Error(`Cannot checkpoint a lost fluid context`);let e=this.gl,t=this.active||this.sceneFireActive||this.radialBlasts.length>0,n=t?new ic(e,this.velocity.read.framebuffer,this.velocity.read.width,this.velocity.read.height,e.RGBA16F,e.HALF_FLOAT):null,r=null;try{r=t?new ic(e,this.dye.read.framebuffer,this.dye.read.width,this.dye.read.height,e.RGBA16F,e.HALF_FLOAT):null}catch(e){throw n?.dispose(),e}return{velocity:n,dye:r,width:this.width,height:this.height,quality:this.quality,view:u(this.view),active:this.active,sceneFireActive:this.sceneFireActive,idle:this.idle,radialBlasts:u(this.radialBlasts),flameOrigin:u(this.flameOrigin),dispose:()=>{n?.dispose(),r?.dispose()}}}restoreState(e){if(this.lost)throw Error(`Cannot restore a lost fluid context`);this.quality=e.quality,this.resize(e.width,e.height,!0),this.reset(),e.velocity?.restore(this.velocity.read.framebuffer,this.velocity.read.width,this.velocity.read.height),e.dye?.restore(this.dye.read.framebuffer,this.dye.read.width,this.dye.read.height),this.view=u(e.view),this.active=e.active,this.sceneFireActive=e.sceneFireActive,this.idle=e.idle,this.radialBlasts=u(e.radialBlasts),this.flameOrigin=u(e.flameOrigin)}constructor(e,t,n,r=oc,i=18,a=!1,o=!1,s=!1,c=!1){this.quality=n,this.tint=r,this.vorticity=i,this.flamePalette=a,this.flameSmokeTail=o,this.ghostField=s,this.agePalette=c;let l=this.canvas.getContext(`webgl2`,{alpha:!0,depth:!1,stencil:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!0});if(!l||!l.getExtension(`EXT_color_buffer_float`))throw Error(`Float WebGL2 render targets are unavailable`);this.gl=l,this.canvas.addEventListener(`webglcontextlost`,e=>{e.preventDefault(),this.lost=!0}),this.quad=ls(l,new Float32Array([-1,-1,1,-1,-1,1,1,1]));for(let[e,t]of Object.entries(fc)){if((e===`inkFlame`||e===`inkFlow`||e===`sceneInkFlame`||e===`sceneFlow`)&&!this.flameSmokeTail)continue;let n=is(l,cc,t,`Fluid ${e}`);this.programs[e]=n,this.positions[e]=os(n,`aPosition`)}for(let e of[`vehicleLightPosition[0]`,`vehicleLightShape[0]`,`vehicleLightColor[0]`,`vehicleLightShadows`])this.uniform(`display`,e);if(this.flamePalette){let e=is(l,lc,uc,`Flame stamps`),t=l.createBuffer();if(!t)throw U(l,e),Error(`Unable to allocate flame stamps`);this.flameStampProgram=e,this.flameStampBuffer=t}this.resize(e,t)}get resolution(){return{quality:this.quality,cols:this.simulation.width,rows:this.simulation.height,engine:`WebGL2`}}get available(){return!this.lost}dispose(){if(!this.lost){this.gpuTimer?.dispose();for(let e of this.allSurfaces)this.gl.deleteTexture(e.texture),this.gl.deleteFramebuffer(e.framebuffer);for(let e of Object.values(this.programs))U(this.gl,e);for(let e of this.sceneInk.values())this.gl.deleteTexture(e.texture);this.flameInk&&this.gl.deleteTexture(this.flameInk.texture),this.wallTexture&&this.gl.deleteTexture(this.wallTexture),this.lightDepthTexture&&this.gl.deleteTexture(this.lightDepthTexture);for(let e of this.silhouettes.values())this.gl.deleteTexture(e.texture);this.silhouettes.clear(),this.flameStampProgram&&U(this.gl,this.flameStampProgram),this.flameStampBuffer&&this.gl.deleteBuffer(this.flameStampBuffer),this.gl.deleteBuffer(this.quad),this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.lost=!0}}get managedBytes(){return this.active&&!this.lost?this.allSurfaces.reduce((e,t)=>e+t.width*t.height*t.bytesPerPixel,0)+this.wallPixels.byteLength+this.wallNext.byteLength+(this.lightDepthTexture?this.lightDepths.byteLength:0)+[...this.silhouettes.values()].reduce((e,t)=>e+t.bytes,0)+[...this.sceneInk.values()].reduce((e,t)=>e+t.width*t.height,0):0}get hasSceneFire(){return this.sceneFireActive}activateBuoyancy(){this.sceneFireActive=!0}queueRadialBlast(e,t){this.radialBlasts.push({center:e,radius:t}),this.sceneFireActive=!0}setTint(e){this.tint=e}get running(){return this.active&&!this.lost}setQuality(e){e!==this.quality&&(this.quality=e,this.lost||this.resize(this.width,this.height,!0))}use(e){let t=this.gl,n=this.programs[e];t.useProgram(n),t.bindBuffer(t.ARRAY_BUFFER,this.quad);let r=this.positions[e];t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0)}uniform(e,t){return H(this.programs[e],t)}texture(e,t,n,r){let i=this.gl;i.activeTexture(i.TEXTURE0+r),i.bindTexture(i.TEXTURE_2D,n.texture),i.uniform1i(this.uniform(e,t),r)}bindWalls(e){let t=this.gl;t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.wallTexture),t.uniform1i(this.uniform(e,`uWalls`),2),t.uniform1i(this.uniform(e,`hasWalls`),Number(this.hasWalls))}vec2(e,t,n,r){this.gl.uniform2f(this.uniform(e,t),n,r)}draw(e){let t=this.gl;ds(t,e,e?.width??this.canvas.width,e?.height??this.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),f(this.flamePalette?`gpu.combustion.passes`:`gpu.smoke.passes`)}surface(e,t,n=!1){let r=this.gl,i={...us(r,e,t,n?r.RGBA8:r.RGBA16F,n?r.UNSIGNED_BYTE:r.HALF_FLOAT,r.NEAREST,`Fluid render target`),width:e,height:t,bytesPerPixel:n?4:8};return this.allSurfaces.push(i),r.viewport(0,0,e,t),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),i}pair(e,t){let n={read:this.surface(e,t),write:this.surface(e,t),swap:()=>{[n.read,n.write]=[n.write,n.read]}};return n}scaled(e){let t=this.presentationPixelRatio===void 0?this.width/this.height:this.canvas.width/this.canvas.height;return t>=1?{width:e,height:Math.max(1,Math.round(e/t))}:{width:Math.max(1,Math.round(e*t)),height:e}}resize(e,t,n=!1,r){if(this.lost)return;e=Math.max(1,Math.round(e)),t=Math.max(1,Math.round(t)),r!==void 0&&(this.presentationPixelRatio=Math.max(.1,Math.min(2,r)));let i=this.presentationPixelRatio??Math.min(2,window.devicePixelRatio||1);if(!n&&e===this.width&&t===this.height&&i===this.pixelRatio&&this.allSurfaces.length)return;let a=this.allSurfaces.length?{surfaces:this.allSurfaces,velocity:this.velocity,dye:this.dye,active:this.active,view:this.view,idle:this.idle}:null;if(a?.view){let n=e/this.width,r=t/this.height;a.view={origin:{x:a.view.origin.x*n,y:a.view.origin.y*r},scaleX:a.view.scaleX*n,scaleY:a.view.scaleY*r},this.flameOrigin={x:this.flameOrigin.x*n,y:this.flameOrigin.y*r}}this.width=e,this.height=t,this.pixelRatio=i;let o=sc[this.quality],s=this.quality===`high`?Math.min(2304,Math.max(o.dye,Math.round(Math.max(e,t)*i))):o.dye,c=Math.min(i,Math.max(1,s*1.5/Math.max(e,t))),l=Math.round(e*c),u=Math.round(t*c);this.canvas.width!==l&&(this.canvas.width=l),this.canvas.height!==u&&(this.canvas.height=u);let d=this.scaled(o.simulation),f=this.scaled(s);if(!n&&a&&d.width===this.simulation.width&&d.height===this.simulation.height&&f.width===this.dyeSize.width&&f.height===this.dyeSize.height){this.view=a.view;return}let p=this.gl;if(this.allSurfaces=[],this.simulation=d,this.wallTexture&&p.deleteTexture(this.wallTexture),this.wallTexture=p.createTexture(),!this.wallTexture)throw Error(`Unable to allocate fluid wall mask`);p.bindTexture(p.TEXTURE_2D,this.wallTexture),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.pixelStorei(p.UNPACK_ALIGNMENT,1),this.wallPixels=new Uint8Array(this.simulation.width*this.simulation.height),this.wallNext=new Uint8Array(this.wallPixels.length),p.texImage2D(p.TEXTURE_2D,0,p.R8,this.simulation.width,this.simulation.height,0,p.RED,p.UNSIGNED_BYTE,this.wallPixels),this.hasWalls=!1,this.dyeSize=f,this.velocity=this.pair(this.simulation.width,this.simulation.height),this.dye=this.pair(this.dyeSize.width,this.dyeSize.height),this.flameSource=this.flamePalette?this.surface(this.dyeSize.width,this.dyeSize.height,!0):null,this.pressure=this.pair(this.simulation.width,this.simulation.height),this.curl=this.surface(this.simulation.width,this.simulation.height),this.divergence=this.surface(this.simulation.width,this.simulation.height),a?.active&&(this.use(`copy`),this.texture(`copy`,`uTexture`,a.velocity.read,0),this.draw(this.velocity.read),this.texture(`copy`,`uTexture`,a.dye.read,0),this.draw(this.dye.read));for(let e of a?.surfaces??[])p.deleteTexture(e.texture),p.deleteFramebuffer(e.framebuffer);this.view=a?.view??null,this.active=a?.active??!1,this.idle=a?.idle??0}reset(){if(this.lost)return;let e=this.gl;for(let t of this.sceneInk.values())e.deleteTexture(t.texture);this.sceneInk.clear(),e.clearColor(0,0,0,0);for(let t of this.allSurfaces)e.bindFramebuffer(e.FRAMEBUFFER,t.framebuffer),e.viewport(0,0,t.width,t.height),e.clear(e.COLOR_BUFFER_BIT);this.active=!1,this.sceneFireActive=!1,this.radialBlasts=[],this.idle=0,this.view=null}align(e){if(!this.view||!this.active){this.view=e;return}let t=this.view,n=Math.abs(e.origin.x-t.origin.x)+Math.abs(e.origin.y-t.origin.y),r=Math.abs(e.scaleX/t.scaleX-1)+Math.abs(e.scaleY/t.scaleY-1);if(n<.2&&r<.001)return;let i=this.gl;this.beginGpu(`fire.align`),this.use(`align`),this.vec2(`align`,`size`,this.width,this.height),this.vec2(`align`,`oldOrigin`,t.origin.x,t.origin.y),this.vec2(`align`,`nextOrigin`,e.origin.x,e.origin.y),this.vec2(`align`,`oldScale`,t.scaleX,t.scaleY),this.vec2(`align`,`nextScale`,e.scaleX,e.scaleY);for(let e of[this.velocity,this.dye])this.texture(`align`,`uSource`,e.read,0),this.draw(e.write),e.swap();this.endGpu(),this.flamePalette&&(this.flameOrigin={x:e.origin.x+(this.flameOrigin.x-t.origin.x)/t.scaleX*e.scaleX,y:e.origin.y+(this.flameOrigin.y-t.origin.y)/t.scaleY*e.scaleY}),this.view=e,i.bindFramebuffer(i.FRAMEBUFFER,null)}splat(e,t,n,r){if(t.x<-n*2||t.y<-n*2||t.x>this.width+n*2||t.y>this.height+n*2)return;let i=this.gl;this.use(`splat`),this.texture(`splat`,`uTarget`,e.read,0),this.vec2(`splat`,`point`,t.x/this.width,1-t.y/this.height),this.vec2(`splat`,`size`,this.width,this.height),i.uniform1f(this.uniform(`splat`,`radius`),Math.max(2,n)),i.uniform4f(this.uniform(`splat`,`value`),...r),this.draw(e.write),e.swap()}splatBatch(e,t){if(!t)return;let n=this.gl;this.use(`splatBatch`),this.texture(`splatBatch`,`uTarget`,e.read,0),this.vec2(`splatBatch`,`size`,this.width,this.height),n.uniform1i(this.uniform(`splatBatch`,`count`),t),n.uniform4fv(this.uniform(`splatBatch`,`stamps[0]`),this.batchStamps.subarray(0,t*4)),n.uniform4fv(this.uniform(`splatBatch`,`values[0]`),this.batchValues.subarray(0,t*4)),this.draw(e.write),e.swap()}splatSegment(e,t,n,r,i,a){let o=this.gl;this.use(`splatSegment`),this.texture(`splatSegment`,`uTarget`,e.read,0),this.vec2(`splatSegment`,`start`,t.x/this.width,1-t.y/this.height),this.vec2(`splatSegment`,`end`,n.x/this.width,1-n.y/this.height),this.vec2(`splatSegment`,`size`,this.width,this.height),this.vec2(`splatSegment`,`radii`,Math.max(2,r),Math.max(2,i)),o.uniform4f(this.uniform(`splatSegment`,`value`),...a),this.draw(e.write),e.swap()}splatFlame(e,t,n,r,i){let a=this.gl;this.use(`flameSource`),this.texture(`flameSource`,`uTarget`,this.dye.read,0),this.vec2(`flameSource`,`start`,e.x/this.width,1-e.y/this.height),this.vec2(`flameSource`,`end`,t.x/this.width,1-t.y/this.height),this.vec2(`flameSource`,`size`,this.width,this.height),a.uniform3f(this.uniform(`flameSource`,`radii`),...n),a.uniform3f(this.uniform(`flameSource`,`strengths`),...r),a.uniform1f(this.uniform(`flameSource`,`time`),i),this.draw(this.dye.write),this.dye.swap()}stirFlame(e,t,n,r,i,a){let o=this.gl;this.use(`flameEddies`),this.texture(`flameEddies`,`uTarget`,this.velocity.read,0),this.vec2(`flameEddies`,`start`,e.x,e.y),this.vec2(`flameEddies`,`end`,t.x,t.y),this.vec2(`flameEddies`,`size`,this.width,this.height),this.vec2(`flameEddies`,`cellSize`,i,a),o.uniform1f(this.uniform(`flameEddies`,`time`),n),o.uniform1f(this.uniform(`flameEddies`,`dt`),r),this.draw(this.velocity.write),this.velocity.swap()}applyBody(e){let t=this.gl;this.use(`body`),this.texture(`body`,`uVelocity`,this.velocity.read,0),this.vec2(`body`,`size`,this.width,this.height),this.vec2(`body`,`texelSize`,1/this.simulation.width,1/this.simulation.height),this.vec2(`body`,`center`,e.center.x,e.center.y),this.vec2(`body`,`forward`,e.forward.x,e.forward.y),this.vec2(`body`,`halfSize`,e.halfLength,e.halfWidth),this.vec2(`body`,`motion`,e.velocity.x,e.velocity.y),t.uniform1f(this.uniform(`body`,`spin`),e.spin),t.uniform1f(this.uniform(`body`,`bodyInfluence`),e.influence??(this.flamePalette?.35:1)),this.draw(this.velocity.write),this.velocity.swap()}updateWalls(e){let{width:t,height:n}=this.simulation;this.wallNext.fill(0);let r=!1;for(let i of e){if(i.width<=0||i.height<=0)continue;let e=Math.max(0,Math.floor(i.x/this.width*t)),a=Math.min(t-1,Math.ceil((i.x+i.width)/this.width*t)-1),o=Math.max(0,Math.floor(i.y/this.height*n)),s=Math.min(n-1,Math.ceil((i.y+i.height)/this.height*n)-1);for(let i=o;i<=s;i++)for(let o=e;o<=a;o++)this.wallNext[(n-1-i)*t+o]=255,r=!0}let i=r!==this.hasWalls;if(!i){for(let e=0;e<this.wallNext.length;e++)if(this.wallNext[e]!==this.wallPixels[e]){i=!0;break}}if(this.hasWalls=r,!i)return;[this.wallPixels,this.wallNext]=[this.wallNext,this.wallPixels];let a=this.gl;a.activeTexture(a.TEXTURE2),a.bindTexture(a.TEXTURE_2D,this.wallTexture),a.texSubImage2D(a.TEXTURE_2D,0,0,0,t,n,a.RED,a.UNSIGNED_BYTE,this.wallPixels)}inject(e,t,n,r,i){if(this.lost||t<=0)return;this.active=!0,this.idle=0;let a=this.width/this.simulation.width,o=this.height/this.simulation.height;this.splat(this.velocity,e,r*1.3,[n.x/a*t*.22,-n.y/o*t*.22,0,0]),i&&this.splat(this.velocity,{x:e.x+r*.5,y:e.y+r*.5},r,[-i/a*t*.08,i/o*t*.08,0,0]),this.splat(this.dye,e,r*1.2,[t*2.2,0,0,0])}injectSilhouette(e,t,n,r,i){if(this.lost||n<=0)return;let a=this.gl,o=this.silhouettes.get(e);if(!o||o.image!==i?.image){o&&a.deleteTexture(o.texture);let t=a.createTexture();if(!t)throw Error(`Unable to allocate smoke silhouette`);a.activeTexture(a.TEXTURE3),a.bindTexture(a.TEXTURE_2D,t),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.pixelStorei(a.UNPACK_ALIGNMENT,1);let n=e.solid.byteLength;if(i){let e=document.createElement(`canvas`);e.width=Math.min(512,Math.round(i.source.width)),e.height=Math.max(1,Math.round(e.width*i.source.height/i.source.width)),e.getContext(`2d`).drawImage(i.image,i.source.x,i.source.y,i.source.width,i.source.height,0,0,e.width,e.height),a.texImage2D(a.TEXTURE_2D,0,a.RGBA8,a.RGBA,a.UNSIGNED_BYTE,e),n=e.width*e.height*4}else a.texImage2D(a.TEXTURE_2D,0,a.R8,e.columns,e.rows,0,a.RED,a.UNSIGNED_BYTE,e.solid.map(e=>e?255:0));if(o={texture:t,image:i?.image,bytes:n},this.silhouettes.set(e,o),this.silhouettes.size>8){let e=this.silhouettes.keys().next().value;a.deleteTexture(this.silhouettes.get(e).texture),this.silhouettes.delete(e)}}this.active=!0,this.idle=0,this.use(`silhouette`),this.texture(`silhouette`,`uTarget`,this.dye.read,0),a.activeTexture(a.TEXTURE3),a.bindTexture(a.TEXTURE_2D,o.texture),a.uniform1i(this.uniform(`silhouette`,`uSilhouette`),3),a.uniform1i(this.uniform(`silhouette`,`imageMask`),Number(!!i)),this.vec2(`silhouette`,`size`,this.width,this.height),this.vec2(`silhouette`,`center`,t.center.x,t.center.y),this.vec2(`silhouette`,`forward`,t.forward.x,t.forward.y),this.vec2(`silhouette`,`halfSize`,t.halfLength,t.halfWidth),a.uniform1f(this.uniform(`silhouette`,`amount`),n),a.uniform1f(this.uniform(`silhouette`,`time`),r),this.draw(this.dye.write),this.dye.swap()}bindLightShadows(e){if(!e.some(e=>e.shadow))return;let t=this.gl;if(t.activeTexture(t.TEXTURE3),this.lightDepthTexture)t.bindTexture(t.TEXTURE_2D,this.lightDepthTexture);else{if(this.lightDepthTexture=t.createTexture(),!this.lightDepthTexture)throw Error(`Unable to allocate light occlusion`);t.bindTexture(t.TEXTURE_2D,this.lightDepthTexture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,t.R32F,W,12,0,t.RED,t.FLOAT,null)}this.lightDepths.fill(1);for(let t=0;t<e.length;t++){let n=e[t].shadow;n&&this.lightDepths.set(n.distances,t*W)}t.texSubImage2D(t.TEXTURE_2D,0,0,0,W,12,t.RED,t.FLOAT,this.lightDepths),t.uniform1i(this.uniform(`display`,`vehicleLightShadows`),3)}injectBatch(e){if(this.lost||e.length===0)return;if(e.length===1){let t=e[0];this.inject(t.point,t.amount,t.flow,t.radiusPx,t.swirlPx);return}this.active=!0,this.idle=0;let t=this.width/this.simulation.width,n=this.height/this.simulation.height,r=0,i=(e,t,n,i)=>{if(e.x<-t*2||e.y<-t*2||e.x>this.width+t*2||e.y>this.height+t*2)return;let a=r*4;this.batchStamps[a]=e.x/this.width,this.batchStamps[a+1]=1-e.y/this.height,this.batchStamps[a+2]=Math.max(2,t),this.batchStamps[a+3]=0,this.batchValues[a]=n,this.batchValues[a+1]=i,this.batchValues[a+2]=0,this.batchValues[a+3]=0,r++,r===16&&(this.splatBatch(this.velocity,r),r=0)};for(let r of e){let{point:e,amount:a,flow:o,radiusPx:s,swirlPx:c}=r;a<=0||(i(e,s*1.3,o.x/t*a*.22,-o.y/n*a*.22),c&&i({x:e.x+s*.5,y:e.y+s*.5},s,-c/t*a*.08,c/n*a*.08))}this.splatBatch(this.velocity,r),r=0;for(let t of e){let{point:e,amount:n,radiusPx:i}=t;if(n<=0)continue;let a=i*1.2;if(e.x<-a*2||e.y<-a*2||e.x>this.width+a*2||e.y>this.height+a*2)continue;let o=r*4;this.batchStamps[o]=e.x/this.width,this.batchStamps[o+1]=1-e.y/this.height,this.batchStamps[o+2]=Math.max(2,a),this.batchStamps[o+3]=0,this.batchValues[o]=n*2.2,this.batchValues[o+1]=0,this.batchValues[o+2]=0,this.batchValues[o+3]=0,r++,r===16&&(this.splatBatch(this.dye,r),r=0)}this.splatBatch(this.dye,r)}disturb(e,t,n,r){if(!this.active||this.lost||r<=0)return;let i=this.width/this.simulation.width,a=this.height/this.simulation.height,o={x:e.x-t.x*r,y:e.y-t.y*r};this.splatSegment(this.velocity,o,e,n,n,[t.x/i*r*2.8,-t.y/a*r*2.8,0,0])}injectFlameSegment(e,t,n,r,i){if(this.lost||n<=0)return;this.active=!0,this.idle=0,this.flameOrigin=e;let a=this.width/this.simulation.width,o=this.height/this.simulation.height;this.splatSegment(this.velocity,e,t,8,21,[r.x/a*n*.26,-r.y/o*n*.26,0,0]);let s={x:e.x+(t.x-e.x)*.9,y:e.y+(t.y-e.y)*.9};this.stirFlame(e,s,i,n,a,o),this.splatFlame(e,t,[24,17,9],[n*.65,n*1.55,n*2.2],i)}injectFlameStamps(e,t,n){if(!e.length||this.lost||!this.flameSource||!this.flameStampProgram||!this.flameStampBuffer)return;this.beginGpu(`fire.stamps`);let r=this.gl,i=Math.min(e.length,this.flameStampData.length/5),a=null,o=null,s=0,c=0,l=0;for(let n=0;n<i;n++){let r=e[Math.floor(n*e.length/i)];!r.blast&&r.stir!==!1&&((!a||r.progress<a.progress)&&(a=r),(!o||r.progress>o.progress)&&(o=r),s+=r.flow.x,c+=r.flow.y,l++);let u=n*5;this.flameStampData[u]=r.point.x,this.flameStampData[u+1]=r.point.y,this.flameStampData[u+2]=Math.max(3,r.radius),this.flameStampData[u+3]=r.progress,this.flameStampData[u+4]=(r.blast?Math.min(.4,t*12):Math.min(.08,t*.65))*(r.strength??1)}this.active=!0,this.idle=0,this.flameOrigin=a?.point??{x:-1e3,y:-1e3},r.bindFramebuffer(r.FRAMEBUFFER,this.flameSource.framebuffer),r.viewport(0,0,this.flameSource.width,this.flameSource.height),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.useProgram(this.flameStampProgram),r.bindBuffer(r.ARRAY_BUFFER,this.flameStampBuffer),r.bufferData(r.ARRAY_BUFFER,this.flameStampData.subarray(0,i*5),r.DYNAMIC_DRAW);let u=os(this.flameStampProgram,`aStamp`),d=os(this.flameStampProgram,`aStrength`);if(r.enableVertexAttribArray(u),r.vertexAttribPointer(u,4,r.FLOAT,!1,20,0),r.enableVertexAttribArray(d),r.vertexAttribPointer(d,1,r.FLOAT,!1,20,16),r.uniform2f(H(this.flameStampProgram,`canvasSize`),this.width,this.height),r.uniform2f(H(this.flameStampProgram,`dyeSize`),this.flameSource.width,this.flameSource.height),r.uniform1i(H(this.flameStampProgram,`agePalette`),Number(this.agePalette)),r.enable(r.BLEND),r.blendFunc(r.ONE,r.ONE),r.drawArrays(r.POINTS,0,i),r.disable(r.BLEND),this.use(`addFlame`),this.texture(`addFlame`,`uTarget`,this.dye.read,0),this.texture(`addFlame`,`uSource`,this.flameSource,1),this.draw(this.dye.write),this.dye.swap(),!a||!o||!l){this.endGpu();return}let f=this.width/this.simulation.width,p=this.height/this.simulation.height,m={x:s/l,y:c/l},h=[m.x/f*t*.18,-m.y/p*t*.18,0,0],g=Math.hypot(m.x,m.y);if(g>.001){let r=1/0,i=-1/0;for(let t of e){if(t.blast||t.stir===!1)continue;let e=(-t.point.x*m.y+t.point.y*m.x)/g;r=Math.min(r,e),i=Math.max(i,e)}if(i-r>10){let a=(r+i)*.5,o=null,s=null,c=null,l=null;for(let t of e)t.blast||t.stir===!1||((-t.point.x*m.y+t.point.y*m.x)/g<a?((!o||t.progress<o.progress)&&(o=t),(!s||t.progress>s.progress)&&(s=t)):((!c||t.progress<c.progress)&&(c=t),(!l||t.progress>l.progress)&&(l=t)));if(o&&s&&c&&l){this.splatSegment(this.velocity,o.point,s.point,7,19,h),this.splatSegment(this.velocity,c.point,l.point,7,19,h),this.stirFlame(o.point,s.point,n,t*.55,f,p),this.stirFlame(c.point,l.point,n,t*.55,f,p),this.endGpu();return}}}this.splatSegment(this.velocity,a.point,o.point,7,19,h),this.stirFlame(a.point,o.point,n,t*.55,f,p),this.endGpu()}setFlameInk(e){if(!this.flamePalette||!this.flameSmokeTail||this.lost)return;let t=this.gl;this.flameInk&&t.deleteTexture(this.flameInk.texture);let n=t.createTexture();if(!n)throw Error(`Unable to allocate flame ink texture`);t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.R8,e.pixelWidth,e.pixelHeight,0,t.RED,t.UNSIGNED_BYTE,e.alpha),this.flameInk={texture:n,x:e.x,y:e.y,width:e.width,height:e.height,ignitionX:e.origin.x-e.x}}injectFlameInk(e,t){let n=this.flameInk;if(!n||!this.flameSource||this.lost||e>(n.width-n.ignitionX)/88+1.28)return;let r=this.gl;this.active=!0,this.idle=0,this.flameOrigin={x:-1e3,y:-1e3},this.use(`inkFlame`),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,n.texture),r.uniform1i(this.uniform(`inkFlame`,`uInk`),0),this.vec2(`inkFlame`,`uCanvasSize`,this.width,this.height),this.vec2(`inkFlame`,`uInkOrigin`,n.x,n.y),this.vec2(`inkFlame`,`uInkSize`,n.width,n.height),this.vec2(`inkFlame`,`uIgnition`,n.ignitionX,0),r.uniform1f(this.uniform(`inkFlame`,`uTime`),e),r.uniform1f(this.uniform(`inkFlame`,`uDt`),Math.min(.05,t)),this.draw(this.flameSource),this.use(`addFlame`),this.texture(`addFlame`,`uTarget`,this.dye.read,0),this.texture(`addFlame`,`uSource`,this.flameSource,1),this.draw(this.dye.write),this.dye.swap(),this.use(`inkFlow`),this.texture(`inkFlow`,`uVelocity`,this.velocity.read,0),this.vec2(`inkFlow`,`uCanvasSize`,this.width,this.height),this.vec2(`inkFlow`,`uCellSize`,this.width/this.simulation.width,this.height/this.simulation.height),this.vec2(`inkFlow`,`uInkOrigin`,n.x,n.y),this.vec2(`inkFlow`,`uInkSize`,n.width,n.height),r.uniform1f(this.uniform(`inkFlow`,`uIgnitionX`),n.ignitionX),r.uniform1f(this.uniform(`inkFlow`,`uTime`),e),r.uniform1f(this.uniform(`inkFlow`,`uDt`),Math.min(.05,t)),this.draw(this.velocity.write),this.velocity.swap()}injectBurnMasks(e,t,n){if(!this.flameSmokeTail||!this.flameSource||this.lost)return;this.beginGpu(`fire.mask`);let r=this.gl,i=this.flameSource,a=new Set;r.bindFramebuffer(r.FRAMEBUFFER,i.framebuffer),r.viewport(0,0,i.width,i.height),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),this.use(`sceneInkFlame`),this.vec2(`sceneInkFlame`,`uCanvasSize`,this.width,this.height),r.uniform1f(this.uniform(`sceneInkFlame`,`uDt`),Math.min(.05,t)),r.uniform1f(this.uniform(`sceneInkFlame`,`uTime`),n),r.uniform1i(this.uniform(`sceneInkFlame`,`uAgePalette`),Number(this.agePalette)),r.enable(r.BLEND),r.blendFunc(r.ONE,r.ONE),r.enable(r.SCISSOR_TEST);let o=0;for(let t of e){if(t.width<=0||t.height<=0||t.pixelWidth<=0||t.pixelHeight<=0||t.alpha.length<t.pixelWidth*t.pixelHeight)continue;let e=t.x+t.width/2,n=t.y+t.height/2,s=Math.hypot(t.width,t.height)/2+5;if(e+s<0||e-s>this.width||n+s<0||n-s>this.height)continue;let c=Math.max(0,Math.floor((e-s)*i.width/this.width)),l=Math.min(i.width,Math.ceil((e+s)*i.width/this.width)),u=Math.max(0,Math.floor((this.height-n-s)*i.height/this.height)),d=Math.min(i.height,Math.ceil((this.height-n+s)*i.height/this.height));if(l<=c||d<=u)continue;a.add(t.key);let f=this.sceneInk.get(t.key);if(!f||f.width!==t.pixelWidth||f.height!==t.pixelHeight){f&&r.deleteTexture(f.texture);let e=r.createTexture();if(!e)continue;f={texture:e,width:t.pixelWidth,height:t.pixelHeight,alpha:t.alpha,revision:t.revision??0},this.sceneInk.set(t.key,f),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,e),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.R8,f.width,f.height,0,r.RED,r.UNSIGNED_BYTE,t.alpha)}else r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,f.texture),(f.alpha!==t.alpha||f.revision!==(t.revision??0))&&(r.texSubImage2D(r.TEXTURE_2D,0,0,0,f.width,f.height,r.RED,r.UNSIGNED_BYTE,t.alpha),f.alpha=t.alpha,f.revision=t.revision??0);r.uniform1i(this.uniform(`sceneInkFlame`,`uInk`),0),r.scissor(c,u,l-c,d-u),r.uniform4f(this.uniform(`sceneInkFlame`,`uRect`),t.x,t.y,t.width,t.height),this.vec2(`sceneInkFlame`,`uOrigin`,t.origin.x,t.origin.y),r.uniform1f(this.uniform(`sceneInkFlame`,`uAngle`),t.angle??0),r.uniform1f(this.uniform(`sceneInkFlame`,`uAge`),t.age),r.uniform1f(this.uniform(`sceneInkFlame`,`uFarthest`),t.farthest),r.uniform1f(this.uniform(`sceneInkFlame`,`uSpreadSeconds`),t.spreadSeconds),r.uniform1f(this.uniform(`sceneInkFlame`,`uBurnSeconds`),t.burnSeconds),r.uniform1f(this.uniform(`sceneInkFlame`,`uSmokeRate`),(t.smokeRate??13)/13),r.uniform1f(this.uniform(`sceneInkFlame`,`uIntensity`),t.intensity??1),r.uniform1f(this.uniform(`sceneInkFlame`,`uFixedRadius`),t.fixedRadius??0),r.uniform1f(this.uniform(`sceneInkFlame`,`uSmokeOnly`),+!!t.smokeOnly),r.uniform1f(this.uniform(`sceneInkFlame`,`uBlastAge`),t.blastAge??-1),r.uniform1f(this.uniform(`sceneInkFlame`,`uBlastSeconds`),t.blastSeconds??0),this.draw(i),o++}r.disable(r.SCISSOR_TEST),r.disable(r.BLEND);for(let[e,t]of this.sceneInk)a.has(e)||(r.deleteTexture(t.texture),this.sceneInk.delete(e));o&&(this.active=!0,this.sceneFireActive=!0,this.idle=0,this.flameOrigin={x:-1e3,y:-1e3},this.use(`addFlame`),this.texture(`addFlame`,`uTarget`,this.dye.read,0),this.texture(`addFlame`,`uSource`,i,1),this.draw(this.dye.write),this.dye.swap()),this.endGpu()}applySceneFlow(e,t){let n=this.gl;this.use(`sceneFlow`),this.texture(`sceneFlow`,`uVelocity`,this.velocity.read,0),this.texture(`sceneFlow`,`uDye`,this.dye.read,1),this.vec2(`sceneFlow`,`uCanvasSize`,this.width,this.height),this.vec2(`sceneFlow`,`uCellSize`,this.width/this.simulation.width,this.height/this.simulation.height),n.uniform1f(this.uniform(`sceneFlow`,`uTime`),t),n.uniform1f(this.uniform(`sceneFlow`,`uDt`),Math.min(.05,e)),this.draw(this.velocity.write),this.velocity.swap()}step(e,t,n=[]){if(!this.active||this.lost)return;let r=this.gl;if(e=Math.min(.05,e),this.idle+=e,this.idle>(this.ghostField?1.7:this.flamePalette?this.flameSmokeTail?3.2:1.35:10)){this.reset();return}this.beginGpu(`fire.curlAndWalls`),r.disable(r.BLEND),this.updateWalls(n);let i=1/this.simulation.width,a=1/this.simulation.height;t&&this.applyBody(t),this.use(`curl`),this.vec2(`curl`,`texelSize`,i,a),this.texture(`curl`,`uVelocity`,this.velocity.read,0),this.draw(this.curl),this.use(`vorticity`),this.vec2(`vorticity`,`texelSize`,i,a),this.texture(`vorticity`,`uVelocity`,this.velocity.read,0),this.texture(`vorticity`,`uCurl`,this.curl,1),r.uniform1f(this.uniform(`vorticity`,`curl`),this.vorticity),r.uniform1f(this.uniform(`vorticity`,`dt`),e),this.draw(this.velocity.write),this.velocity.swap(),this.use(`divergence`),this.bindWalls(`divergence`),this.vec2(`divergence`,`texelSize`,i,a),this.texture(`divergence`,`uVelocity`,this.velocity.read,0),this.draw(this.divergence),this.endGpu(),this.beginGpu(`fire.pressure`),this.use(`clear`),this.texture(`clear`,`uTexture`,this.pressure.read,0),r.uniform1f(this.uniform(`clear`,`value`),.8),this.draw(this.pressure.write),this.pressure.swap(),this.use(`pressure`),this.bindWalls(`pressure`),this.vec2(`pressure`,`texelSize`,i,a),this.texture(`pressure`,`uDivergence`,this.divergence,0);for(let e=0;e<sc[this.quality].iterations;e++)this.texture(`pressure`,`uPressure`,this.pressure.read,1),this.draw(this.pressure.write),this.pressure.swap();this.use(`gradient`),this.bindWalls(`gradient`),this.vec2(`gradient`,`texelSize`,i,a),this.texture(`gradient`,`uPressure`,this.pressure.read,0),this.texture(`gradient`,`uVelocity`,this.velocity.read,1),this.draw(this.velocity.write),this.velocity.swap(),this.endGpu(),this.beginGpu(`fire.transport`),t&&this.applyBody(t),this.use(`advection`),this.bindWalls(`advection`),r.uniform1i(this.uniform(`advection`,`ageDye`),0),this.vec2(`advection`,`velocityTexel`,i,a),this.vec2(`advection`,`sourceTexel`,i,a),r.uniform1f(this.uniform(`advection`,`dt`),e),r.uniform4f(this.uniform(`advection`,`dissipation`),.2,.2,.2,.2),this.texture(`advection`,`uVelocity`,this.velocity.read,0),this.texture(`advection`,`uSource`,this.velocity.read,1),this.draw(this.velocity.write),this.velocity.swap(),this.sceneFireActive&&this.applySceneFlow(e,performance.now()*.001);for(let e of this.radialBlasts)this.use(`radialBlast`),this.texture(`radialBlast`,`uVelocity`,this.velocity.read,0),this.vec2(`radialBlast`,`uCanvasSize`,this.width,this.height),this.vec2(`radialBlast`,`uCellSize`,this.width/this.simulation.width,this.height/this.simulation.height),this.vec2(`radialBlast`,`uCenter`,e.center.x,e.center.y),r.uniform1f(this.uniform(`radialBlast`,`uRadius`),e.radius),this.draw(this.velocity.write),this.velocity.swap();this.radialBlasts=[],this.use(`advection`),this.bindWalls(`advection`),r.uniform1i(this.uniform(`advection`,`ageDye`),Number(this.agePalette)),this.vec2(`advection`,`velocityTexel`,i,a),r.uniform1f(this.uniform(`advection`,`dt`),e),this.vec2(`advection`,`sourceTexel`,1/this.dyeSize.width,1/this.dyeSize.height);let o=this.idle<.1,s=o?1:2.8;r.uniform4f(this.uniform(`advection`,`dissipation`),this.agePalette?s:this.flamePalette?o?.7:3:this.ghostField?2.1:.65,this.agePalette?s:this.flamePalette?o?.85:3.8:0,this.agePalette?s:this.flamePalette?o?1.05:4.8:0,this.flameSmokeTail?rc(this.idle).dissipation:0),this.texture(`advection`,`uVelocity`,this.velocity.read,0),this.texture(`advection`,`uSource`,this.dye.read,1),this.draw(this.dye.write),this.dye.swap(),this.endGpu()}drawTo(e,t,n=!1,r=[]){if(!this.active||this.lost)return;this.align(t),performance.now(),this.beginGpu(`fire.display`);let i=this.gl,a=`display`;this.use(a),this.bindWalls(a),this.texture(a,`uDye`,this.dye.read,0);let o=this.tint;i.uniform3f(this.uniform(a,`smokeColor`),o[0],o[1],o[2]),i.uniform1i(this.uniform(a,`darkBackground`),Number(n));let s=Math.min(r.length,12);i.uniform1i(this.uniform(`display`,`vehicleLightCount`),s);for(let e=0;e<s;e++){let t=r[e],n=e*4;this.lightPositions[n]=t.point.x,this.lightPositions[n+1]=t.point.y,this.lightPositions[n+2]=t.range,this.lightPositions[n+3]=t.radius,this.lightShapes[n]=t.direction.x,this.lightShapes[n+1]=t.direction.y,this.lightShapes[n+2]=t.spread,this.lightShapes[n+3]=t.shadow?.range??0,this.lightColors[n]=t.color[0],this.lightColors[n+1]=t.color[1],this.lightColors[n+2]=t.color[2],this.lightColors[n+3]=t.intensity}this.bindLightShadows(r.slice(0,s)),s&&(i.uniform4fv(this.uniform(`display`,`vehicleLightPosition[0]`),this.lightPositions),i.uniform4fv(this.uniform(`display`,`vehicleLightShape[0]`),this.lightShapes),i.uniform4fv(this.uniform(`display`,`vehicleLightColor[0]`),this.lightColors)),i.uniform1i(this.uniform(`display`,`flamePalette`),Number(this.flamePalette)),i.uniform1i(this.uniform(`display`,`agePalette`),Number(this.agePalette)),i.uniform1f(this.uniform(`display`,`lifecycleOpacity`),this.flameSmokeTail?rc(this.idle).opacity:1),this.vec2(`display`,`flameOrigin`,this.flameOrigin.x,this.height-this.flameOrigin.y),this.vec2(`display`,`size`,this.width,this.height),i.bindFramebuffer(i.FRAMEBUFFER,null),i.viewport(0,0,this.canvas.width,this.canvas.height),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),this.draw(null),this.endGpu(),f(`composited megapixels`,this.canvas.width*this.canvas.height/1e6),performance.now(),e.drawImage(this.canvas,0,0,this.width,this.height)}};function mc(e,t,n,r=`fuel-age`){return new pc(e,t,n,void 0,12,!0,!0,!1,r===`fuel-age`)}var hc=class{camera;quality;tireFire=new ec;fluid=null;fluidAttempted=!1;fluidClock=0;maskBatch=new $s;sceneMasks=new Map;hadSceneMasks=!1;stamps=[];blasts=[];vehicleAlpha=new WeakMap;previousFireTire=new Map;fireRefreshClock=0;constructor(e,t){this.camera=e,this.quality=t}get count(){return this.tireFire.count}get managedBytes(){return this.tireFire.managedBytes+(this.fluid?.managedBytes??0)}get resolution(){return this.fluid?.resolution}get available(){return this.fluid?.available??!1}prepare(){if(!this.fluidAttempted){this.fluidAttempted=!0,performance.now();try{this.fluid=mc(this.camera.width,this.camera.height,this.quality)}catch(e){console.error(`Joy Ride fire requires WebGL2`,e)}}return this.fluid?.available?this.fluid:null}ensure(){return!!this.prepare()}get running(){return!!this.fluid?.running}setQuality(e){this.quality=e,this.fluid?.setQuality(e)}resize(e){this.fluid?.resize(this.camera.width,this.camera.height,!1,e)}alphaFor(e){let t=this.vehicleAlpha.get(e);return t||(t=e.map(e=>e?255:0),this.vehicleAlpha.set(e,t)),t}sceneMasksDue(e){return!this.sceneMasks.size||this.fluidClock+e>=this.solveInterval()}solveInterval(){return 1/(this.quality===`high`?45:this.quality===`medium`?30:24)}queueMask(e){this.prepare()&&this.sceneMasks.set(e.key,e)}queueBlast(e,t){this.blasts.push({point:e,radius:t})}queueStamp(e){this.prepare()&&this.stamps.push(e)}activateBuoyancy(){let e=this.prepare();return e?(e.activateBuoyancy(),!0):!1}emitJet(e,t,n,r,i,a){if(!this.prepare())return;let o=this.camera.particlePoint(e),s=this.camera.particlePoint(t),c=x(s,o),l=this.camera.particleScale(),u=Math.max(a===`rocket`?6:4,r*l*1.9),d=a===`exhaust`&&m(c)<.001?0:Math.min(10,Math.max(1,Math.ceil(m(c)/Math.max(4,u)))),f=this.camera.pixelSpace?C(n.x*this.camera.zoom,-n.y*this.camera.zoom):{...n};for(let e=0;e<=d;e++){let t=1-e/Math.max(1,d);this.stamps.push({point:S(S(o,v(c,e/Math.max(1,d))),a===`rocket`?v(f,t*.025):C()),radius:u*(a===`rocket`?.8+t*.65:1),progress:a===`rocket`?.08+t*.48:.95,flow:f,strength:a===`rocket`?i*5.2:4+i*8,source:a===`rocket`?`rocket`:void 0,stir:a===`rocket`})}}igniteTire(e,t,n,r,i){this.tireFire.ignite(e,t,n,r,i)}stepTire(e){this.tireFire.step(e)}emberSource(){return this.tireFire.emberSource()}clearTireHistory(){this.previousFireTire.clear(),this.fireRefreshClock=0}stepBoostFire(e,t,n){if(!e.car.boostActive){this.clearTireHistory();return}this.fireRefreshClock+=t;let r=this.fireRefreshClock>=1/15;r&&(this.fireRefreshClock%=1/15);let i=this.camera.particleScale();e.car.tires.forEach((t,a)=>{if(t.front)return;let o=this.camera.particlePoint(e.body.world(t.local));n(o);let s=this.previousFireTire.get(a)??o;!r&&m(x(o,s))<.24*i&&this.previousFireTire.has(a)||(this.igniteTire(s,o,e.car.preset.geometry.tireWidthM*i,e.car.preset.launch.fireLifetimeSeconds,.24*i),this.previousFireTire.set(a,o))})}particleScreen(e){return this.camera.pixelSpace?x(e,this.camera.sceneScroll()):this.camera.screen(e)}step(e,t,n,r,i,a,o){let s=this.fluid??(this.tireFire.count?this.prepare():null);if(!s?.available){this.stamps=[],this.blasts=[],this.sceneMasks.clear();return}if(!this.stamps.length&&!this.blasts.length&&!this.sceneMasks.size&&!this.tireFire.count&&s.managedBytes===0)return;this.fluidClock+=e;let c=this.solveInterval();if(this.fluidClock<c)return;let l=Math.min(.1,this.fluidClock);this.fluidClock=Math.max(0,this.fluidClock-c),s.align(a);let u=i?[]:this.tireFire.stamps();u.length&&s.activateBuoyancy();let d=[...this.stamps,...u].map(e=>({...e,point:this.particleScreen(e.point),radius:e.radius*(this.camera.pixelSpace?1:this.camera.zoom),flow:this.camera.pixelSpace?e.flow:C(e.flow.x*this.camera.zoom,-e.flow.y*this.camera.zoom)}));this.stamps=[];for(let e of this.blasts)s.queueRadialBlast(this.particleScreen(e.point),e.radius*(this.camera.pixelSpace?1:this.camera.zoom));this.blasts=[];let f=this.camera.pixelSpace?this.camera.sceneScroll():C(),p=[...this.sceneMasks.values()].map(e=>({...e,x:e.x-f.x,y:e.y-f.y,origin:x(e.origin,f)}));this.sceneMasks.clear();let m=Math.min(8,p.length);for(let e=0;e<m;e++){let t=p[Math.floor((e+.5)*p.length/m)];t.smokeOnly||o.emitFire(t,l)}performance.now();let h=this.maskBatch.combine(p,this.camera.width,this.camera.height);(h.length||this.hadSceneMasks||s.hasSceneFire)&&(performance.now(),s.injectBurnMasks(h,l,t),this.hadSceneMasks=h.length>0),performance.now();let g=d.filter(e=>e.source===`rocket`);s.injectFlameStamps(g.length?d.filter(e=>e.source!==`rocket`):d,l,t),g.length&&s.injectFlameStamps(g,l,t);let _=this.camera.pixelSpace?r.map(e=>({x:e.x-f.x,y:e.y-f.y,width:e.width,height:e.height})):[];performance.now(),s.step(l,n&&this.camera.pixelSpace?{...n,center:x(n.center,C(this.camera.smokeMargin,this.camera.smokeMargin))}:n,_)}draw(e,t,n,r){this.fluid?.drawTo(e,t,n,r)}captureState(){let e=this.tireFire.captureState();try{let t=this.fluid?.captureState()??null;return{tireFire:e,flame:t,fluidAttempted:this.fluidAttempted,fluidClock:this.fluidClock,hadSceneMasks:this.hadSceneMasks,stamps:this.stamps.map(e=>({...e,point:{...e.point},flow:{...e.flow}})),blasts:this.blasts.map(e=>({point:{...e.point},radius:e.radius})),previousFireTire:new Map([...this.previousFireTire].map(([e,t])=>[e,{...t}])),fireRefreshClock:this.fireRefreshClock,dispose:()=>{e.dispose(),t?.dispose()}}}catch(t){throw e.dispose(),t}}restoreState(e){if(this.reset(),this.tireFire.restoreState(e.tireFire),e.flame){this.fluid||(this.fluidAttempted=!1);let t=this.fluid??this.prepare();if(!t)throw Error(`Flame GPU context is unavailable`);t.restoreState(e.flame),this.fluidAttempted=e.fluidAttempted}else this.fluid?.dispose(),this.fluid=null,this.fluidAttempted=!1;this.fluidClock=e.fluidClock,this.hadSceneMasks=e.hadSceneMasks,this.stamps=e.stamps.map(e=>({...e,point:{...e.point},flow:{...e.flow}})),this.blasts=e.blasts.map(e=>({point:{...e.point},radius:e.radius}));for(let[t,n]of e.previousFireTire)this.previousFireTire.set(t,{...n});this.fireRefreshClock=e.fireRefreshClock}reset(){this.tireFire.reset(),this.fluid?.reset(),this.fluidClock=0,this.sceneMasks.clear(),this.hadSceneMasks=!1,this.stamps=[],this.blasts=[],this.clearTireHistory()}dispose(){this.fluid?.dispose(),this.tireFire.dispose()}},gc=class{quality;gpu=null;constructor(e,t,n){this.quality=n;try{this.gpu=new pc(e,t,n)}catch(e){console.error(`Joy Ride smoke requires WebGL2`,e)}}get running(){return!!this.gpu?.running}get usesWebGL(){return!!this.gpu?.available}get managedBytes(){return this.usesWebGL?this.gpu.managedBytes:0}get resolution(){return this.usesWebGL?this.gpu.resolution:{quality:this.quality,cols:0,rows:0,engine:`WebGL2 required`}}captureState(){return this.usesWebGL?this.gpu.captureState():null}restoreState(e){if(e&&!this.usesWebGL)throw Error(`Smoke GPU context is unavailable`);e?this.gpu.restoreState(e):this.reset()}setQuality(e){this.quality=e,this.usesWebGL&&this.gpu.setQuality(e)}resize(e,t,n){this.usesWebGL&&this.gpu.resize(e,t,!1,n)}reset(){this.usesWebGL&&this.gpu.reset()}dispose(){this.gpu?.dispose(),this.gpu=null}align(e){this.usesWebGL&&this.gpu.align(e)}inject(e,t,n,r,i){this.usesWebGL&&this.gpu.inject(e,t,n,r,i)}injectBatch(e){this.usesWebGL&&this.gpu.injectBatch(e)}disturb(e,t,n,r){this.usesWebGL&&this.gpu.disturb(e,t,n,r)}step(e,t,n=[]){this.usesWebGL&&this.gpu.step(e,t,n)}draw(e,t,n=[],r=!1){this.usesWebGL&&this.gpu.drawTo(e,t,r,n)}},K={lightColor:[.012,.015,.021],darkColor:[.98,.985,1],vorticity:23,maxMotionSpeedPxPerSecond:260,emissionFactor:1.2,wakeSpeedPxPerSecond:260,wakeEmissionFactor:1.6,wakeFlowFactor:.18,wallSmokeFactor:1.45,emergenceSmokeFactor:1.7,emergenceFadeSeconds:.8,emissionPerSecond:.82,driftPixelsPerSecond:27,radiusFactor:.17,bodyInfluence:.24};function _c(e,t,n,r,i){if(!i.length)return 0;let a=C(-t.y,t.x),o=Math.abs(t.x)*n+Math.abs(a.x)*r,s=Math.abs(t.y)*n+Math.abs(a.y)*r,c=i.filter(t=>t.x<=e.x+o&&t.x+t.width>=e.x-o&&t.y<=e.y+s&&t.y+t.height>=e.y-s);if(!c.length)return 0;let l=0;for(let i=0;i<5;i++)for(let o=0;o<7;o++){let s=((o+.5)/7*2-1)*n,u=((i+.5)/5*2-1)*r,d=e.x+t.x*s+a.x*u,f=e.y+t.y*s+a.y*u;c.some(e=>d>=e.x&&d<=e.x+e.width&&f>=e.y&&f<=e.y+e.height)&&l++}return l/35}var vc=new WeakMap;function yc(e,t=`high`){let n=vc.get(e),r=n?.get(t);if(r)return r;let i=[],a=t===`high`?4:t===`medium`?2:1,o=4*a,s=9*a,c=(t,n)=>{if(t<0||t>=o||n<0||n>=s)return!1;let r=Math.min(e.columns-1,Math.floor((n+.5)/s*e.columns)),i=Math.min(e.rows-1,Math.floor((t+.5)/o*e.rows));return!!e.solid[i*e.columns+r]};for(let e=0;e<o;e++)for(let t=0;t<s;t++)c(e,t)&&(c(e-1,t)&&c(e+1,t)&&c(e,t-1)&&c(e,t+1)||i.push(C((t+.5)/s*2-1,(e+.5)/o*2-1)));return i.length||i.push(C()),n||vc.set(e,n=new Map),n.set(t,i),i}var bc=class{camera;quality;smoke;sources=[];smokeClock=0;ghost=null;ghostAttempted=!1;ghostClock=0;ghostWallCoverage=new Map;ghostEmergence=new Map;constructor(e,t){this.camera=e,this.quality=t,this.smoke=new gc(1,1,t)}get smokeResolution(){return this.smoke.resolution}get smokeBytes(){return this.sources.length*64+this.smoke.managedBytes}get ghostBytes(){return this.ghost?.managedBytes??0}get ghostAvailable(){return this.ghost?.available??!1}get running(){return this.smoke.running||!!this.ghost?.running}setQuality(e){this.quality=e,this.smoke.setQuality(e),this.ghost?.setQuality(e)}resize(e){this.smoke.resize(this.camera.width+2*this.camera.smokeMargin,this.camera.height+2*this.camera.smokeMargin,e),this.ghost?.resize(this.camera.width,this.camera.height,!1,e)}emitSmoke(e){this.sources.push(e)}clearSmokeSources(){this.sources=[]}particleScreen(e){return this.camera.pixelSpace?x(e,this.camera.sceneScroll()):this.camera.screen(e)}stepSmoke(e,t,n,r){if(!this.smoke.usesWebGL){this.sources=[];return}this.smokeClock+=e;let i=1/(this.quality===`high`?45:this.quality===`medium`?30:24);if(this.smokeClock<i)return;let a=Math.min(.1,this.smokeClock);this.smokeClock=Math.max(0,this.smokeClock-i),this.smoke.align(r),this.smoke.injectBatch(this.sources.map(e=>({...e,point:S(this.particleScreen(e.point),C(this.camera.smokeMargin,this.camera.smokeMargin))}))),this.sources=[];let o=this.camera.sceneScroll(),s=this.camera.pixelSpace?n.map(e=>({x:e.x-o.x+this.camera.smokeMargin,y:e.y-o.y+this.camera.smokeMargin,width:e.width,height:e.height})):[];this.smoke.step(a,t,s)}drawSmoke(e,t,n,r){this.smoke.draw(e,t,n,r)}prepareGhost(){if(!this.ghostAttempted){this.ghostAttempted=!0;try{this.ghost=new pc(this.camera.width,this.camera.height,this.quality,K.lightColor,K.vorticity,!1,!1,!0)}catch(e){console.error(`Joy Ride ghost mode requires WebGL2`,e)}}return this.ghost?.available?this.ghost:null}stepGhost(e,t,n,r,i,a,o){let s=t.filter(e=>e.isGhost);if(!s.length)this.ghostWallCoverage.clear(),this.ghostEmergence.clear();else{let e=new Set(s.map(e=>e.id));for(let t of this.ghostWallCoverage.keys())e.has(t)||this.ghostWallCoverage.delete(t);for(let t of this.ghostEmergence.keys())e.has(t)||this.ghostEmergence.delete(t)}let c=s.length?this.prepareGhost():this.ghost;if(!c?.available||!s.length&&c.managedBytes===0)return;this.ghostClock+=e;let l=1/(this.quality===`high`?45:this.quality===`medium`?30:24);if(this.ghostClock<l)return;let u=Math.min(.1,this.ghostClock);this.ghostClock=Math.max(0,this.ghostClock-l),c.align(i);let d=this.camera.sceneScroll(),f=this.camera.pixelSpace?n.map(e=>({x:e.x-d.x,y:e.y-d.y,width:e.width,height:e.height})):[],p=null;if(r&&s.length){let e=K,n=[];for(let i of s){let{sim:s}=i,l=r(i),d=S(this.camera.screen(s.body.position),i===t[0]?a(i):C()),h=C(Math.cos(s.body.angle),-Math.sin(s.body.angle)),g=C(-h.y,h.x),_=l.lengthM*this.camera.zoom/2,y=l.widthM*this.camera.zoom/2,b=_c(d,h,_,y,f),x=this.ghostWallCoverage.get(i.id)??0,w=x+(b-x)*(1-Math.exp(-u*12));this.ghostWallCoverage.set(i.id,w);let T=Math.max(0,(this.ghostEmergence.get(i.id)??0)-u/K.emergenceFadeSeconds,(x-b)*1.8);this.ghostEmergence.set(i.id,T);let ee=C(s.body.velocity.x*this.camera.zoom,-s.body.velocity.y*this.camera.zoom),E=v(ee,Math.min(1,K.maxMotionSpeedPxPerSecond/Math.max(1,m(ee)))),D=m(E),te=Math.min(1,D/K.wakeSpeedPxPerSecond),ne=E.x*h.x+E.y*h.y,re=Math.max(3,Math.min(14,y*e.radiusFactor));p||={center:d,forward:h,halfLength:_*.94,halfWidth:y*.78,velocity:E,spin:-s.body.spin,influence:e.bodyInfluence},c.injectSilhouette(l.alpha,{center:d,forward:h,halfLength:_,halfWidth:y,velocity:E,spin:-s.body.spin},u*e.emissionPerSecond*3,this.camera.timeSeconds,o?.(i));let O=yc(l.alpha,this.quality),ie=yc(l.alpha,`low`).length/O.length;for(let t of O){let r=Math.max(0,ne>=0?-t.x:t.x);n.push({point:S(d,S(v(h,t.x*_),v(g,t.y*y))),amount:u*e.emissionPerSecond*K.emissionFactor*ie*(1+te*r*K.wakeEmissionFactor)*(1+w*K.wallSmokeFactor+T*K.emergenceSmokeFactor),flow:S(v(E,.18-te*r*K.wakeFlowFactor),S(v(g,t.y*e.driftPixelsPerSecond),v(h,-e.driftPixelsPerSecond*.65))),radiusPx:re,swirlPx:e.driftPixelsPerSecond*(t.y<0?-1:1)})}if(T>.05){let t=ne>=0?-1:1,r=S(d,v(h,_*t*.72));for(let i of[-1,1])n.push({point:S(r,v(g,i*y*.45)),amount:u*e.emissionPerSecond*K.emissionFactor*T*1.35,flow:S(v(h,t*e.driftPixelsPerSecond*2),v(g,i*e.driftPixelsPerSecond*.7)),radiusPx:re*1.55,swirlPx:i*e.driftPixelsPerSecond})}}c.injectBatch(n)}c.step(u,p,f)}drawGhost(e,t,n,r=[]){this.ghost?.available&&(this.ghost.setTint(n?K.darkColor:K.lightColor),this.ghost.drawTo(e,t,n,r))}captureState(){let e=this.smoke.captureState();try{let t=this.ghost?.captureState()??null;return{smoke:e,ghost:t,sources:this.sources.map(e=>({...e,point:{...e.point},flow:{...e.flow}})),smokeClock:this.smokeClock,ghostAttempted:this.ghostAttempted,ghostClock:this.ghostClock,ghostWallCoverage:new Map(this.ghostWallCoverage),ghostEmergence:new Map(this.ghostEmergence),dispose:()=>{e?.dispose(),t?.dispose()}}}catch(t){throw e?.dispose(),t}}restoreState(e){if(this.reset(),this.smoke.restoreState(e.smoke),e.ghost){this.ghost||(this.ghostAttempted=!1);let t=this.ghost??this.prepareGhost();if(!t)throw Error(`Ghost GPU context is unavailable`);t.restoreState(e.ghost),this.ghostAttempted=e.ghostAttempted}else this.ghost?.dispose(),this.ghost=null,this.ghostAttempted=!1;this.sources=e.sources.map(e=>({...e,point:{...e.point},flow:{...e.flow}})),this.smokeClock=e.smokeClock,this.ghostClock=e.ghostClock,this.ghostWallCoverage=new Map(e.ghostWallCoverage),this.ghostEmergence=new Map(e.ghostEmergence)}reset(){this.smoke.reset(),this.ghost?.reset(),this.sources=[],this.smokeClock=0,this.ghostClock=0,this.ghostWallCoverage.clear(),this.ghostEmergence.clear()}dispose(){this.smoke.dispose(),this.ghost?.dispose()}},xc={color:[.14,.64,1],corona:[.28,.13,1]},Sc=14,Cc=`#version 300 es
|
|
700
|
-
precision highp float;
|
|
701
|
-
in vec2 aStart, aEnd, aMotion;
|
|
702
|
-
in vec4 aStyle;
|
|
703
|
-
in float aSeed;
|
|
704
|
-
in vec3 aColor;
|
|
705
|
-
uniform vec2 uViewport;
|
|
706
|
-
uniform vec4 uDisturbance;
|
|
707
|
-
uniform float uDisturbanceRadius;
|
|
708
|
-
out vec2 vLocal;
|
|
709
|
-
out float vLength, vCooling, vKind, vSeed, vSize;
|
|
710
|
-
out vec3 vColor;
|
|
711
|
-
|
|
712
|
-
vec2 emberPosition(float t) {
|
|
713
|
-
float s = aSeed * 6.2831853;
|
|
714
|
-
// Two incommensurate eddies give some firebrands a short reverse turn.
|
|
715
|
-
// Their amplitudes and periods differ per particle, like turbulent lofting.
|
|
716
|
-
float slow = 3.0 + fract(aSeed * 73.19) * 3.1;
|
|
717
|
-
float fast = 7.5 + fract(aSeed * 41.73) * 6.2;
|
|
718
|
-
vec2 eddy = vec2(
|
|
719
|
-
(sin(slow*t+s*2.3)-sin(s*2.3)) * (5.0+fract(aSeed*91.7)*13.0)
|
|
720
|
-
+ (sin(fast*t-s*3.1)-sin(-s*3.1))*3.5,
|
|
721
|
-
(cos(slow*t+s*1.7)-cos(s*1.7))*4.0
|
|
722
|
-
+ (sin(fast*t+s*4.7)-sin(s*4.7))*2.5);
|
|
723
|
-
vec2 travel = aMotion*t + vec2(0.0, -t*t*(24.0+fract(aSeed*19.3)*38.0));
|
|
724
|
-
vec2 point = aStart + travel + eddy;
|
|
725
|
-
vec2 fromGust = point-uDisturbance.xy;
|
|
726
|
-
float nearGust = exp(-dot(fromGust,fromGust) /
|
|
727
|
-
max(1.0,uDisturbanceRadius*uDisturbanceRadius));
|
|
728
|
-
vec2 turn = vec2(-fromGust.y,fromGust.x) /
|
|
729
|
-
max(length(fromGust),14.0);
|
|
730
|
-
point += (uDisturbance.zw*0.17+turn*length(uDisturbance.zw)*0.055)
|
|
731
|
-
* nearGust * t;
|
|
732
|
-
return point;
|
|
733
|
-
}
|
|
734
|
-
|
|
735
|
-
void main() {
|
|
736
|
-
float age = aStyle.x;
|
|
737
|
-
vCooling = clamp(age/max(aStyle.y,0.001),0.0,1.0);
|
|
738
|
-
vKind = aStyle.w;
|
|
739
|
-
vSeed = aSeed;
|
|
740
|
-
vColor = aColor;
|
|
741
|
-
vSize = aStyle.z;
|
|
742
|
-
vec2 start = aStart;
|
|
743
|
-
vec2 end = aEnd;
|
|
744
|
-
if (vKind > 4.5) {
|
|
745
|
-
// Pickup motes remain circular while their world-space positions drift independently.
|
|
746
|
-
start = end;
|
|
747
|
-
} else if (vKind > 1.5 && vKind < 2.5) {
|
|
748
|
-
start = emberPosition(max(0.0,age-(0.018+fract(aSeed*17.2)*0.024)));
|
|
749
|
-
end = emberPosition(age);
|
|
750
|
-
} else if (vKind > 2.5 && vKind < 3.5) {
|
|
751
|
-
vec2 axis = vec2(cos(aSeed*6.2831853),sin(aSeed*6.2831853));
|
|
752
|
-
start = aStart-axis*aStyle.z*0.12;
|
|
753
|
-
end = aStart+axis*aStyle.z*0.12;
|
|
754
|
-
}
|
|
755
|
-
vec2 delta = end-start;
|
|
756
|
-
float lengthPx = max(length(delta),0.01);
|
|
757
|
-
vec2 axis = lengthPx < 0.1 ? vec2(1.0,0.0) : delta/lengthPx;
|
|
758
|
-
vec2 normal = vec2(-axis.y,axis.x);
|
|
759
|
-
vec2 corner[6] = vec2[6](
|
|
760
|
-
vec2(0.0,-1.0),vec2(0.0,1.0),vec2(1.0,-1.0),
|
|
761
|
-
vec2(1.0,-1.0),vec2(0.0,1.0),vec2(1.0,1.0));
|
|
762
|
-
vec2 uv = corner[gl_VertexID];
|
|
763
|
-
float radius = vKind > 4.5 ? max(7.0,aStyle.z*4.5) :
|
|
764
|
-
vKind > 3.5 ? max(7.0,aStyle.z*5.0) :
|
|
765
|
-
vKind > 2.5 ? max(12.0,aStyle.z*2.4) :
|
|
766
|
-
vKind > 1.5 ? max(8.0,aStyle.z*4.5) : max(7.0,aStyle.z*3.0);
|
|
767
|
-
float axial = mix(-radius,lengthPx+radius,uv.x);
|
|
768
|
-
float across = uv.y*radius;
|
|
769
|
-
vLocal = vec2(axial,across);
|
|
770
|
-
vLength = lengthPx;
|
|
771
|
-
vec2 position = start+axis*axial+normal*across;
|
|
772
|
-
gl_Position = vec4(position/uViewport*vec2(2.0,-2.0)+vec2(-1.0,1.0),0.0,1.0);
|
|
773
|
-
}`,wc=`#version 300 es
|
|
774
|
-
precision highp float;
|
|
775
|
-
in vec2 vLocal;
|
|
776
|
-
in float vLength, vCooling, vKind, vSeed, vSize;
|
|
777
|
-
in vec3 vColor;
|
|
778
|
-
uniform float uFade;
|
|
779
|
-
uniform vec2 uViewport;
|
|
780
|
-
uniform int uWallCount;
|
|
781
|
-
uniform vec4 uWalls[32];
|
|
782
|
-
uniform vec3 uElectricColor;
|
|
783
|
-
uniform vec3 uElectricCorona;
|
|
784
|
-
out vec4 color;
|
|
785
|
-
void main() {
|
|
786
|
-
vec2 pixel = vec2(gl_FragCoord.x,uViewport.y-gl_FragCoord.y);
|
|
787
|
-
for (int index=0;index<32;index++) {
|
|
788
|
-
if (index>=uWallCount) break;
|
|
789
|
-
vec4 wall = uWalls[index];
|
|
790
|
-
if (pixel.x>=wall.x && pixel.x<=wall.z &&
|
|
791
|
-
pixel.y>=wall.y && pixel.y<=wall.w) discard;
|
|
792
|
-
}
|
|
793
|
-
float dist = length(vLocal-vec2(clamp(vLocal.x,0.0,vLength),0.0));
|
|
794
|
-
float aa = max(0.7,fwidth(dist));
|
|
795
|
-
bool ember = vKind>1.5 && vKind<2.5;
|
|
796
|
-
bool flash = vKind>2.5 && vKind<3.5;
|
|
797
|
-
bool electrical = vKind>3.5 && vKind<4.5;
|
|
798
|
-
if (vKind>4.5) {
|
|
799
|
-
float body = exp(-dist*dist/max(0.6,vSize*vSize*0.85));
|
|
800
|
-
float glow = exp(-dist*dist/max(1.5,vSize*vSize*5.0));
|
|
801
|
-
float life = 1.0-smoothstep(0.4,1.0,vCooling);
|
|
802
|
-
float alpha = clamp(body+glow*0.22,0.0,1.0)*life*uFade;
|
|
803
|
-
color = vec4(mix(vColor,vec3(1.0),body*0.85),alpha);
|
|
804
|
-
return;
|
|
805
|
-
}
|
|
806
|
-
if (electrical) {
|
|
807
|
-
float heat = pow(1.0-vCooling,0.85+vSeed*0.25);
|
|
808
|
-
float coreRadius = 0.3+vSize*0.2;
|
|
809
|
-
float core = 1.0-smoothstep(max(0.0,coreRadius-aa*0.7),coreRadius+aa*0.7,dist);
|
|
810
|
-
float sheath = exp(-dist*dist/max(0.6,vSize*vSize*2.5));
|
|
811
|
-
float glow = exp(-dist*dist/max(4.0,vSize*vSize*15.0));
|
|
812
|
-
float flicker = 0.88+0.12*sin(vSeed*157.0+vCooling*52.0);
|
|
813
|
-
vec3 cool = mix(uElectricCorona,uElectricColor,sheath);
|
|
814
|
-
cool = mix(cool,vec3(0.92,0.985,1.0),core*heat*0.93);
|
|
815
|
-
float alpha = clamp(core+sheath*0.28+glow*0.13,0.0,1.0)*heat*flicker*uFade;
|
|
816
|
-
color = vec4(cool,alpha);
|
|
817
|
-
return;
|
|
818
|
-
}
|
|
819
|
-
float heat = pow(1.0-vCooling,
|
|
820
|
-
ember?0.55:flash?1.8:0.55+vSeed*0.8);
|
|
821
|
-
// Cold metal loses its white core before its amber afterglow.
|
|
822
|
-
float coreRadius = flash?2.0:ember?0.32+vSize*0.26:0.38+vSize*0.13;
|
|
823
|
-
float core = 1.0-smoothstep(coreRadius-aa,coreRadius+aa,dist);
|
|
824
|
-
float rim = 1.0-smoothstep(coreRadius+0.55-aa,coreRadius+0.55+aa,dist);
|
|
825
|
-
float haloRadius = flash?7.0:ember?2.8+vSize*0.9:2.6+vSize*0.45;
|
|
826
|
-
float glow = exp(-dist*dist/(haloRadius*haloRadius));
|
|
827
|
-
float flicker = ember ? 0.83+0.17*sin(vSeed*139.1+vCooling*31.0) : 1.0;
|
|
828
|
-
float alpha = clamp(core+rim*0.3+glow*(ember?0.22:0.18),0.0,1.0);
|
|
829
|
-
alpha *= heat*flicker*uFade;
|
|
830
|
-
vec3 orange = mix(vec3(0.85,0.16,0.012),vec3(1.0,0.53,0.07),heat);
|
|
831
|
-
vec3 hot = mix(orange,vec3(1.0,0.88,0.45),
|
|
832
|
-
clamp(rim*heat*1.3,0.0,1.0));
|
|
833
|
-
hot = mix(hot,vec3(1.0,0.99,0.87),core*heat*0.85);
|
|
834
|
-
if (flash) {
|
|
835
|
-
hot = mix(vec3(1.0,0.44,0.025),vec3(1.0,0.96,0.62),core);
|
|
836
|
-
alpha = max(alpha,glow*0.5*heat*uFade);
|
|
837
|
-
}
|
|
838
|
-
color = vec4(hot,alpha);
|
|
839
|
-
}`,Tc=class{canvas=document.createElement(`canvas`);gl;program;buffer;viewportUniform;fadeUniform;wallCountUniform;wallsUniform;disturbanceUniform;disturbanceRadiusUniform;electricColorUniform;electricCoronaUniform;wallData=new Float32Array(128);data=new Float32Array(256*Sc);lost=!1;overlayHost=null;constructor(){this.canvas.width=512,this.canvas.height=512;let e=this.canvas.getContext(`webgl2`,{alpha:!0,depth:!1,stencil:!1,antialias:!0,premultipliedAlpha:!0});if(!e)throw Error(`WebGL2 is required for spark particles`);this.gl=e,this.canvas.addEventListener(`webglcontextlost`,e=>{e.preventDefault(),this.lost=!0});let t=is(e,Cc,wc,`Spark`),n=e.createBuffer();if(!n)throw U(e,t),Error(`Unable to allocate spark buffer`);this.program=t,this.buffer=n,this.viewportUniform=H(t,`uViewport`),this.fadeUniform=H(t,`uFade`),this.wallCountUniform=H(t,`uWallCount`),this.wallsUniform=H(t,`uWalls[0]`),this.disturbanceUniform=H(t,`uDisturbance`),this.disturbanceRadiusUniform=H(t,`uDisturbanceRadius`),this.electricColorUniform=H(t,`uElectricColor`),this.electricCoronaUniform=H(t,`uElectricCorona`),e.bindBuffer(e.ARRAY_BUFFER,n),cs(e,t,{aStart:{buffer:n,numComponents:2,stride:56,offset:0,divisor:1},aEnd:{buffer:n,numComponents:2,stride:56,offset:8,divisor:1},aMotion:{buffer:n,numComponents:2,stride:56,offset:16,divisor:1},aStyle:{buffer:n,numComponents:4,stride:56,offset:24,divisor:1},aSeed:{buffer:n,numComponents:1,stride:56,offset:40,divisor:1},aColor:{buffer:n,numComponents:3,stride:56,offset:44,divisor:1}})}clear(){if(this.lost||!this.overlayHost||this.canvas.style.display===`none`)return;let e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.viewport(0,0,this.canvas.width,this.canvas.height),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),this.canvas.style.display!==`none`&&(this.canvas.style.display=`none`)}dispose(){this.canvas.remove(),this.overlayHost=null,U(this.gl,this.program),this.gl.deleteBuffer(this.buffer),this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.lost=!0}mountOverlay(e,t,n){this.overlayHost!==e&&(this.canvas.remove(),this.overlayHost=e,this.canvas.dataset.jrOverlay=``,this.canvas.style.position=e.style.position===`absolute`?`absolute`:`fixed`,this.canvas.style.pointerEvents=`none`,this.canvas.style.zIndex=e.style.zIndex||l(`world`),document.body.append(this.canvas)),this.canvas.style.display!==`block`&&(this.canvas.style.display=`block`);let r=e.hasAttribute(`data-jr-overlay`),i=r&&e.style.position===`absolute`,a=i?`absolute`:`fixed`,o=i?e.style.translate:``;this.canvas.style.position!==a&&(this.canvas.style.position=a),this.canvas.style.translate!==o&&(this.canvas.style.translate=o);let s=r?{left:0,top:0}:e.getBoundingClientRect(),c=`${s.left}px`,u=`${s.top}px`,d=`${t.width}px`,f=`${t.height}px`;this.canvas.style.left!==c&&(this.canvas.style.left=c),this.canvas.style.top!==u&&(this.canvas.style.top=u),this.canvas.style.width!==d&&(this.canvas.style.width=d),this.canvas.style.height!==f&&(this.canvas.style.height=f);let p=Math.ceil(t.width*n),m=Math.ceil(t.height*n);(this.canvas.width!==p||this.canvas.height!==m)&&(this.canvas.width=p,this.canvas.height=m)}draw(e,t,n,r,i=1,a,o=[],s,c=xc){if(this.lost||!t.length||n<=0){this.clear();return}let l=t.filter(e=>{let t=e.kind===2?Ec(e.start,e.motion,e.age,e.seed):e.end;return t.x>-64&&t.x<r.width+64&&t.y>-64&&t.y<r.height+64});if(!l.length){this.clear();return}let u=1/0,d=1/0,f=-1/0,p=-1/0;for(let e of l){let t=e.kind===2?Ec(e.start,e.motion,e.age,e.seed):e.end,n=e.kind===2?Ec(e.start,e.motion,Math.max(0,e.age-.045),e.seed):e.start;u=Math.min(u,n.x,t.x),f=Math.max(f,n.x,t.x),d=Math.min(d,n.y,t.y),p=Math.max(p,n.y,t.y)}let m=a?0:Math.floor((u-16)/32)*32,h=a?0:Math.floor((d-16)/32)*32,g=a?r.width:Math.max(32,Math.ceil((f+16-m)/32)*32),_=a?r.height:Math.max(32,Math.ceil((p+16-h)/32)*32),v=Math.min(2,Math.max(1,i)),y=Math.ceil(g*v),b=Math.ceil(_*v);a?this.mountOverlay(a,r,v):(y>this.canvas.width&&(this.canvas.width=Math.ceil(y/256)*256),b>this.canvas.height&&(this.canvas.height=Math.ceil(b/256)*256)),this.data.length<l.length*Sc&&(this.data=new Float32Array(Math.max(l.length*Sc,this.data.length*2)));let x=0;for(let e of l)this.data[x]=(e.start.x-m)*v,this.data[x+1]=(e.start.y-h)*v,this.data[x+2]=(e.end.x-m)*v,this.data[x+3]=(e.end.y-h)*v,this.data[x+4]=e.motion.x*v,this.data[x+5]=e.motion.y*v,this.data[x+6]=e.age,this.data[x+7]=e.life,this.data[x+8]=e.size*v,this.data[x+9]=e.kind,this.data[x+10]=e.seed,this.data[x+11]=e.color?.[0]??1,this.data[x+12]=e.color?.[1]??1,this.data[x+13]=e.color?.[2]??1,x+=Sc;let S=this.gl;performance.now();let C=a?0:this.canvas.height-b;S.viewport(0,C,y,b),a||(S.enable(S.SCISSOR_TEST),S.scissor(0,C,y,b)),S.clearColor(0,0,0,0),S.clear(S.COLOR_BUFFER_BIT),S.useProgram(this.program),S.bindBuffer(S.ARRAY_BUFFER,this.buffer),S.bufferData(S.ARRAY_BUFFER,this.data.subarray(0,x),S.DYNAMIC_DRAW),S.uniform2f(this.viewportUniform,y,b),S.uniform1f(this.fadeUniform,n),S.uniform3f(this.electricColorUniform,...c.color),S.uniform3f(this.electricCoronaUniform,...c.corona),s?(S.uniform4f(this.disturbanceUniform,(s.point.x-m)*v,(s.point.y-h)*v,s.velocity.x*v,s.velocity.y*v),S.uniform1f(this.disturbanceRadiusUniform,s.radius*v)):(S.uniform4f(this.disturbanceUniform,-1e5,-1e5,0,0),S.uniform1f(this.disturbanceRadiusUniform,1));let w=Math.min(32,o.length);for(let e=0;e<w;e++){let t=o[e],n=e*4;this.wallData[n]=(t.x-m)*v,this.wallData[n+1]=(t.y-h)*v,this.wallData[n+2]=(t.x+t.width-m)*v,this.wallData[n+3]=(t.y+t.height-h)*v}S.uniform1i(this.wallCountUniform,w),w&&S.uniform4fv(this.wallsUniform,this.wallData.subarray(0,w*4)),S.enable(S.BLEND),S.blendFuncSeparate(S.SRC_ALPHA,S.ONE_MINUS_SRC_ALPHA,S.ONE,S.ONE_MINUS_SRC_ALPHA),S.drawArraysInstanced(S.TRIANGLES,0,6,l.length),S.disable(S.BLEND),a||S.disable(S.SCISSOR_TEST),!a&&(performance.now(),e.drawImage(this.canvas,0,0,y,b,m,h,g,_))}};function Ec(e,t,n,r){let i=r*Math.PI*2,a=3+r*73.19%1*3.1,o=7.5+r*41.73%1*6.2;return{x:e.x+t.x*n+(Math.sin(a*n+i*2.3)-Math.sin(i*2.3))*(5+r*91.7%1*13)+(Math.sin(o*n-i*3.1)-Math.sin(-i*3.1))*3.5,y:e.y+t.y*n-n*n*(24+r*19.3%1*38)+(Math.cos(a*n+i*1.7)-Math.cos(i*1.7))*4+(Math.sin(o*n+i*4.7)-Math.sin(i*4.7))*2.5}}var Dc=360,q=(e,t,n)=>Math.max(t,Math.min(n,e));function Oc(e){let t=Math.max(1,e.pixelsPerMeter),n=Math.max(0,-_(e.velocity,e.normal))/t,r=x(e.velocity,v(e.normal,_(e.velocity,e.normal))),i=m(r)/t,a=i/Math.max(.001,i+n),o=q((n+(e.wall?.4:0))/1.8,0,1)*q((i-.8)/7,0,1)*q(a/.65,0,1),s=q((n-1.4)/9,0,1)*(1-a*.35);return Math.max(o,s)}function kc(e){let t=t=>{let n=C(-t.y,t.x);return _(n,e.velocity)<0&&(n=v(n,-1)),n},n=t(e.normal),r=t(e.carNormal??v(e.normal,-1)),i=S(n,r),a=m(i);if(a<.001)return n;let o=S(v(i,1/a),v(e.normal,.12));return v(o,1/m(o))}function Ac(e,t){let n=q(e.x,t.x,t.x+t.width),r=q(e.y,t.y,t.y+t.height);return e.x!==n||e.y!==r?C(n,r):[{distance:n-t.x,point:C(t.x,r)},{distance:t.x+t.width-n,point:C(t.x+t.width,r)},{distance:r-t.y,point:C(n,t.y)},{distance:t.y+t.height-r,point:C(n,t.y+t.height)}].reduce((e,t)=>t.distance<e.distance?t:e).point}function jc(e,t,n){if(Math.abs(n.x)>=Math.abs(n.y)){let r=C(n.x<0?-1:1,0);return{point:C(r.x<0?t.x:t.x+t.width,q(e.y,t.y,t.y+t.height)),normal:r}}let r=C(0,n.y<0?-1:1);return{point:C(q(e.x,t.x,t.x+t.width),r.y<0?t.y:t.y+t.height),normal:r}}function Mc(e,t,n){let r=_(e.velocity,t);r<0&&(e.velocity=x(e.velocity,v(t,r*(1+n))))}function Nc(e,t,n){let r=e.point,i=e=>e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height,a=x(r,n),o=0,s=1,c=C(),l=!0;for(let e of[`x`,`y`]){let r=a[e],i=t[e],u=i+(e===`x`?t.width:t.height);if(Math.abs(r)<1e-6){if(n[e]<i||n[e]>u){l=!1;break}continue}let d=(i-n[e])/r,f=(u-n[e])/r,p=Math.min(d,f),m=Math.max(d,f);if(p>o&&(o=p,c=e===`x`?C(r>0?-1:1,0):C(0,r>0?-1:1)),s=Math.min(s,m),o>s){l=!1;break}}if(l&&!i(n)&&o>=0&&o<=1&&o<=s&&m(c)){e.point=S(S(n,v(a,o)),v(c,.75)),Mc(e,c,.38);return}if(!i(r))return;let u=jc(Ac(r,t),t,[{value:Math.abs(n.x-t.x),normal:C(-1,0)},{value:Math.abs(n.x-t.x-t.width),normal:C(1,0)},{value:Math.abs(n.y-t.y),normal:C(0,-1)},{value:Math.abs(n.y-t.y-t.height),normal:C(0,1)}].reduce((e,t)=>t.value<e.value?t:e).normal);e.point=S(u.point,v(u.normal,.75)),Mc(e,u.normal,.38),e.previous={...e.point}}var Pc=class{random;particles=[];walls=[];gpu=null;gpuUnavailable=!1;elapsed=0;lastEmission=-1/0;enabled=!0;electricalPalette=xc;airflow=null;constructor(e=Math.random){this.random=e}captureState(){return u({particles:this.particles,walls:this.walls,gpuUnavailable:this.gpuUnavailable,elapsed:this.elapsed,lastEmission:this.lastEmission,enabled:this.enabled,electricalPalette:this.electricalPalette,airflow:this.airflow})}restoreState(e){this.gpu?.clear();let t=u(e);this.particles=t.particles,this.walls=t.walls,this.gpuUnavailable=t.gpuUnavailable,this.elapsed=t.elapsed,this.lastEmission=t.lastEmission,this.enabled=t.enabled,this.electricalPalette=t.electricalPalette,this.airflow=t.airflow}get count(){return this.particles.length}setEnabled(e){this.enabled=e,e||this.reset()}prepare(){if(!this.enabled||this.gpu||this.gpuUnavailable)return!!this.gpu;try{this.gpu=new Tc}catch{this.gpuUnavailable=!0}return!!this.gpu}reset(){this.particles=[],this.lastEmission=-1/0,this.walls=[],this.airflow=null,this.gpu?.clear()}setElectricalPalette(e){let t=(e,t)=>Number.isFinite(e)?q(e,0,1):t,n=e.color??this.electricalPalette.color,r=e.corona??this.electricalPalette.corona;this.electricalPalette={color:[0,1,2].map(e=>t(n[e],this.electricalPalette.color[e])),corona:[0,1,2].map(e=>t(r[e],this.electricalPalette.corona[e]))}}electric(e,t,n=1){if(!this.enabled||!Number.isFinite(n)||n<=0||!Number.isFinite(e.x)||!Number.isFinite(e.y)||!Number.isFinite(t.x)||!Number.isFinite(t.y))return 0;let r=q(n,.1,3),i=m(t)>.001,a=i?Math.atan2(t.y,t.x):0,o=Math.round(3+r*5);for(let t=0;t<o;t++){let t=i?a+(this.random()-.5)*1.6:this.random()*Math.PI*2,n=C(Math.cos(t),Math.sin(t)),o=S(e,v(n,this.random()*1.6));this.particles.push({point:o,previous:{...o},velocity:v(n,(220+this.random()*460)*Math.sqrt(r)),plane:null,age:0,life:.06+this.random()*.16,size:.65+this.random()*.7,kind:4,seed:this.random()})}return this.trim(),o}pickup(e,t,n,r,i,a=1,o){if(!this.enabled||![e.x,e.y,t.x,t.y,n.x,n.y,i,a].every(Number.isFinite)||i<=0||a<=0||o!==void 0&&!Number.isFinite(o)||r.some(e=>!Number.isFinite(e)||e<0||e>1))return 0;let s=q(a,.15,1.5),c=i/28,l=q(c,.8,3),u=m(n),d=u>.001?v(n,1/u):C(),f=Math.atan2(d.y,d.x),p=m(t),h=this.random()*Math.PI*2,g=[...r],_=o===void 0?Math.round(6+s*4):q(Math.floor(o),0,20);for(let t=0;t<_;t++){let n=h+f+(t+(this.random()-.5)*.5)/_*Math.PI*2,r=C(Math.cos(n),Math.sin(n)),i=S(e,v(r,Math.sqrt(this.random())*1.5*c)),a=f+(this.random()-.5)*.2,o=p*(.16+this.random()*.08);this.particles.push({point:i,previous:{...i},velocity:C(Math.cos(a)*o,Math.sin(a)*o),plane:null,age:0,life:.4+this.random()*.2,size:(.7+this.random()*.5)*l,kind:5,seed:this.random(),color:g})}return this.trim(),_}disturb(e,t,n=90){this.airflow={point:{...e},velocity:{...t},radius:n}}dispose(){this.gpu?.dispose(),this.gpu=null}emit(e){if(!this.enabled||this.elapsed-this.lastEmission<.045)return 0;let t=Oc(e);if(t<=0)return 0;this.lastEmission=this.elapsed;let n=kc(e),r=x(e.velocity,v(e.normal,_(e.velocity,e.normal))),i=Math.max(0,-_(e.velocity,e.normal)),a=i/Math.max(.001,i+m(r)),o=S(v(n,1-a),v(e.normal,a)),s=m(o),c=s>.001?v(o,1/s):e.normal,l=Math.round(24+80*Math.sqrt(t)),u=m(e.velocity)/Math.max(1,e.pixelsPerMeter),d=e.wall?jc(e.point,e.wall,e.normal):null,f=d?.point??e.point,p=d?.normal??e.normal;for(let n=0;n<l;n++){let n=(this.random()-.5)*(.4+t*.45+a*1.5),i=Math.cos(n),o=Math.sin(n),s=C(c.x*i-c.y*o,c.x*o+c.y*i),l=(140+Math.min(420,u*30))*(.45+this.random()*1.15),d=S(v(s,l),v(r,.08)),m=e.wall?1.35+this.random()*.25:.35+this.random()*.3,h=S(f,v(p,m));this.particles.push({point:h,previous:{...h},velocity:d,plane:{origin:f,normal:p},age:0,life:.18+this.random()*.34,size:.85+this.random()*1.6,kind:0,seed:this.random()})}let h=S(f,v(p,e.wall?1.5:.8));return this.particles.push({point:h,previous:{...h},velocity:C(),plane:null,age:0,life:.18,size:5.5+t*4,kind:3,seed:this.random()}),this.trim(),l+1}emitBulletImpact(e,t){if(!this.enabled)return;let n=m(t);if(n<.001)return;let r=v(t,-1/n),i=S(e,v(r,1.4));for(let t=0;t<40;t++){let n=(this.random()-.5)*2.7,a=C(r.x*Math.cos(n)-r.y*Math.sin(n),r.x*Math.sin(n)+r.y*Math.cos(n)),o=S(i,v(a,this.random()*1.5));this.particles.push({point:o,previous:{...o},velocity:v(a,t<12?320+this.random()*300:150+this.random()*330),plane:{origin:e,normal:r},age:0,life:.16+this.random()*.24,size:.7+this.random()*1.2,kind:0,seed:this.random()})}this.particles.push({point:i,previous:{...i},velocity:C(),plane:null,age:0,life:.15,size:8,kind:3,seed:this.random()}),this.trim()}emitExplosion(e,t,n,r=1){if(!this.enabled)return 0;let i=Math.max(1,n),a=q(r,.5,2),o=Math.atan2(t.y,t.x),s=Math.round(32+20*Math.sqrt(a));for(let t=0;t<s;t++){let n=o+t*Math.PI*(3-Math.sqrt(5))+(this.random()-.5)*.3,r=C(Math.cos(n),Math.sin(n)),s=i*(5+this.random()*9)*Math.sqrt(a),c=S(e,v(r,i*.03));this.particles.push({point:c,previous:{...c},velocity:v(r,s),plane:null,age:0,life:.24+this.random()*.36,size:1+this.random()*1.1,kind:1,seed:this.random()})}return this.trim(),s}emitFire(e,t){if(!this.enabled||this.random()>=Math.min(1,t*15))return;let n=C(e.x+e.width/2,e.y+e.height/2),r=Math.cos(e.angle??0),i=Math.sin(e.angle??0);for(let t=0;t<12;t++){let t=e.fixedRadius??0,a=this.random()*Math.PI*2,o=Math.sqrt(this.random())*t,s=t>0?S(e.origin,C(Math.cos(a)*o,Math.sin(a)*o)):C(e.x+this.random()*e.width,e.y+this.random()*e.height),c=s.x-n.x,l=s.y-n.y,u=c*r+l*i,d=-c*i+l*r,f=Math.floor((u/e.width+.5)*e.pixelWidth),p=Math.floor((d/e.height+.5)*e.pixelHeight);if(f<0||p<0||f>=e.pixelWidth||p>=e.pixelHeight||(e.alpha[p*e.pixelWidth+f]??0)<32)continue;let m=C(n.x+u*r-d*i,n.y+u*i+d*r),h=(e.age-(t>0?0:Math.hypot(m.x-e.origin.x,m.y-e.origin.y)/e.farthest*e.spreadSeconds))/e.burnSeconds;if(!(h<=0||h>=.82)){this.addEmber(m);return}}}emitFireAt(e,t,n,r=10){if(!this.enabled||this.random()>=Math.min(1,n*r))return;let i=this.random()*Math.PI*2,a=Math.sqrt(this.random())*t;this.addEmber(S(e,C(Math.cos(i)*a,Math.sin(i)*a)))}addEmber(e){this.particles.push({point:e,previous:{...e},velocity:C((this.random()-.5)*76,-35-this.random()*100),plane:null,age:0,life:.5+this.random()*1.25,size:.55+this.random()**2*1.25,kind:2,seed:this.random()}),this.trim()}trim(){this.particles.length>Dc&&this.particles.splice(0,this.particles.length-Dc)}step(e,t={walls:[]}){if(this.elapsed+=e,this.airflow){let t=Math.exp(-e*5.5);this.airflow.velocity=v(this.airflow.velocity,t),m(this.airflow.velocity)<1&&(this.airflow=null)}if(this.walls=t.walls,!this.particles.length)return;let n=Math.min(e,.05);for(let e of this.particles)if(e.age+=n,e.kind!==2&&e.kind!==3){e.previous={...e.point};for(let r=0;r<2;r++){let r={...e.point},i=e.kind===4,a=e.kind===5,o=i?8+e.seed*8:a?.7:3.2+e.seed*6.3;if(e.velocity=v(e.velocity,Math.exp(-o*n/2)),i){let t=(e.seed-.5)*9*n*.5,r=Math.cos(t),i=Math.sin(t);e.velocity=C(e.velocity.x*r-e.velocity.y*i,e.velocity.x*i+e.velocity.y*r)}else a||(e.velocity.y+=(38+e.seed*84)*n*.5);if(e.point=S(e.point,v(e.velocity,n/2)),e.plane){let t=_(x(e.point,e.plane.origin),e.plane.normal);t<0&&(e.point=S(e.point,v(e.plane.normal,-t+.4)),Mc(e,e.plane.normal,.55))}for(let n of t.walls)Nc(e,n,r);if(!a&&t.car&&ie(t.car.mask,t.car.shape,e.point)){let n=re(t.car.mask,t.car.shape,e.point);for(let r=0;r<16&&ie(t.car.mask,t.car.shape,e.point);r++)e.point=S(e.point,v(n,1.2));Mc(e,n,.48)}}}this.particles=this.particles.filter(e=>e.age<e.life)}draw(e,t,n,r,i=1,a){if(!this.enabled||!this.particles.length||n<=0){this.gpu?.clear();return}if(this.prepare(),!this.gpu)return;let o=this.particles.map(e=>{let n=t(e.point),r=t(S(e.point,e.velocity)),i=x(r,n),a=e.kind<2||e.kind===4,o=a?t(e.previous):n;if(a){let r=x(n,o),a=m(r),s=e.kind===4?Math.min(20,m(i)*.04):Math.min(18,m(i)*(e.kind===1?.032:.038));if(a>.001&&a<s?(o.x=n.x-r.x/a*s,o.y=n.y-r.y/a*s):a<1&&(o.x-=i.x*.02,o.y-=i.y*.02),e.plane){let n=t(e.plane.origin),r=x(t(S(e.plane.origin,e.plane.normal)),n),i=_(x(o,n),r)/Math.max(1e-6,m(r));if(i<.7){let e=v(r,1/Math.max(1e-6,m(r)));o.x+=e.x*(.7-i),o.y+=e.y*(.7-i)}}}return{start:o,end:n,motion:i,age:e.age,life:e.life,size:e.size,kind:e.kind,seed:e.seed,color:e.color}}),s=[];if(a)for(let e of this.walls){let n=t({x:e.x,y:e.y}),i=t({x:e.x+e.width,y:e.y+e.height}),a=Math.min(n.x,i.x),o=Math.min(n.y,i.y),c=Math.abs(n.x-i.x),l=Math.abs(n.y-i.y);if(!(a>r.width||o>r.height||a+c<0||o+l<0)&&(s.push({x:a,y:o,width:c,height:l}),s.length===32))break}let c=this.airflow?{point:t(this.airflow.point),velocity:x(t(S(this.airflow.point,this.airflow.velocity)),t(this.airflow.point)),radius:m(x(t(S(this.airflow.point,C(this.airflow.radius,0))),t(this.airflow.point)))}:void 0;this.gpu.draw(e,o,n,r,i,a,s,c,this.electricalPalette)}},Fc=[[0,0],[60,120],[120,180],[240,240],[300,300],[360,360]];function Ic(e,t=!1){for(let n=1;n<Fc.length;n++){let r=Fc[n-1],i=Fc[n],a=t?r[1]:r[0],o=t?i[1]:i[0];if(e<=o)return(t?r[0]:r[1])+(e-a)/(o-a)*((t?i[0]:i[1])-(t?r[0]:r[1]))}return e}function Lc(e){let[t,n,r]=e.map(e=>e/255),i=Math.max(t,n,r),a=Math.min(t,n,r),o=i-a,s=(i+a)*.5,c=o===0?0:o/(1-Math.abs(2*s-1)),l=o===0?0:i===t?(n-r)/o%6:i===n?(r-t)/o+2:(t-n)/o+4;return l=Ic((l*60+360)%360)*Math.PI/180,[.5+.5*Math.cos(l)*c,.5+.5*Math.sin(l)*c,c,s]}function Rc(e){let t=e[0]*2-1,n=e[1]*2-1,r=Math.max(0,Math.min(1,e[2])),i=Math.max(0,Math.min(1,Math.hypot(t,n)/Math.max(r,1e-6))),a=r*Math.min(1,Math.sqrt(i*2)),o=Math.max(0,Math.min(1,e[3]))*(r>1e-6?.65+.35*i:1),s=Ic((Math.atan2(n,t)*180/Math.PI+360)%360,!0),c=(1-Math.abs(2*o-1))*a,l=c*(1-Math.abs(s/60%2-1)),u=Math.floor(s/60)%6,d=0,f=0,p=0;switch(u){case 0:d=c,f=l;break;case 1:d=l,f=c;break;case 2:f=c,p=l;break;case 3:f=l,p=c;break;case 4:d=l,p=c;break;default:d=c,p=l}let m=o-c*.5;return[Math.max(0,Math.min(255,(d+m)*255)),Math.max(0,Math.min(255,(f+m)*255)),Math.max(0,Math.min(255,(p+m)*255))]}function zc(e){return e.radius*(1.8+e.angularity*1.7)}function Bc(e,t,n){let{radius:r,angularity:o,seed:s}=n;e.save(),e.translate(n.point.x,n.point.y),e.rotate(n.angle),e.fillStyle=`rgb(${n.color.join(` `)})`;let c=a(t)===`water`;if(e.globalAlpha=n.opacity*(c?Math.min(1,Math.max(0,(.65-n.age)/.25)):1),c){e.beginPath(),e.arc(0,0,r,0,Math.PI*2),e.fill(),e.restore();return}if(r<.45){e.beginPath(),e.ellipse(0,0,r*(1+o*1.7),r*(.5+s*.45),0,0,Math.PI*2),e.fill(),e.restore();return}let l=i(t),u=Math.min(1.6,o*(.5+l.impact)),d=s*Math.PI*2,f=5+Math.floor(s*3),p=r*(1+u*.18);e.globalAlpha*=.72+l.coverage*.28;let m=e=>{let t=e/18*Math.PI*2,n=Math.max(0,Math.sin(t*f+d))**6*u*.6,r=p*(.86+.12*Math.sin(t*3+d)+n);return{x:Math.cos(t)*r*(1+u*.3),y:Math.sin(t)*r}},h=m(0),g=m(17);e.beginPath(),e.moveTo((h.x+g.x)/2,(h.y+g.y)/2);for(let t=0;t<18;t++){let n=m(t),r=m((t+1)%18);e.quadraticCurveTo(n.x,n.y,(n.x+r.x)/2,(n.y+r.y)/2)}if(e.closePath(),e.fill(),r>.55&&u>.25){e.strokeStyle=e.fillStyle,e.lineWidth=Math.max(.12,r*.15);for(let t=0;t<2;t++){let n=d+t*2.4;e.beginPath(),e.moveTo(Math.cos(n)*p*.7,Math.sin(n)*p*.7),e.lineTo(Math.cos(n)*p*(1.4+u),Math.sin(n)*p*(1.4+u)),e.stroke()}}e.restore()}function Vc(e){let t=s[e],n=e===`paint`?null:r(e),i=Math.max(t?.gloss??0,(n?.surface?.clearcoat??0)*.5),a=Math.max(t?.relief??0,(n?.surface?.microRelief??0)*.7),o=Math.max(t?.film??0,n?.iridescence??0),c=Math.max(t?.grain??0,n?.sediment??0),l=n?.atmosphere?.emission??0;return{gloss:i,relief:a,film:o,grain:c,emission:l,emissionColor:n?.atmosphere?.emissionColor??[0,0,0],shaded:i+a+o+c+l>0}}function Hc(e,t,n,r,i,a){if(!e.shaded)return t;let o=Math.max(0,-i*.55-a*.8)*e.gloss*82,s=Math.sin(n*.16+r*.08)*e.relief*8,c=Math.sin(n*.095+r*.13+i*3)*e.film*27,l=Math.sin(n*127.1+r*311.7)*43758.5453%1*e.grain*12,u=o+s+l,d=e.emission*.22,f=(t,n,r)=>Math.max(0,Math.min(255,t+u+r+e.emissionColor[n]*d));return[f(t[0],0,c),f(t[1],1,-c*.65),f(t[2],2,c*.8)]}var Uc=2;function Wc(e){if(!e)return null;let t=document.createElement(`canvas`);return t.width=e.width,t.height=e.height,t.getContext(`2d`)?.drawImage(e,0,0),t}var J=(e,t,n)=>Math.max(t,Math.min(n,e)),Gc=new Uint8Array(new Uint32Array([1]).buffer)[0]===1,Y=(e,t,n)=>e+(t-e)*n,Kc=[[1,0],[-1,0],[0,1],[0,-1]],qc=[[.7,.7],[-.7,.7],[.7,-.7],[-.7,-.7]],Jc=class{kind;width;height;profile;canvas=document.createElement(`canvas`);splatterCanvas=null;splatterBounds=null;drawnDrops=0;transientSpray;transientDirty=!1;material;authored;deposited;pigment;colorPixels;basePixels;outline;spring;velocity;drops=[];splatterRemainder=0;burnDecay=new Float32Array;revision=0;pulled=!1;maxOutline=0;presented=-1;active=null;activeCells=new Set;outlineCells=new Set;wetBounds=null;renderedBounds=null;dirtyBounds=null;fullDirty=!0;color;appearance;cellSizePx=1;listeners=new Set;constructor(e,n,r,i,o){this.kind=e,this.width=n,this.height=r,this.profile=o,this.transientSpray=a(e)===`water`,this.color=[...i],this.appearance=Vc(e);let s=t[e];this.material={thickness:s.thickness,deformation:o?.deformation??s.deformation,alpha:o?.opacity??s.alpha};let c=n*r;this.authored=new Uint8Array(c),this.deposited=new Uint8Array(c),this.pigment=new Float32Array(c*4),this.colorPixels=new Uint8Array(c*3),this.basePixels=Gc&&!this.appearance.shaded?new Uint32Array(c):null,this.outline=new Float32Array(c*2),this.spring=new Float32Array(c*2),this.velocity=new Float32Array(c*2),this.canvas.width=n,this.canvas.height=r}get shapeRevision(){return this.revision}get displaced(){return this.pulled||this.active!==null}get moving(){return this.active!==null}get hasSplatter(){return this.drops.length>0||this.splatterCanvas!==null}get hasDeposits(){return this.deposited.some(e=>e>0)}get managedBytes(){return this.authored.byteLength+this.deposited.byteLength+this.pigment.byteLength+this.colorPixels.byteLength+(this.basePixels?.byteLength??0)+this.outline.byteLength+this.spring.byteLength+this.velocity.byteLength+this.canvas.width*this.canvas.height*4+(this.splatterCanvas?this.splatterCanvas.width*this.splatterCanvas.height*4:0)}setCellSize(e){this.cellSizePx=Math.max(.01,e)}configure(e,n){this.color=[...e],this.material.deformation=n?.deformation??t[this.kind].deformation;let r=n?.opacity??t[this.kind].alpha;r!==this.material.alpha&&(this.material.alpha=r,this.rebuildBasePixels()),this.changed()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}changed(e){e?this.fullDirty||(this.dirtyBounds=this.dirtyBounds?{left:Math.min(this.dirtyBounds.left,e.left),top:Math.min(this.dirtyBounds.top,e.top),right:Math.max(this.dirtyBounds.right,e.right),bottom:Math.max(this.dirtyBounds.bottom,e.bottom)}:{...e}):(this.fullDirty=!0,this.dirtyBounds=null),this.revision++;for(let e of this.listeners)e()}alphaAt(e){return Math.max(this.authored[e],this.deposited[e])}refreshBasePixel(e){if(!this.basePixels)return;let t=this.alphaAt(e),n=e*3;this.basePixels[e]=Math.round(t*this.material.alpha)<<24|this.colorPixels[n+2]<<16|this.colorPixels[n+1]<<8|this.colorPixels[n]}rebuildBasePixels(){if(this.basePixels)for(let e=0;e<this.width*this.height;e++)this.refreshBasePixel(e)}wetAt(e,t){let n=Math.floor(e),r=Math.floor(t);return n>=0&&r>=0&&n<this.width&&r<this.height&&this.alphaAt(r*this.width+n)>=24}includeWetBounds(e){this.wetBounds=this.wetBounds?{left:Math.min(this.wetBounds.left,e.left),top:Math.min(this.wetBounds.top,e.top),right:Math.max(this.wetBounds.right,e.right),bottom:Math.max(this.wetBounds.bottom,e.bottom)}:e}rebuildWetBounds(){let e=this.width,t=this.height,n=-1,r=-1;for(let i=0;i<this.height;i++)for(let a=0;a<this.width;a++)this.alphaAt(i*this.width+a)&&(e=Math.min(e,a),t=Math.min(t,i),n=Math.max(n,a),r=Math.max(r,i));this.wetBounds=n>=e?{left:e,top:t,right:n,bottom:r}:null}componentAt(e,t,n,r){let i=J(t.x-.5,0,this.width-1),a=J(t.y-.5,0,this.height-1),o=Math.floor(i),s=Math.floor(a),c=Math.min(this.width-1,o+1),l=Math.min(this.height-1,s+1),u=i-o,d=a-s,f=e[(s*this.width+o)*r+n],p=e[(s*this.width+c)*r+n],m=e[(l*this.width+o)*r+n],h=e[(l*this.width+c)*r+n];return Y(Y(f,p,u),Y(m,h,u),d)}offsetAt(e,t=!0){return{x:this.componentAt(this.spring,e,0,2)+(t?this.componentAt(this.outline,e,0,2):0),y:this.componentAt(this.spring,e,1,2)+(t?this.componentAt(this.outline,e,1,2):0)}}sourcePoint(e){let t=this.offsetAt(e);return{x:e.x-t.x,y:e.y-t.y}}rawCoverage(e){return this.rawCoverageXY(e.x,e.y)}rawCoverageXY(e,t){if(e<0||t<0||e>=this.width||t>=this.height)return 0;let n=J(e-.5,0,this.width-1),r=J(t-.5,0,this.height-1),i=Math.floor(n),a=Math.floor(r),o=Math.min(this.width-1,i+1),s=Math.min(this.height-1,a+1),c=n-i,l=r-a;return Y(Y(this.alphaAt(a*this.width+i),this.alphaAt(a*this.width+o),c),Y(this.alphaAt(s*this.width+i),this.alphaAt(s*this.width+o),c),l)/255}densityAt(e){return e.x<0||e.y<0||e.x>=this.width||e.y>=this.height?0:this.rawCoverage(this.sourcePoint(e))}colorAt(e){let t=this.sourcePoint(e),n=J(Math.floor(t.y),0,this.height-1)*this.width+J(Math.floor(t.x),0,this.width-1);return this.alphaAt(n)?[this.colorPixels[n*3],this.colorPixels[n*3+1],this.colorPixels[n*3+2]]:this.color}captureFuel(){let e=new Float32Array(this.width*this.height);for(let t=0;t<this.height;t++)for(let n=0;n<this.width;n++)e[t*this.width+n]=this.densityAt({x:n+.5,y:t+.5});return e}inspectState(){let e=this.captureFuel(),t=0,n=1/0,r=0;for(let i of e)t+=i,n=Math.min(n,i),r=Math.max(r,i);return{volume:t,minimum:n,maximum:r,finite:Number.isFinite(t)}}setPigment(e,t,n,r=Lc(t)){let i=e*4;if(n>=1||!this.alphaAt(e))for(let e=0;e<4;e++)this.pigment[i+e]=r[e];else for(let e=0;e<4;e++)this.pigment[i+e]=Y(this.pigment[i+e],r[e],n);let a=Rc([this.pigment[i],this.pigment[i+1],this.pigment[i+2],this.pigment[i+3]]);for(let t=0;t<3;t++)this.colorPixels[e*3+t]=Math.round(a[t]);this.refreshBasePixel(e)}seedMask(e,t,n,r=this.color){if(e.length!==this.width*this.height)throw RangeError(`Liquid seed must match the field resolution`);this.authored.set(e);let i=Lc(r),a=this.width,o=this.height,s=-1,c=-1;for(let t=0;t<e.length;t++){if(e[t]&&!this.deposited[t]&&(this.pigment.set(i,t*4),this.colorPixels.set(r,t*3)),this.refreshBasePixel(t),!e[t]&&!this.deposited[t])continue;let n=t%this.width,l=(t-n)/this.width;n<a&&(a=n),n>s&&(s=n),l<o&&(o=l),l>c&&(c=l)}this.wetBounds=s>=a?{left:a,top:o,right:s,bottom:c}:null,this.changed()}removeSeed(){this.authored.fill(0),this.rebuildBasePixels(),this.rebuildWetBounds(),this.changed()}pour(e,t,n,r,i,a=this.color,o=n,s=r){if(!(e>0))return;n=this.sourcePoint(n),o=this.sourcePoint(o);let c=Math.max(0,Math.floor(Math.min(o.x-s,n.x-r)-2)),l=Math.min(this.width-1,Math.ceil(Math.max(o.x+s,n.x+r)+2)),u=Math.max(0,Math.floor(Math.min(o.y-s,n.y-r)-2)),d=Math.min(this.height-1,Math.ceil(Math.max(o.y+s,n.y+r)+2)),f=n.x-o.x,p=n.y-o.y,m=Math.max(1e-6,f*f+p*p),h=Lc(a),g=!1;for(let t=u;t<=d;t++)for(let i=c;i<=l;i++){let c=i+.5,l=t+.5,u=J(((c-o.x)*f+(l-o.y)*p)/m,0,1),d=Y(o.x,n.x,u),_=Y(o.y,n.y,u),v=Y(s,r,u),y=Math.hypot(c-d,l-_),b=Math.round(J(v+.5-y,0,1)*255);if(!b)continue;let x=t*this.width+i,S=this.alphaAt(x),C=this.colorPixels[x*3]===a[0]&&this.colorPixels[x*3+1]===a[1]&&this.colorPixels[x*3+2]===a[2];b<=this.deposited[x]&&S&&C||(!S||C?(this.pigment.set(h,x*4),this.colorPixels.set(a,x*3)):this.setPigment(x,a,J(e*b/(S*2),0,1),h),this.deposited[x]=Math.max(this.deposited[x],b),this.refreshBasePixel(x),g=!0)}g&&(this.includeWetBounds({left:c,top:u,right:l,bottom:d}),this.changed())}transferPigment(e,t,n,r,i){if(!(i>0))return;let a=Lc(r),o=this.width,s=this.height,c=-1,l=-1;if(this.eachContactPixel(e,t,n,(e,t,n,u)=>{if(!this.alphaAt(e))return;this.setPigment(e,r,J(t*i,0,1),a);let d=Math.floor(n),f=Math.floor(u);o=Math.min(o,d),s=Math.min(s,f),c=Math.max(c,d),l=Math.max(l,f)},Math.max(2,n*1.1)),c>=o){let e=Math.ceil(this.maxOutline+8/this.cellSizePx)+2;this.changed({left:o-e,top:s-e,right:c+e,bottom:l+e})}}eachContactPixel(e,t,n,r,i=Math.max(2,n*1.8,(24*this.material.deformation+2)/this.cellSizePx)){let a=this.wetBounds,o=i+(this.pulled||this.active?8/this.cellSizePx:0),s=Math.max(0,Math.floor(Math.min(e.x,t.x)-i),a?Math.floor(a.left-o):0),c=Math.min(this.width-1,Math.ceil(Math.max(e.x,t.x)+i),a?Math.ceil(a.right+o):this.width-1),l=Math.max(0,Math.floor(Math.min(e.y,t.y)-i),a?Math.floor(a.top-o):0),u=Math.min(this.height-1,Math.ceil(Math.max(e.y,t.y)+i),a?Math.ceil(a.bottom+o):this.height-1),d=t.x-e.x,f=t.y-e.y,p=Math.max(1e-6,d*d+f*f),m=i*i;for(let t=l;t<=u;t++)for(let n=s;n<=c;n++){let a=n+.5,o=t+.5,s=J(((a-e.x)*d+(o-e.y)*f)/p,0,1),c=a-e.x-d*s,l=o-e.y-f*s,u=c*c+l*l;if(u>=m)continue;let h=1-Math.sqrt(u)/i;r(t*this.width+n,h*h,a,o)}return{left:s,top:l,right:c,bottom:u}}drag(e,t,n,r=5.5,i=0){if(this.material.deformation===0)return;let a=t.x-e.x,o=t.y-e.y;if(Math.hypot(a,o)<.5)return;let s=Math.max(2,r*1.8,(24*this.material.deformation+2)/this.cellSizePx),c=Math.max(2,r*1.8),l=Math.hypot(a,o),u=a/l,d=o/l,f=Math.max(2,r*1.25),p=!1,m=this.width,h=this.height,g=-1,_=-1,v=this.eachContactPixel(e,t,r,(e,t,n,r)=>{let i=Math.floor(n),c=Math.floor(r);if(!this.wetAt(n-u*f,r-d*f)||this.wetAt(n+u*f,r+d*f))return;let l=this.alphaAt(e)>=24,v=0;for(let[e,t]of Kc)this.wetAt(n+e*s*.35,r+t*s*.35)===l?this.wetAt(n+e*s*.7,r+t*s*.7)===l?this.wetAt(n+e*s,r+t*s)!==l&&(v=Math.max(v,.12)):v=Math.max(v,.3):v=Math.max(v,.65);if(!l&&v===0){for(let[e,t]of qc)if(this.wetAt(n+e*s,r+t*s)){v=.12;break}}if(!l&&v===0)return;let y=this.material.deformation/(.65+this.material.thickness*.7),b=e*2;if(this.velocity[b]=J(this.velocity[b]+a*t*18*y,-90,90),this.velocity[b+1]=J(this.velocity[b+1]+o*t*18*y,-90,90),this.activeCells.add(e),v>0){let n=24*this.material.deformation/this.cellSizePx;this.outline[b]=J(this.outline[b]+a*t*y*v*.48,-n,n),this.outline[b+1]=J(this.outline[b+1]+o*t*y*v*.48,-n,n),this.maxOutline=Math.max(this.maxOutline,Math.abs(this.outline[b]),Math.abs(this.outline[b+1])),this.pulled=!0,this.outlineCells.add(e)}p=!0,m=Math.min(m,i),h=Math.min(h,c),g=Math.max(g,i),_=Math.max(_,c)},c);p&&(this.active=this.active?{left:Math.min(v.left,this.active.left),top:Math.min(v.top,this.active.top),right:Math.max(v.right,this.active.right),bottom:Math.max(v.bottom,this.active.bottom)}:v,this.changed({left:m,top:h,right:g,bottom:_}))}step(e,t=0,n=[],r,i=e){let a=J(e,0,1/30);if(this.transientSpray&&this.drops.length){for(let e of this.drops)e.age+=a;this.drops=this.drops.filter(e=>e.age<.65),this.drops.length||(this.splatterCanvas=null,this.splatterBounds=null),this.drawnDrops=0,this.transientDirty=!0}if(this.activeCells.size){let e=Math.exp(-(7+this.material.thickness*5)*a),t=this.width,n=this.height,r=-1,i=-1;for(let o of this.activeCells){let s=o%this.width,c=Math.floor(o/this.width),l=0;for(let t=0;t<2;t++){let n=o*2+t,r=this.spring[n],i=(this.velocity[n]-r*95*a)*e;this.velocity[n]=i,this.spring[n]=J(r+i*a,-8/this.cellSizePx,8/this.cellSizePx),l=Math.max(l,Math.abs(this.spring[n]),Math.abs(i)*.08)}if(t=Math.min(t,s),n=Math.min(n,c),r=Math.max(r,s),i=Math.max(i,c),l<.012){let e=o*2;this.spring[e]=this.spring[e+1]=0,this.velocity[e]=this.velocity[e+1]=0,this.activeCells.delete(o)}}r>=t&&this.changed({left:t,top:n,right:r,bottom:i}),this.active=this.activeCells.size?{left:t,top:n,right:r,bottom:i}:null}if(t<=0&&!r)return;let o=this.wetBounds;if(!o)return;let s=r?.size??0;if(r){this.burnDecay.length!==r.rates.length&&(this.burnDecay=new Float32Array(r.rates.length));for(let e=0;e<r.rates.length;e++){let n=t+r.rates[e];this.burnDecay[e]=n>0?Math.exp(-n*i):1}}let c=t>0?Math.exp(-t*i):1,l=this.width===s*4&&this.height===s*4,u=this.width,d=this.height,f=-1,p=-1;for(let e=Math.max(0,o.top);e<=Math.min(this.height-1,o.bottom);e++){let t=r?(l?e>>2:Math.floor(e*s/this.height))*s:0;for(let n=Math.max(0,o.left);n<=Math.min(this.width-1,o.right);n++){let i=e*this.width+n;if(!this.authored[i]&&!this.deposited[i])continue;let a=i*2,o=c;if(r){let r=this.spring[a]+this.outline[a],i=this.spring[a+1]+this.outline[a+1],c=r===0&&i===0?t+(l?n>>2:Math.floor(n*s/this.width)):J(Math.floor((e+i)*s/this.height),0,s-1)*s+J(Math.floor((n+r)*s/this.width),0,s-1);o=this.burnDecay[c]}if(o>=1)continue;let m=Math.round(this.authored[i]*o),h=Math.round(this.deposited[i]*o);(m!==this.authored[i]||h!==this.deposited[i])&&(this.authored[i]=m,this.deposited[i]=h,this.refreshBasePixel(i),u=Math.min(u,n),d=Math.min(d,e),f=Math.max(f,n),p=Math.max(p,e))}}f>=u&&this.changed({left:u,top:d,right:f,bottom:p})}mayIntersect(e,t,n=1){let r=Math.max(1,Math.ceil(Math.hypot(t.x-e.x,t.y-e.y)/Math.max(1,n)));for(let n=0;n<=r;n++){let i=n/r,a={x:Y(e.x,t.x,i),y:Y(e.y,t.y,i)};if(this.densityAt(a)>.02)return!0}return!1}spray(e,t,n,r,i=1,a=this.colorAt(e)){if(r<=0)return;let o=this.splatterRemainder+r*(9+(1-this.material.thickness)*7),s=Math.min(48,Math.floor(o));this.splatterRemainder=o-Math.floor(o);for(let r of ce(e,t,n,s,i,this.material.thickness))this.drops.push({point:{x:r.x,y:r.y},radius:Math.max(.5,r.radius),color:a,opacity:this.material.alpha*r.opacity,angle:Math.atan2(t.y,t.x),angularity:r.angularity,seed:Math.random(),age:0});if(this.drops.length>1200){let e=this.drops.length-1200;this.drops.splice(0,e),this.drawnDrops=Math.max(0,this.drawnDrops-e)}}grow(e){if(e<=1)return this.width;let t=this.width,n=Math.ceil(this.width*e/2)*2,r=Math.ceil(this.height*e/2)*2,i=Math.floor((n-this.width)/2),a=Math.floor((r-this.height)/2),o=(e,t,r)=>{for(let o=0;o<this.height;o++)r.set(e.subarray(o*this.width*t,(o+1)*this.width*t),((o+a)*n+i)*t);return r};this.authored=o(this.authored,1,new Uint8Array(n*r)),this.deposited=o(this.deposited,1,new Uint8Array(n*r)),this.pigment=o(this.pigment,4,new Float32Array(n*r*4)),this.colorPixels=o(this.colorPixels,3,new Uint8Array(n*r*3)),this.basePixels&&=o(this.basePixels,1,new Uint32Array(n*r)),this.outline=o(this.outline,2,new Float32Array(n*r*2)),this.spring=o(this.spring,2,new Float32Array(n*r*2)),this.velocity=o(this.velocity,2,new Float32Array(n*r*2)),this.activeCells=new Set([...this.activeCells].map(e=>(Math.floor(e/t)+a)*n+e%t+i)),this.outlineCells=new Set([...this.outlineCells].map(e=>(Math.floor(e/t)+a)*n+e%t+i));for(let e of this.drops)e.point.x+=i,e.point.y+=a;return this.splatterBounds&&(this.splatterBounds.left+=i,this.splatterBounds.right+=i,this.splatterBounds.top+=a,this.splatterBounds.bottom+=a),this.active&&(this.active.left+=i,this.active.right+=i,this.active.top+=a,this.active.bottom+=a),this.wetBounds&&(this.wetBounds.left+=i,this.wetBounds.right+=i,this.wetBounds.top+=a,this.wetBounds.bottom+=a),this.width=n,this.height=r,this.canvas.width=n,this.canvas.height=r,this.renderedBounds=null,this.changed(),n}setColor(e){this.color=[...e],this.changed()}reset(){this.authored.fill(0),this.deposited.fill(0),this.outline.fill(0),this.spring.fill(0),this.velocity.fill(0),this.drops=[],this.splatterRemainder=0,this.splatterCanvas=null,this.splatterBounds=null,this.drawnDrops=0,this.transientDirty=!1,this.active=null,this.activeCells.clear(),this.outlineCells.clear(),this.basePixels?.fill(0),this.wetBounds=null,this.pulled=!1,this.maxOutline=0,this.changed()}captureState(){let e=Wc(this.splatterCanvas);return{width:this.width,height:this.height,cellSizePx:this.cellSizePx,active:this.active?{...this.active}:null,pulled:this.pulled,authored:this.authored.slice(),deposited:this.deposited.slice(),pigment:this.pigment.slice(),colorPixels:this.colorPixels.slice(),outline:this.outline.slice(),spring:this.spring.slice(),velocity:this.velocity.slice(),drops:this.drops.map(e=>({...e,point:{...e.point}})),splatterRemainder:this.splatterRemainder,splatterBounds:this.splatterBounds?{...this.splatterBounds}:null,splatterImage:e,drawnDrops:this.drawnDrops,color:[...this.color],dispose(){e&&(e.width=0,e.height=0)}}}restoreState(e){this.width=e.width,this.height=e.height,this.canvas.width=e.width,this.canvas.height=e.height,this.cellSizePx=e.cellSizePx,this.active=e.active?{...e.active}:null,this.pulled=e.pulled,this.authored=e.authored.slice(),this.deposited=e.deposited.slice(),this.pigment=e.pigment.slice(),this.colorPixels=e.colorPixels.slice(),this.basePixels=Gc&&!this.appearance.shaded?new Uint32Array(this.width*this.height):null,this.outline=e.outline.slice(),this.outlineCells=new Set;for(let e=0;e<this.width*this.height;e++)(this.outline[e*2]||this.outline[e*2+1])&&this.outlineCells.add(e);if(this.maxOutline=this.outline.reduce((e,t)=>Math.max(e,Math.abs(t)),0),this.spring=e.spring.slice(),this.velocity=e.velocity.slice(),this.activeCells=new Set,this.active)for(let e=this.active.top;e<=this.active.bottom;e++)for(let t=this.active.left;t<=this.active.right;t++){let n=e*this.width+t,r=n*2;(this.spring[r]!==0||this.spring[r+1]!==0||this.velocity[r]!==0||this.velocity[r+1]!==0)&&this.activeCells.add(n)}this.activeCells.size||(this.active=null),this.drops=e.drops.map(e=>({...e,point:{...e.point}})),this.splatterRemainder=e.splatterRemainder,this.splatterCanvas=Wc(e.splatterImage),this.splatterBounds=e.splatterBounds?{...e.splatterBounds}:null,this.drawnDrops=e.splatterImage?e.drawnDrops:0,this.transientDirty=!1,this.color=[...e.color],this.rebuildBasePixels(),this.rebuildWetBounds(),this.renderedBounds=null,this.changed()}dispose(){this.listeners.clear(),this.canvas.remove(),this.splatterCanvas?.remove()}paintUnshaded(e,t){let n=this.basePixels,r=new Uint32Array(e.data.buffer),i=t.right-t.left+1;for(let e=t.top;e<=t.bottom;e++)r.set(n.subarray(e*this.width+t.left,e*this.width+t.right+1),(e-t.top)*i);let a=0,o=e=>{let n=e%this.width,o=Math.floor(e/this.width);if(n<t.left||n>t.right||o<t.top||o>t.bottom)return;let s=e*2,c=this.spring[s]+this.outline[s],l=this.spring[s+1]+this.outline[s+1];if(c===0&&l===0)return;a++;let u=n+.5-c,d=o+.5-l,f=this.rawCoverageXY(u,d),p=(o-t.top)*i+n-t.left;if(f<=0){r[p]=0;return}let m=(J(Math.floor(d),0,this.height-1)*this.width+J(Math.floor(u),0,this.width-1))*3;r[p]=Math.round(f*this.material.alpha*255)<<24|this.colorPixels[m+2]<<16|this.colorPixels[m+1]<<8|this.colorPixels[m]};for(let e of this.outlineCells)o(e);for(let e of this.activeCells)this.outlineCells.has(e)||o(e);return i*(t.bottom-t.top+1)-a}present(){if(this.presented!==this.revision){performance.now();let e=this.canvas.getContext(`2d`),t=this.pulled||this.active?Math.ceil(this.maxOutline+8/this.cellSizePx)+2:2,n=this.wetBounds,r=n?{left:Math.max(0,n.left-t),top:Math.max(0,n.top-t),right:Math.min(this.width-1,n.right+t),bottom:Math.min(this.height-1,n.bottom+t)}:null,i=this.renderedBounds,a=this.fullDirty?i&&r?{left:Math.min(i.left,r.left),top:Math.min(i.top,r.top),right:Math.max(i.right,r.right),bottom:Math.max(i.bottom,r.bottom)}:i??r:this.dirtyBounds;a&&e.clearRect(a.left,a.top,a.right-a.left+1,a.bottom-a.top+1);let o=r&&a?{left:Math.max(0,r.left,a.left),top:Math.max(0,r.top,a.top),right:Math.min(this.width-1,r.right,a.right),bottom:Math.min(this.height-1,r.bottom,a.bottom)}:null;if(o&&o.right>=o.left&&o.bottom>=o.top){let t=o.right-o.left+1,n=o.bottom-o.top+1,r=e.createImageData(t,n),i=Gc&&!this.appearance.shaded?new Uint32Array(r.data.buffer):null;performance.now();let a=this.basePixels?this.paintUnshaded(r,o):0;if(!this.basePixels)for(let e=o.top;e<=o.bottom;e++)for(let n=o.left;n<=o.right;n++){let s=(e*this.width+n)*2,c=this.spring[s]+this.outline[s],l=this.spring[s+1]+this.outline[s+1],u=c===0&&l===0;u&&a++;let d=((e-o.top)*t+n-o.left)*4;if(u&&i){let t=e*this.width+n,r=this.alphaAt(t);if(!r)continue;let a=t*3;i[d/4]=Math.round(r*this.material.alpha)<<24|this.colorPixels[a+2]<<16|this.colorPixels[a+1]<<8|this.colorPixels[a];continue}let f=n+.5-c,p=e+.5-l,m=u?this.alphaAt(e*this.width+n)/255:this.rawCoverageXY(f,p);if(m<=0)continue;let h=u?e*this.width+n:J(Math.floor(p),0,this.height-1)*this.width+J(Math.floor(f),0,this.width-1);if(this.appearance.shaded){let t=[this.colorPixels[h*3],this.colorPixels[h*3+1],this.colorPixels[h*3+2]],i=Hc(this.appearance,t,n,e,this.rawCoverageXY(f+1,p)-this.rawCoverageXY(f-1,p),this.rawCoverageXY(f,p+1)-this.rawCoverageXY(f,p-1));for(let e=0;e<3;e++)r.data[d+e]=i[e]}else{if(i){i[d/4]=Math.round(m*this.material.alpha*255)<<24|this.colorPixels[h*3+2]<<16|this.colorPixels[h*3+1]<<8|this.colorPixels[h*3];continue}r.data[d]=this.colorPixels[h*3],r.data[d+1]=this.colorPixels[h*3+1],r.data[d+2]=this.colorPixels[h*3+2]}r.data[d+3]=Math.round(m*this.material.alpha*255)}f(`liquid raster pixels`,t*n),f(`liquid still pixels`,a),performance.now(),e.putImageData(r,o.left,o.top)}this.renderedBounds=r,this.fullDirty=!1,this.dirtyBounds=null,this.presented=this.revision}}draw(e){if(this.present(),this.renderedBounds){let{left:t,top:n,right:r,bottom:i}=this.renderedBounds,a=r-t+1,o=i-n+1;e.drawImage(this.canvas,t,n,a,o,t,n,a,o)}this.drawSplatter(e)}drawSplatter(e){if(this.drawnDrops<this.drops.length){let e=this.drops.slice(this.drawnDrops),t=e=>zc(e),n={left:Math.floor(Math.min(...e.map(e=>e.point.x-t(e))))-32,top:Math.floor(Math.min(...e.map(e=>e.point.y-t(e))))-32,right:Math.ceil(Math.max(...e.map(e=>e.point.x+t(e))))+32,bottom:Math.ceil(Math.max(...e.map(e=>e.point.y+t(e))))+32},r=this.splatterBounds,i=r?{left:Math.min(r.left,n.left),top:Math.min(r.top,n.top),right:Math.max(r.right,n.right),bottom:Math.max(r.bottom,n.bottom)}:n;if(!this.splatterCanvas||!r||r.left!==i.left||r.top!==i.top||r.right!==i.right||r.bottom!==i.bottom){let e=document.createElement(`canvas`);e.width=(i.right-i.left)*Uc,e.height=(i.bottom-i.top)*Uc,this.splatterCanvas&&r&&!this.transientDirty&&e.getContext(`2d`)?.drawImage(this.splatterCanvas,(r.left-i.left)*Uc,(r.top-i.top)*Uc),this.splatterCanvas=e,this.splatterBounds=i}let a=this.splatterCanvas.getContext(`2d`);this.transientDirty&&=(a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,this.splatterCanvas.width,this.splatterCanvas.height),!1),a.setTransform(Uc,0,0,Uc,-i.left*Uc,-i.top*Uc);for(let t of e)Bc(a,this.kind,t);this.drawnDrops=this.drops.length}this.splatterCanvas&&this.splatterBounds&&e.drawImage(this.splatterCanvas,this.splatterBounds.left,this.splatterBounds.top,this.splatterBounds.right-this.splatterBounds.left,this.splatterBounds.bottom-this.splatterBounds.top)}};function Yc(e,t,n){let r=Math.ceil(t/4),i=new Float32Array(r*r),a=n.width/r;for(let n=0;n<t;n++)for(let a=0;a<t;a++){let o=Math.floor(n/4)*r+Math.floor(a/4);i[o]=Math.max(i[o],e[n*t+a])}return{size:r,fuel:i,spacing:a,point:e=>({x:n.x+(e%r+.5)*a,y:n.y+(Math.floor(e/r)+.5)*a})}}function Xc(e){let t=e.flatMap(e=>Array.from(e.fuel,(t,n)=>({field:e,i:n,fuel:t,point:e.point(n)})).filter(e=>e.fuel>=.035)),n=Math.max(1,...e.map(e=>e.spacing))*2,r=e=>`${Math.floor(e.x/n)},${Math.floor(e.y/n)}`,i=new Map;t.forEach((e,t)=>{let n=r(e.point),a=i.get(n)??[];a.push(t),i.set(n,a)});let a=function*(e,t){let r=Math.ceil(t/n),a=Math.floor(e.x/n),o=Math.floor(e.y/n);for(let e=-r;e<=r;e++)for(let t=-r;t<=r;t++)for(let n of i.get(`${a+e},${o+t}`)??[])yield n};return{nodes:t,neighbors:function*(e){let r=t[e];for(let e of a(r.point,n)){let n=t[e],i=Math.hypot(r.point.x-n.point.x,r.point.y-n.point.y);i<=(r.field.spacing+n.field.spacing)*.74&&(yield{next:e,distance:i})}},nearby:a,cellSize:n}}function Zc(e,t,n=0){let r=Xc(e),i=new Int32Array(r.nodes.length).fill(-2),a=[];for(let e of t)for(let t of r.nearby(e,n+r.cellSize)){let o=r.nodes[t];i[t]===-2&&Math.hypot(o.point.x-e.x,o.point.y-e.y)<=n+o.field.spacing*.75&&(i[t]=-1,a.push(t))}for(let e=0;e<a.length;e++)for(let{next:t}of r.neighbors(a[e]))i[t]===-2&&(i[t]=a[e],a.push(t));let o=(e,t)=>{let n=-1,a=1/0;for(let o of r.nearby(e,t+r.cellSize)){if(i[o]===-2)continue;let s=r.nodes[o],c=Math.hypot(s.point.x-e.x,s.point.y-e.y);c<=t+s.field.spacing*.75&&c<a&&(n=o,a=c)}return n};return{points:a.map(e=>r.nodes[e].point),contains:(e,t=0)=>o(e,t)>=0,intersects:(e,t=0)=>{let n={x:e.x+e.width/2,y:e.y+e.height/2};for(let a of r.nearby(n,Math.hypot(e.width,e.height)/2+t+r.cellSize)){if(i[a]===-2)continue;let n=r.nodes[a],o=n.point,s=t+n.field.spacing*.5;if(o.x>=e.x-s&&o.x<=e.x+e.width+s&&o.y>=e.y-s&&o.y<=e.y+e.height+s)return!0}return!1},pathTo:(e,t=0)=>{let n=o(e,t),a=[];for(;n>=0;)a.push(r.nodes[n].point),n=i[n];return a.reverse()}}}var Qc=class{density;resolution;rect;lifetime;spreadMps;pixelsPerMeter;size;fuel;starts;ends;rates;alpha;baseAlpha;light;pixelsByCell;revision=0;complete=!1;lit=!1;constructor(e,t,n,r,i,a){this.density=e,this.resolution=t,this.rect=n,this.lifetime=r,this.spreadMps=i,this.pixelsPerMeter=a;let o=Yc(e,t,n);this.size=o.size,this.fuel=o.fuel,this.starts=new Float64Array(this.fuel.length).fill(1/0),this.ends=new Float64Array(this.fuel.length).fill(1/0),this.rates=new Float32Array(this.fuel.length),this.alpha=new Uint8Array(e.length),this.baseAlpha=new Uint8Array(e.length),this.light=new Float32Array(this.fuel.length);let s=Array.from({length:this.fuel.length},()=>[]);for(let n=0;n<t;n++)for(let r=0;r<t;r++){let i=n*t+r;e[i]<=.035||(this.baseAlpha[i]=Math.round(255*Math.min(1,(e[i]-.035)/.12)),s[Math.floor(n/4)*this.size+Math.floor(r/4)].push(i))}this.pixelsByCell=s.map(e=>e.length?Uint32Array.from(e):void 0)}point(e){return{x:this.rect.x+(e%this.size+.5)*this.spacing,y:this.rect.y+(Math.floor(e/this.size)+.5)*this.spacing}}get spacing(){return this.rect.width/this.size}get managedBytes(){return[this.density,this.fuel,this.starts,this.ends,this.rates,this.alpha,this.baseAlpha,this.light].reduce((e,t)=>e+t.byteLength,0)+this.pixelsByCell.reduce((e,t)=>e+(t?.byteLength??0),0)}indexAt(e){let t=Math.floor((e.x-this.rect.x)/this.spacing),n=Math.floor((e.y-this.rect.y)/this.spacing);return t<0||n<0||t>=this.size||n>=this.size?-1:n*this.size+t}inherit(e,t){for(let n=0;n<this.fuel.length;n++){let r=e.indexAt(this.point(n));if(r>=0&&Number.isFinite(e.starts[r])&&e.ends[r]>t){this.starts[n]=Math.max(t,e.starts[r]);let i=Math.min(1,(e.ends[r]-t)/Math.max(.01,e.ends[r]-e.starts[r])),a=this.fuel[n]>e.fuel[r]*i**2+.05;this.ends[n]=a?Math.max(e.ends[r],t+this.lifetime):e.ends[r]}}}update(e,t){let n=!1,r=this.light,i=!1;for(let a=0;a<this.fuel.length;a++){this.rates[a]=0;let o=this.starts[a],s=this.ends[a],c=r[a],l=0;if(Number.isFinite(o)&&e>=o){let r=Math.max(.01,s-o),i=Math.max(0,Math.min(1,(e-t-o)/r)),c=Math.max(0,Math.min(1,(e-o)/r)),u=Math.max(1e-6,(1-i)**2),d=Math.max(1e-6,(1-c)**2);this.rates[a]=Math.log(u/d)/Math.max(t,1e-4),e<s&&(n=!0,l=Math.min(1,(e-o)/.15)*Math.min(1,(s-e)/Math.min(2,r*.3)))}if(r[a]=l,c<=0&&l<=0)continue;let u=this.pixelsByCell[a];if(u)for(let e of u){let t=Math.round(this.baseAlpha[e]*l);this.alpha[e]=t,i||=t>0}}return this.lit=i,this.revision++,this.complete=this.starts.some(Number.isFinite)&&this.ends.every((t,n)=>this.fuel[n]<.035||t<=e),n}};function $c(e,t,n,r,i=[]){let{nodes:a,neighbors:o,nearby:s,cellSize:c}=Xc(e);if(!a.length)return;let l=new Set;for(let e of[t,...i])for(let t of s(e,n+c)){let r=a[t];Math.hypot(r.point.x-e.x,r.point.y-e.y)<=n+r.field.spacing*.75&&l.add(t)}let u=new Float64Array(a.length).fill(1/0),d=[],f=(e,t)=>{if(t>=u[e])return;u[e]=t;let n=d.length;for(d.push({index:e,time:t});n>0;){let e=n-1>>1;if(d[e].time<=t)break;d[n]=d[e],n=e}d[n]={index:e,time:t}};for(a.forEach((e,t)=>{e.field.ends[e.i]<=r||(l.has(t)?f(t,r):Number.isFinite(e.field.starts[e.i])&&e.field.ends[e.i]>r&&f(t,Math.max(r,e.field.starts[e.i])))});d.length;){let e=d[0],t=d.pop();if(d.length){let e=0;for(;e*2+1<d.length;){let n=e*2+1;if(n+1<d.length&&d[n+1].time<d[n].time&&n++,d[n].time>=t.time)break;d[e]=d[n],e=n}d[e]=t}if(e.time===u[e.index])for(let{next:t,distance:n}of o(e.index)){let i=a[t];i.field.ends[i.i]<=r||f(t,e.time+n/Math.max(1,i.field.pixelsPerMeter)/i.field.spreadMps)}}a.forEach((e,t)=>{u[t]>=e.field.starts[e.i]||(e.field.starts[e.i]=u[t],e.field.ends[e.i]=u[t]+e.field.lifetime)})}function el(e){let t=e.extentM*e.pixelsPerMeter;return{x:e.center.x-t/2,y:e.center.y-t/2,width:t,height:t}}function tl(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 nl(e,t,n){return t.x>=e.x-n&&t.x<=e.x+e.width+n&&t.y>=e.y-n&&t.y<=e.y+e.height+n}function rl(e,t,n=0){if(!e.length||!t.length)return[];let r=e.map(el),i=new Uint8Array(e.length),a=[];for(let o=0;o<e.length;o++)t.some(e=>nl(r[o],e,n))&&(i[o]=1,a.push(o));for(let t=0;t<a.length;t++){let n=r[a[t]];for(let t=0;t<e.length;t++)!i[t]&&tl(n,r[t])&&(i[t]=1,a.push(t))}return a.map(t=>e[t])}function il(e,n,r=0){return Zc(rl(e.filter(e=>t[e.kind].conductive),n,r).map(e=>Yc(e.fluid.captureFuel(),e.resolution,el(e))),n,r)}function al(e,n,r){let i=[];for(let a of e){let e=a.fire;if(!e||!t[a.kind].burnable)continue;let o=e.size,s=Math.max(1,Math.ceil(r/e.spacing)),c=(t,r)=>{if(t<0||r<0||t>=o||r>=o)return!1;let i=r*o+t;return e.fuel[i]>=.035&&e.starts[i]<=n&&e.ends[i]>n};for(let t=0;t<o;t++)for(let n=0;n<o;n++)c(n,t)&&(c(n-1,t)&&c(n+1,t)&&c(n,t-1)&&c(n,t+1)&&(n%s!==0||t%s!==0)||i.push(e.point(t*o+n)))}return i}function ol(e,n,o,s){let c=0,l=0,u=0,d=new Set,f=null,p=[0,0,0],m=[],h=[];for(let g of e){let e=o(g,n);if(e>.12&&(f=g.id),e>.1&&d.add(g.kind),a(g.kind)===`water`&&!r(g.kind)||e<.04)continue;let _=g.fluid.colorAt?.(s(g,n))??g.color;h.push({id:`liquid:${g.id}`,color:`rgb(${_.map(e=>Math.round(e)).join(` `)})`,opacity:Math.min(1,e),distanceM:g.elementProfile?.distanceM??(r(g.kind)?i(g.kind).carryM:t[g.kind].treadDistanceM),material:i(g.kind)}),m.push(g.id);for(let t=0;t<3;t++)p[t]+=_[t]*e;c+=e,l=1-(1-l)*(1-e),u=Math.max(u,g.elementProfile?.distanceM??t[g.kind].treadDistanceM)}let g=c?{id:`liquid:${m.join(`,`)}`,color:`rgb(${p.map(e=>Math.round(e/c)).join(` `)})`,opacity:l,distanceM:u}:null;return{materials:[...d],paint:g,paints:h,splashFieldId:f}}function sl(e,t,n,r,i){let a=new Uint8Array(e*e),o=0,s=i?Math.max(0,Math.floor(((i.left-t.x)/n+.5)*e)-1):0,c=i?Math.min(e,Math.ceil(((i.right-t.x)/n+.5)*e)+1):e,l=i?Math.max(0,Math.floor(((i.top-t.y)/n+.5)*e)-1):0,u=i?Math.min(e,Math.ceil(((i.bottom-t.y)/n+.5)*e)+1):e;for(let i=l;i<u;i++)for(let l=s;l<c;l++){let s=0;for(let a=0;a<2;a++)for(let o=0;o<2;o++)r({x:t.x+((l+.25+o*.5)/e-.5)*n,y:t.y+((i+.25+a*.5)/e-.5)*n})&&s++;let c=Math.round(s/4*255);a[i*e+l]=c,o+=c/255}return{mask:a,coverage:o/(e*e)}}var cl=4,ll={low:128,medium:160,high:192},ul={low:192,medium:256,high:384},dl=.115,fl=1/10,pl=(e,t)=>{let n=typeof window>`u`?1:Math.min(3,Math.max(1,window.devicePixelRatio||1));return Math.max(ul[t],Math.min(768,Math.ceil(e*n/16)*16))},ml=(e,t)=>e.every((e,n)=>e===t[n]);function hl(e,t,n,r,i){let a=h(C(-1),t),o=h(C(0,1),t+n),s=r.x*o.x+r.y*o.y;if(e){let e=m(r),t=Math.min(.55,e/22),n=Math.min(.28,Math.abs(s)/28),c=S(S(v(a,1-t-n),v(i,t)),v(o,-Math.sign(s)*n));return v(c,1/Math.max(.001,m(c)))}if(Math.abs(s)<=.8)return i;let c=Math.min(1,Math.abs(s)/Math.max(.8,m(r))),l=S(v(i,1-c),v(o,-Math.sign(s)*c));return v(l,1/Math.max(.001,m(l)))}var gl=class{quality;fields=[];clock=0;fireTime=0;nextId=1;lastPours=new Map;lastFirePlan=-1/0;seam=null;wheelContacts=[];splashFields=new Map;captureState(){let e=[];try{for(let{fluid:t,...n}of this.fields)e.push({meta:u(n),fluid:t.captureState()})}catch(t){for(let t of e)t.fluid.dispose();throw t}return{fields:e,clock:this.clock,fireTime:this.fireTime,nextId:this.nextId,lastPours:u(this.lastPours),lastFirePlan:this.lastFirePlan,seam:this.seam?{previousId:this.seam.previous.id,currentId:this.seam.current.id,point:u(this.seam.point)}:null,wheelContacts:u(this.wheelContacts),splashFields:u(this.splashFields),quality:this.quality,dispose:()=>e.forEach(e=>e.fluid.dispose())}}restoreState(e){this.reset(),this.quality=e.quality;try{for(let{meta:t,fluid:n}of e.fields){let e=u(t),r=new Jc(e.kind,e.resolution,e.resolution,e.color,e.elementProfile);r.setCellSize(e.extentM*e.pixelsPerMeter/e.resolution);try{r.restoreState(n)}catch(e){throw r.dispose(),e}this.fields.push({...e,fluid:r})}}catch(e){throw this.reset(),e}this.clock=e.clock,this.fireTime=e.fireTime,this.nextId=e.nextId,this.lastPours=u(e.lastPours),this.lastFirePlan=e.lastFirePlan,this.wheelContacts=u(e.wheelContacts),this.splashFields=u(e.splashFields??new Map);let t=this.fields.find(t=>t.id===e.seam?.previousId),n=this.fields.find(t=>t.id===e.seam?.currentId);this.seam=e.seam&&t&&n?{previous:t,current:n,point:u(e.seam.point)}:null}constructor(e=`high`){this.quality=e}get managedBytes(){return this.fields.reduce((e,t)=>e+96+(t.fire?.managedBytes??0)+t.fluid.managedBytes,0)}fireContactBounds(){return this.fields.filter(e=>t[e.kind].burnable).map(e=>{let t=e.extentM*e.pixelsPerMeter;return{x:e.center.x-t/2,y:e.center.y-t/2,width:t,height:t}})}hasConductiveCandidate(e,n){return this.fields.some(r=>{if(!t[r.kind].conductive)return!1;let i=r.extentM*r.pixelsPerMeter/2+n;return e.some(e=>Math.abs(e.x-r.center.x)<=i&&Math.abs(e.y-r.center.y)<=i)})}reset(){for(let e of this.fields)e.fluid.dispose();this.fields=[],this.clock=0,this.fireTime=0,this.lastPours.clear(),this.lastFirePlan=-1/0,this.seam=null,this.wheelContacts=[],this.splashFields.clear()}setQuality(e){this.quality=e}removeSeed(e){for(let t=this.fields.length-1;t>=0;t--){let n=this.fields[t];if(n.seedKey===e){n.fluid.removeSeed(),n.fluid.hasDeposits?n.seedKey=void 0:(n.fluid.dispose(),this.fields.splice(t,1));for(let[e,t]of this.splashFields)t===n.id&&this.splashFields.delete(e)}}}fieldForSeed(e){return this.fields.find(t=>t.seedKey===e)??null}seedShape(e,t,n,r,i,a,o,s,c){let l=this.fieldForSeed(e);l&&l.kind!==t&&(this.removeSeed(e),l=null);let u=Math.max(cl,i/a+1.4);if(l??=this.create(t,n,r,a,s,pl(u*a,this.quality)),!l)return!1;try{let t=l.pixelsPerMeter;l.seedKey=e,l.elementProfile=s,l.color=n;let a=Math.max(cl,i/t+1.4,2*(m(x(r,l.center))/t+i/t/2+.7));l.poured===0?l.extentM=a:a>l.extentM&&this.expand(l,a/l.extentM),l.fluid.setCellSize(l.extentM*t/l.resolution),l.fluid.configure(n,s);let u=l.fluid.displaced,d=l.extentM*t/l.resolution;performance.now();let{mask:f,coverage:p}=(u?null:c?.(l.resolution,l.center,l.extentM*t))??sl(l.resolution,l.center,l.extentM*t,e=>{if(!u)return o(e);let t=l.fluid.offsetAt(this.localPoint(l,e));return o(C(e.x+t.x*d,e.y+t.y*d))},u?void 0:{left:r.x-i/2,top:r.y-i/2,right:r.x+i/2,bottom:r.y+i/2});if(p<=0)return this.removeSeed(e),!1;let h=Math.max(1,p*l.extentM*l.extentM*3);return l.poured=Math.max(l.poured,h),performance.now(),l.fluid.seedMask(f,.85,h,n),!0}catch(t){throw this.removeSeed(e),t}}pour(e,n,r,i,a,o=t[e].color,s=`default`){if(i<=0)return;let c=this.lastPours.get(s),l=c?m(x(n,c.point))/Math.max(1,r):0,u=c?.kind===e&&ml(o,c.color)&&c.age<.12&&l<2.5?c:void 0,d=u?l:0,f=Math.max(u?.age??1/120,1/120),p=Math.exp(-d/.45),h=(u?.localAmount??0)*p+i,g=Math.min(1.8,.11+Math.sqrt(h)*.32),_=-Math.expm1(-f/.12),v=u?u.radiusM+(g-u.radiusM)*_:g;this.deposit(e,o,n,r,i,a,v,u?.point,u?.radiusM),this.lastPours.set(s,{kind:e,color:o,point:{...n},age:0,localAmount:h,radiusM:v})}emit(e,n,r,i,a,o,s=t[e].color){i<=0||a<=0||this.deposit(e,s,n,r,i,o,a)}deposit(e,t,n,i,a,o,s,c,l=s){let u=this.fields.at(-1),d=e===`paint`||r(e)?.mixing,f=a=>{if(!(a.kind===e||r(e)?.mixing&&r(a.kind)?.mixing)&&!(d&&a.kind===`paint`)||!d&&!ml(t,a.color))return!1;let o=s*i;return[n,c??n,C((n.x+(c?.x??n.x))/2,(n.y+(c?.y??n.y))/2)].some(e=>m(x(e,a.center))/i+s>6.8?!1:[C(),C(o),C(-o),C(0,o),C(0,-o)].some(t=>{let n=S(e,t);return this.covers(a,n)&&a.fluid.densityAt(this.localPoint(a,n))>.02}))},p=(u&&f(u)?u:[...this.fields].reverse().find(f))??this.create(e,t,n,i);if(!p)return;p!==u&&!u?.seedKey&&u?.kind===e&&ml(t,u.color)&&(this.seam={previous:u,current:p,point:{...n}});let h=this.seam?.current===p&&m(x(n,this.seam.point))<i*.85;this.depositIn(p,n,h?a*.5:a,o,s,t,c,l),h&&this.seam&&this.depositIn(this.seam.previous,n,a*.5,o,s,t,c,l)}depositIn(e,t,n,r,i,a=e.color,o,s=i){e.poured+=n;let c=2*(Math.max(m(x(t,e.center)),o?m(x(o,e.center)):0)/e.pixelsPerMeter+i+.25);c>e.extentM&&this.expand(e,Math.min(14/e.extentM,Math.max(1.25,c/e.extentM)));let l=this.localPoint(e,t),u=v(r,e.resolution/e.extentM);e.fluid.pour(n,this.clock+e.id,l,i*e.resolution/e.extentM,u,a,this.localPoint(e,o??t),s*e.resolution/e.extentM)}eject(e,t,n,r,i){this.pour(e,t,n,1.1,r,i)}splatter(e,t,n,r,i,a=!1,o=1,s){if(i<=0)return!1;let c=this.wheelContacts[e]?.splashFieldId??(s?this.splashFields.get(e):null),l=c==null?a||this.wheelContacts.length===0?[...this.fields].reverse().find(e=>this.covers(e,t)&&this.coverage(e,t)>.12):null:this.fields.find(e=>e.id===c);if(!l||!this.covers(l,t))return!1;let u=this.localPoint(l,t),d=l.resolution/l.extentM/l.pixelsPerMeter,f=s?.color.match(/[\d.]+/g)?.slice(0,3).map(Number);return l.fluid.spray(u,n,r*d,i*1.5*(s?.opacity??1),o,f?.length===3?f:void 0),!0}create(e,t,n,r,i,a){let o=a??ll[this.quality],s;try{s=new Jc(e,o,o,t,i)}catch{return null}let c={id:this.nextId++,kind:e,color:t,center:n,pixelsPerMeter:r,resolution:o,extentM:cl,fluid:s,poured:0,elementProfile:i};return s.setCellSize(c.extentM*r/o),this.fields.push(c),c}step(e,n=[]){for(let[t,n]of this.lastPours)n.age+=e,n.age>1&&this.lastPours.delete(t);if(this.clock+=e,this.clock<1/30)return;let r=Math.min(.05,this.clock);this.clock=Math.max(0,this.clock-1/30),this.fireTime+=r;let i=this.fields.filter(e=>t[e.kind].burnable);this.fireTime-this.lastFirePlan>=.2&&i.some(e=>e.fire?.starts.some(Number.isFinite))&&i.some(e=>!e.fire||e.poured!==e.firePoured)&&($c(i.map(e=>!e.fire||e.poured!==e.firePoured?this.prepareFire(e):e.fire),C(1/0,1/0),0,this.fireTime),this.lastFirePlan=this.fireTime);for(let e of this.fields){let i=[];for(let t of n){let n=m(t.velocity);if(m(x(t.point,e.center))>e.extentM*e.pixelsPerMeter*.62)continue;let a=e.resolution/e.extentM/e.pixelsPerMeter,o=this.localPoint(e,t.point);if(n<3&&(t.slip??0)<.05)continue;let s=C(t.point.x-t.velocity.x*r,t.point.y-t.velocity.y*r),c=this.localPoint(e,s);i.push({from:c,to:o,radius:Math.max(.65,t.radiusPx*a),paint:t.paint,slip:t.slip??0})}performance.now();let o=i.filter(t=>this.nearLiquid(e,t.from,t.to,t.radius));performance.now();for(let t of o)if(performance.now(),e.fluid.drag(t.from,t.to,r,t.radius,0),a(e.kind)===`paint`&&t.paint){let n=t.paint.color.match(/[\d.]+/g)?.slice(0,3).map(Number);if(n?.length===3){let i=m(x(t.to,t.from)),a=(1-Math.exp(-i/Math.max(1,t.radius*3)-t.slip*r*2))*t.paint.opacity;performance.now(),e.fluid.transferPigment?.(t.from,t.to,t.radius,n,a*.32)}}let s=t[e.kind].burnable&&e.fire?.starts.some(Number.isFinite)?e.fire:void 0,c=s?this.fireTime-(e.fireUpdatedAt??this.fireTime-r):0,l=!!s&&c+1e-9>=fl,u=e.firePendingElapsed??0;performance.now(),e.fluid.step(r,0,[],u>0&&s?.rates.some(e=>e>0)?s:void 0,u||r),e.firePendingElapsed=0,l&&(performance.now(),s.update(this.fireTime,c),e.fireUpdatedAt=this.fireTime,e.firePendingElapsed=c)}for(let e=this.fields.length-1;e>=0;e--){let n=this.fields[e];if(!t[n.kind].burnable||!n.fire?.complete||(n.firePendingElapsed??0)>0)continue;let r=n.fluid.captureFuel();r.some(e=>e>=.035)?(this.prepareFire(n,r,.75),$c([n.fire],n.center,n.extentM*n.pixelsPerMeter,this.fireTime)):n.seedKey?(n.fluid.reset(),n.fire=void 0):(n.fluid.dispose(),this.fields.splice(e,1))}performance.now(),this.wheelContacts=n.map((e,t)=>{let n=this.sampleContact(e.point);return n.splashFieldId===null?e.paint||this.splashFields.delete(t):this.splashFields.set(t,n.splashFieldId),n});for(let e of this.splashFields.keys())e>=n.length&&this.splashFields.delete(e)}sampleContact(e){return ol(this.fields,e,(e,t)=>this.coverage(e,t),(e,t)=>this.localPoint(e,t))}nearLiquid(e,t,n,r){return e.fluid.mayIntersect(t,n,r)}expand(e,t){if(t<=1)return;let n=e.resolution;e.resolution=e.fluid.grow(t),e.extentM*=e.resolution/n,e.fire&&(this.prepareFire(e),e.firePoured=-1)}localPoint(e,t){return C(e.resolution/2+(t.x-e.center.x)/e.pixelsPerMeter*e.resolution/e.extentM,e.resolution/2+(t.y-e.center.y)/e.pixelsPerMeter*e.resolution/e.extentM)}covers(e,t){let n=e.extentM*e.pixelsPerMeter*.5;return Math.abs(t.x-e.center.x)<=n&&Math.abs(t.y-e.center.y)<=n}coverage(e,n){if(!this.covers(e,n))return 0;let r=e.fluid.densityAt(this.localPoint(e,n));return Math.max(0,Math.min(1,(r-dl+.012)/.024))*(e.elementProfile?.opacity??t[e.kind].alpha)}contacts(e,t){return this.fields.filter(n=>n.kind===e&&t.some(e=>this.coverage(n,e)>.1)).map(e=>e.id)}conductAt(e,t=0){return il(this.fields,e,t)}densityAt(e,t){return Math.max(0,...this.fields.filter(n=>n.kind===e&&this.covers(n,t)).map(e=>e.fluid.densityAt(this.localPoint(e,t))))}prepareFire(e,n=e.fluid.captureFuel(),r){let i=t[e.kind],a=e.extentM*e.pixelsPerMeter,o=new Qc(n,e.resolution,{x:e.center.x-a/2,y:e.center.y-a/2,width:a,height:a},r??i.burnLifetime??i.burnSeconds??12,i.fireSpreadMps??t.oil.fireSpreadMps,e.pixelsPerMeter);return e.fire&&o.inherit(e.fire,this.fireTime),e.fire=o,e.firePoured=e.poured,e.fireSampleAt=this.fireTime,e.fireUpdatedAt=this.fireTime-e.id%3*fl/3,e.firePendingElapsed=0,o}igniteConducted(e,n){if(!e.length)return;let r=rl(this.fields.filter(e=>t[e.kind].burnable),e,n).map(e=>!e.fire||e.firePoured!==e.poured?this.prepareFire(e):e.fire);if(r.length){$c(r,e[0],n,this.fireTime,e.slice(1));for(let e of r)e.update(this.fireTime,0);this.lastFirePlan=this.fireTime}}igniteAt(e,n=0){if(this.fireTime-this.lastFirePlan<.15)return;let r=[e];if(n>0)for(let t=0;t<8;t++)r.push(C(e.x+Math.cos(t*Math.PI/4)*n,e.y+Math.sin(t*Math.PI/4)*n));let i=this.fields.filter(e=>t[e.kind].burnable&&r.some(t=>this.coverage(e,t)>.08));if(!i.length||(this.lastFirePlan=this.fireTime,i.every(e=>e.fire&&e.firePoured===e.poured&&r.every(t=>{let n=e.fire.indexAt(t);return n<0||e.fire.fuel[n]<.035||Number.isFinite(e.fire.starts[n])}))))return;let a=this.fields.filter(e=>t[e.kind].burnable).map(e=>!e.fire||e.poured!==e.firePoured&&this.fireTime-(e.fireSampleAt??0)>=.2?this.prepareFire(e):e.fire);$c(a,e,n,this.fireTime);for(let e of a)e.update(this.fireTime,0)}igniteAlong(e,t,n=0){for(let r=0;r<=4;r++)this.igniteAt(C(e.x+(t.x-e.x)*r/4,e.y+(t.y-e.y)*r/4),n)}burningSources(e){return al(this.fields,this.fireTime,e)}burningMasks(){return this.fields.flatMap(e=>{let n=e.fire;return!t[e.kind].burnable||!n?.lit?[]:[{key:e,alpha:n.alpha,pixelWidth:n.resolution,pixelHeight:n.resolution,...n.rect,origin:e.center,age:.4,farthest:Math.max(1,n.rect.width),spreadSeconds:0,burnSeconds:1,intensity:.55,smokeRate:10,revision:n.revision}]})}kindAt(e){let t=!1,n=!1,r=!1;for(let i=this.fields.length-1;i>=0;i--){let o=this.fields[i];if(!(this.coverage(o,e)<=.1)){if(a(o.kind)===`water`)return`water`;a(o.kind)===`oil`&&(t=!0),a(o.kind)===`paint`&&(n=!0),a(o.kind)===`mud`&&(r=!0)}}return r?`mud`:t?`oil`:n?`paint`:null}pruneOutside(e){this.fields=this.fields.filter(t=>{let n=t.extentM*t.pixelsPerMeter*1.5,r=t.center.x+n>=e.x&&t.center.x-n<=e.x+e.width&&t.center.y+n>=e.y&&t.center.y-n<=e.y+e.height;return r||t.fluid.dispose(),r}),!this.seam||this.fields.includes(this.seam.previous)&&this.fields.includes(this.seam.current)||(this.seam=null)}draw(e,t,n,r,i){performance.now(),e.save(),e.globalAlpha=r;for(let r of this.fields){let a=t(r.center),o=r.extentM*r.pixelsPerMeter*n,s=r.fluid.hasSplatter?o*1.5:o/2;i&&(a.x+s<0||a.y+s<0||a.x-s>i.width||a.y-s>i.height)||(e.save(),e.translate(a.x-o/2,a.y-o/2),e.scale(o/r.resolution,o/r.resolution),r.fluid.draw(e),e.restore())}e.restore()}},_l=class{liquids;camera;pixelSpace;elementFields=new Map;nextElementId=1;initialPuddles=[];constructor(e,t,n){this.liquids=e,this.camera=t,this.pixelSpace=n}captureState(){return u({elementFields:this.elementFields,nextElementId:this.nextElementId,initialPuddles:this.initialPuddles})}restoreState(e){let t=u(e);this.elementFields=t.elementFields,this.nextElementId=t.nextElementId,this.initialPuddles=t.initialPuddles}clearEffects(){this.elementFields.clear(),this.nextElementId=1}pourWorldLiquid(e,t,n,r,i){this.liquids.pour(e,this.camera.particlePoint(t),this.camera.particleScale(),n,C(),r,i)}addLiquid(e,t){let r=n(e),i=t.amount??24;if(!Number.isFinite(t.at.x)||!Number.isFinite(t.at.y)||!Number.isFinite(i)||i<=0)throw RangeError(`Liquid position and positive amount must be finite.`);let a=t.color?o(t.color):void 0;if(t.initial){let e={kind:r,point:this.camera.documentPoint(t.at),amount:i,color:a};this.initialPuddles.push(e),this.depositInitialPuddle(e)}else this.pourWorldLiquid(r,t.at,i,a)}syncElementLiquids(e){performance.now();let t=new Set(e.map(e=>e.key));for(let[e,n]of this.elementFields)t.has(e)||(this.liquids.removeSeed(n.id),this.elementFields.delete(e));let n=new Map,r=!1;for(let t of e){let e=this.localFromDocument({x:t.bounds.x,y:t.bounds.y}),i=this.localFromDocument({x:t.bounds.x+t.bounds.width,y:t.bounds.y+t.bounds.height}),a=C((e.x+i.x)/2,(e.y+i.y)/2),o=this.elementFields.get(t.key),s=o?.signature!==t.signature,c=o&&(o.center.x!==a.x||o.center.y!==a.y);if(!o||s||c){if(t.rasterize){if(r){let e=o&&this.liquids.fieldForSeed(o.id);e&&n.set(t.key,e);continue}r=!0}f(`liquid field reseeds`),o&&s&&f(`liquid signature reseeds`),o&&c&&f(`liquid position reseeds`),performance.now();let l=o?.id??`element-liquid-${this.nextElementId++}`,u=Math.max(Math.abs(i.x-e.x),Math.abs(i.y-e.y));if(!this.liquids.seedShape(l,t.kind,t.color,a,u,this.camera.particleScale(),e=>t.contains(this.pixelSpace?e:this.camera.documentPoint(e)),t.profile,this.pixelSpace?t.rasterize:void 0))continue;o={id:l,signature:t.signature,center:a},this.elementFields.set(t.key,o)}let l=this.liquids.fieldForSeed(o.id);l&&n.set(t.key,l)}return n}setInitialPuddles(e){this.liquids.reset(),this.elementFields.clear(),this.nextElementId=1,this.initialPuddles=e.map(({kind:e,color:t,point:n,amount:r})=>({kind:e,color:t?[...t]:void 0,point:{...n},amount:r})),this.restoreInitialPuddles()}restoreInitialPuddles(){for(let e of this.initialPuddles)this.depositInitialPuddle(e)}depositInitialPuddle({kind:e,color:t,point:n,amount:r}){let i=this.localFromDocument(n),a=this.camera.particleScale(),o=Math.max(1,Math.ceil(r/2));for(let n=0;n<o;n++)this.liquids.pour(e,i,a,r/o,C(),t),this.liquids.step(1/30)}localFromDocument(e){return this.pixelSpace?{...e}:this.camera.worldFromDocument(e)}},vl=class{bounds=[];tiles=new Map;dpr=1;scale=1;documentOrigin={x:0,y:0};measureDocumentOrigin(){let e=document.body,t=e.getBoundingClientRect(),n=O();this.documentOrigin={x:t.left+n.x+e.clientLeft,y:t.top+n.y+e.clientTop}}setAbsoluteViewport(){this.measureDocumentOrigin();for(let e of this.tiles.values())e.canvas.style.position=`absolute`}setBounds(e){this.bounds=e;for(let[t,n]of this.tiles)t>=e.length&&(n.canvas.remove(),this.tiles.delete(t))}resize(e,t,n,r){this.dpr=n,this.scale=r,this.measureDocumentOrigin()}tile(e){let t=this.tiles.get(e);if(t)return t;let n=document.createElement(`canvas`);n.dataset.jrLiquidTextVehicle=``;let r=n.getContext(`2d`);if(!r)throw Error(`Joy Ride requires a 2D canvas context.`);return n.setAttribute(`aria-hidden`,`true`),Object.assign(n.style,{position:`absolute`,left:`0`,top:`0`,pointerEvents:`none`,zIndex:l(`foreground`),transformOrigin:`0 0`,display:`none`}),document.body.append(n),t={canvas:n,context:r,visible:!1},this.tiles.set(e,t),t}draw(e,t,n,r){for(let i=0;i<this.bounds.length;i++){let a=this.bounds[i],o=e({x:a.x,y:a.y}),s=e({x:a.x+a.width,y:a.y+a.height}),c=o.x,l=o.y,u=s.x-c,d=s.y-l;if(!t.some(({point:e,radius:t})=>e.x>=c-t&&e.x<=c+u+t&&e.y>=l-t&&e.y<=l+d+t)||u<=0||d<=0){let e=this.tiles.get(i);e?.visible&&(e.canvas.style.display=`none`,e.visible=!1);continue}let f=this.tile(i),{canvas:p,context:m}=f,h=Math.max(1,Math.ceil(u*this.dpr)),g=Math.max(1,Math.ceil(d*this.dpr));(p.width!==h||p.height!==g)&&(p.width=h,p.height=g,p.style.width=`${u}px`,p.style.height=`${d}px`);let _=O(),v=`${_.x+c*this.scale-this.documentOrigin.x}px ${_.y+l*this.scale-this.documentOrigin.y}px`;p.style.translate!==v&&(p.style.translate=v),p.style.scale!==String(this.scale)&&(p.style.scale=String(this.scale)),f.visible||=(p.style.display=`block`,!0),m.setTransform(this.dpr,0,0,this.dpr,0,0),m.clearRect(0,0,u,d),m.save(),m.translate(-c+n.x,-l+n.y),r(m),m.restore()}}dispose(){for(let e of this.tiles.values())e.canvas.remove();this.tiles.clear()}};function yl(e,t,n,r,i,o,s,l=[]){let{sim:u,tirePaint:d}=e;if(u.mode!==`car`)return;let f=[];u.car.statusEffects.setContacts(`mud`,w.mud,f),e.isGhost?u.car.tires.forEach((e,t)=>d.pauseTrack(t)):(d.step(o?u.car.tires.map(e=>m(u.body.velocityAt(u.body.world(e.local)))*r):[]),s?(u.car.tires.forEach((e,r)=>{let s=t[r],p=s?.materials??[],m=e=>p.some(t=>a(t)===e&&!c(t)),h=()=>{for(let e of p){let t=c(e);t&&u.car.statusEffects.apply(`liquid:${e}`,t,r)}};if(p.some(e=>a(e)===`water`)&&(u.car.washWheel(r),d.wash(r,s?.paints??[]),!s?.paints?.length)){h();return}m(`oil`)&&u.car.coatWithOil(r),p.some(e=>a(e)===`mud`)&&(m(`mud`)&&u.car.coatWithMud(r),f.push(r)),h();for(let e of s?.paints??(s?.paint?[s.paint]:[]))d.touch(r,e);if(d.touch(r,l[r]??null),!o){d.pauseTrack(r);return}let g=d.coating(r),_=p.length>0&&!!s?.paint&&g?.color!==s.paint.color;(s?.paints?.length??+!!s?.paint)>0||l[r]?d.trackWet(r,n[r],-u.body.angle-e.angle,u.car.preset.geometry.tireWidthM,i,e.slip,_&&!l[r]):d.track(r,n[r],-u.body.angle-e.angle,u.car.preset.geometry.tireWidthM,i,_,e.slip)}),u.car.statusEffects.setContacts(`mud`,w.mud,f)):u.car.tires.forEach((e,t)=>d.pauseTrack(t)))}function bl(e,t,n,r,i,a,o){let s=e=>{let t=e.sim;return t.mode!==`car`||e.isGhost?[]:t.car.tires.map((n,r)=>{let i=t.body.world(n.local);return{point:o.particlePoint(i),velocity:o.particleVelocity(t.body.velocityAt(i)),radiusPx:t.car.preset.geometry.tireWidthM*o.particleScale*.7,slip:n.slip,paint:e.tirePaint.coating(r)}})},c=s(t),l=n.map(e=>({vehicle:e,tires:s(e)}));performance.now(),e.step(r,[...c,...l.flatMap(e=>e.tires)]),performance.now();for(let t of e.burningMasks())o.emitFire(t,r);performance.now();let u=e=>typeof a==`function`?a(e.sim.car.tires.map(t=>o.documentPoint(e.sim.body.world(t.local)))):e===t?a:[];yl(t,e.wheelContacts.slice(0,c.length),c.map(e=>e.point),r,o.particleScale,i,!o.fading,u(t));let d=c.length;for(let{vehicle:t,tires:n}of l)yl(t,e.wheelContacts.slice(d,d+n.length),n.map(e=>e.point),r,o.particleScale,!0,!o.fading,u(t)),d+=n.length;return{tires:c,companionTires:l}}var xl=class{camera;fields=new gl;authoring;textVehicles=null;constructor(e,t){this.camera=e,this.fields.setQuality(t),this.authoring=new _l(this.fields,e,e.pixelSpace)}get managedBytes(){return this.fields.managedBytes}setQuality(e){this.fields.setQuality(e)}captureState(){let e=this.fields.captureState();try{return{fields:e,authoring:this.authoring.captureState(),dispose:()=>e.dispose()}}catch(t){throw e.dispose(),t}}restoreState(e){this.fields.restoreState(e.fields),this.authoring.restoreState(e.authoring)}clearEffects(){this.fields.reset(),this.authoring.clearEffects()}restoreInitialPuddles(){this.authoring.restoreInitialPuddles()}dispose(){this.textVehicles?.dispose(),this.textVehicles=null,this.fields.reset()}resize(){this.textVehicles?.resize(this.camera.width,this.camera.height,this.camera.dpr,this.camera.regionScale)}pruneOutside(e){this.fields.pruneOutside(e)}draw(e,t){this.fields.draw(e,e=>this.camera.pixelSpace?x(e,this.camera.sceneScroll()):this.camera.screen(e),this.camera.pixelSpace?1:this.camera.zoom,t,{width:this.camera.width,height:this.camera.height})}drawTextVehicles(e,t,n){this.textVehicles?.draw(e=>this.camera.viewportFromDocument(e),e,t,n)}pourWorldLiquid(e,t,n,r,i){this.authoring.pourWorldLiquid(e,t,n,r,i)}emitPaint(e,t,n,r,i){this.fields.emit(`paint`,this.camera.particlePoint(e),this.camera.particleScale(),n,t,this.camera.pixelSpace?C(i.x,-i.y):i,r)}local(e){return this.camera.particlePoint(this.camera.worldFromDocument(e))}get ratio(){return this.camera.particleScale()/this.camera.documentScale()}hasConductiveCandidate(e,t){return this.fields.hasConductiveCandidate(e.map(e=>this.local(e)),t*this.ratio)}conductLightning(e,t=0){let n=e=>this.local(e),r=e=>this.camera.pixelSpace?e:this.camera.documentPoint(e),i=this.ratio,a=this.fields.conductAt(e.map(n),t*i);return{points:a.points.map(r),contains:(e,t=0)=>a.contains(n(e),t*i),intersects:(e,t=0)=>{let r=n(e),o=n({x:e.x+e.width,y:e.y+e.height});return a.intersects({x:Math.min(r.x,o.x),y:Math.min(r.y,o.y),width:Math.abs(r.x-o.x),height:Math.abs(r.y-o.y)},t*i)},pathTo:(e,t=0)=>a.pathTo(n(e),t*i).map(r)}}igniteAt(e,t){this.fields.igniteAt(this.local(e),t*this.ratio)}igniteConducted(e,t){this.fields.igniteConducted(e.map(e=>this.local(e)),t*this.ratio)}igniteFromFire(e){if(!e.length)return;let t=new Map,n=this.fields.fireContactBounds().map(e=>{if(this.camera.pixelSpace)return e;let t=this.camera.documentPoint({x:e.x,y:e.y}),n=this.camera.documentPoint({x:e.x+e.width,y:e.y+e.height});return{x:Math.min(t.x,n.x),y:Math.min(t.y,n.y),width:Math.abs(t.x-n.x),height:Math.abs(t.y-n.y)}});for(let r of e){let e=Math.max(0,Math.round(r.radiusPx/4)*4),i=t.get(e)??[],a=r.bounds?n.flatMap(e=>le(r,e)):le(r);for(let e of a)i.push(this.local(e));t.set(e,i)}for(let[e,n]of t)this.fields.igniteConducted(n,e*this.ratio)}burningSources(){let e=24*this.ratio;return this.fields.burningSources(e).map(e=>({point:this.camera.pixelSpace?e:this.camera.documentPoint(e),radiusPx:24,spreadSeconds:te.spreadSeconds}))}hasContact(e,t){return this.fields.contacts(n(e),t.map(e=>this.camera.particlePoint(e))).length>0}add(e,t){this.authoring.addLiquid(e,t)}syncElements(e){if(this.camera.overlay){let t=e.filter(e=>typeof SVGGeometryElement<`u`&&e.key instanceof SVGGeometryElement||typeof HTMLElement<`u`&&e.key instanceof HTMLElement&&(e.key.childElementCount>0||!!e.key.textContent?.trim())).map(e=>e.bounds);t.length&&!this.textVehicles&&(this.textVehicles=new vl,this.textVehicles.setAbsoluteViewport()),this.textVehicles?.setBounds(t),this.resize()}return this.authoring.syncElementLiquids(e)}setInitialPuddles(e){this.authoring.setInitialPuddles(e)}pourVehicle(e,t,n,r,i=`player`){if(e.mode!==`car`)return;let a=e.body.world(C(-e.car.preset.geometry.lengthM/2-.58,0)),o=h(C(-4,0),e.body.angle);this.fields.pour(t,this.camera.particlePoint(a),this.camera.particleScale(),n,this.camera.pixelSpace?C(o.x,-o.y):o,r,i)}stepVehicles(e,t,n,r,i,a,o){return bl(this.fields,e,t,n,r,i,{particlePoint:e=>this.camera.particlePoint(e),particleVelocity:e=>this.camera.pixelSpace?C(e.x*this.camera.zoom,-e.y*this.camera.zoom):{...e},documentPoint:e=>this.camera.documentPoint(e),particleScale:this.camera.particleScale(),fading:a,emitFire:o})}splatter(e,t,n,r,i,a,o,s){let c=e.tirePaint.coating(t);return this.fields.splatter(n,r,i,a,o,!1,s,c)?!0:(e.tirePaint.splatter(t,r,i,a,o,s,this.camera.particleScale()),!!c)}igniteAlong(e,t,n){this.fields.igniteAlong(e,t,n)}igniteAtLocal(e){this.fields.igniteAt(e)}pourOilPreview(e,t){this.fields.pour(`oil`,e,this.camera.particleScale(),t*6,C())}},Sl=e=>{let t=Math.sin(e*127.1+311.7)*43758.5453;return t-Math.floor(t)};function Cl(e,t,n,r,i,a,o=1){let s=t.material;e.save();let c=t.exit?.leadInM,l=c?Math.max(.05,c-Math.max(t.widthM*1.5,.25)):0,u=c?Math.max(0,Math.min(1,(c+(t.exit.fromM+t.exit.toM)*.5)/l)):1,d=o*u*u*(3-2*u);if(e.strokeStyle=t.color,e.fillStyle=t.color,e.globalAlpha=t.opacity*d,t.droplet){e.translate(r.x,r.y),e.rotate(t.angle),e.beginPath(),e.ellipse(0,0,i/2,i*t.droplet.aspect/2,0,0,Math.PI*2),e.fill(),e.restore();return}let f=r.x-n.x,p=r.y-n.y,m=Math.hypot(f,p);if(!s){e.lineWidth=i,e.lineCap=`round`,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(r.x,r.y),e.stroke(),e.restore();return}e.translate(n.x,n.y),e.rotate(m>.01?Math.atan2(p,f):t.angle);let h=t.wetness??1,g=t.slip??0,_=Math.max(1.5,s.pitchM*a),v=(t.phaseM??0)*a%_,y=t.opacity*d*s.coverage,b=Math.min(1,s.film*(.35+.65*h)+g*.3);if(t.exit){let e=Math.max(0,(t.exit.fromM+t.exit.toM)*.5),n=Math.min(1,e/t.exit.lengthM);b+=(1-b)*(1-n)*(1-n)}b>.005&&m>0&&(e.globalAlpha=y*b,e.lineWidth=i*.88,e.lineCap=t.exit?`round`:`butt`,e.beginPath(),e.moveTo(0,0),e.lineTo(m,0),e.stroke());let x=m<.01?0:_-v;for(let n=x,r=0;n<=m+.001&&r<256;n+=_,r++){let r=Math.round(((t.phaseM??0)*a+n)/_);for(let a=0;a<4;a++){let o=Sl(r*17+a*7);if(o<s.breakup*(1-h*.65))continue;let c=(a-1.5)*i*.245,l=i*(.19+o*.025),u=_*(.5+g*.35),d=(a<2?1:-1)*l*.4;e.globalAlpha=y*(.62+o*.38)*(1-b*.65),e.fillStyle=t.color,e.beginPath(),e.moveTo(n-u*.5,c-l*.5),e.lineTo(n+u*.5,c-l*.5+d),e.lineTo(n+u*.5,c+l*.5+d),e.lineTo(n-u*.5,c+l*.5),e.closePath(),e.fill(),(s.gloss>.1||s.emission>0)&&(e.strokeStyle=s.emission>.5?`#ff9b25`:s.iridescence>.15?r%3?`#7faaa3`:`#9d7d99`:`#e2e8db`,e.globalAlpha=y*h*(s.emission>.5?.7:.11+s.gloss*.16),e.lineWidth=Math.max(.2,i*.035),e.beginPath(),e.moveTo(n-u*.4,c-l*.4),e.lineTo(n+u*.4,c-l*.4+d),e.stroke()),s.grain>.1&&o>.45&&(e.globalAlpha=y*s.grain*.35,e.fillStyle=`#372b22`,e.fillRect(n+u*.1,c,Math.max(.25,i*.05),Math.max(.3,i*.1)))}}e.restore()}var X=256,wl=48,Tl=class{overPuddle;constructor(e=null){this.overPuddle=e}tiles=new Map;records=new Map;archived=0;references=0;processed=0;ratio=0;scale=0;captureState(){return{marks:u([...new Set([...this.records.values()].flat())]),processed:this.processed,scale:this.scale}}restoreState(e){this.clear(),this.scale=e.scale,this.seed(u(e.marks),e.scale),this.processed=e.processed}managedBytes(e){return this.tiles.size*(X*this.ratio)**2*4+Math.max(0,this.archived-e)*136+this.references*8}clear(){this.tiles.clear(),this.records.clear(),this.archived=0,this.references=0,this.processed=0}seed(e,t){for(let n of e)(this.overPuddle===null||!!n.overPuddle===this.overPuddle)&&this.indexMark(n,t)}draw(e,t,n,r,i,a,o,s,c,l){n<this.processed&&this.clear(),(this.ratio!==c||this.scale!==s)&&(this.tiles.clear(),this.ratio=c,this.scale=s);let u=Math.min(t.length,n-this.processed);for(let e=t.length-u;e<t.length;e++){let n=t[e];(this.overPuddle===null||!!n.overPuddle===this.overPuddle)&&this.indexMark(n,s)}if(this.processed=n,!this.archived)return;let d=Math.floor(r/X),p=Math.floor((r+a)/X),m=Math.floor(i/X),h=Math.floor((i+o)/X),g=new Set;e.save(),e.globalAlpha=l;for(let t=m;t<=h;t++)for(let n=d;n<=p;n++){let a=`${n},${t}`;g.add(a);let o=this.records.get(a);if(!o?.length)continue;let c=this.tiles.get(a);if(!c){c=this.createTile(n,t),f(`tire tile rebuilds`);for(let e of o)this.stroke(c,e,s);this.tiles.set(a,c)}f(`tire tile composites`),e.drawImage(c.canvas,n*X-r,t*X-i,X,X)}if(e.restore(),this.tiles.size>wl)for(let e of this.tiles.keys()){if(this.tiles.size<=wl)break;g.has(e)||this.tiles.delete(e)}}pruneOutside(e){for(let t of this.records.keys()){let[n,r]=t.split(`,`).map(Number);((n+1)*X<e.x||n*X>e.x+e.width||(r+1)*X<e.y||r*X>e.y+e.height)&&(this.records.delete(t),this.tiles.delete(t))}this.archived=new Set([...this.records.values()].flat()).size,this.references=[...this.records.values()].reduce((e,t)=>e+t.length,0)}indexMark(e,t){this.archived++;let n=e.widthM*Math.max(32,t)*.38+2,r=Math.floor((Math.min(e.from.x,e.point.x)-n)/X),i=Math.floor((Math.max(e.from.x,e.point.x)+n)/X),a=Math.floor((Math.min(e.from.y,e.point.y)-n)/X),o=Math.floor((Math.max(e.from.y,e.point.y)+n)/X);for(let n=a;n<=o;n++)for(let a=r;a<=i;a++){let r=`${a},${n}`,i=this.records.get(r);i||(i=[],this.records.set(r,i)),i.push(e),this.references++;let o=this.tiles.get(r);o&&this.stroke(o,e,t)}}createTile(e,t){let n=document.createElement(`canvas`);n.width=Math.ceil(X*this.ratio),n.height=Math.ceil(X*this.ratio);let r=n.getContext(`2d`);if(!r)throw Error(`Joy Ride tire marks require a 2D canvas context`);return r.setTransform(this.ratio,0,0,this.ratio,-e*X*this.ratio,-t*X*this.ratio),{canvas:n,context:r}}stroke(e,t,n){f(`tire mark strokes`);let r=e.context;Cl(r,t,t.from,t.point,t.widthM*n*.76,n)}},El=class{ground=new Tl;dry=new Map;wet=new Map;seed(e,t){this.ground.seed(e,t)}forgetVehicle(e){this.dry.delete(e),this.wet.delete(e)}captureState(){return{ground:this.ground.captureState(),dry:[...this.dry].map(([e,t])=>[e,t.captureState()]),wet:[...this.wet].map(([e,t])=>[e,t.captureState()])}}restoreState(e){this.ground.restoreState(e.ground),this.dry=new Map(e.dry.map(([e,t])=>{let n=new Tl(!1);return n.restoreState(t),[e,n]})),this.wet=new Map(e.wet.map(([e,t])=>{let n=new Tl(!0);return n.restoreState(t),[e,n]}))}get managedBytes(){return this.ground.managedBytes(0)+[...this.dry.values(),...this.wet.values()].reduce((e,t)=>e+t.managedBytes(0),0)}clear(){this.ground.clear(),this.dry.clear(),this.wet.clear()}pruneOutside(e){for(let t of[...this.dry.values(),...this.wet.values()])t.pruneOutside(e)}draw(e,t,n,r){let{pixelSpace:i,scroll:a,width:o,height:s,particleScale:c,rasterRatio:l,zoom:u,effectsAlpha:d,screen:f}=r;if(e.save(),e.lineCap=`round`,i){n||this.ground.draw(e,[],0,a.x,a.y,o,s,c,l,d);let r=n?this.wet:this.dry;for(let i of t){let t=r.get(i.id);t||(t=new Tl(n),r.set(i.id,t)),t.draw(e,i.tirePaint.marks,i.tirePaint.totalMarks,a.x,a.y,o,s,c,l,d)}}else for(let r of t)for(let t of r.tirePaint.marks){if(!!t.overPuddle!==n)continue;let r=f(t.point),i=f(t.from);(r.x<-20||r.x>o+20||r.y<-20||r.y>s+20)&&(i.x<-20||i.x>o+20||i.y<-20||i.y>s+20)||Cl(e,t,i,r,t.widthM*c*u*.76,c*u,d)}e.restore()}};function Dl(e,t,n,r){let i=x(n,t),a=m(i);if(a<1e-5)return;let o=v(i,1/a),s=e.widthPx,c=Math.max(.055*(s/e.widthM),s*.4),l=e.nextStamp,u=0;for(;l<=a&&u++<80;){let n=C(-o.y,o.x),i=S(S(t,v(o,l)),v(n,(Math.random()-.5)*s*.04));e.stamps.push({point:i,direction:o,length:c*(.78+Math.random()*.14),opacity:b(.57+r*.26+(Math.random()-.5)*.12,.3,1),shoulder:(Math.random()-.5)*.06}),l+=c}e.nextStamp=Math.max(0,l-a)}function Ol(e,t,n){if(e.contactStamps>=48)return;let r=e.widthPx,i=C(-n.y,n.x);for(let a=0;a<2;a++)e.stamps.push({point:S(t,S(v(n,(Math.random()-.5)*r*1.4),v(i,(Math.random()-.5)*r*.2))),direction:n,length:r*(.3+Math.random()*.18),opacity:.35+Math.random()*.25,shoulder:(Math.random()-.5)*.06});e.contactStamps+=2}function kl(e,t,n,r,i,a){if(t.length<2)return;let o=t.map((e,r)=>{let i=t[Math.max(0,r-1)],a=t[Math.min(t.length-1,r+1)],o=x(a,i),s=Math.max(1e-5,m(o));return C(e.x-o.y/s*n,e.y+o.x/s*n)});e.beginPath(),e.moveTo(o[0].x,o[0].y);for(let t=1;t<o.length-1;t++){let n=v(S(o[t],o[t+1]),.5);e.quadraticCurveTo(o[t].x,o[t].y,n.x,n.y)}e.lineTo(o[o.length-1].x,o[o.length-1].y),e.strokeStyle=a,e.globalAlpha=i,e.lineWidth=r,e.stroke()}function Al(e,t,n,r,i,a){t.road&&(r=Ks.dark);let o=n?t.points.map(a.screen):t.points,s=Math.max(2,(a.pixelSpace?t.widthPx:t.widthM*a.zoom)*.72);kl(e,o,0,s*.92,.075*t.opacity*r.alphaScale*i,r.ink),kl(e,o,-s*.29,s*.22,.17*t.opacity*r.alphaScale*i,r.ink),kl(e,o,s*.29,s*.22,.17*t.opacity*r.alphaScale*i,r.ink),e.fillStyle=r.ink;for(let o of t.stamps){let c=n?a.screen(o.point):o.point;if(n&&(c.x<-12||c.x>a.width+12||c.y<-12||c.y>a.height+12))continue;let l=a.pixelSpace?o.direction:C(o.direction.x,-o.direction.y),u=o.length*(a.pixelSpace?1:a.zoom);e.save(),e.translate(c.x,c.y),e.rotate(Math.atan2(l.y,l.x)),e.globalAlpha=.28*t.opacity*o.opacity*r.alphaScale*i;let d=s*.2,f=Math.max(1,u*.82),p=s*(.29+o.shoulder);e.beginPath(),e.roundRect(-f/2,-p-d/2,f,d,Math.min(.7,d*.2)),e.roundRect(-f/2,p-d/2,f,d,Math.min(.7,d*.2)),e.fill(),e.restore()}}var Z=256,jl=48,Ml=class{records=new Map;tiles=new Map;paths=0;pathBytes=0;references=0;ratio=0;theme=``;captureState(){return u([...new Set([...this.records.values()].flat())])}restoreState(e,t){this.clear();for(let n of u(e))this.add(n,t)}get managedBytes(){return this.tiles.size*(Z*this.ratio)**2*4+this.pathBytes+this.references*8}clear(){this.records.clear(),this.tiles.clear(),this.paths=0,this.pathBytes=0,this.references=0}add(e,t){this.paths++,this.pathBytes+=96+e.points.length*24+e.stamps.length*64;let n=Math.max(2,e.widthPx)*2,r=Math.floor((e.bounds.left-n)/Z),i=Math.floor((e.bounds.right+n)/Z),a=Math.floor((e.bounds.bottom-n)/Z),o=Math.floor((e.bounds.top+n)/Z);for(let n=a;n<=o;n++)for(let a=r;a<=i;a++){let r=`${a},${n}`,i=this.records.get(r);i||(i=[],this.records.set(r,i)),i.push(e),this.references++;let o=this.tiles.get(r);o&&t(o.context,e)}}draw(e,t,n,r,i,a,o,s,c){if(!this.paths)return;(this.ratio!==a||this.theme!==o)&&(this.tiles.clear(),this.ratio=a,this.theme=o);let l=Math.floor(t/Z),u=Math.floor((t+r)/Z),d=Math.floor(n/Z),p=Math.floor((n+i)/Z),m=new Set;e.save(),e.globalAlpha=s;for(let r=d;r<=p;r++)for(let i=l;i<=u;i++){let a=`${i},${r}`,o=this.records.get(a);if(!o?.length)continue;m.add(a);let s=this.tiles.get(a);if(!s){s=this.createTile(i,r),f(`skid tile rebuilds`);for(let e of o)c(s.context,e);this.tiles.set(a,s)}f(`skid tile composites`),e.drawImage(s.canvas,i*Z-t,r*Z-n,Z,Z)}if(e.restore(),this.tiles.size>jl)for(let e of this.tiles.keys()){if(this.tiles.size<=jl)break;m.has(e)||this.tiles.delete(e)}}pruneOutside(e){for(let t of this.records.keys()){let[n,r]=t.split(`,`).map(Number);((n+1)*Z<e.x||n*Z>e.x+e.width||(r+1)*Z<e.y||r*Z>e.y+e.height)&&(this.records.delete(t),this.tiles.delete(t))}let t=new Set([...this.records.values()].flat());this.paths=t.size,this.references=[...this.records.values()].reduce((e,t)=>e+t.length,0),this.pathBytes=[...t].reduce((e,t)=>e+96+t.points.length*24+t.stamps.length*64,0)}createTile(e,t){let n=document.createElement(`canvas`);n.width=Math.ceil(Z*this.ratio),n.height=Math.ceil(Z*this.ratio);let r=n.getContext(`2d`);if(!r)throw Error(`Joy Ride skid tiles require a 2D canvas context`);return r.setTransform(this.ratio,0,0,this.ratio,-e*Z*this.ratio,-t*Z*this.ratio),r.lineCap=`round`,r.lineJoin=`round`,{canvas:n,context:r}}},Nl=class{clock=0;time=0;presetId=null;previous=new Map;paths=[];tiles=new Ml;revealAlpha=1;pendingReveal=new Set;captureState(){let e=u({previous:this.previous,paths:this.paths});return{clock:this.clock,time:this.time,presetId:this.presetId,previous:e.previous,paths:e.paths,revealAlpha:this.revealAlpha,pendingRevealIndices:this.paths.flatMap((e,t)=>this.pendingReveal.has(e)?[t]:[]),tiles:this.tiles.captureState()}}restoreState(e,t,n){this.clock=e.clock,this.time=e.time,this.presetId=e.presetId;let r=u({previous:e.previous,paths:e.paths});this.previous=r.previous,this.paths=r.paths,this.revealAlpha=e.revealAlpha,this.pendingReveal=new Set(e.pendingRevealIndices.map(e=>this.paths[e]));let i=Ks[n?`dark`:`light`];this.tiles.restoreState(e.tiles,(e,n)=>Al(e,n,!1,i,1,t))}get managedBytes(){return this.paths.reduce((e,t)=>e+96+t.points.length*24+t.stamps.length*64,0)+this.tiles.managedBytes}clear(){this.clock=0,this.time=0,this.presetId=null,this.previous.clear(),this.paths=[],this.revealAlpha=1,this.pendingReveal.clear(),this.tiles.clear()}beginReveal(e,t){this.setRevealAlpha(1,e,t),this.stop(e,t),this.revealAlpha=0}setRevealAlpha(e,t,n){let r=b(e,0,1);if((r!==this.revealAlpha||this.pendingReveal.size!==0)&&(this.revealAlpha=r,!(this.revealAlpha<1))){for(let e of this.pendingReveal)this.rasterize(e,t,n);this.pendingReveal.clear()}}fade(){this.previous.clear()}stop(e,t,n=!1){for(let{path:n}of this.previous.values())this.finish(n,e,t);this.previous.clear(),n&&(this.clock=0)}pruneOutside(e){this.tiles.pruneOutside(e)}step(e,t,n,r,i){this.time+=e,this.clock+=e,!(this.clock<1/30)&&(this.clock%=1/30,this.presetId!==t.car.preset.id&&(this.stop(i.view,i.dark),this.presetId=t.car.preset.id),t.car.tires.forEach((e,a)=>{let o=this.previous.get(a);if(r(a)){o&&this.finish(o.path,i.view,i.dark),this.previous.delete(a);return}let s=i.project(t.body.world(e.local)),c=n&&!e.front;if(!e.skidding&&!c){o&&this.finish(o.path,i.view,i.dark),this.previous.delete(a);return}let l=i.project(t.body.world(S(e.local,C(-t.car.preset.geometry.tireLengthM*.8)))),u=!i.dark&&i.roadAt(e,s),d=o&&o.path.road===u&&this.time-o.time<.18&&o.path.stamps.length<(i.pixelSpace?64:320)?o.path:{road:u,points:e.spinning?[l,s]:i.pixelSpace&&o&&o.path.stamps.length>=64?[o.path.points[o.path.points.length-1],s]:[s],stamps:[],contactStamps:0,nextStamp:0,widthM:t.car.preset.geometry.tireWidthM,widthPx:t.car.preset.geometry.tireWidthM*i.scale,opacity:e.spinning?1:c?.72:b(.25+e.slip*.55+e.heat*.2,.3,1),bounds:{left:Math.min(l.x,s.x),right:Math.max(l.x,s.x),bottom:Math.min(l.y,s.y),top:Math.max(l.y,s.y)}};if(d!==o?.path)o&&this.finish(o.path,i.view,i.dark),this.paths.push(d),e.spinning?Dl(d,l,s,1):d.points.length>1&&Dl(d,d.points[0],s,c?.72:e.slip);else{let n=d.points[d.points.length-1];m(x(s,n))>(i.pixelSpace?.05:.001)?(Dl(d,n,s,e.spinning?1:c?.72:e.slip),d.points.push(s),d.bounds.left=Math.min(d.bounds.left,s.x),d.bounds.right=Math.max(d.bounds.right,s.x),d.bounds.bottom=Math.min(d.bounds.bottom,s.y),d.bounds.top=Math.max(d.bounds.top,s.y)):e.spinning&&Ol(d,s,C(Math.cos(t.body.angle),i.pixelSpace?-Math.sin(t.body.angle):Math.sin(t.body.angle)))}this.previous.set(a,{path:d,time:this.time})}))}finish(e,t,n){this.revealAlpha<1?this.pendingReveal.add(e):this.rasterize(e,t,n)}rasterize(e,t,n){if(!t.pixelSpace)return;let r=Ks[n?`dark`:`light`];this.tiles.add(e,(e,n)=>Al(e,n,!1,r,1,t));let i=this.paths.indexOf(e);i>=0&&this.paths.splice(i,1)}draw(e,t){let{pixelSpace:n,scroll:r,width:i,height:a,ratio:o,dark:s,alpha:c,visible:l,view:u}=t,d=Ks[s?`dark`:`light`];performance.now(),n&&this.tiles.draw(e,r.x,r.y,i,a,o,s?`dark`:`light`,c,(e,t)=>Al(e,t,!1,d,1,u)),performance.now();for(let t of this.paths){let r=(n?t.widthPx:t.widthM*u.zoom)*2;t.bounds.right<l.left-r||t.bounds.left>l.right+r||t.bounds.top<l.bottom-r||t.bounds.bottom>l.top+r||Al(e,t,!0,d,c*this.revealAlpha,u)}}},Pl={crashLow:{amplitudePx:.65,durationMs:85,frequencyHz:17},crashMedium:{amplitudePx:1.35,durationMs:125,frequencyHz:19},crashFast:{amplitudePx:2.35,durationMs:165,frequencyHz:21},rocketExplosion:{amplitudePx:2.8,durationMs:190,frequencyHz:16},lightning:{amplitudePx:3.1,durationMs:210,frequencyHz:26},combustibleExplosion:{amplitudePx:3.3,durationMs:215,frequencyHz:17}};function Fl(e){return!Number.isFinite(e)||e<.8?null:e<3.5?`crashLow`:e<8?`crashMedium`:`crashFast`}var Il=class{enabled=!0;profiles={...Pl};impulses=[];lastTriggered=new Map;sequence=0;captureState(){return{at:performance.now(),data:u({enabled:this.enabled,profiles:this.profiles,impulses:this.impulses,lastTriggered:this.lastTriggered,sequence:this.sequence})}}restoreState(e){let t=u(e.data);this.enabled=t.enabled,this.profiles=t.profiles,this.impulses=t.impulses,this.lastTriggered=t.lastTriggered,this.sequence=t.sequence;let n=performance.now()-e.at;for(let e of this.impulses)e.startedAt+=n;for(let[e,t]of this.lastTriggered)this.lastTriggered.set(e,t+n)}get active(){return this.impulses.length>0}setEnabled(e){this.enabled=e,e||this.reset()}setProfiles(e){let t={...Pl};if(e)for(let n of Object.keys(t)){let r=e[n];if(!r)continue;let i=t[n],a=(e,t,n,r)=>e!==void 0&&Number.isFinite(e)?Math.max(n,Math.min(r,e)):t;t[n]={amplitudePx:a(r.amplitudePx,i.amplitudePx,0,6),durationMs:a(r.durationMs,i.durationMs,25,300),frequencyHz:a(r.frequencyHz,i.frequencyHz,5,35)}}this.profiles=t}reset(){this.impulses.length=0,this.lastTriggered.clear()}trigger(e,t=1,n=performance.now()){if(!this.enabled||!Number.isFinite(t)||t<=0)return;let r=this.profiles[e];!r||r.amplitudePx<=0||n-(this.lastTriggered.get(e)??-1/0)<55||(this.lastTriggered.set(e,n),this.impulses.push({event:e,startedAt:n,profile:r,amplitudePx:Math.min(5,r.amplitudePx*Math.min(2,t)),phase:++this.sequence*2.399963}),this.impulses.length>4&&this.impulses.shift())}sample(e){if(!this.enabled||!this.impulses.length)return{x:0,y:0};let t=0,n=0;for(let r=this.impulses.length-1;r>=0;r--){let i=this.impulses[r],a=Math.max(0,e-i.startedAt);if(a>=i.profile.durationMs){this.impulses.splice(r,1);continue}let o=(1-a/i.profile.durationMs)**2,s=a*i.profile.frequencyHz*Math.PI*2/1e3,c=i.amplitudePx*o;t+=Math.sin(s+i.phase)*c,n+=Math.sin(s*1.17+i.phase*.7+.8)*c*.72}return{x:Math.max(-4,Math.min(4,t)),y:Math.max(-4,Math.min(4,n))}}};function Ll(e,t,n,r,i,a,o=!1){let s=!t.front&&(t.spinning||o);if(!t.skidding&&!o)return null;let c=s?.38+.62*t.heat:b(t.slip*(.22+t.heat*.78),0,1);if(c<.05)return null;let l=m(e.body.velocity),u=l>.1?v(e.body.velocity,-1/l):h(C(-1),e.body.angle),d=C(u.x,-u.y),f=C(Math.cos(e.body.angle),-Math.sin(e.body.angle)),p=C(-f.y,f.x),g=Math.sign(t.local.y)||1;return{point:a(e.body.world(S(t.local,C(0,g*e.car.preset.geometry.tireWidthM*.53)))),amount:n*(t.front?3:s?12:6.5)*c,flow:S(v(r,s?.08:.22),S(v(d,(s?110+Math.min(18,Math.abs(t.wheelSurfaceSpeedMps)*3):125)*c),v(p,g*(s?64:45)*c))),radiusPx:(s?.8:.55+t.heat*.16)*i,swirlPx:g*(s?85:105)*c,strength:c,burnout:s}}function Rl(e,t,n,r,i,a,o,s=!1){let c=e.sim;c.car.tires.forEach((l,u)=>{let d=Ll(c,l,r,a,o.zoom,o.particlePoint,s&&!l.front);if(!d)return;let f=c.body.world(l.local),p=hl(d.burnout,c.body.angle,l.angle,c.body.velocityAt(f),i),h=o.spray(e,u,n+u,t[u].point,o.particleVelocity(p),t[u].radiusPx,r*(d.burnout?85:48)*d.strength,b(.75+l.slipSpeedMps/12+m(c.body.velocityAt(f))/28,.8,1.9));o.smoke?.({point:d.point,amount:h?d.amount*.3:d.amount,flow:d.flow,radiusPx:d.radiusPx,swirlPx:d.swirlPx})})}var zl=class{canvas=document.createElement(`canvas`);mask=document.createElement(`canvas`);gl=this.canvas.getContext(`webgl2`,{alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0});program=null;texture=null;startedAt=-1/0;duration=680;constructor(){let e=this.gl;e&&(this.program=is(e,`#version 300 es
|
|
840
|
-
precision highp float;
|
|
841
|
-
out vec2 uv;
|
|
842
|
-
void main() {
|
|
843
|
-
vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
|
|
844
|
-
uv = p;
|
|
845
|
-
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
|
|
846
|
-
}`,`#version 300 es
|
|
847
|
-
precision highp float;
|
|
848
|
-
in vec2 uv;
|
|
849
|
-
out vec4 color;
|
|
850
|
-
uniform sampler2D mask;
|
|
851
|
-
uniform vec2 pixel;
|
|
852
|
-
uniform float progress;
|
|
853
|
-
uniform bool dark;
|
|
854
|
-
void main() {
|
|
855
|
-
float shape = texture(mask, uv).a;
|
|
856
|
-
float nearShape = max(max(texture(mask, uv + vec2(pixel.x * 3.0, 0.0)).a,
|
|
857
|
-
texture(mask, uv - vec2(pixel.x * 3.0, 0.0)).a),
|
|
858
|
-
max(texture(mask, uv + vec2(0.0, pixel.y * 3.0)).a,
|
|
859
|
-
texture(mask, uv - vec2(0.0, pixel.y * 3.0)).a));
|
|
860
|
-
float rim = max(0.0, nearShape - shape);
|
|
861
|
-
float sweep = exp(-pow((fract((uv.x + uv.y * 0.28) * 4.0 - progress * 2.2) - 0.5) * 10.0, 2.0));
|
|
862
|
-
float pulse = sin(3.14159265 * progress);
|
|
863
|
-
float alpha = clamp((shape * (0.15 + sweep * 0.6) + rim * 0.75) * pulse, 0.0, 0.78);
|
|
864
|
-
vec3 tint = dark ? vec3(1.0, 0.86, 0.55) : vec3(0.72, 0.38, 0.08);
|
|
865
|
-
color = vec4(tint, alpha);
|
|
866
|
-
}`,`Object glint`),this.texture=e.createTexture(),this.texture||(U(e,this.program),this.program=null))}trigger(e,t,n,r){let i=this.gl;if(!i||!this.program||!this.texture)return;this.canvas.width=this.mask.width=Math.ceil(e*n),this.canvas.height=this.mask.height=Math.ceil(t*n);let a=this.mask.getContext(`2d`);a&&(a.setTransform(n,0,0,n,0,0),a.clearRect(0,0,e,t),r(a),i.bindTexture(i.TEXTURE_2D,this.texture),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!0),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,this.mask),this.startedAt=performance.now())}draw(e,t,n,r){let i=this.gl,a=(performance.now()-this.startedAt)/this.duration;!i||!this.program||!this.texture||a<0||a>=1||(i.viewport(0,0,this.canvas.width,this.canvas.height),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),i.useProgram(this.program),i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.texture),i.uniform1i(H(this.program,`mask`),0),ss(this.program,{pixel:[1/this.canvas.width,1/this.canvas.height],progress:a,dark:Number(r)}),i.drawArrays(i.TRIANGLES,0,3),f(`composited megapixels`,this.canvas.width*this.canvas.height/1e6),e.drawImage(this.canvas,0,0,t,n))}dispose(){this.gl&&(this.texture&&this.gl.deleteTexture(this.texture),this.program&&U(this.gl,this.program),this.texture=null,this.program=null)}};function Bl(e,t,n=!1){if(!t)return{...e};let r=e.x*t.scaleX,i=e.y*t.scaleY,a=Math.cos(t.angle),o=Math.sin(t.angle);return{x:(n?0:t.x)+r*a-i*o,y:(n?0:t.y)+r*o+i*a}}function Vl(e,t,n){if(!n)return;let r=Math.cos(n.angle),i=Math.sin(n.angle);for(let a of[0,2]){let o=e[t+a]*n.scaleX,s=e[t+a+1]*n.scaleY;e[t+a]=n.x+o*r-s*i,e[t+a+1]=n.y+o*i+s*r}e[t+4]*=n.width,e[t+8]*=n.scaleX,e[t+9]*=n.scaleX}var Q=(e,t,n)=>Math.max(t,Math.min(n,e)),Hl=(e,t)=>Number.isFinite(e)?e:t,$=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y);function Ul(e,t){let n=!1;for(let r=0,i=e.length-1;r<e.length;i=r++){let a=e[r],o=e[i];a.y>t.y!=o.y>t.y&&t.x<(o.x-a.x)*(t.y-a.y)/(o.y-a.y)+a.x&&(n=!n)}return n}function Wl(e,t,n){let r=n.x-t.x,i=n.y-t.y,a=Q(((e.x-t.x)*r+(e.y-t.y)*i)/Math.max(1e-9,r*r+i*i),0,1);return Math.hypot(e.x-t.x-a*r,e.y-t.y-a*i)}function Gl(e,t,n){let r=t.x-e.x,i=t.y-e.y;for(let t=0,a=n.length-1;t<n.length;a=t++){let o=n[a],s=n[t],c=s.x-o.x,l=s.y-o.y,u=r*l-i*c;if(Math.abs(u)<1e-9)continue;let d=((o.x-e.x)*l-(o.y-e.y)*c)/u,f=((o.x-e.x)*i-(o.y-e.y)*r)/u;if(d>0&&d<1&&f>=0&&f<=1)return!0}return!1}function Kl(e,t,n){if(e.kind===`point`)return!0;if(e.kind===`surface`)return!Gl(t,n,e.points)&&!(e.holes??[]).some(e=>Gl(t,n,e));let r=Math.max(8,Math.ceil($(t,n)/.75));for(let i=1;i<r;i++)if(!ql(e,{x:t.x+(n.x-t.x)*i/r,y:t.y+(n.y-t.y)*i/r}))return!1;return!0}function ql(e,t){if(e.kind===`point`)return $(t,e.center)<=e.radius;if(e.kind===`surface`)return Ul(e.points,t)&&!(e.holes??[]).some(e=>Ul(e,t));let n=e.points.length;for(let r=1;r<n;r++)if(Wl(t,e.points[r-1],e.points[r])<=e.width/2)return!0;return!!e.closed&&n>1&&Wl(t,e.points[n-1],e.points[0])<=e.width/2}function Jl(e){if(e.kind===`point`)return{x:e.center.x-e.radius,y:e.center.y-e.radius,width:e.radius*2,height:e.radius*2};let t=e.kind===`path`?e.width/2:0,n=1/0,r=1/0,i=-1/0,a=-1/0;for(let t of e.points)n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x),a=Math.max(a,t.y);return{x:n-t,y:r-t,width:i-n+t*2,height:a-r+t*2}}function Yl(e,t){if(e.kind===`point`)return Math.max(0,e.radius-$(t,e.center));let n=1/0,r=(e,r)=>{for(let r=1;r<e.length;r++)n=Math.min(n,Wl(t,e[r-1],e[r]));r&&e.length>1&&(n=Math.min(n,Wl(t,e.at(-1),e[0])))};if(e.kind===`path`)return r(e.points,!!e.closed),Math.max(0,e.width/2-n);r(e.points,!0);for(let t of e.holes??[])r(t,!0);return n}var Xl=class{onDischarge;onEmission;emissionFrame;setEmissionFrame(e){this.emissionFrame=e?{...e}:void 0}nodes=[];ionization=new Float32Array;ionScratch=new Float32Array;sources=[];targets=[];strokes=[];sourceCursor=0;randomState;nextStrike=0;accumulator=0;elapsed=0;sparkBudget=0;disposed=!1;shape;options;_spacing=10;constructor(e,t={}){this.options={seed:1,spacing:9,maxNodes:1800,strikesPerSecond:5,branching:.6,intensity:1,corona:0,nearbyTargets:!1,...t},this.randomState=this.options.seed>>>0||1,this.shape=e.shape,this.setDomain(e)}random(){let e=this.randomState;return e^=e<<13,e^=e>>>17,e^=e<<5,this.randomState=e>>>0,this.randomState/4294967296}configure(e){Object.assign(this.options,e)}get stats(){return{nodes:this.nodes.length,segments:this.strokes.reduce((e,t)=>e+t.segments.length,0),strokes:this.strokes.length,spacing:this._spacing,growing:this.strokes.filter(e=>!e.connected).length,ionizedNodes:this.ionization.reduce((e,t)=>e+ +(t>.08),0)}}setDomain(e){if(this.disposed)return;this.shape=e.shape,this.nodes=[],this.strokes=[],this.sources=[],this.targets=[],this.nextStrike=0,this.accumulator=0,this.ionization=new Float32Array;let t=Jl(e.shape);if(!Number.isFinite(t.width)||!Number.isFinite(t.height)||t.width<=0||t.height<=0)return;let n=Q(Math.floor(Hl(this.options.maxNodes,1800)),64,4096),r=Math.max(3,Hl(this.options.spacing,9),Math.sqrt(t.width*t.height/n)*1.1,t.width/512,t.height/512);this._spacing=r;let i=Math.ceil(t.width/r)+1,a=Math.ceil(t.height/r)+1,o=new Int32Array(i*a).fill(-1);for(let e=0;e<a;e++)for(let a=0;a<i;a++){let s={x:t.x+(a+.2+this.random()*.6)*r,y:t.y+(e+.2+this.random()*.6)*r};this.nodes.length>=n||!ql(this.shape,s)||(o[e*i+a]=this.nodes.length,this.nodes.push({...s,links:[]}))}for(let e=0;e<a;e++)for(let t=0;t<i;t++){let n=o[e*i+t];if(n<0)continue;let r=this.nodes[n];for(let n=-1;n<=1;n++)for(let s=-1;s<=1;s++){let c=t+s,l=e+n;if(!s&&!n||c<0||l<0||c>=i||l>=a)continue;let u=o[l*i+c];u<0||Kl(this.shape,r,this.nodes[u])&&r.links.push(u)}}this.ionization=new Float32Array(this.nodes.length),this.ionScratch=new Float32Array(this.nodes.length),this.setElectrodes(e.sources,e.targets)}setElectrodes(e,t){this.disposed||(this.sources=e.map(e=>this.closest(e)).filter(e=>e>=0),this.sourceCursor=0,t&&(this.targets=t.map(e=>this.closest(e)).filter(e=>e>=0)))}closest(e){let t=-1,n=1/0;for(let r=0;r<this.nodes.length;r++){let i=$(this.nodes[r],e);i<n&&(t=r,n=i)}return t}relax(e,t){for(let n=0;n<t;n++){let t=e.potential,n=e.scratch;for(let r=0;r<this.nodes.length;r++){if(r===e.target){n[r]=1;continue}if(e.grounded[r]){n[r]=0;continue}let i=this.nodes[r].links,a=0;for(let e=0;e<i.length;e++)a+=t[i[e]];n[r]=i.length?a/i.length:0}e.potential=n,e.scratch=t}}strike(){if(this.strokes.length>=10||!this.nodes.length||!this.sources.length||!this.targets.length)return;let e=this.sources[this.sourceCursor];this.sourceCursor=(this.sourceCursor+1)%this.sources.length;let t=0;for(let n of this.targets)t=Math.max(t,$(this.nodes[e],this.nodes[n]));let n=this.targets.filter(n=>{let r=$(this.nodes[e],this.nodes[n]);return this.options.nearbyTargets?r>Math.max(this._spacing*3,t*.16)&&r<t*.65:r>=t*.6}),r=n.length?n:this.targets,i=r[Math.floor(this.random()*r.length)];if(i===e&&(i=this.targets.find(t=>t!==e)??e),i===e)return;let a=this.nodes.length,o=new Int32Array(a).fill(-1),s=new Int32Array(a);o[i]=0,s[0]=i;let c=0,l=1;for(;c<l;){let e=s[c++];for(let t of this.nodes[e].links)o[t]<0&&(o[t]=o[e]+1,s[l++]=t)}if(o[e]<0)return;let u=new Float32Array(a),d=new Uint8Array(a);d[e]=1;let f=Math.max(1,o[e]);for(let e=0;e<a;e++)u[e]=o[e]<0?0:Q(1-o[e]/(f+2),.01,1);let p=this.vertex(this.nodes[e],-1,1,0,e,!1),m={frame:this.emissionFrame?{...this.emissionFrame}:void 0,segments:[],vertices:[p],fronts:[{at:e,vertex:0,distance:0,branch:!1,steps:0,limit:256,budget:0,energy:1,diffuse:!1}],potential:u,scratch:new Float32Array(a),grounded:d,hops:o,target:i,source:e,age:0,life:.75+this.random()*.35,seed:this.random(),connected:!1,noise:0,drive:.6,pulse:0,sparkTimer:.02};m.fronts[0].diffuse=this.random()<this.options.corona*.45,this.relax(m,12),this.strokes.push(m)}vertex(e,t,n,r,i,a){return{position:{x:e.x,y:e.y},rest:{x:e.x,y:e.y},velocity:{x:0,y:0},parent:t,children:[],base:n,charge:0,arc:r,node:i,diffuse:a,clearance:Yl(this.shape,e),motionRadius:3}}choose(e,t){let n=this.nodes[t.at].links,r=n=>{if(e.grounded[n]||e.hops[n]<0||!t.branch&&e.hops[n]>=e.hops[t.at])return 0;let r=e.hops[t.at]-e.hops[n];if(t.branch&&t.direction){if(n===e.target)return 0;let r=this.nodes[n].x-this.nodes[t.at].x,i=this.nodes[n].y-this.nodes[t.at].y,a=(r*t.direction.x+i*t.direction.y)/Math.max(.001,Math.hypot(r,i));return Math.max(.02,a+.25)**2*(.6+e.potential[n]*.4)}return Math.max(.015,e.potential[n])**1.7*(r>0?3.5:.25)*(1+this.ionization[n]*4)},i=0;for(let e of n)i+=r(e);if(!i)return-1;let a=this.random()*i;for(let e of n)if(a-=r(e),a<=0&&r(e)>0)return e;return-1}grow(e,t){for(let n=e.fronts.length-1;n>=0;n--){let r=e.fronts[n];r.budget+=t*(r.branch?1250:3200);let i=0;for(;r.budget>=this._spacing*.55&&i++<8;){let t=this.choose(e,r);if(t<0||r.steps>=r.limit||e.segments.length>=690){e.fronts.splice(n,1);break}let i=this.nodes[r.at],a=this.nodes[t],o=$(i,a);if(r.budget<o)break;r.budget-=o;let s={x:-(a.y-i.y)/o,y:(a.x-i.x)/o},c=r.vertex,l=Math.max(2,Math.ceil(o/4)),u=(this.random()-.5)*Math.min(3,this._spacing*.3);for(let n=1;n<=l;n++){let d=n/l,f={x:i.x+(a.x-i.x)*d,y:i.y+(a.y-i.y)*d},p={x:f.x+s.x*Math.sin(d*Math.PI)*u,y:f.y+s.y*Math.sin(d*Math.PI)*u},m=e.vertices[c].position,h=ql(this.shape,p)&&Kl(this.shape,e.vertices[c].rest,p)&&Kl(this.shape,m,p)&&Kl(this.shape,p,a)?p:f,g=r.energy*(r.branch?Math.max(.08,1-r.steps/r.limit):1),_=this.vertex(h,c,g,r.distance+o*d,t,r.diffuse),v=e.vertices[c],y=$(v.rest,_.rest),b={x:(v.rest.x+h.x)/2,y:(v.rest.y+h.y)/2},x=Math.max(0,Math.min(v.clearance,_.clearance,Yl(this.shape,b))-y/4)*.45;v.motionRadius=Math.min(v.motionRadius,x),_.motionRadius=Math.min(3,x);let S=e.vertices.length;e.vertices[c].children.push(S),e.vertices.push(_),e.segments.push({start:m,end:_.position,energy:g,distance:e.vertices[c].arc,length:$(m,h),branch:r.branch}),c=S}if(r.vertex=c,r.distance+=o,r.at=t,r.steps++,e.grounded[t]=1,this.ionization[t]=Math.min(1,this.ionization[t]+.28),!r.branch&&r.steps%3==0&&this.relax(e,2),(!r.branch||this.options.branching>1&&r.energy>.2)&&r.steps>2&&e.fronts.length<9&&this.random()<this.options.branching*(r.branch?.08:.26)){let n=this.random()<.5?-1:1,l=this.options.branching>1?{x:s.x*n*.85+(a.x-i.x)/o*.35,y:s.y*n*.85+(a.y-i.y)/o*.35}:void 0;e.fronts.push({direction:l,at:t,vertex:c,distance:r.distance,branch:!0,steps:0,limit:2+Math.floor(this.random()*(7+Math.max(0,this.options.branching-1)*10)),budget:0,energy:r.energy*(.45+this.random()*.2),diffuse:this.random()<this.options.corona})}if(t===e.target){e.fronts.splice(n,1),!r.branch&&!e.connected&&(e.connected=!0,e.pulse=.2,this.onDischarge?.({source:Bl(this.nodes[e.source],e.frame),target:Bl(this.nodes[e.target],e.frame),segments:e.frame?e.segments.map(t=>({...t,start:Bl(t.start,e.frame),end:Bl(t.end,e.frame)})):e.segments}));break}}}}advance(e,t){e.age+=t,this.grow(e,t),e.noise+=-e.noise*8*t+(this.random()-.5)*Math.sqrt(t)*1.6,e.pulse*=Math.exp(-t*18);let n=.57+.15*Math.sin(this.elapsed*3.4+e.seed*17)+e.noise*.24+e.pulse;e.drive+=(Q(n,.25,1)-e.drive)*(1-Math.exp(-t*12));let r=Math.exp(-t*11),i=1-Math.exp(-t*36);for(let n=0;n<e.vertices.length;n++){let a=e.vertices[n],o=.9+.1*Math.sin(this.elapsed*15-a.arc*.035+e.seed*9),s=a.parent<0?e.drive:e.vertices[a.parent].charge,c=(e.drive*.78+s*.22)*a.base*o;if(a.charge+=(c-a.charge)*i,this.options.corona>0&&(this.ionization[a.node]=Math.min(1,this.ionization[a.node]+t*a.charge*.8)),a.parent<0||a.node===e.target)continue;let l=a.position,u=a.rest,d=a.velocity,f=u.x*.031,p=u.y*.031,m=this.elapsed,h=Math.sin(f+m*.8)*Math.cos(p-m*1.1)+.4*Math.cos(f*2.7-p*1.9+m*2.6),g=-Math.cos(f+m*.8)*Math.sin(p-m*1.1)+.4*Math.sin(f*2.7-p*1.9+m*2.6);d.x=(d.x+((u.x-l.x)*65+h*130)*t)*r,d.y=(d.y+((u.y-l.y)*65+g*130)*t)*r;let _={x:l.x+d.x*t,y:l.y+d.y*t},v=_.x-u.x,y=_.y-u.y,b=Math.hypot(v,y);b>a.motionRadius&&b>0?(l.x=u.x+v/b*a.motionRadius,l.y=u.y+y/b*a.motionRadius,d.x*=.4,d.y*=.4):(l.x=_.x,l.y=_.y)}if(e.sparkTimer-=t,e.sparkTimer<=0&&this.sparkBudget>=1&&e.vertices.length>3&&e.age<e.life-.15){let t=e.vertices[Math.floor(this.random()*(e.vertices.length-1))+1];if(t.charge>.12){let n=e.vertices[t.parent].position,r=t.position.x-n.x,i=t.position.y-n.y,a=this.random()<.5?-1:1;this.onEmission?.({point:Bl(t.position,e.frame),direction:Bl({x:-i*a,y:r*a},e.frame,!0),strength:.2+t.charge*.35}),this.sparkBudget--}e.sparkTimer=.075+this.random()*.09}}step(e){if(this.disposed)return;this.accumulator+=Q(Hl(e,0),0,.05);let t=1/120;for(;this.accumulator>=.008333332333333334;){if(this.accumulator-=t,this.elapsed+=t,this.sparkBudget=Math.min(3,this.sparkBudget+t*36),this.options.corona>0){for(let e=0;e<this.nodes.length;e++){let n=this.nodes[e].links,r=0;for(let e of n)r+=this.ionization[e];let i=this.ionization[e],a=n.length?r/n.length:i;this.ionScratch[e]=Math.max(0,i+(a-i)*t*18-i*t*1.4)}let e=this.ionization;this.ionization=this.ionScratch,this.ionScratch=e}else for(let e=0;e<this.ionization.length;e++)this.ionization[e]*=.99;for(let e=this.strokes.length-1;e>=0;e--){let n=this.strokes[e];this.advance(n,t),n.age>=n.life&&this.strokes.splice(e,1)}this.nextStrike-=t,this.nextStrike<=0&&this.options.strikesPerSecond>0&&(this.strike(),this.nextStrike=(.8+this.random()*.4)/Q(this.options.strikesPerSecond,.1,30))}}discharge(e=1){if(!this.disposed){for(let t=0;t<Q(Math.round(Hl(e,1)),1,4);t++)this.strike();this.nextStrike=(.8+this.random()*.4)/Q(Hl(this.options.strikesPerSecond,1),.1,30)}}writeInstances(e,t=0){let n=Math.min(Math.floor(e.length/10),Math.max(0,Math.floor(Hl(t,0)))),r=n,i=Q(Hl(this.options.intensity,1),0,3);for(let t=this.strokes.length-1;t>=0;t--){let a=this.strokes[t],o=Q((a.life-a.age)/.24,0,1),s=o*o*(3-2*o);for(let t=0;t<a.segments.length;t++){if(r*10+10>e.length)return r-n;let o=a.segments[t],c=a.vertices[t+1],l=a.vertices[c.parent],u=(c.charge+l.charge)*.5*i*s;if(u<.008)continue;let d=r++*10;e[d]=o.start.x,e[d+1]=o.start.y,e[d+2]=o.end.x,e[d+3]=o.end.y,e[d+4]=o.branch?.65:1.05,e[d+5]=u,e[d+6]=a.seed,e[d+7]=c.diffuse?3:+!!o.branch,e[d+8]=o.distance,e[d+9]=o.distance+o.length,Vl(e,d,a.frame)}for(let t=0;t<(a.connected?2:1)&&!(r*10+10>e.length);t++){let n=t===0?a.vertices[0].position:this.nodes[a.target],o=r++*10;e[o]=n.x,e[o+1]=n.y,e[o+2]=n.x+.1,e[o+3]=n.y,e[o+4]=1.25,e[o+5]=a.drive*i*s*.5,e[o+6]=a.seed,e[o+7]=2,e[o+8]=0,e[o+9]=1,Vl(e,o,a.frame)}}if(this.options.corona>0&&!this.emissionFrame){let t=Math.max(1,Math.ceil(this.nodes.length/128));for(let n=0;n<this.nodes.length&&!(r*10+10>e.length);n+=t){let t=this.ionization[n]*this.options.corona*i*.7;if(t<.01)continue;let a=this.nodes[n],o=r++*10;e[o]=a.x,e[o+1]=a.y,e[o+2]=a.x+.1,e[o+3]=a.y,e[o+4]=.9,e[o+5]=t,e[o+6]=n/Math.max(1,this.nodes.length),e[o+7]=4,e[o+8]=0,e[o+9]=1}}return r-n}reset(){this.strokes=[],this.nextStrike=0,this.accumulator=0,this.ionization.fill(0)}dispose(){this.reset(),this.nodes=[],this.sources=[],this.targets=[],this.ionization=new Float32Array,this.ionScratch=new Float32Array,this.onDischarge=void 0,this.onEmission=void 0,this.disposed=!0}},Zl=`#version 300 es
|
|
867
|
-
precision highp float;
|
|
868
|
-
in vec2 aStart;
|
|
869
|
-
in vec2 aEnd;
|
|
870
|
-
in vec4 aStyle;
|
|
871
|
-
in vec2 aDistance;
|
|
872
|
-
uniform vec2 uViewport;
|
|
873
|
-
out vec2 vLocal;
|
|
874
|
-
out vec2 vScreen;
|
|
875
|
-
out float vLength;
|
|
876
|
-
out float vWidth;
|
|
877
|
-
out float vEnergy;
|
|
878
|
-
out float vSeed;
|
|
879
|
-
out float vKind;
|
|
880
|
-
out vec2 vDistance;
|
|
881
|
-
|
|
882
|
-
void main() {
|
|
883
|
-
vec2 delta = aEnd-aStart;
|
|
884
|
-
float lengthPx = length(delta);
|
|
885
|
-
vec2 axis = lengthPx>0.001 ? delta/lengthPx : vec2(1.0,0.0);
|
|
886
|
-
vec2 normal = vec2(-axis.y,axis.x);
|
|
887
|
-
vec2 corners[6] = vec2[6](
|
|
888
|
-
vec2(0.0,-1.0),vec2(0.0,1.0),vec2(1.0,-1.0),
|
|
889
|
-
vec2(1.0,-1.0),vec2(0.0,1.0),vec2(1.0,1.0));
|
|
890
|
-
vec2 corner = corners[gl_VertexID];
|
|
891
|
-
float width = max(0.12,aStyle.x);
|
|
892
|
-
bool contact = aStyle.w>1.5 && aStyle.w<2.5;
|
|
893
|
-
bool field = aStyle.w>2.5;
|
|
894
|
-
// The broad halo is deliberately cheap and local: no fullscreen bloom or
|
|
895
|
-
// oversized transparent quad. Contacts earn a larger soft pool of light.
|
|
896
|
-
float radius = aStyle.w>4.5 ? width*1.25 : contact ? max(48.0,width*70.0) :
|
|
897
|
-
field ? (aStyle.w<3.5 ? max(18.0,width*12.0) : max(28.0,width*76.0)) :
|
|
898
|
-
aStyle.w<0.5 ? max(18.0,width*38.0) : max(12.0,width*26.0);
|
|
899
|
-
vec2 local = vec2(mix(-radius,lengthPx+radius,corner.x),corner.y*radius);
|
|
900
|
-
vec2 position = aStart+axis*local.x+normal*local.y;
|
|
901
|
-
vLocal=local;
|
|
902
|
-
vScreen=position;
|
|
903
|
-
vLength=lengthPx;
|
|
904
|
-
vWidth=width;
|
|
905
|
-
vEnergy=max(0.0,aStyle.y);
|
|
906
|
-
vSeed=aStyle.z;
|
|
907
|
-
vKind=aStyle.w;
|
|
908
|
-
vDistance=aDistance;
|
|
909
|
-
gl_Position=vec4(position/uViewport*vec2(2.0,-2.0)+vec2(-1.0,1.0),0.0,1.0);
|
|
910
|
-
}`,Ql=`#version 300 es
|
|
911
|
-
precision highp float;
|
|
912
|
-
in vec2 vLocal;
|
|
913
|
-
in vec2 vScreen;
|
|
914
|
-
in float vLength;
|
|
915
|
-
in float vWidth;
|
|
916
|
-
in float vEnergy;
|
|
917
|
-
in float vSeed;
|
|
918
|
-
in float vKind;
|
|
919
|
-
in vec2 vDistance;
|
|
920
|
-
uniform float uTime;
|
|
921
|
-
uniform vec3 uColor;
|
|
922
|
-
uniform vec3 uCorona;
|
|
923
|
-
uniform float uExposure;
|
|
924
|
-
uniform float uDark;
|
|
925
|
-
uniform vec2 uNoiseOrigin;
|
|
926
|
-
uniform float uNoiseScale;
|
|
927
|
-
out vec4 color;
|
|
928
|
-
|
|
929
|
-
float hash(float p) { return fract(sin(p*127.1+311.7)*43758.5453); }
|
|
930
|
-
float airHash(vec2 p) {
|
|
931
|
-
vec3 q=fract(vec3(p.xyx)*0.1031);
|
|
932
|
-
q+=dot(q,q.yzx+33.33);
|
|
933
|
-
return fract((q.x+q.y)*q.z);
|
|
934
|
-
}
|
|
935
|
-
float airNoise(vec2 p) {
|
|
936
|
-
vec2 cell=floor(p), f=fract(p);
|
|
937
|
-
f=f*f*(3.0-2.0*f);
|
|
938
|
-
return mix(mix(airHash(cell),airHash(cell+vec2(1.0,0.0)),f.x),
|
|
939
|
-
mix(airHash(cell+vec2(0.0,1.0)),airHash(cell+1.0),f.x),f.y);
|
|
940
|
-
}
|
|
941
|
-
// Neighboring collinear segments partition their halo at the joint instead of
|
|
942
|
-
// adding bright beads. Short segments get a proportionate share of soft light.
|
|
943
|
-
float finiteChannel(float reach) {
|
|
944
|
-
return max(0.0,smoothstep(-reach,reach,vLocal.x)-
|
|
945
|
-
smoothstep(vLength-reach,vLength+reach,vLocal.x));
|
|
946
|
-
}
|
|
947
|
-
|
|
948
|
-
void main() {
|
|
949
|
-
float axisPosition=clamp(vLocal.x,0.0,vLength);
|
|
950
|
-
vec2 fromChannel=vLocal-vec2(axisPosition,0.0);
|
|
951
|
-
float distancePx=length(fromChannel);
|
|
952
|
-
bool contact=vKind>1.5 && vKind<2.5;
|
|
953
|
-
bool branch=vKind>0.5 && vKind<1.5;
|
|
954
|
-
bool field=vKind>2.5;
|
|
955
|
-
float energy=clamp(vEnergy,0.0,2.4);
|
|
956
|
-
if (energy<0.002) discard;
|
|
957
|
-
vec2 mediumPosition=vScreen*uNoiseScale+uNoiseOrigin;
|
|
958
|
-
if (vKind>4.5) {
|
|
959
|
-
// Excited air fills the influence disk. No ring edge or sprite-shaped mask.
|
|
960
|
-
float r=length(vLocal)/max(1.0,vWidth);
|
|
961
|
-
float envelope=exp(-r*r*2.4)*(1.0-smoothstep(0.75,1.22,r));
|
|
962
|
-
vec2 flow=mediumPosition*0.018+vec2(uTime*0.045,-uTime*0.035);
|
|
963
|
-
float coarse=airNoise(flow);
|
|
964
|
-
if (vSeed>0.5) {
|
|
965
|
-
// Two overlapping advection windows prevent an ever-increasing angular
|
|
966
|
-
// frequency (radial streaks) or a visible reset as vapor travels inward.
|
|
967
|
-
vec2 radial=normalize(vLocal+vec2(0.001));
|
|
968
|
-
vec2 drift=radial*2.4+vec2(-radial.y,radial.x)*0.45;
|
|
969
|
-
float phase=fract(uTime*0.16);
|
|
970
|
-
float weight=1.0-abs(phase*2.0-1.0);
|
|
971
|
-
vec2 base=mediumPosition*0.018;
|
|
972
|
-
coarse=mix(airNoise(base+drift*fract(phase+0.5)),airNoise(base+drift*phase),weight);
|
|
973
|
-
flow=base;
|
|
974
|
-
}
|
|
975
|
-
float detail=airNoise(flow*2.7+coarse*1.7+vec2(-uTime*0.065,uTime*0.025));
|
|
976
|
-
float wisps=smoothstep(0.20,0.85,coarse*0.65+detail*0.35);
|
|
977
|
-
vec3 tint=mix(uCorona,uColor,0.55+detail*0.3);
|
|
978
|
-
float density=envelope*(0.055+wisps*0.24)*energy*uExposure;
|
|
979
|
-
float alpha=density*mix(0.10,1.0,uDark);
|
|
980
|
-
color=vec4(mix(vec3(0.36,0.38,0.42),tint,uDark)*alpha,alpha);
|
|
981
|
-
return;
|
|
982
|
-
}
|
|
983
|
-
if (vKind>2.5 && vKind<3.5) {
|
|
984
|
-
// Inward current reveals suspended vapor, with no hard electrical core.
|
|
985
|
-
float along=mix(vDistance.x,vDistance.y,clamp(vLocal.x/max(vLength,0.001),0.0,1.0));
|
|
986
|
-
float pulse=pow(0.5+0.5*cos(along*0.055-uTime*5.0+vSeed*6.283),7.0);
|
|
987
|
-
float body=exp(-vLocal.y*vLocal.y/max(1.0,vWidth*vWidth*2.8));
|
|
988
|
-
float mist=exp(-vLocal.y*vLocal.y/max(3.0,vWidth*vWidth*12.0));
|
|
989
|
-
float grain=0.45+0.55*airNoise(mediumPosition*0.06+uTime*0.08);
|
|
990
|
-
float alpha=energy*(body*0.8+mist*0.14)*(0.20+pulse)*grain*finiteChannel(7.0)*uExposure;
|
|
991
|
-
alpha*=mix(0.35,1.0,uDark);
|
|
992
|
-
vec3 tint=mix(vec3(0.25,0.28,0.33),vec3(0.65,0.79,0.9),uDark);
|
|
993
|
-
color=vec4(tint*alpha,alpha);
|
|
994
|
-
return;
|
|
995
|
-
}
|
|
996
|
-
if (vKind>3.5) {
|
|
997
|
-
// Isotropic density from a simulated cloud cell, not an electrical line.
|
|
998
|
-
// Shared advected texture connects overlapping cells into wisps; it only
|
|
999
|
-
// reveals the density supplied by the simulation and never births clouds.
|
|
1000
|
-
float r2=dot(fromChannel,fromChannel);
|
|
1001
|
-
float inner=exp(-r2/max(48.0,vWidth*vWidth*150.0));
|
|
1002
|
-
float outer=exp(-r2/max(100.0,vWidth*vWidth*520.0));
|
|
1003
|
-
vec2 flow=mediumPosition*0.032+vec2(uTime*0.055,-uTime*0.035);
|
|
1004
|
-
float body=airNoise(flow);
|
|
1005
|
-
float detail=airNoise(mediumPosition*0.095+vec2(-uTime*0.08,uTime*0.06)+body*0.5);
|
|
1006
|
-
float wisp=smoothstep(0.20,0.84,body*0.68+detail*0.32);
|
|
1007
|
-
vec3 tint=mix(uCorona,uColor,0.35+detail*0.32);
|
|
1008
|
-
float density=energy*(inner*0.24+outer*0.20)*wisp;
|
|
1009
|
-
density*=mix(0.18,1.0,clamp(uDark,0.0,1.0))*max(0.0,uExposure);
|
|
1010
|
-
tint=mix(vec3(0.30,0.33,0.38),tint,uDark);
|
|
1011
|
-
vec3 emission=clamp(tint*density,0.0,1.0);
|
|
1012
|
-
float opacity=max(emission.r,max(emission.g,emission.b));
|
|
1013
|
-
if (opacity<0.0005) discard;
|
|
1014
|
-
color=vec4(emission,opacity);
|
|
1015
|
-
return;
|
|
1016
|
-
}
|
|
1017
|
-
float aa=max(0.55,fwidth(distancePx));
|
|
1018
|
-
float charge=sqrt(min(energy,1.0));
|
|
1019
|
-
// Fractional-pixel coverage retains fine capillaries as charge wanes, with
|
|
1020
|
-
// width controlled by simulated local current rather than per-segment waves.
|
|
1021
|
-
float radius=vWidth*(field?0.24:branch?0.42:0.53)*
|
|
1022
|
-
(branch?0.35+0.65*charge:0.60+0.40*charge);
|
|
1023
|
-
float core=clamp((radius+aa*0.5-distancePx)/aa,0.0,1.0);
|
|
1024
|
-
float sheath=exp(-distancePx*distancePx/max(0.35,radius*radius*6.0));
|
|
1025
|
-
float closeScale=max(2.0,vWidth*vWidth*(field?75.0:35.0));
|
|
1026
|
-
float closeHalo=contact ? exp(-distancePx*distancePx/closeScale) :
|
|
1027
|
-
exp(-vLocal.y*vLocal.y/closeScale)*finiteChannel(sqrt(closeScale)*1.4);
|
|
1028
|
-
// A little off-axis corona avoids a uniform Photoshop outer-glow silhouette.
|
|
1029
|
-
float drift=(hash(vSeed+4.7)-0.5)*vWidth*(field?12.0:branch?2.8:7.0);
|
|
1030
|
-
vec2 softOffset=fromChannel-vec2(0.0,drift);
|
|
1031
|
-
float broadScale=max(9.0,vWidth*vWidth*(field?600.0:branch?85.0:196.0));
|
|
1032
|
-
float broadHalo=contact ? exp(-dot(softOffset,softOffset)/broadScale) :
|
|
1033
|
-
exp(-pow(vLocal.y-drift,2.0)/broadScale)*finiteChannel(sqrt(broadScale)*1.4);
|
|
1034
|
-
// A shared drifting air field gives the low-density corona depth without
|
|
1035
|
-
// moving the actual channel. Brightness/motion stay rooted in the simulation.
|
|
1036
|
-
vec2 air=mediumPosition*0.034+vec2(uTime*0.085,-uTime*0.055);
|
|
1037
|
-
float along=mix(vDistance.x,vDistance.y,clamp(vLocal.x/max(vLength,0.001),0.0,1.0));
|
|
1038
|
-
float vapor=airNoise(air+vec2(0.0,along*0.0008));
|
|
1039
|
-
float atmosphere=0.30+0.70*vapor*vapor;
|
|
1040
|
-
float grain=0.82+0.18*airNoise(mediumPosition*0.18-vec2(uTime*0.13,uTime*0.08));
|
|
1041
|
-
float darkness=clamp(uDark,0.0,1.0);
|
|
1042
|
-
float glowScale=mix(0.22,1.0,darkness);
|
|
1043
|
-
vec3 dayColor=mix(uColor*vec3(0.18,0.40,0.72),vec3(0.035,0.22,0.72),0.35);
|
|
1044
|
-
vec3 whiteHot=mix(dayColor,
|
|
1045
|
-
mix(uColor,vec3(0.93,0.985,1.0),0.12+0.88*smoothstep(0.14,1.05,energy)),darkness);
|
|
1046
|
-
vec3 sheathColor=mix(dayColor,uColor,darkness);
|
|
1047
|
-
vec3 light=(field?sheathColor:whiteHot)*core*(field?0.18:0.92);
|
|
1048
|
-
light+=sheathColor*(sheath*(field?0.055:0.19)+closeHalo*(field?0.13:branch?0.075:0.10))*glowScale;
|
|
1049
|
-
light+=mix(uCorona,uColor,field?0.45:0.22)*broadHalo*(field?0.19:branch?0.025:0.115)*atmosphere*grain*glowScale;
|
|
1050
|
-
light*=energy/(0.72+0.28*min(energy,1.0));
|
|
1051
|
-
if (contact) {
|
|
1052
|
-
// Brief terminal attachment light, not a decorative six-point star.
|
|
1053
|
-
float pool=exp(-distancePx*distancePx/max(90.0,vWidth*vWidth*490.0));
|
|
1054
|
-
float attachment=exp(-distancePx*distancePx/max(12.0,vWidth*vWidth*55.0));
|
|
1055
|
-
float pin=exp(-distancePx*distancePx/max(0.2,vWidth*vWidth*0.55));
|
|
1056
|
-
light+=(mix(uCorona,sheathColor,0.7)*pool*0.21+
|
|
1057
|
-
sheathColor*attachment*0.19)*energy*glowScale+whiteHot*pin*energy*0.45;
|
|
1058
|
-
}
|
|
1059
|
-
if (uDark<0.5) {
|
|
1060
|
-
// Daylight plasma: a fine white-hot core, a neutral ionized sheath and very
|
|
1061
|
-
// little colored emission. Alpha compositing avoids blue marker-like lines.
|
|
1062
|
-
float edge=exp(-distancePx*distancePx/max(1.0,vWidth*vWidth*3.5));
|
|
1063
|
-
float neutralHalo=edge*0.08;
|
|
1064
|
-
float hot=core*(branch?0.42:0.95)*min(1.0,energy);
|
|
1065
|
-
float scatter=(closeHalo*0.08+broadHalo*atmosphere*0.035)*(branch?0.45:1.0);
|
|
1066
|
-
if (contact) scatter+=exp(-distancePx*distancePx/max(36.0,vWidth*vWidth*180.0))*0.22;
|
|
1067
|
-
float total=hot+neutralHalo+scatter;
|
|
1068
|
-
float alpha=clamp(total*min(1.0,energy)*uExposure,0.0,0.96);
|
|
1069
|
-
vec3 tint=(vec3(0.28,0.29,0.35)*neutralHalo+vec3(0.95,0.97,1.0)*hot+vec3(0.80,0.84,0.96)*scatter)/max(0.001,total);
|
|
1070
|
-
color=vec4(tint*alpha,alpha);
|
|
1071
|
-
return;
|
|
1072
|
-
}
|
|
1073
|
-
light=clamp(light*max(0.0,uExposure),0.0,1.0);
|
|
1074
|
-
float alpha=max(light.r,max(light.g,light.b));
|
|
1075
|
-
if (alpha<0.001) discard;
|
|
1076
|
-
color=vec4(light,alpha);
|
|
1077
|
-
}`,$l=class{canvas;gl;program;buffer;vao;data=new Float32Array(81920);width=1;height=1;lost=!1;disposed=!1;onLost=e=>{e.preventDefault(),this.lost=!0};onRestored=()=>{this.disposed||(this.initialize(),this.lost=!1)};constructor(e=document.createElement(`canvas`)){this.canvas=e;let t=e.getContext(`webgl2`,{alpha:!0,premultipliedAlpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1});if(!t)throw Error(`WebGL2 is required for electricity`);this.gl=t,this.initialize(),e.addEventListener(`webglcontextlost`,this.onLost),e.addEventListener(`webglcontextrestored`,this.onRestored)}initialize(){let e=this.gl,t=is(e,Zl,Ql,`Electricity`),n=e.createBuffer(),r=e.createVertexArray();if(!n||!r)throw U(e,t),e.deleteBuffer(n),e.deleteVertexArray(r),Error(`Unable to allocate electricity renderer`);this.program=t,this.buffer=n,this.vao=r,e.bindVertexArray(r),e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,this.data.byteLength,e.DYNAMIC_DRAW),cs(e,t,{aStart:{buffer:n,numComponents:2,stride:40,offset:0,divisor:1},aEnd:{buffer:n,numComponents:2,stride:40,offset:8,divisor:1},aStyle:{buffer:n,numComponents:4,stride:40,offset:16,divisor:1},aDistance:{buffer:n,numComponents:2,stride:40,offset:32,divisor:1}}),e.bindVertexArray(null)}resize(e,t,n=1){if(this.disposed)return;this.width=Math.max(1,Number.isFinite(e)?e:1),this.height=Math.max(1,Number.isFinite(t)?t:1);let r=Math.min(2,Math.max(.25,Number.isFinite(n)?n:1),Math.sqrt(3e6/(this.width*this.height)),4096/this.width,4096/this.height),i=Math.ceil(this.width*r),a=Math.ceil(this.height*r);this.canvas.width!==i&&(this.canvas.width=i),this.canvas.height!==a&&(this.canvas.height=a)}render(e,t,n={}){if(this.lost||this.disposed)return 0;let r=this.gl;r.viewport(0,0,this.canvas.width,this.canvas.height),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT);let i=0;if(Array.isArray(e))for(let t of e)i+=t.writeInstances(this.data,i);else i=e.writeInstances(this.data);return i?(r.useProgram(this.program),r.bindVertexArray(this.vao),r.bindBuffer(r.ARRAY_BUFFER,this.buffer),r.bufferSubData(r.ARRAY_BUFFER,0,this.data,0,i*10),ss(this.program,{uViewport:[this.width,this.height],uTime:t,uNoiseOrigin:n.noiseOrigin??[0,0],uNoiseScale:n.noiseScale??1,uDark:n.dark===!1?0:1,uExposure:n.exposure??.95,uColor:n.color??[.14,.64,1],uCorona:n.corona??[.28,.13,1]}),r.enable(r.BLEND),r.blendFunc(r.ONE,n.dark===!1?r.ONE_MINUS_SRC_ALPHA:r.ONE),r.drawArraysInstanced(r.TRIANGLES,0,6,i),r.bindVertexArray(null),i):0}dispose(){this.disposed||(this.disposed=!0,this.canvas.removeEventListener(`webglcontextlost`,this.onLost),this.canvas.removeEventListener(`webglcontextrestored`,this.onRestored),this.gl.deleteBuffer(this.buffer),U(this.gl,this.program),this.gl.deleteVertexArray(this.vao))}},eu={color:[.58,.81,1],corona:[.25,.48,.9]},tu=(e,t,n)=>Math.max(t,Math.min(n,e)),nu=(e,t)=>({x:Math.cos(e)*t,y:Math.sin(e)*t});function ru(){return{shape:{kind:`point`,center:{x:0,y:0},radius:154},sources:Array.from({length:12},(e,t)=>nu(t/12*Math.PI*2,126)),targets:Array.from({length:17},(e,t)=>nu(t/17*Math.PI*2+.8,102))}}function iu(e){let t=e|0,n=()=>(t^=t<<13,t^=t>>>17,t^=t<<5,(t>>>0)/4294967296),r=[{x:0,y:0},{x:300,y:0}];for(let e=0;e<5;e++){let t=[r[0]],i=82*.54**e;for(let e=1;e<r.length;e++){let a=r[e-1],o=r[e];t.push({x:(a.x+o.x)/2,y:(a.y+o.y)/2+(n()-.5)*i*2},o)}r=t}return{shape:{kind:`path`,points:r,width:82},sources:[{x:0,y:0}],targets:[{x:300,y:0}]}}var au=class{vehicles=new Map;visible=[];strikes=[];volumes=[];scratch=new Float32Array(12e3);gpu=null;elapsed=0;emit;failed=!1;cameraOrigin={x:0,y:0};cameraScale=1;get active(){return this.visible.length>0||this.strikes.length>0||this.volumes.length>0}get stats(){let e=[...this.vehicles.values()].flatMap(e=>[e.field,e.charge,e.arc,e.halo]);return{vehicles:this.vehicles.size,fields:e.filter(Boolean).length,nodes:e.reduce((e,t)=>e+(t?.simulation.stats.nodes??0),0),visible:this.visible.length+this.strikes.length+this.volumes.length}}create(e,t){let n=new Xl(e===`arc`?iu(t):e===`field`?{...ru(),targets:[{x:0,y:0}]}:ru(),{seed:t,spacing:e===`field`?13:11,maxNodes:e===`arc`?640:e===`field`?520:330,strikesPerSecond:0,branching:.65,corona:e===`field`?.5:0,nearbyTargets:!1}),r={simulation:n,gain:1,pull:e===`field`};return n.onEmission=e=>{this.emit?.(e.point,e.direction,e.strength*(r.pull?.5:.8))},r}radial(e,t,n,r){let i=t.pixelsPerMetre*n/160;e.simulation.setEmissionFrame({x:t.center.x,y:t.center.y,angle:0,scaleX:i,scaleY:i,width:tu(i,.65,2)}),e.gain=r}tether(e,t,n){return{x:e.x,y:e.y,angle:Math.atan2(t.y-e.y,t.x-e.x),scaleX:Math.max(.001,Math.hypot(t.x-e.x,t.y-e.y)/300),scaleY:tu(Math.hypot(t.x-e.x,t.y-e.y)/300,.6,3)*(.95-n*.25),width:.75+n*.45}}strike(e,t,n){let r=e.simulation;r.reset(),r.setEmissionFrame(),r.configure({strikesPerSecond:0,branching:1.8,intensity:1.8});let i=r.onEmission;r.onEmission=void 0,r.discharge(1);for(let e=0;e<24;e++)r.step(1/60);r.onEmission=i;let a=r.writeInstances(this.scratch),o=this.scratch.slice(0,a*10),s=[],c=(e,t,n=!1)=>{if(e.length<2)return;let r=[0];for(let t=1;t<e.length;t++)r.push(r[t-1]+Math.hypot(e[t].x-e[t-1].x,e[t].y-e[t-1].y));let i=r[r.length-1];for(let c=0;c<a&&s.length<22e3;c++){let a=c*10;for(let t of[0,2]){let c=tu(o[a+t]/300,0,1)*i,l=1;for(;l<r.length-1&&r[l]<c;)l++;let u=e[l-1],d=e[l],f=Math.max(.001,r[l]-r[l-1]),p=tu((c-r[l-1])/f,0,1),m=n?Math.min(.15,i/300*.1):Math.min(3,Math.max(.65,i/300*.85)),h=o[a+t+1]*m;s.push(u.x+(d.x-u.x)*p-(d.y-u.y)/f*h,u.y+(d.y-u.y)*p+(d.x-u.x)/f*h)}s.push(o[a+4]*t,o[a+5],o[a+6],o[a+7],tu(o[a]/300,0,1),tu(o[a+2]/300,0,1))}};c([t.center,n],1.25);for(let e of t.lightning.branches.filter(e=>Math.hypot(e.x-n.x,e.y-n.y)>8).slice(0,4))c([n,e],.8),this.emit?.(e,{x:e.x-n.x,y:e.y-n.y},1.2);for(let e of t.lightning.paths?.slice(0,4)??[])c(e,.85,!0),e.length&&this.emit?.(e[e.length-1],{x:0,y:-1},1.2);this.strikes.push({data:new Float32Array(s),age:0,source:{...t.center},target:{...n},shook:!1}),this.strikes.length>4&&this.strikes.shift(),this.emit?.(n,{x:n.x-t.center.x,y:n.y-t.center.y},2.8),this.emit?.(t.center,{x:t.center.x-n.x,y:t.center.y-n.y},1.8),r.reset()}step(e,t,n,r){let i=tu(e,0,.05);this.elapsed+=i,this.emit=n,this.visible.length=0,this.volumes.length=0;for(let e=this.strikes.length-1;e>=0;e--){let t=this.strikes[e],a=t.age;t.age+=i,!t.shook&&t.age>=.075&&(t.shook=!0,r?.(t.target),n?.(t.source,{x:0,y:-1},2.4));for(let e=0;e<t.data.length;e+=80){let r=(1-t.data[e+8])*.075;a<=r&&t.age>r&&a<.08&&n?.({x:t.data[e],y:t.data[e+1]},{x:t.data[e+3]-t.data[e+1],y:t.data[e]-t.data[e+2]},.6)}t.age>1.5&&this.strikes.splice(e,1)}for(let e of this.vehicles.values()){e.volumeTarget=0;for(let t of[e.field,e.charge,e.arc,e.halo])t?.simulation.configure({strikesPerSecond:0})}for(let e of t.slice(0,6)){let t=e.lightning.phase===`charging`,n=e.lightning.phase===`discharged`;if(!e.attractor&&!t&&!n&&!e.electrified)continue;let r=this.vehicles.get(e.id);r||(this.vehicles.size>=8&&this.release(this.vehicles.keys().next().value),r={touched:this.elapsed,dischargeId:-1},this.vehicles.set(e.id,r)),r.touched=this.elapsed;let i=tu(e.lightning.charge,0,1);if(e.attractor){let t=r.field??=this.create(`field`,131+e.id.length);t.simulation.configure({strikesPerSecond:5,intensity:.95,corona:.6,branching:.35}),this.radial(t,e,e.attractorRadiusM,.9),r.volume={center:e.center,radius:e.attractorRadiusM*e.pixelsPerMetre,pull:!0,gain:r.volume?.gain??0},r.volumeTarget=1.3}if(t){let t=r.charge??=this.create(`field`,431+e.id.length);t.simulation.configure({strikesPerSecond:5+i*6,intensity:1+i*.7}),this.radial(t,e,2.8-i*.8,.9),e.attractor||(r.volume={center:e.center,radius:e.pixelsPerMetre*(2.8-i*.8),gain:r.volume?.gain??0},r.volumeTarget=.25+i*.3)}let a=e.lightning.target;if((t||n)&&a){let o=r.arc??=this.create(`arc`,761+e.id.length);n&&e.lightning.dischargeId!==r.dischargeId&&this.strike(o,e,a),t&&(o.simulation.setEmissionFrame(this.tether(e.center,a,i)),o.simulation.configure({strikesPerSecond:2+i*7,branching:.9+i*.5,intensity:.6+i*.5}),o.gain=i**1.4*.9)}if(e.electrified){let t=r.halo??=this.create(`halo`,919+e.id.length);t.simulation.configure({strikesPerSecond:8,intensity:.95}),this.radial(t,e,e.lengthM*.7,.9)}r.dischargeId=e.lightning.dischargeId}for(let[e,t]of this.vehicles)if(t.volume&&(t.volume.gain+=((t.volumeTarget??0)-t.volume.gain)*(1-Math.exp(-i*10)),t.volume.gain>.003&&this.volumes.push(t.volume)),this.elapsed-t.touched>2)this.release(e);else for(let e of[t.field,t.charge,t.arc,t.halo])e&&(e.simulation.step(i),e.simulation.stats.strokes>0&&this.visible.push(e))}writeInstances(e,t=0){let n=t,r=()=>n*10+10<=e.length;for(let t of this.volumes){if(!r())break;let i=this.cameraOrigin.x+t.center.x*this.cameraScale,a=this.cameraOrigin.y+t.center.y*this.cameraScale,o=n++*10;e.set([i,a,i+.01,a,t.radius*this.cameraScale,t.gain,+!!t.pull,5,0,1],o)}for(let t of this.strikes)for(let i=0;i<t.data.length&&r();i+=10){let r=n++*10;e.set(t.data.subarray(i,i+10),r);let a=(1-(t.data[i+8]+t.data[i+9])*.5)*.075,o=t.age-a,s=o<0?.1:t.age<.15?2.5:Math.exp(-(t.age-.15)*3.7)*1.8;e[r+5]*=s,e[r+4]*=o>=0&&o<.08?1.4:1,this.projectInstance(e,r)}for(let t of this.visible){let r=e.subarray(n*10,Math.min(e.length,(n+1200)*10)),i=t.simulation.writeInstances(r),a=t.pull&&i?r[6]:-1;for(let e=0;e<i;e++){let n=e*10;r[n+5]*=t.gain,t.pull&&(r[n+7]===2?r[n+5]*=.2:r[n+6]===a?(r[n+7]=0,r[n+5]*=1.2):(r[n+7]=3,r[n+4]*=3.8)),this.projectInstance(r,n)}n+=i}return n-t}projectInstance(e,t){for(let n of[0,2])e[t+n]=this.cameraOrigin.x+e[t+n]*this.cameraScale,e[t+n+1]=this.cameraOrigin.y+e[t+n+1]*this.cameraScale;e[t+4]*=this.cameraScale,e[t+8]*=this.cameraScale,e[t+9]*=this.cameraScale}draw(e,t,n,r,i,a,o=1,s=e=>e,c=1){if(!this.active||this.failed||o<=0)return;if(!this.gpu)try{this.gpu=new $l}catch{this.failed=!0;return}this.cameraScale=c;let l=s({x:0,y:0});this.cameraOrigin=l,this.gpu.resize(t,n,r),this.gpu.render(this,i,{dark:a,exposure:a?1.05:1.2,...eu,noiseOrigin:[-l.x/c,-l.y/c],noiseScale:1/c}),this.cameraOrigin={x:0,y:0},this.cameraScale=1,e.save(),e.globalAlpha*=o,f(`composited megapixels`,this.gpu.canvas.width*this.gpu.canvas.height/1e6),e.drawImage(this.gpu.canvas,0,0,t,n),e.restore()}release(e){let t=this.vehicles.get(e);if(t){for(let e of[t.field,t.charge,t.arc,t.halo])e?.simulation.dispose();this.vehicles.delete(e)}}reset(){for(let e of this.vehicles.keys())this.release(e);this.visible.length=0,this.strikes.length=0,this.volumes.length=0,this.elapsed=0}dispose(){this.reset(),this.gpu?.dispose(),this.gpu=null}},ou=class{camera;effects=new au;clock=0;constructor(e){this.camera=e}step(e,t,n,r,i){if(this.clock+=n,this.clock<1/60)return;let a=Math.min(.05,this.clock);this.clock=Math.max(0,this.clock-1/60);let o=[];for(let n of[e,...t]){let e=n.sim;if(e.mode!==`car`||e.car.explodedAt!==null||n.isGhost)continue;let t=n.weapons.lightning.visual,r=e.car.statusEffects.remaining(`electrified`)>0;if(!n.controls.attractor&&t.phase===`idle`&&!r)continue;let i=this.camera.screen(e.body.position),a=Math.max(7,se(e.car.preset,this.camera.width,this.camera.documentScale()))*this.camera.zoom;i.x<-a||i.x>this.camera.width+a||i.y<-a||i.y>this.camera.height+a||o.push({id:n.id,center:this.camera.documentPoint(e.body.position),angle:-e.body.angle,pixelsPerMetre:this.camera.documentScale(),lengthM:e.car.preset.geometry.lengthM,widthM:e.car.preset.geometry.widthM,attractor:!!n.controls.attractor&&!e.paused,attractorRadiusM:7,electrified:r,lightning:t})}this.effects.step(e.sim.paused?0:a,o,(e,t,n)=>r.electric(this.camera.particlePoint(this.camera.worldFromDocument(e)),this.camera.pixelSpace?t:C(t.x/this.camera.documentScale(),-t.y/this.camera.documentScale()),n),()=>i.trigger(`lightning`,1,performance.now()))}draw(e,t,n,r){this.effects.draw(e,this.camera.width,this.camera.height,this.camera.dpr,t/1e3,n,r,e=>this.camera.screen(this.camera.worldFromDocument(e)),this.camera.zoom/this.camera.documentScale())}reset(){this.clock=0,this.effects.reset()}dispose(){this.effects.dispose()}},su=e({Renderer:()=>cu}),cu=class{overlay;canvasWorld;vehicleImageLoadState(e){return this.vehicles.imageLoadState(e)}carVisualOffset(e){return this.vehicles.carVisualOffset(e)}get cameraLock(){return this.view.cameraLock}set cameraLock(e){this.view.cameraLock=e}get cameraSmoothing(){return this.view.cameraSmoothing}set cameraSmoothing(e){this.view.cameraSmoothing=e}get deadZone(){return this.view.deadZone}set deadZone(e){this.view.deadZone=e}screen(e){return this.view.screen(e)}world(e){return this.view.world(e)}vehicleViewportPosition(e){return this.view.vehicleViewportPosition(e)}sceneScroll(){return this.view.sceneScroll()}get documentProjection(){return this.view.documentProjection}virtualOffset(){return this.view.virtualOffset()}documentPoint(e){return this.view.documentPoint(e)}worldFromDocument(e){return this.view.worldFromDocument(e)}documentScale(){return this.view.documentScale()}viewportSize(){return this.view.viewportSize()}presentationScale(){return this.view.presentationScale()}setSlowMoZoom(e){this.view.slowMoZoom=e}setCanvasWorldScale(e,t=1.5){this.view.setCanvasWorldScale(e,t)}setCameraFrame(e){this.view.setCameraFrame(e)}setCameraLock(e){this.view.setCameraLock(e)}viewportFromDocument(e){return this.view.viewportFromDocument(e)}documentFromViewport(e){return this.view.documentFromViewport(e)}bounds(){return this.view.bounds()}vehicleMarkerAt(e){if(!this.showVehicleMarkers)return null;let t=this.view.documentFromViewport(e);return this.vehicles.markerAt(this.view.screen(this.view.worldFromDocument(t)))}revealVehicle(e){this.view.revealVehicle(e)}resumeFollow(){this.view.resumeFollow()}interruptFollow(){this.view.interruptFollow()}restorePage(e){this.view.restorePage(e)&&(this.lastFlowCenter=null,this.flowVelocity=C())}followDocument(e){return this.view.followDocument(e)}primaryVehicleVisible=!0;primaryVehicleOpacity=1;beginVehicleArrivalFade(){this.skidTracks.beginReveal(this.skidView(),this.darkSurface()),this.primaryVehicleOpacity=0}setVehicleArrivalOpacity(e){this.primaryVehicleOpacity=b(e,0,1),this.skidTracks.setRevealAlpha(this.primaryVehicleOpacity,this.skidView(),this.darkSurface())}view;surface;vehicles;debris=new d;get ctx(){return this.surface.context}nextHistoryPrune=0;trailClock=0;quality=T.game.quality;fluidGovernor=new Ce;vehicleLights=new Gs;surfaceTones=new Xs;vehicleLighting={...E};setVehicleLighting(e){this.vehicleLighting=ee({...this.vehicleLighting,...e})}getVehicleLighting(){return{...this.vehicleLighting}}toggleVehicleLight(e){return this.setVehicleLighting({[e]:e===`underglow`?this.vehicleLighting.underglow?void 0:`#66e6ff`:!this.vehicleLighting[e]}),this.getVehicleLighting()}surfaceTone=T.game.surfaceTone;trail=[];skidTracks=new Nl;volumetrics;pointPuffs=[];objectGlint=null;showVehicleMarkers=T.game.showVehicleMarkers;tireSmokeEnabled=T.game.tireSmoke;vehicleShadowsEnabled=T.game.vehicleShadows;effectsFadeStartedAt=null;wallRects=[];combustion;sparks=new Pc;electricity;liquidLayer;tireMarks=new El;seedGroundMarks(e){this.overlay&&this.tireMarks.seed(e,this.particleScale())}focusVehicle=null;activeVehicles=[];bindVehicle(e){this.focusVehicle=e}forgetVehicle(e){this.tireMarks.forgetVehicle(e),this.activeVehicles=this.activeVehicles.filter(t=>t.id!==e),this.focusVehicle?.id===e&&(this.focusVehicle=null)}get rocketFlightPosition(){let e=this.focusVehicle?.sim.body.position??C(),t=null,n=1/0;for(let r of this.activeVehicles){let i=r.weapons.rocket.projectile?.position;if(!i)continue;let a=m(x(i,e));a<n&&(t=i,n=a)}return t}screenShake=new Il;exhaustBursts=[];queueExhaustPops(e){for(let t of e)t<.12||this.exhaustBursts.push({age:0,lifetime:.08+t*.11,intensity:.4+t*.6});this.exhaustBursts.length>6&&this.exhaustBursts.splice(0,this.exhaustBursts.length-6)}lastFlowCenter=null;flowVelocity=C();captureState(){let e=[],t=t=>(t&&e.push(()=>t.dispose()),t);try{let n=t(this.volumetrics.captureState()),r=t(this.combustion.captureState()),i=t(this.liquidLayer.captureState());return{at:performance.now(),data:u({primaryVehicleVisible:this.primaryVehicleVisible,primaryVehicleOpacity:this.primaryVehicleOpacity,nextHistoryPrune:this.nextHistoryPrune,trailClock:this.trailClock,quality:this.quality,fluidQualityLimit:this.fluidGovernor.limit,vehicleLighting:this.vehicleLighting,surfaceTone:this.surfaceTone,trail:this.trail,pointPuffs:this.pointPuffs,showVehicleMarkers:this.showVehicleMarkers,tireSmokeEnabled:this.tireSmokeEnabled,vehicleShadowsEnabled:this.vehicleShadowsEnabled,effectsFadeStartedAt:this.effectsFadeStartedAt,wallRects:this.wallRects,exhaustBursts:this.exhaustBursts,lastFlowCenter:this.lastFlowCenter,flowVelocity:this.flowVelocity,debugDrive:this.debugDrive,previewGroundFire:this.previewGroundFire,previewWallSmoke:this.previewWallSmoke,previewSparks:this.previewSparks,previewDamage:this.previewDamage,previewOil:this.previewOil,previewOilSplatter:this.previewOilSplatter,oilSplatterPreviewSeconds:this.oilSplatterPreviewSeconds,sparkPreviewClock:this.sparkPreviewClock,damagePreviewApplied:this.damagePreviewApplied,groundFirePreviewLit:this.groundFirePreviewLit,trailLifetime:this.trailLifetime,fallbackSurfaceTone:this.fallbackSurfaceTone}),camera:this.view.captureState(),diagnostics:this.diagnostics.captureState(),vehicles:this.vehicles.captureState(),volumetrics:n,combustion:r,liquids:i,debris:this.debris.captureState(),skidTracks:this.skidTracks.captureState(),tireMarks:this.tireMarks.captureState(),sparks:this.sparks.captureState(),screenShake:this.screenShake.captureState(),dispose:()=>e.forEach(e=>e())}}catch(t){throw e.forEach(e=>e()),t}}restoreState(e){let t=this.captureState();try{this.applyState(e)}catch(e){try{this.applyState(t)}catch(t){throw AggregateError([e,t],`Renderer checkpoint rollback failed`,{cause:t})}throw e}finally{t.dispose()}}applyState(e){this.clearEffects();let t=u(e.data);this.primaryVehicleVisible=t.primaryVehicleVisible,this.primaryVehicleOpacity=t.primaryVehicleOpacity,this.nextHistoryPrune=t.nextHistoryPrune,this.trailClock=t.trailClock,this.quality=t.quality,this.fluidGovernor.restoreLimit(t.fluidQualityLimit),this.vehicleLighting=t.vehicleLighting,this.surfaceTone=t.surfaceTone,this.trail=t.trail,this.pointPuffs=t.pointPuffs,this.showVehicleMarkers=t.showVehicleMarkers,this.tireSmokeEnabled=t.tireSmokeEnabled,this.vehicleShadowsEnabled=t.vehicleShadowsEnabled,this.effectsFadeStartedAt=t.effectsFadeStartedAt,this.wallRects=t.wallRects,this.exhaustBursts=t.exhaustBursts,this.lastFlowCenter=t.lastFlowCenter,this.flowVelocity=t.flowVelocity,this.debugDrive=t.debugDrive,this.previewGroundFire=t.previewGroundFire,this.previewWallSmoke=t.previewWallSmoke,this.previewSparks=t.previewSparks,this.previewDamage=t.previewDamage,this.previewOil=t.previewOil,this.previewOilSplatter=t.previewOilSplatter,this.oilSplatterPreviewSeconds=t.oilSplatterPreviewSeconds,this.sparkPreviewClock=t.sparkPreviewClock,this.damagePreviewApplied=t.damagePreviewApplied,this.groundFirePreviewLit=t.groundFirePreviewLit,this.trailLifetime=t.trailLifetime,this.fallbackSurfaceTone=t.fallbackSurfaceTone,this.view.restoreState(e.camera),this.diagnostics.restoreState(e.diagnostics),this.vehicles.restoreState(e.vehicles),this.volumetrics.setQuality(this.fluidGovernor.apply(this.quality)),this.volumetrics.restoreState(e.volumetrics),this.combustion.setQuality(this.fluidGovernor.apply(this.quality)),this.combustion.restoreState(e.combustion),this.liquidLayer.restoreState(e.liquids),e.debris&&this.debris.restoreState(e.debris),this.skidTracks.restoreState(e.skidTracks,this.skidView(),this.darkSurface()),this.tireMarks.restoreState(e.tireMarks),this.sparks.restoreState(e.sparks),this.screenShake.restoreState(e.screenShake),this.effectsFadeStartedAt!==null&&(this.effectsFadeStartedAt+=performance.now()-e.at),this.view.rebaseTime(performance.now()),this.view.restorePresentation()}get flamethrowerFiring(){return this.activeVehicles.some(e=>e.weapons.flamethrower.firing)}get managedMemoryGroups(){return[{label:`Tire marks`,bytes:this.skidTracks.managedBytes+this.activeVehicles.reduce((e,t)=>e+t.tirePaint.managedBytes,0)+this.tireMarks.managedBytes},{label:`Smoke`,bytes:this.volumetrics.smokeBytes},{label:`Ghost`,bytes:this.volumetrics.ghostBytes},{label:`Fire`,bytes:this.combustion.managedBytes},{label:`Liquids`,bytes:this.liquidLayer.managedBytes},{label:`Debris`,bytes:this.debris.managedBytes+Le().bytes},{label:`Tools`,bytes:this.activeVehicles.reduce((e,t)=>e+t.weapons.managedBytes,0)},{label:`Sparks`,bytes:this.sparks.count*112},{label:`Points`,bytes:this.pointPuffs.length*32},{label:`Vehicle trail`,bytes:this.trail.length*48}]}get managedBytes(){return this.managedMemoryGroups.reduce((e,t)=>e+t.bytes,0)}debugDrive=!1;previewGroundFire=!1;previewWallSmoke=!1;previewSparks=!1;previewDamage=!1;previewOil=!1;previewOilSplatter=!1;oilSplatterPreviewSeconds=0;sparkPreviewClock=0;damagePreviewApplied=!1;groundFirePreviewLit=!1;diagnostics=new Ns;trailLifetime=12;constructor(e,t=!1,n=T.game.quality,r=!1){this.overlay=t,this.canvasWorld=r,this.sparks.setElectricalPalette(eu),this.view=new js(t,r,()=>this.resize()),this.surface=new Ms(e,this.view,t,r),this.combustion=new hc(this.view,n),this.volumetrics=new bc(this.view,n),this.electricity=new ou(this.view),this.liquidLayer=new xl(this.view,n),this.vehicles=new _s(this.view),this.quality=n,this.resize()}get pixelSpace(){return this.overlay||this.canvasWorld}prepareFire(){return this.sparks.prepare()?this.combustion.ensure():!1}setQuality(e){if(e===this.quality)return;this.quality=e;let t=this.fluidGovernor.apply(e);this.volumetrics.setQuality(t),this.liquidLayer.setQuality(e),this.combustion.setQuality(t)}applyFluidQuality(){let e=this.fluidGovernor.apply(this.quality);this.volumetrics.setQuality(e),this.combustion.setQuality(e)}setTireSmokeEnabled(e){this.tireSmokeEnabled=e}setVehicleShadowsEnabled(e){this.vehicleShadowsEnabled=e}setAbsoluteViewport(){this.surface.setAbsoluteViewport()}setSparksEnabled(e){this.sparks.setEnabled(e)}setScreenShakeEnabled(e){this.screenShake.setEnabled(e)}setScreenShakeProfiles(e){this.screenShake.setProfiles(e)}emitCrashShake(e){if(this.effectsFadeStartedAt!==null)return;let t=Fl(e);t&&this.screenShake.trigger(t)}emitRocketExplosionShake(e=1){this.effectsFadeStartedAt===null&&this.screenShake.trigger(`rocketExplosion`,Math.sqrt(Math.max(0,e)))}emitCombustibleExplosion(e,t){if(this.effectsFadeStartedAt!==null)return;this.screenShake.trigger(`combustibleExplosion`);let n=this.particlePoint(this.worldFromDocument(e));this.sparks.emitExplosion(n,C(),this.particleScale(),1.2),this.combustion.queueBlast(n,t*this.particleScale()/Math.max(1,this.documentScale())),this.emitCombustibleBlast(e,t,0)}emitCombustibleBlast(e,t,n){if(this.effectsFadeStartedAt!==null||!this.combustion.activateBuoyancy())return;let r=this.particlePoint(this.worldFromDocument(e)),i=t*this.particleScale()/Math.max(1,this.documentScale()),a=Math.min(1,n/.34);for(let e=0;e<24;e++){let t=e*Math.PI*(3-Math.sqrt(5)),n=C(Math.cos(t),Math.sin(t));this.combustion.queueStamp({point:S(r,v(n,i*a*1.05)),radius:Math.max(4,i*(.29-a*.12)),flow:S(v(n,i*(2.6-a)),C(0,-i*.4)),progress:.28+a*.53,blast:!0})}}emitRocketExplosion(e,t,n=1){if(this.effectsFadeStartedAt!==null)return;let r=this.particlePoint(this.worldFromDocument(e)),i=this.particleVelocity(C(t.x/this.view.zoom,-t.y/this.view.zoom)),a=this.particleScale(),o=Math.sqrt(b(n,.5,2));this.combustion.ensure()&&(this.combustion.queueBlast(r,a*2.2*o),this.combustion.queueStamp({point:r,radius:a*.95*o,flow:C(0,-a*.7),progress:.24,strength:2.6,blast:!0}));for(let t=0;t<64;t++){let n=t*Math.PI*(3-Math.sqrt(5))+Math.atan2(i.y,i.x),s=a*Math.sqrt((t+.5)/64)*1.75*(.83+.17*Math.sin(t*11.8+e.x*.03))*o,c=C(Math.cos(n),Math.sin(n));this.combustion.available&&this.combustion.queueStamp({point:S(r,v(c,s)),radius:a*(.38+t%4*.065)*o,flow:S(v(c,a*2.5),C(0,-a*.5)),progress:.3+t%5*.06,strength:1.7+t%3*.28,blast:!0})}this.sparks.emitExplosion(r,i,a,n),this.sparks.emitFireAt(r,a*.5,.25,14)}setDeformEnabled(e){this.focusVehicle?.damage.setEnabled(e),e||(this.damagePreviewApplied=!1)}resetVehicleDamage(){this.focusVehicle?.damage.reset()}emitSparks(e){this.effectsFadeStartedAt===null&&this.sparks.emit(e)}emitVehicleBurn(e,t,n,r){let i=e.sim,a=this.documentScale(),o=S(this.documentPoint(i.body.position),this.carVisualOffset(i)),s=n.lengthM*a,c=n.widthM*a,l=C(Math.cos(i.body.angle),-Math.sin(i.body.angle)),u=C(-l.y,l.x),d=S(o,S(v(l,t.burnOriginLocal.x*a),v(u,t.burnOriginLocal.y*a))),f=this.combustion.alphaFor(n.alpha.solid);if(t.stage===`exploded`)return t.explosionStarted&&this.emitCombustibleExplosion(o,Math.max(78,s*.7)),t.blastAge<y.fireballSeconds&&this.emitSceneFire({key:t.key,alpha:f,pixelWidth:n.alpha.columns,pixelHeight:n.alpha.rows,x:o.x-s/2,y:o.y-c/2,width:s,height:c,angle:-i.body.angle,origin:o,farthest:Math.hypot(s,c),...p(t.blastAge)},r),t.blastPulse&&this.emitCombustibleBlast(o,Math.max(78,s*.7),t.blastAge),t.explosionStarted?o:null;let m=g(t.health,t.maxHealth,s,c);return m&&this.emitSceneFire({key:t.key,alpha:f,pixelWidth:n.alpha.columns,pixelHeight:n.alpha.rows,x:o.x-s/2,y:o.y-c/2,width:s,height:c,angle:-i.body.angle,origin:d,farthest:Math.hypot(s,c),...m},r),null}sceneFireDue(e){return this.effectsFadeStartedAt===null&&this.combustion.sceneMasksDue(e)}emitSceneFire(e,t=1/60){this.effectsFadeStartedAt===null&&this.combustion.queueMask(e)}pourWorldLiquid(e,t,n,r,i){this.liquidLayer.pourWorldLiquid(e,t,n,r,i)}emitPaint(e,t,n,r,i){this.liquidLayer.emitPaint(e,t,n,r,i)}hasConductiveLiquidNear(e,t){return this.liquidLayer.hasConductiveCandidate(e,t)}conductLightning(e,t=0){return this.liquidLayer.conductLightning(e,t)}igniteLiquidAt(e,t){this.liquidLayer.igniteAt(e,t)}igniteConductedLiquids(e,t){this.liquidLayer.igniteConducted(e,t)}igniteLiquidsFromFire(e){this.liquidLayer.igniteFromFire(e)}burningLiquidSources(){return this.liquidLayer.burningSources()}hasLiquidContact(e,t){return this.liquidLayer.hasContact(e,t)}addLiquid(e,t){this.liquidLayer.add(e,t)}syncElementLiquids(e){return this.liquidLayer.syncElements(e)}ejectLiquid(e,t=`oil`,n){this.liquidLayer.pourVehicle(e,t,.65,n)}setInitialPuddles(e){this.liquidLayer.setInitialPuddles(e)}setSurfaceTone(e){this.surfaceTone=e}fallbackSurfaceTone={at:-1/0,dark:!1};darkSurface(){if(this.surfaceTone!==`auto`)return this.surfaceTone===`dark`;let e=document.documentElement.dataset.jrTheme;if(e===`light`||e===`dark`)return e===`dark`;let t=performance.now();if(t-this.fallbackSurfaceTone.at<80)return this.fallbackSurfaceTone.dark;let n=getComputedStyle(document.body).backgroundColor,r=qs(/rgba\([^)]*,\s*0(?:\.0+)?\s*\)/.test(n)||n===`transparent`?getComputedStyle(document.documentElement).backgroundColor:n);return this.fallbackSurfaceTone={at:t,dark:r},r}setDebugEnabled(e){this.debugDrive=e||!1}fadeEffects(){if(this.effectsFadeStartedAt!==null)return;this.effectsFadeStartedAt=performance.now(),this.liquidLayer.clearEffects(),this.liquidLayer.restoreInitialPuddles(),this.volumetrics.clearSmokeSources();let e=this.activeVehicles.length?this.activeVehicles:this.focusVehicle?[this.focusVehicle]:[];for(let t of e)t.weapons.reset(),t.tirePaint.reset(),t.pickupEffect.reset(),t.damage.reset();this.screenShake.reset(),this.electricity.reset(),this.skidTracks.fade(),this.combustion.clearTireHistory(),this.exhaustBursts=[]}clearEffects(e=!0){this.debris.reset(),this.electricity.reset(),this.objectGlint?.dispose(),this.objectGlint=null,this.trail=[],this.skidTracks.clear(),this.volumetrics.reset(),this.pointPuffs=[];for(let e of this.activeVehicles.length?this.activeVehicles:this.focusVehicle?[this.focusVehicle]:[])e.pickupEffect.reset(),e.weapons.rocket.reset(),e.weapons.machineGuns.reset(),e.weapons.flamethrower.reset();this.screenShake.reset(),this.combustion.reset(),this.exhaustBursts=[],this.sparks.reset(),e&&this.liquidLayer.clearEffects(),this.tireMarks.clear(),this.lastFlowCenter=null,this.flowVelocity=C(),this.trailClock=0,this.effectsFadeStartedAt=null}reset(){this.view.reset(),this.clearEffects(),this.liquidLayer.restoreInitialPuddles(),this.wallRects=[],this.groundFirePreviewLit=!1,this.sparkPreviewClock=0,this.damagePreviewApplied=!1,this.vehicles.reset(),this.surface.clear(),this.view.resetFollow()}dispose(){this.liquidLayer.dispose(),this.debris.clear(),this.electricity.dispose(),this.vehicles.dispose(),this.objectGlint?.dispose(),this.surface.dispose(),this.view.dispose(),this.skidTracks.clear(),this.tireMarks.clear(),this.volumetrics.dispose(),this.combustion.dispose(),this.sparks.dispose()}resize(){let e=this.surface.resize();this.liquidLayer.resize(),this.volumetrics.resize(e),this.combustion.resize(e)}rasterPixelRatio(){return this.canvasWorld?Math.min(2,Math.round(this.view.dpr/this.view.regionScale*100)/100):this.view.dpr}setShowVehicleMarkers(e){this.showVehicleMarkers=e}flashTargets(e){this.resize(),this.objectGlint??=new zl;let t=this.sceneScroll();this.objectGlint.trigger(this.view.width,this.view.height,this.view.dpr,n=>e(n,t))}particlePoint(e){return this.view.particlePoint(e)}particleScreen(e){return this.pixelSpace?x(e,this.sceneScroll()):this.screen(e)}particleVelocity(e){return this.pixelSpace?C(e.x*this.view.zoom,-e.y*this.view.zoom):{...e}}particleScale(){return this.view.particleScale()}emitPoints(e,t){t<=0||this.pointPuffs.push({point:this.particlePoint(this.worldFromDocument(e)),amount:t,age:0})}fluidView(){let e=this.sceneScroll();return this.pixelSpace?{origin:C(this.view.smokeMargin-e.x,this.view.smokeMargin-e.y),scaleX:1,scaleY:1}:{origin:C(this.view.width/2-this.view.camera.x*this.view.zoom,this.view.height/2+this.view.camera.y*this.view.zoom),scaleX:this.view.zoom,scaleY:-this.view.zoom}}flameView(){let e=this.fluidView();return this.pixelSpace?{...e,origin:C(e.origin.x-this.view.smokeMargin,e.origin.y-this.view.smokeMargin)}:e}clipFluidWalls(e){if(!this.overlay)return;let t=this.sceneScroll();for(let n of this.wallRects){let r=n.x-t.x,i=n.y-t.y;n.width<=0||n.height<=0||r>=this.view.width||i>=this.view.height||r+n.width<=0||i+n.height<=0||(e.beginPath(),e.rect(0,0,this.view.width,this.view.height),e.rect(r,i,n.width,n.height),e.clip(`evenodd`))}}stepVehicleWeapons(e,t,n,r,i,a,o,s,c){let l=e.sim;performance.now(),e.weapons.rocket.step(t,l,e=>{this.effectsFadeStartedAt===null&&this.volumetrics.emitSmoke({point:this.particlePoint(e.point),amount:e.amount,flow:this.particleVelocity(e.flow),radiusPx:e.radiusM*this.view.zoom,swirlPx:10})},n?(t,r,i)=>{let a=n(e,this.documentPoint(t),this.documentPoint(r),i*this.documentScale());return a?this.worldFromDocument(a):null}:void 0,e=>{this.effectsFadeStartedAt===null&&this.combustion.emitJet(e.from,e.to,e.flow,e.widthM,e.intensity,`rocket`)},o,s,void 0),e.weapons.machineGuns.step(t,l,r?(t,n,i)=>{let a=r(e,this.documentPoint(t),this.documentPoint(n),i*this.documentScale());return a?this.worldFromDocument(a):null}:void 0,i,(e,t)=>{this.effectsFadeStartedAt===null&&this.sparks.emitBulletImpact(this.particlePoint(e),this.particleVelocity(t)),c?.(e)}),e.weapons.flamethrower.step(t,l,e=>{this.effectsFadeStartedAt===null&&this.volumetrics.emitSmoke({point:this.particlePoint(e.point),amount:e.amount,flow:this.particleVelocity(e.flow),radiusPx:e.radiusM*this.view.zoom,swirlPx:10})},a?(t,n,r,i)=>{let o=a(e,this.documentPoint(t),this.documentPoint(n),r*this.documentScale(),i);return o?this.worldFromDocument(o):null}:void 0,(e,n,r,i,a)=>{if(this.effectsFadeStartedAt!==null)return;let o=this.particleScale();this.liquidLayer.igniteAlong(this.particlePoint(e),this.particlePoint(n),r*o*.5),a>.3&&this.sparks.emitFireAt(this.particlePoint(n),r*o*.4,t,3),this.combustion.queueStamp({point:this.particlePoint(n),radius:r*o,progress:a,flow:this.particleVelocity(i)})})}sprayTirePaint(e,t,n,r,i,a,o,s){return this.liquidLayer.splatter(e,t,n,r,i,a,o,s)}advanceEffects(e,t,{walls:r=[],carMask:i,tirePaintSources:a=[],driven:o=!0,rocketCollision:s,bulletCollision:c,onGunshot:l,flameContact:u,onRocketLaunch:d,onRocketImpact:f,onBulletImpact:p,maskFor:g,companions:_=[]}={}){for(let e of this.pointPuffs)e.age+=t;this.pointPuffs=this.pointPuffs.filter(e=>e.age<.9),this.activeVehicles=[e,..._];let y=this.sceneScroll();this.debris.count&&this.debris.step(t,this.activeVehicles.filter(e=>e.sim.mode===`car`&&!e.isGhost&&e.sim.car.explodedAt===null).map(e=>{let t=this.particlePoint(e.sim.body.position),n=this.particleVelocity(e.sim.body.velocity),r=this.particleScale();return{x:t.x,y:t.y,vx:n.x,vy:n.y,angle:-e.sim.body.angle,length:e.sim.car.preset.geometry.lengthM*r,width:e.sim.car.preset.geometry.widthM*r}}),{x:y.x,y:y.y,width:this.view.width,height:this.view.height},r),this.volumetrics.stepGhost(t,this.activeVehicles,r,g,this.flameView(),e=>this.carVisualOffset(e.sim),e=>{let t=this.vehicles.imageFor(e.sim.car.preset);if(!t)return;let n=k(e.sim.car.preset,t.naturalWidth,t.naturalHeight),r=e.damage.spriteFor(t,n);return{image:r??t,source:r?{x:0,y:0,width:r.width,height:r.height}:n.source}});let b=e.sim;if(this.wallRects=r,this.vehicles.updateCarPose(b,t),this.effectsFadeStartedAt===null){for(let e of this.activeVehicles)for(let r of e.liquidEmissions(t))this.liquidLayer.pourVehicle(e.sim,n(r.liquid),r.amount,void 0,e.id);this.previewOil&&!this.previewOilSplatter&&this.liquidLayer.pourVehicle(b,`oil`,t*6)}for(let n of[e,..._])this.stepVehicleWeapons(n,t,s,c,l,u,d,f,p);let{tires:w,companionTires:T}=this.liquidLayer.stepVehicles(e,_,t,o,a,this.effectsFadeStartedAt!==null,(e,t)=>this.emitSceneFire(e,t)),ee=this.documentScale(),E=C(Math.cos(b.body.angle),-Math.sin(b.body.angle)),D=b.mode===`car`&&i&&!e.isGhost?{mask:i.alpha,shape:{center:S(this.documentPoint(b.body.position),this.carVisualOffset(b)),forward:E,side:C(-E.y,E.x),halfLength:i.lengthM*ee/2,halfWidth:i.widthM*ee/2}}:void 0;this.previewDamage&&!this.damagePreviewApplied&&D&&(this.damagePreviewApplied=e.damage.hit(S(D.shape.center,v(D.shape.forward,D.shape.halfLength)),v(D.shape.forward,-1),D.shape,20,ee)),this.electricity.step(e,_,t,this.sparks,this.screenShake);for(let e of this.activeVehicles){if(e.sim.mode!==`car`||this.effectsFadeStartedAt!==null)continue;let n=g?.(e)??e.sim.car.preset.geometry;for(let r of e.pickupEffect.active){let i=C(Math.cos(r.angle),Math.sin(r.angle)),a=this.particleVelocity(h(i,e.sim.body.angle));for(let i of bs(r,n,t)){let t=e.sim.body.world(i);this.sparks.pickup(this.particlePoint(t),v(a,r.velocity),a,r.color,this.particleScale(),Math.max(.2,r.strength),1)}}}if(performance.now(),b.mode===`car`&&m(b.body.velocity)>.15&&this.sparks.disturb(this.particlePoint(b.body.position),this.particleVelocity(b.body.velocity),this.particleScale()*2.8),this.sparks.step(t,{walls:r,car:D}),this.previewSparks&&b.mode===`car`&&(this.sparkPreviewClock+=t,this.sparkPreviewClock>.12)){this.sparkPreviewClock=0;let e=this.particlePoint(b.body.position),t=this.particleScale();this.emitSparks({point:S(e,C(t*1.9,0)),velocity:C(t*4,t*10),normal:C(-1,0),pixelsPerMeter:t})}let te=this.particleScale(),ne=this.particlePoint(b.body.position),re=this.lastFlowCenter?v(x(ne,this.lastFlowCenter),1/Math.max(t,1e-4)):this.particleVelocity(b.body.velocity),O=m(re),ie=O>40*te?v(re,40*te/O):re;this.flowVelocity=S(this.flowVelocity,v(x(ie,this.flowVelocity),1-Math.exp(-12*t))),this.lastFlowCenter=ne;let ae=this.pixelSpace?this.flowVelocity:C(this.flowVelocity.x*this.view.zoom,-this.flowVelocity.y*this.view.zoom),oe=C(Math.cos(b.body.angle),-Math.sin(b.body.angle)),se=b.mode===`car`?{center:S(this.screen(b.body.position),C(this.view.smokeMargin,this.view.smokeMargin)),velocity:ae,forward:oe,halfLength:b.car.preset.geometry.lengthM*this.view.zoom*.46,halfWidth:b.car.preset.geometry.widthM*this.view.zoom*.39,spin:-b.body.spin}:null;if(this.effectsFadeStartedAt!==null){this.volumetrics.clearSmokeSources(),this.combustion.stepTire(t),this.combustion.step(t,this.view.timeSeconds,e.isGhost?null:se,this.wallRects,!0,this.flameView(),this.sparks),this.volumetrics.stepSmoke(t,se,this.wallRects,this.fluidView());return}if(this.previewWallSmoke&&this.overlay){let e=this.sceneScroll(),n=this.wallRects.filter(t=>t.x-e.x>48&&t.x-e.x<this.view.width-48&&t.y+t.height/2-e.y>30&&t.y+t.height/2-e.y<this.view.height-30),r=n.find(t=>t.x-e.x>this.view.width*.5)??n[0];r&&this.volumetrics.emitSmoke({point:C(r.x-25,r.y+r.height/2),amount:t*15,flow:C(210,0),radiusPx:17,swirlPx:25})}if(performance.now(),this.combustion.stepTire(t),this.combustion.step(t,this.view.timeSeconds,e.isGhost?null:se,this.wallRects,!1,this.flameView(),this.sparks),!this.pixelSpace){for(let e of this.trail)e.age+=t;if(this.trail=this.trail.filter(e=>e.age<this.trailLifetime),this.trailClock+=t,this.trailLifetime>0&&this.trailClock>=1/30){this.trailClock%=1/30;let e=this.trail.at(-1);(!e||m(x(e.point,b.body.position))>.04)&&this.trail.push({point:{...b.body.position},age:0,color:b.mode===`ship`?`#9bbcff`:b.mode===`brick`?`#f6bd79`:`#8ce6c5`}),this.trail.length>800&&this.trail.shift()}}if(b.mode!==`car`){this.volumetrics.stepSmoke(t,null,this.wallRects,this.fluidView()),this.skidTracks.stop(this.skidView(),this.darkSurface(),!0),this.combustion.clearTireHistory();return}if(e.isGhost){this.volumetrics.stepSmoke(t,null,this.wallRects,this.fluidView()),this.skidTracks.stop(this.skidView(),this.darkSurface()),this.combustion.clearTireHistory();return}let ce=this.advanceVehicleTireEffects(e,t,w,T,ae),le=this.combustion.emberSource();le&&this.sparks.emitFireAt(le.point,le.radius,t,20*le.heat),performance.now(),this.volumetrics.stepSmoke(t,se,this.wallRects,this.fluidView());let ue=this.darkSurface();this.skidTracks.step(t,b,ce,t=>!!e.tirePaint.coating(t),{pixelSpace:this.pixelSpace,scale:this.particleScale(),dark:ue,project:e=>this.particlePoint(e),roadAt:(e,t)=>!!this.overlay&&this.surfaceTones.at(e,this.viewportFromDocument(t),ue),view:this.skidView()})}advanceVehicleTireEffects(e,t,n,r,i){let a=e.sim,o=this.particleScale();if(this.previewGroundFire&&!this.groundFirePreviewLit){for(let e of a.car.tires.filter(e=>!e.front)){let t=a.body.world(e.local);this.combustion.igniteTire(this.particlePoint(a.body.world(S(e.local,C(-2.4)))),this.particlePoint(t),a.car.preset.geometry.tireWidthM*o,18,.2*o)}this.groundFirePreviewLit=!0}let s=m(a.body.velocity),c=s>.1?v(a.body.velocity,-1/s):h(C(-1),a.body.angle);this.previewOilSplatter&&(s>.5?this.oilSplatterPreviewSeconds=0:s<.2&&(this.oilSplatterPreviewSeconds+=t),this.oilSplatterPreviewSeconds<2.25&&this.liquidLayer.pourOilPreview(n[0].point,t));let l={zoom:this.view.zoom,particlePoint:e=>this.particlePoint(e),particleVelocity:e=>this.particleVelocity(e),spray:(...e)=>this.sprayTirePaint(...e),smoke:this.tireSmokeEnabled?e=>this.volumetrics.emitSmoke(e):void 0};Rl(e,n,0,t,c,i,l,this.previewOilSplatter&&s<.2&&this.oilSplatterPreviewSeconds>1&&this.oilSplatterPreviewSeconds<2.25);let u=n.length;for(let{vehicle:e,tires:n}of r){if(!e.isGhost){let r=e.sim,i=m(r.body.velocity),a=i>.1?v(r.body.velocity,-1/i):h(C(-1),r.body.angle);Rl(e,n,u,t,a,this.particleVelocity(r.body.velocity),l)}u+=n.length}(e.isGhost||a.car.preset.sound.electric)&&(this.exhaustBursts=[]);for(let e of this.exhaustBursts){e.age+=t;let n=e.intensity*Math.max(0,1-e.age/e.lifetime);if(n<=0)continue;let r=h(C(-1,0),a.body.angle),i=S(v(r,4+5*n),v(a.body.velocity,.12));for(let e of this.vehicles.exhaustOutlets(a)){let o=a.body.world(e);if(this.combustion.emitJet(o,o,i,.13,n*.8,`exhaust`),n>.55){let e=S(o,v(r,1.45));this.volumetrics.emitSmoke({point:this.particlePoint(e),amount:t*n*.2,flow:this.particleVelocity(v(i,.48)),radiusPx:.13*this.particleScale(),swirlPx:7})}}}this.exhaustBursts=this.exhaustBursts.filter(e=>e.age<e.lifetime);let d=a.car.boostActive&&!e.isGhost;return d?this.combustion.stepBoostFire(a,t,e=>this.liquidLayer.igniteAtLocal(e)):this.combustion.clearTireHistory(),d}skidView(){return{pixelSpace:this.pixelSpace,zoom:this.view.zoom,width:this.view.width,height:this.view.height,screen:e=>this.particleScreen(e)}}vehicleLightInput(e,t,n){let r=D(e.sim.car.preset),i=e=>[-1,1].map(t=>C(e.xM*this.view.zoom,t*e.yM*this.view.zoom)),a=e.sim,o=this.vehicles.imageFor(a.car.preset)??void 0,s=o?k(a.car.preset,o.naturalWidth,o.naturalHeight):null,c=a.body.velocity.x*Math.cos(a.body.angle)+a.body.velocity.y*Math.sin(a.body.angle),l=a.lastInput,u=this.sceneScroll(),d=Math.max(l.brake??0,+!!l.action,+(l.throttle<0&&c>.5||l.throttle>0&&c<-.5));return{center:S(this.screen(a.body.position),this.carVisualOffset(a)),angle:-a.body.angle,width:(s?.lengthM??a.car.preset.geometry.lengthM)*this.view.zoom,height:(s?.widthM??a.car.preset.geometry.widthM)*this.view.zoom,mounts:{headlights:i(r.headlights),taillights:i(r.taillights)},image:o,source:s?.source,dark:e.appearance===`auto`?this.overlay?this.surfaceTones.at(e,this.viewportFromDocument(this.documentPoint(a.body.position)),t):t:e.appearance===`dark`,braking:d,options:this.vehicleLighting,opacity:n,walls:this.pixelSpace?this.wallRects.map(e=>({...e,x:e.x-u.x,y:e.y-u.y})):[]}}drawVehicleAndWeapons(e,t,n){performance.now(),f(`vehicle render passes`);let r=e.sim,{rocket:i,machineGuns:a,flamethrower:o}=e.weapons,s=this.ctx;if(e.isGhost){i.drawFlight(s,e=>this.screen(e),r.car.preset,this.view.zoom,t),a.drawProjectiles(s,e=>this.screen(e),this.view.zoom,t);return}let c=this.carVisualOffset(r);if(s.save(),s.translate(c.x,c.y),r.car.explodedAt===null){this.vehicles.car(this.ctx,r.body,r,e.damage,Math.max(o.openAmount,a.openAmount),e);let i=n??this.vehicleLightInput(e,this.darkSurface(),t);this.vehicleLights.glints(s,{...i,center:this.screen(r.body.position)})}let l;if(i.state!==`idle`||o.state!==`closed`||a.state!==`closed`){let t=this.vehicles.imageFor(r.car.preset);if(t){let n=k(r.car.preset,t.naturalWidth,t.naturalHeight),i=e.damage.spriteFor(t,n);l={image:i??t,source:i?{x:0,y:0,width:i.width,height:i.height}:n.source,lengthM:n.lengthM,widthM:n.widthM}}}r.car.explodedAt===null&&i.drawMount(s,this.screen(r.body.position),r.body.angle,r.car.preset,this.view.zoom,t,l),r.car.explodedAt===null&&o.state!==`closed`?o.drawMount(s,this.screen(r.body.position),r.body.angle,r.car.preset,this.view.zoom,t,l):r.car.explodedAt===null&&a.drawMount(s,this.screen(r.body.position),r.body.angle,r.car.preset,this.view.zoom,t,l),s.restore(),s.save(),this.clipFluidWalls(s),s.translate(c.x,c.y),r.car.explodedAt===null&&this.vehicles.exhaust(this.ctx,r),s.restore(),i.drawFlight(s,e=>this.screen(e),r.car.preset,this.view.zoom,t),a.drawProjectiles(s,e=>this.screen(e),this.view.zoom,t)}drawGroundLayers(e,t,n,r){let i=t.sim;if(!this.pixelSpace){let{left:e,right:t,bottom:n,top:r}=this.bounds();for(let i=Math.floor(e/5)*5;i<=t;i+=5)this.vehicles.line(this.ctx,C(i,n),C(i,r),`#293c46`);for(let i=Math.floor(n/5)*5;i<=r;i+=5)this.vehicles.line(this.ctx,C(e,i),C(t,i),`#293c46`)}for(let t of this.trail){let n=this.screen(t.point),i=1-t.age/this.trailLifetime;e.globalAlpha=.6*i*i*r,e.fillStyle=t.color,e.beginPath(),e.arc(n.x,n.y,.8+1.4*i,0,Math.PI*2),e.fill()}e.globalAlpha=1,e.save(),e.lineCap=`round`,e.lineJoin=`round`;let a=this.sceneScroll(),o=this.pixelSpace?{left:a.x,right:a.x+this.view.width,bottom:a.y,top:a.y+this.view.height}:{left:this.world(C(0,0)).x,right:this.world(C(this.view.width,0)).x,bottom:this.world(C(0,this.view.height)).y,top:this.world(C(0,0)).y},s=this.darkSurface();performance.now(),this.skidTracks.draw(e,{pixelSpace:this.pixelSpace,scroll:a,width:this.view.width,height:this.view.height,ratio:this.rasterPixelRatio(),dark:s,alpha:r,visible:o,view:this.skidView()}),performance.now();let c={pixelSpace:this.pixelSpace,scroll:a,width:this.view.width,height:this.view.height,particleScale:this.particleScale(),rasterRatio:this.rasterPixelRatio(),zoom:this.view.zoom,effectsAlpha:r,screen:e=>this.particleScreen(e)};return this.tireMarks.draw(e,[t,...n],!1,c),e.restore(),this.liquidLayer.draw(e,1),performance.now(),this.tireMarks.draw(e,[t,...n],!0,c),i.barrier&&!this.overlay&&(e.strokeStyle=`#d4ab71`,e.lineWidth=2,e.strokeRect(3,3,this.view.width-6,this.view.height-6)),{scroll:a,darkSurface:s}}render(e,t,n,r,i=[]){let a=e.sim;performance.now(),this.resize();let o=de(this.effectsFadeStartedAt,t);if(this.effectsFadeStartedAt!==null&&o===0&&(this.clearEffects(!1),o=0),this.view.cameraStep(a,t),this.canvasWorld&&t>=this.nextHistoryPrune){this.nextHistoryPrune=t+2e3;let e=this.documentPoint(a.body.position),n=2800,r={x:e.x-n,y:e.y-n,width:n*2,height:n*2};this.skidTracks.pruneOutside(r),this.tireMarks.pruneOutside(r),this.liquidLayer.pruneOutside(r)}let s=this.ctx;this.surface.clear();let c=this.screenShake.sample(t);s.save(),(c.x||c.y)&&s.translate(c.x,c.y),r?.drawGround?.(s,this.sceneScroll(),{width:this.view.width,height:this.view.height});let{scroll:l,darkSurface:u}=this.drawGroundLayers(s,e,i,o),d=new Map((this.primaryVehicleVisible?[e,...i]:i).filter(e=>e.sim.mode===`car`&&e.sim.car.explodedAt===null&&!e.isGhost).map(t=>[t,this.vehicleLightInput(t,u,o*(t===e?this.primaryVehicleOpacity:1))])),f=[...d.values()].flatMap(e=>this.vehicleLights.smokeLights(e));this.pixelSpace&&(s.save(),s.translate(-l.x,-l.y),Ve(s,this.debris.particles,{x:l.x,y:l.y,width:this.view.width,height:this.view.height},u,`ground`),s.restore());for(let t of this.primaryVehicleVisible?[e,...i]:i)t.sim.mode!==`car`||t.sim.car.explodedAt!==null||t.isGhost||t===e&&this.primaryVehicleOpacity<=0||(s.save(),t===e&&(s.globalAlpha*=this.primaryVehicleOpacity),this.vehicles.carGround(this.ctx,t.sim,t.damage,this.rasterPixelRatio(),this.vehicleShadowsEnabled),s.restore());for(let e of d.values())this.vehicleLights.ground(s,e);if(s.save(),performance.now(),this.clipFluidWalls(s),s.globalAlpha=o,s.save(),s.translate(-this.view.smokeMargin,-this.view.smokeMargin),this.volumetrics.drawSmoke(s,this.fluidView(),f.map(e=>({...e,point:S(e.point,C(this.view.smokeMargin,this.view.smokeMargin))})),u),s.restore(),s.restore(),s.globalAlpha=1,r?.draw(s,l,{width:this.view.width,height:this.view.height}),this.debugDrive&&a.mode===`car`&&a.car.explodedAt===null&&!e.isGhost){let e=this.screen(a.body.position);s.save(),s.beginPath(),s.arc(e.x,e.y,se(a.car.preset,this.view.width,this.documentScale())*this.view.zoom,0,Math.PI*2),s.strokeStyle=u?`#92cfff88`:`#12528e88`,s.lineWidth=1,s.setLineDash([5,6]),s.stroke(),s.fillStyle=u?`#b7ddff`:`#12528e`,s.font=`10px ui-monospace, monospace`,s.fillText(`Lightning influence`,e.x+8,e.y-se(a.car.preset,this.view.width,this.documentScale())*this.view.zoom+14),s.restore()}this.volumetrics.ghostAvailable&&(s.save(),s.globalAlpha=o,this.volumetrics.drawGhost(s,this.flameView(),u,f),s.restore()),this.primaryVehicleVisible&&a.mode===`car`&&(s.save(),s.globalAlpha*=this.primaryVehicleOpacity,this.drawVehicleAndWeapons(e,o,d.get(e)),s.restore(),this.debugDrive&&(r?.drawDebug?.(s,a,this,e.damage),this.diagnostics.draw(s,a,t,e=>this.screen(e),{width:this.view.width,rocketState:e.weapons.rocket.state,gunState:e.weapons.machineGuns.state,bulletCount:e.weapons.machineGuns.projectileCount,fluidEngine:this.volumetrics.smokeResolution.engine,quality:this.quality,fluidCols:this.volumetrics.smokeResolution.cols,fluidRows:this.volumetrics.smokeResolution.rows,fireCols:this.combustion.resolution?.cols??0,fireRows:this.combustion.resolution?.rows??0,groundedFireCount:this.combustion.count}))),this.primaryVehicleVisible&&a.mode===`ship`&&this.vehicles.ship(this.ctx,a.body,a),this.primaryVehicleVisible&&a.mode===`brick`&&this.vehicles.brick(this.ctx,a.body);for(let e of i){let t=e.sim;if(t.mode!==`car`||(this.drawVehicleAndWeapons(e,o,d.get(e)),t.car.explodedAt!==null))continue;let n=this.screen(t.body.position);s.save(),s.font=`600 10px ui-monospace, monospace`,s.textAlign=`center`;let r=e.label;if(!r)continue;let i=Math.max(30,Math.ceil(s.measureText(r).width)+14);s.fillStyle=`rgba(24, 27, 30, 0.88)`,s.fillRect(n.x-i/2,n.y-37,i,16),s.fillStyle=`#f5f2ec`,s.fillText(r,n.x,n.y-25),s.restore()}if(this.pixelSpace&&(s.save(),s.translate(-l.x,-l.y),Ve(s,this.debris.particles,{x:l.x,y:l.y,width:this.view.width,height:this.view.height},u,`air`),s.restore()),s.save(),this.clipFluidWalls(s),performance.now(),this.combustion.draw(s,this.flameView(),u,f),s.restore(),this.electricity.draw(s,t,u,o),performance.now(),this.sparks.draw(s,e=>this.particleScreen(e),o,{width:this.view.width,height:this.view.height},this.view.dpr,this.canvasWorld?void 0:this.surface.canvas),this.pointPuffs.length){s.save(),s.font=`700 13px ui-monospace, monospace`,s.textAlign=`center`,s.textBaseline=`middle`;for(let e of this.pointPuffs){let t=this.particleScreen(e.point),n=e.age/.9;s.globalAlpha=(1-n)*o,s.fillStyle=`#f8f4e9`,s.strokeStyle=`rgba(22, 24, 26, 0.85)`,s.lineWidth=3;let r=`+${e.amount}`,i=t.y-16-n*26;s.strokeText(r,t.x,i),s.fillText(r,t.x,i)}s.restore()}if(r?.drawForeground?.(s,l,{width:this.view.width,height:this.view.height}),performance.now(),r?.drawHealthBars?.(s,l,{width:this.view.width,height:this.view.height},e,this,i),n){let e=this.screen(n.from),t=this.screen(n.to);s.strokeStyle=`#ffdf93`,s.lineWidth=2,s.beginPath(),s.moveTo(e.x,e.y),s.lineTo(t.x,t.y),s.stroke()}s.restore(),this.objectGlint?.draw(s,this.view.width,this.view.height,this.darkSurface()),this.vehicles.drawVehicleMarkers(this.ctx,this.primaryVehicleVisible?[e,...i]:i,this.showVehicleMarkers),this.surface.presentLockedCamera(),this.liquidLayer.drawTextVehicles([e,...i].filter(t=>(t!==e||this.primaryVehicleVisible)&&t.sim.mode===`car`&&!t.isGhost&&t.sim.car.explodedAt===null).map(e=>({point:this.screen(e.sim.body.position),radius:Math.hypot(e.sim.car.preset.geometry.lengthM,e.sim.car.preset.geometry.widthM)*this.view.zoom/2+12})),c,t=>{for(let n of[e,...i]){if(n===e&&!this.primaryVehicleVisible||n.sim.mode!==`car`||n.isGhost||n.sim.car.explodedAt!==null)continue;let r=this.carVisualOffset(n.sim);t.save(),t.translate(r.x,r.y),this.vehicles.car(t,n.sim.body,n.sim,n.damage,Math.max(n.weapons.flamethrower.openAmount,n.weapons.machineGuns.openAmount)),t.restore()}}),this.governFluidQuality(t)}governFluidQuality(e){let t=performance.now()-e;if(!(t>=0&&t<1e3))return;let n=this.volumetrics.running||this.combustion.running;this.fluidGovernor.sample(e,t,n,this.quality)&&(f(`fluid quality limit ${this.fluidGovernor.limit}`),this.applyFluidQuality())}};export{su as n,cu as t};
|