From 13d9f831ae6f0d7015d744b7e5345691ca86b2da Mon Sep 17 00:00:00 2001 From: Mottributo <87079566+Mottributo@users.noreply.github.com> Date: Thu, 23 Mar 2023 00:06:30 +0300 Subject: [PATCH] starting --- favicon.ico | Bin 0 -> 15406 bytes game.js | 1195 +++++++++++++++++++++++++++++++++++++++++++++++ index.html | 12 + p5.min.js | 9 + p5.sound.min.js | 28 ++ sketch.js | 782 +++++++++++++++++++++++++++++++ 6 files changed, 2026 insertions(+) create mode 100644 favicon.ico create mode 100644 game.js create mode 100644 index.html create mode 100644 p5.min.js create mode 100644 p5.sound.min.js create mode 100644 sketch.js diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..b7e4442a178a5e0ba2429e3a914891458bacaf40 GIT binary patch literal 15406 zcmeI3c~n$qzOL2GLlLVXIYo0K22XQSC$O5dw4kB7B!!?vMZ_40Qxs&LL>#~&MvWR1 zG$d$5Q4|prwU7u-;2a^uOeV$*eUeUR=%o9ex$o)py{p%H@AGZNfV18Azk68gS(~cb zd%w^As`m8zzTK-=?_Rg`>f5&$)Be3OZ|&7<;~ps4z`f zUaXR)8kIKf)V!vBn%{I(3z|ArP&ZhGbso*A8wukTm;IRf+}cNk^`Lj}-f}08S4rJY zmDcUkyt<>BU)QPps=+F#@~E(Cq$V#Nu3K*FqX7d3C?zH3;_|Vvu^KdJkb1F>l;TAy zsoJN~s-v1$)v3Jl!OAc9sGxkLe(`v)Y(DqN{dlbAELfs(Pfyd66H=95T&mHD<7NMe zuO5E%G0iRCr;_rcDlP9+?()IPSvpKFZGJ)C!|gir+dt~#@BX(w`Tqa(z`S?%>;KZ; zV`sE>+i}f)e!ohVcdBsFNVUEFQIBQJyr)0=pE`NwE1fv=Tb(-ljn01aUl-SBK0kH# zJ1ulLO=50Rqi8j`4?eX46 z-~LI*-u+FF_sn|V`TSpX^xZFdyuW+jS!GU+R>SLudiWoC`=5HuXO=hbb+wC`wjB9P zb5f5gBXO`Y#yqaMx%t|>wNc04{#-}j`9dFj^}jBz!_42>`KjJG^R4Q(zpW)R_i4tM zLn=<}R7M=j$9a?)H&R(~09%V$0RA$t8WkpRl^?ZE1yMCBjM}LgQRGJ*RZ&!@riTp% zkJ7_NDkE&XGQ*}QD=bS{kwtp<^MA9pdG3?zloz&6`C&CG2-~T`uzhe;Gr~HR7Caa{ znjSn->B0C1Pf=zt%Lf;!ZtHO!Km8@IUsP@|>jV5Fu8 zj8}TV6lDZtDKnr*i&EC;wWTe}4p^<6fOX0Zs8L?PPUQ#eQ$YaB2Xty$-@!`l>w%F< z>pNc4`%Y1M-z;VHEmFFpMA@OwE35BnW%pgDoW3>6?YmQXefKH9?@<->?KJz?-}GmW zGyP#GnB&vc{tBBTG^05RqE*y94B{a{Gn>ajvWlB0!8FKJ@!lLw-#Aq&Fu5j=&@<(;G`p!nCCwXD+Pnp7HLrOGcs0Md84f_37BruL4lQgxt-{6# zAipsh$ZsUSk^DyT85d&h{*Goi0OapD0p#yEt%BMJAip*m$ghnD@@vO2P1d-1F}nS(t8a7n z-0uJP?$bw)KRrQnw~}A$g=QeXwhhRy?Evzt$*+zA@~ejd`PB(9PU+=iUdho#qFMf8*ZMSJc$zqjMlV44K^#LHi`UH?)eOmeJ$zM3R!ZbSRY30v;R?Ew)w61oKYB|sE+~2O92Rc;0_qaCHH|wR>YBX!X za*dyqrh$VVlik-(=6B$JVv^>rB7fBZXan+BbpZJ*$zMtS%4nv;l)G%WG8QDMcxkED zZrN>}E6usjoGZG{Gnbx&yT9(5@7(Wx&|9DWL0cOStMvH_6+XL3Gneks+!x4SN&ZUm zSDsexQu3EZDQC%0Wz0*|nr&Ov`RVU(D64z!wf;9w@BijMv~BMx&3dj@#fw^1va|!p ze>OrHC68%g*#dQb^8NqQ+)JH|hq;bfv*n-)X7AP9g{PG1!OJ=Ce)7cj5)pE_%``Srdh^ZC}sb`=yIRA$i_+UDOco|C(>x=+pg z=GtX@%Sj#T_?T;;f3dEIKE7}rWW3BZn7OtxZf3srkA8Q}b(&=sFZXKM>gCsMbF<#M z*Nv{dxeO=~%Gw(L`cQd{8vn#ze-@*0T|IBayQ^olWTxUioH)j&_e|ydK zHy=NvH$VRVy7|V@d{P&_xH?xzWdOdSDerMUJtzSiDu{4YsORDE2NxO=C}xmf@q~Ca=(i$5-);B2OaE^=@~*WXbiIFmd;h4$gYRomNrQ3{8&sThT(ib?0Q-Le`3dAF zL@O&{7}I!7A2mv8Nhz8?=Q&kvZq$L3XZ7}H|E!jiALxw_zqx9@$*OHSVqG5}IsLh6 z8%}E3a}CN%*`VB!+f|gXUo#WhRGe@E$WI_Yp7xI?KRz1BkB{e?J^{u-vNDEGP+Ht1 zrH!1f?35W=v*GIdl{qdK0OeW-L#~SAoX1~LLCgjf#%zIF z&4?jChWr@vV-5iMF(-ihnA1vkM*#WmXdvHBzMFhE`R-&O-#rb;cjqWAI!A4tpIx5M z?_zHD8s-0LtqR;5fP8l?kni?FGm!6Y1M=M+K>iT&heQGSLxutQLlR&dkUxa`t|8

@&|4J@(0!e`2)Ss z4CD`N1M&xU0QsThhqC{Nk{>z@$PZ0`aX^0PBp^RD6UYxORNA8j+IQl^i)~=`$)c1p z<%X6kFLW)CAG!s|58VOehms$90LTwL0py3CR+=*c$ah8q`ObJC-$}lc-@lW5=QJSS zN&7nsVU|`d{_*&J{GBf~HS}5KI>~pE?J};AOXl9K>mP9K>mPCAb$Y)17<1n@sf-8@)a*PDl3S4*#YIS7B(nvz!o5Xzz!gP zKr@g(fcya`fcyccmD(=?$nO^otk=2J-t&1M>UjKq1Uh+C#In=iuAc zzL+;+xpMlg0`mKj-;d)>Kl1z40{Q*CKz_di&<5o9>j3io$@eGUpM3veK)!zhknc~v z|0E#aKNHCJC*Pm#_b=7b;tgu+_)O3I{d{HnlkZ;+`_C$oC=NXBd$0lK|xVBm?{O+1DAkOeD>bK?dP>VWs8VSQHH{W( zy)D}`uVp*zf=116*$dQuTc~fev}!>MHDIp67qql%VM`}a=V+qNVbzrJZ^FNcYn>+i zoA9T`T-1br6aH4M8UH5ysW}%n;op>@{Dw3ouSinF_+RSpLj!b={hkZ;dZC7me^a|v z%U;-ozZZWmHEl2cUi`iId-3<;@5SGXzZZWm?e9$i{Jm3{rYd9OL=8%MRJI3fSFC~a z)py&5AOAP^_;=oWw|*88X4RDD?%JeMFYWKe-@6^~_u}u}3$(u%e=q)CYUp14z4&`O z0sjX48}M&%0sam6H^jmSz`tP(B*Az{fr%=tpQMy!qx4|tPifcg?fj$T)!Z+A|K6Y2 z6_@dhindg$qyhg1{2O)w{tfsyQ2TG7KGcAJ1O8k)&TqiK0sjW-MD_UB<6n<|{ZPQa z9{+m$>*-^t$G;x`di?8CsAWB^#JL{b-~T69Y}-ryZshe{wtKC**S7=y_4wCNXR4u3qXz#P{A=jjsKLJm{~G*j@UOwYW<39=XyWrv z=z)iD?|t)aeXVV|^WJ+EH+7okY^hgC4gNLw*X#xQPHOP4!M}z+lp6eN@UQ8Ft~wq5 z)h@ul8vp887y}(x8NX;TMQ)XMbJ9Yox?6;3S_L#h0 zuhy+w*P|xcHQz(j)N)>0PoEY3Rrp(dSJdaKS}*ir;a}Bm^<~Yk!oQL_VI}QfiGL;j zmGo^@;$Mk>CH|H8S0-ulbHn8uaNlKarrl4SI;Fq-(f5jN(zdBZ)2?KTO?YCT(ch_BaY1OJ#`tr*!wPM8z>a9Q4g)j9tHP6Jv zM4dZ#PREWNlhf(EY<-+<^+<$UMP+r=MfU=Ie^z}I{|fvoP6GZF_?tRuIqh%tDY}^A zUvByq@h=}?^)VJwtImEgK_NpPx@?~{HQKxI{aNtC8lODD>WBQrpdlLK_Q=is=Hqdr z_c$kuLpmuuJ2fdRkGx8mjyH+NtkeUW4~_JgAI?uhD0Tztwk1eYG5a zs}B?Z@^-+#9RD)voMnRn|FWUr0sPDGFB=JCl(y&z{q!MUYkxESr4NVvTw|V`NKJQz z$~SDM26RMCN8Zt)H$SG&@N=E~;48JC{nn}pc6|JuRr5J@_G{`%zfs#;pHVM3qlSH_ zR9V}kMJp>bWqQ5_4f&Ps|2u!HUVX=%_b54YvF4WHUq<_v;a^5=wCpJ0Uxt5KCv??` z@n4DmO8i%P_&=8EaQbSWP}Y($nmT*D66qhFzwBl0I`}5_)ZbfmO>=){?#~U~?-_68 z|E}fC)ZF*K`^CS}XZeX%SJrD{YK|sm&R5}cTQzf;S94z2uemE*0socwuf%^P{-(~n zoc5vpuGNeCL6;G^2ErX3X8MISV^9_u13RnNOW&PNZ^5 zCTPe0BUTObulbF1wVC;ieL$Vqw413lni{vkj4wFz<$qe=XV-pnGuvd=Z`N)4`j@=4 zQ~5KSHD}&i%A}tmqc~AbM?0<0Z`R$+Z~B4EF=yAo4pr|wpsF4Ftm&5Bt*Y_1X$#lB z)w>Q_?{A`pT1UO~(3_v={V)IHruL_^O)?W!|y9MZ--KI;x`n)gcYndQxxnYCNI zR~^4|rR6St&#cFMFB`Y-Q|+E3H|%fLW48afm76p*eH7=)Z*FQ?lY9KVFZuqPt^7;9 zZsxV=6Dp=}cF*B=ZrGt~yXP%luhg`m+P3GQwLLeJYsM(8+uC$P{eo9puk}6B@Aul) zJ=VTqUSDnA?(duVPJQ^Ta?y*B;Yb$d@-x9`(9nD3|M#7CMpcdK&7?^e-M zCp9biP0dd3>Sx4%oC}63Jtt>PS8Ku4xLs%W#(Age=PoE zUCJ6e6u5p)q`x2`PSX+@ualLp7hhV-wzM%;;0x=#(X}lm$MoM;RPVCJJ9hWD*8gTX zbNyiY-n*~MoD<(X_r3NUdQWTD9niwr^~z1&tlZJNRFrr~GshlP@mSh^EdFEhA4@;u zX#7XxKbrO*Jrq338Xe1Y1Te;M6gB@*V>LZ7MHwm7JPYP))hnCT(0oeAxRx^Kesc~s zza!&yE$^<+jI+5;GGi>waj=;&s_QrJ)3ft8a!h$eIZ5l4H+q{2M)6x2P5W=lgl%IR02;O7V}w-x^zre;n;^jWNYPF3B2e znjM#-?6`@*n9;aYWyhu~YgmRdhcSM0LNQ}rKfmsGVEpSEk86@^0pnBYlZ>TLG#2kT z#+t@)T#4Hb_{ZTNhrcy;mG+Or-x|Y;e;oddWi5`Q{XO`5Xn&6j@b}RE9{fG{dl=*D z!QX?whxYg2@4?@Lzb92Wo(#x>TxE=4JZ}B9&*R43+=tAXL7!H1xe7d$P^Ci8X29Qr zzXyL0{vP~2_&&`-zH~wzMT2cGRaO3aB-;KW;e>eVa z{M{*lzZ-uy?eE6ljlUcJp?P}#xk~GrzUy~>>D2hQb^coEqnFShzD5OZ{M}W6zZ-w| zHrNjMyBlFIF!tB#A8)09oH4*|{N3%)dA^_A#r>BHe;58P{9X9FVgY{_{;n~AzYBjC z{;r9DzYBj?24q1lnS|_($R&c@prC#6OaL`f&Q`!x@tuj(<4kuW-g@hvOfPe>lg_ zaQwsZ563?|1ttRi;i-@T_=n>kUchn%DlIOv?rkpp?U>gm-}_40qn0UW;LFMj$3GnZ z@G8JR9RF~Rnc>?3|L{iG3yj?k$3MIk7y}-Te|S4|0{&t6TVu-c55qsqj4h7^{H-zO zW0>M^jWx$V41dO)XNKV)hJP5xo-q8w3YZpgY%Q?v56y4A`!<-@Tj_t8`U}PbguTM} z^fiEg82(|KFN{^kKMen{U4VZW{?^!a{KN3K#<1fbhJP6TVfcsOA42u~Sz*zSX{6p{$!9N855d1^%55YeK|B#uQ`tv-kt@2)WJz=gv0of5=I|KLr1fu5lKOsdwV< z914uhcjE8F-^mz#C;m?So%lOB2Rre1;_pla{GIqa*?*n*J7+5MA7`m>>SC*2()Ar! z$DOx+tqFr>DaW~r@fi3!@pt0y#NUa(6MyG6z~70#vk~?J{?_=6R;G;McjE7ChtBik zG=dqYVLelTe=z>R=Gg-LgYmbXF&M)Xf9qKT{DUW6c;*2AV9s5^S%7~q{=qY0w$h@C z)qLdri{~YAlg631^5Ty9~28Cfc6i@DJjdhamie@DIX2 z2>&4bgYXZUt@KA`Yt5^>x$gawwGWt@Nmk+_Yb;7m5dJ~<2d#lhz&~g+@T^1-{z3Q$ z?E?IR@DIX22>&4bgJ}PtlYoB^{y~fr31pl|AkS0;;vYB^cs3&t|3Lf$c}61;|3Lf$ zc~&Ek>z_dU1Mv@}|2Gi-K>P!9p#b>(1mfR+j^?GkOx^ALSih!&?=p^Oo^k@qfM+`b z@ejm55dXj`z&{ZGz-_P{@DFT+y?}op<4XctfoC`Z@egc=PQX6^f1W8x4ZuGDf9u(j zSf=<}&zOv1iof-&3H|{SFFbRCe?W%y>`6ud{sH(0;2$s>N*FIzq5~&Bwyxt}exZSF zTEa6a_*>7WaE%#&e*pdg_y=%}Y(1-je*pdgy8!9e+FicKq%5+wr&KZ^z$`za4*j z3gB4SyT{HvDb)+wix=0{%AqZS;TH@VDV_ z!{0U$@VDV_!{3$#_}lQe;cvs=RtocZzG|N0?`NEpZ3(YmP?imU8~!%@ZEFC38~(P< sfWHlY8~(OkfWHlY8~!%@ZTQ>px8ZNY--f^KzsE_@$NS%Ze?trWUyEhrY5)KL literal 0 HcmV?d00001 diff --git a/game.js b/game.js new file mode 100644 index 0000000..80a56ff --- /dev/null +++ b/game.js @@ -0,0 +1,1195 @@ +var translateration = 0; +var fps = 0; +var isDebug = false; +var draw_grid = false; +var plummetingSoundNotPlayedBefore = false; +var text_hor_unit; +var text_vert_unit; +var sfx = {}; +var mus = {}; +var skydecay = 0; +var fps_recent_values = []; +var random_values = []; // from 0 to 1 +for (i = 0; i < 500; i++) { + random_values[i] = Math.random(); +} +var memorized_platform; +var amounts = { + tree: 200, + cloud: 200, + mountain: 200, + canyon: 80, + collectable: 23, + enemies: 30, + platforms: 50, +}; +var env = { + skyColor: 0, //assigned at setup() + floorPos_y: ((512 + 256) * 3) / 4, + groundColor: "#7F562A", + end_x: 3000, + state: "INTRO", + isSoundEnabled: false, // never set it true. it causes premature playing of the game sfx and music before loading. + isMusicEnabled: false, +}; +class Entity { + constructor(x, y) { + (this.x = x), + (this.y = y), + (this.size = 1.5), + (this.speed = 8), + (this.score = 0), + (this.lives = 3), + (this.health = 100), + this.prejump_y, + (this.gravity = 1.5); + this.vert_speed = -1; // Is negative. + (this.state = { + isLeft: false, + isRight: false, + isFalling: false, + isJumping: false, + isPlummeting: false, + isDescending: false, + isAscending: false, + }), + (this.projectiles = []); + } + resetValues() { + this.size = 1.5; + this.speed = 7; + } +} +var gameChar; +var flagpole = { + x: env.end_x, + isReached: false, + size_vert: 4, + size_hor: 7, + cell_size: 20, + cell_size_v: 20, + cell_size_h: 20, +}; + +class Cloud { + constructor(x, y, size) { + this.x = x; + this.y = y; + this.size = size; + } +} +class Canyon { + constructor(x, width) { + this.x = x; + this.width = width; + } +} +class Collectable { + constructor(x, y, size, worth) { + this.x = x; + this.y = y; + this.size = size; + this.worth = worth; + } +} +class Enemy extends Entity { + constructor(x, y, damage, sin_x_speed, sin_y_speed) { + super(x, y); + this.damage = damage; + this.sin_x_speed = sin_x_speed; + this.sin_y_speed = sin_y_speed; + } + collidesWith(whoCollidesWith) { + let temp_x = this.x; + let temp_y = this.y; + this.x = this.x + 25 * Math.sin(frameCount / this.sin_x_speed) - 15; + this.y = this.y + 50 * Math.sin(frameCount / this.sin_y_speed) - 20; + if ( + Math.abs(whoCollidesWith.x - this.x) < 24 * this.size && + Math.abs(whoCollidesWith.y - this.y) < 24 * this.size + ) { + return true; + } + this.y = temp_y; + this.x = temp_x; + return false; + } + + drawEnemy() { + // lazy so its just a game character model, but with a black hat and no body. + let temp_y = this.y; + let temp_x = this.x; + this.x = this.x + 25 * Math.sin(frameCount / this.sin_x_speed); + this.y = this.y + 50 * Math.sin(frameCount / this.sin_y_speed); + drawGameChar(this.x, this.y, 1, this.size, false, color(this.damage, 100)); + this.y = temp_y; + this.x = temp_x; + } +} +class Platform { + constructor(left_x, right_x, y) { + this.left_x = left_x; + this.right_x = right_x; + this.y = y; + } + + isInXBorders(whoCollidesWith) { + return whoCollidesWith.x > this.left_x && whoCollidesWith.x < this.right_x; + } + isUnder(whoCollidesWith) { + return this.isInXBorders(whoCollidesWith) && whoCollidesWith.y < this.y; + } + isOver(whoCollidesWith) { + return this.isInXBorders(whoCollidesWith) && whoCollidesWith.y > this.y; + } + drawPlatform() { + push(); + rectMode(CORNERS); + fill(env.groundColor); + rect(this.left_x, this.y, this.right_x, this.y + 10); + pop(); + } +} + +var mountains_x = []; +var trees_x = []; +var enemies = []; +var clouds = []; +var canyons = []; +var collectables = []; +var platforms = []; +var cnv; +var win_img; +var gameover_img; + +function preload() { + soundFormats("mp3", "ogg"); + sfx.enemy = loadSound("../assets/sfx/enemy.ogg"); + sfx.falling = loadSound("../assets/sfx/falling.ogg"); + sfx.gameover = loadSound("../assets/sfx/gamover.ogg"); + sfx.jumping = loadSound("../assets/sfx/jumping.ogg"); + sfx.levelcomplete = loadSound("../assets/sfx/levelcomplete.ogg"); + sfx.plummeting = loadSound("../assets/sfx/plummeting.ogg"); + sfx.coin = loadSound("../assets/sfx/coin.mp3"); + /* "Midnight Tale", "Take a Chance" and "SCP-x5x" Kevin MacLeod (incompetech.com) + Licensed under Creative Commons: Attribution 4.0 License + http://creativecommons.org/licenses/by/4.0/ */ + mus.level = loadSound("../assets/Midnight Tale.mp3"); + mus.win = loadSound("../assets/Take A Chance.mp3"); + mus.gameover = loadSound("../assets/SCP-x5x.mp3"); + win_img = loadImage( + "https://static.wikia.nocookie.net/someordinarygamers/images/8/88/Bp_1401520973_youre_winner.png" + ); + gameover_img = loadImage("../assets/gameover.png"); +} +function drawFlagpole() { + push(); + strokeWeight(0); + fill(0); + translate(translateration, 0); + + if (flagpole.isReached && flagpole.cell_size_h > -flagpole.cell_size) flagpole.cell_size_h--; + // the flagpole pole + rect(flagpole.x, env.floorPos_y / 2, 2, env.floorPos_y / 2); + + // the flagpole flag + for (i = 0; i < flagpole.size_hor; i++) { + for (j = 0; j < flagpole.size_vert; j++) { + fill(((i + j) % 2) * 255); + rect( + flagpole.x + flagpole.cell_size_h * i, + env.floorPos_y / 2 + flagpole.cell_size_v * j, + flagpole.cell_size_h, + flagpole.cell_size_v + ); + } + } + pop(); +} +function drawGameChar(x, y, sprite, scale, has_body, hat_color, hand, width_mod, height_mod, jump_shift) { + // Note: + // The drawing starts at bottom-middlecenter! not at top-left! + // The aspect ratio is 5:8. + if (has_body == undefined) has_body = true; + if (hat_color == undefined) hat_color = "red"; + if (scale == undefined) { + scale = 1; + } + if (width_mod == undefined) { + width_mod = 1; + } + if (height_mod == undefined) { + height_mod = 1; + } + if (jump_shift == undefined) { + jump_shift = 12; + } + var ax_step = 5 * scale * width_mod; + var ay_step = 8 * scale * height_mod; + jump_shift = jump_shift * scale; + function _drawDefaultHat() { + strokeWeight(1); + stroke(0); + fill(hat_color); + ellipse(x, y - ay_step * 6, ax_step * 10, ay_step * 3); + ellipse(x, y - ay_step * 6, ax_step * 4, ay_step * 1); // x +0.5 * scale is a minor fix of misalignment. May become a bug. + strokeWeight(1); + beginShape(); + vertex(x - ax_step * 2, y - ay_step * 6); + vertex(x, y - ay_step * 10); + vertex(x + ax_step * 2, y - ay_step * 6); + endShape(); + } + function _drawDefaultBody(jumping) { + if (jumping) { + strokeWeight(1); + stroke(1); + fill("brown"); + triangle(x - ax_step * 2, y - ay_step * 1.5, x, y - ay_step * 4, x + ax_step * 2, y - ay_step * 1.5); + } else { + strokeWeight(1); + stroke(1); + fill("brown"); + triangle(x - ax_step * 2, y, x, y - ay_step * 4, x + ax_step * 2, y); + } + } + function _drawDefaultHand(direction) { + switch (direction) { + // to left + case 0: { + line(x, y - ay_step * 2.5, x + ax_step * 0.8, y - ay_step * 1); + break; + } + // relaxed + case 1: { + line(x, y - ax_step * 4, x, y - ay_step); + break; + } + // to right + case 2: { + line(x, y - ay_step * 2.5, x - ax_step * 0.8, y - ay_step * 1); + break; + } + // relaxed; doubled for easy animation cycling + case 3: { + line(x, y - ax_step * 4, x, y - ay_step); + break; + } + // relaxed + default: { + line(x, y - ax_step * 2.5, x, y - ay_step); + break; + } + } + } + switch (sprite) { + // Standing, facing frontwards + case 1: { + // Body + if (has_body) _drawDefaultBody(); + // Head + fill(0); + ellipse(x, y - ay_step * 5, ax_step * 6, ay_step * 4); + // Eyes + fill(255); + ellipse(x - ax_step * 1.2, y - ay_step * 4.2, ax_step / 1.5, ay_step / 2); + ellipse(x + ax_step * 1.2, y - ay_step * 4.2, ax_step / 1.5, ay_step / 2); + // Hat + _drawDefaultHat(); + break; + } + // Jumping, facing forwards + case 2: { + y -= jump_shift; + // Body + if (has_body) _drawDefaultBody(true); + // Hands. (Hands!) + line(x - ax_step * 1, y - ay_step * 2.5, x - ax_step * 3.2, y - ay_step * 3.2); + line(x + ax_step * 1, y - ay_step * 2.5, x + ax_step * 3.2, y - ay_step * 3.2); + // Head + fill(0); + ellipse(x, y - ay_step * 5, ax_step * 6, ay_step * 4); + // Eyes + fill(255); + ellipse(x - ax_step * 1, y - ay_step * 3.8, ax_step / 1.5, ay_step / 2); + ellipse(x + ax_step * 1, y - ay_step * 3.8, ax_step / 1.5, ay_step / 2); + + // Hat + _drawDefaultHat(); + break; + } + // Walking left + case 3: { + // Body + if (has_body) _drawDefaultBody(); + // Hand. (Hand!) + if (has_body) _drawDefaultHand(hand); + // Head + fill(0); + ellipse(x, y - ay_step * 5, ax_step * 6, ay_step * 4); + // Eyes + fill(255); + ellipse(x + ax_step * 1.2, y - ay_step * 4.2, ax_step / 1.5, ay_step / 2); + // Hat + _drawDefaultHat(); + break; + } + // Walking right + case 4: { + // Body + if (has_body) _drawDefaultBody(); + // Hand. (Hand!) + if (has_body) _drawDefaultHand(hand); + // Head + fill(0); + ellipse(x, y - ay_step * 5, ax_step * 6, ay_step * 4); + // Eyes + fill(255); + ellipse(x - ax_step * 1.2, y - ay_step * 4.2, ax_step / 1.5, ay_step / 2); + // Hat + _drawDefaultHat(); + break; + } + // Jumping left + case 5: { + y -= jump_shift; + // Body + if (has_body) _drawDefaultBody(true); + // Hands. (Hands!) + line(x - ax_step * 1, y - ay_step * 2.5, x - ax_step * 3.2, y - ay_step * 3.2); + line(x + ax_step * 1, y - ay_step * 2.5, x + ax_step * 3.2, y - ay_step * 3.2); + + // Head + fill(0); + ellipse(x, y - ay_step * 5, ax_step * 6, ay_step * 4); + // Eyes + fill(255); + ellipse(x - ax_step * 1, y - ay_step * 3.8, ax_step / 1.5, ay_step / 2); + + // Hat + _drawDefaultHat(); + break; + } + // Jumping right + case 6: { + y -= jump_shift; + // Body + if (has_body) _drawDefaultBody(true); + // Hands. (Hands!) + line(x - ax_step * 1, y - ay_step * 2.5, x - ax_step * 3.2, y - ay_step * 3.2); + line(x + ax_step * 1, y - ay_step * 2.5, x + ax_step * 3.2, y - ay_step * 3.2); + + // Head + fill(0); + ellipse(x, y - ay_step * 5, ax_step * 6, ay_step * 4); + // Eyes + fill(255); + ellipse(x + ax_step * 1, y - ay_step * 3.8, ax_step / 1.5, ay_step / 2); + + // Hat + _drawDefaultHat(); + break; + } + // Error + default: + fill("red"); + text("Character error - No or wrong sprite number provided", x, y); + break; + } +} +function drawTree(x, y, scale, type, hasLeaves) { + // x, y are the middle bottom of the tree. + noStroke(); + fill(255); + if (hasLeaves == undefined) { + hasLeaves = true; + } + if (scale == undefined) { + scale = 1; + } + if (type == 0) { + fill(110, 87, 20); + triangle(x - 15 * scale, y, x, y - 150 * scale, x + 15 * scale, y); + fill(63, 72, 52); + if (hasLeaves) triangle(x - 45 * scale, y - 45 * scale, x, y - 120 * scale, x + 45 * scale, y - 45 * scale); + if (hasLeaves) triangle(x - 45 * scale, y - 85 * scale, x, y - 180 * scale, x + 45 * scale, y - 85 * scale); + } else if (type == 1) { + fill(147, 105, 7); + triangle(x - 10 * scale, y, x, y - 120 * scale, x + 10 * scale, y); + fill(78, 61, 31); + if (hasLeaves) { + ellipse(x, y - 50 * scale, 80 * scale, 30 * scale); + ellipse(x, y - 70 * scale, 100 * scale, 30 * scale); + ellipse(x, y - 90 * scale, 80 * scale, 30 * scale); + ellipse(x, y - 110 * scale, 40 * scale, 30 * scale); + } + } +} +function drawCloud(cloud) { + if (cloud.size == undefined) { + scale = 1; + } + noStroke(); + + fill(200); + ellipse(cloud.x - 20, cloud.y - 10, 50 * cloud.size, 30 * cloud.size); + + fill(220); + ellipse(cloud.x + 20, cloud.y - 20, 70 * cloud.size, 50 * cloud.size); + + fill(255); + ellipse(cloud.x, cloud.y, 90 * cloud.size, 40 * cloud.size); + ellipse(cloud.x + 45, cloud.y - 10, 50 * cloud.size, 35 * cloud.size); +} +function drawMountain(x, m_width, m_height, skew) { + noStroke(); + fill(60); + triangle(x - m_width, env.floorPos_y, x + skew, m_height, x + m_width, env.floorPos_y); + fill(90); + triangle(x - m_width, env.floorPos_y, x + skew, m_height, x - m_width / 1.5, env.floorPos_y); + fill(170); + triangle( + (4 * x - m_width + 3 * skew) / 4, + (env.floorPos_y + 3 * m_height) / 4, + x + skew, + m_height, + (4 * x + m_width + 3 * skew) / 4, + (env.floorPos_y + 3 * m_height) / 4 + ); +} +function drawCanyon(canyon) { + noStroke(); + let x = canyon.x; + let c_width = canyon.width; + fill(90, 30, 0); + quad( + x - c_width / 2, + env.floorPos_y, + x + c_width / 2, + env.floorPos_y, + x + c_width / 2, + height, + x - c_width / 2, + height + ); + + fill("blue"); + quad( + x - c_width / 20, + env.floorPos_y, + x + c_width / 20, + env.floorPos_y, + x + c_width / 20, + height, + x - c_width / 20, + height + ); + + fill(30); + quad( + x - c_width / 2, + env.floorPos_y, + x + c_width / 2, + env.floorPos_y, + x + c_width / 10, + env.floorPos_y + env.floorPos_y / 40, + x - c_width / 10, + env.floorPos_y + env.floorPos_y / 40 + ); +} +function drawCollectable(collectable) { + let x = collectable.x; + let y = collectable.y; + let size = collectable.size; + let worth = collectable.worth; + strokeWeight(0.5); + fill(253, 195, 52); + ellipse(x, y, 3.5 * size, 3.5 * size); + fill(171); + ellipse(x, y, 3 * size, 3 * size); + fill(253, 195, 52); + ellipse(x, y, 2.5 * size, 2.5 * size); + fill(200, 150, 30); + textSize(size * 1.5); + textAlign(CENTER, CENTER); + fill(0); + text(worth, x, y); + + textSize(12); + textAlign(LEFT, TOP); +} +function drawSky() { + background(env.skyColor); +} +function drawAudioSymbol() { + push(); + fill(0); + strokeWeight(4); + triangle( + width - text_vert_unit * 5, + text_hor_unit * 7, + width - text_vert_unit * 4, + text_hor_unit * 5, + width - text_vert_unit * 4, + text_hor_unit * 9 + ); + if (env.isSoundEnabled) { + arc(width - text_vert_unit * 3, text_hor_unit * 7, text_hor_unit, text_vert_unit * 1.5, (3 * PI) / 2, PI / 2); + arc(width - text_vert_unit * 3.5, text_hor_unit * 7, text_hor_unit, text_vert_unit, (3 * PI) / 2, PI / 2); + } + textSize(text_vert_unit / 2); + strokeWeight(0); + pop(); +} +function drawMusicSymbol() { + push(); + fill(0); + strokeWeight(4); + rectMode(CORNERS); + if (env.isMusicEnabled) { + line(width - text_vert_unit * 4.5, text_hor_unit * 15, width - text_vert_unit * 4.5, text_hor_unit * 11); + line(width - text_vert_unit * 2.5, text_hor_unit * 14, width - text_vert_unit * 2.5, text_hor_unit * 10); + line(width - text_vert_unit * 4.5, text_hor_unit * 11, width - text_vert_unit * 2.5, text_hor_unit * 10); + } + ellipse(width - text_vert_unit * 4.5, text_hor_unit * 15, text_vert_unit / 2); + ellipse(width - text_vert_unit * 2.5, text_hor_unit * 14, text_vert_unit / 2); + pop(); +} +function playSound(sound, volume, isMusicEnabled) { + if (volume == undefined) volume = 1; + if (env.isSoundEnabled) { + sound.play(0, 1, volume); + } else { + sound.stop(); + } +} +function playMusic(sound, volume) { + if (volume == undefined) volume = 1; + if (env.isMusicEnabled) { + sound.play(0, 1, volume); + } else { + sound.stop(); + } +} + +function drawMountains() { + push(); + translate(translateration * 0.3, 0); + for (i = 0; i < mountains_x.length; i++) { + drawMountain( + mountains_x[i], + 100 + 200 * random_values[i + 121], + 400 - 50 * random_values[i + 211], + 50 * random_values[i + 8] + ); + } + pop(); +} +function drawClouds(areMoving) { + push(); + translate(translateration * 0.6, 0); + for (i = 0; i < clouds.length; i++) { + push(); + if (areMoving) translate(frameCount * random_values[i], 0); + drawCloud(clouds[i]); + pop(); + } + pop(); +} +function drawCanyons() { + push(); + translate(translateration, 0); + for (i = 0; i < canyons.length; i++) { + drawCanyon(canyons[i]); + fill(200, 150, 0); + } + pop(); +} +function drawTrees() { + push(); + translate(translateration, 0); + for (i = 0; i < trees_x.length; i++) { + drawTree(trees_x[i], env.floorPos_y, 0.5 + random_values[i], Math.round(trees_x[i]) % 2); + } + pop(); +} +function drawCollectables() { + push(); + translate(translateration, 0); + for (i = 0; i < collectables.length; i++) { + drawCollectable(collectables[i]); + } + pop(); +} +function drawPlatforms() { + push(); + translate(translateration, 0); + for (i = 0; i < platforms.length; i++) { + platforms[i].drawPlatform(); + } + pop(); +} +function manageEnemies() { + push(); + translate(0, 0); + for (i = 0; i < enemies.length; i++) { + enemies[i].drawEnemy(); + for (j = 0; j < gameChar.projectiles.length; j++) { + if (enemies[i].collidesWith(gameChar.projectiles[j])) { + enemies.splice(i, 1); + gameChar.projectiles.splice(j, 1); + i = 0; + j = 0; + playSound(sfx.enemy); + } + } + if (enemies[i].collidesWith(gameChar) && env.state == "LEVEL") { + background(255 * random(), 255 * random(), 255 * random()); + playSound(sfx.enemy, enemies[i].damage / 10); + gameChar.state.isPlummeting = true; + } + } + pop(); +} +function drawInterface() { + push(); + translate(-translateration, 0); + fill("black"); + rect(0, 0, width, text_vert_unit * 2); + + stroke("red"); + line(0, text_vert_unit * 2, width, text_vert_unit * 2); + fill("red"); + textFont("Courier New"); + textSize(text_vert_unit); + text("Score: " + gameChar.score, width - text_vert_unit * 7, text_hor_unit * 2); + text("Lives: " + gameChar.lives, width - text_vert_unit * 14, text_hor_unit * 2); + // Debug things + drawAudioSymbol(); + drawMusicSymbol(); + if (isDebug) debug(); + pop(); +} +function shootProjectile() { + playSound(sfx.coin, 0, 1, 0.5); + let projectile = { color: "red", x: gameChar.x, y: gameChar.y - 45, direction: 0 }; + if (gameChar.state.isLeft) { + projectile.direction = -15; + gameChar.projectiles.push(projectile); + } else { + projectile.direction = 15; + gameChar.projectiles.push(projectile); + } +} +function updateProjectiles() { + for (i = 0; i < gameChar.projectiles.length; i++) { + push(); + stroke(gameChar.projectiles[i].color); + strokeWeight(4); + line( + gameChar.projectiles[i].x, + gameChar.projectiles[i].y, + gameChar.projectiles[i].x - 30, + gameChar.projectiles[i].y + ); + pop(); + gameChar.projectiles[i].x += gameChar.projectiles[i].direction; + if (gameChar.projectiles[i].x > width - translateration || gameChar.projectiles[i].x < 0 - translateration) { + gameChar.projectiles.splice(i, 1); + } + } +} +function manageMovement() { + if (gameChar.state.isPlummeting) { + gameChar.y += gameChar.speed / 2; + gameChar.size *= 0.98; + gameChar.speed *= 0.96; + if (gameChar.size < 0.2) restart(1); + } else if (!(gameChar.state.isJumping || gameChar.state.isFalling)) { + // Checking if the character is beyond the platform, then making them fall. + if (memorized_platform != undefined && !memorized_platform.isInXBorders(gameChar)) { + gameChar.state.isFalling = true; + memorized_platform = undefined; + } else { + // Falling into canyons + if (isOverCanyon(gameChar) && memorized_platform == undefined) { + gameChar.state.isPlummeting = true; + if (!plummetingSoundNotPlayedBefore) { + playSound(sfx.plummeting); + plummetingSoundNotPlayedBefore = true; + } + } + if (gameChar.state.isAscending && gameChar.y > floorPos_y) { + gameChar_y -= gameChar.speed; + } + if (gameChar.state.isDescending && gameChar_y < height) { + gameChar_y += gameChar.speed; + } + if (gameChar.state.isLeft) { + gameChar.x -= gameChar.speed; + } + if (gameChar.state.isRight) { + gameChar.x += gameChar.speed; + } + } + } else if (gameChar.state.isJumping) { + // Forget the platform as it is irrelevant when we gain height. + memorized_platform = undefined; + gameChar.y += gameChar.vert_speed; + gameChar.vert_speed += gameChar.gravity; + if (gameChar.vert_speed > 0) { + gameChar.state.isJumping = false; + gameChar.state.isFalling = true; + playSound(sfx.falling); + } + if (gameChar.state.isLeft) { + gameChar.x -= gameChar.speed; + } + if (gameChar.state.isRight) { + gameChar.x += gameChar.speed; + } + } else if (gameChar.state.isFalling) { + // Checking is a platform under the player, and therefore, if it is, save it and check the next frame did the character + // go under the platform - if so, end them on the platform. + for (i = 0; i < platforms.length; i++) { + if (platforms[i].isUnder(gameChar)) memorized_platform = platforms[i]; + } + if (memorized_platform != undefined && memorized_platform.isOver(gameChar)) { + gameChar.y = memorized_platform.y; + gameChar.state.isJumping = false; + gameChar.state.isFalling = false; + } else { + gameChar.y += gameChar.vert_speed; + gameChar.vert_speed += gameChar.gravity; + if (gameChar.y >= env.floorPos_y + 50) { + gameChar.y = env.floorPos_y + 50; + gameChar.state.isJumping = false; + gameChar.state.isFalling = false; + } + if (gameChar.state.isLeft) { + gameChar.x -= gameChar.speed; + } + if (gameChar.state.isRight) { + gameChar.x += gameChar.speed; + } + } + } + // Borders of the world check + if (gameChar.x <= 50) { + gameChar.x = 50; + } +} + +// Fun fact - the following function is made using ChatGPT! +function drawIsogonalBrickWall(x, y, size, hSkew, vSkew) { + push(); + translate(translateration, 0); + // Set the fill color of the bricks to a redish + fill(150, 100, 110); + + // Calculate the width and height of each brick + let brickWidth = size / 5; + let brickHeight = size / 10; + + // Draw the bricks in a 5x10 grid, with a small gap between each brick + for (let i = 0; i < 5; i++) { + for (let j = 0; j < 10; j++) { + let xPos = x + i * (brickWidth + 1) + j * hSkew; + let yPos = y + j * (brickHeight + 1) + i * vSkew; + rect(xPos, yPos, brickWidth, brickHeight); + } + } + pop(); +} + +function checkCollectable(whoCollidesWith) { + for (i = 0; i < collectables.length; i++) { + if ( + Math.abs(whoCollidesWith.x - collectables[i].x) < collectables[i].size * 2 && + Math.abs(whoCollidesWith.y - collectables[i].y) < collectables[i].size * 2 + ) { + whoCollidesWith.score += collectables[i].worth; + collectables.splice(i, 1); + playSound(sfx.coin); + } + } +} +function isOverCanyon(who) { + for (i = 0; i < canyons.length; i++) { + if (Math.abs(who.x - canyons[i].x) < 43 + 25 * random_values[i + 124]) { + return true; + } + } + return false; +} +function scrolling(centerOnWho) { + if (centerOnWho.x > width - width / 2.5 - translateration) { + translateration -= centerOnWho.speed; + } else if (centerOnWho.x < width / 2.5 - translateration) { + translateration += centerOnWho.speed; + } +} +function checkFlagpole(withWho) { + if (withWho.x > env.end_x) { + flagpole.isReached = true; + env.state = "WIN"; + withWho.isWinner = true; + playSound(sfx.levelcomplete); + } +} +function restart(decreaseLives) { + if (env.state != "LEVEL") window.location.reload(); // Reloads the web page. + gameChar.state.isPlummeting = false; + gameChar.lives -= decreaseLives; + if (gameChar.lives < 1) { + env.state = "GAMEOVER"; + playSound(sfx.gameover); + return; + } + gameChar.x = width / 2; + gameChar.y = env.floorPos_y + 50; + gameChar.resetValues(); + translateration = -gameChar.x; + plummetingSoundNotPlayedBefore = false; +} + +function getSpriteNumber() { + if (gameChar.state.isJumping && gameChar.state.isLeft) return 5; + else if (gameChar.state.isJumping && gameChar.state.isRight) return 6; + else if (gameChar.state.isJumping) return 2; + else if (gameChar.state.isFalling && gameChar.state.isLeft) return 5; + else if (gameChar.state.isFalling && gameChar.state.isRight) return 6; + else if (gameChar.state.isFalling) return 2; + else if (gameChar.state.isPlummeting) return 2; + else if (gameChar.state.isLeft) return 4; + else if (gameChar.state.isRight) return 3; + else if (gameChar.state.isDescending) return 1; + else return 1; +} +function debug() { + function _drawGridLines() { + push(); + console.log("works"); + stroke(255); + strokeWeight(1); + for (i = text_vert_unit; i < width; i += text_vert_unit) { + line(0, i, width, i); + } + for (j = text_hor_unit; j < height * 2; j += text_hor_unit) { + line(j, 0, j, height); + } + pop(); + } + this.drawGrid = false; + + if (gameChar.state.isJumping) text("JUMPING", text_vert_unit * 6, text_hor_unit * 2); + if (gameChar.state.isFalling) text("FALLING", text_vert_unit * 6, text_hor_unit * 2); + if (gameChar.state.isPlummeting) text("PLUMMETING", text_vert_unit * 11, text_hor_unit * 2); + + if (frameCount % 2 == 0) { + fps = Math.round(frameRate() * 10) / 10; + if (fps_recent_values.length < 200) fps_recent_values.push(fps); + else fps_recent_values.splice(0, 1); + fps_recent_values.push(fps); + } + fill("red"); + text(fps, text_vert_unit, text_hor_unit * 2); + stroke("black"); + beginShape(LINES); + for (i = 1; i < fps_recent_values.length; i++) { + vertex((text_vert_unit + i) * 1.5, (text_hor_unit * 6 - fps_recent_values[i]) * 2); + } + endShape(); + text(gameChar.x, text_vert_unit * 18, text_hor_unit * 2); + if (draw_grid) drawGridLines(); +} + +function createEnemies() { + enemies[0] = new Enemy(1100, 600, random(10, 50), random(20, 50), random(10, 30)); + + for (let i = 1; i < amounts.enemies; i++) { + let elevation; + if (random_values[i] <= 1 / 3) elevation = 350; + else if (random_values[i] > 1 / 3 && random_values <= 2 / 3) elevation = 300; + else elevation = 400; + + enemies[i] = new Enemy( + enemies[i - 1].x + 200 + 250 * random(), + elevation, + random(10, 50), + random(20, 50), + random(10, 30) + ); + } +} +function createTrees() {} +function setup() { + cnv = createCanvas(1024 + 256, 512 + 256); + + env.skyColor = color(142, 152, 135); + gameChar = new Entity(); + gameChar.x = width / 2; + gameChar.y = env.floorPos_y + 50; + + platforms[0] = new Platform(500, 600, 350); + for (i = 1; i < amounts.platforms; i++) { + let left_x = platforms[i - 1].right_x + 100 + 300 * random(); + let right_x = left_x + 50 + 100 * random(); + if (left_x > env.end_x && right_x > env.end_x) break; + platforms[i] = new Platform(left_x, right_x, 300 + 100 * random()); + } + createEnemies(); + + trees_x = [50]; + for (i = 1; i <= amounts.tree; i++) { + trees_x[i] = trees_x[i - 1] + 20 + 50 * random_values[i]; + } + clouds[0] = new Cloud(-1000, 60, 1); + for (i = 1; i <= amounts.cloud; i++) { + clouds[i] = new Cloud( + clouds[i - 1].x + 20 + 50 * random_values[i], + (env.floorPos_y / 1.9) * random_values[i + 60], + 0.5 + random_values[i + 100] + ); + } + + mountains_x = [50]; + for (i = 1; i <= amounts.mountain; i++) { + mountains_x[i] = mountains_x[i - 1] + 20 + 400 * random_values[i + 100]; + } + + canyons[0] = new Canyon(gameChar.x + 200, 100 + 50 * random_values[124]); + for (i = 1; i <= amounts.canyon; i++) { + let x = canyons[i - 1].x + 200 + 600 * random_values[i + 100]; + if (x > flagpole.x - 250) break; + canyons[i] = new Canyon(x, 100 + 50 * random_values[i + 124]); + } + + collectables[0] = new Collectable(gameChar.x + 350, env.floorPos_y + 50, 20, 10); + for (i = 1; i <= amounts.collectable; i++) { + let worth; + if (random_values[i] <= 1 / 3) worth = 15; + else if (random_values[i] > 1 / 3 && random_values <= 2 / 3) worth = 20; + else worth = 25; + let x = collectables[i - 1].x + 70 + 400 * random_values[i + 213]; + if (x > flagpole.x) break; + collectables[i] = new Collectable(x, env.floorPos_y + 50, worth, worth); + } + + // Pruning over-canyon trees. Literally. + for (i = 0; i < trees_x.length; i++) { + for (j = 0; j < canyons.length; j++) { + if ( + trees_x[i] > canyons[j].x - (40 + 50 * random_values[j + 124]) && + trees_x[i] < canyons[j].x + (40 + 50 * random_values[j + 124]) + ) { + trees_x[i] = undefined; + } + } + } + // Doing the same with collectables, for honesty. + for (i = 0; i < collectables.length; i++) { + for (j = 0; j < canyons.length; j++) { + if ( + collectables[i].x > canyons[j].x - (40 + 50 * random_values[j + 124]) && + collectables[i].x < canyons[j].x + (40 + 50 * random_values[j + 124]) + ) { + collectables[i].x = NaN; + } + } + } +} +function draw() { + text_hor_unit = height / 40; + text_vert_unit = width / 40; + + drawSky(); //fill the sky + fill(env.groundColor); + rect(0, env.floorPos_y, width, height); + drawMountains(); + // Also updates clouds movement using translate(). May be disabled. + drawClouds(true); + drawTrees(); + drawCanyons(); + drawFlagpole(); + drawIsogonalBrickWall(-89, env.floorPos_y - 89, 200, 0, -30); + drawCollectables(); + drawPlatforms(); + + switch (env.state) { + case "INTRO": { + push(); + textAlign(CENTER); + textSize(text_vert_unit * 3); + strokeWeight(10); + textFont("Courier"); + textStyle(BOLD); + fill(0); + text("The Dead Magic Run", width / 2, height / 2); + textSize(text_vert_unit); + text("Press any button to attempt a run", width / 2, height / 2 + text_vert_unit * 2); + pop(); + break; + } + case "INSTRUCTIONS": { + push(); + textAlign(LEFT); + textSize(text_vert_unit); + strokeWeight(3); + textFont("Courier"); + rectMode(CORNERS); + fill(0, 100); + rect(text_hor_unit, text_vert_unit * 3, text_hor_unit * 55, text_vert_unit * 11); + fill(255); + text("The goal is to survive and reach the right end.", text_hor_unit, text_vert_unit * 4); + text("Press WASD to move, Space to jump", text_hor_unit, text_vert_unit * 5); + text("E or mouse click to shoot.", text_hor_unit, text_vert_unit * 6); + text("Press P to enable and disable sounds,", text_hor_unit, text_vert_unit * 7); + text("and O letter to enable and disable music.", text_hor_unit, text_vert_unit * 8); + text("Press Space to continue and begin the run. Good luck.", text_hor_unit, text_vert_unit * 10); + pop(); + break; + } + case "LEVEL": { + // Update scrolling based on the character movement + scrolling(gameChar); + translate(translateration, 0); // Translating everything else to prevent next elements from scrolling too. + // Collectables collision + checkCollectable(gameChar); + checkFlagpole(gameChar); + manageMovement(); + // the sprite state machine + var sprite = getSpriteNumber(); + drawGameChar( + gameChar.x, + gameChar.y, + sprite, + gameChar.size, + true, + "red", + (hand = Math.floor(frameCount / 12) % 4) + ); + manageEnemies(); + updateProjectiles(); + playMusic(mus.level); + break; + } + case "WIN": { + manageEnemies(); + push(); + image(win_img, width / 2 - win_img.width / 2 + 10, height / 2 - win_img.height / 2); + fill("yellow"); + textSize(text_vert_unit * 1.5); + textAlign(CENTER); + strokeWeight(2); + textFont("Courier"); + text("Level complete. Press R to replay.", width / 2, height / 2 - win_img.height / 2); + translate(translateration, frameCount); + pop(); + scrolling(flagpole); // fix the viewpoint on the flagpole + translate(translateration, 0); // Translating everything else to prevent next elements from scrolling too. + // Forcing to run right + gameChar.state.isRight = true; + gameChar.state.isLeft = false; + // the sprite state machine + var sprite = getSpriteNumber(); + manageMovement(); + drawGameChar(gameChar.x, gameChar.y, sprite, gameChar.size, true, "red", Math.floor(frameCount / 12) % 4); + playMusic(mus.win); + break; + } + case "GAMEOVER": { + manageEnemies(); + push(); + image(gameover_img, width / 2 - 256 / 2, height / 2 - 256 / 2); + fill("black"); + textSize(text_vert_unit * 1.5); + textAlign(CENTER); + strokeWeight(2); + textFont("Courier"); + text("Gamover. Press R to replay.", width / 2, height / 2 - 256 / 2); + pop(); + translate(translateration, 0); + playMusic(mus.gameover); + break; + } + default: { + push(); + textSize(50); + fill("red"); + text("Game state error!", width / 2, height / 2); + pop(); + break; + } + } + drawInterface(); +} + +function playMusic(requestedMelody) { + // spaghetti code. + if (requestedMelody != mus.level) mus.level.stop(); + if (requestedMelody != mus.win) mus.win.stop(); + if (requestedMelody != mus.gameover) mus.gameover.stop(); + if (!requestedMelody.isPlaying() && env.isMusicEnabled) { + requestedMelody.play(0, 1, 0.3); + } else if (!env.isMusicEnabled) requestedMelody.stop(); +} + +function mouseClicked() { + shootProjectile(); +} +function keyPressed() { + if (env.state == "INTRO") { + env.state = "INSTRUCTIONS"; + } else if (key == " " && env.state == "INSTRUCTIONS") { + env.state = "LEVEL"; + } + if (keyCode == 32 && !(gameChar.state.isJumping || gameChar.state.isFalling)) { + gameChar.state.isJumping = true; + gameChar.prejump_y = gameChar.y; + gameChar.vert_speed = -30; + playSound(sfx.jumping); + } + if (key == "E" && env.state == "LEVEL") { + shootProjectile(); + } + if (key == "A") { + gameChar.state.isLeft = true; + } + if (key == "D") { + gameChar.state.isRight = true; + } + if (key == "R" && (env.state == "WIN" || env.state == "GAMEOVER")) { + restart(); + } + if (key == "P" && !env.isSoundEnabled) { + env.isSoundEnabled = true; + } else if (key == "P" && env.isSoundEnabled) { + env.isSoundEnabled = false; + } + if (key == "O" && !env.isMusicEnabled) { + env.isMusicEnabled = true; + } else if (key == "O" && env.isMusicEnabled) { + env.isMusicEnabled = false; + } + if (key == "G" && isDebug) draw_grid = true; + + console.log("keyPressed: " + key); + console.log("keyPressed: " + keyCode); + return false; +} +function keyReleased() { + if (key == "M") { + if (isDebug) isDebug = false; + else isDebug = true; + } + if (key == "A") { + gameChar.state.isLeft = false; + } + if (key == "D") { + gameChar.state.isRight = false; + } + if (key == "G" && isDebug) draw_grid = false; + console.log("keyReleased: " + key); + console.log("keyReleased: " + keyCode); +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..5549848 --- /dev/null +++ b/index.html @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/p5.min.js b/p5.min.js new file mode 100644 index 0000000..7cc3cf4 --- /dev/null +++ b/p5.min.js @@ -0,0 +1,9 @@ +/*! p5.js v0.5.11 June 01, 2017 */ !function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.p5=a()}}(function(){var a;return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g0,"No English "+b+" specified.")}var c=[],d=this;b("fontFamily"),b("weightName"),b("manufacturer"),b("copyright"),b("version"),a(this.unitsPerEm>0,"No unitsPerEm specified.")},d.prototype.toTables=function(){return f.fontToTable(this)},d.prototype.toBuffer=function(){for(var a=this.toTables(),b=a.encode(),c=new ArrayBuffer(b.length),d=new Uint8Array(c),e=0;e=0&&c>0&&(a+=" "),a+=b(d)}return a}a=void 0!==a?a:2;for(var d="",e=0;e>4,g=15&e;if(f===c)break;if(b+=d[f],g===c)break;b+=d[g]}return parseFloat(b)}function g(a,b){var c,d,e,g;if(28===b)return c=a.parseByte(),d=a.parseByte(),c<<8|d;if(29===b)return c=a.parseByte(),d=a.parseByte(),e=a.parseByte(),g=a.parseByte(),c<<24|d<<16|e<<8|g;if(30===b)return f(a);if(b>=32&&b<=246)return b-139;if(b>=247&&b<=250)return c=a.parseByte(),256*(b-247)+c+108;if(b>=251&&b<=254)return c=a.parseByte(),256*-(b-251)-c-108;throw new Error("Invalid b0 "+b)}function h(a){for(var b={},c=0;c>1,l.length=0,n=!0}function f(c){for(var s,t,u,v,w,x,y,z,A,B,C,D,E=0;E1&&!n&&(o=l.shift()+a.nominalWidthX,n=!0),r+=l.pop(),d(q,r);break;case 5:for(;l.length>0;)q+=l.shift(),r+=l.shift(),k.lineTo(q,r);break;case 6:for(;l.length>0&&(q+=l.shift(),k.lineTo(q,r),0!==l.length);)r+=l.shift(),k.lineTo(q,r);break;case 7:for(;l.length>0&&(r+=l.shift(),k.lineTo(q,r),0!==l.length);)q+=l.shift(),k.lineTo(q,r);break;case 8:for(;l.length>0;)g=q+l.shift(),h=r+l.shift(),i=g+l.shift(),j=h+l.shift(),q=i+l.shift(),r=j+l.shift(),k.curveTo(g,h,i,j,q,r);break;case 10:w=l.pop()+a.subrsBias,x=a.subrs[w],x&&f(x);break;case 11:return;case 12:switch(F=c[E],E+=1,F){case 35:g=q+l.shift(),h=r+l.shift(),i=g+l.shift(),j=h+l.shift(),y=i+l.shift(),z=j+l.shift(),A=y+l.shift(),B=z+l.shift(),C=A+l.shift(),D=B+l.shift(),q=C+l.shift(),r=D+l.shift(),l.shift(),k.curveTo(g,h,i,j,y,z),k.curveTo(A,B,C,D,q,r);break;case 34:g=q+l.shift(),h=r,i=g+l.shift(),j=h+l.shift(),y=i+l.shift(),z=j,A=y+l.shift(),B=j,C=A+l.shift(),D=r,q=C+l.shift(),k.curveTo(g,h,i,j,y,z),k.curveTo(A,B,C,D,q,r);break;case 36:g=q+l.shift(),h=r+l.shift(),i=g+l.shift(),j=h+l.shift(),y=i+l.shift(),z=j,A=y+l.shift(),B=j,C=A+l.shift(),D=B+l.shift(),q=C+l.shift(),k.curveTo(g,h,i,j,y,z),k.curveTo(A,B,C,D,q,r);break;case 37:g=q+l.shift(),h=r+l.shift(),i=g+l.shift(),j=h+l.shift(),y=i+l.shift(),z=j+l.shift(),A=y+l.shift(),B=z+l.shift(),C=A+l.shift(),D=B+l.shift(),Math.abs(C-q)>Math.abs(D-r)?q=C+l.shift():r=D+l.shift(),k.curveTo(g,h,i,j,y,z),k.curveTo(A,B,C,D,q,r);break;default:console.log("Glyph "+b.index+": unknown operator 1200"+F),l.length=0}break;case 14:l.length>0&&!n&&(o=l.shift()+a.nominalWidthX,n=!0),p&&(k.closePath(),p=!1);break;case 18:e();break;case 19:case 20:e(),E+=m+7>>3;break;case 21:l.length>2&&!n&&(o=l.shift()+a.nominalWidthX,n=!0),r+=l.pop(),q+=l.pop(),d(q,r);break;case 22:l.length>1&&!n&&(o=l.shift()+a.nominalWidthX,n=!0),q+=l.pop(),d(q,r);break;case 23:e();break;case 24:for(;l.length>2;)g=q+l.shift(),h=r+l.shift(),i=g+l.shift(),j=h+l.shift(),q=i+l.shift(),r=j+l.shift(),k.curveTo(g,h,i,j,q,r);q+=l.shift(),r+=l.shift(),k.lineTo(q,r);break;case 25:for(;l.length>6;)q+=l.shift(),r+=l.shift(),k.lineTo(q,r);g=q+l.shift(),h=r+l.shift(),i=g+l.shift(),j=h+l.shift(),q=i+l.shift(),r=j+l.shift(),k.curveTo(g,h,i,j,q,r);break;case 26:for(l.length%2&&(q+=l.shift());l.length>0;)g=q,h=r+l.shift(),i=g+l.shift(),j=h+l.shift(),q=i,r=j+l.shift(),k.curveTo(g,h,i,j,q,r);break;case 27:for(l.length%2&&(r+=l.shift());l.length>0;)g=q+l.shift(),h=r,i=g+l.shift(),j=h+l.shift(),q=i+l.shift(),r=j,k.curveTo(g,h,i,j,q,r);break;case 28:s=c[E],t=c[E+1],l.push((s<<24|t<<16)>>16),E+=2;break;case 29:w=l.pop()+a.gsubrsBias,x=a.gsubrs[w],x&&f(x);break;case 30:for(;l.length>0&&(g=q,h=r+l.shift(),i=g+l.shift(),j=h+l.shift(),q=i+l.shift(),r=j+(1===l.length?l.shift():0),k.curveTo(g,h,i,j,q,r),0!==l.length);)g=q+l.shift(),h=r,i=g+l.shift(),j=h+l.shift(),r=j+l.shift(),q=i+(1===l.length?l.shift():0),k.curveTo(g,h,i,j,q,r);break;case 31:for(;l.length>0&&(g=q+l.shift(),h=r,i=g+l.shift(),j=h+l.shift(),r=j+l.shift(),q=i+(1===l.length?l.shift():0),k.curveTo(g,h,i,j,q,r),0!==l.length);)g=q,h=r+l.shift(),i=g+l.shift(),j=h+l.shift(),q=i+l.shift(),r=j+(1===l.length?l.shift():0),k.curveTo(g,h,i,j,q,r);break;default:F<32?console.log("Glyph "+b.index+": unknown operator "+F):F<247?l.push(F-139):F<251?(s=c[E],E+=1,l.push(256*(F-247)+s+108)):F<255?(s=c[E],E+=1,l.push(256*-(F-251)-s-108)):(s=c[E],t=c[E+1],u=c[E+2],v=c[E+3],E+=4,l.push((s<<24|t<<16|u<<8|v)/65536))}}}var g,h,i,j,k=new K.Path,l=[],m=0,n=!1,o=a.defaultWidthX,p=!1,q=0,r=0;return f(c),b.advanceWidth=o,k}function r(a){return a.length<1240?107:a.length<33900?1131:32768}function s(a,b,c){c.tables.cff={};var d=l(a,b),f=e(a,d.endOffset,J.bytesToString),g=e(a,f.endOffset),h=e(a,g.endOffset,J.bytesToString),i=e(a,h.endOffset);c.gsubrs=i.objects,c.gsubrsBias=r(c.gsubrs);var j=new DataView(new Uint8Array(g.objects[0]).buffer),k=m(j,h.objects);c.tables.cff.topDict=k;var s=b+k.private[1],t=n(a,s,k.private[0],h.objects);if(c.defaultWidthX=t.defaultWidthX,c.nominalWidthX=t.nominalWidthX,0!==t.subrs){var u=s+t.subrs,v=e(a,u);c.subrs=v.objects,c.subrsBias=r(c.subrs)}else c.subrs=[],c.subrsBias=0;var w=e(a,b+k.charStrings);c.nGlyphs=w.objects.length;var x=o(a,b+k.charset,c.nGlyphs,h.objects);0===k.encoding?c.cffEncoding=new H.CffEncoding(H.cffStandardEncoding,x):1===k.encoding?c.cffEncoding=new H.CffEncoding(H.cffExpertEncoding,x):c.cffEncoding=p(a,b+k.encoding,x),c.encoding=c.encoding||c.cffEncoding,c.glyphs=new I.GlyphSet(c);for(var y=0;y=0&&(c=d),d=b.indexOf(a),d>=0?c=d+H.cffStandardStrings.length:(c=H.cffStandardStrings.length+b.length,b.push(a)),c}function u(){return new L.Table("Header",[{name:"major",type:"Card8",value:1},{name:"minor",type:"Card8",value:0},{name:"hdrSize",type:"Card8",value:4},{name:"major",type:"Card8",value:1}])}function v(a){var b=new L.Table("Name INDEX",[{name:"names",type:"INDEX",value:[]}]);b.names=[];for(var c=0;c>1,j.skip("uShort",3),d.glyphIndexMap={};var l=new i.Parser(a,b+e+14),m=new i.Parser(a,b+e+16+2*k),n=new i.Parser(a,b+e+16+4*k),o=new i.Parser(a,b+e+16+6*k),p=b+e+16+8*k;for(c=0;c0?(f=a.parseByte(),0==(b&e)&&(f=-f),f=c+f):f=(b&e)>0?c:c+a.parseShort(),f}function e(a,b,c){var e=new m.Parser(b,c);a.numberOfContours=e.parseShort(),a.xMin=e.parseShort(),a.yMin=e.parseShort(),a.xMax=e.parseShort(),a.yMax=e.parseShort();var f,g;if(a.numberOfContours>0){var h,i=a.endPointIndices=[];for(h=0;h0)for(var l=e.parseByte(),n=0;n0){var o,p=[];if(j>0){for(h=0;h=0,p.push(o);var q=0;for(h=0;h0?(t.dx=e.parseShort(),t.dy=e.parseShort()):(t.dx=e.parseChar(),t.dy=e.parseChar()),(8&f)>0?t.xScale=t.yScale=e.parseF2Dot14():(64&f)>0?(t.xScale=e.parseF2Dot14(),t.yScale=e.parseF2Dot14()):(128&f)>0&&(t.xScale=e.parseF2Dot14(),t.scale01=e.parseF2Dot14(),t.scale10=e.parseF2Dot14(),t.yScale=e.parseF2Dot14()),a.components.push(t),s=!!(32&f)}}}function f(a,b){for(var c=[],d=0;d>1;a=c.begin&&a=1&&(c.ulCodePageRange1=d.parseULong(),c.ulCodePageRange2=d.parseULong()),c.version>=2&&(c.sxHeight=d.parseShort(),c.sCapHeight=d.parseShort(),c.usDefaultChar=d.parseUShort(),c.usBreakChar=d.parseUShort(),c.usMaxContent=d.parseUShort()),c}function f(a){return new h.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],a)}var g=a("../parse"),h=a("../table"),i=[{begin:0,end:127},{begin:128,end:255},{begin:256,end:383},{begin:384,end:591},{begin:592,end:687},{begin:688,end:767},{begin:768,end:879},{begin:880,end:1023},{begin:11392,end:11519},{begin:1024,end:1279},{begin:1328,end:1423},{begin:1424,end:1535},{begin:42240,end:42559},{begin:1536,end:1791},{begin:1984,end:2047},{begin:2304,end:2431},{begin:2432,end:2559},{begin:2560,end:2687},{begin:2688,end:2815},{begin:2816,end:2943},{begin:2944,end:3071},{begin:3072,end:3199},{begin:3200,end:3327},{begin:3328,end:3455},{begin:3584,end:3711},{begin:3712,end:3839},{begin:4256,end:4351},{begin:6912,end:7039},{begin:4352,end:4607},{begin:7680,end:7935},{begin:7936,end:8191},{begin:8192,end:8303},{begin:8304,end:8351},{begin:8352,end:8399},{begin:8400,end:8447},{begin:8448,end:8527},{begin:8528,end:8591},{begin:8592,end:8703},{begin:8704,end:8959},{begin:8960,end:9215},{begin:9216,end:9279},{begin:9280,end:9311},{begin:9312,end:9471},{begin:9472,end:9599},{begin:9600,end:9631},{begin:9632,end:9727},{begin:9728,end:9983},{begin:9984,end:10175},{begin:12288,end:12351},{begin:12352,end:12447},{begin:12448,end:12543},{begin:12544,end:12591},{begin:12592,end:12687},{begin:43072,end:43135},{begin:12800,end:13055},{begin:13056,end:13311},{begin:44032,end:55215},{begin:55296,end:57343},{begin:67840,end:67871},{begin:19968,end:40959},{begin:57344,end:63743},{begin:12736,end:12783},{begin:64256,end:64335},{begin:64336,end:65023},{begin:65056,end:65071},{begin:65040,end:65055},{begin:65104,end:65135},{begin:65136,end:65279},{begin:65280,end:65519},{begin:65520,end:65535},{begin:3840,end:4095},{begin:1792,end:1871},{begin:1920,end:1983},{begin:3456,end:3583},{begin:4096,end:4255},{begin:4608,end:4991},{begin:5024,end:5119},{begin:5120,end:5759},{begin:5760,end:5791},{begin:5792,end:5887},{begin:6016,end:6143},{begin:6144,end:6319},{begin:10240,end:10495},{begin:40960,end:42127},{begin:5888,end:5919},{begin:66304,end:66351},{begin:66352,end:66383},{begin:66560,end:66639},{begin:118784,end:119039},{begin:119808,end:120831},{begin:1044480,end:1048573},{begin:65024,end:65039},{begin:917504,end:917631},{begin:6400,end:6479},{begin:6480,end:6527},{begin:6528,end:6623},{begin:6656,end:6687},{begin:11264,end:11359},{begin:11568,end:11647},{begin:19904,end:19967},{begin:43008,end:43055},{begin:65536,end:65663},{begin:65856,end:65935},{begin:66432,end:66463},{begin:66464,end:66527},{begin:66640,end:66687},{begin:66688,end:66735},{begin:67584,end:67647},{begin:68096,end:68191},{begin:119552,end:119647},{begin:73728,end:74751},{begin:119648,end:119679},{begin:7040,end:7103},{begin:7168,end:7247},{begin:7248,end:7295},{begin:43136,end:43231},{begin:43264,end:43311},{begin:43312,end:43359},{begin:43520,end:43615},{begin:65936,end:65999},{begin:66e3,end:66047},{begin:66208,end:66271},{begin:127024,end:127135}];c.unicodeRanges=i,c.getUnicodeRange=d,c.parse=e,c.make=f},{"../parse":11,"../table":13}],28:[function(a,b,c){"use strict";function d(a,b){var c,d={},e=new g.Parser(a,b);switch(d.version=e.parseVersion(),d.italicAngle=e.parseFixed(),d.underlinePosition=e.parseShort(),d.underlineThickness=e.parseShort(),d.isFixedPitch=e.parseULong(),d.minMemType42=e.parseULong(),d.maxMemType42=e.parseULong(),d.minMemType1=e.parseULong(),d.maxMemType1=e.parseULong(),d.version){case 1:d.names=f.standardNames.slice();break;case 2:for(d.numberOfGlyphs=e.parseUShort(),d.glyphNameIndex=new Array(d.numberOfGlyphs),c=0;c=f.standardNames.length){var h=e.parseChar();d.names.push(e.parseString(h))}break;case 2.5:for(d.numberOfGlyphs=e.parseUShort(),d.offset=new Array(d.numberOfGlyphs),c=0;cb.value.tag?1:-1}),b.fields=b.fields.concat(g),b.fields=b.fields.concat(h),b}function h(a,b,c){for(var d=0;d0){return a.glyphs.get(e).getMetrics()}}return c}function i(a){for(var b=0,c=0;cE||null===b)&&(b=E),x 123 are reserved for internal usage");B|=1<0?r.make(U):void 0,X=v.make(),Y=n.make(a.glyphs,{version:a.getEnglishName("version"),fullName:Q,familyName:O,weightName:P,postScriptName:R,unitsPerEm:a.unitsPerEm}),Z=[I,J,K,L,V,N,X,Y,M];W&&Z.push(W);var $=g(Z),_=$.encode(),aa=e(_),ba=$.fields,ca=!1;for(C=0;C=0&&a<=255,"Byte value should be between 0 and 255."),[a]},j.BYTE=d(1),i.CHAR=function(a){return[a.charCodeAt(0)]},j.CHAR=d(1),i.CHARARRAY=function(a){for(var b=[],c=0;c>8&255,255&a]},j.USHORT=d(2),i.SHORT=function(a){return a>=f&&(a=-(2*f-a)),[a>>8&255,255&a]},j.SHORT=d(2),i.UINT24=function(a){return[a>>16&255,a>>8&255,255&a]},j.UINT24=d(3),i.ULONG=function(a){return[a>>24&255,a>>16&255,a>>8&255,255&a]},j.ULONG=d(4),i.LONG=function(a){return a>=g&&(a=-(2*g-a)),[a>>24&255,a>>16&255,a>>8&255,255&a]},j.LONG=d(4),i.FIXED=i.ULONG,j.FIXED=j.ULONG,i.FWORD=i.SHORT,j.FWORD=j.SHORT,i.UFWORD=i.USHORT,j.UFWORD=j.USHORT,i.LONGDATETIME=function(){return[0,0,0,0,0,0,0,0]},j.LONGDATETIME=d(8),i.TAG=function(a){return e.argument(4===a.length,"Tag should be exactly 4 ASCII characters."),[a.charCodeAt(0),a.charCodeAt(1),a.charCodeAt(2),a.charCodeAt(3)]},j.TAG=d(4),i.Card8=i.BYTE,j.Card8=j.BYTE,i.Card16=i.USHORT,j.Card16=j.USHORT,i.OffSize=i.BYTE,j.OffSize=j.BYTE,i.SID=i.USHORT,j.SID=j.USHORT,i.NUMBER=function(a){return a>=-107&&a<=107?[a+139]:a>=108&&a<=1131?(a-=108,[247+(a>>8),255&a]):a>=-1131&&a<=-108?(a=-a-108,[251+(a>>8),255&a]):a>=-32768&&a<=32767?i.NUMBER16(a):i.NUMBER32(a)},j.NUMBER=function(a){return i.NUMBER(a).length},i.NUMBER16=function(a){return[28,a>>8&255,255&a]},j.NUMBER16=d(3),i.NUMBER32=function(a){return[29,a>>24&255,a>>16&255,a>>8&255,255&a]},j.NUMBER32=d(5),i.REAL=function(a){var b=a.toString(),c=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(b);if(c){var d=parseFloat("1e"+((c[2]?+c[2]:0)+c[1].length));b=(Math.round(a*d)/d).toString()}var e,f,g="";for(e=0,f=b.length;e>8&255),b.push(255&d)}return b},j.UTF16=function(a){return 2*a.length};var k={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};h.MACSTRING=function(a,b,c,d){var e=k[d];if(void 0!==e){for(var f="",g=0;g=128&&void 0===(f=c[f]))return;d.push(f)}return d}},j.MACSTRING=function(a,b){var c=i.MACSTRING(a,b);return void 0!==c?c.length:0},i.INDEX=function(a){var b,c=1,d=[c],e=[],f=0;for(b=0;b1)for(var c=1;c-1?b:a}function n(a,b){b=b||{};var c=b.body;if(a instanceof n){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,b.headers||(this.headers=new e(a.headers)),this.method=a.method,this.mode=a.mode,c||null==a._bodyInit||(c=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=b.credentials||this.credentials||"omit",!b.headers&&this.headers||(this.headers=new e(b.headers)),this.method=m(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&c)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(c)}function o(a){var b=new FormData;return a.trim().split("&").forEach(function(a){if(a){var c=a.split("="),d=c.shift().replace(/\+/g," "),e=c.join("=").replace(/\+/g," ");b.append(decodeURIComponent(d),decodeURIComponent(e))}}),b}function p(a){var b=new e;return a.split(/\r?\n/).forEach(function(a){var c=a.split(":"),d=c.shift().trim();if(d){var e=c.join(":").trim();b.append(d,e)}}),b}function q(a,b){b||(b={}),this.type="default",this.status="status"in b?b.status:200,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in b?b.statusText:"OK",this.headers=new e(b.headers),this.url=b.url||"",this._initBody(a)}if(!a.fetch){var r={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch(a){return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};if(r.arrayBuffer)var s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],t=function(a){return a&&DataView.prototype.isPrototypeOf(a)},u=ArrayBuffer.isView||function(a){return a&&s.indexOf(Object.prototype.toString.call(a))>-1};e.prototype.append=function(a,d){a=b(a),d=c(d);var e=this.map[a];this.map[a]=e?e+","+d:d},e.prototype.delete=function(a){delete this.map[b(a)]},e.prototype.get=function(a){return a=b(a),this.has(a)?this.map[a]:null},e.prototype.has=function(a){return this.map.hasOwnProperty(b(a))},e.prototype.set=function(a,d){this.map[b(a)]=c(d)},e.prototype.forEach=function(a,b){for(var c in this.map)this.map.hasOwnProperty(c)&&a.call(b,this.map[c],c,this)},e.prototype.keys=function(){var a=[];return this.forEach(function(b,c){a.push(c)}),d(a)},e.prototype.values=function(){var a=[];return this.forEach(function(b){a.push(b)}),d(a)},e.prototype.entries=function(){var a=[];return this.forEach(function(b,c){a.push([c,b])}),d(a)},r.iterable&&(e.prototype[Symbol.iterator]=e.prototype.entries);var v=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];n.prototype.clone=function(){return new n(this,{body:this._bodyInit})},l.call(n.prototype),l.call(q.prototype),q.prototype.clone=function(){return new q(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new e(this.headers),url:this.url})},q.error=function(){var a=new q(null,{status:0,statusText:""});return a.type="error",a};var w=[301,302,303,307,308];q.redirect=function(a,b){if(w.indexOf(b)===-1)throw new RangeError("Invalid status code");return new q(null,{status:b,headers:{location:a}})},a.Headers=e,a.Request=n,a.Response=q,a.fetch=function(a,b){return new Promise(function(c,d){var e=new n(a,b),f=new XMLHttpRequest;f.onload=function(){var a={status:f.status,statusText:f.statusText,headers:p(f.getAllResponseHeaders()||"")};a.url="responseURL"in f?f.responseURL:a.headers.get("X-Request-URL"),c(new q("response"in f?f.response:f.responseText,a))},f.onerror=function(){d(new TypeError("Network request failed"))},f.ontimeout=function(){d(new TypeError("Network request failed"))},f.open(e.method,e.url,!0),"include"===e.credentials&&(f.withCredentials=!0),"responseType"in f&&r.blob&&(f.responseType="blob"),e.headers.forEach(function(a,b){f.setRequestHeader(b,a)}),f.send(void 0===e._bodyInit?null:e._bodyInit)})},a.fetch.polyfill=!0}}("undefined"!=typeof self?self:this)},{}],33:[function(a,b,c){"use strict";var d=a("./core/core");a("./color/p5.Color"),a("./core/p5.Element"),a("./typography/p5.Font"),a("./core/p5.Graphics"),a("./core/p5.Renderer2D"),a("./image/p5.Image"),a("./math/p5.Vector"),a("./io/p5.TableRow"),a("./io/p5.Table"),a("./io/p5.XML"),a("./color/creating_reading"),a("./color/setting"),a("./core/constants"),a("./utilities/conversion"),a("./utilities/array_functions"),a("./utilities/string_functions"),a("./core/environment"),a("./image/image"),a("./image/loading_displaying"),a("./image/pixels"),a("./io/files"),a("./events/keyboard"),a("./events/acceleration"),a("./events/mouse"),a("./utilities/time_date"),a("./events/touch"),a("./math/math"),a("./math/calculation"),a("./math/random"),a("./math/noise"),a("./math/trigonometry"),a("./core/rendering"),a("./core/2d_primitives"),a("./core/attributes"),a("./core/curves"),a("./core/vertex"),a("./core/structure"),a("./core/transform"),a("./typography/attributes"),a("./typography/loading_displaying"),a("./webgl/p5.RendererGL"),a("./webgl/p5.Geometry"),a("./webgl/p5.RendererGL.Retained"),a("./webgl/p5.RendererGL.Immediate"),a("./webgl/primitives"),a("./webgl/loading"),a("./webgl/p5.Matrix"),a("./webgl/material"),a("./webgl/light"),a("./webgl/shader"),a("./webgl/camera"),a("./webgl/interaction");var e=function(){window.PHANTOMJS||window.mocha||(window.setup&&"function"==typeof window.setup||window.draw&&"function"==typeof window.draw)&&!d.instance&&new d};"complete"===document.readyState?e():window.addEventListener("load",e,!1),b.exports=d},{"./color/creating_reading":35,"./color/p5.Color":36,"./color/setting":37,"./core/2d_primitives":38,"./core/attributes":39,"./core/constants":41,"./core/core":42,"./core/curves":43,"./core/environment":44,"./core/p5.Element":46,"./core/p5.Graphics":47,"./core/p5.Renderer2D":49,"./core/rendering":50,"./core/structure":52,"./core/transform":53,"./core/vertex":54,"./events/acceleration":55,"./events/keyboard":56,"./events/mouse":57,"./events/touch":58,"./image/image":60,"./image/loading_displaying":61,"./image/p5.Image":62,"./image/pixels":63,"./io/files":64,"./io/p5.Table":65,"./io/p5.TableRow":66,"./io/p5.XML":67,"./math/calculation":68,"./math/math":69,"./math/noise":70,"./math/p5.Vector":71,"./math/random":73,"./math/trigonometry":74,"./typography/attributes":75,"./typography/loading_displaying":76,"./typography/p5.Font":77,"./utilities/array_functions":78,"./utilities/conversion":79,"./utilities/string_functions":80,"./utilities/time_date":81,"./webgl/camera":82,"./webgl/interaction":83,"./webgl/light":84,"./webgl/loading":85,"./webgl/material":86,"./webgl/p5.Geometry":87,"./webgl/p5.Matrix":88,"./webgl/p5.RendererGL":91,"./webgl/p5.RendererGL.Immediate":89,"./webgl/p5.RendererGL.Retained":90,"./webgl/primitives":92,"./webgl/shader":93}],34:[function(a,b,c){"use strict";var d=a("../core/core");d.ColorConversion={},d.ColorConversion._hsbaToHSLA=function(a){var b=a[0],c=a[1],d=a[2],e=(2-c)*d/2;return 0!==e&&(1===e?c=0:e<.5?c/=2-c:c=c*d/(2-2*e)),[b,c,e,a[3]]},d.ColorConversion._hsbaToRGBA=function(a){var b=6*a[0],c=a[1],d=a[2],e=[];if(0===c)e=[d,d,d,a[3]];else{var f,g,h,i=Math.floor(b),j=d*(1-c),k=d*(1-c*(b-i)),l=d*(1-c*(1+i-b));1===i?(f=k,g=d,h=j):2===i?(f=j,g=d,h=l):3===i?(f=j,g=k,h=d):4===i?(f=l,g=j,h=d):5===i?(f=d,g=j,h=k):(f=d,g=l,h=j),e=[f,g,h,a[3]]}return e},d.ColorConversion._hslaToHSBA=function(a){var b,c=a[0],d=a[1],e=a[2];return b=e<.5?(1+d)*e:e+d-e*d,d=2*(b-e)/b,[c,d,b,a[3]]},d.ColorConversion._hslaToRGBA=function(a){var b=6*a[0],c=a[1],d=a[2],e=[];if(0===c)e=[d,d,d,a[3]];else{var f;f=d<.5?(1+c)*d:d+c-d*c;var g=2*d-f,h=function(a,b,c){return a<0?a+=6:a>=6&&(a-=6),a<1?b+(c-b)*a:a<3?c:a<4?b+(c-b)*(4-a):b};e=[h(b+2,g,f),h(b,g,f),h(b-2,g,f),a[3]]}return e},d.ColorConversion._rgbaToHSBA=function(a){var b,c,d=a[0],e=a[1],f=a[2],g=Math.max(d,e,f),h=g-Math.min(d,e,f);return 0===h?(b=0,c=0):(c=h/g,d===g?b=(e-f)/h:e===g?b=2+(f-d)/h:f===g&&(b=4+(d-e)/h),b<0?b+=6:b>=6&&(b-=6)),[b/6,c,g,a[3]]},d.ColorConversion._rgbaToHSLA=function(a){var b,c,d=a[0],e=a[1],f=a[2],g=Math.max(d,e,f),h=Math.min(d,e,f),i=g+h,j=g-h;return 0===j?(b=0,c=0):(c=i<1?j/i:j/(2-i),d===g?b=(e-f)/j:e===g?b=2+(f-d)/j:f===g&&(b=4+(d-e)/j),b<0?b+=6:b>=6&&(b-=6)),[b/6,c,i/2,a[3]]},b.exports=d.ColorConversion},{"../core/core":42}],35:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("../core/constants");a("./p5.Color"),d.prototype.alpha=function(a){if(a instanceof d.Color||a instanceof Array)return this.color(a)._getAlpha();throw new Error("Needs p5.Color or pixel array as argument.")},d.prototype.blue=function(a){if(a instanceof d.Color||a instanceof Array)return this.color(a)._getBlue();throw new Error("Needs p5.Color or pixel array as argument.")},d.prototype.brightness=function(a){if(a instanceof d.Color||a instanceof Array)return this.color(a)._getBrightness();throw new Error("Needs p5.Color or pixel array as argument.")},d.prototype.color=function(){return arguments[0]instanceof d.Color?arguments[0]:arguments[0]instanceof Array?this instanceof d.Renderer?new d.Color(this,arguments[0]):new d.Color(this._renderer,arguments[0]):this instanceof d.Renderer?new d.Color(this,arguments):new d.Color(this._renderer,arguments)},d.prototype.green=function(a){if(a instanceof d.Color||a instanceof Array)return this.color(a)._getGreen();throw new Error("Needs p5.Color or pixel array as argument.")},d.prototype.hue=function(a){if(a instanceof d.Color||a instanceof Array)return this.color(a)._getHue();throw new Error("Needs p5.Color or pixel array as argument.")},d.prototype.lerpColor=function(a,b,c){var d,f,g,h,i,j,k=this._renderer._colorMode,l=this._renderer._colorMaxes;if(k===e.RGB)i=a.levels.map(function(a){return a/255}),j=b.levels.map(function(a){return a/255});else if(k===e.HSB)a._getBrightness(),b._getBrightness(),i=a.hsba,j=b.hsba;else{if(k!==e.HSL)throw new Error(k+"cannot be used for interpolation.");a._getLightness(),b._getLightness(),i=a.hsla,j=b.hsla}return c=Math.max(Math.min(c,1),0),d=this.lerp(i[0],j[0],c),f=this.lerp(i[1],j[1],c),g=this.lerp(i[2],j[2],c),h=this.lerp(i[3],j[3],c),d*=l[k][0],f*=l[k][1],g*=l[k][2],h*=l[k][3],this.color(d,f,g,h)},d.prototype.lightness=function(a){if(a instanceof d.Color||a instanceof Array)return this.color(a)._getLightness();throw new Error("Needs p5.Color or pixel array as argument.")},d.prototype.red=function(a){if(a instanceof d.Color||a instanceof Array)return this.color(a)._getRed();throw new Error("Needs p5.Color or pixel array as argument.")},d.prototype.saturation=function(a){if(a instanceof d.Color||a instanceof Array)return this.color(a)._getSaturation();throw new Error("Needs p5.Color or pixel array as argument.")},b.exports=d},{"../core/constants":41,"../core/core":42,"./p5.Color":36}],36:[function(a,b,c){var d=a("../core/core"),e=a("../core/constants"),f=a("./color_conversion");d.Color=function(a,b){if(this.mode=a._colorMode,this.maxes=a._colorMaxes,this.mode!==e.RGB&&this.mode!==e.HSL&&this.mode!==e.HSB)throw new Error(this.mode+" is an invalid colorMode.");return this._array=d.Color._parseInputs.apply(a,b),this.levels=this._array.map(function(a){return Math.round(255*a)}),this},d.Color.prototype.toString=function(){var a=this.levels,b=this._array[3];return"rgba("+a[0]+","+a[1]+","+a[2]+","+b+")"},d.Color.prototype._getAlpha=function(){return this._array[3]*this.maxes[this.mode][3]},d.Color.prototype._getBlue=function(){return this._array[2]*this.maxes[e.RGB][2]},d.Color.prototype._getBrightness=function(){return this.hsba||(this.hsba=f._rgbaToHSBA(this._array)),this.hsba[2]*this.maxes[e.HSB][2]},d.Color.prototype._getGreen=function(){return this._array[1]*this.maxes[e.RGB][1]},d.Color.prototype._getHue=function(){return this.mode===e.HSB?(this.hsba||(this.hsba=f._rgbaToHSBA(this._array)),this.hsba[0]*this.maxes[e.HSB][0]):(this.hsla||(this.hsla=f._rgbaToHSLA(this._array)),this.hsla[0]*this.maxes[e.HSL][0])},d.Color.prototype._getLightness=function(){return this.hsla||(this.hsla=f._rgbaToHSLA(this._array)),this.hsla[2]*this.maxes[e.HSL][2]},d.Color.prototype._getRed=function(){return this._array[0]*this.maxes[e.RGB][0]},d.Color.prototype._getSaturation=function(){return this.mode===e.HSB?(this.hsba||(this.hsba=f._rgbaToHSBA(this._array)),this.hsba[1]*this.maxes[e.HSB][1]):(this.hsla||(this.hsla=f._rgbaToHSLA(this._array)),this.hsla[1]*this.maxes[e.HSL][1])};var g={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},h=/\s*/,i=/(\d{1,3})/,j=/((?:\d+(?:\.\d+)?)|(?:\.\d+))/,k=new RegExp(j.source+"%"),l={HEX3:/^#([a-f0-9])([a-f0-9])([a-f0-9])$/i,HEX6:/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i,RGB:new RegExp(["^rgb\\(",i.source,",",i.source,",",i.source,"\\)$"].join(h.source),"i"),RGB_PERCENT:new RegExp(["^rgb\\(",k.source,",",k.source,",",k.source,"\\)$"].join(h.source),"i"),RGBA:new RegExp(["^rgba\\(",i.source,",",i.source,",",i.source,",",j.source,"\\)$"].join(h.source),"i"),RGBA_PERCENT:new RegExp(["^rgba\\(",k.source,",",k.source,",",k.source,",",j.source,"\\)$"].join(h.source),"i"),HSL:new RegExp(["^hsl\\(",i.source,",",k.source,",",k.source,"\\)$"].join(h.source),"i"),HSLA:new RegExp(["^hsla\\(",i.source,",",k.source,",",k.source,",",j.source,"\\)$"].join(h.source),"i"),HSB:new RegExp(["^hsb\\(",i.source,",",k.source,",",k.source,"\\)$"].join(h.source),"i"),HSBA:new RegExp(["^hsba\\(",i.source,",",k.source,",",k.source,",",j.source,"\\)$"].join(h.source),"i")};d.Color._parseInputs=function(){var a=arguments.length,b=this._colorMode,c=this._colorMaxes,h=[];if(a>=3)return h[0]=arguments[0]/c[b][0],h[1]=arguments[1]/c[b][1],h[2]=arguments[2]/c[b][2],"number"==typeof arguments[3]?h[3]=arguments[3]/c[b][3]:h[3]=1,h=h.map(function(a){return Math.max(Math.min(a,1),0)}),b===e.HSL?f._hslaToRGBA(h):b===e.HSB?f._hsbaToRGBA(h):h;if(1===a&&"string"==typeof arguments[0]){var i=arguments[0].trim().toLowerCase();if(g[i])return d.Color._parseInputs.apply(this,[g[i]]);if(l.HEX3.test(i))return h=l.HEX3.exec(i).slice(1).map(function(a){return parseInt(a+a,16)/255}),h[3]=1,h;if(l.HEX6.test(i))return h=l.HEX6.exec(i).slice(1).map(function(a){return parseInt(a,16)/255}),h[3]=1,h;if(l.RGB.test(i))return h=l.RGB.exec(i).slice(1).map(function(a){return a/255}),h[3]=1,h;if(l.RGB_PERCENT.test(i))return h=l.RGB_PERCENT.exec(i).slice(1).map(function(a){return parseFloat(a)/100}),h[3]=1,h;if(l.RGBA.test(i))return h=l.RGBA.exec(i).slice(1).map(function(a,b){return 3===b?parseFloat(a):a/255});if(l.RGBA_PERCENT.test(i))return h=l.RGBA_PERCENT.exec(i).slice(1).map(function(a,b){return 3===b?parseFloat(a):parseFloat(a)/100});if(l.HSL.test(i)?(h=l.HSL.exec(i).slice(1).map(function(a,b){return 0===b?parseInt(a,10)/360:parseInt(a,10)/100}),h[3]=1):l.HSLA.test(i)&&(h=l.HSLA.exec(i).slice(1).map(function(a,b){return 0===b?parseInt(a,10)/360:3===b?parseFloat(a):parseInt(a,10)/100})),h=h.map(function(a){return Math.max(Math.min(a,1),0)}),h.length)return f._hslaToRGBA(h);if(l.HSB.test(i)?(h=l.HSB.exec(i).slice(1).map(function(a,b){return 0===b?parseInt(a,10)/360:parseInt(a,10)/100}),h[3]=1):l.HSBA.test(i)&&(h=l.HSBA.exec(i).slice(1).map(function(a,b){return 0===b?parseInt(a,10)/360:3===b?parseFloat(a):parseInt(a,10)/100})),h=h.map(function(a){return Math.max(Math.min(a,1),0)}),h.length)return f._hsbaToRGBA(h);h=[1,1,1,1]}else{if(1!==a&&2!==a||"number"!=typeof arguments[0])throw new Error(arguments+"is not a valid color representation.");h[0]=arguments[0]/c[b][2],h[1]=arguments[0]/c[b][2],h[2]=arguments[0]/c[b][2],"number"==typeof arguments[1]?h[3]=arguments[1]/c[b][3]:h[3]=1,h=h.map(function(a){return Math.max(Math.min(a,1),0)})}return h},b.exports=d.Color},{"../core/constants":41,"../core/core":42,"./color_conversion":34}],37:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("../core/constants");a("./p5.Color"),d.prototype.background=function(){return arguments[0]instanceof d.Image?this.image(arguments[0],0,0,this.width,this.height):this._renderer.background.apply(this._renderer,arguments),this},d.prototype.clear=function(){return this._renderer.clear(),this},d.prototype.colorMode=function(){if(arguments[0]===e.RGB||arguments[0]===e.HSB||arguments[0]===e.HSL){this._renderer._colorMode=arguments[0];var a=this._renderer._colorMaxes[this._renderer._colorMode];2===arguments.length?(a[0]=arguments[1],a[1]=arguments[1],a[2]=arguments[1],a[3]=arguments[1]):4===arguments.length?(a[0]=arguments[1],a[1]=arguments[2],a[2]=arguments[3]):5===arguments.length&&(a[0]=arguments[1],a[1]=arguments[2],a[2]=arguments[3],a[3]=arguments[4])}return this},d.prototype.fill=function(){return this._renderer._setProperty("_fillSet",!0),this._renderer._setProperty("_doFill",!0),this._renderer.fill.apply(this._renderer,arguments),this},d.prototype.noFill=function(){return this._renderer._setProperty("_doFill",!1),this},d.prototype.noStroke=function(){return this._renderer._setProperty("_doStroke",!1),this},d.prototype.stroke=function(){return this._renderer._setProperty("_strokeSet",!0),this._renderer._setProperty("_doStroke",!0),this._renderer.stroke.apply(this._renderer,arguments),this},b.exports=d},{"../core/constants":41,"../core/core":42,"./p5.Color":36}],38:[function(a,b,c){"use strict";var d=a("./core"),e=a("./constants"),f=a("./canvas");a("./error_helpers"),d.prototype.arc=function(a,b,c,d,f,g,h){for(var i=new Array(arguments.length),j=0;je.HALF_PI&&f<=3*e.HALF_PI?Math.atan(c/d*Math.tan(f))+e.PI:Math.atan(c/d*Math.tan(f))+e.TWO_PI,g=g<=e.HALF_PI?Math.atan(c/d*Math.tan(g)):g>e.HALF_PI&&g<=3*e.HALF_PI?Math.atan(c/d*Math.tan(g))+e.PI:Math.atan(c/d*Math.tan(g))+e.TWO_PI,f>g&&(g+=e.TWO_PI),c=Math.abs(c),d=Math.abs(d),this._renderer.arc(a,b,c,d,f,g,h),this},d.prototype.ellipse=function(){for(var a=new Array(arguments.length),b=0;b=c-5)&&(this._setProperty("frameCount",this.frameCount+1),this.redraw(),this._updateMouseCoords(),this._frameRate=1e3/(a-this._lastFrameTime),this._lastFrameTime=a),this._loop&&(this._requestAnimId=window.requestAnimationFrame(this._draw))}.bind(this),this._runFrames=function(){this._updateInterval&&clearInterval(this._updateInterval)}.bind(this),this._setProperty=function(a,b){this[a]=b,this._isGlobal&&(window[a]=b)}.bind(this),this.remove=function(){if(this._curElement){this._loop=!1,this._requestAnimId&&window.cancelAnimationFrame(this._requestAnimId);for(var a in this._events)window.removeEventListener(a,this._events[a]);for(var b=0;b1)console.log.apply(console,arguments);else{var b=JSON.parse(JSON.stringify(a));"{}"===JSON.stringify(b)?console.log(a):console.log(b)}}catch(b){console.log(a)}}:h.prototype.print=function(){},h.prototype.frameCount=0,h.prototype.focused=document.hasFocus(),h.prototype.cursor=function(a,b,c){var d="auto",e=this._curElement.elt;if(j.indexOf(a)>-1)d=a;else if("string"==typeof a){var f="";b&&c&&"number"==typeof b&&"number"==typeof c&&(f=b+" "+c),d="http://"===a.substring(0,7)||"https://"===a.substring(0,8)?"url("+a+") "+f+", auto":/\.(cur|jpg|jpeg|gif|png|CUR|JPG|JPEG|GIF|PNG)$/.test(a)?"url("+a+") "+f+", auto":a}e.style.cursor=d},h.prototype.frameRate=function(a){return"number"!=typeof a||a<=0?this._frameRate:(this._setProperty("_targetFrameRate",a),this._runFrames(),this)},h.prototype.getFrameRate=function(){return this.frameRate()},h.prototype.setFrameRate=function(a){return this.frameRate(a)},h.prototype.noCursor=function(){this._curElement.elt.style.cursor="none"},h.prototype.displayWidth=screen.width,h.prototype.displayHeight=screen.height,h.prototype.windowWidth=d(),h.prototype.windowHeight=e(),h.prototype._onresize=function(a){this._setProperty("windowWidth",d()),this._setProperty("windowHeight",e());var b,c=this._isGlobal?window:this;"function"==typeof c.windowResized&&(void 0===(b=c.windowResized(a))||b||a.preventDefault())},h.prototype.width=0,h.prototype.height=0,h.prototype.fullscreen=function(a){if(void 0===a)return document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement;a?f(document.documentElement):g()},h.prototype.pixelDensity=function(a){if("number"!=typeof a)return this._pixelDensity;this._pixelDensity=a,this.resizeCanvas(this.width,this.height,!0)},h.prototype.displayDensity=function(){return window.devicePixelRatio},h.prototype.getURL=function(){return location.href},h.prototype.getURLPath=function(){return location.pathname.split("/").filter(function(a){return""!==a})},h.prototype.getURLParams=function(){for(var a,b=/[?&]([^&=]+)(?:[&=])([^&=]+)/gim,c={};null!=(a=b.exec(location.search));)a.index===b.lastIndex&&b.lastIndex++,c[a[1]]=a[2];return c},b.exports=h},{"./constants":41,"./core":42}],45:[function(a,b,c){"use strict";function d(a,b,c){i&&(e(),i=!1),"undefined"===n(c)?c="#B40033":"number"===n(c)&&(c=o[c])}function e(){console.log("%c _ \n /\\| |/\\ \n \\ ` ' / \n / , . \\ \n \\/|_|\\/ \n\n%c> p5.js says: Welcome! This is your friendly debugger. To turn me off switch to using “p5.min.js”.","background-color:transparent;color:#ED225D;","background-color:#ED225D;color:white;")}function f(){var b={},c=function(a){return Object.getOwnPropertyNames(a).filter(function(a){return"_"!==a[0]&&(!(a in b)&&(b[a]=!0,!0))}).map(function(b){var c;return c="function"==typeof a[b]?"function":b===b.toUpperCase()?"constant":"variable",{name:b,type:c}})};q=[].concat(c(h.prototype),c(a("./constants"))),q.sort(function(a,b){return b.name.length-a.name.length})}function g(a,b){b||(b=console.log.bind(console)),q||f(),q.some(function(c){if(a.message&&null!==a.message.match("\\W?"+c.name+"\\W"))return b("%cDid you just try to use p5.js's "+c.name+("function"===c.type?"() ":" ")+c.type+"? If so, you may want to move it into your sketch's setup() function.\n\nFor more details, see: "+r,"color: #B40033"),!0})}for(var h=a("./core"),i=!1,j={},k=j.toString,l=["Boolean","Number","String","Function","Array","Date","RegExp","Object","Error"],m=0;m1&&d("drop",b,this),d("drop",function(a){a.stopPropagation(),a.preventDefault();for(var b=a.dataTransfer.files,d=0;d-1?f.readAsText(e):f.readAsDataURL(e)}},this)):console.log("The File APIs are not fully supported in this browser."),this},e.Element.prototype._setProperty=function(a,b){this[a]=b},b.exports=e.Element},{"./core":42}],47:[function(a,b,c){var d=a("./core"),e=a("./constants");d.Graphics=function(a,b,c,f){var g=c||e.P2D;this.canvas=document.createElement("canvas"),(this._userNode||document.body).appendChild(this.canvas),d.Element.call(this,this.canvas,f,!1),this._styles=[],this.width=a,this.height=b,this._pixelDensity=f._pixelDensity,g===e.WEBGL?this._renderer=new d.RendererGL(this.canvas,this,!1):this._renderer=new d.Renderer2D(this.canvas,this,!1),this._renderer.resize(a,b),this._renderer._applyDefaults(),f._elements.push(this);for(var h in d.prototype)this[h]||("function"==typeof d.prototype[h]?this[h]=d.prototype[h].bind(this):this[h]=d.prototype[h]);return this},d.Graphics.prototype=Object.create(d.Element.prototype),d.Graphics.prototype.remove=function(){this.elt.parentNode&&this.elt.parentNode.removeChild(this.elt);for(var a in this._events)this.elt.removeEventListener(a,this._events[a])},b.exports=d.Graphics},{"./constants":41,"./core":42}],48:[function(a,b,c){function d(a){var b=0,c=0;if(a.offsetParent)do{b+=a.offsetLeft,c+=a.offsetTop}while(a=a.offsetParent);else b+=a.offsetLeft,c+=a.offsetTop;return[b,c]}var e=a("./core"),f=a("../core/constants");e.Renderer=function(a,b,c){e.Element.call(this,a,b),this.canvas=a,this._pInst=b,c?(this._isMainCanvas=!0,this._pInst._setProperty("_curElement",this),this._pInst._setProperty("canvas",this.canvas),this._pInst._setProperty("width",this.width),this._pInst._setProperty("height",this.height)):(this.canvas.style.display="none",this._styles=[]),this._textSize=12,this._textLeading=15,this._textFont="sans-serif",this._textStyle=f.NORMAL,this._textAscent=null,this._textDescent=null,this._rectMode=f.CORNER,this._ellipseMode=f.CENTER,this._curveTightness=0,this._imageMode=f.CORNER,this._tint=null,this._doStroke=!0,this._doFill=!0,this._strokeSet=!1,this._fillSet=!1,this._colorMode=f.RGB,this._colorMaxes={rgb:[255,255,255,255],hsb:[360,100,100,1],hsl:[360,100,100,1]}},e.Renderer.prototype=Object.create(e.Element.prototype),e.Renderer.prototype.resize=function(a,b){this.width=a,this.height=b,this.elt.width=a*this._pInst._pixelDensity,this.elt.height=b*this._pInst._pixelDensity,this.elt.style.width=a+"px",this.elt.style.height=b+"px",this._isMainCanvas&&(this._pInst._setProperty("width",this.width),this._pInst._setProperty("height",this.height))},e.Renderer.prototype.textLeading=function(a){return arguments.length&&arguments[0]?(this._setProperty("_textLeading",a),this):this._textLeading},e.Renderer.prototype.textSize=function(a){return arguments.length&&arguments[0]?(this._setProperty("_textSize",a),this._setProperty("_textLeading",a*f._DEFAULT_LEADMULT),this._applyTextProperties()):this._textSize},e.Renderer.prototype.textStyle=function(a){return arguments.length&&arguments[0]?(a!==f.NORMAL&&a!==f.ITALIC&&a!==f.BOLD||this._setProperty("_textStyle",a),this._applyTextProperties()):this._textStyle},e.Renderer.prototype.textAscent=function(){return null===this._textAscent&&this._updateTextMetrics(),this._textAscent},e.Renderer.prototype.textDescent=function(){return null===this._textDescent&&this._updateTextMetrics(),this._textDescent},e.Renderer.prototype._applyDefaults=function(){return this},e.Renderer.prototype._isOpenType=function(a){return"object"==typeof(a=a||this._textFont)&&a.font&&a.font.supported},e.Renderer.prototype._updateTextMetrics=function(){if(this._isOpenType())return this._setProperty("_textAscent",this._textFont._textAscent()),this._setProperty("_textDescent",this._textFont._textDescent()),this;var a=document.createElement("span");a.style.fontFamily=this._textFont,a.style.fontSize=this._textSize+"px",a.innerHTML="ABCjgq|";var b=document.createElement("div");b.style.display="inline-block",b.style.width="1px",b.style.height="0px";var c=document.createElement("div");c.appendChild(a),c.appendChild(b),c.style.height="0px",c.style.overflow="hidden",document.body.appendChild(c),b.style.verticalAlign="baseline";var e=d(b),f=d(a),g=e[1]-f[1];b.style.verticalAlign="bottom",e=d(b),f=d(a);var h=e[1]-f[1],i=h-g;return document.body.removeChild(c),this._setProperty("_textAscent",g),this._setProperty("_textDescent",i),this},b.exports=e.Renderer},{"../core/constants":41,"./core":42}],49:[function(a,b,c){var d=a("./core"),e=a("./canvas"),f=a("./constants"),g=a("../image/filters");a("./p5.Renderer");var h="rgba(0,0,0,0)";d.Renderer2D=function(a,b,c){return d.Renderer.call(this,a,b,c),this.drawingContext=this.canvas.getContext("2d"),this._pInst._setProperty("drawingContext",this.drawingContext),this},d.Renderer2D.prototype=Object.create(d.Renderer.prototype),d.Renderer2D.prototype._applyDefaults=function(){this.drawingContext.fillStyle=f._DEFAULT_FILL,this.drawingContext.strokeStyle=f._DEFAULT_STROKE,this.drawingContext.lineCap=f.ROUND,this.drawingContext.font="normal 12px sans-serif"},d.Renderer2D.prototype.resize=function(a,b){d.Renderer.prototype.resize.call(this,a,b),this.drawingContext.scale(this._pInst._pixelDensity,this._pInst._pixelDensity)},d.Renderer2D.prototype.background=function(){if(this.drawingContext.save(),this.drawingContext.setTransform(1,0,0,1,0,0),this.drawingContext.scale(this._pInst._pixelDensity,this._pInst._pixelDensity),arguments[0]instanceof d.Image)this._pInst.image(arguments[0],0,0,this.width,this.height);else{var a=this.drawingContext.fillStyle,b=this._pInst.color.apply(this,arguments),c=b.toString();this.drawingContext.fillStyle=c,this.drawingContext.fillRect(0,0,this.width,this.height),this.drawingContext.fillStyle=a}this.drawingContext.restore()},d.Renderer2D.prototype.clear=function(){this.drawingContext.clearRect(0,0,this.width,this.height)},d.Renderer2D.prototype.fill=function(){var a=this.drawingContext,b=this._pInst.color.apply(this,arguments);a.fillStyle=b.toString()},d.Renderer2D.prototype.stroke=function(){var a=this.drawingContext,b=this._pInst.color.apply(this,arguments);a.strokeStyle=b.toString()},d.Renderer2D.prototype.image=function(a,b,c,e,f,g,h,i,j){var k;try{this._tint&&(d.MediaElement&&a instanceof d.MediaElement&&a.loadPixels(),a.canvas&&(k=this._getTintedImageCanvas(a))),k||(k=a.canvas||a.elt),this.drawingContext.drawImage(k,b,c,e,f,g,h,i,j)}catch(a){if("NS_ERROR_NOT_AVAILABLE"!==a.name)throw a}},d.Renderer2D.prototype._getTintedImageCanvas=function(a){if(!a.canvas)return a;var b=g._toPixels(a.canvas),c=document.createElement("canvas");c.width=a.canvas.width,c.height=a.canvas.height;for(var d=c.getContext("2d"),e=d.createImageData(a.canvas.width,a.canvas.height),f=e.data,h=0;hthis.width||b>this.height)return[0,0,0,255];var f=this._pInst||this;f.loadPixels();var g=f._pixelDensity;a=Math.floor(a),b=Math.floor(b),c=Math.floor(c),e=Math.floor(e);var h=a*g,i=b*g;if(1===c&&1===e){var j=this.drawingContext.getImageData(h,i,1,1).data;return[j[0],j[1],j[2],j[3]]}var k=Math.min(c,f.width),l=Math.min(e,f.height),m=k*g,n=l*g,o=new d.Image(k,l);return o.canvas.getContext("2d").drawImage(this.canvas,h,i,m,n,0,0,k,l),o},d.Renderer2D.prototype.loadPixels=function(){var a=this._pixelDensity||this._pInst._pixelDensity,b=this.width*a,c=this.height*a,d=this.drawingContext.getImageData(0,0,b,c);this._pInst?(this._pInst._setProperty("imageData",d),this._pInst._setProperty("pixels",d.data)):(this._setProperty("imageData",d),this._setProperty("pixels",d.data))},d.Renderer2D.prototype.set=function(a,b,c){if(a=Math.floor(a),b=Math.floor(b),c instanceof d.Image)this.drawingContext.save(),this.drawingContext.setTransform(1,0,0,1,0,0),this.drawingContext.scale(this._pInst._pixelDensity,this._pInst._pixelDensity),this.drawingContext.drawImage(c.canvas,a,b),this.loadPixels.call(this._pInst),this.drawingContext.restore();else{var e=this._pInst||this,f=0,g=0,h=0,i=0,j=4*(b*e._pixelDensity*(this.width*e._pixelDensity)+a*e._pixelDensity);if(e.imageData||e.loadPixels.call(e),"number"==typeof c)jn;)o=Math.min(h-g,f.HALF_PI),p.push(this._acuteArcToBezier(g,o)),g+=o;return this._doFill&&(j.beginPath(),p.forEach(function(a,b){0===b&&j.moveTo(k.x+a.ax*l,k.y+a.ay*m),j.bezierCurveTo(k.x+a.bx*l,k.y+a.by*m,k.x+a.cx*l,k.y+a.cy*m,k.x+a.dx*l,k.y+a.dy*m)}),i!==f.PIE&&null!=i||j.lineTo(k.x,k.y),j.closePath(),j.fill()),this._doStroke&&(j.beginPath(),p.forEach(function(a,b){0===b&&j.moveTo(k.x+a.ax*l,k.y+a.ay*m),j.bezierCurveTo(k.x+a.bx*l,k.y+a.by*m,k.x+a.cx*l,k.y+a.cy*m,k.x+a.dx*l,k.y+a.dy*m)}),i===f.PIE?(j.lineTo(k.x,k.y),j.closePath()):i===f.CHORD&&j.closePath(),j.stroke()),this},d.Renderer2D.prototype.ellipse=function(a){var b=this.drawingContext,c=this._doFill,d=this._doStroke,e=a[0],f=a[1],g=a[2],i=a[3];if(c&&!d){if(b.fillStyle===h)return this}else if(!c&&d&&b.strokeStyle===h)return this;var j=.5522847498,k=g/2*j,l=i/2*j,m=e+g,n=f+i,o=e+g/2,p=f+i/2;b.beginPath(),b.moveTo(e,p),b.bezierCurveTo(e,p-l,o-k,f,o,f),b.bezierCurveTo(o+k,f,m,p-l,m,p),b.bezierCurveTo(m,p+l,o+k,n,o,n),b.bezierCurveTo(o-k,n,e,p+l,e,p),b.closePath(),c&&b.fill(),d&&b.stroke()},d.Renderer2D.prototype.line=function(a,b,c,d){var e=this.drawingContext;return this._doStroke?e.strokeStyle===h?this:(e.lineWidth%2==1&&e.translate(.5,.5),e.beginPath(),e.moveTo(a,b),e.lineTo(c,d),e.stroke(),e.lineWidth%2==1&&e.translate(-.5,-.5),this):this},d.Renderer2D.prototype.point=function(a,b){var c=this.drawingContext,d=c.strokeStyle,e=c.fillStyle;return this._doStroke?c.strokeStyle===h?this:(a=Math.round(a),b=Math.round(b),c.fillStyle=d,c.lineWidth>1?(c.beginPath(),c.arc(a,b,c.lineWidth/2,0,f.TWO_PI,!1),c.fill()):c.fillRect(a,b,1,1),void(c.fillStyle=e)):this},d.Renderer2D.prototype.quad=function(a,b,c,d,e,f,g,i){var j=this.drawingContext,k=this._doFill,l=this._doStroke;if(k&&!l){if(j.fillStyle===h)return this}else if(!k&&l&&j.strokeStyle===h)return this;return j.beginPath(),j.moveTo(a,b),j.lineTo(c,d),j.lineTo(e,f),j.lineTo(g,i),j.closePath(),k&&j.fill(),l&&j.stroke(),this},d.Renderer2D.prototype.rect=function(a){var b=a[0],c=a[1],d=a[2],e=a[3],f=a[4],g=a[5],i=a[6],j=a[7],k=this.drawingContext,l=this._doFill,m=this._doStroke;if(l&&!m){if(k.fillStyle===h)return this}else if(!l&&m&&k.strokeStyle===h)return this;if(this._doStroke&&k.lineWidth%2==1&&k.translate(.5,.5),k.beginPath(),void 0===f)k.rect(b,c,d,e);else{void 0===g&&(g=f),void 0===i&&(i=g),void 0===j&&(j=i);var n=d/2,o=e/2;d<2*f&&(f=n),e<2*f&&(f=o),d<2*g&&(g=n),e<2*g&&(g=o),d<2*i&&(i=n),e<2*i&&(i=o),d<2*j&&(j=n),e<2*j&&(j=o),k.beginPath(),k.moveTo(b+f,c),k.arcTo(b+d,c,b+d,c+e,g),k.arcTo(b+d,c+e,b,c+e,i),k.arcTo(b,c+e,b,c,j),k.arcTo(b,c,b+d,c,f),k.closePath()}return this._doFill&&k.fill(),this._doStroke&&k.stroke(),this._doStroke&&k.lineWidth%2==1&&k.translate(-.5,-.5),this},d.Renderer2D.prototype.triangle=function(a){var b=this.drawingContext,c=this._doFill,d=this._doStroke,e=a[0],f=a[1],g=a[2],i=a[3],j=a[4],k=a[5];if(c&&!d){if(b.fillStyle===h)return this}else if(!c&&d&&b.strokeStyle===h)return this;b.beginPath(),b.moveTo(e,f),b.lineTo(g,i),b.lineTo(j,k),b.closePath(),c&&b.fill(),d&&b.stroke()},d.Renderer2D.prototype.endShape=function(a,b,c,d,e,g,h){if(0===b.length)return this;if(!this._doStroke&&!this._doFill)return this;var i,j=a===f.CLOSE;j&&!g&&b.push(b[0]);var k,l,m=b.length;if(!c||h!==f.POLYGON&&null!==h)if(!d||h!==f.POLYGON&&null!==h)if(!e||h!==f.POLYGON&&null!==h)if(h===f.POINTS)for(k=0;k2)for(this.drawingContext.beginPath(),this.drawingContext.moveTo(b[0][0],b[0][1]),this.drawingContext.lineTo(b[1][0],b[1][1]),this.drawingContext.lineTo(b[2][0],b[2][1]),this._doFill&&this._pInst.fill(b[2][5]),this._doStroke&&this._pInst.stroke(b[2][6]),this._doFillStrokeClose(),k=3;k3)for(k=0;k+13){var n=[],o=1-this._curveTightness;for(this.drawingContext.beginPath(),this.drawingContext.moveTo(b[1][0],b[1][1]),k=1;k+2d?(k=n[h]+" ",o+=q.textLeading()):k=l;switch(this._rectMode===f.CENTER&&(b-=d/2,c-=e/2),this.drawingContext.textAlign){case f.CENTER:b+=d/2;break;case f.RIGHT:b+=d}if(void 0!==e){switch(this.drawingContext.textBaseline){case f.BOTTOM:c+=e-o;break;case f._CTX_MIDDLE:c+=(e-o)/2;break;case f.BASELINE:p=!0,this.drawingContext.textBaseline=f.TOP}r=c+e-q.textAscent()}for(i=0;id&&k.length>0?(this._renderText(q,k,b,c,r),k=n[h]+" ",c+=q.textLeading()):k=l;this._renderText(q,k,b,c,r),c+=q.textLeading()}}else{var s=0,t=q.textAlign().vertical;for(t===f.CENTER?s=(g.length-1)*q.textLeading()/2:t===f.BOTTOM&&(s=(g.length-1)*q.textLeading()),j=0;j=e))return a.push(),this._isOpenType()?this._textFont._renderPath(b,c,d,{renderer:this}):(this._doStroke&&this._strokeSet&&this.drawingContext.strokeText(b,c,d),this._doFill&&(this.drawingContext.fillStyle=this._fillSet?this.drawingContext.fillStyle:f._DEFAULT_TEXT_FILL,this.drawingContext.fillText(b,c,d))),a.pop(),a},d.Renderer2D.prototype.textWidth=function(a){return this._isOpenType()?this._textFont._textWidth(a,this._textSize):this.drawingContext.measureText(a).width},d.Renderer2D.prototype.textAlign=function(a,b){if(arguments.length)return a!==f.LEFT&&a!==f.RIGHT&&a!==f.CENTER||(this.drawingContext.textAlign=a),b!==f.TOP&&b!==f.BOTTOM&&b!==f.CENTER&&b!==f.BASELINE||(b===f.CENTER?this.drawingContext.textBaseline=f._CTX_MIDDLE:this.drawingContext.textBaseline=b),this._pInst;var c=this.drawingContext.textBaseline;return c===f._CTX_MIDDLE&&(c=f.CENTER),{horizontal:this.drawingContext.textAlign,vertical:c}},d.Renderer2D.prototype._applyTextProperties=function(){var a,b=this._pInst;return this._setProperty("_textAscent",null),this._setProperty("_textDescent",null),a=this._textFont,this._isOpenType()&&(a=this._textFont.font.familyName,this._setProperty("_textStyle",this._textFont.font.styleName)),this.drawingContext.font=this._textStyle+" "+this._textSize+"px "+a,b},d.Renderer2D.prototype.push=function(){this.drawingContext.save()},d.Renderer2D.prototype.pop=function(){this.drawingContext.restore()},b.exports=d.Renderer2D},{"../image/filters":59,"./canvas":40,"./constants":41,"./core":42,"./p5.Renderer":48}],50:[function(a,b,c){var d=a("./core"),e=a("./constants");a("./p5.Graphics"),a("./p5.Renderer2D"),a("../webgl/p5.RendererGL");var f="defaultCanvas0";d.prototype.createCanvas=function(a,b,c){var g,h,i=c||e.P2D;if(arguments[3]&&(g="boolean"==typeof arguments[3]&&arguments[3]),i===e.WEBGL)h=document.getElementById(f),h&&h.parentNode.removeChild(h),h=document.createElement("canvas"),h.id=f;else if(g){h=document.createElement("canvas");for(var j=0;document.getElementById("defaultCanvas"+j);)j++;f="defaultCanvas"+j,h.id=f}else h=this.canvas;return this._setupDone||(h.dataset.hidden=!0,h.style.visibility="hidden"),this._userNode?this._userNode.appendChild(h):document.body.appendChild(h),i===e.WEBGL?(this._setProperty("_renderer",new d.RendererGL(h,this,!0)),this._isdefaultGraphics=!0):this._isdefaultGraphics||(this._setProperty("_renderer",new d.Renderer2D(h,this,!0)),this._isdefaultGraphics=!0),this._renderer.resize(a,b),this._renderer._applyDefaults(),g&&this._elements.push(this._renderer),this._renderer},d.prototype.resizeCanvas=function(a,b,c){if(this._renderer){var d={};for(var e in this.drawingContext){var f=this.drawingContext[e];"object"!=typeof f&&"function"!=typeof f&&(d[e]=f)}this._renderer.resize(a,b);for(var g in d)this.drawingContext[g]=d[g];c||this.redraw()}},d.prototype.noCanvas=function(){this.canvas&&this.canvas.parentNode.removeChild(this.canvas)},d.prototype.createGraphics=function(a,b,c){return new d.Graphics(a,b,c,this)},d.prototype.blendMode=function(a){if(a!==e.BLEND&&a!==e.DARKEST&&a!==e.LIGHTEST&&a!==e.DIFFERENCE&&a!==e.MULTIPLY&&a!==e.EXCLUSION&&a!==e.SCREEN&&a!==e.REPLACE&&a!==e.OVERLAY&&a!==e.HARD_LIGHT&&a!==e.SOFT_LIGHT&&a!==e.DODGE&&a!==e.BURN&&a!==e.ADD&&a!==e.NORMAL)throw new Error("Mode "+a+" not recognized.");this._renderer.blendMode(a)},b.exports=d},{"../webgl/p5.RendererGL":91,"./constants":41,"./core":42,"./p5.Graphics":47,"./p5.Renderer2D":49}],51:[function(a,b,c){window.requestAnimationFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a,b){window.setTimeout(a,1e3/60)}}(),window.performance=window.performance||{},window.performance.now=function(){var a=Date.now();return window.performance.now||window.performance.mozNow||window.performance.msNow||window.performance.oNow||window.performance.webkitNow||function(){return Date.now()-a}}(),function(){"use strict";"undefined"==typeof Uint8ClampedArray||Uint8ClampedArray.prototype.slice||Object.defineProperty(Uint8ClampedArray.prototype,"slice",{value:Array.prototype.slice,writable:!0,configurable:!0,enumerable:!1})}()},{}],52:[function(a,b,c){"use strict";var d=a("./core");d.prototype.exit=function(){throw"exit() not implemented, see remove()"},d.prototype.noLoop=function(){this._loop=!1},d.prototype.loop=function(){this._loop=!0,this._draw()},d.prototype.push=function(){this._renderer.push(),this._styles.push({_doStroke:this._renderer._doStroke,_strokeSet:this._renderer._strokeSet,_doFill:this._renderer._doFill,_fillSet:this._renderer._fillSet,_tint:this._renderer._tint,_imageMode:this._renderer._imageMode,_rectMode:this._renderer._rectMode,_ellipseMode:this._renderer._ellipseMode,_colorMode:this._renderer._colorMode,_textFont:this._renderer._textFont,_textLeading:this._renderer._textLeading,_textSize:this._renderer._textSize,_textStyle:this._renderer._textStyle})},d.prototype.pop=function(){this._renderer.pop();var a=this._styles.pop();for(var b in a)this._renderer[b]=a[b]},d.prototype.pushStyle=function(){throw new Error("pushStyle() not used, see push()")},d.prototype.popStyle=function(){throw new Error("popStyle() not used, see pop()")},d.prototype.redraw=function(){this.resetMatrix(),this._renderer.isP3D&&this._renderer._update();var a=1;if(1===arguments.length)try{parseInt(arguments[0])>1&&(a=parseInt(arguments[0]))}catch(a){}var b=this.setup||window.setup,c=this.draw||window.draw;if("function"==typeof c){void 0===b&&this.scale(this._pixelDensity,this._pixelDensity);for(var d=this,e=function(a){a.call(d)},f=0;f1?this._renderer.rotate(a,b[1]):this._renderer.rotate(a),this},d.prototype.rotateX=function(a){if(!this._renderer.isP3D)throw"not supported in p2d. Please use webgl mode";return this._renderer.rotateX(a),this},d.prototype.rotateY=function(a){if(!this._renderer.isP3D)throw"not supported in p2d. Please use webgl mode";return this._renderer.rotateY(a),this},d.prototype.rotateZ=function(a){if(!this._renderer.isP3D)throw"not supported in p2d. Please use webgl mode";return this._renderer.rotateZ(a),this},d.prototype.scale=function(){for(var a,b,c,e=new Array(arguments.length),f=0;f0))throw"vertex() must be used once before calling quadraticVertex()";k=!0;for(var i=[],j=0;jn||Math.abs(this.accelerationY-this.pAccelerationY)>n||Math.abs(this.accelerationZ-this.pAccelerationZ)>n)&&a();var b=this.deviceTurned||window.deviceTurned;if("function"==typeof b){var c=this.rotationX+180,d=this.pRotationX+180,p=h+180;c-d>0&&c-d<270||c-d<-270?k="clockwise":(c-d<0||c-d>270)&&(k="counter-clockwise"),k!==e&&(p=c),Math.abs(c-p)>90&&Math.abs(c-p)<270&&(p=c,this._setProperty("turnAxis","X"),b()),e=k,h=p-180;var q=this.rotationY+180,r=this.pRotationY+180,s=i+180;q-r>0&&q-r<270||q-r<-270?l="clockwise":(q-r<0||q-this.pRotationY>270)&&(l="counter-clockwise"),l!==f&&(s=q),Math.abs(q-s)>90&&Math.abs(q-s)<270&&(s=q,this._setProperty("turnAxis","Y"),b()),f=l,i=s-180,this.rotationZ-this.pRotationZ>0&&this.rotationZ-this.pRotationZ<270||this.rotationZ-this.pRotationZ<-270?m="clockwise":(this.rotationZ-this.pRotationZ<0||this.rotationZ-this.pRotationZ>270)&&(m="counter-clockwise"),m!==g&&(j=this.rotationZ),Math.abs(this.rotationZ-j)>90&&Math.abs(this.rotationZ-j)<270&&(j=this.rotationZ,this._setProperty("turnAxis","Z"),b()),g=m,this._setProperty("turnAxis",void 0)}var t=this.deviceShaken||window.deviceShaken;if("function"==typeof t){var u,v;null!==this.pAccelerationX&&(u=Math.abs(this.accelerationX-this.pAccelerationX),v=Math.abs(this.accelerationY-this.pAccelerationY)),u+v>o&&t()}},b.exports=d},{"../core/core":42}],56:[function(a,b,c){"use strict";function d(){for(var a in f)if(f.hasOwnProperty(a)&&f[a]===!0)return!0;return!1}var e=a("../core/core"),f={};e.prototype.isKeyPressed=!1,e.prototype.keyIsPressed=!1,e.prototype.key="",e.prototype.keyCode=0,e.prototype._onkeydown=function(a){if(!f[a.which]){this._setProperty("isKeyPressed",!0),this._setProperty("keyIsPressed",!0),this._setProperty("keyCode",a.which),f[a.which]=!0;var b=String.fromCharCode(a.which);b||(b=a.which),this._setProperty("key",b);var c=this.keyPressed||window.keyPressed;if("function"==typeof c&&!a.charCode){c(a)===!1&&a.preventDefault()}}},e.prototype._onkeyup=function(a){var b=this.keyReleased||window.keyReleased;f[a.which]=!1,d()||(this._setProperty("isKeyPressed",!1),this._setProperty("keyIsPressed",!1)),this._setProperty("_lastKeyCodeTyped",null);var c=String.fromCharCode(a.which);if(c||(c=a.which),this._setProperty("key",c),this._setProperty("keyCode",a.which),"function"==typeof b){b(a)===!1&&a.preventDefault()}},e.prototype._onkeypress=function(a){if(a.which!==this._lastKeyCodeTyped){this._setProperty("keyCode",a.which),this._setProperty("_lastKeyCodeTyped",a.which),this._setProperty("key",String.fromCharCode(a.which));var b=this.keyTyped||window.keyTyped;if("function"==typeof b){b(a)===!1&&a.preventDefault()}}},e.prototype._onblur=function(a){f={}},e.prototype.keyIsDown=function(a){return f[a]},b.exports=e},{"../core/core":42}],57:[function(a,b,c){"use strict";function d(a,b,c,d){d&&!d.clientX&&(d.touches?d=d.touches[0]:d.changedTouches&&(d=d.changedTouches[0]));var e=a.getBoundingClientRect(),f=a.scrollWidth/b,g=a.scrollHeight/c;return{x:(d.clientX-e.left)/f,y:(d.clientY-e.top)/g,winX:d.clientX,winY:d.clientY,id:d.identifier}}var e=a("../core/core"),f=a("../core/constants");e.prototype._hasMouseInteracted=!1,e.prototype.mouseX=0,e.prototype.mouseY=0,e.prototype.pmouseX=0,e.prototype.pmouseY=0,e.prototype.winMouseX=0,e.prototype.winMouseY=0,e.prototype.pwinMouseX=0,e.prototype.pwinMouseY=0,e.prototype.mouseButton=0,e.prototype.mouseIsPressed=!1,e.prototype._updateNextMouseCoords=function(a){if(null!==this._curElement&&(!a.touches||a.touches.length>0)){var b=d(this._curElement.elt,this.width,this.height,a);this._setProperty("mouseX",b.x),this._setProperty("mouseY",b.y),this._setProperty("winMouseX",b.winX),this._setProperty("winMouseY",b.winY)}this._hasMouseInteracted||(this._updateMouseCoords(),this._setProperty("_hasMouseInteracted",!0))},e.prototype._updateMouseCoords=function(){this._setProperty("pmouseX",this.mouseX),this._setProperty("pmouseY",this.mouseY),this._setProperty("pwinMouseX",this.winMouseX),this._setProperty("pwinMouseY",this.winMouseY)},e.prototype._setMouseButton=function(a){1===a.button?this._setProperty("mouseButton",f.CENTER):2===a.button?this._setProperty("mouseButton",f.RIGHT):this._setProperty("mouseButton",f.LEFT)},e.prototype._onmousemove=function(a){var b=this._isGlobal?window:this;this._updateNextMouseCoords(a),this.mouseIsPressed?"function"==typeof b.mouseDragged?b.mouseDragged(a)===!1&&a.preventDefault():"function"==typeof b.touchMoved&&b.touchMoved(a)===!1&&a.preventDefault():"function"==typeof b.mouseMoved&&b.mouseMoved(a)===!1&&a.preventDefault()},e.prototype._onmousedown=function(a){var b=this._isGlobal?window:this;this._setProperty("mouseIsPressed",!0),this._setMouseButton(a),this._updateNextMouseCoords(a),"function"==typeof b.mousePressed?b.mousePressed(a)===!1&&a.preventDefault():"function"==typeof b.touchStarted&&b.touchStarted(a)===!1&&a.preventDefault()},e.prototype._onmouseup=function(a){var b=this._isGlobal?window:this;this._setProperty("mouseIsPressed",!1),"function"==typeof b.mouseReleased?b.mouseReleased(a)===!1&&a.preventDefault():"function"==typeof b.touchEnded&&b.touchEnded(a)===!1&&a.preventDefault()},e.prototype._ondragend=e.prototype._onmouseup,e.prototype._ondragover=e.prototype._onmousemove,e.prototype._onclick=function(a){var b=this._isGlobal?window:this;if("function"==typeof b.mouseClicked){b.mouseClicked(a)===!1&&a.preventDefault()}},e.prototype._onwheel=function(a){var b=this._isGlobal?window:this;if("function"==typeof b.mouseWheel){a.delta=a.deltaY;b.mouseWheel(a)===!1&&a.preventDefault()}},b.exports=e},{"../core/constants":41,"../core/core":42}],58:[function(a,b,c){"use strict";function d(a,b,c,d,e){e=e||0;var f=a.getBoundingClientRect(),g=a.scrollWidth/b,h=a.scrollHeight/c,i=d.touches[e]||d.changedTouches[e];return{x:(i.clientX-f.left)/g,y:(i.clientY-f.top)/h,winX:i.clientX,winY:i.clientY,id:i.identifier}}var e=a("../core/core");e.prototype.touches=[],e.prototype._updateTouchCoords=function(a){if(null!==this._curElement){for(var b=[],c=0;c=e)break;x=0}for(F=x;F=e);F++){var H=m[t+C];G=j[F],s+=G[(H&-16777216)>>>24],p+=G[(16711680&H)>>16],q+=G[(65280&H)>>8],r+=G[255&H],o+=i[F],t++}u=C+D,y[u]=s/o,z[u]=p/o,A[u]=q/o,B[u]=r/o}C+=e}for(C=0,v=-g,w=v*e,E=0;E=k)break;x=0,u=v,t=D+w}for(F=x;F=k);F++)G=j[F],s+=G[y[t]],p+=G[z[t]],q+=G[A[t]],r+=G[B[t]],o+=i[F],u++,t+=e;m[D+C]=s/o<<24|p/o<<16|q/o<<8|r/o}C+=e,w+=e,v++}f._setPixels(c,m)}var f={};f._toPixels=function(a){return a instanceof ImageData?a.data:a.getContext("2d").getImageData(0,0,a.width,a.height).data},f._getARGB=function(a,b){var c=4*b;return a[c+3]<<24&4278190080|a[c]<<16&16711680|a[c+1]<<8&65280|255&a[c+2]},f._setPixels=function(a,b){for(var c=0,d=0,e=a.length;d>>16,a[c+1]=(65280&b[d])>>>8,a[c+2]=255&b[d],a[c+3]=(4278190080&b[d])>>>24},f._toImageData=function(a){return a instanceof ImageData?a:a.getContext("2d").getImageData(0,0,a.width,a.height)},f._createImageData=function(a,b){return f._tmpCanvas=document.createElement("canvas"),f._tmpCtx=f._tmpCanvas.getContext("2d"),this._tmpCtx.createImageData(a,b)},f.apply=function(a,b,c){var d=a.getContext("2d"),e=d.getImageData(0,0,a.width,a.height),f=b(e,c);f instanceof ImageData?d.putImageData(f,0,0,0,0,a.width,a.height):d.putImageData(e,0,0,0,0,a.width,a.height)},f.threshold=function(a,b){var c=f._toPixels(a);void 0===b&&(b=.5);for(var d=Math.floor(255*b),e=0;e=d?255:0,c[e]=c[e+1]=c[e+2]=g}},f.gray=function(a){for(var b=f._toPixels(a),c=0;c255)throw new Error("Level must be greater than 2 and less than 255 for posterize");for(var d=b-1,e=0;e>8)/d,c[e+1]=255*(h*b>>8)/d,c[e+2]=255*(i*b>>8)/d}},f.dilate=function(a){for(var b,c,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t=f._toPixels(a),u=0,v=t.length?t.length/4:0,w=new Int32Array(v);u=c&&(h=u),j<0&&(j=0),k>=v&&(k=u),n=f._getARGB(t,j),m=f._getARGB(t,i),o=f._getARGB(t,k),l=f._getARGB(t,h),g=77*(d>>16&255)+151*(d>>8&255)+28*(255&d),q=77*(m>>16&255)+151*(m>>8&255)+28*(255&m),p=77*(l>>16&255)+151*(l>>8&255)+28*(255&l),r=77*(n>>16&255)+151*(n>>8&255)+28*(255&n),s=77*(o>>16&255)+151*(o>>8&255)+28*(255&o),q>g&&(e=m,g=q),p>g&&(e=l,g=p),r>g&&(e=n,g=r),s>g&&(e=o,g=s),w[u++]=e;f._setPixels(t,w)},f.erode=function(a){for(var b,c,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t=f._toPixels(a),u=0,v=t.length?t.length/4:0,w=new Int32Array(v);u=c&&(h=u),j<0&&(j=0),k>=v&&(k=u),n=f._getARGB(t,j),m=f._getARGB(t,i),o=f._getARGB(t,k),l=f._getARGB(t,h),g=77*(d>>16&255)+151*(d>>8&255)+28*(255&d),q=77*(m>>16&255)+151*(m>>8&255)+28*(255&m),p=77*(l>>16&255)+151*(l>>8&255)+28*(255&l),r=77*(n>>16&255)+151*(n>>8&255)+28*(255&n),s=77*(o>>16&255)+151*(o>>8&255)+28*(255&o),q0&&a0&&this.loadPixels()},d.Image.prototype.copy=function(){d.prototype.copy.apply(this,arguments)},d.Image.prototype.mask=function(a){void 0===a&&(a=this);var b=this.drawingContext.globalCompositeOperation,c=1;a instanceof d.Renderer&&(c=a._pInst._pixelDensity);var e=[a,0,0,c*a.width,c*a.height,0,0,this.width,this.height];this.drawingContext.globalCompositeOperation="destination-in",d.Image.prototype.copy.apply(this,e),this.drawingContext.globalCompositeOperation=b},d.Image.prototype.filter=function(a,b){e.apply(this.canvas,e[a.toLowerCase()],b)},d.Image.prototype.blend=function(){d.prototype.blend.apply(this,arguments)},d.Image.prototype.save=function(a,b){var c;if(b)switch(b.toLowerCase()){case"png":c="image/png";break;case"jpeg":c="image/jpeg";break;case"jpg":c="image/jpeg";break;default:c="image/png"}else b="png",c="image/png";var e=this.canvas.toDataURL(c) +;e=e.replace(c,"image/octet-stream"),d.prototype.downloadFile(e,a,b)},b.exports=d.Image},{"../core/core":42,"./filters":59}],63:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("./filters");a("../color/p5.Color"),d.prototype.pixels=[],d.prototype.blend=function(){this._renderer?this._renderer.blend.apply(this._renderer,arguments):d.Renderer2D.prototype.blend.apply(this,arguments)},d.prototype.copy=function(){d.Renderer2D._copyHelper.apply(this,arguments)},d.prototype.filter=function(a,b){void 0!==this.canvas?e.apply(this.canvas,e[a.toLowerCase()],b):e.apply(this.elt,e[a.toLowerCase()],b)},d.prototype.get=function(a,b,c,d){return this._renderer.get(a,b,c,d)},d.prototype.loadPixels=function(){this._renderer.loadPixels()},d.prototype.set=function(a,b,c){this._renderer.set(a,b,c)},d.prototype.updatePixels=function(a,b,c,d){0!==this.pixels.length&&this._renderer.updatePixels(a,b,c,d)},b.exports=d},{"../color/p5.Color":36,"../core/core":42,"./filters":59}],64:[function(a,b,c){"use strict";function d(a,b){var c={};if(void 0===(b=b||[]))for(var d=0;d/g,">").replace(/"/g,""").replace(/'/g,"'")}function f(a,b){b&&b!==!0&&"true"!==b||(b=""),a||(a="untitled");var c="";return a&&a.indexOf(".")>-1&&(c=a.split(".").pop()),b&&c!==b&&(c=b,a=a+"."+c),[a,c]}function g(a){document.body.removeChild(a.target)}var h=a("../core/core"),i=a("opentype.js");a("whatwg-fetch"),a("es6-promise").polyfill();var j=a("fetch-jsonp");a("../core/error_helpers"),h._getDecrementPreload=function(){var a=arguments[arguments.length-1];return(window.preload||this&&this.preload)&&"function"==typeof a?a:null},h.prototype.loadFont=function(a,b,c){var d=new h.Font(this),e=h._getDecrementPreload.apply(this,arguments);return i.load(a,function(f,g){if(f)return void 0!==c&&c!==e?c(f):(h._friendlyFileLoadError(4,a),void console.error(f,a));d.font=g,void 0!==b&&b(d),e&&b!==e&&e();var i,j,k=["ttf","otf","woff","woff2"],l=a.split("\\").pop().split("/").pop(),m=l.lastIndexOf("."),n=m<1?null:l.substr(m+1);k.indexOf(n)>-1&&(i=l.substr(0,m),j=document.createElement("style"),j.appendChild(document.createTextNode("\n@font-face {\nfont-family: "+i+";\nsrc: url("+a+");\n}\n")),document.head.appendChild(j))}),d},h.prototype.loadJSON=function(){for(var a,b,c,d=arguments[0],e=h._getDecrementPreload.apply(this,arguments),f={},g="json",i=1;i0&&"function"==typeof arguments[h];h--)f++;if(2==arguments.length-f&&"string"==typeof arguments[0]&&"object"==typeof arguments[1])c=new Request(arguments[0],arguments[1]),a=arguments[2],b=arguments[3],""===d&&(d=c.url.indexOf("json")!==-1?"json":c.url.indexOf("xml")!==-1?"xml":"text");else{for(var i,k=arguments[0],l="GET",m=1;m"),f.print("");var l=' "),f.print(""),f.print(" "),"0"!==g[0]){f.print(" ");for(var m=0;m"+n),f.print(" ")}f.print(" ")}for(var o=0;o");for(var p=0;p"+r),f.print(" ")}f.print(" ")}f.print("
"),f.print(""),f.print("")}f.close(),f.flush()},h.prototype.writeFile=function(a,b,c){var d="application/octet-stream";h.prototype._isSafari()&&(d="text/plain");var e=new Blob(a,{type:d}),f=window.URL.createObjectURL(e);h.prototype.downloadFile(f,b,c)},h.prototype.downloadFile=function(a,b,c){var d=f(b,c),e=d[0],i=d[1],j=document.createElement("a");if(j.href=a,j.download=e,j.onclick=function(a){g(a),a.stopPropagation()},j.style.display="none",document.body.appendChild(j),h.prototype._isSafari()){var k="Hello, Safari user! To download this file...\n";k+="1. Go to File --> Save As.\n",k+='2. Choose "Page Source" as the Format.\n',k+='3. Name it with this extension: ."'+i+'"',alert(k)}j.click(),a=null},h.prototype._checkFileExtension=f,h.prototype._isSafari=function(){return Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0},b.exports=h},{"../core/core":42,"../core/error_helpers":45,"es6-promise":2,"fetch-jsonp":3,"opentype.js":10,"whatwg-fetch":32}],65:[function(a,b,c){"use strict";var d=a("../core/core");d.Table=function(a){this.columns=[],this.rows=[]},d.Table.prototype.addRow=function(a){var b=a||new d.TableRow;if(void 0===b.arr||void 0===b.obj)throw"invalid TableRow: "+b;return b.table=this,this.rows.push(b),b},d.Table.prototype.removeRow=function(a){this.rows[a].table=null;var b=this.rows.splice(a+1,this.rows.length);this.rows.pop(),this.rows=this.rows.concat(b)},d.Table.prototype.getRow=function(a){return this.rows[a]},d.Table.prototype.getRows=function(){return this.rows},d.Table.prototype.findRow=function(a,b){if("string"==typeof b){for(var c=0;c=0))throw'This table has no column named "'+a+'"';c=b[a],d[c]=b}else d[e]=this.rows[e].obj;return d},d.Table.prototype.getArray=function(){for(var a=[],b=0;b=0))throw'This table has no column named "'+a+'"';this.obj[a]=b,this.arr[c]=b}else{if(!(a0},d.XML.prototype.listChildren=function(){return this.children.map(function(a){return a.name})},d.XML.prototype.getChildren=function(a){return a?this.children.filter(function(b){return b.name===a}):this.children},d.XML.prototype.getChild=function(a){return"string"==typeof a?this.children.find(function(b){return b.name===a}):this.children[a]},d.XML.prototype.addChild=function(a){a instanceof d.XML&&this.children.push(a)},d.XML.prototype.removeChild=function(a){var b=-1;if("string"==typeof a){for(var c=0;cf&&(f=h),e[g]=h}0===f&&(f=1);for(var i=0,j=0,k=0;k=1&&(s++,v--),w>=1&&(t++,w--),x>=1&&(u++,x--)}return y},e.prototype.noiseDetail=function(a,b){a>0&&(k=a),b>0&&(l=b)},e.prototype.noiseSeed=function(a){var b=function(){var a,b,c=4294967296,d=1664525,e=1013904223;return{setSeed:function(d){b=a=(null==d?Math.random()*c:d)>>>0},getSeed:function(){return a},rand:function(){return(b=(d*b+e)%c)/c}}}();b.setSeed(a),d=new Array(j+1);for(var c=0;ca*a&&(this.div(Math.sqrt(b)),this.mult(a)),this},d.Vector.prototype.setMag=function(a){return this.normalize().mult(a)},d.Vector.prototype.heading=function(){var a=Math.atan2(this.y,this.x);return this.p5?this.p5._angleMode===f.RADIANS?a:e.radiansToDegrees(a):a},d.Vector.prototype.rotate=function(a){var b=this.heading()+a;this.p5&&this.p5._angleMode===f.DEGREES&&(b=e.degreesToRadians(b));var c=this.mag();return this.x=Math.cos(b)*c,this.y=Math.sin(b)*c,this},d.Vector.prototype.angleBetween=function(a){var b=Math.acos(this.dot(a)/(this.mag()*a.mag()));return this.p5&&this.p5._angleMode===f.DEGREES&&(b=e.radiansToDegrees(b)),b},d.Vector.prototype.lerp=function(a,b,c,e){return a instanceof d.Vector?this.lerp(a.x,a.y,a.z,b):(this.x+=(a-this.x)*e||0,this.y+=(b-this.y)*e||0,this.z+=(c-this.z)*e||0,this)},d.Vector.prototype.array=function(){return[this.x||0,this.y||0,this.z||0]},d.Vector.prototype.equals=function(a,b,c){var e,f,g;return a instanceof d.Vector?(e=a.x||0,f=a.y||0,g=a.z||0):a instanceof Array?(e=a[0]||0,f=a[1]||0,g=a[2]||0):(e=a||0,f=b||0,g=c||0),this.x===e&&this.y===f&&this.z===g},d.Vector.fromAngle=function(a){return this.p5&&this.p5._angleMode===f.DEGREES&&(a=e.degreesToRadians(a)),this.p5?new d.Vector(this.p5,[Math.cos(a),Math.sin(a),0]):new d.Vector(Math.cos(a),Math.sin(a),0)},d.Vector.random2D=function(){var a;return a=this.p5?this.p5._angleMode===f.DEGREES?this.p5.random(360):this.p5.random(f.TWO_PI):Math.random()*Math.PI*2,this.fromAngle(a)},d.Vector.random3D=function(){var a,b;this.p5?(a=this.p5.random(0,f.TWO_PI),b=this.p5.random(-1,1)):(a=Math.random()*Math.PI*2,b=2*Math.random()-1);var c=Math.sqrt(1-b*b)*Math.cos(a),e=Math.sqrt(1-b*b)*Math.sin(a);return this.p5?new d.Vector(this.p5,[c,e,b]):new d.Vector(c,e,b)},d.Vector.add=function(a,b,c){return c?c.set(a):c=a.copy(),c.add(b),c},d.Vector.sub=function(a,b,c){return c?c.set(a):c=a.copy(),c.sub(b),c},d.Vector.mult=function(a,b,c){return c?c.set(a):c=a.copy(),c.mult(b),c},d.Vector.div=function(a,b,c){return c?c.set(a):c=a.copy(),c.div(b),c},d.Vector.dot=function(a,b){return a.dot(b)},d.Vector.cross=function(a,b){return a.cross(b)},d.Vector.dist=function(a,b){return a.dist(b)},d.Vector.lerp=function(a,b,c,d){return d?d.set(a):d=a.copy(),d.lerp(b,c),d},d.Vector.mag=function(a){var b=a.x,c=a.y,d=a.z,e=b*b+c*c+d*d;return Math.sqrt(e)},b.exports=d.Vector},{"../core/constants":41,"../core/core":42,"./polargeometry":72}],72:[function(a,b,c){b.exports={degreesToRadians:function(a){return 2*Math.PI*a/360},radiansToDegrees:function(a){return 360*a/(2*Math.PI)}}},{}],73:[function(a,b,c){"use strict";var d=a("../core/core"),e=!1,f=!1,g=0,h=function(){var a,b,c=4294967296,d=1664525,e=1013904223;return{setSeed:function(d){b=a=(null==d?Math.random()*c:d)>>>0},getSeed:function(){return a},rand:function(){return(b=(d*b+e)%c)/c}}}();d.prototype.randomSeed=function(a){h.setSeed(a),e=!0,f=!1},d.prototype.random=function(a,b){var c;if(c=e?h.rand():Math.random(),void 0===a)return c;if(void 0===b)return a instanceof Array?a[Math.floor(c*a.length)]:c*a;if(a>b){var d=a;a=b,b=d}return c*(b-a)+a},d.prototype.randomGaussian=function(a,b){var c,d,e,h;if(f)c=g,f=!1;else{do{d=this.random(2)-1,e=this.random(2)-1,h=d*d+e*e}while(h>=1);h=Math.sqrt(-2*Math.log(h)/h),c=d*h,g=e*h,f=!0}var i=a||0;return c*(b||1)+i},b.exports=d},{"../core/core":42}],74:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("./polargeometry"),f=a("../core/constants");d.prototype._angleMode=f.RADIANS,d.prototype.acos=function(a){return this._angleMode===f.RADIANS?Math.acos(a):e.radiansToDegrees(Math.acos(a))},d.prototype.asin=function(a){return this._angleMode===f.RADIANS?Math.asin(a):e.radiansToDegrees(Math.asin(a))},d.prototype.atan=function(a){return this._angleMode===f.RADIANS?Math.atan(a):e.radiansToDegrees(Math.atan(a))},d.prototype.atan2=function(a,b){return this._angleMode===f.RADIANS?Math.atan2(a,b):e.radiansToDegrees(Math.atan2(a,b))},d.prototype.cos=function(a){return this._angleMode===f.RADIANS?Math.cos(a):Math.cos(this.radians(a))},d.prototype.sin=function(a){return this._angleMode===f.RADIANS?Math.sin(a):Math.sin(this.radians(a))},d.prototype.tan=function(a){return this._angleMode===f.RADIANS?Math.tan(a):Math.tan(this.radians(a))},d.prototype.degrees=function(a){return e.radiansToDegrees(a)},d.prototype.radians=function(a){return e.degreesToRadians(a)},d.prototype.angleMode=function(a){a!==f.DEGREES&&a!==f.RADIANS||(this._angleMode=a)},b.exports=d},{"../core/constants":41,"../core/core":42,"./polargeometry":72}],75:[function(a,b,c){"use strict";var d=a("../core/core");d.prototype.textAlign=function(a,b){return this._renderer.textAlign.apply(this._renderer,arguments)},d.prototype.textLeading=function(a){return this._renderer.textLeading.apply(this._renderer,arguments)},d.prototype.textSize=function(a){return this._renderer.textSize.apply(this._renderer,arguments)},d.prototype.textStyle=function(a){return this._renderer.textStyle.apply(this._renderer,arguments)},d.prototype.textWidth=function(a){return 0===a.length?0:this._renderer.textWidth.apply(this._renderer,arguments)},d.prototype.textAscent=function(){return this._renderer.textAscent()},d.prototype.textDescent=function(){return this._renderer.textDescent()},d.prototype._updateTextMetrics=function(){return this._renderer._updateTextMetrics()},b.exports=d},{"../core/core":42}],76:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("../core/constants");a("../core/error_helpers"),d.prototype.text=function(a,b,c,d,e){return this._renderer._doFill||this._renderer._doStroke?this._renderer.text.apply(this._renderer,arguments):this},d.prototype.textFont=function(a,b){if(arguments.length){if(!a)throw Error("null font passed to textFont");return this._renderer._setProperty("_textFont",a),b&&(this._renderer._setProperty("_textSize",b),this._renderer._setProperty("_textLeading",b*e._DEFAULT_LEADMULT)),this._renderer._applyTextProperties()}return this._renderer._textFont},b.exports=d},{"../core/constants":41,"../core/core":42,"../core/error_helpers":45}],77:[function(a,b,c){"use strict";function d(a,b){for(var c=h(b,{sampleFactor:.1,simplifyThreshold:0}),d=n(a,0,1),f=d/(d*c.sampleFactor),g=[],i=0;i3&&d>=0;--d)j(i(a,d-1),i(a,d),i(a,d+1),b)&&(a.splice(d%a.length,1),c++);return c}function f(a){for(var b,c=[],d=0;ds||rb&&!c)return h=m(d,e,f[1],f[2],f[3],f[4],f[5],f[6],b-k),{x:h.x,y:h.y,alpha:h.alpha};k+=g,d=+f[5],e=+f[6]}i+=f.shift()+f}return j.end=i,h=c?k:l(d,e,f[0],f[1],f[2],f[3],f[4],f[5],1),h.alpha&&(h={x:h.x,y:h.y,alpha:h.alpha}),h}function o(a){var b=[],c=0,d=0,e=0,f=0,g=0;"M"===a[0][0]&&(c=+a[0][1],d=+a[0][2],e=c,f=d,g++,b[0]=["M",c,d]);for(var h,i,j,k=3===a.length&&"M"===a[0][0]&&"R"===a[1][0].toUpperCase()&&"Z"===a[2][0].toUpperCase(),l=g,m=a.length;l7){a[b].shift();for(var e=a[b];e.length;)j[b]="A",d&&(k[b]="A"),a.splice(b++,0,["C"].concat(e.splice(0,6)));a.splice(b,1),p=Math.max(c.length,d&&d.length||0)}},i=function(a,b,e,f,g){a&&b&&"M"===a[g][0]&&"M"!==b[g][0]&&(b.splice(g,0,["M",f.x,f.y]),e.bx=0,e.by=0,e.x=a[g][1],e.y=a[g][2],p=Math.max(c.length,d&&d.length||0))},j=[],k=[],l="",m="",n=0,p=Math.max(c.length,d&&d.length||0);n1&&(x=Math.sqrt(x),c*=x,d*=x);var y=c*c,z=d*d,A=(f===g?-1:1)*Math.sqrt(Math.abs((y*z-y*w*w-z*v*v)/(y*w*w+z*v*v)));m=A*c*w/d+(a+h)/2,n=A*-d*v/c+(b+i)/2,k=Math.asin(((b-n)/d).toFixed(9)),l=Math.asin(((i-n)/d).toFixed(9)),k=al&&(k-=2*p),!g&&l>k&&(l-=2*p)}var B=l-k;if(Math.abs(B)>r){var C=l,D=h,E=i;l=k+r*(g&&l>k?1:-1),h=m+c*Math.cos(l),i=n+d*Math.sin(l),t=q(h,i,c,d,e,0,g,D,E,[l,C,m,n])}B=l-k;var F=Math.cos(k),G=Math.sin(k),H=Math.cos(l),I=Math.sin(l),J=Math.tan(B/4),K=4/3*c*J,L=4/3*d*J,M=[a,b],N=[a+K*G,b-L*F],O=[h+K*I,i-L*H],P=[h,i];if(N[0]=2*M[0]-N[0],N[1]=2*M[1]-N[1],j)return[N,O,P].concat(t);t=[N,O,P].concat(t).join().split(",");for(var Q=[],R=0,S=t.length;Rd;d+=2){var f=[{x:+a[d-2],y:+a[d-1]},{x:+a[d],y:+a[d+1]},{x:+a[d+2],y:+a[d+3]},{x:+a[d+4],y:+a[d+5]}];b?d?e-4===d?f[3]={x:+a[0],y:+a[1]}:e-2===d&&(f[2]={x:+a[0],y:+a[1]},f[3]={x:+a[2],y:+a[3]}):f[0]={x:+a[e-2],y:+a[e-1]}:e-4===d?f[3]=f[2]:d||(f[0]={x:+a[d],y:+a[d+1]}),c.push(["C",(-f[0].x+6*f[1].x+f[2].x)/6,(-f[0].y+6*f[1].y+f[2].y)/6,(f[1].x+6*f[2].x-f[3].x)/6,(f[1].y+6*f[2].y-f[3].y)/6,f[2].x,f[2].y])}return c}function s(a,b,c,d){return[a,b,c,d,c,d]}function t(a,b,c,d,e,f){var g=1/3,h=2/3;return[g*a+h*c,g*b+h*d,g*e+h*c,g*f+h*d,e,f]}function u(a,b,c,d,e,f,g,h,i){null==i&&(i=1),i=i>1?1:i<0?0:i;for(var j=i/2,k=12,l=[-.1252,.1252,-.3678,.3678,-.5873,.5873,-.7699,.7699,-.9041,.9041,-.9816,.9816],m=0,n=[.2491,.2491,.2335,.2335,.2032,.2032,.1601,.1601,.1069,.1069,.0472,.0472],o=0;on;)l/=2,m+=(j2?a=this._getPath(a,b,c,d):"object"==typeof b&&(d=b),d&&"number"==typeof d.decimals&&(e=d.decimals),a.toPathData(e)},y.Font.prototype._getSVG=function(a,b,c,d){var e=3;return"string"==typeof a&&arguments.length>2?a=this._getPath(a,b,c,d):"object"==typeof b&&(d=b),d&&("number"==typeof d.decimals&&(e=d.decimals),"number"==typeof d.strokeWidth&&(a.strokeWidth=d.strokeWidth),void 0!==d.fill&&(a.fill=d.fill),void 0!==d.stroke&&(a.stroke=d.stroke)),a.toSVG(e)},y.Font.prototype._renderPath=function(a,b,c,d){var e,f=d&&d.renderer||this.parent._renderer,g=f.drawingContext;e="object"==typeof a&&a.commands?a.commands:this._getPath(a,b,c,d).commands,g.beginPath();for(var h=0;h1;)d=Math.random()*f|0,e=a[--f],a[f]=a[d],a[d]=e;return a},d.prototype.sort=function(a,b){var c=b?a.slice(0,Math.min(b,a.length)):a,d=b?a.slice(Math.min(b,a.length)):[];return c="string"==typeof c[0]?c.sort():c.sort(function(a,b){return a-b}),c.concat(d)},d.prototype.splice=function(a,b,c){return Array.prototype.splice.apply(a,[c,0].concat(b)),a},d.prototype.subset=function(a,b,c){return void 0!==c?a.slice(b,b+c):a.slice(b,a.length)},b.exports=d},{"../core/core":42}],79:[function(a,b,c){"use strict";var d=a("../core/core");d.prototype.float=function(a){return a instanceof Array?a.map(parseFloat):parseFloat(a)},d.prototype.int=function(a,b){return b=b||10,"string"==typeof a?parseInt(a,b):"number"==typeof a?0|a:"boolean"==typeof a?a?1:0:a instanceof Array?a.map(function(a){return d.prototype.int(a,b)}):void 0},d.prototype.str=function(a){return a instanceof Array?a.map(d.prototype.str):String(a)},d.prototype.boolean=function(a){return"number"==typeof a?0!==a:"string"==typeof a?"true"===a.toLowerCase():"boolean"==typeof a?a:a instanceof Array?a.map(d.prototype.boolean):void 0},d.prototype.byte=function(a){var b=d.prototype.int(a,10);return"number"==typeof b?(b+128)%256-128:b instanceof Array?b.map(d.prototype.byte):void 0},d.prototype.char=function(a){return"number"!=typeof a||isNaN(a)?a instanceof Array?a.map(d.prototype.char):"string"==typeof a?d.prototype.char(parseInt(a,10)):void 0:String.fromCharCode(a)},d.prototype.unchar=function(a){return"string"==typeof a&&1===a.length?a.charCodeAt(0):a instanceof Array?a.map(d.prototype.unchar):void 0},d.prototype.hex=function(a,b){if(b=void 0===b||null===b?b=8:b,a instanceof Array)return a.map(function(a){return d.prototype.hex(a,b)});if("number"==typeof a){a<0&&(a=4294967295+a+1);for(var c=Number(a).toString(16).toUpperCase();c.length=b&&(c=c.substring(c.length-b,c.length)),c}},d.prototype.unhex=function(a){return a instanceof Array?a.map(d.prototype.unhex):parseInt("0x"+a,16)},b.exports=d},{"../core/core":42}],80:[function(a,b,c){"use strict";function d(){var a=arguments[0],b=a<0,c=b?a.toString().substring(1):a.toString(),d=c.indexOf("."),e=d!==-1?c.substring(0,d):c,f=d!==-1?c.substring(d+1):"",g=b?"-":"";if(3===arguments.length){var h="";(d!==-1||arguments[2]-f.length>0)&&(h="."),f.length>arguments[2]&&(f=f.substring(0,arguments[2]));for(var i=0;ic.length){c+=b===-1?".":"";for(var e=arguments[1]-c.length+1,f=0;f0?"+"+arguments[0].toString():arguments[0].toString()}function g(){return parseFloat(arguments[0])>0?" "+arguments[0].toString():arguments[0].toString()}var h=a("../core/core");h.prototype.join=function(a,b){return a.join(b)},h.prototype.match=function(a,b){return a.match(b)},h.prototype.matchAll=function(a,b){for(var c=new RegExp(b,"g"),d=c.exec(a),e=[];null!==d;)e.push(d),d=c.exec(a);return e},h.prototype.nf=function(){if(arguments[0]instanceof Array){var a=arguments[1],b=arguments[2];return arguments[0].map(function(c){return d(c,a,b)})}return"[object Arguments]"===Object.prototype.toString.call(arguments[0])?3===arguments[0].length?this.nf(arguments[0][0],arguments[0][1],arguments[0][2]):2===arguments[0].length?this.nf(arguments[0][0],arguments[0][1]):this.nf(arguments[0][0]):d.apply(this,arguments)},h.prototype.nfc=function(){if(arguments[0]instanceof Array){var a=arguments[1];return arguments[0].map(function(b){return e(b,a)})}return e.apply(this,arguments)},h.prototype.nfp=function(){var a=this.nf.apply(this,arguments);return a instanceof Array?a.map(f):f(a)},h.prototype.nfs=function(){var a=this.nf.apply(this,arguments);return a instanceof Array?a.map(g):g(a)},h.prototype.split=function(a,b){return a.split(b)},h.prototype.splitTokens=function(){var a,b,c,d;return d=arguments[1],arguments.length>1?(c=/\]/g.exec(d),b=/\[/g.exec(d),b&&c?(d=d.slice(0,c.index)+d.slice(c.index+1),b=/\[/g.exec(d),d=d.slice(0,b.index)+d.slice(b.index+1),a=new RegExp("[\\["+d+"\\]]","g")):c?(d=d.slice(0,c.index)+d.slice(c.index+1),a=new RegExp("["+d+"\\]]","g")):b?(d=d.slice(0,b.index)+d.slice(b.index+1),a=new RegExp("["+d+"\\[]","g")):a=new RegExp("["+d+"]","g")):a=/\s/g,arguments[0].split(a).filter(function(a){return a})},h.prototype.trim=function(a){return a instanceof Array?a.map(this.trim):a.trim()},b.exports=h},{"../core/core":42}],81:[function(a,b,c){"use strict";var d=a("../core/core");d.prototype.day=function(){return(new Date).getDate()},d.prototype.hour=function(){return(new Date).getHours()},d.prototype.minute=function(){return(new Date).getMinutes()},d.prototype.millis=function(){return window.performance.now()},d.prototype.month=function(){return(new Date).getMonth()+1},d.prototype.second=function(){return(new Date).getSeconds()},d.prototype.year=function(){return(new Date).getFullYear()},b.exports=d},{"../core/core":42}],82:[function(a,b,c){"use strict";var d=a("../core/core");d.prototype.camera=function(a,b,c){this._renderer.translate(-a,-b,-c)},d.prototype.perspective=function(a,b,c,e){a=a||60/180*this.PI,b=b||this.width/this.height,c=c||this.height/2/this.tan(a/2)*.1,e=e||this.height/2/this.tan(a/2)*10,this._renderer.uPMatrix=d.Matrix.identity(),this._renderer.uPMatrix.perspective(a,b,c,e),this._renderer._curCamera="custom"},d.prototype.ortho=function(a,b,c,e,f,g){a=a||-this.width/2,b=b||this.width/2,c=c||-this.height/2,e=e||this.height/2,f=f||0,g=g||Math.max(this.width,this.height),this._renderer.uPMatrix=d.Matrix.identity(),this._renderer.uPMatrix.ortho(a,b,c,e,f,g),this._renderer._curCamera="custom"},b.exports=d},{"../core/core":42}],83:[function(a,b,c){"use strict";var d=a("../core/core");d.prototype.orbitControl=function(){return this.mouseIsPressed&&(this.rotateY((this.mouseX-this.width/2)/(this.width/2)),this.rotateX((this.mouseY-this.height/2)/(this.width/2))),this},b.exports=d},{"../core/core":42}],84:[function(a,b,c){"use strict";var d=a("../core/core");d.prototype.ambientLight=function(a,b,c,d){var e=this._renderer.GL,f=this._renderer._getShader("lightVert","lightTextureFrag");e.useProgram(f),f.uAmbientColor=e.getUniformLocation(f,"uAmbientColor["+this._renderer.ambientLightCount+"]");var g=this._renderer._pInst.color.apply(this._renderer._pInst,arguments),h=g._array;return e.uniform3f(f.uAmbientColor,h[0],h[1],h[2]),f.uMaterialColor=e.getUniformLocation(f,"uMaterialColor"),e.uniform4f(f.uMaterialColor,1,1,1,1),this._renderer.ambientLightCount++,f.uAmbientLightCount=e.getUniformLocation(f,"uAmbientLightCount"),e.uniform1i(f.uAmbientLightCount,this._renderer.ambientLightCount),this},d.prototype.directionalLight=function(a,b,c,d,e,f,g){var h=this._renderer.GL,i=this._renderer._getShader("lightVert","lightTextureFrag");h.useProgram(i),i.uDirectionalColor=h.getUniformLocation(i,"uDirectionalColor["+this._renderer.directionalLightCount+"]");var j=this._renderer._pInst.color.apply(this._renderer._pInst,[a,b,c]),k=j._array;h.uniform3f(i.uDirectionalColor,k[0],k[1],k[2]);for(var l,m,n,o=new Array(arguments.length),p=0;p0)if("v"===g[0]||"vn"===g[0]){var h=new e.Vector(parseFloat(g[1]),parseFloat(g[2]),parseFloat(g[3]));c[g[0]].push(h)}else if("vt"===g[0]){var i=[parseFloat(g[1]),parseFloat(g[2])];c[g[0]].push(i)}else if("f"===g[0])for(var j=3;j0&&(this._renderer.geometryInHash(a.gid)||this._renderer.createBuffers(a.gid,a),this._renderer.drawBuffers(a.gid))},b.exports=e},{"../core/core":42,"./p5.Geometry":87}],86:[function(a,b,c){"use strict";var d=a("../core/core");d.prototype.normalMaterial=function(){return this._renderer._getShader("normalVert","normalFrag"),this},d.prototype.texture=function(){for(var a=new Array(arguments.length),b=0;bthis.vertices.length-1-this.detailX;b--)a.add(this.vertexNormals[b]);for(a=d.Vector.div(a,this.detailX),b=this.vertices.length-1;b>this.vertices.length-1-this.detailX;b--)this.vertexNormals[b]=a;return this},d.Geometry.prototype.normalize=function(){if(this.vertices.length>0){for(var a=this.vertices[0].copy(),b=this.vertices[0].copy(),c=0;c0?a.reduce(function(a,b){return a.concat(b)}):[]}function e(a){return d(a.map(function(a){return[a.x,a.y,a.z]}))}var f=a("../core/core"),g=0;f.RendererGL.prototype._initBufferDefaults=function(a){if(++g>1e3){var b=Object.keys(this.gHash)[0];delete this.gHash[b],g--}var c=this.GL;this.gHash[a]={},this.gHash[a].vertexBuffer=c.createBuffer(),this.gHash[a].normalBuffer=c.createBuffer(),this.gHash[a].uvBuffer=c.createBuffer(),this.gHash[a].indexBuffer=c.createBuffer()},f.RendererGL.prototype.createBuffers=function(a,b){var c=this.GL;this._setDefaultCamera(),this._initBufferDefaults(a);var f=this.mHash[this._getCurShaderId()];this.gHash[a].numberOfItems=3*b.faces.length,c.bindBuffer(c.ARRAY_BUFFER,this.gHash[a].vertexBuffer),c.bufferData(c.ARRAY_BUFFER,new Float32Array(e(b.vertices)),c.STATIC_DRAW),f.vertexPositionAttribute=c.getAttribLocation(f,"aPosition"),c.enableVertexAttribArray(f.vertexPositionAttribute),c.vertexAttribPointer(f.vertexPositionAttribute,3,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this.gHash[a].normalBuffer),c.bufferData(c.ARRAY_BUFFER,new Float32Array(e(b.vertexNormals)),c.STATIC_DRAW),f.vertexNormalAttribute=c.getAttribLocation(f,"aNormal"),c.enableVertexAttribArray(f.vertexNormalAttribute),c.vertexAttribPointer(f.vertexNormalAttribute,3,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this.gHash[a].uvBuffer),c.bufferData(c.ARRAY_BUFFER,new Float32Array(d(b.uvs)),c.STATIC_DRAW),f.textureCoordAttribute=c.getAttribLocation(f,"aTexCoord"),c.enableVertexAttribArray(f.textureCoordAttribute),c.vertexAttribPointer(f.textureCoordAttribute,2,c.FLOAT,!1,0,0),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this.gHash[a].indexBuffer),c.bufferData(c.ELEMENT_ARRAY_BUFFER,new Uint16Array(d(b.faces)),c.STATIC_DRAW)},f.RendererGL.prototype.drawBuffers=function(a){this._setDefaultCamera();var b=this.GL,c=this._getCurShaderId(),d=this.mHash[c];return b.bindBuffer(b.ARRAY_BUFFER,this.gHash[a].vertexBuffer),b.vertexAttribPointer(d.vertexPositionAttribute,3,b.FLOAT,!1,0,0),b.bindBuffer(b.ARRAY_BUFFER,this.gHash[a].normalBuffer),b.vertexAttribPointer(d.vertexNormalAttribute,3,b.FLOAT,!1,0,0),b.bindBuffer(b.ARRAY_BUFFER,this.gHash[a].uvBuffer),b.vertexAttribPointer(d.textureCoordAttribute,2,b.FLOAT,!1,0,0),b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,this.gHash[a].indexBuffer),this._setMatrixUniforms(c),b.drawElements(b.TRIANGLES,this.gHash[a].numberOfItems,b.UNSIGNED_SHORT,0),this},b.exports=f.RendererGL},{"../core/core":42}],91:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("./shader");a("../core/p5.Renderer"),a("./p5.Matrix");var f=[],g={alpha:!0,depth:!0,stencil:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1};d.RendererGL=function(a,b,c){return d.Renderer.call(this,a,b,c),this._initContext(),this.isP3D=!0,this.GL=this.drawingContext,this.ambientLightCount=0,this.directionalLightCount=0,this.pointLightCount=0,this._curCamera=null,this.uMVMatrix=new d.Matrix,this.uPMatrix=new d.Matrix,this.uNMatrix=new d.Matrix("mat3"),this.gHash={},this.mHash={},this.isImmediateDrawing=!1,this.immediateMode={},this.curFillColor=[.5,.5,.5,1],this.curStrokeColor=[.5,.5,.5,1],this.pointSize=5,this},d.RendererGL.prototype=Object.create(d.Renderer.prototype),d.RendererGL.prototype._initContext=function(){try{if(this.drawingContext=this.canvas.getContext("webgl",g)||this.canvas.getContext("experimental-webgl",g),null===this.drawingContext)throw new Error("Error creating webgl context");console.log("p5.RendererGL: enabled webgl context");var a=this.drawingContext;a.enable(a.DEPTH_TEST),a.depthFunc(a.LEQUAL),a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight)}catch(a){throw new Error(a)}},d.RendererGL.prototype._setDefaultCamera=function(){if(null===this._curCamera){var a=this.width,b=this.height;this.uPMatrix=d.Matrix.identity();var c=this.height/2/Math.tan(30*Math.PI/180);this.uPMatrix.perspective(60/180*Math.PI,a/b,.1*c,10*c),this._curCamera="default"}},d.RendererGL.prototype._update=function(){this.uMVMatrix=d.Matrix.identity(),this.translate(0,0,-(this.height/2)/Math.tan(30*Math.PI/180)),this.ambientLightCount=0,this.directionalLightCount=0,this.pointLightCount=0},d.RendererGL.prototype.background=function(){var a=this.GL,b=this._pInst.color.apply(this._pInst,arguments),c=b.levels[0]/255,d=b.levels[1]/255,e=b.levels[2]/255,f=b.levels[3]/255;a.clearColor(c,d,e,f),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT)},d.RendererGL.prototype._initShaders=function(a,b,c){var d=this.GL,f=d.createShader(d.VERTEX_SHADER);if(d.shaderSource(f,e[a]),d.compileShader(f),!d.getShaderParameter(f,d.COMPILE_STATUS))return alert("Yikes! An error occurred compiling the shaders:"+d.getShaderInfoLog(f)),null;var g=d.createShader(d.FRAGMENT_SHADER);if(d.shaderSource(g,e[b]),d.compileShader(g),!d.getShaderParameter(g,d.COMPILE_STATUS))return alert("Darn! An error occurred compiling the shaders:"+d.getShaderInfoLog(g)),null;var h=d.createProgram();return d.attachShader(h,f),d.attachShader(h,g),d.linkProgram(h),d.getProgramParameter(h,d.LINK_STATUS)||alert("Snap! Error linking shader program"),this._getLocation(h,c),h},d.RendererGL.prototype._getLocation=function(a,b){var c=this.GL;c.useProgram(a),a.uPMatrixUniform=c.getUniformLocation(a,"uProjectionMatrix"),a.uMVMatrixUniform=c.getUniformLocation(a,"uModelViewMatrix"),void 0===b&&(a.uNMatrixUniform=c.getUniformLocation(a,"uNormalMatrix"),a.samplerUniform=c.getUniformLocation(a,"uSampler"))},d.RendererGL.prototype._setUniform1f=function(a,b,c){var d=this.GL,e=this.mHash[a];return d.useProgram(e),e[b]=d.getUniformLocation(e,b),d.uniform1f(e[b],c),this},d.RendererGL.prototype._setMatrixUniforms=function(a){var b=this.GL,c=this.mHash[a];b.useProgram(c),b.uniformMatrix4fv(c.uPMatrixUniform,!1,this.uPMatrix.mat4),b.uniformMatrix4fv(c.uMVMatrixUniform,!1,this.uMVMatrix.mat4),this.uNMatrix.inverseTranspose(this.uMVMatrix),b.uniformMatrix3fv(c.uNMatrixUniform,!1,this.uNMatrix.mat3)},d.RendererGL.prototype._getShader=function(a,b,c){var d=a+"|"+b;if(!this.materialInHash(d)){var e=this._initShaders(a,b,c);this.mHash[d]=e}return this.curShaderId=d,this.mHash[this.curShaderId]},d.RendererGL.prototype._getCurShaderId=function(){var a,b;return"fill"!==this.drawMode&&void 0===this.curShaderId?(a="normalVert|normalFrag",b=this._initShaders("normalVert","normalFrag"),this.mHash[a]=b,this.curShaderId=a):this.isImmediateDrawing&&"fill"===this.drawMode&&(a="immediateVert|vertexColorFrag",b=this._initShaders("immediateVert","vertexColorFrag"),this.mHash[a]=b,this.curShaderId=a),this.curShaderId},d.RendererGL.prototype.fill=function(a,b,c,d){var e,f=this.GL,g=this._applyColorBlend.apply(this,arguments);return this.curFillColor=g,this.drawMode="fill",this.isImmediateDrawing?(e=this._getShader("immediateVert","vertexColorFrag"),f.useProgram(e)):(e=this._getShader("normalVert","basicFrag"),f.useProgram(e),e.uMaterialColor=f.getUniformLocation(e,"uMaterialColor"),f.uniform4f(e.uMaterialColor,g[0],g[1],g[2],g[3])),this},d.RendererGL.prototype.stroke=function(a,b,c,d){var e=this._pInst.color.apply(this._pInst,arguments),f=e._array;return this.curStrokeColor=f,this.drawMode="stroke",this},d.RendererGL.prototype._strokeCheck=function(){if("stroke"===this.drawMode)throw new Error("stroke for shapes in 3D not yet implemented, use fill for now :(")},d.RendererGL.prototype.strokeWeight=function(a){return this.pointSize=a,this},d.RendererGL.prototype.geometryInHash=function(a){return void 0!==this.gHash[a]},d.RendererGL.prototype.materialInHash=function(a){return void 0!==this.mHash[a]},d.RendererGL.prototype.resize=function(a,b){var c=this.GL;d.Renderer.prototype.resize.call(this,a,b),c.viewport(0,0,c.drawingBufferWidth,c.drawingBufferHeight),"default"===this._curCamera&&(this._curCamera=null,this._setDefaultCamera())},d.RendererGL.prototype.clear=function(){var a=this.GL;a.clearColor(arguments[0],arguments[1],arguments[2],arguments[3]),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT)},d.RendererGL.prototype.translate=function(a,b,c){return this.uMVMatrix.translate([a,-b,c]),this},d.RendererGL.prototype.scale=function(a,b,c){return this.uMVMatrix.scale([a,b,c]),this},d.RendererGL.prototype.rotate=function(a,b){return this.uMVMatrix.rotate(a,b),this},d.RendererGL.prototype.rotateX=function(a){return this.rotate(a,[1,0,0]),this},d.RendererGL.prototype.rotateY=function(a){return this.rotate(a,[0,1,0]),this},d.RendererGL.prototype.rotateZ=function(a){return this.rotate(a,[0,0,1]),this},d.RendererGL.prototype.push=function(){f.push(this.uMVMatrix.copy())},d.RendererGL.prototype.pop=function(){if(0===f.length)throw new Error("Invalid popMatrix!");this.uMVMatrix=f.pop()},d.RendererGL.prototype.resetMatrix=function(){return this.uMVMatrix=d.Matrix.identity(),this.translate(0,0,-800),this},d.RendererGL.prototype._applyTextProperties=function(){console.error("text commands not yet implemented in webgl")},b.exports=d.RendererGL},{"../core/core":42,"../core/p5.Renderer":48,"./p5.Matrix":88,"./shader":93}],92:[function(a,b,c){"use strict";var d=a("../core/core");a("./p5.Geometry"),d.prototype.plane=function(){for(var a=new Array(arguments.length),b=0;bf?(r=c,q=1,p=b):p=a+i/f*(b-a),i!==-2&&i!==f+2||(p=0,q=0),r-=c/2,j=0;jf?0:Math.sin(j*Math.PI*2/e)*Math.cos(m),i<0?-1:i>f?1:Math.sin(m),i<0||i>f?0:Math.cos(j*Math.PI*2/e)*Math.cos(m))),this.uvs.push([j/e,q])}for(i=0;i-1))throw arguments[t]+" is not a valid sound format!";e.extensions.push(arguments[t])}},t.prototype.disposeSound=function(){for(var t=0;t-1)if(t.prototype.isFileSupported(o))n=n;else for(var r=n.split("."),s=r[r.length-1],a=0;a1?(this.splitter=i.createChannelSplitter(2),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0)):(this.input.connect(this.left),this.input.connect(this.right)),this.output=i.createChannelMerger(2),this.left.connect(this.output,0,1),this.right.connect(this.output,0,0),this.output.connect(e)},t.Panner.prototype.pan=function(t,e){var n=e||0,o=i.currentTime+n,r=(t+1)/2,s=Math.cos(r*Math.PI/2),a=Math.sin(r*Math.PI/2);this.left.gain.linearRampToValueAtTime(a,o),this.right.gain.linearRampToValueAtTime(s,o)},t.Panner.prototype.inputChannels=function(t){1===t?(this.input.disconnect(),this.input.connect(this.left),this.input.connect(this.right)):2===t&&(this.splitter=i.createChannelSplitter(2),this.input.disconnect(),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0))},t.Panner.prototype.connect=function(t){this.output.connect(t)},t.Panner.prototype.disconnect=function(){this.output&&this.output.disconnect()})}(n);var a;a=function(){function e(t,e){for(var i={},n=t.length,o=0;n>o;o++){if(t[o]>e){var r=t[o],s=new d(r,o);i[o]=s,o+=6e3}o++}return i}function i(t){for(var e=[],i=Object.keys(t).sort(),n=0;no;o++){var r=t[i[n]],s=t[i[n+o]];if(r&&s){var a=r.sampleIndex,u=s.sampleIndex,c=u-a;c>0&&r.intervals.push(c);var p=e.some(function(t){return t.interval===c?(t.count++,t):void 0});p||e.push({interval:c,count:1})}}return e}function s(t,e){var i=[];return t.forEach(function(t){try{var n=Math.abs(60/(t.interval/e));n=u(n);var o=i.some(function(e){return e.tempo===n?e.count+=t.count:void 0});if(!o){if(isNaN(n))return;i.push({tempo:Math.round(n),count:t.count})}}catch(r){throw r}}),i}function a(t,e,i,n){for(var o=[],r=Object.keys(t).sort(),s=0;s.01?!0:void 0})}function u(t){if(isFinite(t)&&0!==t){for(;90>t;)t*=2;for(;t>180&&t>90;)t/=2;return t}}var c=r,p=n,h=p.audiocontext,l=o.midiToFreq;t.SoundFile=function(e,i,n,o){if("undefined"!=typeof e){if("string"==typeof e||"string"==typeof e[0]){var r=t.prototype._checkFileFormats(e);this.url=r}else if("object"==typeof e&&!(window.File&&window.FileReader&&window.FileList&&window.Blob))throw"Unable to load file because the File API is not supported";e.file&&(e=e.file),this.file=e}this._onended=function(){},this._looping=!1,this._playing=!1,this._paused=!1,this._pauseTime=0,this._cues=[],this._lastPos=0,this._counterNode=null,this._scopeNode=null,this.bufferSourceNodes=[],this.bufferSourceNode=null,this.buffer=null,this.playbackRate=1,this.input=p.audiocontext.createGain(),this.output=p.audiocontext.createGain(),this.reversed=!1,this.startTime=0,this.endTime=null,this.pauseTime=0,this.mode="sustain",this.startMillis=null,this.panPosition=0,this.panner=new t.Panner(this.output,p.input,2),(this.url||this.file)&&this.load(i,n),p.soundArray.push(this),"function"==typeof o?this._whileLoading=o:this._whileLoading=function(){}},t.prototype.registerPreloadMethod("loadSound",t.prototype),t.prototype.loadSound=function(e,i,n,o){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&window.alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var r=this,s=new t.SoundFile(e,function(){"function"==typeof i&&i.apply(r,arguments),"function"==typeof r._decrementPreload&&r._decrementPreload()},n,o);return s},t.SoundFile.prototype.load=function(t,e){var i=this,n=(new Error).stack;if(void 0!==this.url&&""!==this.url){var o=new XMLHttpRequest;o.addEventListener("progress",function(t){i._updateProgress(t)},!1),o.open("GET",this.url,!0),o.responseType="arraybuffer",o.onload=function(){if(200===o.status)h.decodeAudioData(o.response,function(e){i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i)},function(){var t=new c("decodeAudioData",n,i.url),o="AudioContext error at decodeAudioData for "+i.url;e?(t.msg=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)});else{var r=new c("loadSound",n,i.url),s="Unable to load "+i.url+". The request status was: "+o.status+" ("+o.statusText+")";e?(r.message=s,e(r)):console.error(s+"\n The error stack trace includes: \n"+r.stack)}},o.onerror=function(){var t=new c("loadSound",n,i.url),o="There was no response from the server at "+i.url+". Check the url and internet connectivity.";e?(t.message=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)},o.send()}else if(void 0!==this.file){var r=new FileReader;r.onload=function(){h.decodeAudioData(r.result,function(e){i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i)})},r.onerror=function(t){onerror&&onerror(t)},r.readAsArrayBuffer(this.file)}},t.SoundFile.prototype._updateProgress=function(t){if(t.lengthComputable){var e=t.loaded/t.total*.99;this._whileLoading(e,t)}else this._whileLoading("size unknown")},t.SoundFile.prototype.isLoaded=function(){return this.buffer?!0:!1},t.SoundFile.prototype.play=function(t,e,i,n,o){if(!this.output)return void console.warn("SoundFile.play() called after dispose");var r,s,a=this,u=p.audiocontext.currentTime,c=t||0;if(0>c&&(c=0),c+=u,"undefined"!=typeof e&&this.rate(e),"undefined"!=typeof i&&this.setVolume(i),!this.buffer)throw"not ready to play file, buffer has yet to load. Try preload()";if(this._pauseTime=0,"restart"===this.mode&&this.buffer&&this.bufferSourceNode&&(this.bufferSourceNode.stop(c),this._counterNode.stop(c)),"untildone"!==this.mode||!this.isPlaying()){if(this.bufferSourceNode=this._initSourceNode(),delete this._counterNode,this._counterNode=this._initCounterNode(),n){if(!(n>=0&&nt&&!this.reversed?(t=Math.abs(t),e=!0):t>0&&this.reversed&&(e=!0),this.bufferSourceNode){var i=p.audiocontext.currentTime;this.bufferSourceNode.playbackRate.cancelScheduledValues(i),this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i),this._counterNode.playbackRate.cancelScheduledValues(i),this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i)}return e&&this.reverseBuffer(),this.playbackRate},t.SoundFile.prototype.setPitch=function(t){var e=l(t)/l(60);this.rate(e)},t.SoundFile.prototype.getPlaybackRate=function(){return this.playbackRate},t.SoundFile.prototype.duration=function(){return this.buffer?this.buffer.duration:0},t.SoundFile.prototype.currentTime=function(){return this.reversed?Math.abs(this._lastPos-this.buffer.length)/h.sampleRate:this._lastPos/h.sampleRate},t.SoundFile.prototype.jump=function(t,e){if(0>t||t>this.buffer.duration)throw"jump time out of range";if(e>this.buffer.duration-t)throw"end time out of range";var i=t||0,n=e||void 0;this.isPlaying()&&this.stop(0),this.play(0,this.playbackRate,this.output.gain.value,i,n)},t.SoundFile.prototype.channels=function(){return this.buffer.numberOfChannels},t.SoundFile.prototype.sampleRate=function(){return this.buffer.sampleRate},t.SoundFile.prototype.frames=function(){return this.buffer.length},t.SoundFile.prototype.getPeaks=function(t){if(!this.buffer)throw"Cannot load peaks yet, buffer is not loaded";if(t||(t=5*window.width),this.buffer){for(var e=this.buffer,i=e.length/t,n=~~(i/10)||1,o=e.numberOfChannels,r=new Float32Array(Math.round(t)),s=0;o>s;s++)for(var a=e.getChannelData(s),u=0;t>u;u++){for(var c=~~(u*i),p=~~(c+i),h=0,l=c;p>l;l+=n){var f=a[l];f>h?h=f:-f>h&&(h=f)}(0===s||Math.abs(h)>r[u])&&(r[u]=h)}return r}},t.SoundFile.prototype.reverseBuffer=function(){if(!this.buffer)throw"SoundFile is not done loading";var t=this._lastPos/h.sampleRate,e=this.getVolume();this.setVolume(0,.001);const i=this.buffer.numberOfChannels;for(var n=0;i>n;n++)this.buffer.getChannelData(n).reverse();this.reversed=!this.reversed,t&&this.jump(this.duration()-t),this.setVolume(e,.001)},t.SoundFile.prototype.onended=function(t){return this._onended=t,this},t.SoundFile.prototype.add=function(){},t.SoundFile.prototype.dispose=function(){var t=p.audiocontext.currentTime,e=p.soundArray.indexOf(this);if(p.soundArray.splice(e,1),this.stop(t),this.buffer&&this.bufferSourceNode){for(var i=0;io;o++){var r=n.getChannelData(o);r.set(t[o])}this.buffer=n,this.panner.inputChannels(e)};var f=function(t){const e=t.length,i=h.createBuffer(1,t.length,h.sampleRate),n=i.getChannelData(0);for(var o=0;e>o;o++)n[o]=o;return i};t.SoundFile.prototype._initCounterNode=function(){var e=this,i=h.currentTime,n=h.createBufferSource();return e._scopeNode&&(e._scopeNode.disconnect(),delete e._scopeNode.onaudioprocess,delete e._scopeNode),e._scopeNode=h.createScriptProcessor(256,1,1),n.buffer=f(e.buffer),n.playbackRate.setValueAtTime(e.playbackRate,i),n.connect(e._scopeNode),e._scopeNode.connect(t.soundOut._silentNode),e._scopeNode.onaudioprocess=function(t){var i=t.inputBuffer.getChannelData(0);e._lastPos=i[i.length-1]||0,e._onTimeUpdate(e._lastPos)},n},t.SoundFile.prototype._initSourceNode=function(){var t=h.createBufferSource();return t.buffer=this.buffer,t.playbackRate.value=this.playbackRate,t.connect(this.output),t},t.SoundFile.prototype.processPeaks=function(t,n,o,r){var u=this.buffer.length,c=this.buffer.sampleRate,p=this.buffer,h=[],l=n||.9,f=l,d=o||.22,m=r||200,y=new window.OfflineAudioContext(1,u,c),v=y.createBufferSource();v.buffer=p;var g=y.createBiquadFilter();g.type="lowpass",v.connect(g),g.connect(y.destination),v.start(0),y.startRendering(),y.oncomplete=function(n){var o=n.renderedBuffer,r=o.getChannelData(0);do h=e(r,f),f-=.005;while(Object.keys(h).length=d);var u=i(h),c=s(u,o.sampleRate),p=c.sort(function(t,e){return e.count-t.count}).splice(0,5);this.tempo=p[0].tempo;var l=5,y=a(h,p[0].tempo,o.sampleRate,l);t(y)}};var d=function(t,e){this.sampleIndex=e,this.amplitude=t,this.tempos=[],this.intervals=[]},m=function(t,e,i,n){this.callback=t,this.time=e,this.id=i,this.val=n};t.SoundFile.prototype.addCue=function(t,e,i){var n=this._cueIDCounter++,o=new m(e,t,n,i);return this._cues.push(o),n},t.SoundFile.prototype.removeCue=function(t){for(var e=this._cues.length,i=0;e>i;i++){var n=this._cues[i];n.id===t&&this.cues.splice(i,1)}0===this._cues.length},t.SoundFile.prototype.clearCues=function(){this._cues=[]},t.SoundFile.prototype._onTimeUpdate=function(t){for(var e=t/this.buffer.sampleRate,i=this._cues.length,n=0;i>n;n++){var o=this._cues[n],r=o.time,s=o.val;this._prevTime=r&&o.callback(s)}this._prevTime=e}}(r,n,o);var u;u=function(){var e=n;t.Amplitude=function(t){this.bufferSize=2048,this.audiocontext=e.audiocontext,this.processor=this.audiocontext.createScriptProcessor(this.bufferSize,2,1),this.input=this.processor,this.output=this.audiocontext.createGain(),this.smoothing=t||0,this.volume=0,this.average=0,this.stereoVol=[0,0],this.stereoAvg=[0,0],this.stereoVolNorm=[0,0],this.volMax=.001,this.normalize=!1,this.processor.onaudioprocess=this._audioProcess.bind(this),this.processor.connect(this.output),this.output.gain.value=0,this.output.connect(this.audiocontext.destination),e.meter.connect(this.processor),e.soundArray.push(this)},t.Amplitude.prototype.setInput=function(i,n){e.meter.disconnect(),n&&(this.smoothing=n),null==i?(console.log("Amplitude input source is not ready! Connecting to master output instead"),e.meter.connect(this.processor)):i instanceof t.Signal?i.output.connect(this.processor):i?(i.connect(this.processor),this.processor.disconnect(),this.processor.connect(this.output)):e.meter.connect(this.processor)},t.Amplitude.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):this.output.connect(t):this.output.connect(this.panner.connect(e.input))},t.Amplitude.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Amplitude.prototype._audioProcess=function(t){for(var e=0;ea;a++)i=n[a],this.normalize?(r+=Math.max(Math.min(i/this.volMax,1),-1),s+=Math.max(Math.min(i/this.volMax,1),-1)*Math.max(Math.min(i/this.volMax,1),-1)):(r+=i,s+=i*i);var u=r/o,c=Math.sqrt(s/o);this.stereoVol[e]=Math.max(c,this.stereoVol[e]*this.smoothing),this.stereoAvg[e]=Math.max(u,this.stereoVol[e]*this.smoothing),this.volMax=Math.max(this.stereoVol[e],this.volMax)}var p=this,h=this.stereoVol.reduce(function(t,e,i){return p.stereoVolNorm[i-1]=Math.max(Math.min(p.stereoVol[i-1]/p.volMax,1),0),p.stereoVolNorm[i]=Math.max(Math.min(p.stereoVol[i]/p.volMax,1),0),t+e});this.volume=h/this.stereoVol.length,this.volNorm=Math.max(Math.min(this.volume/this.volMax,1),0)},t.Amplitude.prototype.getLevel=function(t){return"undefined"!=typeof t?this.normalize?this.stereoVolNorm[t]:this.stereoVol[t]:this.normalize?this.volNorm:this.volume},t.Amplitude.prototype.toggleNormalize=function(t){"boolean"==typeof t?this.normalize=t:this.normalize=!this.normalize},t.Amplitude.prototype.smooth=function(t){t>=0&&1>t?this.smoothing=t:console.log("Error: smoothing must be between 0 and 1")},t.Amplitude.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.input&&(this.input.disconnect(),delete this.input),this.output&&(this.output.disconnect(),delete this.output),delete this.processor}}(n);var c;c=function(){var e=n;t.FFT=function(t,i){this.input=this.analyser=e.audiocontext.createAnalyser(),Object.defineProperties(this,{bins:{get:function(){return this.analyser.fftSize/2},set:function(t){this.analyser.fftSize=2*t},configurable:!0,enumerable:!0},smoothing:{get:function(){return this.analyser.smoothingTimeConstant},set:function(t){this.analyser.smoothingTimeConstant=t},configurable:!0,enumerable:!0}}),this.smooth(t),this.bins=i||1024,e.fftMeter.connect(this.analyser),this.freqDomain=new Uint8Array(this.analyser.frequencyBinCount),this.timeDomain=new Uint8Array(this.analyser.frequencyBinCount),this.bass=[20,140],this.lowMid=[140,400],this.mid=[400,2600],this.highMid=[2600,5200],this.treble=[5200,14e3],e.soundArray.push(this)},t.FFT.prototype.setInput=function(t){t?(t.output?t.output.connect(this.analyser):t.connect&&t.connect(this.analyser),e.fftMeter.disconnect()):e.fftMeter.connect(this.analyser)},t.FFT.prototype.waveform=function(){for(var e,i,n,o=0;oi){var o=i;i=t,t=o}for(var r=Math.round(t/n*this.freqDomain.length),s=Math.round(i/n*this.freqDomain.length),a=0,u=0,c=r;s>=c;c++)a+=this.freqDomain[c],u+=1;var p=a/u;return p}throw"invalid input for getEnergy()"}var h=Math.round(t/n*this.freqDomain.length);return this.freqDomain[h]},t.FFT.prototype.getFreq=function(t,e){console.log("getFreq() is deprecated. Please use getEnergy() instead.");var i=this.getEnergy(t,e);return i},t.FFT.prototype.getCentroid=function(){for(var t=e.audiocontext.sampleRate/2,i=0,n=0,o=0;os;s++)o[r]=void 0!==o[r]?(o[r]+e[s])/2:e[s],s%n===n-1&&r++;return o},t.FFT.prototype.logAverages=function(t){for(var i=e.audiocontext.sampleRate/2,n=this.freqDomain,o=n.length,r=new Array(t.length),s=0,a=0;o>a;a++){var u=Math.round(a*i/this.freqDomain.length);u>t[s].hi&&s++,r[s]=void 0!==r[s]?(r[s]+n[a])/2:n[a]}return r},t.FFT.prototype.getOctaveBands=function(t,i){var t=t||3,i=i||15.625,n=[],o={lo:i/Math.pow(2,1/(2*t)),ctr:i,hi:i*Math.pow(2,1/(2*t))};n.push(o);for(var r=e.audiocontext.sampleRate/2;o.hi1&&(this.input=new Array(t)),this.isUndef(e)||1===e?this.output=this.context.createGain():e>1&&(this.output=new Array(t))};t.prototype.set=function(e,i,n){if(this.isObject(e))n=i;else if(this.isString(e)){var o={};o[e]=i,e=o}t:for(var r in e){i=e[r];var s=this;if(-1!==r.indexOf(".")){for(var a=r.split("."),u=0;u1)for(var t=arguments[0],e=1;e0)for(var t=this,e=0;e0)for(var t=0;te;e++){var n=e/(i-1)*2-1;this._curve[e]=t(n,e)}return this._shaper.curve=this._curve,this},Object.defineProperty(t.WaveShaper.prototype,"curve",{get:function(){return this._shaper.curve},set:function(t){this._curve=new Float32Array(t),this._shaper.curve=this._curve}}),Object.defineProperty(t.WaveShaper.prototype,"oversample",{get:function(){return this._shaper.oversample},set:function(t){if(-1===["none","2x","4x"].indexOf(t))throw new RangeError("Tone.WaveShaper: oversampling must be either 'none', '2x', or '4x'");this._shaper.oversample=t}}),t.WaveShaper.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.disconnect(),this._shaper=null,this._curve=null,this},t.WaveShaper}(p);var f;f=function(t){return t.TimeBase=function(e,i){if(!(this instanceof t.TimeBase))return new t.TimeBase(e,i);if(this._expr=this._noOp,e instanceof t.TimeBase)this.copy(e);else if(!this.isUndef(i)||this.isNumber(e)){i=this.defaultArg(i,this._defaultUnits);var n=this._primaryExpressions[i].method;this._expr=n.bind(this,e)}else this.isString(e)?this.set(e):this.isUndef(e)&&(this._expr=this._defaultExpr())},t.extend(t.TimeBase),t.TimeBase.prototype.set=function(t){return this._expr=this._parseExprString(t),this},t.TimeBase.prototype.clone=function(){var t=new this.constructor;return t.copy(this),t},t.TimeBase.prototype.copy=function(t){var e=t._expr();return this.set(e)},t.TimeBase.prototype._primaryExpressions={n:{regexp:/^(\d+)n/i,method:function(t){return t=parseInt(t),1===t?this._beatsToUnits(this._timeSignature()):this._beatsToUnits(4/t)}},t:{regexp:/^(\d+)t/i,method:function(t){return t=parseInt(t),this._beatsToUnits(8/(3*parseInt(t)))}},m:{regexp:/^(\d+)m/i,method:function(t){return this._beatsToUnits(parseInt(t)*this._timeSignature())}},i:{regexp:/^(\d+)i/i,method:function(t){return this._ticksToUnits(parseInt(t))}},hz:{regexp:/^(\d+(?:\.\d+)?)hz/i,method:function(t){return this._frequencyToUnits(parseFloat(t))}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=0;return t&&"0"!==t&&(n+=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n+=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n+=this._beatsToUnits(parseFloat(i)/4)),n}},s:{regexp:/^(\d+(?:\.\d+)?s)/,method:function(t){return this._secondsToUnits(parseFloat(t))}},samples:{regexp:/^(\d+)samples/,method:function(t){return parseInt(t)/this.context.sampleRate}},"default":{regexp:/^(\d+(?:\.\d+)?)/,method:function(t){return this._primaryExpressions[this._defaultUnits].method.call(this,t)}}},t.TimeBase.prototype._binaryExpressions={"+":{regexp:/^\+/,precedence:2,method:function(t,e){return t()+e()}},"-":{regexp:/^\-/,precedence:2,method:function(t,e){return t()-e()}},"*":{regexp:/^\*/,precedence:1,method:function(t,e){return t()*e()}},"/":{regexp:/^\//,precedence:1,method:function(t,e){return t()/e()}}},t.TimeBase.prototype._unaryExpressions={neg:{regexp:/^\-/,method:function(t){return-t()}}},t.TimeBase.prototype._syntaxGlue={"(":{regexp:/^\(/},")":{regexp:/^\)/}},t.TimeBase.prototype._tokenize=function(t){function e(t,e){for(var i=["_binaryExpressions","_unaryExpressions","_primaryExpressions","_syntaxGlue"],n=0;n0;){t=t.trim();var o=e(t,this);n.push(o),t=t.substr(o.value.length)}return{next:function(){return n[++i]},peek:function(){return n[i+1]}}},t.TimeBase.prototype._matchGroup=function(t,e,i){var n=!1;if(!this.isUndef(t))for(var o in e){var r=e[o];if(r.regexp.test(t.value)){if(this.isUndef(i))return r;if(r.precedence===i)return r}}return n},t.TimeBase.prototype._parseBinary=function(t,e){this.isUndef(e)&&(e=2);var i;i=0>e?this._parseUnary(t):this._parseBinary(t,e-1);for(var n=t.peek();n&&this._matchGroup(n,this._binaryExpressions,e);)n=t.next(),i=n.method.bind(this,i,this._parseBinary(t,e-1)),n=t.peek();return i},t.TimeBase.prototype._parseUnary=function(t){var e,i;e=t.peek();var n=this._matchGroup(e,this._unaryExpressions);return n?(e=t.next(),i=this._parseUnary(t),n.method.bind(this,i)):this._parsePrimary(t)},t.TimeBase.prototype._parsePrimary=function(t){var e,i;if(e=t.peek(),this.isUndef(e))throw new SyntaxError("Tone.TimeBase: Unexpected end of expression");if(this._matchGroup(e,this._primaryExpressions)){e=t.next();var n=e.value.match(e.regexp);return e.method.bind(this,n[1],n[2],n[3])}if(e&&"("===e.value){if(t.next(),i=this._parseBinary(t),e=t.next(),!e||")"!==e.value)throw new SyntaxError("Expected )");return i}throw new SyntaxError("Tone.TimeBase: Cannot process token "+e.value)},t.TimeBase.prototype._parseExprString=function(t){this.isString(t)||(t=t.toString());var e=this._tokenize(t),i=this._parseBinary(e);return i},t.TimeBase.prototype._noOp=function(){return 0},t.TimeBase.prototype._defaultExpr=function(){return this._noOp},t.TimeBase.prototype._defaultUnits="s",t.TimeBase.prototype._frequencyToUnits=function(t){return 1/t},t.TimeBase.prototype._beatsToUnits=function(e){return 60/t.Transport.bpm.value*e},t.TimeBase.prototype._secondsToUnits=function(t){return t},t.TimeBase.prototype._ticksToUnits=function(e){return e*(this._beatsToUnits(1)/t.Transport.PPQ)},t.TimeBase.prototype._timeSignature=function(){return t.Transport.timeSignature},t.TimeBase.prototype._pushExpr=function(e,i,n){return e instanceof t.TimeBase||(e=new this.constructor(e,n)),this._expr=this._binaryExpressions[i].method.bind(this,this._expr,e._expr),this},t.TimeBase.prototype.add=function(t,e){return this._pushExpr(t,"+",e)},t.TimeBase.prototype.sub=function(t,e){return this._pushExpr(t,"-",e)},t.TimeBase.prototype.mult=function(t,e){return this._pushExpr(t,"*",e)},t.TimeBase.prototype.div=function(t,e){return this._pushExpr(t,"/",e)},t.TimeBase.prototype.valueOf=function(){return this._expr()},t.TimeBase.prototype.dispose=function(){this._expr=null},t.TimeBase}(p);var d;d=function(t){return t.Time=function(e,i){return this instanceof t.Time?(this._plusNow=!1,void t.TimeBase.call(this,e,i)):new t.Time(e,i)},t.extend(t.Time,t.TimeBase),t.Time.prototype._unaryExpressions=Object.create(t.TimeBase.prototype._unaryExpressions),t.Time.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){return t.Transport.nextSubdivision(e())}},t.Time.prototype._unaryExpressions.now={regexp:/^\+/,method:function(t){return this._plusNow=!0,t()}},t.Time.prototype.quantize=function(t,e){return e=this.defaultArg(e,1),this._expr=function(t,e,i){t=t(),e=e.toSeconds();var n=Math.round(t/e),o=n*e,r=o-t;return t+r*i}.bind(this,this._expr,new this.constructor(t),e),this},t.Time.prototype.addNow=function(){return this._plusNow=!0,this},t.Time.prototype._defaultExpr=function(){return this._plusNow=!0,this._noOp},t.Time.prototype.copy=function(e){return t.TimeBase.prototype.copy.call(this,e),this._plusNow=e._plusNow,this},t.Time.prototype.toNotation=function(){var t=this.toSeconds(),e=["1m","2n","4n","8n","16n","32n","64n","128n"],i=this._toNotationHelper(t,e),n=["1m","2n","2t","4n","4t","8n","8t","16n","16t","32n","32t","64n","64t","128n"],o=this._toNotationHelper(t,n);return o.split("+").length1-s%1&&(s+=a),s=Math.floor(s),s>0){if(n+=1===s?e[o]:s.toString()+"*"+e[o],t-=s*r,i>t)break;n+=" + "}}return""===n&&(n="0"),n},t.Time.prototype._notationToUnits=function(t){for(var e=this._primaryExpressions,i=[e.n,e.t,e.m],n=0;n3&&(n=parseFloat(n).toFixed(3));var o=[i,e,n];return o.join(":")},t.Time.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Time.prototype.toSamples=function(){return this.toSeconds()*this.context.sampleRate},t.Time.prototype.toFrequency=function(){return 1/this.toSeconds()},t.Time.prototype.toSeconds=function(){return this.valueOf()},t.Time.prototype.toMilliseconds=function(){return 1e3*this.toSeconds()},t.Time.prototype.valueOf=function(){var t=this._expr();return t+(this._plusNow?this.now():0)},t.Time}(p);var m;m=function(t){t.Frequency=function(e,i){return this instanceof t.Frequency?void t.TimeBase.call(this,e,i):new t.Frequency(e,i)},t.extend(t.Frequency,t.TimeBase),t.Frequency.prototype._primaryExpressions=Object.create(t.TimeBase.prototype._primaryExpressions),t.Frequency.prototype._primaryExpressions.midi={regexp:/^(\d+(?:\.\d+)?midi)/,method:function(t){return this.midiToFrequency(t)}},t.Frequency.prototype._primaryExpressions.note={regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method:function(t,i){var n=e[t.toLowerCase()],o=n+12*(parseInt(i)+1);return this.midiToFrequency(o)}},t.Frequency.prototype._primaryExpressions.tr={regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=1;return t&&"0"!==t&&(n*=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n*=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n*=this._beatsToUnits(parseFloat(i)/4)),n}},t.Frequency.prototype.transpose=function(t){return this._expr=function(t,e){var i=t();return i*this.intervalToFrequencyRatio(e)}.bind(this,this._expr,t),this},t.Frequency.prototype.harmonize=function(t){return this._expr=function(t,e){for(var i=t(),n=[],o=0;or&&(o+=-12*r);var s=i[o%12];return s+r.toString()},t.Frequency.prototype.toSeconds=function(){return 1/this.valueOf()},t.Frequency.prototype.toFrequency=function(){return this.valueOf()},t.Frequency.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Frequency.prototype._frequencyToUnits=function(t){return t},t.Frequency.prototype._ticksToUnits=function(e){return 1/(60*e/(t.Transport.bpm.value*t.Transport.PPQ))},t.Frequency.prototype._beatsToUnits=function(e){return 1/t.TimeBase.prototype._beatsToUnits.call(this,e)},t.Frequency.prototype._secondsToUnits=function(t){return 1/t},t.Frequency.prototype._defaultUnits="hz";var e={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},i=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t.Frequency.A4=440,t.Frequency.prototype.midiToFrequency=function(e){return t.Frequency.A4*Math.pow(2,(e-69)/12)},t.Frequency.prototype.frequencyToMidi=function(e){return 69+12*Math.log(e/t.Frequency.A4)/Math.LN2},t.Frequency}(p);var y;y=function(t){return t.TransportTime=function(e,i){return this instanceof t.TransportTime?void t.Time.call(this,e,i):new t.TransportTime(e,i)},t.extend(t.TransportTime,t.Time),t.TransportTime.prototype._unaryExpressions=Object.create(t.Time.prototype._unaryExpressions),t.TransportTime.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){var i=this._secondsToTicks(e()),n=Math.ceil(t.Transport.ticks/i);return this._ticksToUnits(n*i)}},t.TransportTime.prototype._secondsToTicks=function(e){var i=this._beatsToUnits(1),n=e/i;return Math.round(n*t.Transport.PPQ)},t.TransportTime.prototype.valueOf=function(){var e=this._secondsToTicks(this._expr());return e+(this._plusNow?t.Transport.ticks:0)},t.TransportTime.prototype.toTicks=function(){return this.valueOf()},t.TransportTime.prototype.toSeconds=function(){var e=this._expr();return e+(this._plusNow?t.Transport.seconds:0)},t.TransportTime.prototype.toFrequency=function(){return 1/this.toSeconds()},t.TransportTime}(p);var v;v=function(t){"use strict";return t.Emitter=function(){this._events={}},t.extend(t.Emitter),t.Emitter.prototype.on=function(t,e){for(var i=t.split(/\W+/),n=0;nn;n++)i[n].apply(this,e)}return this},t.Emitter.mixin=function(e){var i=["on","off","emit"];e._events={};for(var n=0;n1&&(this.input=new Array(e)),1===i?this.output=new t.Gain:i>1&&(this.output=new Array(e))},t.Gain}(p,T);var x;x=function(t){"use strict";return t.Signal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this.output=this._gain=this.context.createGain(),e.param=this._gain.gain,t.Param.call(this,e),this.input=this._param=this._gain.gain,this.context.getConstant(1).chain(this._gain)},t.extend(t.Signal,t.Param),t.Signal.defaults={value:0,units:t.Type.Default,convert:!0},t.Signal.prototype.connect=t.SignalBase.prototype.connect,t.Signal.prototype.dispose=function(){return t.Param.prototype.dispose.call(this),this._param=null,this._gain.disconnect(),this._gain=null,this},t.Signal}(p,l,_,T);var S;S=function(t){"use strict";return t.Add=function(e){this.createInsOuts(2,0),this._sum=this.input[0]=this.input[1]=this.output=new t.Gain,this._param=this.input[1]=new t.Signal(e),this._param.connect(this._sum)},t.extend(t.Add,t.Signal),t.Add.prototype.dispose=function(){return t.prototype.dispose.call(this),this._sum.dispose(),this._sum=null,this._param.dispose(),this._param=null,this},t.Add}(p,x);var w;w=function(t){"use strict";return t.Multiply=function(e){this.createInsOuts(2,0),this._mult=this.input[0]=this.output=new t.Gain,this._param=this.input[1]=this.output.gain,this._param.value=this.defaultArg(e,0)},t.extend(t.Multiply,t.Signal),t.Multiply.prototype.dispose=function(){return t.prototype.dispose.call(this),this._mult.dispose(),this._mult=null,this._param=null,this},t.Multiply}(p,x);var A;A=function(t){"use strict";return t.Scale=function(e,i){this._outputMin=this.defaultArg(e,0),this._outputMax=this.defaultArg(i,1),this._scale=this.input=new t.Multiply(1),this._add=this.output=new t.Add(0),this._scale.connect(this._add),this._setRange()},t.extend(t.Scale,t.SignalBase),Object.defineProperty(t.Scale.prototype,"min",{get:function(){return this._outputMin},set:function(t){this._outputMin=t,this._setRange()}}),Object.defineProperty(t.Scale.prototype,"max",{get:function(){return this._outputMax},set:function(t){this._outputMax=t,this._setRange()}}),t.Scale.prototype._setRange=function(){this._add.value=this._outputMin,this._scale.value=this._outputMax-this._outputMin},t.Scale.prototype.dispose=function(){return t.prototype.dispose.call(this),this._add.dispose(),this._add=null,this._scale.dispose(),this._scale=null,this},t.Scale}(p,S,w);var P;P=function(){var e=x,i=S,o=w,r=A,s=p,a=n;s.setContext(a.audiocontext),t.Signal=function(t){var i=new e(t);return i},e.prototype.fade=e.prototype.linearRampToValueAtTime,o.prototype.fade=e.prototype.fade,i.prototype.fade=e.prototype.fade,r.prototype.fade=e.prototype.fade,e.prototype.setInput=function(t){t.connect(this)},o.prototype.setInput=e.prototype.setInput,i.prototype.setInput=e.prototype.setInput,r.prototype.setInput=e.prototype.setInput,e.prototype.add=function(t){var e=new i(t);return this.connect(e),e},o.prototype.add=e.prototype.add,i.prototype.add=e.prototype.add,r.prototype.add=e.prototype.add,e.prototype.mult=function(t){var e=new o(t);return this.connect(e),e},o.prototype.mult=e.prototype.mult,i.prototype.mult=e.prototype.mult,r.prototype.mult=e.prototype.mult,e.prototype.scale=function(e,i,n,o){var s,a;4===arguments.length?(s=t.prototype.map(n,e,i,0,1)-.5,a=t.prototype.map(o,e,i,0,1)-.5):(s=arguments[0],a=arguments[1]);var u=new r(s,a);return this.connect(u),u},o.prototype.scale=e.prototype.scale,i.prototype.scale=e.prototype.scale,r.prototype.scale=e.prototype.scale}(x,S,w,A,p,n);var k;k=function(){var e=n,i=S,o=w,r=A;t.Oscillator=function(i,n){if("string"==typeof i){var o=n;n=i,i=o}if("number"==typeof n){var o=n;n=i,i=o}this.started=!1,this.phaseAmount=void 0,this.oscillator=e.audiocontext.createOscillator(),this.f=i||440,this.oscillator.type=n||"sine",this.oscillator.frequency.setValueAtTime(this.f,e.audiocontext.currentTime),this.output=e.audiocontext.createGain(),this._freqMods=[],this.output.gain.value=.5,this.output.gain.setValueAtTime(.5,e.audiocontext.currentTime),this.oscillator.connect(this.output),this.panPosition=0,this.connection=e.input,this.panner=new t.Panner(this.output,this.connection,1),this.mathOps=[this.output],e.soundArray.push(this)},t.Oscillator.prototype.start=function(t,i){if(this.started){var n=e.audiocontext.currentTime; +this.stop(n)}if(!this.started){var o=i||this.f,r=this.oscillator.type;this.oscillator&&(this.oscillator.disconnect(),delete this.oscillator),this.oscillator=e.audiocontext.createOscillator(),this.oscillator.frequency.value=Math.abs(o),this.oscillator.type=r,this.oscillator.connect(this.output),t=t||0,this.oscillator.start(t+e.audiocontext.currentTime),this.freqNode=this.oscillator.frequency;for(var s in this._freqMods)"undefined"!=typeof this._freqMods[s].connect&&this._freqMods[s].connect(this.oscillator.frequency);this.started=!0}},t.Oscillator.prototype.stop=function(t){if(this.started){var i=t||0,n=e.audiocontext.currentTime;this.oscillator.stop(i+n),this.started=!1}},t.Oscillator.prototype.amp=function(t,i,n){var o=this;if("number"==typeof t){var i=i||0,n=n||0,r=e.audiocontext.currentTime;this.output.gain.linearRampToValueAtTime(t,r+n+i)}else{if(!t)return this.output.gain;t.connect(o.output.gain)}},t.Oscillator.prototype.fade=t.Oscillator.prototype.amp,t.Oscillator.prototype.getAmp=function(){return this.output.gain.value},t.Oscillator.prototype.freq=function(t,i,n){if("number"!=typeof t||isNaN(t)){if(!t)return this.oscillator.frequency;t.output&&(t=t.output),t.connect(this.oscillator.frequency),this._freqMods.push(t)}else{this.f=t;var o=e.audiocontext.currentTime,i=i||0,n=n||0;0===i?this.oscillator.frequency.setValueAtTime(t,n+o):t>0?this.oscillator.frequency.exponentialRampToValueAtTime(t,n+i+o):this.oscillator.frequency.linearRampToValueAtTime(t,n+i+o),this.phaseAmount&&this.phase(this.phaseAmount)}},t.Oscillator.prototype.getFreq=function(){return this.oscillator.frequency.value},t.Oscillator.prototype.setType=function(t){this.oscillator.type=t},t.Oscillator.prototype.getType=function(){return this.oscillator.type},t.Oscillator.prototype.connect=function(t){t?t.hasOwnProperty("input")?(this.panner.connect(t.input),this.connection=t.input):(this.panner.connect(t),this.connection=t):this.panner.connect(e.input)},t.Oscillator.prototype.disconnect=function(){this.output&&this.output.disconnect(),this.panner&&(this.panner.disconnect(),this.output&&this.output.connect(this.panner)),this.oscMods=[]},t.Oscillator.prototype.pan=function(t,e){this.panPosition=t,this.panner.pan(t,e)},t.Oscillator.prototype.getPan=function(){return this.panPosition},t.Oscillator.prototype.dispose=function(){var t=e.soundArray.indexOf(this);if(e.soundArray.splice(t,1),this.oscillator){var i=e.audiocontext.currentTime;this.stop(i),this.disconnect(),this.panner=null,this.oscillator=null}this.osc2&&this.osc2.dispose()},t.Oscillator.prototype.phase=function(i){var n=t.prototype.map(i,0,1,0,1/this.f),o=e.audiocontext.currentTime;this.phaseAmount=i,this.dNode||(this.dNode=e.audiocontext.createDelay(),this.oscillator.disconnect(),this.oscillator.connect(this.dNode),this.dNode.connect(this.output)),this.dNode.delayTime.setValueAtTime(n,o)};var s=function(t,e,i,n,o){var r=t.oscillator;for(var s in t.mathOps)t.mathOps[s]instanceof o&&(r.disconnect(),t.mathOps[s].dispose(),i=s,i0&&(r=t.mathOps[s-1]),r.disconnect(),r.connect(e),e.connect(n),t.mathOps[i]=e,t};t.Oscillator.prototype.add=function(t){var e=new i(t),n=this.mathOps.length-1,o=this.output;return s(this,e,n,o,i)},t.Oscillator.prototype.mult=function(t){var e=new o(t),i=this.mathOps.length-1,n=this.output;return s(this,e,i,n,o)},t.Oscillator.prototype.scale=function(e,i,n,o){var a,u;4===arguments.length?(a=t.prototype.map(n,e,i,0,1)-.5,u=t.prototype.map(o,e,i,0,1)-.5):(a=arguments[0],u=arguments[1]);var c=new r(a,u),p=this.mathOps.length-1,h=this.output;return s(this,c,p,h,r)},t.SinOsc=function(e){t.Oscillator.call(this,e,"sine")},t.SinOsc.prototype=Object.create(t.Oscillator.prototype),t.TriOsc=function(e){t.Oscillator.call(this,e,"triangle")},t.TriOsc.prototype=Object.create(t.Oscillator.prototype),t.SawOsc=function(e){t.Oscillator.call(this,e,"sawtooth")},t.SawOsc.prototype=Object.create(t.Oscillator.prototype),t.SqrOsc=function(e){t.Oscillator.call(this,e,"square")},t.SqrOsc.prototype=Object.create(t.Oscillator.prototype)}(n,S,w,A);var O;O=function(t){"use strict";return t.Timeline=function(){var e=this.optionsObject(arguments,["memory"],t.Timeline.defaults);this._timeline=[],this._toRemove=[],this._iterating=!1,this.memory=e.memory},t.extend(t.Timeline),t.Timeline.defaults={memory:1/0},Object.defineProperty(t.Timeline.prototype,"length",{get:function(){return this._timeline.length}}),t.Timeline.prototype.add=function(t){if(this.isUndef(t.time))throw new Error("Tone.Timeline: events must have a time attribute");if(this._timeline.length){var e=this._search(t.time);this._timeline.splice(e+1,0,t)}else this._timeline.push(t);if(this.length>this.memory){var i=this.length-this.memory;this._timeline.splice(0,i)}return this},t.Timeline.prototype.remove=function(t){if(this._iterating)this._toRemove.push(t);else{var e=this._timeline.indexOf(t);-1!==e&&this._timeline.splice(e,1)}return this},t.Timeline.prototype.get=function(t){var e=this._search(t);return-1!==e?this._timeline[e]:null},t.Timeline.prototype.peek=function(){return this._timeline[0]},t.Timeline.prototype.shift=function(){return this._timeline.shift()},t.Timeline.prototype.getAfter=function(t){var e=this._search(t);return e+10&&this._timeline[e-1].time=0?this._timeline[i-1]:null},t.Timeline.prototype.cancel=function(t){if(this._timeline.length>1){var e=this._search(t);if(e>=0)if(this._timeline[e].time===t){for(var i=e;i>=0&&this._timeline[i].time===t;i--)e=i;this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&this._timeline[0].time>=t&&(this._timeline=[]);return this},t.Timeline.prototype.cancelBefore=function(t){if(this._timeline.length){var e=this._search(t);e>=0&&(this._timeline=this._timeline.slice(e+1))}return this},t.Timeline.prototype._search=function(t){var e=0,i=this._timeline.length,n=i;if(i>0&&this._timeline[i-1].time<=t)return i-1;for(;n>e;){var o=Math.floor(e+(n-e)/2),r=this._timeline[o],s=this._timeline[o+1];if(r.time===t){for(var a=o;at)return o;r.time>t?n=o:r.time=n;n++)t(this._timeline[n]);if(this._iterating=!1,this._toRemove.length>0){for(var o=0;o=0&&this._timeline[i].time>=t;)i--;return this._iterate(e,i+1),this},t.Timeline.prototype.forEachAtTime=function(t,e){var i=this._search(t);return-1!==i&&this._iterate(function(i){i.time===t&&e(i)},0,i),this},t.Timeline.prototype.dispose=function(){t.prototype.dispose.call(this),this._timeline=null,this._toRemove=null},t.Timeline}(p);var F;F=function(t){"use strict";return t.TimelineSignal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this._events=new t.Timeline(10),t.Signal.apply(this,e),e.param=this._param,t.Param.call(this,e),this._initial=this._fromUnits(this._param.value)},t.extend(t.TimelineSignal,t.Param),t.TimelineSignal.Type={Linear:"linear",Exponential:"exponential",Target:"target",Curve:"curve",Set:"set"},Object.defineProperty(t.TimelineSignal.prototype,"value",{get:function(){var t=this.now(),e=this.getValueAtTime(t);return this._toUnits(e)},set:function(t){var e=this._fromUnits(t);this._initial=e,this.cancelScheduledValues(),this._param.value=e}}),t.TimelineSignal.prototype.setValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Set,value:e,time:i}),this._param.setValueAtTime(e,i),this},t.TimelineSignal.prototype.linearRampToValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Linear,value:e,time:i}),this._param.linearRampToValueAtTime(e,i),this},t.TimelineSignal.prototype.exponentialRampToValueAtTime=function(e,i){i=this.toSeconds(i);var n=this._searchBefore(i);n&&0===n.value&&this.setValueAtTime(this._minOutput,n.time),e=this._fromUnits(e);var o=Math.max(e,this._minOutput);return this._events.add({type:t.TimelineSignal.Type.Exponential,value:o,time:i}),ee)this.cancelScheduledValues(e),this.linearRampToValueAtTime(i,e);else{var o=this._searchAfter(e);o&&(this.cancelScheduledValues(e),o.type===t.TimelineSignal.Type.Linear?this.linearRampToValueAtTime(i,e):o.type===t.TimelineSignal.Type.Exponential&&this.exponentialRampToValueAtTime(i,e)),this.setValueAtTime(i,e)}return this},t.TimelineSignal.prototype.linearRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.linearRampToValueAtTime(t,i),this},t.TimelineSignal.prototype.exponentialRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.exponentialRampToValueAtTime(t,i),this},t.TimelineSignal.prototype._searchBefore=function(t){return this._events.get(t)},t.TimelineSignal.prototype._searchAfter=function(t){return this._events.getAfter(t)},t.TimelineSignal.prototype.getValueAtTime=function(e){e=this.toSeconds(e);var i=this._searchAfter(e),n=this._searchBefore(e),o=this._initial;if(null===n)o=this._initial;else if(n.type===t.TimelineSignal.Type.Target){var r,s=this._events.getBefore(n.time);r=null===s?this._initial:s.value,o=this._exponentialApproach(n.time,r,n.value,n.constant,e)}else o=n.type===t.TimelineSignal.Type.Curve?this._curveInterpolate(n.time,n.value,n.duration,e):null===i?n.value:i.type===t.TimelineSignal.Type.Linear?this._linearInterpolate(n.time,n.value,i.time,i.value,e):i.type===t.TimelineSignal.Type.Exponential?this._exponentialInterpolate(n.time,n.value,i.time,i.value,e):n.value;return o},t.TimelineSignal.prototype.connect=t.SignalBase.prototype.connect,t.TimelineSignal.prototype._exponentialApproach=function(t,e,i,n,o){return i+(e-i)*Math.exp(-(o-t)/n)},t.TimelineSignal.prototype._linearInterpolate=function(t,e,i,n,o){return e+(n-e)*((o-t)/(i-t))},t.TimelineSignal.prototype._exponentialInterpolate=function(t,e,i,n,o){return e=Math.max(this._minOutput,e),e*Math.pow(n/e,(o-t)/(i-t))},t.TimelineSignal.prototype._curveInterpolate=function(t,e,i,n){var o=e.length;if(n>=t+i)return e[o-1];if(t>=n)return e[0];var r=(n-t)/i,s=Math.floor((o-1)*r),a=Math.ceil((o-1)*r),u=e[s],c=e[a];return a===s?u:this._linearInterpolate(s,u,a,c,r*(o-1))},t.TimelineSignal.prototype.dispose=function(){t.Signal.prototype.dispose.call(this),t.Param.prototype.dispose.call(this),this._events.dispose(),this._events=null},t.TimelineSignal}(p,x);var q;q=function(){var e=n,i=S,o=w,r=A,s=F,a=p;a.setContext(e.audiocontext),t.Envelope=function(t,i,n,o,r,a){this.aTime=t||.1,this.aLevel=i||1,this.dTime=n||.5,this.dLevel=o||0,this.rTime=r||0,this.rLevel=a||0,this._rampHighPercentage=.98,this._rampLowPercentage=.02,this.output=e.audiocontext.createGain(),this.control=new s,this._init(),this.control.connect(this.output),this.connection=null,this.mathOps=[this.control],this.isExponential=!1,this.sourceToClear=null,this.wasTriggered=!1,e.soundArray.push(this)},t.Envelope.prototype._init=function(){var t=e.audiocontext.currentTime,i=t;this.control.setTargetAtTime(1e-5,i,.001),this._setRampAD(this.aTime,this.dTime)},t.Envelope.prototype.set=function(t,e,i,n,o,r){this.aTime=t,this.aLevel=e,this.dTime=i||0,this.dLevel=n||0,this.rTime=o||0,this.rLevel=r||0,this._setRampAD(t,i)},t.Envelope.prototype.setADSR=function(t,e,i,n){this.aTime=t,this.dTime=e||0,this.sPercent=i||0,this.dLevel="undefined"!=typeof i?i*(this.aLevel-this.rLevel)+this.rLevel:0,this.rTime=n||0,this._setRampAD(t,e)},t.Envelope.prototype.setRange=function(t,e){this.aLevel=t||1,this.rLevel=e||0},t.Envelope.prototype._setRampAD=function(t,e){this._rampAttackTime=this.checkExpInput(t),this._rampDecayTime=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=t/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=e/this.checkExpInput(i)},t.Envelope.prototype.setRampPercentages=function(t,e){this._rampHighPercentage=this.checkExpInput(t),this._rampLowPercentage=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=this._rampAttackTime/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=this._rampDecayTime/this.checkExpInput(i)},t.Envelope.prototype.setInput=function(){for(var t=0;t=t&&(t=1e-8),t},t.Envelope.prototype.play=function(t,e,i){var n=e||0,i=i||0;t&&this.connection!==t&&this.connect(t),this.triggerAttack(t,n),this.triggerRelease(t,n+this.aTime+this.dTime+i)},t.Envelope.prototype.triggerAttack=function(t,i){var n=e.audiocontext.currentTime,o=i||0,r=n+o;this.lastAttack=r,this.wasTriggered=!0,t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.aTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.aLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.aLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),r+=this.dTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.dLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.dLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r))},t.Envelope.prototype.triggerRelease=function(t,i){if(this.wasTriggered){var n=e.audiocontext.currentTime,o=i||0,r=n+o;t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.rTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.rLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.rLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),this.wasTriggered=!1}},t.Envelope.prototype.ramp=function(t,i,n,o){var r=e.audiocontext.currentTime,s=i||0,a=r+s,u=this.checkExpInput(n),c="undefined"!=typeof o?this.checkExpInput(o):void 0;t&&this.connection!==t&&this.connect(t);var p=this.checkExpInput(this.control.getValueAtTime(a));u>p?(this.control.setTargetAtTime(u,a,this._rampAttackTC),a+=this._rampAttackTime):p>u&&(this.control.setTargetAtTime(u,a,this._rampDecayTC),a+=this._rampDecayTime),void 0!==c&&(c>u?this.control.setTargetAtTime(c,a,this._rampAttackTC):u>c&&this.control.setTargetAtTime(c,a,this._rampDecayTC))},t.Envelope.prototype.connect=function(i){this.connection=i,(i instanceof t.Oscillator||i instanceof t.SoundFile||i instanceof t.AudioIn||i instanceof t.Reverb||i instanceof t.Noise||i instanceof t.Filter||i instanceof t.Delay)&&(i=i.output.gain),i instanceof AudioParam&&i.setValueAtTime(0,e.audiocontext.currentTime),i instanceof t.Signal&&i.setValue(0),this.output.connect(i)},t.Envelope.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Envelope.prototype.add=function(e){var n=new i(e),o=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,n,o,r,i)},t.Envelope.prototype.mult=function(e){var i=new o(e),n=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,i,n,r,o)},t.Envelope.prototype.scale=function(e,i,n,o){var s=new r(e,i,n,o),a=this.mathOps.length,u=this.output;return t.prototype._mathChain(this,s,a,u,r)},t.Envelope.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.disconnect(),this.control&&(this.control.dispose(),this.control=null);for(var i=1;io;o++)n[o]=1;var r=t.createBufferSource();return r.buffer=e,r.loop=!0,r}var i=n;t.Pulse=function(n,o){t.Oscillator.call(this,n,"sawtooth"),this.w=o||0,this.osc2=new t.SawOsc(n),this.dNode=i.audiocontext.createDelay(),this.dcOffset=e(),this.dcGain=i.audiocontext.createGain(),this.dcOffset.connect(this.dcGain),this.dcGain.connect(this.output),this.f=n||440;var r=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=r,this.dcGain.gain.value=1.7*(.5-this.w),this.osc2.disconnect(),this.osc2.panner.disconnect(),this.osc2.amp(-1),this.osc2.output.connect(this.dNode),this.dNode.connect(this.output),this.output.gain.value=1,this.output.connect(this.panner)},t.Pulse.prototype=Object.create(t.Oscillator.prototype),t.Pulse.prototype.width=function(e){if("number"==typeof e){if(1>=e&&e>=0){this.w=e;var i=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=i}this.dcGain.gain.value=1.7*(.5-this.w)}else{e.connect(this.dNode.delayTime);var n=new t.SignalAdd(-.5);n.setInput(e),n=n.mult(-1),n=n.mult(1.7),n.connect(this.dcGain.gain)}},t.Pulse.prototype.start=function(t,n){var o=i.audiocontext.currentTime,r=n||0;if(!this.started){var s=t||this.f,a=this.oscillator.type;this.oscillator=i.audiocontext.createOscillator(),this.oscillator.frequency.setValueAtTime(s,o),this.oscillator.type=a,this.oscillator.connect(this.output),this.oscillator.start(r+o),this.osc2.oscillator=i.audiocontext.createOscillator(),this.osc2.oscillator.frequency.setValueAtTime(s,r+o),this.osc2.oscillator.type=a,this.osc2.oscillator.connect(this.osc2.output),this.osc2.start(r+o),this.freqNode=[this.oscillator.frequency,this.osc2.oscillator.frequency],this.dcOffset=e(),this.dcOffset.connect(this.dcGain),this.dcOffset.start(r+o),void 0!==this.mods&&void 0!==this.mods.frequency&&(this.mods.frequency.connect(this.freqNode[0]),this.mods.frequency.connect(this.freqNode[1])),this.started=!0,this.osc2.started=!0}},t.Pulse.prototype.stop=function(t){if(this.started){var e=t||0,n=i.audiocontext.currentTime;this.oscillator.stop(e+n),this.osc2.oscillator&&this.osc2.oscillator.stop(e+n),this.dcOffset.stop(e+n),this.started=!1,this.osc2.started=!1}},t.Pulse.prototype.freq=function(t,e,n){if("number"==typeof t){this.f=t;var o=i.audiocontext.currentTime,e=e||0,n=n||0,r=this.oscillator.frequency.value;this.oscillator.frequency.cancelScheduledValues(o),this.oscillator.frequency.setValueAtTime(r,o+n),this.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.osc2.oscillator.frequency.cancelScheduledValues(o),this.osc2.oscillator.frequency.setValueAtTime(r,o+n),this.osc2.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.freqMod&&(this.freqMod.output.disconnect(),this.freqMod=null)}else t.output&&(t.output.disconnect(),t.output.connect(this.oscillator.frequency),t.output.connect(this.osc2.oscillator.frequency),this.freqMod=t)}}(n,k);var V;V=function(){var e=n;t.Noise=function(e){var n;t.Oscillator.call(this),delete this.f,delete this.freq,delete this.oscillator,n="brown"===e?r:"pink"===e?o:i,this.buffer=n},t.Noise.prototype=Object.create(t.Oscillator.prototype);var i=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0;t>o;o++)n[o]=2*Math.random()-1;return i.type="white",i}(),o=function(){var t,i,n,o,r,s,a,u=2*e.audiocontext.sampleRate,c=e.audiocontext.createBuffer(1,u,e.audiocontext.sampleRate),p=c.getChannelData(0);t=i=n=o=r=s=a=0;for(var h=0;u>h;h++){var l=2*Math.random()-1;t=.99886*t+.0555179*l,i=.99332*i+.0750759*l,n=.969*n+.153852*l,o=.8665*o+.3104856*l,r=.55*r+.5329522*l,s=-.7616*s-.016898*l,p[h]=t+i+n+o+r+s+a+.5362*l,p[h]*=.11,a=.115926*l}return c.type="pink",c}(),r=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0,r=0;t>r;r++){var s=2*Math.random()-1;n[r]=(o+.02*s)/1.02,o=n[r],n[r]*=3.5}return i.type="brown",i}();t.Noise.prototype.setType=function(t){switch(t){case"white":this.buffer=i;break;case"pink":this.buffer=o;break;case"brown":this.buffer=r;break;default:this.buffer=i}if(this.started){var n=e.audiocontext.currentTime;this.stop(n),this.start(n+.01)}},t.Noise.prototype.getType=function(){return this.buffer.type},t.Noise.prototype.start=function(){this.started&&this.stop(),this.noise=e.audiocontext.createBufferSource(),this.noise.buffer=this.buffer,this.noise.loop=!0,this.noise.connect(this.output);var t=e.audiocontext.currentTime;this.noise.start(t),this.started=!0},t.Noise.prototype.stop=function(){var t=e.audiocontext.currentTime;this.noise&&(this.noise.stop(t),this.started=!1)},t.Noise.prototype.dispose=function(){var t=e.audiocontext.currentTime,i=e.soundArray.indexOf(this);e.soundArray.splice(i,1),this.noise&&(this.noise.disconnect(),this.stop(t)),this.output&&this.output.disconnect(),this.panner&&this.panner.disconnect(),this.output=null,this.panner=null,this.buffer=null,this.noise=null}}(n);var E;E=function(){var e=n;e.inputSources=[],t.AudioIn=function(i){this.input=e.audiocontext.createGain(),this.output=e.audiocontext.createGain(),this.stream=null,this.mediaStream=null,this.currentSource=null,this.enabled=!1,this.amplitude=new t.Amplitude,this.output.connect(this.amplitude.input),window.MediaStreamTrack&&window.navigator.mediaDevices&&window.navigator.mediaDevices.getUserMedia||(i?i():window.alert("This browser does not support MediaStreamTrack and mediaDevices")),e.soundArray.push(this)},t.AudioIn.prototype.start=function(t,i){var n=this;this.stream&&this.stop();var o=e.inputSources[n.currentSource],r={audio:{sampleRate:e.audiocontext.sampleRate,echoCancellation:!1}};e.inputSources[this.currentSource]&&(r.audio.deviceId=o.deviceId),window.navigator.mediaDevices.getUserMedia(r).then(function(i){n.stream=i,n.enabled=!0,n.mediaStream=e.audiocontext.createMediaStreamSource(i),n.mediaStream.connect(n.output),n.amplitude.setInput(n.output),t&&t()})["catch"](function(t){i?i(t):console.error(t)})},t.AudioIn.prototype.stop=function(){this.stream&&(this.stream.getTracks().forEach(function(t){t.stop()}),this.mediaStream.disconnect(),delete this.mediaStream,delete this.stream)},t.AudioIn.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):t.hasOwnProperty("analyser")?this.output.connect(t.analyser):this.output.connect(t):this.output.connect(e.input)},t.AudioIn.prototype.disconnect=function(){this.output&&(this.output.disconnect(),this.output.connect(this.amplitude.input))},t.AudioIn.prototype.getLevel=function(t){return t&&(this.amplitude.smoothing=t),this.amplitude.getLevel()},t.AudioIn.prototype.amp=function(t,i){if(i){var n=i||0,o=this.output.gain.value;this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(o,e.audiocontext.currentTime),this.output.gain.linearRampToValueAtTime(t,n+e.audiocontext.currentTime)}else this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(t,e.audiocontext.currentTime)},t.AudioIn.prototype.getSources=function(t,i){return new Promise(function(n,o){window.navigator.mediaDevices.enumerateDevices().then(function(i){e.inputSources=i.filter(function(t){return"audioinput"===t.kind}),n(e.inputSources),t&&t(e.inputSources)})["catch"](function(t){o(t),i?i(t):console.error("This browser does not support MediaStreamTrack.getSources()")})})},t.AudioIn.prototype.setSource=function(t){e.inputSources.length>0&&t=t?0:1},127),this._scale=this.input=new t.Multiply(1e4),this._scale.connect(this._thresh)},t.extend(t.GreaterThanZero,t.SignalBase),t.GreaterThanZero.prototype.dispose=function(){return t.prototype.dispose.call(this),this._scale.dispose(),this._scale=null,this._thresh.dispose(),this._thresh=null,this},t.GreaterThanZero}(p,x,w);var N;N=function(t){"use strict";return t.GreaterThan=function(e){this.createInsOuts(2,0),this._param=this.input[0]=new t.Subtract(e),this.input[1]=this._param.input[1],this._gtz=this.output=new t.GreaterThanZero,this._param.connect(this._gtz)},t.extend(t.GreaterThan,t.Signal),t.GreaterThan.prototype.dispose=function(){return t.prototype.dispose.call(this),this._param.dispose(),this._param=null,this._gtz.dispose(),this._gtz=null,this},t.GreaterThan}(p,D,R);var B;B=function(t){"use strict";return t.Abs=function(){this._abs=this.input=this.output=new t.WaveShaper(function(t){return 0===t?0:Math.abs(t)},127)},t.extend(t.Abs,t.SignalBase),t.Abs.prototype.dispose=function(){return t.prototype.dispose.call(this),this._abs.dispose(),this._abs=null,this},t.Abs}(p,l);var U;U=function(t){"use strict";return t.Modulo=function(e){this.createInsOuts(1,0),this._shaper=new t.WaveShaper(Math.pow(2,16)),this._multiply=new t.Multiply,this._subtract=this.output=new t.Subtract,this._modSignal=new t.Signal(e),this.input.fan(this._shaper,this._subtract),this._modSignal.connect(this._multiply,0,0),this._shaper.connect(this._multiply,0,1),this._multiply.connect(this._subtract,0,1),this._setWaveShaper(e)},t.extend(t.Modulo,t.SignalBase),t.Modulo.prototype._setWaveShaper=function(t){this._shaper.setMap(function(e){var i=Math.floor((e+1e-4)/t);return i})},Object.defineProperty(t.Modulo.prototype,"value",{get:function(){return this._modSignal.value},set:function(t){this._modSignal.value=t,this._setWaveShaper(t)}}),t.Modulo.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.dispose(),this._shaper=null,this._multiply.dispose(),this._multiply=null,this._subtract.dispose(),this._subtract=null,this._modSignal.dispose(),this._modSignal=null,this},t.Modulo}(p,l,w);var I;I=function(t){"use strict";return t.Pow=function(e){this._exp=this.defaultArg(e,1),this._expScaler=this.input=this.output=new t.WaveShaper(this._expFunc(this._exp),8192)},t.extend(t.Pow,t.SignalBase),Object.defineProperty(t.Pow.prototype,"value",{get:function(){return this._exp},set:function(t){this._exp=t,this._expScaler.setMap(this._expFunc(this._exp))}}),t.Pow.prototype._expFunc=function(t){return function(e){return Math.pow(Math.abs(e),t)}},t.Pow.prototype.dispose=function(){return t.prototype.dispose.call(this),this._expScaler.dispose(),this._expScaler=null,this},t.Pow}(p);var G;G=function(t){"use strict";return t.AudioToGain=function(){this._norm=this.input=this.output=new t.WaveShaper(function(t){return(t+1)/2})},t.extend(t.AudioToGain,t.SignalBase),t.AudioToGain.prototype.dispose=function(){return t.prototype.dispose.call(this),this._norm.dispose(),this._norm=null,this},t.AudioToGain}(p,l);var L;L=function(t){"use strict";function e(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),i._eval(e[1]).connect(n,0,1),n}function i(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),n}function n(t){return t?parseFloat(t):void 0}function o(t){return t&&t.args?parseFloat(t.args):void 0}return t.Expr=function(){var t=this._replacements(Array.prototype.slice.call(arguments)),e=this._parseInputs(t);this._nodes=[],this.input=new Array(e);for(var i=0;e>i;i++)this.input[i]=this.context.createGain();var n,o=this._parseTree(t);try{n=this._eval(o)}catch(r){throw this._disposeNodes(),new Error("Tone.Expr: Could evaluate expression: "+t)}this.output=n},t.extend(t.Expr,t.SignalBase),t.Expr._Expressions={value:{signal:{regexp:/^\d+\.\d+|^\d+/,method:function(e){var i=new t.Signal(n(e));return i}},input:{regexp:/^\$\d/,method:function(t,e){return e.input[n(t.substr(1))]}}},glue:{"(":{regexp:/^\(/},")":{regexp:/^\)/},",":{regexp:/^,/}},func:{abs:{regexp:/^abs/,method:i.bind(this,t.Abs)},mod:{regexp:/^mod/,method:function(e,i){var n=o(e[1]),r=new t.Modulo(n);return i._eval(e[0]).connect(r),r}},pow:{regexp:/^pow/,method:function(e,i){var n=o(e[1]),r=new t.Pow(n);return i._eval(e[0]).connect(r),r}},a2g:{regexp:/^a2g/,method:function(e,i){var n=new t.AudioToGain;return i._eval(e[0]).connect(n),n}}},binary:{"+":{regexp:/^\+/,precedence:1,method:e.bind(this,t.Add) +},"-":{regexp:/^\-/,precedence:1,method:function(n,o){return 1===n.length?i(t.Negate,n,o):e(t.Subtract,n,o)}},"*":{regexp:/^\*/,precedence:0,method:e.bind(this,t.Multiply)}},unary:{"-":{regexp:/^\-/,method:i.bind(this,t.Negate)},"!":{regexp:/^\!/,method:i.bind(this,t.NOT)}}},t.Expr.prototype._parseInputs=function(t){var e=t.match(/\$\d/g),i=0;if(null!==e)for(var n=0;n0;){e=e.trim();var r=i(e);o.push(r),e=e.substr(r.value.length)}return{next:function(){return o[++n]},peek:function(){return o[n+1]}}},t.Expr.prototype._parseTree=function(e){function i(t,e){return!p(t)&&"glue"===t.type&&t.value===e}function n(e,i,n){var o=!1,r=t.Expr._Expressions[i];if(!p(e))for(var s in r){var a=r[s];if(a.regexp.test(e.value)){if(p(n))return!0;if(a.precedence===n)return!0}}return o}function o(t){p(t)&&(t=5);var e;e=0>t?r():o(t-1);for(var i=c.peek();n(i,"binary",t);)i=c.next(),e={operator:i.value,method:i.method,args:[e,o(t-1)]},i=c.peek();return e}function r(){var t,e;return t=c.peek(),n(t,"unary")?(t=c.next(),e=r(),{operator:t.value,method:t.method,args:[e]}):s()}function s(){var t,e;if(t=c.peek(),p(t))throw new SyntaxError("Tone.Expr: Unexpected termination of expression");if("func"===t.type)return t=c.next(),a(t);if("value"===t.type)return t=c.next(),{method:t.method,args:t.value};if(i(t,"(")){if(c.next(),e=o(),t=c.next(),!i(t,")"))throw new SyntaxError("Expected )");return e}throw new SyntaxError("Tone.Expr: Parse error, cannot process token "+t.value)}function a(t){var e,n=[];if(e=c.next(),!i(e,"("))throw new SyntaxError('Tone.Expr: Expected ( in a function call "'+t.value+'"');if(e=c.peek(),i(e,")")||(n=u()),e=c.next(),!i(e,")"))throw new SyntaxError('Tone.Expr: Expected ) in a function call "'+t.value+'"');return{method:t.method,args:n,name:name}}function u(){for(var t,e,n=[];;){if(e=o(),p(e))break;if(n.push(e),t=c.peek(),!i(t,","))break;c.next()}return n}var c=this._tokenize(e),p=this.isUndef.bind(this);return o()},t.Expr.prototype._eval=function(t){if(!this.isUndef(t)){var e=t.method(t.args,this);return this._nodes.push(e),e}},t.Expr.prototype._disposeNodes=function(){for(var t=0;t0){this.connect(arguments[0]);for(var t=1;t=t&&(t=1),"number"==typeof t?(this.biquad.frequency.value=t,this.biquad.frequency.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.frequency.exponentialRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.frequency),this.biquad.frequency.value},t.Filter.prototype.res=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.Q.value=t,this.biquad.Q.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.Q.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.Q),this.biquad.Q.value},t.Filter.prototype.gain=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.gain.value=t,this.biquad.gain.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.gain.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.gain),this.biquad.gain.value},t.Filter.prototype.toggle=function(){return this._on=!this._on,this._on===!0?this.biquad.type=this._untoggledType:this._on===!1&&(this.biquad.type="allpass"),this._on},t.Filter.prototype.setType=function(t){this.biquad.type=t,this._untoggledType=this.biquad.type},t.Filter.prototype.dispose=function(){e.prototype.dispose.apply(this),this.biquad&&(this.biquad.disconnect(),delete this.biquad)},t.LowPass=function(){t.Filter.call(this,"lowpass")},t.LowPass.prototype=Object.create(t.Filter.prototype),t.HighPass=function(){t.Filter.call(this,"highpass")},t.HighPass.prototype=Object.create(t.Filter.prototype),t.BandPass=function(){t.Filter.call(this,"bandpass")},t.BandPass.prototype=Object.create(t.Filter.prototype),t.Filter}(n,X);var z;z=function(){var e=Y,i=n,o=function(t,i){e.call(this,"peaking"),this.disconnect(),this.set(t,i),this.biquad.gain.value=0,delete this.input,delete this.output,delete this._drywet,delete this.wet};return o.prototype=Object.create(e.prototype),o.prototype.amp=function(){console.warn("`amp()` is not available for p5.EQ bands. Use `.gain()`")},o.prototype.drywet=function(){console.warn("`drywet()` is not available for p5.EQ bands.")},o.prototype.connect=function(e){var i=e||t.soundOut.input;this.biquad?this.biquad.connect(i.input?i.input:i):this.output.connect(i.input?i.input:i)},o.prototype.disconnect=function(){this.biquad&&this.biquad.disconnect()},o.prototype.dispose=function(){var t=i.soundArray.indexOf(this);i.soundArray.splice(t,1),this.disconnect(),delete this.biquad},o}(Y,n);var W;W=function(){var e=X,i=z;return t.EQ=function(t){e.call(this),t=3===t||8===t?t:3;var i;i=3===t?Math.pow(2,3):2,this.bands=[];for(var n,o,r=0;t>r;r++)r===t-1?(n=21e3,o=.01):0===r?(n=100,o=.1):1===r?(n=3===t?360*i:360,o=1):(n=this.bands[r-1].freq()*i,o=1),this.bands[r]=this._newBand(n,o),r>0?this.bands[r-1].connect(this.bands[r].biquad):this.input.connect(this.bands[r].biquad);this.bands[t-1].connect(this.output)},t.EQ.prototype=Object.create(e.prototype),t.EQ.prototype.process=function(t){t.connect(this.input)},t.EQ.prototype.set=function(){if(arguments.length===2*this.bands.length)for(var t=0;t0;)delete this.bands.pop().dispose();delete this.bands}},t.EQ}(X,z);var Q;Q=function(){var e=X;return t.Panner3D=function(){e.call(this),this.panner=this.ac.createPanner(),this.panner.panningModel="HRTF",this.panner.distanceModel="linear",this.panner.connect(this.output),this.input.connect(this.panner)},t.Panner3D.prototype=Object.create(e.prototype),t.Panner3D.prototype.process=function(t){t.connect(this.input)},t.Panner3D.prototype.set=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.panner.positionX.value,this.panner.positionY.value,this.panner.positionZ.value]},t.Panner3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionX.value=t,this.panner.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionX),this.panner.positionX.value},t.Panner3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionY.value=t,this.panner.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionY),this.panner.positionY.value},t.Panner3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionZ.value=t,this.panner.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionZ),this.panner.positionZ.value},t.Panner3D.prototype.orient=function(t,e,i,n){return this.orientX(t,n),this.orientY(e,n),this.orientZ(i,n),[this.panner.orientationX.value,this.panner.orientationY.value,this.panner.orientationZ.value]},t.Panner3D.prototype.orientX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationX.value=t,this.panner.orientationX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationX),this.panner.orientationX.value},t.Panner3D.prototype.orientY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationY.value=t,this.panner.orientationY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationY),this.panner.orientationY.value},t.Panner3D.prototype.orientZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationZ.value=t,this.panner.orientationZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationZ),this.panner.orientationZ.value},t.Panner3D.prototype.setFalloff=function(t,e){this.maxDist(t),this.rolloff(e)},t.Panner3D.prototype.maxDist=function(t){return"number"==typeof t&&(this.panner.maxDistance=t),this.panner.maxDistance},t.Panner3D.prototype.rolloff=function(t){return"number"==typeof t&&(this.panner.rolloffFactor=t),this.panner.rolloffFactor},t.Panner3D.dispose=function(){e.prototype.dispose.apply(this),this.panner&&(this.panner.disconnect(),delete this.panner)},t.Panner3D}(n,X);var H;H=function(){var e=n;return t.Listener3D=function(t){this.ac=e.audiocontext,this.listener=this.ac.listener},t.Listener3D.prototype.process=function(t){t.connect(this.input)},t.Listener3D.prototype.position=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.listener.positionX.value,this.listener.positionY.value,this.listener.positionZ.value]},t.Listener3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionX.value=t,this.listener.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionX),this.listener.positionX.value},t.Listener3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionY.value=t,this.listener.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionY),this.listener.positionY.value},t.Listener3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionZ.value=t,this.listener.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionZ),this.listener.positionZ.value},t.Listener3D.prototype.orient=function(t,e,i,n,o,r,s){return 3===arguments.length||4===arguments.length?(s=arguments[3],this.orientForward(t,e,i,s)):(6===arguments.length||7===arguments)&&(this.orientForward(t,e,i),this.orientUp(n,o,r,s)),[this.listener.forwardX.value,this.listener.forwardY.value,this.listener.forwardZ.value,this.listener.upX.value,this.listener.upY.value,this.listener.upZ.value]},t.Listener3D.prototype.orientForward=function(t,e,i,n){return this.forwardX(t,n),this.forwardY(e,n),this.forwardZ(i,n),[this.listener.forwardX,this.listener.forwardY,this.listener.forwardZ]},t.Listener3D.prototype.orientUp=function(t,e,i,n){return this.upX(t,n),this.upY(e,n),this.upZ(i,n),[this.listener.upX,this.listener.upY,this.listener.upZ]},t.Listener3D.prototype.forwardX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardX.value=t,this.listener.forwardX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardX),this.listener.forwardX.value},t.Listener3D.prototype.forwardY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardY.value=t,this.listener.forwardY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardY),this.listener.forwardY.value},t.Listener3D.prototype.forwardZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardZ.value=t,this.listener.forwardZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardZ),this.listener.forwardZ.value},t.Listener3D.prototype.upX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upX.value=t,this.listener.upX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upX),this.listener.upX.value},t.Listener3D.prototype.upY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upY.value=t,this.listener.upY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upY),this.listener.upY.value},t.Listener3D.prototype.upZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upZ.value=t,this.listener.upZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upZ),this.listener.upZ.value},t.Listener3D}(n,X);var $;$=function(){var e=Y,i=X;t.Delay=function(){i.call(this),this._split=this.ac.createChannelSplitter(2),this._merge=this.ac.createChannelMerger(2),this._leftGain=this.ac.createGain(),this._rightGain=this.ac.createGain(),this.leftDelay=this.ac.createDelay(),this.rightDelay=this.ac.createDelay(),this._leftFilter=new e,this._rightFilter=new e,this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._leftFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._rightFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._leftFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this._rightFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this.input.connect(this._split),this.leftDelay.connect(this._leftGain),this.rightDelay.connect(this._rightGain),this._leftGain.connect(this._leftFilter.input),this._rightGain.connect(this._rightFilter.input),this._merge.connect(this.wet),this._leftFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this._rightFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this.setType(0),this._maxDelay=this.leftDelay.delayTime.maxValue,this.feedback(.5)},t.Delay.prototype=Object.create(i.prototype),t.Delay.prototype.process=function(t,e,i,n){var o=i||0,r=e||0;if(o>=1)throw new Error("Feedback value will force a positive feedback loop.");if(r>=this._maxDelay)throw new Error("Delay Time exceeds maximum delay time of "+this._maxDelay+" second.");t.connect(this.input),this.leftDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this.rightDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this._leftGain.gain.value=o,this._rightGain.gain.value=o,n&&(this._leftFilter.freq(n),this._rightFilter.freq(n))},t.Delay.prototype.delayTime=function(t){"number"!=typeof t?(t.connect(this.leftDelay.delayTime),t.connect(this.rightDelay.delayTime)):(this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.leftDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime),this.rightDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime))},t.Delay.prototype.feedback=function(t){if(t&&"number"!=typeof t)t.connect(this._leftGain.gain),t.connect(this._rightGain.gain);else{if(t>=1)throw new Error("Feedback value will force a positive feedback loop.");"number"==typeof t&&(this._leftGain.gain.value=t,this._rightGain.gain.value=t)}return this._leftGain.gain.value},t.Delay.prototype.filter=function(t,e){this._leftFilter.set(t,e),this._rightFilter.set(t,e)},t.Delay.prototype.setType=function(t){switch(1===t&&(t="pingPong"),this._split.disconnect(),this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._split.connect(this.leftDelay,0),this._split.connect(this.rightDelay,1),t){case"pingPong":this._rightFilter.setType(this._leftFilter.biquad.type),this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.rightDelay),this._rightFilter.output.connect(this.leftDelay);break;default:this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.leftDelay),this._rightFilter.output.connect(this.rightDelay)}},t.Delay.prototype.dispose=function(){i.prototype.dispose.apply(this),this._split.disconnect(),this._leftFilter.dispose(),this._rightFilter.dispose(),this._merge.disconnect(),this._leftGain.disconnect(),this._rightGain.disconnect(),this.leftDelay.disconnect(),this.rightDelay.disconnect(),this._split=void 0,this._leftFilter=void 0,this._rightFilter=void 0,this._merge=void 0,this._leftGain=void 0,this._rightGain=void 0,this.leftDelay=void 0,this.rightDelay=void 0}}(Y,X);var J;J=function(){var e=r,i=X;t.Reverb=function(){i.call(this),this.convolverNode=this.ac.createConvolver(),this.input.gain.value=.5,this.input.connect(this.convolverNode),this.convolverNode.connect(this.wet),this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse()},t.Reverb.prototype=Object.create(i.prototype),t.Reverb.prototype.process=function(t,e,i,n){t.connect(this.input);var o=!1;e&&(this._seconds=e,o=!0),i&&(this._decay=i),n&&(this._reverse=n),o&&this._buildImpulse()},t.Reverb.prototype.set=function(t,e,i){var n=!1;t&&(this._seconds=t,n=!0),e&&(this._decay=e),i&&(this._reverse=i),n&&this._buildImpulse()},t.Reverb.prototype._buildImpulse=function(){var t,e,i=this.ac.sampleRate,n=i*this._seconds,o=this._decay,r=this.ac.createBuffer(2,n,i),s=r.getChannelData(0),a=r.getChannelData(1);for(e=0;n>e;e++)t=this._reverse?n-e:e,s[e]=(2*Math.random()-1)*Math.pow(1-t/n,o),a[e]=(2*Math.random()-1)*Math.pow(1-t/n,o);this.convolverNode.buffer=r},t.Reverb.prototype.dispose=function(){i.prototype.dispose.apply(this),this.convolverNode&&(this.convolverNode.buffer=null,this.convolverNode=null)},t.Convolver=function(t,e,n){i.call(this),this.convolverNode=this.ac.createConvolver(),this.input.gain.value=.5,this.input.connect(this.convolverNode),this.convolverNode.connect(this.wet),t?(this.impulses=[],this._loadBuffer(t,e,n)):(this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse())},t.Convolver.prototype=Object.create(t.Reverb.prototype),t.prototype.registerPreloadMethod("createConvolver",t.prototype),t.prototype.createConvolver=function(e,i,n){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var o=this,r=new t.Convolver(e,function(t){"function"==typeof i&&i(t),"function"==typeof o._decrementPreload&&o._decrementPreload()},n);return r.impulses=[],r},t.Convolver.prototype._loadBuffer=function(i,n,o){var i=t.prototype._checkFileFormats(i),r=this,s=(new Error).stack,a=t.prototype.getAudioContext(),u=new XMLHttpRequest;u.open("GET",i,!0),u.responseType="arraybuffer",u.onload=function(){if(200===u.status)a.decodeAudioData(u.response,function(t){var e={},o=i.split("/");e.name=o[o.length-1],e.audioBuffer=t,r.impulses.push(e),r.convolverNode.buffer=e.audioBuffer,n&&n(e)},function(){var t=new e("decodeAudioData",s,r.url),i="AudioContext error at decodeAudioData for "+r.url;o?(t.msg=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)});else{var t=new e("loadConvolver",s,r.url),c="Unable to load "+r.url+". The request status was: "+u.status+" ("+u.statusText+")";o?(t.message=c,o(t)):console.error(c+"\n The error stack trace includes: \n"+t.stack)}},u.onerror=function(){var t=new e("loadConvolver",s,r.url),i="There was no response from the server at "+r.url+". Check the url and internet connectivity.";o?(t.message=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)},u.send()},t.Convolver.prototype.set=null,t.Convolver.prototype.process=function(t){t.connect(this.input)},t.Convolver.prototype.impulses=[],t.Convolver.prototype.addImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this._loadBuffer(t,e,i)},t.Convolver.prototype.resetImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this.impulses=[],this._loadBuffer(t,e,i)},t.Convolver.prototype.toggleImpulse=function(t){if("number"==typeof t&&tthis._nextTick&&this._state;){var s=this._state.getValueAtTime(this._nextTick);if(s!==this._lastState){this._lastState=s;var a=this._state.get(this._nextTick);s===t.State.Started?(this._nextTick=a.time,this.isUndef(a.offset)||(this.ticks=a.offset),this.emit("start",a.time,this.ticks)):s===t.State.Stopped?(this.ticks=0,this.emit("stop",a.time)):s===t.State.Paused&&this.emit("pause",a.time)}var u=this._nextTick;this.frequency&&(this._nextTick+=1/this.frequency.getValueAtTime(this._nextTick),s===t.State.Started&&(this.callback(u),this.ticks++))}},t.Clock.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)},t.Clock.prototype.dispose=function(){t.Emitter.prototype.dispose.call(this),this.context.off("tick",this._boundLoop),this._writable("frequency"),this.frequency.dispose(),this.frequency=null,this._boundLoop=null,this._nextTick=1/0,this.callback=null,this._state.dispose(),this._state=null},t.Clock}(p,F,K,v);var et;et=function(){var e=n,i=tt;t.Metro=function(){this.clock=new i({callback:this.ontick.bind(this)}),this.syncedParts=[],this.bpm=120,this._init(),this.prevTick=0,this.tatumTime=0,this.tickCallback=function(){}},t.Metro.prototype.ontick=function(t){var i=t-this.prevTick,n=t-e.audiocontext.currentTime;if(!(i-this.tatumTime<=-.02)){this.prevTick=t;var o=this;this.syncedParts.forEach(function(t){t.isPlaying&&(t.incrementStep(n),t.phrases.forEach(function(t){var e=t.sequence,i=o.metroTicks%e.length;0!==e[i]&&(o.metroTicks=t.parts.length?(t.scoreStep=0,t.onended()):(t.scoreStep=0,t.parts[t.currentPart-1].stop(),t.parts[t.currentPart].start())}var i=n,o=120;t.prototype.setBPM=function(t,e){o=t;for(var n in i.parts)i.parts[n]&&i.parts[n].setBPM(t,e)},t.Phrase=function(t,e,i){this.phraseStep=0,this.name=t,this.callback=e,this.sequence=i},t.Part=function(e,n){this.length=e||0,this.partStep=0,this.phrases=[],this.isPlaying=!1,this.noLoop(),this.tatums=n||.0625,this.metro=new t.Metro,this.metro._init(),this.metro.beatLength(this.tatums),this.metro.setBPM(o),i.parts.push(this),this.callback=function(){}},t.Part.prototype.setBPM=function(t,e){this.metro.setBPM(t,e)},t.Part.prototype.getBPM=function(){return this.metro.getBPM()},t.Part.prototype.start=function(t){if(!this.isPlaying){this.isPlaying=!0,this.metro.resetSync(this);var e=t||0;this.metro.start(e)}},t.Part.prototype.loop=function(t){this.looping=!0,this.onended=function(){this.partStep=0};var e=t||0;this.start(e)},t.Part.prototype.noLoop=function(){this.looping=!1,this.onended=function(){this.stop()}},t.Part.prototype.stop=function(t){this.partStep=0,this.pause(t)},t.Part.prototype.pause=function(t){this.isPlaying=!1;var e=t||0;this.metro.stop(e)},t.Part.prototype.addPhrase=function(e,i,n){var o;if(3===arguments.length)o=new t.Phrase(e,i,n);else{if(!(arguments[0]instanceof t.Phrase))throw"invalid input. addPhrase accepts name, callback, array or a p5.Phrase";o=arguments[0]}this.phrases.push(o),o.sequence.length>this.length&&(this.length=o.sequence.length)},t.Part.prototype.removePhrase=function(t){for(var e in this.phrases)this.phrases[e].name===t&&this.phrases.splice(e,1)},t.Part.prototype.getPhrase=function(t){for(var e in this.phrases)if(this.phrases[e].name===t)return this.phrases[e]},t.Part.prototype.replaceSequence=function(t,e){for(var i in this.phrases)this.phrases[i].name===t&&(this.phrases[i].sequence=e)},t.Part.prototype.incrementStep=function(t){this.partStep0&&o.iterations<=o.maxIterations&&o.callback(i)},frequency:this._calcFreq()})},t.SoundLoop.prototype.start=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying||(this.clock.start(n+i),this.isPlaying=!0)},t.SoundLoop.prototype.stop=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.stop(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.pause=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.pause(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.syncedStart=function(t,i){var n=i||0,o=e.audiocontext.currentTime;if(t.isPlaying){if(t.isPlaying){var r=t.clock._nextTick-e.audiocontext.currentTime;this.clock.start(o+r),this.isPlaying=!0}}else t.clock.start(o+n),t.isPlaying=!0,this.clock.start(o+n),this.isPlaying=!0},t.SoundLoop.prototype._update=function(){this.clock.frequency.value=this._calcFreq()},t.SoundLoop.prototype._calcFreq=function(){return"number"==typeof this._interval?(this.musicalTimeMode=!1,1/this._interval):"string"==typeof this._interval?(this.musicalTimeMode=!0,this._bpm/60/this._convertNotation(this._interval)*(this._timeSignature/4)):void 0},t.SoundLoop.prototype._convertNotation=function(t){var e=t.slice(-1);switch(t=Number(t.slice(0,-1)),e){case"m":return this._measure(t);case"n":return this._note(t);default:console.warn("Specified interval is not formatted correctly. See Tone.js timing reference for more info: https://github.com/Tonejs/Tone.js/wiki/Time")}},t.SoundLoop.prototype._measure=function(t){return t*this._timeSignature},t.SoundLoop.prototype._note=function(t){return this._timeSignature/t},Object.defineProperty(t.SoundLoop.prototype,"bpm",{get:function(){return this._bpm},set:function(t){this.musicalTimeMode||console.warn('Changing the BPM in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._bpm=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"timeSignature",{get:function(){return this._timeSignature},set:function(t){this.musicalTimeMode||console.warn('Changing the timeSignature in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._timeSignature=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"interval",{get:function(){return this._interval},set:function(t){this.musicalTimeMode="Number"==typeof t?!1:!0,this._interval=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"iterations",{get:function(){return this.clock.ticks}}),t.SoundLoop}(n,tt);var ot;ot=function(){"use strict";var e=X;return t.Compressor=function(){e.call(this),this.compressor=this.ac.createDynamicsCompressor(),this.input.connect(this.compressor),this.compressor.connect(this.wet)},t.Compressor.prototype=Object.create(e.prototype),t.Compressor.prototype.process=function(t,e,i,n,o,r){t.connect(this.input),this.set(e,i,n,o,r)},t.Compressor.prototype.set=function(t,e,i,n,o){"undefined"!=typeof t&&this.attack(t),"undefined"!=typeof e&&this.knee(e),"undefined"!=typeof i&&this.ratio(i),"undefined"!=typeof n&&this.threshold(n),"undefined"!=typeof o&&this.release(o)},t.Compressor.prototype.attack=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.attack.value=t,this.compressor.attack.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.attack.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.attack),this.compressor.attack.value},t.Compressor.prototype.knee=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.knee.value=t,this.compressor.knee.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.knee.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.knee),this.compressor.knee.value},t.Compressor.prototype.ratio=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.ratio.value=t,this.compressor.ratio.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.ratio.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.ratio),this.compressor.ratio.value},t.Compressor.prototype.threshold=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.threshold.value=t,this.compressor.threshold.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.threshold.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.threshold),this.compressor.threshold.value},t.Compressor.prototype.release=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.release.value=t,this.compressor.release.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.release.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof number&&t.connect(this.compressor.release),this.compressor.release.value},t.Compressor.prototype.reduction=function(){return this.compressor.reduction.value},t.Compressor.prototype.dispose=function(){e.prototype.dispose.apply(this),this.compressor&&(this.compressor.disconnect(),delete this.compressor)},t.Compressor}(n,X,r);var rt;rt=function(){function e(t,e){for(var i=t.length+e.length,n=new Float32Array(i),o=0,r=0;i>r;)n[r++]=t[o],n[r++]=e[o],o++;return n}function i(t,e,i){for(var n=i.length,o=0;n>o;o++)t.setUint8(e+o,i.charCodeAt(o))}var o=n,r=o.audiocontext;t.SoundRecorder=function(){this.input=r.createGain(),this.output=r.createGain(),this.recording=!1,this.bufferSize=1024,this._channels=2,this._clear(),this._jsNode=r.createScriptProcessor(this.bufferSize,this._channels,2),this._jsNode.onaudioprocess=this._audioprocess.bind(this),this._callback=function(){},this._jsNode.connect(t.soundOut._silentNode),this.setInput(),o.soundArray.push(this)},t.SoundRecorder.prototype.setInput=function(e){this.input.disconnect(),this.input=null,this.input=r.createGain(),this.input.connect(this._jsNode),this.input.connect(this.output),e?e.connect(this.input):t.soundOut.output.connect(this.input)},t.SoundRecorder.prototype.record=function(t,e,i){this.recording=!0,e&&(this.sampleLimit=Math.round(e*r.sampleRate)),t&&i?this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer),i()}:t&&(this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer)})},t.SoundRecorder.prototype.stop=function(){this.recording=!1,this._callback(),this._clear()},t.SoundRecorder.prototype._clear=function(){this._leftBuffers=[],this._rightBuffers=[],this.recordedSamples=0,this.sampleLimit=null},t.SoundRecorder.prototype._audioprocess=function(t){if(this.recording!==!1&&this.recording===!0)if(this.sampleLimit&&this.recordedSamples>=this.sampleLimit)this.stop();else{var e=t.inputBuffer.getChannelData(0),i=t.inputBuffer.getChannelData(1);this._leftBuffers.push(new Float32Array(e)),this._rightBuffers.push(new Float32Array(i)),this.recordedSamples+=this.bufferSize}},t.SoundRecorder.prototype._getBuffer=function(){var t=[];return t.push(this._mergeBuffers(this._leftBuffers)),t.push(this._mergeBuffers(this._rightBuffers)),t},t.SoundRecorder.prototype._mergeBuffers=function(t){for(var e=new Float32Array(this.recordedSamples),i=0,n=t.length,o=0;n>o;o++){var r=t[o];e.set(r,i),i+=r.length}return e},t.SoundRecorder.prototype.dispose=function(){this._clear();var t=o.soundArray.indexOf(this);o.soundArray.splice(t,1),this._callback=function(){},this.input&&this.input.disconnect(),this.input=null,this._jsNode=null},t.prototype.saveSound=function(n,o){var r,s;r=n.buffer.getChannelData(0),s=n.buffer.numberOfChannels>1?n.buffer.getChannelData(1):r;var a=e(r,s),u=new window.ArrayBuffer(44+2*a.length),c=new window.DataView(u);i(c,0,"RIFF"),c.setUint32(4,36+2*a.length,!0),i(c,8,"WAVE"),i(c,12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,2,!0),c.setUint32(24,44100,!0),c.setUint32(28,176400,!0),c.setUint16(32,4,!0),c.setUint16(34,16,!0),i(c,36,"data"),c.setUint32(40,2*a.length,!0);for(var p=a.length,h=44,l=1,f=0;p>f;f++)c.setInt16(h,a[f]*(32767*l),!0),h+=2;t.prototype.writeFile([c],o,"wav")}}(n);var st;st=function(){t.PeakDetect=function(t,e,i,n){this.framesPerPeak=n||20,this.framesSinceLastPeak=0,this.decayRate=.95,this.threshold=i||.35,this.cutoff=0,this.cutoffMult=1.5,this.energy=0,this.penergy=0,this.currentValue=0,this.isDetected=!1,this.f1=t||40,this.f2=e||2e4,this._onPeak=function(){}},t.PeakDetect.prototype.update=function(t){var e=this.energy=t.getEnergy(this.f1,this.f2)/255;e>this.cutoff&&e>this.threshold&&e-this.penergy>0?(this._onPeak(),this.isDetected=!0,this.cutoff=e*this.cutoffMult,this.framesSinceLastPeak=0):(this.isDetected=!1,this.framesSinceLastPeak<=this.framesPerPeak?this.framesSinceLastPeak++:(this.cutoff*=this.decayRate,this.cutoff=Math.max(this.cutoff,this.threshold))),this.currentValue=e,this.penergy=e},t.PeakDetect.prototype.onPeak=function(t,e){var i=this;i._onPeak=function(){t(i.energy,e)}}}();var at;at=function(){var e=n;t.Gain=function(){this.ac=e.audiocontext,this.input=this.ac.createGain(),this.output=this.ac.createGain(),this.input.gain.value=.5,this.input.connect(this.output),e.soundArray.push(this)},t.Gain.prototype.setInput=function(t){t.connect(this.input)},t.Gain.prototype.connect=function(e){var i=e||t.soundOut.input;this.output.connect(i.input?i.input:i)},t.Gain.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Gain.prototype.amp=function(t,i,n){var i=i||0,n=n||0,o=e.audiocontext.currentTime,r=this.output.gain.value;this.output.gain.cancelScheduledValues(o),this.output.gain.linearRampToValueAtTime(r,o+n),this.output.gain.linearRampToValueAtTime(t,o+n+i)},t.Gain.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.output&&(this.output.disconnect(),delete this.output),this.input&&(this.input.disconnect(),delete this.input)}}(n);var ut;ut=function(){var e=n;return t.AudioVoice=function(){this.ac=e.audiocontext,this.output=this.ac.createGain(),this.connect(),e.soundArray.push(this)},t.AudioVoice.prototype.play=function(t,e,i,n){},t.AudioVoice.prototype.triggerAttack=function(t,e,i){},t.AudioVoice.prototype.triggerRelease=function(t){},t.AudioVoice.prototype.amp=function(t,e){},t.AudioVoice.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.AudioVoice.prototype.disconnect=function(){this.output.disconnect()},t.AudioVoice.prototype.dispose=function(){this.output&&(this.output.disconnect(),delete this.output)},t.AudioVoice}(n);var ct;ct=function(){var e=n,i=ut,r=o.noteToFreq,s=.15;t.MonoSynth=function(){i.call(this),this.oscillator=new t.Oscillator,this.env=new t.Envelope,this.env.setRange(1,0),this.env.setExp(!0),this.setADSR(.02,.25,.05,.35),this.filter=new t.Filter("highpass"),this.filter.set(5,1),this.oscillator.disconnect(),this.oscillator.connect(this.filter),this.env.disconnect(),this.env.setInput(this.oscillator),this.filter.connect(this.output),this.oscillator.start(),this.connect(),this._isOn=!1,e.soundArray.push(this)},t.MonoSynth.prototype=Object.create(t.AudioVoice.prototype),t.MonoSynth.prototype.play=function(t,e,i,n){this.triggerAttack(t,e,~~i),this.triggerRelease(~~i+(n||s))},t.MonoSynth.prototype.triggerAttack=function(t,e,i){var i=~~i,n=r(t),o=e||.1;this._isOn=!0,this.oscillator.freq(n,0,i),this.env.ramp(this.output,i,o)},t.MonoSynth.prototype.triggerRelease=function(t){var t=t||0;this.env.ramp(this.output,t,0),this._isOn=!1},t.MonoSynth.prototype.setADSR=function(t,e,i,n){this.env.setADSR(t,e,i,n)},Object.defineProperties(t.MonoSynth.prototype,{attack:{get:function(){return this.env.aTime},set:function(t){this.env.setADSR(t,this.env.dTime,this.env.sPercent,this.env.rTime)}},decay:{get:function(){return this.env.dTime},set:function(t){this.env.setADSR(this.env.aTime,t,this.env.sPercent,this.env.rTime)}},sustain:{get:function(){return this.env.sPercent},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,t,this.env.rTime)}},release:{get:function(){return this.env.rTime},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,this.env.sPercent,t)}}}),t.MonoSynth.prototype.amp=function(t,e){var i=e||0;return"undefined"!=typeof t&&this.oscillator.amp(t,i),this.oscillator.amp().value},t.MonoSynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.MonoSynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.MonoSynth.prototype.dispose=function(){i.prototype.dispose.apply(this),this.filter&&this.filter.dispose(),this.env&&this.env.dispose(),this.oscillator&&this.oscillator.dispose()}}(n,ut,o);var pt;pt=function(){var e=n,i=F,r=o.noteToFreq;t.PolySynth=function(n,o){this.audiovoices=[],this.notes={},this._newest=0,this._oldest=0,this.maxVoices=o||8,this.AudioVoice=void 0===n?t.MonoSynth:n,this._voicesInUse=new i(0),this.output=e.audiocontext.createGain(),this.connect(),this._allocateVoices(),e.soundArray.push(this)},t.PolySynth.prototype._allocateVoices=function(){for(var t=0;tf?f:p}this.audiovoices[a].triggerAttack(c,p,s)},t.PolySynth.prototype._updateAfter=function(t,e){if(null!==this._voicesInUse._searchAfter(t)){this._voicesInUse._searchAfter(t).value+=e;var i=this._voicesInUse._searchAfter(t).time;this._updateAfter(i,e)}},t.PolySynth.prototype.noteRelease=function(t,i){var n=e.audiocontext.currentTime,o=i||0,s=n+o;if(t){var a=r(t);if(this.notes[a]&&null!==this.notes[a].getValueAtTime(s)){var u=Math.max(~~this._voicesInUse.getValueAtTime(s).value,1);this._voicesInUse.setValueAtTime(u-1,s),u>0&&this._updateAfter(s,-1),this.audiovoices[this.notes[a].getValueAtTime(s)].triggerRelease(o),this.notes[a].dispose(),delete this.notes[a],this._newest=0===this._newest?0:(this._newest-1)%(this.maxVoices-1)}else console.warn("Cannot release a note that is not already playing")}else{this.audiovoices.forEach(function(t){t.triggerRelease(o)}),this._voicesInUse.setValueAtTime(0,s);for(var c in this.notes)this.notes[c].dispose(),delete this.notes[c]}},t.PolySynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.PolySynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.PolySynth.prototype.dispose=function(){this.audiovoices.forEach(function(t){t.dispose()}),this.output&&(this.output.disconnect(),delete this.output)}}(n,F,o);var ht;ht=function(){function e(t){for(var e,i="number"==typeof t?t:50,n=44100,o=new Float32Array(n),r=Math.PI/180,s=0;n>s;++s)e=2*s/n-1,o[s]=(3+i)*e*20*r/(Math.PI+i*Math.abs(e));return o}var i=X;t.Distortion=function(n,o){if(i.call(this),"undefined"==typeof n&&(n=.25),"number"!=typeof n)throw new Error("amount must be a number");if("undefined"==typeof o&&(o="2x"),"string"!=typeof o)throw new Error("oversample must be a String");var r=t.prototype.map(n,0,1,0,2e3);this.waveShaperNode=this.ac.createWaveShaper(),this.amount=r,this.waveShaperNode.curve=e(r),this.waveShaperNode.oversample=o,this.input.connect(this.waveShaperNode),this.waveShaperNode.connect(this.wet)},t.Distortion.prototype=Object.create(i.prototype),t.Distortion.prototype.process=function(t,e,i){t.connect(this.input),this.set(e,i)},t.Distortion.prototype.set=function(i,n){if(i){var o=t.prototype.map(i,0,1,0,2e3);this.amount=o,this.waveShaperNode.curve=e(o)}n&&(this.waveShaperNode.oversample=n)},t.Distortion.prototype.getAmount=function(){return this.amount},t.Distortion.prototype.getOversample=function(){return this.waveShaperNode.oversample},t.Distortion.prototype.dispose=function(){i.prototype.dispose.apply(this),this.waveShaperNode&&(this.waveShaperNode.disconnect(),this.waveShaperNode=null)}}(X);var lt;lt=function(){var t=n;return t}(e,i,n,o,r,s,a,u,c,P,k,q,M,V,E,Y,W,Q,H,$,J,et,it,nt,ot,rt,st,at,ct,pt,ht,ut,ct,pt)}); \ No newline at end of file diff --git a/sketch.js b/sketch.js new file mode 100644 index 0000000..9a72b1b --- /dev/null +++ b/sketch.js @@ -0,0 +1,782 @@ +var floorPos_y; +var cameraPosX; +var processStop_timer; + +var gameChar; + +var gravity; +var game_score; +var finish_position_x; + +var trees_x = []; +var clouds = []; +var mountains = []; +var collectables = []; +var canyons = []; +var flagpole; + +var text_size; +// Variables to set colors. Set in setup() +var palette; + +function setup() { + createCanvas(1024, 576); + palette = { + body_color: color("white"), + head_color: color("darkgreen"), + sky_color: color("#8E9887"), + ground_color0: color("#684622"), + ground_color1: color("#734E26"), + ground_color2: color("#7F562A"), + canyon_river_color: color("#56C525"), + canyon_river_wave_color: color("#4BAD21"), + canyon_color: color("#7B672A"), + pine_leaves_color: color("#3F4834"), + maple_leaves_color: color("#4E3D1F"), + pine_stem: color("#644D0D"), + maple_stem: color("#936907"), + mountain: color("#5a5a5a"), + mountain_shadow: color("#3c3c3c"), + cloud0: color(200), + cloud1: color(220), + cloud2: color(255), + coin_outer: color("#FDC334"), + coin_middle: color("#ababab"), + coin_inner: color("#FDC334"), + heart_color: color("darkred"), + enemy_head_color: color("red"), + enemy_body_color: color("red"), + }; + startGame((full_start = true), (update_objects = true)); +} +function startGame(full_start, update_objects) { + floorPos_y = 432; + cameraPosX = 0; + + if (full_start) { + gameChar = { + x: width / 2, + y: floorPos_y + (height - floorPos_y) / 6, + x_step: 5, + y_step: 8, + scale: 1, + sprite: 1, + speed: 5, + baseLives: 3, + curLives: 3, + isRight: false, + isLeft: false, + isFalling: false, + isJumping: false, + isPlummeting: false, + possibleGroundPosY: [ + floorPos_y + (height - floorPos_y) / 6, + floorPos_y + (3 * (height - floorPos_y)) / 6, + floorPos_y + (5 * (height - floorPos_y)) / 6, + ], + curGroundPosYIndex: 0, + + getCurGroundPosY() { + return this.possibleGroundPosY[this.curGroundPosYIndex]; + }, + goUp() { + memorizedIndex = this.curGroundPosYIndex; + this.curGroundPosYIndex = max(0, this.curGroundPosYIndex - 1); + if (memorizedIndex != this.curGroundPosYIndex) { + gameChar.y -= (height - floorPos_y) / 3; + gameChar.scale -= 0.1; + } + }, + goDown() { + memorizedIndex = this.curGroundPosYIndex; + this.curGroundPosYIndex = min( + this.possibleGroundPosY.length - 1, + this.curGroundPosYIndex + 1 + ); + if (memorizedIndex != this.curGroundPosYIndex) { + gameChar.y += (height - floorPos_y) / 3; + gameChar.scale += 0.1; + } + }, + }; + } else { + gameChar.x = width / 2; + gameChar.y = floorPos_y + (height - floorPos_y) / 6; + gameChar.scale = 1; + gameChar.curGroundPosYIndex = 0; + gameChar.isPlummeting = false; + gameChar.isFalling = false; + gameChar.isJumping = false; + gameChar.isLeft = false; + gameChar.isRight = false; + } + + gravity = 1; + game_score = 0; + finish_position_x = 2000; + + if (update_objects || full_start) { + // Assigning values of trees, clouds, mountains, canyons, collectables. + for (i = 0; i < 150; i++) { + trees_x[i] = random(-100, 10000); + } + for (i = 0; i < 100; i++) { + clouds[i] = { + x: random(-100, 10000), + y: random(0, floorPos_y / 2), + size: random(0.4, 2), + }; + } + // Latter mountains. + for (i = 0; i < finish_position_x / 90; i++) { + mountains[i] = { + x: random(-200, finish_position_x + 200), + width: random(60, 150), + height: random(floorPos_y - 50, floorPos_y - 150), + skew: random(-20, 20), + }; + // To prevent spiky mountains which are quite ugly + mountains[i].height = max(mountains[i].width, mountains[i].height); + } + // Start mountains. + for (i = 0; i < 6; i++) { + mountains[i] = { + x: width / (i + 1.5), + width: width / (i + random(2, 4)), + height: height / (2 + 0.8 * i), + skew: (random(-10, 20) * i) / 2, + }; + } + for (i = 0; i < 100; i++) { + if (i == 0) { + canyons[0] = { + x: 700, + width: 50, + points: [], + }; + } else + canyons[i] = { + x: canyons[i - 1].x + 300 + 200 * random(0.5, 1), + width: 50 + 30 * random(), + points: [], + }; + } + for (i = 0; i < 100; i++) { + if (i == 0) { + collectables[0] = { + x: 600, + y_pos: floorPos_y, + size: 50, + isFound: false, + }; + } else + collectables[i] = { + x: collectables[i - 1].x + 50 + 150 * random(0.5, 1), + y_pos: gameChar.possibleGroundPosY[ + random(0, gameChar.possibleGroundPosY.length) + ], + size: 50, + isFound: false, + }; + } + } + flagpole = { + x: finish_position_x, + isReached: false, + size_vert: 4, + size_hor: 7, + cell_size: 20, + cell_size_v: 20, + cell_size_h: 20, + }; + text_size = width / 20; + textSize(text_size); +} +function draw() { + // -------- SKY ---------------- + background(palette.sky_color); + + // -------- GROUND ------------- + drawGround(); + + push(); // Scrolling + fill(0); + + translate(-cameraPosX, 0); // Scrolling + cameraPosX = gameChar.x - width / 2; // Scrolling + + // -------- CLOUDS -------------- + drawClouds(); + // -------- MOUNTAINS ----------- + drawMountains(); + // -------- CANYONS ------------- + for (i = 0; i < canyons.length; i++) { + canyon = canyons[i]; + drawCanyon(canyon); + if (!gameChar.isFalling && !gameChar.isJumping) checkCanyon(canyon); + } + // -------- TREES --------------- + drawTrees(); + // -------- COLLECTABLES -------- + for (i = 0; i < collectables.length; i++) { + collectable = collectables[i]; + if (!collectable.isFound) drawCollectable(collectable); + checkCollectable(collectable); + } + // -------- FLAGPOLE ------------ + renderFlagpole(); + if (!flagpole.isReached) checkFlagpole(); + + // -------- GAME CHARACTER ------ + { + // Behavior + if (!gameChar.isPlummeting) { + if (gameChar.isLeft && !gameChar.isRight) { + gameChar.x -= gameChar.speed; + } else if (gameChar.isRight && !gameChar.isLeft) { + gameChar.x += gameChar.speed; + } + + if (gameChar.isJumping) { + gameChar.y -= gameChar.jumpingStrength; + gameChar.jumpingStrength -= gravity; + if (gameChar.jumpingStrength <= 0) { + gameChar.isFalling = true; + gameChar.isJumping = false; + } + } else if (gameChar.isFalling) { + gameChar.y -= gameChar.jumpingStrength; + gameChar.jumpingStrength -= gravity; + if (gameChar.y >= gameChar.getCurGroundPosY()) { + gameChar.y = gameChar.getCurGroundPosY(); + gameChar.isFalling = false; + } + } else { + } + } + checkPlayerDie(); + // Setting sprite + { + if (gameChar.isPlummeting) { + gameChar.sprite = 2; + } else if (gameChar.isFalling) { + gameChar.sprite = 2; + if (gameChar.isLeft && !gameChar.isRight) gameChar.sprite = 5; + else if (gameChar.isRight && !gameChar.isLeft) + gameChar.sprite = 6; + } else { + if (gameChar.isLeft && !gameChar.isRight) gameChar.sprite = 4; + else if (gameChar.isRight && !gameChar.isLeft) + gameChar.sprite = 3; + else gameChar.sprite = 1; + } + } + // Depicting plummeting + if (gameChar.isPlummeting) { + gameChar.y += 3; + } + // Drawing a sprite + drawGameCharacter(); + } + pop(); // Scrolling + // -------- INTERFACE ----------- + push(); + fill(0); + text("Score: " + game_score, 12, text_size); + drawLives(); + if (gameChar.curLives < 1) + text("Game over. Press space to continue...", 0, height / 2); + else if (flagpole.isReached) + text("Level complete. Press space to continue...", 0, height / 2); + text(gameChar.curGroundPosYIndex, 99, 99); + text(gameChar.getCurGroundPosY(), 188, 99); + text(gameChar.sprite, 277, 99); + pop(); +} + +function drawGameCharacter() { + strokeWeight(1); + stroke(1); + gameChar.x_step *= gameChar.scale; + gameChar.y_step *= gameChar.scale; + function _drawBody(jumping = false) { + fill(palette.body_color); + if (jumping) { + triangle( + gameChar.x - gameChar.x_step * 2, + gameChar.y - gameChar.y_step * 1.5, + gameChar.x, + gameChar.y - gameChar.y_step * 4, + gameChar.x + gameChar.x_step * 2, + gameChar.y - gameChar.y_step * 1.5 + ); + } else { + triangle( + gameChar.x - gameChar.x_step * 2, + gameChar.y, + gameChar.x, + gameChar.y - gameChar.y_step * 4, + gameChar.x + gameChar.x_step * 2, + gameChar.y + ); + } + } + function _drawHead() { + fill(palette.head_color); + ellipse( + gameChar.x, + gameChar.y - gameChar.y_step * 5, + gameChar.x_step * 6, + gameChar.y_step * 4 + ); + } + function _drawEyes(draw_left, draw_right, eyes_height) { + fill(0); + if (draw_left) { + ellipse( + gameChar.x - gameChar.x_step * 1.2, + gameChar.y - gameChar.y_step * eyes_height, + gameChar.x_step / 1.5, + gameChar.y_step / 2 + ); + } + if (draw_right) { + ellipse( + gameChar.x + gameChar.x_step * 1.2, + gameChar.y - gameChar.y_step * eyes_height, + gameChar.x_step / 1.5, + gameChar.y_step / 2 + ); + } + } + // Standing, facing frontwards + if (gameChar.sprite == 1) { + // Body + _drawBody(); + // Head + _drawHead(); + // Eyes + _drawEyes(true, true, 4.2); + } + // Jumping, facing forwards + else if (gameChar.sprite == 2) { + // Body + _drawBody(true); + // Hands. (Hands!) + line( + gameChar.x - gameChar.x_step * 1, + gameChar.y - gameChar.y_step * 2.5, + gameChar.x - gameChar.x_step * 3.2, + gameChar.y - gameChar.y_step * 3.2 + ); + line( + gameChar.x + gameChar.x_step * 1, + gameChar.y - gameChar.y_step * 2.5, + gameChar.x + gameChar.x_step * 3.2, + gameChar.y - gameChar.y_step * 3.2 + ); + // Head + _drawHead(); + // Eyes + _drawEyes(true, true, 3.8); + } + // Walking right + else if (gameChar.sprite == 3) { + // Body + _drawBody(); + // Hand. (Hand!) + line( + gameChar.x, + gameChar.y - gameChar.y_step * 2.5, + gameChar.x + gameChar.x_step * 0.8, + gameChar.y - gameChar.y_step * 1 + ); + // Head + _drawHead(); + // Eyes + _drawEyes(false, true, 4.2); + } + // Walking left + else if (gameChar.sprite == 4) { + // Body + _drawBody(); + // Hand. (Hand!) + line( + gameChar.x, + gameChar.y - gameChar.y_step * 2.5, + gameChar.x - gameChar.x_step * 0.8, + gameChar.y - gameChar.y_step * 1 + ); + // Head + _drawHead(); + // Eyes + _drawEyes(true, false, 4.2); + } + // Jumping left + else if (gameChar.sprite == 5) { + // Body + _drawBody(true); + // Hands. (Hands!) + line( + gameChar.x - gameChar.x_step * 1, + gameChar.y - gameChar.y_step * 2.5, + gameChar.x - gameChar.x_step * 3.2, + gameChar.y - gameChar.y_step * 3.2 + ); + line( + gameChar.x + gameChar.x_step * 1, + gameChar.y - gameChar.y_step * 2.5, + gameChar.x + gameChar.x_step * 3.2, + gameChar.y - gameChar.y_step * 3.2 + ); + // Head + _drawHead(); + // Eyes + _drawEyes(true, false, 3.8); + } + // Jumping right + else if (gameChar.sprite == 6) { + // Body + _drawBody(true); + // Hands. (Hands!) + line( + gameChar.x - gameChar.x_step * 1, + gameChar.y - gameChar.y_step * 2.5, + gameChar.x - gameChar.x_step * 3.2, + gameChar.y - gameChar.y_step * 3.2 + ); + line( + gameChar.x + gameChar.x_step * 1, + gameChar.y - gameChar.y_step * 2.5, + gameChar.x + gameChar.x_step * 3.2, + gameChar.y - gameChar.y_step * 3.2 + ); + // Head + _drawHead(); + // Eyes + _drawEyes(false, true, 3.8); + } else { + text("Bad sprite number!", 10, 10); + console.error("Bad gameChar sprite number: " + gameChar.sprite); + } + gameChar.x_step /= gameChar.scale; + gameChar.y_step /= gameChar.scale; +} +function checkCanyon(t_canyon) { + if ( + gameChar.x > canyon.x - canyon.width / 2 && + gameChar.x < canyon.x + canyon.width / 2 + ) { + gameChar.isPlummeting = true; + } +} +function checkCollectable(t_collectable) { + if ( + !t_collectable.isFound && + collectable.y_pos == gameChar.getCurGroundPosY() && + dist( + t_collectable.x, + t_collectable.y_pos, + gameChar.x, + gameChar.y - gameChar.x_step * 4 + ) < + t_collectable.size / 2 + ) { + t_collectable.isFound = true; + game_score++; + } +} +function drawGround() { + push(); + noStroke(); + fill(palette.ground_color0); + rect(0, floorPos_y, width, height - floorPos_y); + fill(palette.ground_color1); + rect( + 0, + floorPos_y + (2 * (height - floorPos_y)) / 6, + width, + floorPos_y + (2 * (height - floorPos_y)) / 6 + ); + fill(palette.ground_color2); + rect( + 0, + floorPos_y + (4 * (height - floorPos_y)) / 6, + width, + floorPos_y + (4 * (height - floorPos_y)) / 6 + ); + stroke(1); + translate(-cameraPosX, 0); + for (i = 0; i < finish_position_x; i += 20) { + line( + i, + floorPos_y + (2 * (height - floorPos_y)) / 6, + i + 1, + floorPos_y + (2 * (height - floorPos_y)) / 6 + ); + line( + i, + floorPos_y + (4 * (height - floorPos_y)) / 6, + i + 1, + floorPos_y + (4 * (height - floorPos_y)) / 6 + ); + } + pop(); +} +function drawCanyon(t_canyon) { + push(); + fill(palette.canyon_river_color); + rect(t_canyon.x - t_canyon.width / 2, floorPos_y, t_canyon.width, height); + if (frameCount % 4 == 0) { + PointX = random( + t_canyon.x - t_canyon.width / 2, + t_canyon.x + t_canyon.width / 2 + ); + PointY = random(floorPos_y, height); + if (t_canyon.points.length > 3) { + t_canyon.points.shift(); + } + t_canyon.points.add((PointX, PointY)); + } + + stroke(palette.canyon_river_wave_color); + strokeWeight(5); + line(PointX, PointY, PointX, PointY + random(20, 100)); + pop(); +} +function drawCollectable(t_collectable) { + stroke(0.2); + fill(palette.coin_outer); + ellipse(t_collectable.x, t_collectable.y_pos, 0.7 * t_collectable.size); + fill(palette.coin_middle); + ellipse(t_collectable.x, t_collectable.y_pos, 0.6 * t_collectable.size); + fill(palette.coin_inner); + ellipse(t_collectable.x, t_collectable.y_pos, 0.5 * t_collectable.size); +} +function drawClouds() { + for (i = 0; i < clouds.length; i++) { + push(); + translate((frameCount / clouds[i].y) * 20, 0); // imitating clouds movement, upper ones should go faster + noStroke(); + fill(palette.cloud0); + ellipse( + clouds[i].x - 20, + clouds[i].y - 10, + 20 * clouds[i].size, + 30 * clouds[i].size + ); + fill(palette.cloud1); + ellipse( + clouds[i].x + 20, + clouds[i].y - 20, + 70 * clouds[i].size, + 50 * clouds[i].size + ); + fill(palette.cloud2); + ellipse( + clouds[i].x, + clouds[i].y, + 90 * clouds[i].size, + 40 * clouds[i].size + ); + ellipse( + clouds[i].x + 45, + clouds[i].y - 10, + 50 * clouds[i].size, + 35 * clouds[i].size + ); + pop(); + } +} +function drawMountains() { + for (i = 0; i < mountains.length; i++) { + noStroke(); + + fill(palette.mountain_shadow); + triangle( + mountains[i].x - mountains[i].width, + floorPos_y, + mountains[i].x + mountains[i].skew, + mountains[i].height, + mountains[i].x + mountains[i].width, + floorPos_y + ); + fill(palette.mountain); + triangle( + mountains[i].x - mountains[i].width, + floorPos_y, + mountains[i].x + mountains[i].skew, + mountains[i].height, + mountains[i].x - mountains[i].width / 1.5, + floorPos_y + ); + } +} +function drawHeart(isEmpty, x, y, size) { + push(); + if (isEmpty) { + noFill(); + stroke(0); + } else { + fill(palette.heart_color); + stroke(palette.heart_color); + } + triangle(x, y, x + size, y - size, x + size * 2, y); + triangle(x - size * 2, y, x - size, y - size, x, y); + triangle(x, y, x + size, y + size, x - size, y + size); + triangle(x - size * 2, y, x, y + size * 2, x + size * 2, y); + pop(); +} +function drawLives() { + push(); + stroke(255, 0, 0); + noFill(); + var heart_size = 20; + for (i = gameChar.baseLives; i > 0; i--) { + drawHeart( + true, + width - i * heart_size * 4.5, + heart_size * 1.5, + heart_size + ); + } + for (i = gameChar.curLives; i > 0; i--) { + drawHeart( + false, + width - i * heart_size * 4.5, + heart_size * 1.5, + heart_size + ); + } + pop(); +} +function drawTrees() { + for (i = 0; i < trees_x.length; i++) { + // Draw pine in case the integer part of tree + // coordinate is even. + if (Math.trunc(trees_x[i]) % 2 == 0) { + fill(palette.pine_stem); + triangle( + trees_x[i] - 15, + floorPos_y, + trees_x[i], + floorPos_y - 150, + trees_x[i] + 15, + floorPos_y + ); + fill(palette.pine_leaves_color); + triangle( + trees_x[i] - 45, + floorPos_y - 45, + trees_x[i], + floorPos_y - 120, + trees_x[i] + 45, + floorPos_y - 45 + ); + triangle( + trees_x[i] - 45, + floorPos_y - 85, + trees_x[i], + floorPos_y - 180, + trees_x[i] + 45, + floorPos_y - 85 + ); + } + // Draw maple + else { + fill(palette.maple_stem); + triangle( + trees_x[i] - 10, + floorPos_y, + trees_x[i], + floorPos_y - 120, + trees_x[i] + 10, + floorPos_y + ); + fill(palette.maple_leaves_color); + ellipse(trees_x[i], floorPos_y - 50, 80, 30); + ellipse(trees_x[i], floorPos_y - 70, 100, 30); + ellipse(trees_x[i], floorPos_y - 90, 80, 30); + ellipse(trees_x[i], floorPos_y - 110, 40, 30); + } + } +} +function renderFlagpole() { + // NB - This function is implemented a bit differently than how it was requested in Part 6. + // It has no states to switch between - instead, the flag gradually goes into the opposite direction + // as the player crosses it, what is done by manipulating flagpole's parameters. + // This is done for animation purposes. + + push(); + strokeWeight(0); + fill(0); + + // Movement animation, as mentioned in NB. + if (flagpole.isReached && flagpole.cell_size_h > -flagpole.cell_size) + flagpole.cell_size_h -= 0.8; + // the flagpole pole + rect(flagpole.x, floorPos_y / 2, 2, floorPos_y / 2); + + // the flagpole flag + for (i = 0; i < flagpole.size_hor; i++) { + for (j = 0; j < flagpole.size_vert; j++) { + fill(((i + j) % 2) * 255); + rect( + flagpole.x + flagpole.cell_size_h * i, + floorPos_y / 2 + flagpole.cell_size_v * j, + flagpole.cell_size_h, + flagpole.cell_size_v + ); + } + } + pop(); +} +function checkFlagpole() { + // Considering the linear nature of the game, the flagpole is triggered whenever player is beyond it by x. + // If to imagine a hypothetical jump where the player somehow jumps beyond the pole in one frame, + // this function will trigger anyway. + if (gameChar.x >= finish_position_x) { + flagpole.isReached = true; + } +} +function checkPlayerDie() { + if (gameChar.y >= height) { + if (gameChar.curLives > 1) { + gameChar.curLives--; + startGame(); + } else if (gameChar.curLives == 1) { + gameChar.curLives--; + } else { + gameChar.curLives = 0; + } + } +} + +function keyPressed() { + console.log(frameCount + " pressed " + key + " " + keyCode); + if (gameChar.curLives < 1 || flagpole.isReached) { + if (keyCode == 32 /*Space*/) { + /*Hard resets the game*/ + startGame((full_start = true), (update_objects = true)); + } + } else if (!gameChar.isPlummeting) { + if (keyCode == 65 /*A*/) gameChar.isLeft = true; + if (keyCode == 68 /*D*/) gameChar.isRight = true; + if (keyCode == 83 /*S*/) gameChar.goDown(); + if (keyCode == 87 /*W*/) gameChar.goUp(); + // Rewrote jumping routine to make it more natural and be able to support platforms and different player dimensions + if ( + keyCode == 32 /*Space*/ && + !gameChar.isFalling && + !gameChar.isJumping + ) { + gameChar.isJumping = true; + gameChar.jumpingStrength = 15; + } + } +} +function keyReleased() { + console.log(frameCount + " released " + key + " " + keyCode); + if (keyCode == 65 /*A*/) gameChar.isLeft = false; + if (keyCode == 68 /*D*/) gameChar.isRight = false; +}