diff --git a/ApfelGrotezk-Regular.ttf b/ApfelGrotezk-Regular.ttf new file mode 100644 index 0000000..f8be438 Binary files /dev/null and b/ApfelGrotezk-Regular.ttf differ diff --git a/ApfelGrotezk-Regular.woff b/ApfelGrotezk-Regular.woff new file mode 100644 index 0000000..50a35f9 Binary files /dev/null and b/ApfelGrotezk-Regular.woff differ diff --git a/ApfelGrotezk-Regular.woff2 b/ApfelGrotezk-Regular.woff2 new file mode 100644 index 0000000..fd6d87f Binary files /dev/null and b/ApfelGrotezk-Regular.woff2 differ diff --git a/INTRO.gif b/INTRO.gif new file mode 100644 index 0000000..b030c60 Binary files /dev/null and b/INTRO.gif differ diff --git a/canvas.js b/canvas.js new file mode 100644 index 0000000..0e84d95 --- /dev/null +++ b/canvas.js @@ -0,0 +1,579 @@ +function fontRead(){ + fontReady = true; +} + + + + + +function preload() { + + footsteps = document.getElementById("footsteps");//walking +PNF1 = document.getElementById("PNF1"); + + +myFont = loadFont("ApfelGrotezk-Regular.ttf", fontRead); + myFont2 = loadFont("typefaces/TINY5x3-40.ttf", fontRead); + myFont3 = loadFont("typefaces/TINY5x3-60.ttf", fontRead); + myFont4 = loadFont("typefaces/TINY5x3-80.ttf", fontRead); + myFont5 = loadFont("typefaces/TINY5x3-100.ttf", fontRead); + myFont6 = loadFont("typefaces/TINY5x3-120.ttf", fontRead); + myFont7 = loadFont("typefaces/TINY5x3-140.ttf", fontRead); + myFont8 = loadFont("typefaces/TINY5x3-160.ttf", fontRead); + myFont9 = loadFont("typefaces/TINY5x3-180.ttf", fontRead); + myFont10 = loadFont("typefaces/TINY5x3-200.ttf", fontRead); + myFont11 = loadFont("typefaces/TINY5x3-220.ttf", fontRead); + myFont12 = loadFont("typefaces/TINY5x3-240.ttf", fontRead); + myFont13 = loadFont("typefaces/TINY5x3-260.ttf", fontRead); + myFont14 = loadFont("typefaces/TINY5x3-280.ttf", fontRead); + + sou = PNF1 +}; + + + + + +// Place not found 1 +// Place not found 2 +// Lobster Lounge 1 +// Lobster Lounge 1 +// The Secret Garden +// Sonic the Sellout1 +// Sonic the Sellout 2 +// Pigeon Plaza 1 +// Pigeon Plaza 2 + + +p5.disableFriendlyErrors = true; + +var canvas; + +var hit = false; + +//little ball +var ballX = Math.random() * window.innerWidth; //set starting point of ball +var ballY = Math.random() * window.innerHeight; +var ballwidth = 35;//set size of ball +var ballheight = 35; + +var ballDirectionX = -1; +var ballDirectionY = -1; +var ballSpeed = 5; + +//player1 is CPU +var p1X = 5;//set a distance from left border*** +var p1Y = 250; +var cpuSpeed = 40; + +//player 2 +var p2X = -5;//set a distance from right border*** +var p2Y = -5; + +//player 2 +var p3X = -20;//set a distance from right border*** +var p3Y = -20; + + +//playersize +var playerWidth = 10; +var playerHeight = 200; +var pSpeed = 15; + +//scoreboard +var p1Score = 0; +var p2Score = 0; + +//FUNCTIONS +var stage = 0; +//0 =splash +//1 =pong + +var coordinateX = Math.random() * window.innerWidth; +var coordinateY = Math.random() * window.innerHeight; + +var letterSize = 50; + + +var myFont, fontReady = false; +var clicks = 0; +var song; + +var hit = false; + +var inside = false; + +var capture = true; + + +var r = 0; +var g = 0; +var b = 0; + +var col = 0; + +var img; + + +//var _createImg2; +//let cheatcode = ''; + +//var sliderRate, +//var sliderPan; + +function setup() { + + + // // console.log(coordinateX); + createCanvas(windowWidth, windowHeight).position(0,0).style('z-index','-10').style('display','fixed'); + width = windowWidth; + height = windowHeight; + rectMode(CENTER); + textSize(30); + //textalignment + textAlign(CENTER); + //img = loadImage =('INTRO.gif'); +} + + + +// function loaded(){ +// song.play(); +// } + +function draw(){ + + footsteps.play(); + + //pong(); //run pong function + if (stage == 0){ + splash1();//run splash1 + } + if(stage == 0 && clicks== 2){ + stage = 1;//startslide1 + document.getElementById("GIF").style.visibility = "hidden"; + }//close 0 + if (stage == 1){ + splash2();//run splash2 + } + if(stage == 1 && clicks == 3){ + stage = 2;//run splash2 + }//close 1 + + if (stage == 2){ + splash3();//run splash3 + } + if(stage == 2 && clicks == 4){ + stage = 3;//run splash3 + }//close 2 + + if (stage == 3){ + splash4();//run splash4 + } + if(stage == 3 && clicks == 5){ + stage = 4;//run splash4 + }//close 3 + if (stage == 4){ + hideSplash(); // added by mb + pong();//run pong + noStroke(); + fill(255); + textSize(80); + textAlign(CENTER, CENTER); + //displaying number of clicks + //text(clicks, width/2, height/2); + }//close 2 + + if(stage == 6){ //player 1 wins + p1Wins(); + }//close 3 + + if(stage == 7){ //player 2 wins + p2Wins(); + }//close 4 + + + +}//close draw + +function keyPressed() { + // console.log('keyPressed: ' + key); +} + +function keyPressed() { + // console.log('keyPressed: ' + key); +} + +function keyReleased() { + // console.log('keyReleased: ' + key); +} + +function keyTyped(){ + // cheatcode += key; + // console.log('keyTyped: ' + key); +} + +function mousePressed(){ + // console.log('mousePressed'); + clicks ++; + capture = true; +} + +function mouseReleased(){ + console.log('mouseReleased'); + capture = false; +} + +function mouseClicked(){ + // console.log('mouseClicked'); +} + +function mouseMoved(){ + // console.log('mouseMoved'); +} + +function mouseDragged(){ + // console.log('mouseDragged'); +} + +function mouseWheel(){ + // console.log('mouseWheel'); +} + +function displayInSplash(html){ + var textcontainer = document.getElementById("textcontainer"); + textcontainer.innerHTML = html; + textcontainer.style.display = "block"; // show the textcontainer +} +function hideSplash(){ + var textcontainer = document.getElementById("textcontainer"); + textcontainer.style.display = "none"; // hide the textcontainer +} + +function splash1(){ + var html = "Tap or Click anywhere to start"; + displayInSplash(html); + fill(255); +} +function splash2(){ + var html = 'You are the ball in a city-based pinball game.

Bounce from bumper to bumper.

Unlock secrets and surprises.

Drift through our urban playfield.'; + displayInSplash(html); + background(255); +} + +function splash3(){ + //welcome screen + var html = " 1. Walk through the city using the coordinates (hints) given in this website.

2. Once you arrive, open your Wi-Fi settings and connect to the hotspot whose name you'll also find here.

3. Go to your web browser and type the name of the hotspot as a url: name.wlan/.

A hotspot is a local wireless access point. Within the context of this issue, however, a hotspot is not a regular Wi-Fi connection: it doesn't connect you to the Internet, but, instead, to our pinball game."; + displayInSplash(html); + background(255); +} + +function splash4(){ + //welcome screen + var html = 'Tap anywhere to launch a ball!'; + displayInSplash(html); + background(255); +} + + +function p1Wins(){ + //P1 Win screen + r = map(mouseX, 0, windowHeight, 0, 255); + g = map(mouseY, 0, windowHeight, 255, 0); + b = map(mouseX, 0, windowWidth, 0, 255); +// col = mouseX/2; + background(r, g, b); + fill(255); + textSize(25); + textFont(myFont); + text('Refresh to launch a new ball', width/2, height/2); + + +}//close P1 + + +function p2Wins(){ + //P2 Win screen + background(163); + fill(255); + + textSize(20); + textFont(myFont); + text('Refresh to launch a new ball', width/2, height/2); +}//close P2 + + +function windowResized() { + resizeCanvas(windowWidth, windowHeight); +} + +function ball(){ + ballX = ballX + (ballDirectionX*ballSpeed);//move horizontally + ballY = ballY + (ballDirectionY*ballSpeed);//move vertically + + noStroke();//turn off outline border + fill(255); //fill set to white + ellipse(ballX, ballY, ballwidth, ballheight); + + if(ballX < 0){//ball off the left of the screen + ballDirectionX = ballDirectionX*-1; + } + if(ballX > width){//ball off the right of the screen + ballDirectionX = ballDirectionX*-1; + //insert a sound here + } + if(ballY < 0){//ball off the left of the screen + ballDirectionY = ballDirectionY*-1; + } + if(ballY > height){//ball off the top of the screen + ballDirectionY = ballDirectionY*-1; + } +} + +function coordinateBall(){ + noStroke();//turn off outline border + fill(0,0,0); //fill set to white + let d = map(mouseY, 0, height, 100, 800); //diameter of the ball + ellipse(coordinateX,coordinateY, d, d); +} + +function coordinateBallColored(){ + noStroke(); + r = map(ballX, 0, windowWidth, 0, 255); + g = map(ballY, 0, windowHeight, 255, 0); + c = map(mouseX, -99 , windowHeight, 255, 0) + let d = map(mouseY, 0, height, 100, 800); //diameter of the ball + fill(r,g,c); + ellipse(coordinateX,coordinateY, d, d); + +} +function pong() { + + let name = "Hotspot name:\nPLACE NOT FOUND"; + let coord = "52.07239, 4.31139"; + + cpu(); //loop cpu function + + //if (PNF1.paused) { + // PNF1.play(); + //} + + + //IN BETWEEN VARIABLES SHOWCASE + + r = map(ballX, 0, windowWidth, 0, 255); + g = map(ballY, 0, windowHeight, 255, 0); + b = map(mouseX, 0, windowWidth, 0, 255); + + let d = map(mouseY, 0, height, 100, 800); //diameter of the ball + let e = int(dist(width/2, height/2, ballX, ballY)); + + if (inside){ + + hit = collideCircleCircle(coordinateX,coordinateY,d-ballwidth,ballX, ballY,ballwidth) + console.log(hit) + } else { + hit = collideCircleCircle(coordinateX,coordinateY,d,ballX, ballY,ballwidth) + console.log(hit) + } + if (hit == true){ + PNF1.play(); + inside = true; + + } else { + if (inside){ + if (capture){ + //inside bounce + ballDirectionX = ballDirectionX*-1; + ballDirectionY = ballDirectionY*-1; + } else { + inside = false; + } + } + } + + + fill(255); +// text(cheatcode, 100, 100); + + + if (hit == false){ + background(r,g,b); + coordinateBall(); + textSize(width/20); + fill(255); + textFont(myFont); + textAlign(TOP); + textLeading(width/20); +text("I Don't Know Where We're Going, But\nyou are "+e+"px away from finding a hotspot ", width/2, 70); + textSize(width/35); + textFont(myFont); + textAlign(CENTER); + textLeading(width/35); + text('Click/Press while the ball is inside the circle\n to get your coordinates', width/2, height-120); + fill(0); + ball(); + //background(r, g, b); + } else if (hit == true) { + background(0,0,0); + + //click.loop = false; + //text('Your mouse is inside the hotspot range range at: '+ mouseX + ' pixels (x) /' + mouseY + ' pixels (y)', width/2, 280); + // clear(); + + if(mouseIsPressed == true) { + // if the mouse is pressed, while the ball is in the circle + // big text at the top + coordinateBallColored(); + ball(); + textSize(width/20); + fill(255); + textFont(myFont); + textAlign(TOP); + textLeading(width/20); + text('I Don\'t Know Where We\'re Going, But\ngo and find a hotspot at:', width/2, 70); + + // text at the bottom + textFont(myFont); + textAlign(CENTER); + textSize(width/20); + textLeading(width/20); + text(name, width/2, height-100); + textSize(width/17); + text(coord , width/2, 150); + fill(0); + //layer1.play();//sirens + } else { + // if the mouse is not pressed, while the ball is in the circle + // big text at the top + coordinateBallColored(); + ball(); + textSize(width/20); + fill(255); + textFont(myFont); + textAlign(TOP); + textLeading(width/20); + text('I Don\'t Know Where We\'re Going, But\ntouch or click find a hotspot!', width/2, 70); + } +} + + if(mouseIsPressed == true) { + textFont(myFont); + textAlign(CENTER); + textSize(20); + fill(0); + //text('Sound Unlocked! (your mouse is currently pressed) ', width/2, height-90); + //layer1.play();//sirens + } + + if(mouseIsPressed){ + if(mouseButton === RIGHT) { + textFont(myFont); + textAlign(CENTER); + textSize(20); + fill(255); + //text('Sound Unlocked! (your mouse is right clicked) ', width/2, height/2-160) + //layer5.play(); + } + } + + if(keyIsPressed == true) { + textAlign(CENTER); + textFont(myFont); + fill(0); + textSize(50); + // // console.log("playlayer4"); + } + + if(ballX >= 900 && ballX <= 1100) { + textAlign(CENTER); + textFont(myFont); + textSize(20); + fill(0); + // // console.log("playlayer6"); + } + + if(ballY >= 50 && ballY <= 200) { + textAlign(CENTER); + textSize(20); + // // console.log("playlayer2"); + } + + if(windowWidth < 800) { + textAlign(BOTTOM); + textFont(myFont); + textSize(20); + fill(0); + // // console.log("playlayer8"); + + } + + if(windowHeight < 400) { + textAlign(CENTER); + fill(0); + textSize(20); + // // console.log("playlayer8"); + } + + + if(ballX <= 0){ + //off left wall - p1 missed + p2Score = p2Score+1;//add point + //recenterball + ball1X = width/2; + ballY = height/2; + }//close p2 scores + + if(ballX >= width){ + //off right wall - p2 missed + p1Score = p1Score+1;//add point + //recenterball + // ball1X = width/2; + // ballY = height/2; + }//close p1 scores + + if(p1Score >= 10000){ + stage = 6; //run p1wins + }//close p1wins + + if(p2Score >= 10000){ + stage = 6; //run p2wins + + }//close p2wins + +}//close pong + + +//UP +function keyTyped(){ + if(key == 'z' && keyIsPressed){ + p1Y = p1Y-pSpeed; + }//close w +//DOWN + if(key == 's' && keyIsPressed){ + p1Y = p1Y+pSpeed; + }//close s + +}//close keytyped + +function cpu(){ + //controls cpu player + if(ballX < width/2){//has the ball crossed the court? + if(p1Y <= ballY){ + p1Y = p1Y+cpuSpeed; + //move down + }//close above cel + + + if(p1Y >= ballY){ + p1Y = p1Y-cpuSpeed; + //move up + }//close bellow ball + }//close move cpu + else{ + p1Y = p1Y; //only move when ball is on cpu side + }//close else + + +}//close cpu +hit \ No newline at end of file diff --git a/code/index.html b/code/index.html new file mode 100644 index 0000000..7eb59fe --- /dev/null +++ b/code/index.html @@ -0,0 +1,17 @@ + + + + + + + LAUNCHER + + + + + +
+ GET YOUR BONUS FILES +
+ + \ No newline at end of file diff --git a/code/style.css b/code/style.css new file mode 100644 index 0000000..0511d73 --- /dev/null +++ b/code/style.css @@ -0,0 +1,58 @@ +*{ +/* Prevent any object from being highlighted upon touch event*/ + tap-highlight-color: transparent; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + -moz-tap-highlight-color: rgba(0, 0, 0, 0); + outline: none; +} + +@font-face { + font-family: "ApfelGrotezk-Regular"; + src: url("../../ApfelGrotezk-Regular.ttf"); +} + +.display-none { + display:none; +} +.display-flex { + display:flex; +} +.display-block{ + display:block; +} + +body{ + font-size: 1.5em; + background-color: black; + color: white; + font-family: "ApfelGrotezk-Regular"; + text-align: center; +} + +.overlay{ + z-index: 2; + position: fixed; +} + +#code-input{ + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; +} + +#input{ + visibility: hidden; +} + +a{ + text-decoration: none; + color: white +} + +a:hover{ + text-decoration: none; + color: blue; + cursor: pointer; +} \ No newline at end of file diff --git a/code/test.zip b/code/test.zip new file mode 100644 index 0000000..b213db0 Binary files /dev/null and b/code/test.zip differ diff --git a/codes.js b/codes.js new file mode 100644 index 0000000..933d392 --- /dev/null +++ b/codes.js @@ -0,0 +1,74 @@ + + function openInput(){ + document.getElementById("input").style.visibility = "visible"; + document.getElementById("code-input").style.visibility = "hidden"; + document.getElementById("fname").focus(); + } + + let toxt = document.querySelector ("input[type='toxt']"); + + function checkCode (e) { + if (e.key == "Enter") { + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "PPRGM") { + location='ZIPFILES/pprgm/'; + }//OK + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "BORDERS") { + location='ZIPFILES/BORDERS.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "LIFE") { + location='ZIPFILES/LIFE.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "FUTURE") { + location='ZIPFILES/FUTURE.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "DIALOGUE") { + location='ZIPFILES/DIALOGUE.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "BREATH") { + location='ZIPFILES/BREATH.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "CAPITALISM") { + location='ZIPFILES/CAPITALISM.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "GAMES") { + location='ZIPFILES/CAPITALISM.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "SYNERGY") { + location='ZIPFILES/SINERGY.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "DEATH") { + location='ZIPFILES/DEATH.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "VIRUS") { + location='ZIPFILES/VIRUS.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "THEWHOLE") { + location='ZIPFILES/THEWHOLE.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "CAT") { + location='https://hub.xpub.nl/sandbot/PrototypingTimes/sketches/Euna/'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "APPOINTMENT") { + location='ZIPFILES/appointment/'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "PRAXIS") { + location='ZIPFILES/PRAXIS.zip'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "OFFLINE") { + location='ZIPFILES/OFFLINE.zip'; + } //OK + + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "POISON") { + location='ZIPFILES/poison/'; + } + if (document.querySelector ("input[type='toxt']").value.toUpperCase() === "THISISNOTART") { + location='ZIPFILES/THISISNOTART.zip'; + } + + else { + console.log("NO GOOD"); + } + } + } + + toxt.addEventListener("keydown", checkCode ); \ No newline at end of file diff --git a/index.html b/index.html index 8714cdc..cc6a2e1 100644 --- a/index.html +++ b/index.html @@ -1,8 +1,200 @@ + + + + - + + + + + + + + + + I Don't Know Where We're Going, But.. + + + +
+ +
+ +
+ +
+ + + + + + + +
+ + -test+ +
+ +
+ +
+ +
+ +
+
+ X + + Another lockdown; shops closed, museums closed, bars closed, cafés closed, restaurants closed. +You turn to escapist media, in another attempt to climb the inner walls of a deflating castle. +All that is left is the city in its rawest form and the people inhabiting its shut down structures. +Where can you go if everything is closed? What could you encounter along the way? +Locked within the walls of a comatose town, you are missing direction. If the city is your new playground, who are the players and what is the objective? + +

+ +Special Issue #14 from Piet Zwart Institute's Master of Experimental Publishing is born from the never-realised seventh issue of The Situationist Times, a magazine edited and published by the Dutch artist Jacqueline de Jong from 1962 to 1964. We began by delving into the material De Jong had gathered for the prospective issue, which revolved around pinball machines and their female player. + +

+ +With this in mind, "I Don't Know Where We're Going, But" intends to explore these themes by situating our emerging experiments in a more contemporary medium: hyper-stimulating video games. We took a deep dive into their history throughout the years and, (from this,) started making prototypes of retro arcade games. The result is an exploration of video game mechanics as a tool for narration. To anchor our digital games into the reality of the city, we felt it was appropriate to lean into the method of dérive, a term coined by The Situationists that refers to the wandering of the city without a set destination. The notion of going against predetermined structures resonated with our theoretical research on feminism, socialism & counter play. In the spirit of Situationism, we are stepping into psychogeographic methods of publishing, encouraging the exploration of urban environments through playfulness and dérive. + +

+ +Find new trajectories or get lost within the many paths of this coordinate-based Special Issue, and discover the hidden signals we are sending out to you all across town. Bounce within a spontaneous rearrangement of situations and nodes, as the only way to experience the local network-based publication. In a battle of chance and control, let your personal path unravel an ensemble of concrete and fictitious publishing environments, where the shared notion of network is flipped-out. + +
+ +You receive coordinates in the city of Den Haag. On arrival at the given location, you log into a local wifi network with your mobile phone. This gives you access to parts of the content of this Issue, only to be directed to the next location. This game is playable within a day or spread out over days, as it will be running for the month of April. We hope that the content you will gather on your devices during your escape will last you for longer than that. + +A short note on the interface: The sounds you are hearing were recorded at the location of the hotspots that you need to find. + +

+ +Colophon + +

+ +Conceptualised, designed, created, edited, produced, published and distributed by XPUB1 class of 2020. + +

+ +Kendal Beynon, Martin Foucaut, Camilo García A., Clara Gradel, Nami Kim, Euna Lee, Jacopo Lega, Federico Poni, Louisa Teichmann, Floor van Meeuwen + +Tutors: Manetta Berends, Aymeric Mansoux, Michael Murtaugh, Lídia Pereira, Steve Rushton, Marloes de Valk + +

+ +Special thanks to: Sébastien Tien , Ola Vasiljeva,Jacqueline de Jong + +

+ +and all the great people we met along the way: Kishonna Gray, Ellef Prestsæter, David Maroto, Anne-Marie Schleiner, Jamie Woodcock + +

+ +Thanks to: Anesca and colleagues Hanny, Vincent and Wim Kenny.The Seafood service for hosting our hotspots. + +

+ +Typeface: Apfel Grotezk, TINY + +

+ +Rotterdam, NL
+Spring, 2021 + +

+ +Published by the Master Experimental Publishing at Piet Zwart Institute and Page Not Found + +

+ +Licensing + +

+ +XPUB - “I Don’t Know Where We’re Going, But”
+A Local Network CityQuest
+A Situationist times license
+© 2021 XPUB - SPECIAL ISSUE 14 + +

+ +All deformation, reproduction, modification, derivation and transformation of the "I Don't Know Where We're Going, But..." is permitted. This refers to all the games, images, texts, and videos created for this local network city quest. + +

+ +This license does not apply to the materials that were created by third party creators. Third party materials will be marked with this symbol : ⨂. +
+
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + +
+ + +
+ +
+ + +
+
+ + + + + + + + + + diff --git a/louisa code/.ipynb_checkpoints/INTRO-checkpoint.gif b/louisa code/.ipynb_checkpoints/INTRO-checkpoint.gif new file mode 100644 index 0000000..2c4a311 Binary files /dev/null and b/louisa code/.ipynb_checkpoints/INTRO-checkpoint.gif differ diff --git a/louisa code/.ipynb_checkpoints/index-checkpoint.html b/louisa code/.ipynb_checkpoints/index-checkpoint.html new file mode 100644 index 0000000..c6c2d48 --- /dev/null +++ b/louisa code/.ipynb_checkpoints/index-checkpoint.html @@ -0,0 +1,48 @@ + + + + + + + LAUNCHER + + + + +
+ + whatever
+
+ +
+ +
+ +
+ + + \ No newline at end of file diff --git a/louisa code/.ipynb_checkpoints/style-checkpoint.css b/louisa code/.ipynb_checkpoints/style-checkpoint.css new file mode 100644 index 0000000..d37dae3 --- /dev/null +++ b/louisa code/.ipynb_checkpoints/style-checkpoint.css @@ -0,0 +1,99 @@ +*{ +/* Prevent any object from being highlighted upon touch event*/ + tap-highlight-color: transparent; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + -moz-tap-highlight-color: rgba(0, 0, 0, 0); + outline: none; +} + +@font-face { + font-family: "ApfelGrotezk-Regular"; + src: url("../ApfelGrotezk-Regular.ttf"); +} + + +.display-none { + display:none; +} +.display-flex { + display:flex; +} +.display-block{ + display:block; +} + +body{ + font-size: 1.5em; + background-color: black; + color: white; + font-family: "ApfelGrotezk-Regular"; +} + +.overlay{ + z-index: 2; + position: fixed; +} + +#code-input{ + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; + color: white; + font-family: "ApfelGrotezk-Regular"; + font-size: 0.8em; +} + +#code-input:hover{ + color: blue; + cursor: pointer; + +} + +#input{ + visibility: hidden; + border: 0; + outline: 0; + background: transparent; + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; + color: white; + font-family: "ApfelGrotezk-Regular"; + font-size: 0.8em; + +} + +#fname{ + border: 0; + outline: 0; + background: transparent; + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; + color: white; + font-family: "ApfelGrotezk-Regular"; + font-size: 1em; + +} + +img { opacity: 1; + z-index: 0; + display: block; + position: fixed; +} + +#gif { + visibility: visible; + position: absolute; + height: 50%; + top: 48%; + text-align: center; + left: 50%; + transform: translate(-50%,-50%); +} \ No newline at end of file diff --git a/louisa code/INTRO.gif b/louisa code/INTRO.gif new file mode 100644 index 0000000..2c4a311 Binary files /dev/null and b/louisa code/INTRO.gif differ diff --git a/louisa code/code/.ipynb_checkpoints/index-checkpoint.html b/louisa code/code/.ipynb_checkpoints/index-checkpoint.html new file mode 100644 index 0000000..7eb59fe --- /dev/null +++ b/louisa code/code/.ipynb_checkpoints/index-checkpoint.html @@ -0,0 +1,17 @@ + + + + + + + LAUNCHER + + + + + +
+ GET YOUR BONUS FILES +
+ + \ No newline at end of file diff --git a/louisa code/code/.ipynb_checkpoints/style-checkpoint.css b/louisa code/code/.ipynb_checkpoints/style-checkpoint.css new file mode 100644 index 0000000..0511d73 --- /dev/null +++ b/louisa code/code/.ipynb_checkpoints/style-checkpoint.css @@ -0,0 +1,58 @@ +*{ +/* Prevent any object from being highlighted upon touch event*/ + tap-highlight-color: transparent; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + -moz-tap-highlight-color: rgba(0, 0, 0, 0); + outline: none; +} + +@font-face { + font-family: "ApfelGrotezk-Regular"; + src: url("../../ApfelGrotezk-Regular.ttf"); +} + +.display-none { + display:none; +} +.display-flex { + display:flex; +} +.display-block{ + display:block; +} + +body{ + font-size: 1.5em; + background-color: black; + color: white; + font-family: "ApfelGrotezk-Regular"; + text-align: center; +} + +.overlay{ + z-index: 2; + position: fixed; +} + +#code-input{ + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; +} + +#input{ + visibility: hidden; +} + +a{ + text-decoration: none; + color: white +} + +a:hover{ + text-decoration: none; + color: blue; + cursor: pointer; +} \ No newline at end of file diff --git a/louisa code/code/index.html b/louisa code/code/index.html new file mode 100644 index 0000000..7eb59fe --- /dev/null +++ b/louisa code/code/index.html @@ -0,0 +1,17 @@ + + + + + + + LAUNCHER + + + + + +
+ GET YOUR BONUS FILES +
+ + \ No newline at end of file diff --git a/louisa code/code/style.css b/louisa code/code/style.css new file mode 100644 index 0000000..0511d73 --- /dev/null +++ b/louisa code/code/style.css @@ -0,0 +1,58 @@ +*{ +/* Prevent any object from being highlighted upon touch event*/ + tap-highlight-color: transparent; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + -moz-tap-highlight-color: rgba(0, 0, 0, 0); + outline: none; +} + +@font-face { + font-family: "ApfelGrotezk-Regular"; + src: url("../../ApfelGrotezk-Regular.ttf"); +} + +.display-none { + display:none; +} +.display-flex { + display:flex; +} +.display-block{ + display:block; +} + +body{ + font-size: 1.5em; + background-color: black; + color: white; + font-family: "ApfelGrotezk-Regular"; + text-align: center; +} + +.overlay{ + z-index: 2; + position: fixed; +} + +#code-input{ + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; +} + +#input{ + visibility: hidden; +} + +a{ + text-decoration: none; + color: white +} + +a:hover{ + text-decoration: none; + color: blue; + cursor: pointer; +} \ No newline at end of file diff --git a/louisa code/code/test.zip b/louisa code/code/test.zip new file mode 100644 index 0000000..b213db0 Binary files /dev/null and b/louisa code/code/test.zip differ diff --git a/louisa code/index.html b/louisa code/index.html new file mode 100644 index 0000000..c6c2d48 --- /dev/null +++ b/louisa code/index.html @@ -0,0 +1,48 @@ + + + + + + + LAUNCHER + + + + +
+ + whatever
+
+ +
+ +
+ +
+ + + \ No newline at end of file diff --git a/louisa code/style.css b/louisa code/style.css new file mode 100644 index 0000000..d37dae3 --- /dev/null +++ b/louisa code/style.css @@ -0,0 +1,99 @@ +*{ +/* Prevent any object from being highlighted upon touch event*/ + tap-highlight-color: transparent; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + -moz-tap-highlight-color: rgba(0, 0, 0, 0); + outline: none; +} + +@font-face { + font-family: "ApfelGrotezk-Regular"; + src: url("../ApfelGrotezk-Regular.ttf"); +} + + +.display-none { + display:none; +} +.display-flex { + display:flex; +} +.display-block{ + display:block; +} + +body{ + font-size: 1.5em; + background-color: black; + color: white; + font-family: "ApfelGrotezk-Regular"; +} + +.overlay{ + z-index: 2; + position: fixed; +} + +#code-input{ + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; + color: white; + font-family: "ApfelGrotezk-Regular"; + font-size: 0.8em; +} + +#code-input:hover{ + color: blue; + cursor: pointer; + +} + +#input{ + visibility: hidden; + border: 0; + outline: 0; + background: transparent; + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; + color: white; + font-family: "ApfelGrotezk-Regular"; + font-size: 0.8em; + +} + +#fname{ + border: 0; + outline: 0; + background: transparent; + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; + color: white; + font-family: "ApfelGrotezk-Regular"; + font-size: 1em; + +} + +img { opacity: 1; + z-index: 0; + display: block; + position: fixed; +} + +#gif { + visibility: visible; + position: absolute; + height: 50%; + top: 48%; + text-align: center; + left: 50%; + transform: translate(-50%,-50%); +} \ No newline at end of file diff --git a/mobile.css b/mobile.css new file mode 100644 index 0000000..aab015b --- /dev/null +++ b/mobile.css @@ -0,0 +1,12 @@ +#textcontainer{ + display: none; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: auto; + background-color: yellow; + font-size: 72px; + text-align: center; + color: blue; +} \ No newline at end of file diff --git a/myTools.js b/myTools.js new file mode 100644 index 0000000..c0e12d1 --- /dev/null +++ b/myTools.js @@ -0,0 +1,137 @@ +/* + myTools KLL + use extra js file here in root + name: myTools.js + idea is to develop it here ( master ) and download / upload to other projects. + content: + + functions to call: + + logo(x,y,radius,speed); + + mysong( true/false ); //________________ from anywhere to start stop song + //______________________________________ here as example linked into the Button press action + + +//_________________________________ !! + + +*/ + +//________________________________________________________ FUNCTIONS MYSOUND + + +let song; + +function preload() { + song = loadSound('sound/loop5.mp3'); +} + +function mysong( go ) { + if ( go && !song.isLooping() ) song.loop(); + if ( !go && song.isLooping() ) song.pause(); +} + + +function mouseVolume() {//___ test a simple mouse slider for volume + if ( song.isLooping() ) { + fill(200); + triangle(10,height-10, width-10,height-30,width-10,height-10); + let amp = map(mouseX, 0, width,0,1); + fill(200,0,0); + rect( amp*width,height-30,5,20); + //print(amp); + masterVolume(amp); + } +} + + + +//________________________________________________________ FUNCTION LOGO +var ang = 0; + +function logo(x, y, r, dang) { + var d1 = 2 * r; + var d2 = 2 * r / sqrt(2); + ang += dang; //__________________ animation + push(); + fill(255); //____________________ fill same all 3 shapes + strokeWeight(4); + stroke(200, 200, 0); //__________ here same as main background gives a nice effect + ellipseMode(CENTER); + rectMode(CENTER); + translate(x + r, y + r); //______ CENTER thinking + push(); + rotate(-ang); //__________________ animate first bigger rect + rect(0, 0, d1, d1); + pop(); + ellipse(0, 0, d1, d1); + rotate(ang); //_________________ animate second smaller rect + rect(0, 0, d2, d2); + textAlign(CENTER, CENTER); + textSize(20); + text("K L L", 0, 0); + pop(); +} + +/* + __________________________________ classes declared: + + class Button + declare: + var button; + Button button(x, y, w, h, sel, textFalse, textTrue, id); + methods: + button.draw(); //_______________ from draw + button.mousePressed(); //_______ local use global mymouseClicked + boolean button.over(); //_______ local + +*/ + +class Button { //____________________________________ begin class + constructor(xi, yi, wi, hi, seli, atextisel,atextinosel, idi) { + this.xb = xi; + this.yb = yi; + this.wb = wi; + this.hb = hi; + this.selb = seli; + this.textbsel = atextisel; + this.textbnosel = atextinosel; + this.idb = idi; + } + + draw() { + this.mousePressed(); + strokeWeight(3); + if (this.selb) fill(0, 200, 0); + else fill(0, 0, 200); + if (this.over()) stroke(200, 0, 200); + else stroke(0, 200, 200); + rect(this.xb, this.yb, this.wb, this.hb); + + noStroke(); + fill(200); + textSize(30); + if ( this.selb ) text(this.textbnosel, this.xb + 5, this.yb + this.hb - 8); + else text(this.textbsel, this.xb + 5, this.yb + this.hb - 8); + } + + over() { + return (mouseX > this.xb & mouseX < this.xb + this.wb & mouseY > this.yb & mouseY < this.yb + this.hb); + } + + mousePressed() { + // if (this.over() && mouseIsPressed) { + if (this.over() && mymouseClicked) { + mymouseClicked = false; // reset global + this.selb = ! this.selb; // toggle; + mysong( this.selb ); //__________________________ start stop sound + } + } + +} //___________________________________________________ end class + diff --git a/p5.dom.min.js b/p5.dom.min.js new file mode 100644 index 0000000..85b3c19 --- /dev/null +++ b/p5.dom.min.js @@ -0,0 +1 @@ +/*! p5.js v0.5.16 October 11, 2017 */ !function(a,b){"function"==typeof define&&define.amd?define("p5.dom",["p5"],function(a){b(a)}):b("object"==typeof exports?require("../p5"):a.p5)}(this,function(a){function b(b){var c=document;return"string"==typeof b&&"#"===b[0]?(b=b.slice(1),c=document.getElementById(b)||document):b instanceof a.Element?c=b.elt:b instanceof HTMLElement&&(c=b),c}function c(b){if("INPUT"===b.tagName&&"checkbox"===b.type){var c=new a.Element(b);return c.checked=function(){return 0===arguments.length?this.elt.checked:(arguments[0]?this.elt.checked=!0:this.elt.checked=!1,this)},c}return"VIDEO"===b.tagName||"AUDIO"===b.tagName?new a.MediaElement(b):"SELECT"===b.tagName?createSelect(new a.Element(b)):new a.Element(b)}function d(b,c,d){(c._userNode?c._userNode:document.body).appendChild(b);var e=d?new a.MediaElement(b):new a.Element(b);return c._elements.push(e),e}function e(a,b,c,e){var f=document.createElement(b),c=c||"";"string"==typeof c&&(c=[c]);for(var g=0;g1&&"function"==typeof c[1]?(a.fn=c[1],a.fn()):c.length>1&&"function"==typeof c[2]&&(a.fn=c[2],a.fn())};return b.src=c[0],c.length>1&&"string"==typeof c[1]&&(b.alt=c[1]),b.onload=function(){e()},a=d(b,this)},a.prototype.createA=function(a,b,c){var e=document.createElement("a");return e.href=a,e.innerHTML=b,c&&(e.target=c),d(e,this)},a.prototype.createSlider=function(a,b,c,e){var f=document.createElement("input");return f.type="range",f.min=a,f.max=b,0===e?f.step=1e-18:e&&(f.step=e),"number"==typeof c&&(f.value=c),d(f,this)},a.prototype.createButton=function(a,b){var c=document.createElement("button");return c.innerHTML=a,b&&(c.value=b),d(c,this)},a.prototype.createCheckbox=function(){var a=document.createElement("div"),b=document.createElement("input");b.type="checkbox",a.appendChild(b);var c=d(a,this);if(c.checked=function(){var a=c.elt.getElementsByTagName("input")[0];if(a){if(0===arguments.length)return a.checked;arguments[0]?a.checked=!0:a.checked=!1}return c},this.value=function(a){return c.value=a,this},arguments[0]){var e=Math.random().toString(36).slice(2),f=document.createElement("label");b.setAttribute("id",e),f.htmlFor=e,c.value(arguments[0]),f.appendChild(document.createTextNode(arguments[0])),a.appendChild(f)}return arguments[1]&&(b.checked=!0),c},a.prototype.createSelect=function(){var a,b,c=arguments[0];return"object"==typeof c&&"SELECT"===c.elt.nodeName?(b=c,a=this.elt=c.elt):(a=document.createElement("select"),c&&"boolean"==typeof c&&a.setAttribute("multiple","true"),b=d(a,this)),b.option=function(b,c){for(var d,e=0;e1?f.value=c:f.value=b,a.appendChild(f)}},b.selected=function(a){var b=[];if(arguments.length>0){for(var c=0;c1){var c=a.length,e=a[0].name,f=a[1].name;b=1;for(var g=1;g1?d.value=c:d.value=a,d.setAttribute("name","defaultradio"+b),h.appendChild(d),a){j++;var e=(Math.random().toString(36).slice(2),document.createElement("label"));d.setAttribute("id","defaultradio"+b+"-"+j),e.htmlFor="defaultradio"+b+"-"+j,e.appendChild(document.createTextNode(a)),h.appendChild(e)}return d},i.selected=function(){var a=this.elt.childNodes.length;if(1==arguments.length){for(var b=0;b-1?h.readAsText(g):h.readAsDataURL(g)}}if(window.File&&window.FileReader&&window.FileList&&window.Blob){var f=document.createElement("input");return f.type="file",c&&(f.multiple="multiple"),f.addEventListener("change",e,!1),d(f,this)}console.log("The File APIs are not fully supported in this browser. Cannot create element.")},a.prototype.createVideo=function(a,b){return e(this,"video",a,b)},a.prototype.createAudio=function(a,b){return e(this,"audio",a,b)},a.prototype.VIDEO="video",a.prototype.AUDIO="audio",void 0===navigator.mediaDevices&&(navigator.mediaDevices={}),void 0===navigator.mediaDevices.getUserMedia&&(navigator.mediaDevices.getUserMedia=function(a){var b=navigator.webkitGetUserMedia||navigator.mozGetUserMedia;return b?new Promise(function(c,d){b.call(navigator,a,c,d)}):Promise.reject(new Error("getUserMedia is not implemented in this browser"))}),a.prototype.createCapture=function(){for(var b,c,e=!0,f=!0,g=0;g2&&(this.elt.style.transform="translate3d("+arguments[0]+"px,"+arguments[1]+"px,"+arguments[2]+"px)",3===arguments.length?this.elt.parentElement.style.perspective="1000px":this.elt.parentElement.style.perspective=arguments[3]+"px"),this.elt.style.transform+=a,this},a.Element.prototype._rotate=function(){var a="";if(this.elt.style.transform){var a=this.elt.style.transform.replace(/rotate3d\(.*\)/g,"");a=a.replace(/rotate[X-Z]?\(.*\)/g,"")}return 1===arguments.length?this.elt.style.transform="rotate("+arguments[0]+"deg)":2===arguments.length?this.elt.style.transform="rotate("+arguments[0]+"deg, "+arguments[1]+"deg)":3===arguments.length&&(this.elt.style.transform="rotateX("+arguments[0]+"deg)",this.elt.style.transform+="rotateY("+arguments[1]+"deg)",this.elt.style.transform+="rotateZ("+arguments[2]+"deg)"),this.elt.style.transform+=a,this},a.Element.prototype.style=function(b,c){var d=this;if(c instanceof a.Color&&(c="rgba("+c.levels[0]+","+c.levels[1]+","+c.levels[2]+","+c.levels[3]/255+")"),void 0===c){if(b.indexOf(":")===-1)return window.getComputedStyle(d.elt).getPropertyValue(b);for(var e=b.split(";"),f=0;f0?(this.elt.value=arguments[0],this):"range"===this.elt.type?parseFloat(this.elt.value):this.elt.value},a.Element.prototype.show=function(){return this.elt.style.display="block",this},a.Element.prototype.hide=function(){return this.elt.style.display="none",this},a.Element.prototype.size=function(b,c){if(0===arguments.length)return{width:this.elt.offsetWidth,height:this.elt.offsetHeight};var d=b,e=c,f=a.prototype.AUTO;if(d!==f||e!==f){if(d===f?d=c*this.width/this.height:e===f&&(e=b*this.height/this.width),this.elt instanceof HTMLCanvasElement){var g={},h=this.elt.getContext("2d");for(var i in h)g[i]=h[i];this.elt.setAttribute("width",d*this._pInst._pixelDensity),this.elt.setAttribute("height",e*this._pInst._pixelDensity),this.elt.setAttribute("style","width:"+d+"px; height:"+e+"px"),this._pInst.scale(this._pInst._pixelDensity,this._pInst._pixelDensity);for(var i in g)this.elt.getContext("2d")[i]=g[i]}else this.elt.style.width=d+"px",this.elt.style.height=e+"px",this.elt.width=d,this.elt.height=e,this.width=d,this.height=e;this.width=this.elt.offsetWidth,this.height=this.elt.offsetHeight,this._pInst&&this._pInst._curElement.elt===this.elt&&(this._pInst._setProperty("width",this.elt.offsetWidth),this._pInst._setProperty("height",this.elt.offsetHeight))}return this},a.Element.prototype.remove=function(){for(var a in this._events)this.elt.removeEventListener(a,this._events[a]);this.elt.parentNode&&this.elt.parentNode.removeChild(this.elt),delete this},a.MediaElement=function(b,c){a.Element.call(this,b,c);var d=this;this.elt.crossOrigin="anonymous",this._prevTime=0,this._cueIDCounter=0,this._cues=[],this._pixelDensity=1,this._modified=!1,Object.defineProperty(d,"src",{get:function(){var a=d.elt.children[0].src,b=d.elt.src===window.location.href?"":d.elt.src;return a===window.location.href?b:a},set:function(a){for(var c=0;c1?this.elt.play():(this.elt.load(),this.elt.play()),this},a.MediaElement.prototype.stop=function(){return this.elt.pause(),this.elt.currentTime=0,this},a.MediaElement.prototype.pause=function(){return this.elt.pause(),this},a.MediaElement.prototype.loop=function(){return this.elt.setAttribute("loop",!0),this.play(),this},a.MediaElement.prototype.noLoop=function(){return this.elt.setAttribute("loop",!1),this},a.MediaElement.prototype.autoplay=function(a){return this.elt.setAttribute("autoplay",a),this},a.MediaElement.prototype.volume=function(a){if(void 0===a)return this.elt.volume;this.elt.volume=a},a.MediaElement.prototype.speed=function(a){if(void 0===a)return this.elt.playbackRate;this.elt.playbackRate=a},a.MediaElement.prototype.time=function(a){if(void 0===a)return this.elt.currentTime;this.elt.currentTime=a},a.MediaElement.prototype.duration=function(){return this.elt.duration},a.MediaElement.prototype.pixels=[],a.MediaElement.prototype.loadPixels=function(){return this.canvas||(this.canvas=document.createElement("canvas"),this.drawingContext=this.canvas.getContext("2d")),this.loadedmetadata&&(this.canvas.width!==this.elt.width&&(this.canvas.width=this.elt.width,this.canvas.height=this.elt.height,this.width=this.canvas.width,this.height=this.canvas.height),this.drawingContext.drawImage(this.elt,0,0,this.canvas.width,this.canvas.height),a.Renderer2D.prototype.loadPixels.call(this)),this.setModified(!0),this},a.MediaElement.prototype.updatePixels=function(b,c,d,e){return this.loadedmetadata&&a.Renderer2D.prototype.updatePixels.call(this,b,c,d,e),this.setModified(!0),this},a.MediaElement.prototype.get=function(b,c,d,e){return this.loadedmetadata?a.Renderer2D.prototype.get.call(this,b,c,d,e):void 0===b?new a.Image(1,1):d>1?new a.Image(b,c,d,e):[0,0,0,255]},a.MediaElement.prototype.set=function(b,c,d){this.loadedmetadata&&(a.Renderer2D.prototype.set.call(this,b,c,d),this.setModified(!0))},a.MediaElement.prototype.copy=function(){a.Renderer2D.prototype.copy.apply(this,arguments)},a.MediaElement.prototype.mask=function(){this.loadPixels(),this.setModified(!0),a.Image.prototype.mask.apply(this,arguments)},a.MediaElement.prototype.isModified=function(){return this._modified},a.MediaElement.prototype.setModified=function(a){this._modified=a},a.MediaElement.prototype.onended=function(a){return this._onended=a,this},a.MediaElement.prototype.connect=function(b){var c,d;if("function"==typeof a.prototype.getAudioContext)c=a.prototype.getAudioContext(),d=a.soundOut.input;else try{c=b.context,d=c.destination}catch(a){throw"connect() is meant to be used with Web Audio API or p5.sound.js"}this.audioSourceNode||(this.audioSourceNode=c.createMediaElementSource(this.elt),this.audioSourceNode.connect(d)),b?b.input?this.audioSourceNode.connect(b.input):this.audioSourceNode.connect(b):this.audioSourceNode.connect(d)},a.MediaElement.prototype.disconnect=function(){if(!this.audioSourceNode)throw"nothing to disconnect";this.audioSourceNode.disconnect()},a.MediaElement.prototype.showControls=function(){this.elt.style["text-align"]="inherit",this.elt.controls=!0},a.MediaElement.prototype.hideControls=function(){this.elt.controls=!1},a.MediaElement.prototype.addCue=function(a,b,c){var d=this._cueIDCounter++,e=new f(b,a,d,c);return this._cues.push(e),this.elt.ontimeupdate||(this.elt.ontimeupdate=this._onTimeUpdate.bind(this)),d},a.MediaElement.prototype.removeCue=function(a){for(var b=0;bEach color stores the color mode and level maxes that applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when saturation() is requested.

\n

Internally we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer.

\n

We also cache normalized, floating point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed.

\n"},Setting:{name:"Setting",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Color",namespace:"",file:"src/color/setting.js",line:1,requires:["core","constants"]},Shape:{name:"Shape",submodules:{"2D Primitives":1,Curves:1,Vertex:1,"3D Models":1,"3D Primitives":1},elements:{},classes:{},fors:{p5:1},namespaces:{}},"2D Primitives":{name:"2D Primitives",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Shape",namespace:"",file:"src/core/2d_primitives.js",line:1,requires:["core","constants"]},Attributes:{name:"Attributes",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Typography",namespace:"",file:"src/core/attributes.js",line:1,requires:["core","constants"]},Constants:{name:"Constants",submodules:{},elements:{},classes:{},fors:{p5:1},namespaces:{},module:"Constants",file:"src/core/constants.js",line:1},Structure:{name:"Structure",submodules:{},elements:{},classes:{},fors:{p5:1},namespaces:{},module:"Structure",file:"src/core/core.js",line:1,requires:["constants"]},Curves:{name:"Curves",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Shape",namespace:"",file:"src/core/curves.js",line:1,requires:["core"]},Environment:{name:"Environment",submodules:{},elements:{},classes:{},fors:{p5:1},namespaces:{},module:"Environment",file:"src/core/environment.js",line:1,requires:["core","constants"]},DOM:{name:"DOM",submodules:{},elements:{},classes:{"p5.Element":1},fors:{"p5.Element":1},namespaces:{},module:"DOM",file:"src/core/p5.Element.js",line:9,description:'

Base class for all elements added to a sketch, including canvas,\ngraphics buffers, and other HTML elements. Methods in blue are\nincluded in the core functionality, methods in brown are added\nwith the p5.dom\nlibrary.\nIt is not called directly, but p5.Element\nobjects are created by calling createCanvas, createGraphics,\nor in the p5.dom library, createDiv, createImg, createInput, etc.

\n'},Rendering:{name:"Rendering",submodules:{},elements:{},classes:{"p5.Graphics":1,"p5.Renderer":1},fors:{p5:1},namespaces:{},module:"Rendering",file:"src/core/p5.Renderer.js",line:10,description:"

Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5.

\n"},Transform:{name:"Transform",submodules:{},elements:{},classes:{},fors:{p5:1},namespaces:{},module:"Transform",file:"src/core/transform.js",line:1,requires:["core","constants"]},Vertex:{name:"Vertex",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Shape",namespace:"",file:"src/core/vertex.js",line:1,requires:["core","constants"]},Data:{name:"Data",submodules:{Dictionary:1,"Array Functions":1,"String Functions":1},elements:{},classes:{"p5.TypedDict":1,"p5.StringDict":1,"p5.NumberDict":1},fors:{"p5.TypedDict":1,p5:1},namespaces:{},file:"src/data/p5.TypedDict.js",line:351},Dictionary:{name:"Dictionary",submodules:{},elements:{},classes:{"p5.TypedDict":1,"p5.StringDict":1,"p5.NumberDict":1},fors:{"p5.TypedDict":1},is_submodule:1,namespaces:{},module:"Data",namespace:"",file:"src/data/p5.TypedDict.js",line:351,requires:["core\n\nThis module defines the p5 methods for the p5 Dictionary classes\nthese classes StringDict and NumberDict are for storing and working\nwith key","value pairs"],description:"

Base class for all p5.Dictionary types. More specifically\n typed Dictionary objects inherit from this

\n"},Events:{name:"Events",submodules:{Acceleration:1,Keyboard:1,Mouse:1,Touch:1},elements:{},classes:{},fors:{p5:1},namespaces:{}},Acceleration:{name:"Acceleration",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Events",namespace:"",file:"src/events/acceleration.js",line:1,requires:["core"]},Keyboard:{name:"Keyboard",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Events",namespace:"",file:"src/events/keyboard.js",line:1,requires:["core"]},Mouse:{name:"Mouse",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Events",namespace:"",file:"src/events/mouse.js",line:1,requires:["core","constants"]},Touch:{name:"Touch",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Events",namespace:"",file:"src/events/touch.js",line:1,requires:["core"]},Image:{name:"Image",submodules:{Pixels:1},elements:{},classes:{"p5.Image":1},fors:{p5:1},namespaces:{},module:"Image",file:"src/image/p5.Image.js",line:23,requires:["core"],description:"

Creates a new p5.Image. A p5.Image is a canvas backed representation of an\nimage.\n

\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\nloadImage() function. The p5.Image class contains fields for the width and\nheight of the image, as well as an array called pixels[] that contains the\nvalues for every pixel in the image.\n

\nThe methods described below allow easy access to the image's pixels and\nalpha channel and simplify the process of compositing.\n

\nBefore using the pixels[] array, be sure to use the loadPixels() method on\nthe image to make sure that the pixel data is properly loaded.

\n"},"Loading & Displaying":{name:"Loading & Displaying",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Typography",namespace:"",file:"src/image/loading_displaying.js",line:1,requires:["core"]},Pixels:{name:"Pixels",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Image",namespace:"",file:"src/image/pixels.js",line:1,requires:["core"]},IO:{name:"IO",submodules:{"Color Conversion":1,Input:1,Output:1,Table:1,XML:1,"Time & Date":1},elements:{},classes:{p5:1,"p5.Table":1,"p5.TableRow":1,"p5.XML":1},fors:{p5:1},namespaces:{},file:"src/io/p5.XML.js",line:11},Input:{name:"Input",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"IO",namespace:"",file:"src/io/files.js",line:1,requires:["core"]},Output:{name:"Output",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"IO",namespace:"",file:"src/io/files.js",line:1012},Table:{name:"Table",submodules:{},elements:{},classes:{"p5.Table":1,"p5.TableRow":1},fors:{},is_submodule:1,namespaces:{},module:"IO",namespace:"",file:"src/io/p5.TableRow.js",line:11,requires:["core"],description:"

Table objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.

\n"},XML:{name:"XML",submodules:{},elements:{},classes:{"p5.XML":1},fors:{},is_submodule:1,namespaces:{},module:"IO",namespace:"",file:"src/io/p5.XML.js",line:11,requires:["core"],description:"

XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects.

\n"},Math:{name:"Math",submodules:{Calculation:1,Noise:1,Random:1,Trigonometry:1},elements:{},classes:{"p5.Vector":1},fors:{p5:1},namespaces:{},module:"Math",file:"src/math/p5.Vector.js",line:13,requires:["core"],description:"

A class to describe a two or three dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude\nand direction can be accessed via the methods mag() and heading().\n

\nIn many of the p5.js examples, you will see p5.Vector used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object's position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object's velocity changes per time\nunit, expressed as a vector).\n

\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we'll need to do some\n"vector" math, which is made easy by the methods inside the p5.Vector class.

\n"},Calculation:{name:"Calculation",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Math",namespace:"",file:"src/math/calculation.js",line:1,requires:["core"]},Noise:{name:"Noise",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Math",namespace:"",file:"src/math/noise.js",line:14,requires:["core"]},Random:{name:"Random",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Math",namespace:"",file:"src/math/random.js",line:1,requires:["core"]},Trigonometry:{name:"Trigonometry",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Math",namespace:"",file:"src/math/trigonometry.js",line:1,requires:["core","polargeometry","constants"]},Typography:{name:"Typography",submodules:{Attributes:1,"Loading & Displaying":1,Font:1},elements:{},classes:{"p5.Font":1},fors:{p5:1},namespaces:{},file:"src/typography/p5.Font.js",line:21},Font:{name:"Font",submodules:{},elements:{},classes:{"p5.Font":1},fors:{},is_submodule:1,namespaces:{},module:"Typography",namespace:"",file:"src/typography/p5.Font.js",line:21,description:"

This module defines the p5.Font class and functions for\ndrawing text to the display canvas.

\n",requires:["core","constants"]},"Array Functions":{name:"Array Functions",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Data",namespace:"",file:"src/utilities/array_functions.js",line:1,requires:["core"]},"String Functions":{name:"String Functions",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Data",namespace:"",file:"src/utilities/string_functions.js",line:1,requires:["core"]},"Time & Date":{name:"Time & Date",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"IO",namespace:"",file:"src/utilities/time_date.js",line:1,requires:["core"]},"Lights, Camera":{name:"Lights, Camera",submodules:{Camera:1,Lights:1,Material:1,Shaders:1},elements:{},classes:{"p5.Geometry":1,"p5.RendererGL":1,"p5.Shader":1,"p5.Texture":1},fors:{p5:1},namespaces:{},file:"src/webgl/p5.Texture.js",line:11},Camera:{name:"Camera",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Lights, Camera",namespace:"",file:"src/webgl/camera.js",line:1,requires:["core"]},Lights:{name:"Lights",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Lights, Camera",namespace:"",file:"src/webgl/light.js",line:1,requires:["core"]},"3D Models":{name:"3D Models",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Shape",namespace:"",file:"src/webgl/loading.js",line:1,requires:["core","p5.Geometry"]},Material:{name:"Material",submodules:{},elements:{},classes:{"p5.Texture":1},fors:{p5:1},is_submodule:1,namespaces:{},module:"Lights, Camera",namespace:"",file:"src/webgl/p5.Texture.js",line:11,requires:["core"],description:"

This module defines the p5.Texture class

\n"},Shaders:{name:"Shaders",submodules:{},elements:{},classes:{"p5.Shader":1},fors:{p5:1},is_submodule:1,namespaces:{},module:"Lights, Camera",namespace:"",file:"src/webgl/p5.Shader.js",line:11,description:"

This module defines the p5.Shader class

\n",requires:["core"]},"3D Primitives":{name:"3D Primitives",submodules:{},elements:{},classes:{},fors:{p5:1},is_submodule:1,namespaces:{},module:"Shape",namespace:"",file:"src/webgl/primitives.js",line:1,requires:["core","p5.Geometry"]},"p5.dom":{name:"p5.dom",submodules:{},elements:{},classes:{"p5.dom":1,"p5.MediaElement":1,"p5.File":1},fors:{"p5.dom":1,"p5.Element":1},namespaces:{},module:"p5.dom",file:"lib/addons/p5.dom.js",line:2482,description:'

The web is much more than just canvas and p5.dom makes it easy to interact\nwith other HTML5 objects, including text, hyperlink, image, input, video,\naudio, and webcam.

\n

There is a set of creation methods, DOM manipulation methods, and\nan extended p5.Element that supports a range of HTML elements. See the\n\nbeyond the canvas tutorial for a full overview of how this addon works.

\n

Methods and properties shown in black are part of the p5.js core, items in\nblue are part of the p5.dom library. You will need to include an extra file\nin order to access the blue functions. See the\nusing a library\nsection for information on how to include this library. p5.dom comes with\np5 complete or you can download the single file\n\nhere.

\n

See tutorial: beyond the canvas\nfor more info on how to use this libary.

\n',tag:"main",itemtype:"main"},"p5.sound":{name:"p5.sound",submodules:{},elements:{},classes:{p5:1,"p5.sound":1,"p5.SoundFile":1,"p5.Amplitude":1,"p5.FFT":1,"p5.Signal":1,"p5.Oscillator":1,"p5.SinOsc":1,"p5.TriOsc":1,"p5.SawOsc":1,"p5.SqrOsc":1,"p5.Env":1,"p5.Pulse":1,"p5.Noise":1,"p5.AudioIn":1,"p5.Effect":1,"p5.Filter":1,"p5.LowPass":1,"p5.HighPass":1,BandPass:1,"p5.Delay":1,"p5.Reverb":1,"p5.Convolver":1,"p5.Phrase":1,"p5.Part":1,"p5.Score":1,"p5.Compressor":1,"p5.SoundRecorder":1,"p5.PeakDetect":1,"p5.Gain":1,"p5.Distortion":1},fors:{"p5.sound":1},namespaces:{},module:"p5.sound",file:"lib/addons/p5.sound.js",line:10410,description:'

p5.sound extends p5 with Web Audio functionality including audio input,\nplayback, analysis and synthesis.\n

\np5.SoundFile: Load and play sound files.
\np5.Amplitude: Get the current volume of a sound.
\np5.AudioIn: Get sound from an input source, typically\n a computer microphone.
\np5.FFT: Analyze the frequency of sound. Returns\n results from the frequency spectrum or time domain (waveform).
\np5.Oscillator: Generate Sine,\n Triangle, Square and Sawtooth waveforms. Base class of\n p5.Noise and p5.Pulse.\n
\np5.Env: An Envelope is a series\n of fades over time. Often used to control an object's\n output gain level as an "ADSR Envelope" (Attack, Decay,\n Sustain, Release). Can also modulate other parameters.
\np5.Delay: A delay effect with\n parameters for feedback, delayTime, and lowpass filter.
\np5.Filter: Filter the frequency range of a\n sound.\n
\np5.Reverb: Add reverb to a sound by specifying\n duration and decay.
\np5.Convolver: Extends\np5.Reverb to simulate the sound of real\n physical spaces through convolution.
\np5.SoundRecorder: Record sound for playback\n / save the .wav file.\np5.Phrase, p5.Part and\np5.Score: Compose musical sequences.\n

\np5.sound is on GitHub.\nDownload the latest version\nhere.

\n',tag:"main",itemtype:"main"}},classes:{p5:{name:"p5",shortname:"p5",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:409},"p5.Color":{name:"p5.Color",shortname:"p5.Color",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Color",submodule:"Creating & Reading",namespace:"",file:"src/color/p5.Color.js",line:14,description:"

Each color stores the color mode and level maxes that applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when saturation() is requested.

\n

Internally we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer.

\n

We also cache normalized, floating point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed.

\n",is_constructor:1},"p5.Element":{name:"p5.Element",shortname:"p5.Element",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"DOM",submodule:"DOM",namespace:"",file:"src/core/p5.Element.js",line:9,description:'

Base class for all elements added to a sketch, including canvas,\ngraphics buffers, and other HTML elements. Methods in blue are\nincluded in the core functionality, methods in brown are added\nwith the p5.dom\nlibrary.\nIt is not called directly, but p5.Element\nobjects are created by calling createCanvas, createGraphics,\nor in the p5.dom library, createDiv, createImg, createInput, etc.

\n',is_constructor:1,params:[{name:"elt",description:"

DOM node that is wrapped

\n",type:"String"},{name:"pInst",description:"

pointer to p5 instance

\n",type:"P5",optional:!0}]},"p5.Graphics":{name:"p5.Graphics",shortname:"p5.Graphics",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Rendering",submodule:"Rendering",namespace:"",file:"src/core/p5.Graphics.js",line:10,description:"

Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5.

\n",is_constructor:1,extends:"p5.Element",params:[{name:"w",description:"

width

\n",type:"Number"},{name:"h",description:"

height

\n",type:"Number"},{name:"renderer",description:"

the renderer to use, either P2D or WEBGL

\n",type:"Constant"},{name:"pInst",description:"

pointer to p5 instance

\n",type:"P5",optional:!0}]},"p5.Renderer":{name:"p5.Renderer",shortname:"p5.Renderer",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Rendering",submodule:"Rendering",namespace:"",file:"src/core/p5.Renderer.js",line:10,description:"

Main graphics and rendering context, as well as the base API\nimplementation for p5.js "core". To be used as the superclass for\nRenderer2D and Renderer3D classes, respecitvely.

\n",is_constructor:1,extends:"p5.Element",params:[{name:"elt",description:"

DOM node that is wrapped

\n",type:"String"},{name:"pInst",description:"

pointer to p5 instance

\n",type:"P5",optional:!0},{name:"isMainCanvas",description:"

whether we're using it as main canvas

\n",type:"Boolean",optional:!0}]},"p5.TypedDict":{name:"p5.TypedDict",shortname:"p5.TypedDict",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Data",submodule:"Dictionary",namespace:"",file:"src/data/p5.TypedDict.js",line:48,description:"

Base class for all p5.Dictionary types. More specifically\n typed Dictionary objects inherit from this

\n",is_constructor:1},"p5.StringDict":{name:"p5.StringDict",shortname:"p5.StringDict",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Data",submodule:"Dictionary",namespace:"",file:"src/data/p5.TypedDict.js",line:330,description:"

A Dictionary class for Strings.

\n",is_constructor:1,extends:"p5.TypedDict"},"p5.NumberDict":{name:"p5.NumberDict",shortname:"p5.NumberDict",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Data",submodule:"Dictionary",namespace:"",file:"src/data/p5.TypedDict.js",line:351,description:"

A simple Dictionary class for Numbers.

\n",is_constructor:1,extends:"p5.TypedDict"},"p5.Image":{name:"p5.Image",shortname:"p5.Image",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Image",submodule:"Image",namespace:"",file:"src/image/p5.Image.js",line:23, +description:"

Creates a new p5.Image. A p5.Image is a canvas backed representation of an\nimage.\n

\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\nloadImage() function. The p5.Image class contains fields for the width and\nheight of the image, as well as an array called pixels[] that contains the\nvalues for every pixel in the image.\n

\nThe methods described below allow easy access to the image's pixels and\nalpha channel and simplify the process of compositing.\n

\nBefore using the pixels[] array, be sure to use the loadPixels() method on\nthe image to make sure that the pixel data is properly loaded.

\n",is_constructor:1,params:[{name:"width",description:"",type:"Number"},{name:"height",description:"",type:"Number"}]},"p5.Table":{name:"p5.Table",shortname:"p5.Table",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"IO",submodule:"Table",namespace:"",file:"src/io/p5.Table.js",line:36,description:"

Table objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.

\n",is_constructor:1,params:[{name:"rows",description:"

An array of p5.TableRow objects

\n",type:"p5.TableRow[]",optional:!0}]},"p5.TableRow":{name:"p5.TableRow",shortname:"p5.TableRow",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"IO",submodule:"Table",namespace:"",file:"src/io/p5.TableRow.js",line:11,description:"

A TableRow object represents a single row of data values,\nstored in columns, from a table.

\n

A Table Row contains both an ordered array, and an unordered\nJSON object.

\n",is_constructor:1,params:[{name:"str",description:"

optional: populate the row with a\n string of values, separated by the\n separator

\n",type:"String",optional:!0},{name:"separator",description:"

comma separated values (csv) by default

\n",type:"String",optional:!0}]},"p5.XML":{name:"p5.XML",shortname:"p5.XML",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"IO",submodule:"XML",namespace:"",file:"src/io/p5.XML.js",line:11,description:"

XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects.

\n",is_constructor:1,example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var children = xml.getChildren("animal");\n\n for (var i = 0; i < children.length; i++) {\n var id = children[i].getNum("id");\n var coloring = children[i].getString("species");\n var name = children[i].getContent();\n print(id + ", " + coloring + ", " + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
'],alt:"no image displayed"},"p5.Vector":{name:"p5.Vector",shortname:"p5.Vector",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Math",submodule:"Math",namespace:"",file:"src/math/p5.Vector.js",line:13,description:"

A class to describe a two or three dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude\nand direction can be accessed via the methods mag() and heading().\n

\nIn many of the p5.js examples, you will see p5.Vector used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object's position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object's velocity changes per time\nunit, expressed as a vector).\n

\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we'll need to do some\n"vector" math, which is made easy by the methods inside the p5.Vector class.

\n",is_constructor:1,params:[{name:"x",description:"

x component of the vector

\n",type:"Number",optional:!0},{name:"y",description:"

y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

z component of the vector

\n",type:"Number",optional:!0}],example:["\n
\n\nvar v1 = createVector(40, 50);\nvar v2 = createVector(40, 50);\n\nellipse(v1.x, v1.y, 50, 50);\nellipse(v2.x, v2.y, 50, 50);\nv1.add(v2);\nellipse(v1.x, v1.y, 50, 50);\n\n
"],alt:"2 white ellipses. One center-left the other bottom right and off canvas"},"p5.Font":{name:"p5.Font",shortname:"p5.Font",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Typography",submodule:"Font",namespace:"",file:"src/typography/p5.Font.js",line:21,description:"

Base class for font handling

\n",is_constructor:1,params:[{name:"pInst",description:"

pointer to p5 instance

\n",type:"P5",optional:!0}]},"p5.Geometry":{name:"p5.Geometry",shortname:"p5.Geometry",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Lights, Camera",namespace:"",file:"src/webgl/p5.Geometry.js",line:6,description:"

p5 Geometry class

\n",is_constructor:1,params:[{name:"vertData",description:"

callback function or Object\n containing routine(s) for vertex data generation

\n",type:"Function | Object"},{name:"detailX",description:"

number of vertices on horizontal surface

\n",type:"Number",optional:!0},{name:"detailY",description:"

number of vertices on horizontal surface

\n",type:"Number",optional:!0},{name:"callback",description:"

function to call upon object instantiation.

\n",type:"Function",optional:!0}]},"p5.RendererGL":{name:"p5.RendererGL",shortname:"p5.RendererGL",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Lights, Camera",namespace:"",file:"src/webgl/p5.RendererGL.js",line:36,description:"

3D graphics class

\n",is_constructor:1,extends:"p5.Renderer",todo:["extend class to include public method for offscreen\nrendering (FBO)."]},"p5.Shader":{name:"p5.Shader",shortname:"p5.Shader",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Lights, Camera",submodule:"Shaders",namespace:"",file:"src/webgl/p5.Shader.js",line:11,description:"

Shader class for WEBGL Mode

\n",is_constructor:1,params:[{name:"renderer",description:"

an instance of p5.RendererGL that\nwill provide the GL context for this new p5.Shader

\n",type:"p5.RendererGL"},{name:"vertSrc",description:"

source code for the vertex shader (as a string)

\n",type:"String"},{name:"fragSrc",description:"

source code for the fragment shader (as a string)

\n",type:"String"}]},"p5.Texture":{name:"p5.Texture",shortname:"p5.Texture",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"Lights, Camera",submodule:"Material",namespace:"",file:"src/webgl/p5.Texture.js",line:11,description:"

Texture class for WEBGL Mode

\n",is_constructor:1,params:[{name:"renderer",description:"

an instance of p5.RendererGL that\nwill provide the GL context for this new p5.Texture

\n",type:"p5.RendererGL"},{name:"obj",description:"

the\nobject containing the image data to store in the texture.

\n",type:"p5.Image|p5.Graphics|p5.Element|p5.MediaElement",optional:!0}]},"p5.dom":{name:"p5.dom",shortname:"p5.dom",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.dom",submodule:"p5.dom",namespace:""},"p5.MediaElement":{name:"p5.MediaElement",shortname:"p5.MediaElement",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.dom",submodule:"p5.dom",namespace:"",file:"lib/addons/p5.dom.js",line:1728,description:"

Extends p5.Element to handle audio and video. In addition to the methods\nof p5.Element, it also contains methods for controlling media. It is not\ncalled directly, but p5.MediaElements are created by calling createVideo,\ncreateAudio, and createCapture.

\n",is_constructor:1,params:[{name:"elt",description:"

DOM node that is wrapped

\n",type:"String"}]},"p5.File":{name:"p5.File",shortname:"p5.File",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.dom",submodule:"p5.dom",namespace:"",file:"lib/addons/p5.dom.js",line:2482,description:"

Base class for a file\nUsing this for createFileInput

\n",is_constructor:1,params:[{name:"file",description:"

File that is wrapped

\n",type:"File"}]},"p5.sound":{name:"p5.sound",shortname:"p5.sound",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:""},"p5.SoundFile":{name:"p5.SoundFile",shortname:"p5.SoundFile",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:754,description:"

SoundFile object with a path to a file.

\n\n

The p5.SoundFile may not be available immediately because\nit loads the file information asynchronously.

\n\n

To do something with the sound as soon as it loads\npass the name of a function as the second parameter.

\n\n

Only one file path is required. However, audio file formats\n(i.e. mp3, ogg, wav and m4a/aac) are not supported by all\nweb browsers. If you want to ensure compatability, instead of a single\nfile path, you may include an Array of filepaths, and the browser will\nchoose a format that works.

",is_constructor:1,params:[{name:"path",description:"

path to a sound file (String). Optionally,\n you may include multiple file formats in\n an array. Alternately, accepts an object\n from the HTML5 File API, or a p5.File.

\n",type:"String|Array"},{name:"successCallback",description:"

Name of a function to call once file loads

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

Name of a function to call if file fails to\n load. This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong.

\n",type:"Function",optional:!0},{name:"whileLoadingCallback",description:"

Name of a function to call while file\n is loading. That function will\n receive progress of the request to\n load the sound file\n (between 0 and 1) as its first\n parameter. This progress\n does not account for the additional\n time needed to decode the audio data.

\n",type:"Function",optional:!0}],example:["\n
\n\nfunction preload() {\n soundFormats('mp3', 'ogg');\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\n\n
"]},"p5.Amplitude":{name:"p5.Amplitude",shortname:"p5.Amplitude",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:2158,description:"

Amplitude measures volume between 0.0 and 1.0.\nListens to all p5sound by default, or use setInput()\nto listen to a specific sound source. Accepts an optional\nsmoothing value, which defaults to 0.

\n",is_constructor:1,params:[{name:"smoothing",description:"

between 0.0 and .999 to smooth\n amplitude readings (defaults to 0)

\n",type:"Number",optional:!0}],example:["\n
\nvar sound, amplitude, cnv;\n\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n cnv = createCanvas(100,100);\n amplitude = new p5.Amplitude();\n\n // start / stop the sound when canvas is clicked\n cnv.mouseClicked(function() {\n if (sound.isPlaying() ){\n sound.stop();\n } else {\n sound.play();\n }\n });\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\n\n
"]},"p5.FFT":{name:"p5.FFT",shortname:"p5.FFT",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:2430,description:'

FFT (Fast Fourier Transform) is an analysis algorithm that\nisolates individual\n\naudio frequencies within a waveform.

\n\n

Once instantiated, a p5.FFT object can return an array based on\ntwo types of analyses:
FFT.waveform() computes\namplitude values along the time domain. The array indices correspond\nto samples across a brief moment in time. Each value represents\namplitude of the waveform at that sample of time.
\n• FFT.analyze() computes amplitude values along the\nfrequency domain. The array indices correspond to frequencies (i.e.\npitches), from the lowest to the highest that humans can hear. Each\nvalue represents amplitude at that slice of the frequency spectrum.\nUse with getEnergy() to measure amplitude at specific\nfrequencies, or within a range of frequencies.

\n\n

FFT analyzes a very short snapshot of sound called a sample\nbuffer. It returns an array of amplitude measurements, referred\nto as bins. The array is 1024 bins long by default.\nYou can change the bin array length, but it must be a power of 2\nbetween 16 and 1024 in order for the FFT algorithm to function\ncorrectly. The actual size of the FFT buffer is twice the\nnumber of bins, so given a standard sample rate, the buffer is\n2048/44100 seconds long.

',is_constructor:1,params:[{name:"smoothing",description:"

Smooth results of Freq Spectrum.\n 0.0 < smoothing < 1.0.\n Defaults to 0.8.

\n",type:"Number",optional:!0},{name:"bins",description:"

Length of resulting array.\n Must be a power of two between\n 16 and 1024. Defaults to 1024.

\n",type:"Number",optional:!0}],example:["\n
\nfunction preload(){\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup(){\n var cnv = createCanvas(100,100);\n cnv.mouseClicked(togglePlay);\n fft = new p5.FFT();\n sound.amp(0.2);\n}\n\nfunction draw(){\n background(0);\n\n var spectrum = fft.analyze();\n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h )\n }\n\n var waveform = fft.waveform();\n noFill();\n beginShape();\n stroke(255,0,0); // waveform is red\n strokeWeight(1);\n for (var i = 0; i< waveform.length; i++){\n var x = map(i, 0, waveform.length, 0, width);\n var y = map( waveform[i], -1, 1, 0, height);\n vertex(x,y);\n }\n endShape();\n\n text('click to play/pause', 4, 10);\n}\n\n// fade sound if mouse is over canvas\nfunction togglePlay() {\n if (sound.isPlaying()) {\n sound.pause();\n } else {\n sound.loop();\n }\n}\n
"]},"p5.Signal":{name:"p5.Signal",shortname:"p5.Signal",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:4274,description:"

p5.Signal is a constant audio-rate signal used by p5.Oscillator\nand p5.Envelope for modulation math.

\n\n

This is necessary because Web Audio is processed on a seprate clock.\nFor example, the p5 draw loop runs about 60 times per second. But\nthe audio clock must process samples 44100 times per second. If we\nwant to add a value to each of those samples, we can't do it in the\ndraw loop, but we can do it by adding a constant-rate audio signal.This class mostly functions behind the scenes in p5.sound, and returns\na Tone.Signal from the Tone.js library by Yotam Mann.\nIf you want to work directly with audio signals for modular\nsynthesis, check out\ntone.js.

",is_constructor:1,return:{description:"A Signal object from the Tone.js library",type:"Tone.Signal"},example:["\n
\nfunction setup() {\n carrier = new p5.Oscillator('sine');\n carrier.amp(1); // set amplitude\n carrier.freq(220); // set frequency\n carrier.start(); // start oscillating\n\n modulator = new p5.Oscillator('sawtooth');\n modulator.disconnect();\n modulator.amp(1);\n modulator.freq(4);\n modulator.start();\n\n // Modulator's default amplitude range is -1 to 1.\n // Multiply it by -200, so the range is -200 to 200\n // then add 220 so the range is 20 to 420\n carrier.freq( modulator.mult(-200).add(220) );\n}\n
"]},"p5.Oscillator":{name:"p5.Oscillator",shortname:"p5.Oscillator",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:4419,description:'

Creates a signal that oscillates between -1.0 and 1.0.\nBy default, the oscillation takes the form of a sinusoidal\nshape ('sine'). Additional types include 'triangle',\n'sawtooth' and 'square'. The frequency defaults to\n440 oscillations per second (440Hz, equal to the pitch of an\n'A' note).

\n\n

Set the type of oscillation with setType(), or by instantiating a\nspecific oscillator: p5.SinOsc, p5.TriOsc, p5.SqrOsc, or p5.SawOsc.\n

',is_constructor:1,params:[{name:"freq",description:"

frequency defaults to 440Hz

\n",type:"Number",optional:!0},{name:"type",description:"

type of oscillator. Options:\n 'sine' (default), 'triangle',\n 'sawtooth', 'square'

\n",type:"String",optional:!0}],example:["\n
\nvar osc;\nvar playing = false;\n\nfunction setup() {\n backgroundColor = color(255,0,255);\n textAlign(CENTER);\n\n osc = new p5.Oscillator();\n osc.setType('sine');\n osc.freq(240);\n osc.amp(0);\n osc.start();\n}\n\nfunction draw() {\n background(backgroundColor)\n text('click to play', width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {\n if (!playing) {\n // ramp amplitude to 0.5 over 0.1 seconds\n osc.amp(0.5, 0.05);\n playing = true;\n backgroundColor = color(0,255,255);\n } else {\n // ramp amplitude to 0 over 0.5 seconds\n osc.amp(0, 0.5);\n playing = false;\n backgroundColor = color(255,0,255);\n }\n }\n}\n
"]},"p5.SinOsc":{name:"p5.SinOsc",shortname:"p5.SinOsc",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:4854,description:"

Constructor: new p5.SinOsc().\nThis creates a Sine Wave Oscillator and is\nequivalent to new p5.Oscillator('sine')\n or creating a p5.Oscillator and then calling\nits method setType('sine').\nSee p5.Oscillator for methods.

\n",is_constructor:1,extends:"{p5.Oscillator}",params:[{name:"freq",description:"

Set the frequency

\n",type:"Number",optional:!0}]},"p5.TriOsc":{name:"p5.TriOsc",shortname:"p5.TriOsc",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:4871,description:"

Constructor: new p5.TriOsc().\nThis creates a Triangle Wave Oscillator and is\nequivalent to new p5.Oscillator('triangle')\n or creating a p5.Oscillator and then calling\nits method setType('triangle').\nSee p5.Oscillator for methods.

\n",is_constructor:1,extends:"{p5.Oscillator}",params:[{name:"freq",description:"

Set the frequency

\n",type:"Number",optional:!0}]},"p5.SawOsc":{name:"p5.SawOsc",shortname:"p5.SawOsc",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:4888,description:"

Constructor: new p5.SawOsc().\nThis creates a SawTooth Wave Oscillator and is\nequivalent to new p5.Oscillator('sawtooth')\n or creating a p5.Oscillator and then calling\nits method setType('sawtooth').\nSee p5.Oscillator for methods.

\n",is_constructor:1,extends:"{p5.Oscillator}",params:[{name:"freq",description:"

Set the frequency

\n",type:"Number",optional:!0}]},"p5.SqrOsc":{name:"p5.SqrOsc",shortname:"p5.SqrOsc",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:4905,description:"

Constructor: new p5.SqrOsc().\nThis creates a Square Wave Oscillator and is\nequivalent to new p5.Oscillator('square')\n or creating a p5.Oscillator and then calling\nits method setType('square').\nSee p5.Oscillator for methods.

\n",is_constructor:1,extends:"{p5.Oscillator}",params:[{name:"freq",description:"

Set the frequency

\n",type:"Number",optional:!0}]},"p5.Env":{name:"p5.Env",shortname:"p5.Env",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:5280,description:'

Envelopes are pre-defined amplitude distribution over time.\nTypically, envelopes are used to control the output volume\nof an object, a series of fades referred to as Attack, Decay,\nSustain and Release (\nADSR\n). Envelopes can also control other Web Audio Parameters—for example, a p5.Env can\ncontrol an Oscillator's frequency like this: osc.freq(env).

\n

Use setRange to change the attack/release level.\nUse setADSR to change attackTime, decayTime, sustainPercent and releaseTime.

\n

Use the play method to play the entire envelope,\nthe ramp method for a pingable trigger,\nor triggerAttack/\ntriggerRelease to trigger noteOn/noteOff.

',is_constructor:1,example:["\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
"]},"p5.Pulse":{name:"p5.Pulse",shortname:"p5.Pulse",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:6076,description:'

Creates a Pulse object, an oscillator that implements\nPulse Width Modulation.\nThe pulse is created with two oscillators.\nAccepts a parameter for frequency, and to set the\nwidth between the pulses. See \np5.Oscillator for a full list of methods.

\n',extends:"p5.Oscillator",is_constructor:1,params:[{name:"freq",description:"

Frequency in oscillations per second (Hz)

\n",type:"Number",optional:!0},{name:"w",description:"

Width between the pulses (0 to 1.0,\n defaults to 0)

\n",type:"Number",optional:!0}],example:["\n
\nvar pulse;\nfunction setup() {\n background(0);\n\n // Create and start the pulse wave oscillator\n pulse = new p5.Pulse();\n pulse.amp(0.5);\n pulse.freq(220);\n pulse.start();\n}\n\nfunction draw() {\n var w = map(mouseX, 0, width, 0, 1);\n w = constrain(w, 0, 1);\n pulse.width(w)\n}\n
"]},"p5.Noise":{name:"p5.Noise",shortname:"p5.Noise",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:6253,description:"

Noise is a type of oscillator that generates a buffer with random values.

\n",extends:"p5.Oscillator",is_constructor:1,params:[{name:"type",description:"

Type of noise can be 'white' (default),\n 'brown' or 'pink'.

\n",type:"String"}]},"p5.AudioIn":{name:"p5.AudioIn",shortname:"p5.AudioIn",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:6439,description:'

Get audio from an input, i.e. your computer's microphone.

\n\n

Turn the mic on/off with the start() and stop() methods. When the mic\nis on, its volume can be measured with getLevel or by connecting an\nFFT object.

\n\n

If you want to hear the AudioIn, use the .connect() method.\nAudioIn does not connect to p5.sound output by default to prevent\nfeedback.

\n\n

Note: This uses the getUserMedia/\nStream API, which is not supported by certain browsers. Access in Chrome browser\nis limited to localhost and https, but access over http may be limited.

',is_constructor:1,params:[{name:"errorCallback",description:"

A function to call if there is an error\n accessing the AudioIn. For example,\n Safari and iOS devices do not\n currently allow microphone access.

\n",type:"Function",optional:!0}],example:["\n
\nvar mic;\nfunction setup(){\n mic = new p5.AudioIn()\n mic.start();\n}\nfunction draw(){\n background(0);\n micLevel = mic.getLevel();\n ellipse(width/2, constrain(height-micLevel*height*5, 0, height), 10, 10);\n}\n
"]},"p5.Effect":{name:"p5.Effect",shortname:"p5.Effect",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:7694,description:'

Effect is a base class for audio effects in p5.
\nThis module handles the nodes and methods that are \ncommon and useful for current and future effects.

\n

This class is extended by p5.Distortion, \np5.Compressor,\np5.Delay, \np5.Filter, \np5.Reverb.

\n',is_constructor:1,params:[{name:"ac",description:"

Reference to the audio context of the p5 object

\n",type:"Object",optional:!0},{name:"input",description:"

Gain Node effect wrapper

\n",type:"WebAudioNode",optional:!0},{name:"output",description:"

Gain Node effect wrapper

\n",type:"WebAudioNode",optional:!0},{name:"_drywet",description:"

Tone.JS CrossFade node (defaults to value: 1)

\n",type:"Object",optional:!0},{name:"wet",description:"

Effects that extend this class should connect\n to the wet signal to this gain node, so that dry and wet \n signals are mixed properly.

\n",type:"WebAudioNode",optional:!0}]},"p5.Filter":{name:"p5.Filter",shortname:"p5.Filter",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:7825,description:'

A p5.Filter uses a Web Audio Biquad Filter to filter\nthe frequency response of an input source. Subclasses\ninclude:

\n
    \n
  • p5.LowPass:\nAllows frequencies below the cutoff frequency to pass through,\nand attenuates frequencies above the cutoff.
  • \n
  • p5.HighPass:\nThe opposite of a lowpass filter.
  • \n
  • p5.BandPass:\nAllows a range of frequencies to pass through and attenuates\nthe frequencies below and above this frequency range.
  • \n
\n

The .res() method controls either width of the\nbandpass, or resonance of the low/highpass cutoff frequency.

\n

This class extends p5.Effect.
Methods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available.

\n',extends:"p5.Effect",is_constructor:1,params:[{name:"type",description:"

'lowpass' (default), 'highpass', 'bandpass'

\n",type:"String",optional:!0}],example:["\n
\nvar fft, noise, filter;\n\nfunction setup() {\n fill(255, 40, 255);\n\n filter = new p5.BandPass();\n\n noise = new p5.Noise();\n // disconnect unfiltered noise,\n // and connect to filter\n noise.disconnect();\n noise.connect(filter);\n noise.start();\n\n fft = new p5.FFT();\n}\n\nfunction draw() {\n background(30);\n\n // set the BandPass frequency based on mouseX\n var freq = map(mouseX, 0, width, 20, 10000);\n filter.freq(freq);\n // give the filter a narrow band (lower res = wider bandpass)\n filter.res(50);\n\n // draw filtered spectrum\n var spectrum = fft.analyze();\n noStroke();\n for (var i = 0; i < spectrum.length; i++) {\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width/spectrum.length, h);\n }\n\n isMouseOverCanvas();\n}\n\nfunction isMouseOverCanvas() {\n var mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n noise.amp(0.5, 0.2);\n } else {\n noise.amp(0, 0.2);\n }\n}\n
"]},"p5.LowPass":{name:"p5.LowPass",shortname:"p5.LowPass",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:8015, +description:"

Constructor: new p5.LowPass() Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('lowpass').\nSee p5.Filter for methods.

\n",is_constructor:1,extends:"{p5.Filter}"},"p5.HighPass":{name:"p5.HighPass",shortname:"p5.HighPass",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:8029,description:"

Constructor: new p5.HighPass() Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('highpass').\nSee p5.Filter for methods.

\n",is_constructor:1,extends:"{p5.Filter}"},BandPass:{name:"BandPass",shortname:"BandPass",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:8043,description:"

Constructor: new p5.BandPass() Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('bandpass').\nSee p5.Filter for methods.

\n",is_constructor:1,extends:"{p5.Filter}"},"p5.Delay":{name:"p5.Delay",shortname:"p5.Delay",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:8064,description:'

Delay is an echo effect. It processes an existing sound source,\nand outputs a delayed version of that sound. The p5.Delay can\nproduce different effects depending on the delayTime, feedback,\nfilter, and type. In the example below, a feedback of 0.5 (the\ndefaul value) will produce a looping delay that decreases in\nvolume by 50% each repeat. A filter will cut out the high\nfrequencies so that the delay does not sound as piercing as the\noriginal source.

\n

This class extends p5.Effect.
Methods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available.

\n',extends:"p5.Effect",is_constructor:1,example:["\n
\nvar noise, env, delay;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n noise = new p5.Noise('brown');\n noise.amp(0);\n noise.start();\n\n delay = new p5.Delay();\n\n // delay.process() accepts 4 parameters:\n // source, delayTime, feedback, filter frequency\n // play with these numbers!!\n delay.process(noise, .12, .7, 2300);\n\n // play the noise with an envelope,\n // a series of fades ( time / value pairs )\n env = new p5.Env(.01, 0.2, .2, .1);\n}\n\n// mouseClick triggers envelope\nfunction mouseClicked() {\n // is mouse over canvas?\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n env.play(noise);\n }\n}\n
"]},"p5.Reverb":{name:"p5.Reverb",shortname:"p5.Reverb",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:8341,description:'

Reverb adds depth to a sound through a large number of decaying\nechoes. It creates the perception that sound is occurring in a\nphysical space. The p5.Reverb has paramters for Time (how long does the\nreverb last) and decayRate (how much the sound decays with each echo)\nthat can be set with the .set() or .process() methods. The p5.Convolver\nextends p5.Reverb allowing you to recreate the sound of actual physical\nspaces through convolution.

\n

This class extends p5.Effect.
Methods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available.

\n',extends:"p5.Effect",is_constructor:1,example:["\n
\nvar soundFile, reverb;\nfunction preload() {\n soundFile = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n reverb = new p5.Reverb();\n soundFile.disconnect(); // so we'll only hear reverb...\n\n // connect soundFile to reverb, process w/\n // 3 second reverbTime, decayRate of 2%\n reverb.process(soundFile, 3, 2);\n soundFile.play();\n}\n
"]},"p5.Convolver":{name:"p5.Convolver",shortname:"p5.Convolver",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:8501,description:'

p5.Convolver extends p5.Reverb. It can emulate the sound of real\nphysical spaces through a process called \nconvolution.

\n\n

Convolution multiplies any audio input by an "impulse response"\nto simulate the dispersion of sound over time. The impulse response is\ngenerated from an audio file that you provide. One way to\ngenerate an impulse response is to pop a balloon in a reverberant space\nand record the echo. Convolution can also be used to experiment with\nsound.

\n\n

Use the method createConvolution(path) to instantiate a\np5.Convolver with a path to your impulse response audio file.

',extends:"p5.Effect",is_constructor:1,params:[{name:"path",description:"

path to a sound file

\n",type:"String"},{name:"callback",description:"

function to call when loading succeeds

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to call if loading fails.\n This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong.

\n",type:"Function",optional:!0}],example:["\n
\nvar cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons_-_power_melody'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\n
"]},"p5.Phrase":{name:"p5.Phrase",shortname:"p5.Phrase",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:9074,description:"

A phrase is a pattern of musical events over time, i.e.\na series of notes and rests.

\n\n

Phrases must be added to a p5.Part for playback, and\neach part can play multiple phrases at the same time.\nFor example, one Phrase might be a kick drum, another\ncould be a snare, and another could be the bassline.

\n\n

The first parameter is a name so that the phrase can be\nmodified or deleted later. The callback is a a function that\nthis phrase will call at every step—for example it might be\ncalled playNote(value){}. The array determines\nwhich value is passed into the callback at each step of the\nphrase. It can be numbers, an object with multiple numbers,\nor a zero (0) indicates a rest so the callback won't be called).

",is_constructor:1,params:[{name:"name",description:"

Name so that you can access the Phrase.

\n",type:"String"},{name:"callback",description:"

The name of a function that this phrase\n will call. Typically it will play a sound,\n and accept two parameters: a time at which\n to play the sound (in seconds from now),\n and a value from the sequence array. The\n time should be passed into the play() or\n start() method to ensure precision.

\n",type:"Function"},{name:"sequence",description:"

Array of values to pass into the callback\n at each step of the phrase.

\n",type:"Array"}],example:["\n
\nvar mySound, myPhrase, myPart;\nvar pattern = [1,0,0,2,0,2,0,0];\nvar msg = 'click to play';\n\nfunction preload() {\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n\n myPhrase = new p5.Phrase('bbox', makeSound, pattern);\n myPart = new p5.Part();\n myPart.addPhrase(myPhrase);\n myPart.setBPM(60);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\n}\n\nfunction makeSound(time, playbackRate) {\n mySound.rate(playbackRate);\n mySound.play(time);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing pattern';\n }\n}\n\n
"]},"p5.Part":{name:"p5.Part",shortname:"p5.Part",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:9159,description:"

A p5.Part plays back one or more p5.Phrases. Instantiate a part\nwith steps and tatums. By default, each step represents 1/16th note.

\n\n

See p5.Phrase for more about musical timing.

",is_constructor:1,params:[{name:"steps",description:"

Steps in the part

\n",type:"Number",optional:!0},{name:"tatums",description:"

Divisions of a beat (default is 1/16, a quarter note)

\n",type:"Number",optional:!0}],example:["\n
\nvar box, drum, myPart;\nvar boxPat = [1,0,0,2,0,2,0,0];\nvar drumPat = [0,1,1,0,2,0,1,0];\nvar msg = 'click to play';\n\nfunction preload() {\n box = loadSound('assets/beatbox.mp3');\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n\n var boxPhrase = new p5.Phrase('box', playBox, boxPat);\n var drumPhrase = new p5.Phrase('drum', playDrum, drumPat);\n myPart = new p5.Part();\n myPart.addPhrase(boxPhrase);\n myPart.addPhrase(drumPhrase);\n myPart.setBPM(60);\n masterVolume(0.1);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\n}\n\nfunction playBox(time, playbackRate) {\n box.rate(playbackRate);\n box.play(time);\n}\n\nfunction playDrum(time, playbackRate) {\n drum.rate(playbackRate);\n drum.play(time);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing part';\n }\n}\n
"]},"p5.Score":{name:"p5.Score",shortname:"p5.Score",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:9413,description:"

A Score consists of a series of Parts. The parts will\nbe played back in order. For example, you could have an\nA part, a B part, and a C part, and play them back in this order\nnew p5.Score(a, a, b, a, c)

\n",is_constructor:1,params:[{name:"parts",description:"

One or multiple parts, to be played in sequence.

\n",type:"p5.Part",optional:!0,multiple:!0}]},"p5.Compressor":{name:"p5.Compressor",shortname:"p5.Compressor",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:9544,description:'

Compressor is an audio effect class that performs dynamics compression\non an audio input source. This is a very commonly used technique in music\nand sound production. Compression creates an overall louder, richer, \nand fuller sound by lowering the volume of louds and raising that of softs.\nCompression can be used to avoid clipping (sound distortion due to \npeaks in volume) and is especially useful when many sounds are played \nat once. Compression can be used on indivudal sound sources in addition\nto the master output.

\n

This class extends p5.Effect.
Methods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available.

\n',is_constructor:1,extends:"p5.Effect"},"p5.SoundRecorder":{name:"p5.SoundRecorder",shortname:"p5.SoundRecorder",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:9750,description:"

Record sounds for playback and/or to save as a .wav file.\nThe p5.SoundRecorder records all sound output from your sketch,\nor can be assigned a specific source with setInput().

\n

The record() method accepts a p5.SoundFile as a parameter.\nWhen playback is stopped (either after the given amount of time,\nor with the stop() method), the p5.SoundRecorder will send its\nrecording to that p5.SoundFile for playback.

",is_constructor:1,example:["\n
\nvar mic, recorder, soundFile;\nvar state = 0;\n\nfunction setup() {\n background(200);\n // create an audio in\n mic = new p5.AudioIn();\n\n // prompts user to enable their browser mic\n mic.start();\n\n // create a sound recorder\n recorder = new p5.SoundRecorder();\n\n // connect the mic to the recorder\n recorder.setInput(mic);\n\n // this sound file will be used to\n // playback & save the recording\n soundFile = new p5.SoundFile();\n\n text('keyPress to record', 20, 20);\n}\n\nfunction keyPressed() {\n // make sure user enabled the mic\n if (state === 0 && mic.enabled) {\n\n // record to our p5.SoundFile\n recorder.record(soundFile);\n\n background(255,0,0);\n text('Recording!', 20, 20);\n state++;\n }\n else if (state === 1) {\n background(0,255,0);\n\n // stop recorder and\n // send result to soundFile\n recorder.stop();\n\n text('Stopped', 20, 20);\n state++;\n }\n\n else if (state === 2) {\n soundFile.play(); // play the result!\n save(soundFile, 'mySound.wav');\n state++;\n }\n}\n
"]},"p5.PeakDetect":{name:"p5.PeakDetect",shortname:"p5.PeakDetect",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:10039,description:'

PeakDetect works in conjunction with p5.FFT to\nlook for onsets in some or all of the frequency spectrum.\n

\n

\nTo use p5.PeakDetect, call update in the draw loop\nand pass in a p5.FFT object.\n

\n

\nYou can listen for a specific part of the frequency spectrum by\nsetting the range between freq1 and freq2.\n

\n\n

threshold is the threshold for detecting a peak,\nscaled between 0 and 1. It is logarithmic, so 0.1 is half as loud\nas 1.0.

\n\n

\nThe update method is meant to be run in the draw loop, and\nframes determines how many loops must pass before\nanother peak can be detected.\nFor example, if the frameRate() = 60, you could detect the beat of a\n120 beat-per-minute song with this equation:\n framesPerPeak = 60 / (estimatedBPM / 60 );\n

\n\n

\nBased on example contribtued by @b2renger, and a simple beat detection\nexplanation by a\nhref="http://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/"\ntarget="_blank"Felix Turner.\n

',is_constructor:1,params:[{name:"freq1",description:"

lowFrequency - defaults to 20Hz

\n",type:"Number",optional:!0},{name:"freq2",description:"

highFrequency - defaults to 20000 Hz

\n",type:"Number",optional:!0},{name:"threshold",description:"

Threshold for detecting a beat between 0 and 1\n scaled logarithmically where 0.1 is 1/2 the loudness\n of 1.0. Defaults to 0.35.

\n",type:"Number",optional:!0},{name:"framesPerPeak",description:"

Defaults to 20.

\n",type:"Number",optional:!0}],example:["\n
\n\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 10;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n\n soundFile = loadSound('assets/beat.mp3');\n\n // p5.PeakDetect requires a p5.FFT\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n\n}\n\nfunction draw() {\n background(0);\n text('click to play/pause', width/2, height/2);\n\n // peakDetect accepts an fft post-analysis\n fft.analyze();\n peakDetect.update(fft);\n\n if ( peakDetect.isDetected ) {\n ellipseWidth = 50;\n } else {\n ellipseWidth *= 0.95;\n }\n\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// toggle play/stop when canvas is clicked\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n }\n}\n
"]},"p5.Gain":{name:"p5.Gain",shortname:"p5.Gain",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:10259,description:"

A gain node is usefull to set the relative volume of sound.\nIt's typically used to build mixers.

\n",is_constructor:1,example:["\n
\n\n // load two soundfile and crossfade beetween them\n var sound1,sound2;\n var gain1, gain2, gain3;\n\n function preload(){\n soundFormats('ogg', 'mp3');\n sound1 = loadSound('../_files/Damscray_-_Dancing_Tiger_01');\n sound2 = loadSound('../_files/beat.mp3');\n }\n\n function setup() {\n createCanvas(400,200);\n\n // create a 'master' gain to which we will connect both soundfiles\n gain3 = new p5.Gain();\n gain3.connect();\n\n // setup first sound for playing\n sound1.rate(1);\n sound1.loop();\n sound1.disconnect(); // diconnect from p5 output\n\n gain1 = new p5.Gain(); // setup a gain node\n gain1.setInput(sound1); // connect the first sound to its input\n gain1.connect(gain3); // connect its output to the 'master'\n\n sound2.rate(1);\n sound2.disconnect();\n sound2.loop();\n\n gain2 = new p5.Gain();\n gain2.setInput(sound2);\n gain2.connect(gain3);\n\n }\n\n function draw(){\n background(180);\n\n // calculate the horizontal distance beetween the mouse and the right of the screen\n var d = dist(mouseX,0,width,0);\n\n // map the horizontal position of the mouse to values useable for volume control of sound1\n var vol1 = map(mouseX,0,width,0,1);\n var vol2 = 1-vol1; // when sound1 is loud, sound2 is quiet and vice versa\n\n gain1.amp(vol1,0.5,0);\n gain2.amp(vol2,0.5,0);\n\n // map the vertical position of the mouse to values useable for 'master volume control'\n var vol3 = map(mouseY,0,height,0,1);\n gain3.amp(vol3,0.5,0);\n }\n
\n"]},"p5.Distortion":{name:"p5.Distortion",shortname:"p5.Distortion",classitems:[],plugins:[],extensions:[],plugin_for:[],extension_for:[],module:"p5.sound",submodule:"p5.sound",namespace:"",file:"lib/addons/p5.sound.js",line:10410,description:'

A Distortion effect created with a Waveshaper Node,\nwith an approach adapted from\nKevin Ennis

\n

This class extends p5.Effect.
Methods amp(), chain(), \ndrywet(), connect(), and \ndisconnect() are available.

\n',extends:"p5.Effect",is_constructor:1,params:[{name:"amount",description:"

Unbounded distortion amount.\n Normal values range from 0-1.

\n",type:"Number",optional:!0,optdefault:"0.25"},{name:"oversample",description:"

'none', '2x', or '4x'.

\n",type:"String",optional:!0,optdefault:"'none'"}]}},elements:{},classitems:[{file:"src/color/color_conversion.js",line:10,description:'

Conversions adapted from http://www.easyrgb.com/math.html.

\n

In these functions, hue is always in the range [0,1); all other components\nare in the range [0,1]. 'Brightness' and 'value' are used interchangeably.

\n',class:"p5",module:"Conversion",submodule:"Color Conversion"},{file:"src/color/color_conversion.js",line:20,description:"

Convert an HSBA array to HSLA.

\n",class:"p5",module:"Conversion",submodule:"Color Conversion"},{file:"src/color/color_conversion.js",line:46,description:"

Convert an HSBA array to RGBA.

\n",class:"p5",module:"Conversion",submodule:"Color Conversion"},{file:"src/color/color_conversion.js",line:95,description:"

Convert an HSLA array to HSBA.

\n",class:"p5",module:"Conversion",submodule:"Color Conversion"},{file:"src/color/color_conversion.js",line:118,description:"

Convert an HSLA array to RGBA.

\n

We need to change basis from HSLA to something that can be more easily be\nprojected onto RGBA. We will choose hue and brightness as our first two\ncomponents, and pick a convenient third one ('zest') so that we don't need\nto calculate formal HSBA saturation.

\n",class:"p5",module:"Conversion",submodule:"Color Conversion"},{file:"src/color/color_conversion.js",line:176,description:"

Convert an RGBA array to HSBA.

\n",class:"p5",module:"Conversion",submodule:"Color Conversion"},{file:"src/color/color_conversion.js",line:211,description:"

Convert an RGBA array to HSLA.

\n",class:"p5",module:"Conversion",submodule:"Color Conversion"},{file:"src/color/creating_reading.js",line:16,description:"

Extracts the alpha value from a color or pixel array.

\n",itemtype:"method",name:"alpha",params:[{name:"color",description:"

p5.Color object or pixel array

\n",type:"p5.Color|Array"}],return:{description:"the alpha value",type:"Number"},example:["\n
\n\nnoStroke();\nc = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nvalue = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\n\n
"],alt:"Left half of canvas light blue and right half light charcoal grey.\nLeft half of canvas light purple and right half a royal blue.\nLeft half of canvas salmon pink and the right half white.\nYellow rect in middle right of canvas, with 55 pixel width and height.\nYellow ellipse in top left canvas, black ellipse in bottom right,both 80x80.\nBright fuschia rect in middle of canvas, 60 pixel width and height.\nTwo bright green rects on opposite sides of the canvas, both 45x80.\nFour blue rects in each corner of the canvas, each are 35x35.\nBright sea green rect on left and darker rect on right of canvas, both 45x80.\nDark green rect on left and light green rect on right of canvas, both 45x80.\nDark blue rect on left and light teal rect on right of canvas, both 45x80.\nblue rect on left and green on right, both with black outlines & 35x60.\nsalmon pink rect on left and black on right, both 35x60.\n4 rects, tan, brown, brownish purple and purple, with white outlines & 20x60.\nlight pastel green rect on left and dark grey rect on right, both 35x60.\nyellow rect on left and red rect on right, both with black outlines & 35x60.\ngrey canvas\ndeep pink rect on left and grey rect on right, both 35x60.",class:"p5",module:"Color",submodule:"Creating & Reading"},{file:"src/color/creating_reading.js",line:60,description:"

Extracts the blue value from a color or pixel array.

\n",itemtype:"method",name:"blue",params:[{name:"color",description:"

p5.Color object or pixel array

\n",type:"p5.Color|Array"}],return:{description:"the blue value",type:"Number"},example:["\n
\n\nc = color(175, 100, 220); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nblueValue = blue(c); // Get blue in 'c'\nprint(blueValue); // Prints \"220.0\"\nfill(0, 0, blueValue); // Use 'blueValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
"],alt:"Left half of canvas light purple and right half a royal blue.",class:"p5",module:"Color",submodule:"Creating & Reading"},{file:"src/color/creating_reading.js",line:89,description:"

Extracts the HSB brightness value from a color or pixel array.

\n",itemtype:"method",name:"brightness",params:[{name:"color",description:"

p5.Color object or pixel array

\n",type:"p5.Color|Array"}],return:{description:"the brightness value",type:"Number"},example:["\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nc = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvalue = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\n\n
"],alt:"Left half of canvas salmon pink and the right half white.",class:"p5",module:"Color",submodule:"Creating & Reading"},{file:"src/color/creating_reading.js",line:118,description:"

Creates colors for storing in variables of the color datatype. The\nparameters are interpreted as RGB or HSB values depending on the\ncurrent colorMode(). The default mode is RGB values from 0 to 255\nand, therefore, the function call color(255, 204, 0) will return a\nbright yellow color.\n

\nNote that if only one value is provided to color(), it will be interpreted\nas a grayscale value. Add a second value, and it will be used for alpha\ntransparency. When three values are specified, they are interpreted as\neither RGB or HSB values. Adding a fourth value applies alpha\ntransparency.\n

\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.

\n",itemtype:"method",name:"color",return:{description:"resulting color",type:"p5.Color"},example:["\n
\n\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(30, 20, 55, 55); // Draw rectangle\n\n
\n\n
\n\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nellipse(25, 25, 80, 80); // Draw left circle\n\n// Using only one value with color()\n// generates a grayscale value.\nvar c = color(65); // Update 'c' with grayscale value\nfill(c); // Use updated 'c' as fill color\nellipse(75, 75, 80, 80); // Draw right circle\n\n
\n\n
\n\n// Named SVG & CSS colors may be used,\nvar c = color('magenta');\nfill(c); // Use 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(20, 20, 60, 60); // Draw rectangle\n\n
\n\n
\n\n// as can hex color codes:\nnoStroke(); // Don't draw a stroke around shapes\nvar c = color('#0f0');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('#00ff00');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n\n
\n\n
\n\n// RGB and RGBA color strings are also supported:\n// these all set to the same color (solid blue)\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('rgb(0,0,255)');\nfill(c); // Use 'c' as fill color\nrect(10, 10, 35, 35); // Draw rectangle\n\nc = color('rgb(0%, 0%, 100%)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 35, 35); // Draw rectangle\n\nc = color('rgba(0, 0, 255, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(10, 55, 35, 35); // Draw rectangle\n\nc = color('rgba(0%, 0%, 100%, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 55, 35, 35); // Draw rectangle\n\n
\n\n
\n\n// HSL color is also supported and can be specified\n// by value\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsl(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsla(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n\n
\n\n
\n\n// HSB color is also supported and can be specified\n// by value\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsb(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsba(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n\n
\n\n
\n\nvar c; // Declare color 'c'\nnoStroke(); // Don't draw a stroke around shapes\n\n// If no colorMode is specified, then the\n// default of RGB with scale of 0-255 is used.\nc = color(50, 55, 100); // Create a color for 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(0, 10, 45, 80); // Draw left rect\n\ncolorMode(HSB, 100); // Use HSB with scale of 0-100\nc = color(50, 55, 100); // Update 'c' with new color\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw right rect\n\n
"],alt:"Yellow rect in middle right of canvas, with 55 pixel width and height.\nYellow ellipse in top left of canvas, black ellipse in bottom right,both 80x80.\nBright fuschia rect in middle of canvas, 60 pixel width and height.\nTwo bright green rects on opposite sides of the canvas, both 45x80.\nFour blue rects in each corner of the canvas, each are 35x35.\nBright sea green rect on left and darker rect on right of canvas, both 45x80.\nDark green rect on left and lighter green rect on right of canvas, both 45x80.\nDark blue rect on left and light teal rect on right of canvas, both 45x80.",class:"p5",module:"Color",submodule:"Creating & Reading",overloads:[{line:118,params:[{name:"gray",description:"

number specifying value between white\n and black.

\n",type:"Number"},{name:"alpha",description:"

alpha value relative to current color range\n (default is 0-255)

\n",type:"Number",optional:!0}],return:{description:"resulting color",type:"p5.Color"}},{line:277,params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],return:{description:"",type:"p5.Color"}},{line:289,params:[{name:"value",description:"

a color string

\n",type:"String"},{name:"alpha",description:"",type:"Number",optional:!0}],return:{description:"",type:"p5.Color"}},{line:295,params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Array"}],return:{description:"",type:"p5.Color"}},{line:301,params:[{name:"color",description:"",type:"p5.Color" +}],return:{description:"",type:"p5.Color"}}]},{file:"src/color/creating_reading.js",line:326,description:"

Extracts the green value from a color or pixel array.

\n",itemtype:"method",name:"green",params:[{name:"color",description:"

p5.Color object or pixel array

\n",type:"p5.Color|Array"}],return:{description:"the green value",type:"Number"},example:["\n
\n\nc = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\ngreenValue = green(c); // Get green in 'c'\nprint(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
"],alt:"blue rect on left and green on right, both with black outlines & 35x60.",class:"p5",module:"Color",submodule:"Creating & Reading"},{file:"src/color/creating_reading.js",line:356,description:"

Extracts the hue value from a color or pixel array.

\n

Hue exists in both HSB and HSL. This function will return the\nHSB-normalized hue when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL-normalized hue otherwise. (The values will only be different if the\nmaximum hue setting for each system is different.)

\n",itemtype:"method",name:"hue",params:[{name:"color",description:"

p5.Color object or pixel array

\n",type:"p5.Color|Array"}],return:{description:"the hue",type:"Number"},example:["\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nc = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvalue = hue(c); // Sets 'value' to \"0\"\nfill(value);\nrect(50, 20, 35, 60);\n\n
"],alt:"salmon pink rect on left and black on right, both 35x60.",class:"p5",module:"Color",submodule:"Creating & Reading"},{file:"src/color/creating_reading.js",line:392,description:"

Blends two colors to find a third color somewhere between them. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first color, 0.1 is very near the first color, 0.5 is halfway\nin between, etc. An amount below 0 will be treated as 0. Likewise, amounts\nabove 1 will be capped at 1. This is different from the behavior of lerp(),\nbut necessary because otherwise numbers outside the range will produce\nstrange and unexpected colors.\n

\nThe way that colours are interpolated depends on the current color mode.

\n",itemtype:"method",name:"lerpColor",params:[{name:"c1",description:"

interpolate from this color

\n",type:"p5.Color"},{name:"c2",description:"

interpolate to this color

\n",type:"p5.Color"},{name:"amt",description:"

number between 0 and 1

\n",type:"Number"}],return:{description:"interpolated color",type:"p5.Color"},example:["\n
\n\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nfrom = color(218, 165, 32);\nto = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\ninterA = lerpColor(from, to, .33);\ninterB = lerpColor(from, to, .66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\n\n
"],alt:"4 rects one tan, brown, brownish purple, purple, with white outlines & 20x60",class:"p5",module:"Color",submodule:"Creating & Reading"},{file:"src/color/creating_reading.js",line:489,description:"

Extracts the HSL lightness value from a color or pixel array.

\n",itemtype:"method",name:"lightness",params:[{name:"color",description:"

p5.Color object or pixel array

\n",type:"p5.Color|Array"}],return:{description:"the lightness",type:"Number"},example:["\n
\n\nnoStroke();\ncolorMode(HSL);\nc = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nvalue = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\n\n
"],alt:"light pastel green rect on left and dark grey rect on right, both 35x60.",class:"p5",module:"Color",submodule:"Creating & Reading"},{file:"src/color/creating_reading.js",line:518,description:"

Extracts the red value from a color or pixel array.

\n",itemtype:"method",name:"red",params:[{name:"color",description:"

p5.Color object or pixel array

\n",type:"p5.Color|Array"}],return:{description:"the red value",type:"Number"},example:["\n
\n\nc = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nredValue = red(c); // Get red in 'c'\nprint(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
\n\n
\n\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\ncolorMode(RGB, 1);\nvar myColor = red(c);\nprint(myColor);\n\n
"],alt:"yellow rect on left and red rect on right, both with black outlines and 35x60.\ngrey canvas",class:"p5",module:"Color",submodule:"Creating & Reading"},{file:"src/color/creating_reading.js",line:557,description:"

Extracts the saturation value from a color or pixel array.

\n

Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL saturation otherwise.

\n",itemtype:"method",name:"saturation",params:[{name:"color",description:"

p5.Color object or pixel array

\n",type:"p5.Color|Array"}],return:{description:"the saturation value",type:"Number"},example:["\n
\n\nnoStroke();\ncolorMode(HSB, 255);\nc = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvalue = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\n\n
"],alt:"deep pink rect on left and grey rect on right, both 35x60.",class:"p5",module:"Color",submodule:"Creating & Reading"},{file:"src/color/p5.Color.js",line:118,description:"

Hue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.

\n",class:"p5.Color",module:"Color",submodule:"Creating & Reading"},{file:"src/color/p5.Color.js",line:149,description:"

Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise.

\n",class:"p5.Color",module:"Color",submodule:"Creating & Reading"},{file:"src/color/p5.Color.js",line:168,description:"

CSS named colors.

\n",class:"p5.Color",module:"Color",submodule:"Creating & Reading"},{file:"src/color/p5.Color.js",line:321,description:"

These regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code.

\n

Note that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.

\n",class:"p5.Color",module:"Color",submodule:"Creating & Reading"},{file:"src/color/p5.Color.js",line:334,description:"

Full color string patterns. The capture groups are necessary.

\n",class:"p5.Color",module:"Color",submodule:"Creating & Reading"},{file:"src/color/p5.Color.js",line:447,description:"

For a number of different inputs, returns a color formatted as [r, g, b, a]\narrays, with each component normalized between 0 and 1.

\n",params:[{name:"args",description:"

An 'array-like' object that represents a list of\n arguments

\n",type:"Array",optional:!0,multiple:!0}],return:{description:"a color formatted as [r, g, b, a]\n Example:\n input ==> output\n g ==> [g, g, g, 255]\n g,a ==> [g, g, g, a]\n r, g, b ==> [r, g, b, 255]\n r, g, b, a ==> [r, g, b, a]\n [g] ==> [g, g, g, 255]\n [g, a] ==> [g, g, g, a]\n [r, g, b] ==> [r, g, b, 255]\n [r, g, b, a] ==> [r, g, b, a]",type:"Number[]"},example:["\n
\n\n// todo\n\n
"],alt:"//todo",class:"p5.Color",module:"Color",submodule:"Creating & Reading"},{file:"src/color/p5.Color.js",line:638,description:"

For HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum.

\n",class:"p5.Color",module:"Color",submodule:"Creating & Reading"},{file:"src/color/setting.js",line:15,description:"

The background() function sets the color used for the background of the\np5.js canvas. The default background is light gray. This function is\ntypically used within draw() to clear the display window at the beginning\nof each frame, but it can be used inside setup() to set the background on\nthe first frame of animation or if the background need only be set once.\n

\nThe color is either specified in terms of the RGB, HSB, or HSL color\ndepending on the current colorMode. (The default color space is RGB, with\neach value in the range from 0 to 255).\n

\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n

\nA p5.Color object can also be provided to set the background color.\n

\nA p5.Image can also be provided to set the background iamge.

\n",itemtype:"method",name:"background",chainable:1,example:["\n
\n\n// Grayscale integer value\nbackground(51);\n\n
\n\n
\n\n// R, G & B integer values\nbackground(255, 204, 0);\n\n
\n\n
\n\n// H, S & B integer values\ncolorMode(HSB);\nbackground(255, 204, 100);\n\n
\n\n
\n\n// Named SVG/CSS color string\nbackground('red');\n\n
\n\n
\n\n// three-digit hexadecimal RGB notation\nbackground('#fae');\n\n
\n\n
\n\n// six-digit hexadecimal RGB notation\nbackground('#222222');\n\n
\n\n
\n\n// integer RGB notation\nbackground('rgb(0,255,0)');\n\n
\n\n
\n\n// integer RGBA notation\nbackground('rgba(0,255,0, 0.25)');\n\n
\n\n
\n\n// percentage RGB notation\nbackground('rgb(100%,0%,10%)');\n\n
\n\n
\n\n// percentage RGBA notation\nbackground('rgba(100%,0%,100%,0.5)');\n\n
\n\n
\n\n// p5 Color object\nbackground(color(0, 0, 255));\n\n
"],alt:"canvas with darkest charcoal grey background.\ncanvas with yellow background.\ncanvas with royal blue background.\ncanvas with red background.\ncanvas with pink background.\ncanvas with black background.\ncanvas with bright green background.\ncanvas with soft green background.\ncanvas with red background.\ncanvas with light purple background.\ncanvas with blue background.",class:"p5",module:"Color",submodule:"Setting",overloads:[{line:15,params:[{name:"color",description:"

any value created by the color() function

\n",type:"p5.Color"},{name:"a",description:"

opacity of the background relative to current\n color range (default is 0-100)

\n",type:"Number",optional:!0}],chainable:1},{line:133,params:[{name:"colorstring",description:"

color string, possible formats include: integer\n rgb() or rgba(), percentage rgb() or rgba(),\n 3-digit hex, 6-digit hex

\n",type:"String"},{name:"a",description:"",type:"Number",optional:!0}],chainable:1},{line:142,params:[{name:"gray",description:"

specifies a value between white and black

\n",type:"Number"},{name:"a",description:"",type:"Number",optional:!0}],chainable:1},{line:149,params:[{name:"v1",description:"

red or hue value (depending on the current color\n mode)

\n",type:"Number"},{name:"v2",description:"

green or saturation value (depending on the current\n color mode)

\n",type:"Number"},{name:"v3",description:"

blue or brightness value (depending on the current\n color mode)

\n",type:"Number"},{name:"a",description:"",type:"Number",optional:!0}],chainable:1},{line:161,params:[{name:"image",description:"

image created with loadImage() or createImage(),\n to set as background\n (must be same size as the sketch window)

\n",type:"p5.Image"},{name:"a",description:"",type:"Number",optional:!0}],chainable:1}]},{file:"src/color/setting.js",line:178,description:"

Clears the pixels within a buffer. This function only works on p5.Canvas\nobjects created with the createCanvas() function; it won't work with the\nmain display window. Unlike the main graphics context, pixels in\nadditional graphics areas created with createGraphics() can be entirely\nor partially transparent. This function clears everything to make all of\nthe pixels 100% transparent.

\n",itemtype:"method",name:"clear",chainable:1,example:["\n
\n\n// Clear the screen on mouse press.\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n ellipse(mouseX, mouseY, 20, 20);\n}\n\nfunction mousePressed() {\n clear();\n}\n\n
"],alt:"20x20 white ellipses are continually drawn at mouse x and y coordinates.",class:"p5",module:"Color",submodule:"Setting"},{file:"src/color/setting.js",line:216,description:"

colorMode() changes the way p5.js interprets color data. By default, the\nparameters for fill(), stroke(), background(), and color() are defined by\nvalues between 0 and 255 using the RGB color model. This is equivalent to\nsetting colorMode(RGB, 255). Setting colorMode(HSB) lets you use the HSB\nsystem instead. By default, this is colorMode(HSB, 360, 100, 100, 1). You\ncan also use HSL.\n

\nNote: existing color objects remember the mode that they were created in,\nso you can change modes as you like without affecting their appearance.

\n",itemtype:"method",name:"colorMode",chainable:1,class:"p5",module:"Color",submodule:"Setting",overloads:[{line:216,params:[{name:"mode",description:"

either RGB, HSB or HSL, corresponding to\n Red/Green/Blue and Hue/Saturation/Brightness\n (or Lightness)

\n",type:"Constant"},{name:"max",description:"

range for all values

\n",type:"Number",optional:!0}],chainable:1},{line:235,params:[{name:"mode",description:"",type:"Constant"},{name:"max1",description:"

range for the red or hue depending on the\n current color mode

\n",type:"Number"},{name:"max2",description:"

range for the green or saturation depending\n on the current color mode

\n",type:"Number"},{name:"max3",description:"

range for the blue or brightness/lighntess\n depending on the current color mode

\n",type:"Number"},{name:"maxA",description:"

range for the alpha

\n",type:"Number",optional:!0}],chainable:1}]},{file:"src/color/setting.js",line:335,description:"

Sets the color used to fill shapes. For example, if you run\nfill(204, 102, 0), all subsequent shapes will be filled with orange. This\ncolor is either specified in terms of the RGB or HSB color depending on\nthe current colorMode(). (The default color space is RGB, with each value\nin the range from 0 to 255).\n

\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n

\nA p5 Color object can also be provided to set the fill color.

\n",itemtype:"method",name:"fill",chainable:1,class:"p5",module:"Color",submodule:"Setting",overloads:[{line:335,params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{line:359,params:[{name:"value",description:"

a color string

\n",type:"String"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{line:366,params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}],chainable:1},{line:373,params:[{name:"color",description:"

the fill color

\n",type:"p5.Color"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1}]},{file:"src/color/setting.js",line:489,description:"

Disables filling geometry. If both noStroke() and noFill() are called,\nnothing will be drawn to the screen.

\n",itemtype:"method",name:"noFill",chainable:1,example:["\n
\n\nrect(15, 10, 55, 55);\nnoFill();\nrect(20, 20, 60, 60);\n\n
"],alt:"white rect top middle and noFill rect center. Both 60x60 with black outlines.",class:"p5",module:"Color",submodule:"Setting"},{file:"src/color/setting.js",line:514,description:"

Disables drawing the stroke (outline). If both noStroke() and noFill()\nare called, nothing will be drawn to the screen.

\n",itemtype:"method",name:"noStroke",chainable:1,example:["\n
\n\nnoStroke();\nrect(20, 20, 60, 60);\n\n
"],alt:"60x60 white rect at center. no outline.",class:"p5",module:"Color",submodule:"Setting"},{file:"src/color/setting.js",line:542,description:"

Sets the color used to draw lines and borders around shapes. This color\nis either specified in terms of the RGB or HSB color depending on the\ncurrent colorMode() (the default color space is RGB, with each value in\nthe range from 0 to 255).\n

\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.\n

\nA p5 Color object can also be provided to set the stroke color.

\n",itemtype:"method",name:"stroke",chainable:1,class:"p5",module:"Color",submodule:"Setting",overloads:[{line:542,params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{line:567,params:[{name:"value",description:"

a color string

\n",type:"String"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{line:574,params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}],chainable:1},{line:581,params:[{name:"color",description:"

the stroke color

\n",type:"p5.Color"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1}]},{file:"src/core/2d_primitives.js",line:16,description:"

Draw an arc to the screen. If called with only a, b, c, d, start, and\nstop, the arc will be drawn as an open pie. If mode is provided, the arc\nwill be drawn either open, as a chord, or as a pie as specified. The\norigin may be changed with the ellipseMode() function.

\nNote that drawing a full circle (ex: 0 to TWO_PI) will appear blank\nbecause 0 and TWO_PI are the same position on the unit circle. The\nbest way to handle this is by using the ellipse() function instead\nto create a closed ellipse, and to use the arc() function\nonly to draw parts of an ellipse.

\n",itemtype:"method",name:"arc",params:[{name:"a",description:"

x-coordinate of the arc's ellipse

\n",type:"Number"},{name:"b",description:"

y-coordinate of the arc's ellipse

\n",type:"Number"},{name:"c",description:"

width of the arc's ellipse by default

\n",type:"Number"},{name:"d",description:"

height of the arc's ellipse by default

\n",type:"Number"},{name:"start",description:"

angle to start the arc, specified in radians

\n",type:"Number"},{name:"stop",description:"

angle to stop the arc, specified in radians

\n",type:"Number"},{name:"mode",description:"

optional parameter to determine the way of drawing\n the arc. either CHORD or PIE

\n",type:"Constant",optional:!0}],chainable:1,example:["\n
\n\narc(50, 55, 50, 50, 0, HALF_PI);\nnoFill();\narc(50, 55, 60, 60, HALF_PI, PI);\narc(50, 55, 70, 70, PI, PI+QUARTER_PI);\narc(50, 55, 80, 80, PI+QUARTER_PI, TWO_PI);\n\n
\n\n
\n\narc(50, 50, 80, 80, 0, PI+QUARTER_PI, OPEN);\n\n
\n\n
\n\narc(50, 50, 80, 80, 0, PI+QUARTER_PI, CHORD);\n\n
\n\n
\n\narc(50, 50, 80, 80, 0, PI+QUARTER_PI, PIE);\n\n
"],alt:"shattered outline of an ellipse with a quarter of a white circle bottom-right.\nwhite ellipse with black outline with top right missing.\nwhite ellipse with top right missing with black outline around shape.\nwhite ellipse with top right quarter missing with black outline around the shape.",class:"p5",module:"Shape",submodule:"2D Primitives"},{file:"src/core/2d_primitives.js",line:132,description:"

Draws an ellipse (oval) to the screen. An ellipse with equal width and\nheight is a circle. By default, the first two parameters set the location,\nand the third and fourth parameters set the shape's width and height. If\nno height is specified, the value of width is used for both the width and\nheight. If a negative height or width is specified, the absolute value is taken.\nThe origin may be changed with the ellipseMode() function.

\n",itemtype:"method",name:"ellipse",params:[{name:"x",description:"

x-coordinate of the ellipse.

\n",type:"Number"},{name:"y",description:"

y-coordinate of the ellipse.

\n",type:"Number"},{name:"w",description:"

width of the ellipse.

\n",type:"Number"},{name:"h",description:"

height of the ellipse.

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\nellipse(56, 46, 55, 55);\n\n
"],alt:"white ellipse with black outline in middle-right of canvas that is 55x55.",class:"p5",module:"Shape",submodule:"2D Primitives"},{file:"src/core/2d_primitives.js",line:187,description:"

Draws a line (a direct path between two points) to the screen. The version\nof line() with four parameters draws the line in 2D. To color a line, use\nthe stroke() function. A line cannot be filled, therefore the fill()\nfunction will not affect the color of a line. 2D lines are drawn with a\nwidth of one pixel by default, but this can be changed with the\nstrokeWeight() function.

\n",itemtype:"method",name:"line",params:[{name:"x1",description:"

the x-coordinate of the first point

\n",type:"Number"},{name:"y1",description:"

the y-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"

the x-coordinate of the second point

\n",type:"Number"},{name:"y2",description:"

the y-coordinate of the second point

\n",type:"Number"}],chainable:1,example:["\n
\n\nline(30, 20, 85, 75);\n\n
\n\n
\n\nline(30, 20, 85, 20);\nstroke(126);\nline(85, 20, 85, 75);\nstroke(255);\nline(85, 75, 30, 75);\n\n
"],alt:"line 78 pixels long running from mid-top to bottom-right of canvas.\n3 lines of various stroke sizes. Form top, bottom and right sides of a square.",class:"p5",module:"Shape",submodule:"2D Primitives"},{file:"src/core/2d_primitives.js",line:262,description:"

Draws a point, a coordinate in space at the dimension of one pixel.\nThe first parameter is the horizontal value for the point, the second\nvalue is the vertical value for the point. The color of the point is\ndetermined by the current stroke.

\n",itemtype:"method",name:"point",params:[{name:"x",description:"

the x-coordinate

\n",type:"Number"},{name:"y",description:"

the y-coordinate

\n",type:"Number"}],chainable:1,example:["\n
\n\npoint(30, 20);\npoint(85, 20);\npoint(85, 75);\npoint(30, 75);\n\n
"],alt:"4 points centered in the middle-right of the canvas.",class:"p5",module:"Shape",submodule:"2D Primitives"},{file:"src/core/2d_primitives.js",line:313,description:"

Draw a quad. A quad is a quadrilateral, a four sided polygon. It is\nsimilar to a rectangle, but the angles between its edges are not\nconstrained to ninety degrees. The first pair of parameters (x1,y1)\nsets the first vertex and the subsequent pairs should proceed\nclockwise or counter-clockwise around the defined shape.

\n",itemtype:"method",name:"quad",chainable:1,example:["\n
\n\nquad(38, 31, 86, 20, 69, 63, 30, 76);\n\n
"],alt:"irregular white quadrilateral shape with black outline mid-right of canvas.",class:"p5",module:"Shape",submodule:"2D Primitives",overloads:[{line:313,params:[{name:"x1",description:"

the x-coordinate of the first point

\n",type:"Number"},{name:"y1",description:"

the y-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"

the x-coordinate of the second point

\n",type:"Number"},{name:"y2",description:"

the y-coordinate of the second point

\n",type:"Number"},{name:"x3",description:"

the x-coordinate of the third point

\n",type:"Number"},{name:"y3",description:"

the y-coordinate of the third point

\n",type:"Number"},{name:"x4",description:"

the x-coordinate of the fourth point

\n",type:"Number"},{name:"y4",description:"

the y-coordinate of the fourth point

\n",type:"Number"}],chainable:1},{line:341,params:[{name:"x1",description:"",type:"Number"},{name:"y1",description:"",type:"Number"},{name:"x2",description:"",type:"Number"},{name:"y2",description:"",type:"Number"},{name:"x3",description:"",type:"Number"},{name:"y3",description:"",type:"Number"},{name:"x4",description:"",type:"Number"},{name:"y4",description:"",type:"Number"}],chainable:1}]},{file:"src/core/2d_primitives.js",line:393,description:"

Draws a rectangle to the screen. A rectangle is a four-sided shape with\nevery angle at ninety degrees. By default, the first two parameters set\nthe location of the upper-left corner, the third sets the width, and the\nfourth sets the height. The way these parameters are interpreted, however,\nmay be changed with the rectMode() function.\n

\nThe fifth, sixth, seventh and eighth parameters, if specified,\ndetermine corner radius for the top-right, top-left, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.

\n",itemtype:"method",name:"rect",return:{description:"the p5 object.",type:"P5"},example:["\n
\n\n// Draw a rectangle at location (30, 20) with a width and height of 55.\nrect(30, 20, 55, 55);\n\n
\n\n
\n\n// Draw a rectangle with rounded corners, each having a radius of 20.\nrect(30, 20, 55, 55, 20);\n\n
\n\n
\n\n// Draw a rectangle with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nrect(30, 20, 55, 55, 20, 15, 10, 5);\n\n
"],alt:"55x55 white rect with black outline in mid-right of canvas.\n55x55 white rect with black outline and rounded edges in mid-right of canvas.\n55x55 white rect with black outline and rounded edges of different radii.",class:"p5",module:"Shape",submodule:"2D Primitives",overloads:[{line:393,params:[{name:"x",description:"

x-coordinate of the rectangle.

\n",type:"Number"},{name:"y",description:"

y-coordinate of the rectangle.

\n",type:"Number"},{name:"w",description:"

width of the rectangle.

\n",type:"Number"},{name:"h",description:"

height of the rectangle.

\n",type:"Number"},{name:"tl",description:"

optional radius of top-left corner.

\n",type:"Number",optional:!0},{name:"tr",description:"

optional radius of top-right corner.

\n",type:"Number",optional:!0},{name:"br",description:"

optional radius of bottom-right corner.

\n",type:"Number",optional:!0},{name:"bl",description:"

optional radius of bottom-left corner.

\n",type:"Number",optional:!0}],return:{description:"the p5 object.",type:"P5"}},{line:443,params:[{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"w",description:"",type:"Number"},{name:"h",description:"",type:"Number"},{name:"detailX",description:"",type:"Number",optional:!0},{name:"detailY",description:"",type:"Number",optional:!0}],chainable:1}]},{file:"src/core/2d_primitives.js",line:477,description:"

A triangle is a plane created by connecting three points. The first two\narguments specify the first point, the middle two arguments specify the\nsecond point, and the last two arguments specify the third point.

\n",itemtype:"method",name:"triangle",params:[{name:"x1",description:"

x-coordinate of the first point

\n",type:"Number"},{name:"y1",description:"

y-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"

x-coordinate of the second point

\n",type:"Number"},{name:"y2",description:"

y-coordinate of the second point

\n",type:"Number"},{name:"x3",description:"

x-coordinate of the third point

\n",type:"Number"},{name:"y3",description:"

y-coordinate of the third point

\n",type:"Number"}],chainable:1,example:["\n
\n\ntriangle(30, 75, 58, 20, 86, 75);\n\n
"],alt:"white triangle with black outline in mid-right of canvas.",class:"p5",module:"Shape",submodule:"2D Primitives"},{file:"src/core/attributes.js",line:14,description:"

Modifies the location from which ellipses are drawn by changing the way\nin which parameters given to ellipse() are interpreted.\n

\nThe default mode is ellipseMode(CENTER), which interprets the first two\nparameters of ellipse() as the shape's center point, while the third and\nfourth parameters are its width and height.\n

\nellipseMode(RADIUS) also uses the first two parameters of ellipse() as\nthe shape's center point, but uses the third and fourth parameters to\nspecify half of the shapes's width and height.\n

\nellipseMode(CORNER) interprets the first two parameters of ellipse() as\nthe upper-left corner of the shape, while the third and fourth parameters\nare its width and height.\n

\nellipseMode(CORNERS) interprets the first two parameters of ellipse() as\nthe location of one corner of the ellipse's bounding box, and the third\nand fourth parameters as the location of the opposite corner.\n

\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.

\n",itemtype:"method",name:"ellipseMode",params:[{name:"mode",description:"

either CENTER, RADIUS, CORNER, or CORNERS

\n",type:"Constant"}],chainable:1, +example:["\n
\n\nellipseMode(RADIUS); // Set ellipseMode to RADIUS\nfill(255); // Set fill to white\nellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode\n\nellipseMode(CENTER); // Set ellipseMode to CENTER\nfill(100); // Set fill to gray\nellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode\n\n
\n\n
\n\nellipseMode(CORNER); // Set ellipseMode is CORNER\nfill(255); // Set fill to white\nellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode\n\nellipseMode(CORNERS); // Set ellipseMode to CORNERS\nfill(100); // Set fill to gray\nellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode\n\n
"],alt:"60x60 white ellipse and 30x30 grey ellipse with black outlines at center.\n60x60 white ellipse @center and 30x30 grey ellipse top-right, black outlines.",class:"p5",module:"Shape",submodule:"Attributes"},{file:"src/core/attributes.js",line:80,description:"

Draws all geometry with jagged (aliased) edges. Note that smooth() is\nactive by default, so it is necessary to call noSmooth() to disable\nsmoothing of geometry, images, and fonts.

\n",itemtype:"method",name:"noSmooth",chainable:1,example:["\n
\n\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n\n
"],alt:"2 pixelated 36x36 white ellipses to left & right of center, black background",class:"p5",module:"Shape",submodule:"Attributes"},{file:"src/core/attributes.js",line:108,description:"

Modifies the location from which rectangles are drawn by changing the way\nin which parameters given to rect() are interpreted.\n

\nThe default mode is rectMode(CORNER), which interprets the first two\nparameters of rect() as the upper-left corner of the shape, while the\nthird and fourth parameters are its width and height.\n

\nrectMode(CORNERS) interprets the first two parameters of rect() as the\nlocation of one corner, and the third and fourth parameters as the\nlocation of the opposite corner.\n

\nrectMode(CENTER) interprets the first two parameters of rect() as the\nshape's center point, while the third and fourth parameters are its\nwidth and height.\n

\nrectMode(RADIUS) also uses the first two parameters of rect() as the\nshape's center point, but uses the third and fourth parameters to specify\nhalf of the shapes's width and height.\n

\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.

\n",itemtype:"method",name:"rectMode",params:[{name:"mode",description:"

either CORNER, CORNERS, CENTER, or RADIUS

\n",type:"Constant"}],chainable:1,example:["\n
\n\nrectMode(CORNER); // Default rectMode is CORNER\nfill(255); // Set fill to white\nrect(25, 25, 50, 50); // Draw white rect using CORNER mode\n\nrectMode(CORNERS); // Set rectMode to CORNERS\nfill(100); // Set fill to gray\nrect(25, 25, 50, 50); // Draw gray rect using CORNERS mode\n\n
\n\n
\n\nrectMode(RADIUS); // Set rectMode to RADIUS\nfill(255); // Set fill to white\nrect(50, 50, 30, 30); // Draw white rect using RADIUS mode\n\nrectMode(CENTER); // Set rectMode to CENTER\nfill(100); // Set fill to gray\nrect(50, 50, 30, 30); // Draw gray rect using CENTER mode\n\n
"],alt:"50x50 white rect at center and 25x25 grey rect in the top left of the other.\n50x50 white rect at center and 25x25 grey rect in the center of the other.",class:"p5",module:"Shape",submodule:"Attributes"},{file:"src/core/attributes.js",line:174,description:"

Draws all geometry with smooth (anti-aliased) edges. smooth() will also\nimprove image quality of resized images. Note that smooth() is active by\ndefault; noSmooth() can be used to disable smoothing of geometry,\nimages, and fonts.

\n",itemtype:"method",name:"smooth",chainable:1,example:["\n
\n\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n\n
"],alt:"2 pixelated 36x36 white ellipses one left one right of center. On black.",class:"p5",module:"Shape",submodule:"Attributes"},{file:"src/core/attributes.js",line:203,description:"

Sets the style for rendering line endings. These ends are either squared,\nextended, or rounded, each of which specified with the corresponding\nparameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND.

\n",itemtype:"method",name:"strokeCap",params:[{name:"cap",description:"

either SQUARE, PROJECT, or ROUND

\n",type:"Constant"}],chainable:1,example:["\n
\n\nstrokeWeight(12.0);\nstrokeCap(ROUND);\nline(20, 30, 80, 30);\nstrokeCap(SQUARE);\nline(20, 50, 80, 50);\nstrokeCap(PROJECT);\nline(20, 70, 80, 70);\n\n
"],alt:"3 lines. Top line: rounded ends, mid: squared, bottom:longer squared ends.",class:"p5",module:"Shape",submodule:"Attributes"},{file:"src/core/attributes.js",line:237,description:"

Sets the style of the joints which connect line segments. These joints\nare either mitered, beveled, or rounded and specified with the\ncorresponding parameters MITER, BEVEL, and ROUND. The default joint is\nMITER.

\n",itemtype:"method",name:"strokeJoin",params:[{name:"join",description:"

either MITER, BEVEL, ROUND

\n",type:"Constant"}],chainable:1,example:["\n
\n\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(MITER);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n\n
\n\n
\n\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(BEVEL);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n\n
\n\n
\n\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(ROUND);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n\n
"],alt:"Right-facing arrowhead shape with pointed tip in center of canvas.\nRight-facing arrowhead shape with flat tip in center of canvas.\nRight-facing arrowhead shape with rounded tip in center of canvas.",class:"p5",module:"Shape",submodule:"Attributes"},{file:"src/core/attributes.js",line:301,description:"

Sets the width of the stroke used for lines, points, and the border\naround shapes. All widths are set in units of pixels.

\n",itemtype:"method",name:"strokeWeight",params:[{name:"weight",description:"

the weight (in pixels) of the stroke

\n",type:"Number"}],return:{description:"the p5 object",type:"P5"},example:["\n
\n\nstrokeWeight(1); // Default\nline(20, 20, 80, 20);\nstrokeWeight(4); // Thicker\nline(20, 40, 80, 40);\nstrokeWeight(10); // Beastly\nline(20, 70, 80, 70);\n\n
"],alt:"3 horizontal black lines. Top line: thin, mid: medium, bottom:thick.",class:"p5",module:"Shape",submodule:"Attributes"},{file:"src/core/canvas.js",line:1,requires:["constants"],class:"p5",module:"Shape"},{file:"src/core/constants.js",line:12,itemtype:"property",name:"P2D",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:17,itemtype:"property",name:"WEBGL",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:33,description:"

HALF_PI is a mathematical constant with the value\n1.57079632679489661923. It is half the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos().

\n",itemtype:"property",name:"HALF_PI",type:"Number",final:1,example:["\n
\narc(50, 50, 80, 80, 0, HALF_PI);\n
"],alt:"80x80 white quarter-circle with curve toward bottom right of canvas.",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:52,description:"

PI is a mathematical constant with the value\n3.14159265358979323846. It is the ratio of the circumference\nof a circle to its diameter. It is useful in combination with\nthe trigonometric functions sin() and cos().

\n",itemtype:"property",name:"PI",type:"Number",final:1,example:["\n
\narc(50, 50, 80, 80, 0, PI);\n
"],alt:"white half-circle with curve toward bottom of canvas.",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:71,description:"

QUARTER_PI is a mathematical constant with the value 0.7853982.\nIt is one quarter the ratio of the circumference of a circle to\nits diameter. It is useful in combination with the trigonometric\nfunctions sin() and cos().

\n",itemtype:"property",name:"QUARTER_PI",type:"Number",final:1,example:["\n
\narc(50, 50, 80, 80, 0, QUARTER_PI);\n
"],alt:"white eighth-circle rotated about 40 degrees with curve bottom right canvas.",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:90,description:"

TAU is an alias for TWO_PI, a mathematical constant with the\nvalue 6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos().

\n",itemtype:"property",name:"TAU",type:"Number",final:1,example:["\n
\narc(50, 50, 80, 80, 0, TAU);\n
"],alt:"80x80 white ellipse shape in center of canvas.",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:109,description:"

TWO_PI is a mathematical constant with the value\n6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos().

\n",itemtype:"property",name:"TWO_PI",type:"Number",final:1,example:["\n
\narc(50, 50, 80, 80, 0, TWO_PI);\n
"],alt:"80x80 white ellipse shape in center of canvas.",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:128,itemtype:"property",name:"DEGREES",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:133,itemtype:"property",name:"RADIANS",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:142,itemtype:"property",name:"CORNER",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:147,itemtype:"property",name:"CORNERS",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:152,itemtype:"property",name:"RADIUS",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:157,itemtype:"property",name:"RIGHT",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:162,itemtype:"property",name:"LEFT",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:167,itemtype:"property",name:"CENTER",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:172,itemtype:"property",name:"TOP",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:177,itemtype:"property",name:"BOTTOM",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:182,itemtype:"property",name:"BASELINE",type:"String",final:1,default:"alphabetic",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:188,itemtype:"property",name:"POINTS",type:"Number",final:1,default:"0x0000",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:194,itemtype:"property",name:"LINES",type:"Number",final:1,default:"0x0001",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:200,itemtype:"property",name:"LINE_STRIP",type:"Number",final:1,default:"0x0003",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:206,itemtype:"property",name:"LINE_LOOP",type:"Number",final:1,default:"0x0002",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:212,itemtype:"property",name:"TRIANGLES",type:"Number",final:1,default:"0x0004",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:218,itemtype:"property",name:"TRIANGLE_FAN",type:"Number",final:1,default:"0x0006",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:224,itemtype:"property",name:"TRIANGLE_STRIP",type:"Number",final:1,default:"0x0005",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:230,itemtype:"property",name:"QUADS",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:235,itemtype:"property",name:"QUAD_STRIP",type:"String",final:1,default:"quad_strip",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:241,itemtype:"property",name:"CLOSE",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:246,itemtype:"property",name:"OPEN",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:251,itemtype:"property",name:"CHORD",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:256,itemtype:"property",name:"PIE",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:261,itemtype:"property",name:"PROJECT",type:"String",final:1,default:"square",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:267,itemtype:"property",name:"SQUARE",type:"String",final:1,default:"butt",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:273,itemtype:"property",name:"ROUND",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:278,itemtype:"property",name:"BEVEL",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:283,itemtype:"property",name:"MITER",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:290,itemtype:"property",name:"RGB",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:295,itemtype:"property",name:"HSB",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:300,itemtype:"property",name:"HSL",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:326,itemtype:"property",name:"BLEND",type:"String",final:1,default:"source-over",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:332,itemtype:"property",name:"ADD",type:"String",final:1,default:"lighter",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:340,itemtype:"property",name:"DARKEST",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:345,itemtype:"property",name:"LIGHTEST",type:"String",final:1,default:"lighten",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:351,itemtype:"property",name:"DIFFERENCE",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:356,itemtype:"property",name:"EXCLUSION",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:361,itemtype:"property",name:"MULTIPLY",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:366,itemtype:"property",name:"SCREEN",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:371,itemtype:"property",name:"REPLACE",type:"String",final:1,default:"copy",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:377,itemtype:"property",name:"OVERLAY",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:382,itemtype:"property",name:"HARD_LIGHT",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:387,itemtype:"property",name:"SOFT_LIGHT",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:392,itemtype:"property",name:"DODGE",type:"String",final:1,default:"color-dodge",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:398,itemtype:"property",name:"BURN",type:"String",final:1,default:"color-burn",class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:406,itemtype:"property",name:"THRESHOLD",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:411,itemtype:"property",name:"GRAY",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:416,itemtype:"property",name:"OPAQUE",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:421,itemtype:"property",name:"INVERT",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:426,itemtype:"property",name:"POSTERIZE",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:431,itemtype:"property",name:"DILATE",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:436,itemtype:"property",name:"ERODE",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:441,itemtype:"property",name:"BLUR",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:448,itemtype:"property",name:"NORMAL",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:453,itemtype:"property",name:"ITALIC",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:458,itemtype:"property",name:"BOLD",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:482,itemtype:"property",name:"LANDSCAPE",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/constants.js",line:487,itemtype:"property",name:"PORTRAIT",type:"String",final:1,class:"p5",module:"Constants",submodule:"Constants"},{file:"src/core/core.js",line:15,description:"

This is the p5 instance constructor.

\n

A p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set preload(), setup(), and/or\ndraw() properties on it for running a sketch.

\n

A p5 sketch can run in "global" or "instance" mode:\n"global" - all properties and methods are attached to the window\n"instance" - all properties and methods are bound to this p5 object

\n",params:[{name:"sketch",description:"

a closure that can set optional preload(),\n setup(), and/or draw() properties on the\n given p5 instance

\n",type:"Function"},{name:"node",description:"

element to attach canvas to, if a\n boolean is passed in use it as sync

\n",type:"HTMLElement|boolean",optional:!0},{name:"sync",description:"

start synchronously (optional)

\n",type:"Boolean",optional:!0}],return:{description:"a p5 instance",type:"P5"},class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/core.js",line:49,description:'

Called directly before setup(), the preload() function is used to handle\nasynchronous loading of external files. If a preload function is\ndefined, setup() will wait until any load calls within have finished.\nNothing besides load calls should be inside preload (loadImage,\nloadJSON, loadFont, loadStrings, etc).

\nBy default the text "loading..." will be displayed. To make your own\nloading page, include an HTML element with id "p5_loading" in your\npage. More information here.

\n',itemtype:"method",name:"preload",example:["\n
\nvar img;\nvar c;\nfunction preload() { // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() { // setup() waits until preload() is done\n img.loadPixels();\n // get color of middle pixel\n c = img.get(img.width/2, img.height/2);\n}\n\nfunction draw() {\n background(c);\n image(img, 25, 25, 50, 50);\n}\n
"],alt:"nothing displayed",class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/core.js",line:85,description:"

The setup() function is called once when the program starts. It's used to\ndefine initial environment properties such as screen size and background\ncolor and to load media such as images and fonts as the program starts.\nThere can only be one setup() function for each program and it shouldn't\nbe called again after its initial execution.\n

\nNote: Variables declared within setup() are not accessible within other\nfunctions, including draw().

\n",itemtype:"method",name:"setup",example:["\n
\nvar a = 0;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(102);\n}\n\nfunction draw() {\n rect(a++%width, 10, 2, 80);\n}\n
"],alt:"nothing displayed",class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/core.js",line:116,description:"

Called directly after setup(), the draw() function continuously executes\nthe lines of code contained inside its block until the program is stopped\nor noLoop() is called. Note if noLoop() is called in setup(), draw() will\nstill be executed once before stopping. draw() is called automatically and\nshould never be called explicitly.\n

\nIt should always be controlled with noLoop(), redraw() and loop(). After\nnoLoop() stops the code in draw() from executing, redraw() causes the\ncode inside draw() to execute once, and loop() will cause the code\ninside draw() to resume executing continuously.\n

\nThe number of times draw() executes in each second may be controlled with\nthe frameRate() function.\n

\nThere can only be one draw() function for each sketch, and draw() must\nexist if you want the code to run continuously, or to process events such\nas mousePressed(). Sometimes, you might have an empty call to draw() in\nyour program, as shown in the above example.\n

\nIt is important to note that the drawing coordinate system will be reset\nat the beginning of each draw() call. If any transformations are performed\nwithin draw() (ex: scale, rotate, translate, their effects will be\nundone at the beginning of draw(), so transformations will not accumulate\nover time. On the other hand, styling applied (ex: fill, stroke, etc) will\nremain in effect.

\n",itemtype:"method",name:"draw",example:["\n
\nvar yPos = 0;\nfunction setup() { // setup() runs once\n frameRate(30);\n}\nfunction draw() { // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n
"],alt:"nothing displayed",class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/core.js",line:393,description:"

Removes the entire p5 sketch. This will remove the canvas and any\nelements created by p5.js. It will also stop the draw loop and unbind\nany properties or methods from the window global scope. It will\nleave a variable p5 in case you wanted to create a new p5 sketch.\nIf you like, you can set p5 = null to erase it. While all functions and\nvariables and objects created by the p5 library will be removed, any\nother global variables created by your code will remain.

\n",itemtype:"method",name:"remove",example:["\n
\nfunction draw() {\n ellipse(50, 50, 10, 10);\n}\n\nfunction mousePressed() {\n remove(); // remove whole sketch on mouse press\n}\n
"],alt:"nothing displayed",class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/curves.js",line:16,description:"

Draws a cubic Bezier curve on the screen. These curves are defined by a\nseries of anchor and control points. The first two parameters specify\nthe first anchor point and the last two parameters specify the other\nanchor point, which become the first and last points on the curve. The\nmiddle parameters specify the two control points which define the shape\nof the curve. Approximately speaking, control points "pull" the curve\ntowards them.

Bezier curves were developed by French\nautomotive engineer Pierre Bezier, and are commonly used in computer\ngraphics to define gently sloping curves. See also curve().

\n",itemtype:"method",name:"bezier",return:{description:"the p5 object",type:"P5"},example:["\n
\n\nnoFill();\nstroke(255, 102, 0);\nline(85, 20, 10, 10);\nline(90, 90, 15, 80);\nstroke(0, 0, 0);\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\n\n
"],alt:"stretched black s-shape in center with orange lines extending from end points.\nstretched black s-shape with 10 5x5 white ellipses along the shape.\nstretched black s-shape with 7 5x5 ellipses and orange lines along the shape.\nstretched black s-shape with 17 small orange lines extending from under shape.\nhorseshoe shape with orange ends facing left and black curved center.\nhorseshoe shape with orange ends facing left and black curved center.\nLine shaped like right-facing arrow,points move with mouse-x and warp shape.\nhorizontal line that hooks downward on the right and 13 5x5 ellipses along it.\nright curving line mid-right of canvas with 7 short lines radiating from it.",class:"p5",module:"Shape",submodule:"Curves",overloads:[{line:16,params:[{name:"x1",description:"

x-coordinate for the first anchor point

\n",type:"Number"},{name:"y1",description:"

y-coordinate for the first anchor point

\n",type:"Number"},{name:"x2",description:"

x-coordinate for the first control point

\n",type:"Number"},{name:"y2",description:"

y-coordinate for the first control point

\n",type:"Number"},{name:"x3",description:"

x-coordinate for the second control point

\n",type:"Number"},{name:"y3",description:"

y-coordinate for the second control point

\n",type:"Number"},{name:"x4",description:"

x-coordinate for the second anchor point

\n",type:"Number"},{name:"y4",description:"

y-coordinate for the second anchor point

\n",type:"Number"}],return:{description:"the p5 object",type:"P5"}},{line:59,params:[{name:"z1",description:"

z-coordinate for the first anchor point

\n",type:"Number"},{name:"z2",description:"

z-coordinate for the first control point

\n",type:"Number"},{name:"z3",description:"

z-coordinate for the first anchor point

\n",type:"Number"},{name:"z4",description:"

z-coordinate for the first control point

\n",type:"Number"}],chainable:1}]},{file:"src/core/curves.js",line:99,description:"

Sets the resolution at which Beziers display.

\n

The default value is 20.

\n",params:[{name:"detail",description:"

resolution of the curves

\n",type:"Number"}],chainable:1,example:["\n
\n\nbackground(204);\nbezierDetail(50);\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\n\n
"],alt:"stretched black s-shape with 7 5x5 ellipses and orange lines along the shape.",class:"p5",module:"Shape",submodule:"Curves"},{file:"src/core/curves.js",line:124,description:"

Evaluates the Bezier at position t for points a, b, c, d.\nThe parameters a and d are the first and last points\non the curve, and b and c are the control points.\nThe final parameter t varies between 0 and 1.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a bezier curve at t.

\n",itemtype:"method",name:"bezierPoint",params:[{name:"a",description:"

coordinate of first point on the curve

\n",type:"Number"},{name:"b",description:"

coordinate of first control point

\n",type:"Number"},{name:"c",description:"

coordinate of second control point

\n",type:"Number"},{name:"d",description:"

coordinate of second point on the curve

\n",type:"Number"},{name:"t",description:"

value between 0 and 1

\n",type:"Number"}],return:{description:"the value of the Bezier at position t",type:"Number"},example:["\n
\n\nnoFill();\nx1 = 85, x2 = 10, x3 = 90, x4 = 15;\ny1 = 20, y2 = 10, y3 = 90, y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nsteps = 10;\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n x = bezierPoint(x1, x2, x3, x4, t);\n y = bezierPoint(y1, y2, y3, y4, t);\n ellipse(x, y, 5, 5);\n}\n\n
"],alt:"stretched black s-shape with 17 small orange lines extending from under shape.",class:"p5",module:"Shape",submodule:"Curves"},{file:"src/core/curves.js",line:175,description:"

Evaluates the tangent to the Bezier at position t for points a, b, c, d.\nThe parameters a and d are the first and last points\non the curve, and b and c are the control points.\nThe final parameter t varies between 0 and 1.

\n",itemtype:"method",name:"bezierTangent",params:[{name:"a",description:"

coordinate of first point on the curve

\n",type:"Number"},{name:"b",description:"

coordinate of first control point

\n",type:"Number"},{name:"c",description:"

coordinate of second control point

\n",type:"Number"},{name:"d",description:"

coordinate of second point on the curve

\n",type:"Number"},{name:"t",description:"

value between 0 and 1

\n",type:"Number"}],return:{description:"the tangent at position t",type:"Number"},example:["\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nsteps = 6;\nfill(255);\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n // Get the location of the point\n x = bezierPoint(85, 10, 90, 15, t);\n y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n tx = bezierTangent(85, 10, 90, 15, t);\n ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n a = atan2(ty, tx);\n a += PI;\n stroke(255, 102, 0);\n line(x, y, cos(a)*30 + x, sin(a)*30 + y);\n // The following line of code makes a line\n // inverse of the above line\n //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);\n stroke(0);\n ellipse(x, y, 5, 5);\n}\n\n
\n\n
\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nsteps = 16;\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n x = bezierPoint(85, 10, 90, 15, t);\n y = bezierPoint(20, 10, 90, 80, t);\n tx = bezierTangent(85, 10, 90, 15, t);\n ty = bezierTangent(20, 10, 90, 80, t);\n a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a)*8 + x, sin(a)*8 + y);\n}\n\n
"],alt:"s-shaped line with 17 short orange lines extending from underside of shape",class:"p5",module:"Shape",submodule:"Curves"},{file:"src/core/curves.js",line:256, +description:"

Draws a curved line on the screen between two points, given as the\nmiddle four parameters. The first two parameters are a control point, as\nif the curve came from this point even though it's not drawn. The last\ntwo parameters similarly describe the other control point.

\nLonger curves can be created by putting a series of curve() functions\ntogether or using curveVertex(). An additional function called\ncurveTightness() provides control for the visual quality of the curve.\nThe curve() function is an implementation of Catmull-Rom splines.

\n",itemtype:"method",name:"curve",return:{description:"the p5 object",type:"P5"},example:["\n
\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\nstroke(0);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nstroke(255, 102, 0);\ncurve(73, 24, 73, 61, 15, 65, 15, 65);\n\n
\n
\n\n// Define the curve points as JavaScript objects\np1 = {x: 5, y: 26}, p2 = {x: 73, y: 24}\np3 = {x: 73, y: 61}, p4 = {x: 15, y: 65}\nnoFill();\nstroke(255, 102, 0);\ncurve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y)\nstroke(0);\ncurve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y)\nstroke(255, 102, 0);\ncurve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y)\n\n
"],alt:"horseshoe shape with orange ends facing left and black curved center.\nhorseshoe shape with orange ends facing left and black curved center.",class:"p5",module:"Shape",submodule:"Curves",overloads:[{line:256,params:[{name:"x1",description:"

x-coordinate for the beginning control point

\n",type:"Number"},{name:"y1",description:"

y-coordinate for the beginning control point

\n",type:"Number"},{name:"x2",description:"

x-coordinate for the first point

\n",type:"Number"},{name:"y2",description:"

y-coordinate for the first point

\n",type:"Number"},{name:"x3",description:"

x-coordinate for the second point

\n",type:"Number"},{name:"y3",description:"

y-coordinate for the second point

\n",type:"Number"},{name:"x4",description:"

x-coordinate for the ending control point

\n",type:"Number"},{name:"y4",description:"

y-coordinate for the ending control point

\n",type:"Number"}],return:{description:"the p5 object",type:"P5"}},{line:308,params:[{name:"z1",description:"

z-coordinate for the beginning control point

\n",type:"Number"},{name:"z2",description:"

z-coordinate for the first point

\n",type:"Number"},{name:"z3",description:"

z-coordinate for the second point

\n",type:"Number"},{name:"z4",description:"

z-coordinate for the ending control point

\n",type:"Number"}],chainable:1}]},{file:"src/core/curves.js",line:353,description:"

Sets the resolution at which curves display.

\n

The default value is 20.

\n",params:[{name:"resolution",description:"

of the curves

\n",type:"Number"}],chainable:1,example:["\n
\n\nbackground(204);\ncurveDetail(20);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\n\n
"],alt:"white arch shape in top-mid canvas.",class:"p5",module:"Shape",submodule:"Curves"},{file:"src/core/curves.js",line:378,description:"

Modifies the quality of forms created with curve() and curveVertex().\nThe parameter tightness determines how the curve fits to the vertex\npoints. The value 0.0 is the default value for tightness (this value\ndefines the curves to be Catmull-Rom splines) and the value 1.0 connects\nall the points with straight lines. Values within the range -5.0 and 5.0\nwill deform the curves but will leave them recognizable and as values\nincrease in magnitude, they will continue to deform.

\n",itemtype:"method",name:"curveTightness",params:[{name:"amount",description:"

of deformation from the original vertices

\n",type:"Number"}],chainable:1,example:["\n
\n\n// Move the mouse left and right to see the curve change\n\nfunction setup() {\n createCanvas(100, 100);\n noFill();\n}\n\nfunction draw() {\n background(204);\n var t = map(mouseX, 0, width, -5, 5);\n curveTightness(t);\n beginShape();\n curveVertex(10, 26);\n curveVertex(10, 26);\n curveVertex(83, 24);\n curveVertex(83, 61);\n curveVertex(25, 65);\n curveVertex(25, 65);\n endShape();\n}\n\n
"],alt:"Line shaped like right-facing arrow,points move with mouse-x and warp shape.",class:"p5",module:"Shape",submodule:"Curves"},{file:"src/core/curves.js",line:423,description:"

Evaluates the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are points\non the curve, and b and c are the control points.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a curve at t.

\n",itemtype:"method",name:"curvePoint",params:[{name:"a",description:"

coordinate of first point on the curve

\n",type:"Number"},{name:"b",description:"

coordinate of first control point

\n",type:"Number"},{name:"c",description:"

coordinate of second control point

\n",type:"Number"},{name:"d",description:"

coordinate of second point on the curve

\n",type:"Number"},{name:"t",description:"

value between 0 and 1

\n",type:"Number"}],return:{description:"bezier value at position t",type:"Number"},example:["\n
\n\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nsteps = 6;\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n x = curvePoint(5, 5, 73, 73, t);\n y = curvePoint(26, 26, 24, 61, t);\n ellipse(x, y, 5, 5);\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n ellipse(x, y, 5, 5);\n}\n\n
\n\nline hooking down to right-bottom with 13 5x5 white ellipse points"],class:"p5",module:"Shape",submodule:"Curves"},{file:"src/core/curves.js",line:476,description:"

Evaluates the tangent to the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are points on the curve,\nand b and c are the control points.

\n",itemtype:"method",name:"curveTangent",params:[{name:"a",description:"

coordinate of first point on the curve

\n",type:"Number"},{name:"b",description:"

coordinate of first control point

\n",type:"Number"},{name:"c",description:"

coordinate of second control point

\n",type:"Number"},{name:"d",description:"

coordinate of second point on the curve

\n",type:"Number"},{name:"t",description:"

value between 0 and 1

\n",type:"Number"}],return:{description:"the tangent at position t",type:"Number"},example:["\n
\n\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nsteps = 6;\nfor (i = 0; i <= steps; i++) {\n t = i / steps;\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n tx = curveTangent(5, 73, 73, 15, t);\n ty = curveTangent(26, 24, 61, 65, t);\n a = atan2(ty, tx);\n a -= PI/2.0;\n line(x, y, cos(a)*8 + x, sin(a)*8 + y);\n}\n\n
"],alt:"right curving line mid-right of canvas with 7 short lines radiating from it.",class:"p5",module:"Shape",submodule:"Curves"},{file:"src/core/environment.js",line:22,description:"

The print() function writes to the console area of your browser.\nThis function is often helpful for looking at the data a program is\nproducing. This function creates a new line of text for each call to\nthe function. Individual elements can be\nseparated with quotes ("") and joined with the addition operator (+).

\n",itemtype:"method",name:"print",params:[{name:"contents",description:"

any combination of Number, String, Object, Boolean,\n Array to print

\n",type:"Any"}],example:['\n
\nvar x = 10;\nprint("The value of x is " + x);\n// prints "The value of x is 10"\n
'],alt:"default grey canvas",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:51,description:"

The system variable frameCount contains the number of frames that have\nbeen displayed since the program started. Inside setup() the value is 0,\nafter the first iteration of draw it is 1, etc.

\n",itemtype:"property",name:"frameCount",type:"Number",readonly:"",example:["\n
\n function setup() {\n frameRate(30);\n textSize(20);\n textSize(30);\n textAlign(CENTER);\n }\n\n function draw() {\n background(200);\n text(frameCount, width/2, height/2);\n }\n
"],alt:"numbers rapidly counting upward with frame count set to 30.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:79,description:"

Confirms if the window a p5.js program is in is "focused," meaning that\nthe sketch will accept mouse or keyboard input. This variable is\n"true" if the window is focused and "false" if not.

\n",itemtype:"property",name:"focused",type:"Boolean",readonly:"",example:['\n
\n// To demonstrate, put two windows side by side.\n// Click on the window that the p5 sketch isn\'t in!\nfunction draw() {\n background(200);\n noStroke();\n fill(0, 200, 0);\n ellipse(25, 25, 50, 50);\n\n if (!focused) { // or "if (focused === false)"\n stroke(200,0,0);\n line(0, 0, 100, 100);\n line(100, 0, 0, 100);\n }\n}\n
'],alt:"green 50x50 ellipse at top left. Red X covers canvas when page focus changes",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:110,description:"

Sets the cursor to a predefined symbol or an image, or makes it visible\nif already hidden. If you are trying to set an image as the cursor, the\nrecommended size is 16x16 or 32x32 pixels. It is not possible to load an\nimage as the cursor if you are exporting your program for the Web, and not\nall MODES work with all browsers. The values for parameters x and y must\nbe less than the dimensions of the image.

\n",itemtype:"method",name:"cursor",params:[{name:"type",description:"

either ARROW, CROSS, HAND, MOVE, TEXT, or\n WAIT, or path for image

\n",type:"String|Constant"},{name:"x",description:"

the horizontal active spot of the cursor

\n",type:"Number",optional:!0},{name:"y",description:"

the vertical active spot of the cursor

\n",type:"Number",optional:!0}],example:["\n
\n// Move the mouse left and right across the image\n// to see the cursor change from a cross to a hand\nfunction draw() {\n line(width/2, 0, width/2, height);\n if (mouseX < 50) {\n cursor(CROSS);\n } else {\n cursor(HAND);\n }\n}\n
"],alt:"horizontal line divides canvas. cursor on left is a cross, right is hand.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:169,description:"

Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default rate is 60 frames per second. This is the same as\nsetFrameRate(val).\n

\nCalling frameRate() with no arguments returns the current framerate. The\ndraw function must run at least once before it will return a value. This\nis the same as getFrameRate().\n

\nCalling frameRate() with arguments that are not of the type numbers\nor are non positive also returns current framerate.

\n",itemtype:"method",name:"frameRate",chainable:1,class:"p5",module:"Environment",submodule:"Environment",overloads:[{line:169,params:[{name:"fps",description:"

number of frames to be displayed every second

\n",type:"Number"}],chainable:1},{line:188,params:[],return:{description:"current frameRate",type:"Number"}}]},{file:"src/core/environment.js",line:238,description:"

Returns the current framerate.

\n",return:{description:"current frameRate",type:"Number"},class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:247,description:"

Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default rate is 60 frames per second.

\n

Calling frameRate() with no arguments returns the current framerate.

\n",params:[{name:"fps",description:"

number of frames to be displayed every second

\n",type:"Number",optional:!0}],class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:262,description:"

Hides the cursor from view.

\n",itemtype:"method",name:"noCursor",example:["\n
\nfunction setup() {\n noCursor();\n}\n\nfunction draw() {\n background(200);\n ellipse(mouseX, mouseY, 10, 10);\n}\n
"],alt:"cursor becomes 10x 10 white ellipse the moves with mouse x and y.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:288,description:"

System variable that stores the width of the entire screen display. This\nis used to run a full-screen program on any display size.

\n",itemtype:"property",name:"displayWidth",type:"Number",readonly:"",example:['\n
\ncreateCanvas(displayWidth, displayHeight);\n
'],alt:"cursor becomes 10x 10 white ellipse the moves with mouse x and y.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:305,description:"

System variable that stores the height of the entire screen display. This\nis used to run a full-screen program on any display size.

\n",itemtype:"property",name:"displayHeight",type:"Number",readonly:"",example:['\n
\ncreateCanvas(displayWidth, displayHeight);\n
'],alt:"no display.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:322,description:"

System variable that stores the width of the inner window, it maps to\nwindow.innerWidth.

\n",itemtype:"property",name:"windowWidth",type:"Number",readonly:"",example:['\n
\ncreateCanvas(windowWidth, windowHeight);\n
'],alt:"no display.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:338,description:"

System variable that stores the height of the inner window, it maps to\nwindow.innerHeight.

\n",itemtype:"property",name:"windowHeight",type:"Number",readonly:"",example:['\n
\ncreateCanvas(windowWidth, windowHeight);\n
'],alt:"no display.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:354,description:"

The windowResized() function is called once every time the browser window\nis resized. This is a good place to resize the canvas or do any other\nadjustments to accommodate the new window size.

\n",itemtype:"method",name:"windowResized",example:['\n
\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
'],alt:"no display.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:404,description:"

System variable that stores the width of the drawing canvas. This value\nis set by the first parameter of the createCanvas() function.\nFor example, the function call createCanvas(320, 240) sets the width\nvariable to the value 320. The value of width defaults to 100 if\ncreateCanvas() is not used in a program.

\n",itemtype:"property",name:"width",type:"Number",readonly:"",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:416,description:"

System variable that stores the height of the drawing canvas. This value\nis set by the second parameter of the createCanvas() function. For\nexample, the function call createCanvas(320, 240) sets the height\nvariable to the value 240. The value of height defaults to 100 if\ncreateCanvas() is not used in a program.

\n",itemtype:"property",name:"height",type:"Number",readonly:"",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:428,description:"

If argument is given, sets the sketch to fullscreen or not based on the\nvalue of the argument. If no argument is given, returns the current\nfullscreen state. Note that due to browser restrictions this can only\nbe called on user input, for example, on mouse press like the example\nbelow.

\n",itemtype:"method",name:"fullscreen",params:[{name:"val",description:"

whether the sketch should be in fullscreen mode\nor not

\n",type:"Boolean",optional:!0}],return:{description:"current fullscreen state",type:"Boolean"},example:["\n
\n\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n var fs = fullscreen();\n fullscreen(!fs);\n }\n}\n\n
"],alt:"no display.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:475,description:"

Sets the pixel scaling for high pixel density displays. By default\npixel density is set to match display density, call pixelDensity(1)\nto turn this off. Calling pixelDensity() with no arguments returns\nthe current pixel density of the sketch.

\n",itemtype:"method",name:"pixelDensity",params:[{name:"val",description:"

whether or how much the sketch should scale

\n",type:"Number",optional:!0}],return:{description:"current pixel density of the sketch",type:"Number"},example:["\n
\n\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n background(200);\n ellipse(width/2, height/2, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n pixelDensity(3.0);\n createCanvas(100, 100);\n background(200);\n ellipse(width/2, height/2, 50, 50);\n}\n\n
"],alt:"fuzzy 50x50 white ellipse with black outline in center of canvas.\nsharp 50x50 white ellipse with black outline in center of canvas.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:520,description:"

Returns the pixel density of the current display the sketch is running on.

\n",itemtype:"method",name:"displayDensity",return:{description:"current pixel density of the display",type:"Number"},example:["\n
\n\nfunction setup() {\n var density = displayDensity();\n pixelDensity(density);\n createCanvas(100, 100);\n background(200);\n ellipse(width/2, height/2, 50, 50);\n}\n\n
"],alt:"50x50 white ellipse with black outline in center of canvas.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:577,description:"

Gets the current URL.

\n",itemtype:"method",name:"getURL",return:{description:"url",type:"String"},example:["\n
\n\nvar url;\nvar x = 100;\n\nfunction setup() {\n fill(0);\n noStroke();\n url = getURL();\n}\n\nfunction draw() {\n background(200);\n text(url, x, height/2);\n x--;\n}\n\n
"],alt:"current url (http://p5js.org/reference/#/p5/getURL) moves right to left.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:608,description:"

Gets the current URL path as an array.

\n",itemtype:"method",name:"getURLPath",return:{description:"path components",type:"String[]"},example:["\n
\nfunction setup() {\n var urlPath = getURLPath();\n for (var i=0; i<urlPath.length; i++) {\n text(urlPath[i], 10, i*20+20);\n }\n}\n
"],alt:"no display",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/environment.js",line:629,description:"

Gets the current URL params as an Object.

\n",itemtype:"method",name:"getURLParams",return:{description:"URL params",type:"Object"},example:["\n
\n\n// Example: http://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n var params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n}\n\n
"],alt:"no display.",class:"p5",module:"Environment",submodule:"Environment"},{file:"src/core/error_helpers.js",line:1,requires:["core"],class:"p5",module:"Environment"},{file:"src/core/error_helpers.js",line:34,description:"

Prints out a fancy, colorful message to the console log

\n",params:[{name:"message",description:"

the words to be said

\n",type:"String"},{name:"func",description:"

the name of the function to link

\n",type:"String"},{name:"color",description:"

CSS color string or error type

\n",type:"Number|String"}],return:{description:"console logs"},class:"p5",module:"Environment"},{file:"src/core/error_helpers.js",line:106,description:"

Validates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments

\n

example:\n var a;\n ellipse(10,10,a,5);\nconsole ouput:\n "It looks like ellipse received an empty variable in spot #2."

\n

example:\n ellipse(10,"foo",5,5);\nconsole output:\n "ellipse was expecting a number for parameter #1,\n received "foo" instead."

\n",class:"p5",module:"Environment"},{file:"src/core/error_helpers.js",line:273,description:"

Prints out all the colors in the color pallete with white text.\nFor color blindness testing.

\n",class:"p5",module:"Environment"},{file:"src/core/init.js",line:5,description:"

_globalInit

\n

TODO: ???\nif sketch is on window\nassume "global" mode\nand instantiate p5 automatically\notherwise do nothing

\n",return:{description:"",type:"Undefined"},class:"p5.Element",module:"Environment"},{file:"src/core/p5.Element.js",line:25,description:"

Underlying HTML element. All normal HTML methods can be called on this.

\n",itemtype:"property",name:"elt",readonly:"",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:39,description:"

Attaches the element to the parent specified. A way of setting\n the container for the element. Accepts either a string ID, DOM\n node, or p5.Element. If no arguments given, parent node is returned.\n For more ways to position the canvas, see the\n \n positioning the canvas wiki page.

\n",itemtype:"method",name:"parent",chainable:1,class:"p5.Element",module:"DOM",submodule:"DOM",overloads:[{line:39,params:[{name:"parent",description:"

the ID, DOM node, or p5.Element\n of desired parent element

\n",type:"String|p5.Element|Object"}],chainable:1},{line:53,params:[],return:{description:"",type:"p5.Element"}}]},{file:"src/core/p5.Element.js",line:103,description:"

Sets the ID of the element. If no ID argument is passed in, it instead\n returns the current ID of the element.

\n",itemtype:"method",name:"id",chainable:1,class:"p5.Element",module:"DOM",submodule:"DOM",overloads:[{line:103,params:[{name:"id",description:"

ID of the element

\n",type:"String"}],chainable:1},{line:112,params:[],return:{description:"the id of the element",type:"String"}}]},{file:"src/core/p5.Element.js",line:141,description:"

Adds given class to the element. If no class argument is passed in, it\n instead returns a string containing the current class(es) of the element.

\n",itemtype:"method",name:"class",chainable:1,class:"p5.Element",module:"DOM",submodule:"DOM",overloads:[{line:141,params:[{name:"class",description:"

class to add

\n",type:"String"}],chainable:1},{line:150,params:[],return:{description:"the class of the element",type:"String"}}]},{file:"src/core/p5.Element.js",line:163,description:"

The .mousePressed() function is called once after every time a\nmouse button is pressed over the element. This can be used to\nattach element specific event listeners.

\n",itemtype:"method",name:"mousePressed",params:[{name:"fxn",description:"

function to be fired when mouse is\n pressed over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mousePressed(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires with any click anywhere\nfunction mousePressed() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:213,description:"

The .doubleClicked() function is called once after every time a\nmouse button is pressed twice over the element. This can be used to\nattach element and action specific event listeners.

\n",itemtype:"method",name:"doubleClicked",params:[{name:"fxn",description:"

function to be fired when mouse is\n double clicked over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],return:{description:"",type:"p5.Element"},example:["\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.doubleClicked(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires with any double click anywhere\nfunction doubleClicked() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:263,description:"

The .mouseWheel() function is called once after every time a\nmouse wheel is scrolled over the element. This can be used to\nattach element specific event listeners.\n

\nThe function accepts a callback function as argument which will be executed\nwhen the wheel event is triggered on the element, the callback function is\npassed one argument event. The event.deltaY property returns negative\nvalues if the mouse wheel is rotated up or away from the user and positive\nin the other direction. The event.deltaX does the same as event.deltaY\nexcept it reads the horizontal wheel scroll of the mouse wheel.\n

\nOn OS X with "natural" scrolling enabled, the event.deltaY values are\nreversed.

\n",itemtype:"method",name:"mouseWheel",params:[{name:"fxn",description:"

function to be fired when mouse is\n scrolled over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseWheel(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires with mousewheel movement\n// anywhere on screen\nfunction mouseWheel() {\n g = g + 10;\n}\n\n// this function fires with mousewheel movement\n// over canvas only\nfunction changeSize(event) {\n if (event.deltaY > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:329,description:"

The .mouseReleased() function is called once after every time a\nmouse button is released over the element. This can be used to\nattach element specific event listeners.

\n",itemtype:"method",name:"mouseReleased",params:[{name:"fxn",description:"

function to be fired when mouse is\n released over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseReleased(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires after the mouse has been\n// released\nfunction mouseReleased() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// released while on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:383,description:"

The .mouseClicked() function is called once after a mouse button is\npressed and released over the element. This can be used to\nattach element specific event listeners.

\n",itemtype:"method",name:"mouseClicked",params:[{name:"fxn",description:"

function to be fired when mouse is\n clicked over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:['\n
\n\nvar cnv;\nvar d;\nvar g;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires after the mouse has been\n// clicked anywhere\nfunction mouseClicked() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// clicked on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n\n
'],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:437,description:"

The .mouseMoved() function is called once every time a\nmouse moves over the element. This can be used to attach an\nelement specific event listener.

\n",itemtype:"method",name:"mouseMoved",params:[{name:"fxn",description:"

function to be fired when a mouse moves\n over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1, +example:["\n
\nvar cnv;\nvar d = 30;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseMoved(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n fill(200);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires when mouse moves anywhere on\n// page\nfunction mouseMoved() {\n g = g + 5;\n if (g > 255) {\n g = 0;\n }\n}\n\n// this function fires when mouse moves over canvas\nfunction changeSize() {\n d = d + 2;\n if (d > 100) {\n d = 0;\n }\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:496,description:"

The .mouseOver() function is called once after every time a\nmouse moves onto the element. This can be used to attach an\nelement specific event listener.

\n",itemtype:"method",name:"mouseOver",params:[{name:"fxn",description:"

function to be fired when a mouse moves\n onto the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width/2, height/2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:541,description:"

The .changed() function is called when the value of an\nelement changes.\nThis can be used to attach an element specific event listener.

\n",itemtype:"method",name:"changed",params:[{name:"fxn",description:"

function to be fired when the value of\n an element changes.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nvar sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n var item = sel.value();\n background(200);\n text(\"it's a \"+item+\"!\", 50, 50);\n}\n
\n
\nvar checkbox;\nvar cnv;\n\nfunction setup() {\n checkbox = createCheckbox(\" fill\");\n checkbox.changed(changeFill);\n cnv = createCanvas(100, 100);\n cnv.position(0, 30);\n noFill();\n}\n\nfunction draw() {\n background(200);\n ellipse(50, 50, 50, 50);\n}\n\nfunction changeFill() {\n if (checkbox.checked()) {\n fill(0);\n } else {\n noFill();\n }\n}\n
"],alt:'dropdown: pear, kiwi, grape. When selected text "its a" + selection shown.',class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:608,description:"

The .input() function is called when any user input is\ndetected with an element. The input event is often used\nto detect keystrokes in a input element, or changes on a\nslider element. This can be used to attach an element specific\nevent listener.

\n",itemtype:"method",name:"input",params:[{name:"fxn",description:"

function to be fired when any user input is\n detected within the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\n// Open your console to see the output\nfunction setup() {\n var inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:643,description:"

The .mouseOut() function is called once after every time a\nmouse moves off the element. This can be used to attach an\nelement specific event listener.

\n",itemtype:"method",name:"mouseOut",params:[{name:"fxn",description:"

function to be fired when a mouse\n moves off of an element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width/2, height/2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:686,description:"

The .touchStarted() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.

\n",itemtype:"method",name:"touchStarted",params:[{name:"fxn",description:"

function to be fired when a touch\n starts over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchStarted(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchStarted() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:735,description:"

The .touchMoved() function is called once after every time a touch move is\nregistered. This can be used to attach element specific event listeners.

\n",itemtype:"method",name:"touchMoved",params:[{name:"fxn",description:"

function to be fired when a touch moves over\n the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nvar cnv;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchMoved(changeGray); // attach listener for\n // canvas click only\n g = 100;\n}\n\nfunction draw() {\n background(g);\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:776,description:"

The .touchEnded() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.

\n",itemtype:"method",name:"touchEnded",params:[{name:"fxn",description:"

function to be fired when a touch ends\n over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchEnded(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width/2, height/2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchEnded() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"],alt:"no display.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:828,description:"

The .dragOver() function is called once after every time a\nfile is dragged over the element. This can be used to attach an\nelement specific event listener.

\n",itemtype:"method",name:"dragOver",params:[{name:"fxn",description:"

function to be fired when a file is\n dragged over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\n// To test this sketch, simply drag a\n// file over the canvas\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width/2, height/2);\n c.dragOver(dragOverCallback);\n}\n\n// This function will be called whenever\n// a file is dragged over the canvas\nfunction dragOverCallback() {\n background(240);\n text('Dragged over', width/2, height/2);\n}\n
"],alt:"nothing displayed",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:866,description:"

The .dragLeave() function is called once after every time a\ndragged file leaves the element area. This can be used to attach an\nelement specific event listener.

\n",itemtype:"method",name:"dragLeave",params:[{name:"fxn",description:"

function to be fired when a file is\n dragged off the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\n// To test this sketch, simply drag a file\n// over and then out of the canvas area\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width/2, height/2);\n c.dragLeave(dragLeaveCallback);\n}\n\n// This function will be called whenever\n// a file is dragged out of the canvas\nfunction dragLeaveCallback() {\n background(240);\n text('Dragged off', width/2, height/2);\n}\n
"],alt:"nothing displayed",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:904,description:"

The .drop() function is called for each file dropped on the element.\nIt requires a callback that is passed a p5.File object. You can\noptionally pass two callbacks, the first one (required) is triggered\nfor each file dropped when the file is loaded. The second (optional)\nis triggered just once when a file (or files) are dropped.

\n",itemtype:"method",name:"drop",params:[{name:"callback",description:"

callback triggered when files are dropped.

\n",type:"Function|Boolean"},{name:"fxn",description:"

callback to receive loaded file.

\n",type:"Function|Boolean"}],chainable:1,example:["\n
\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop image', width/2, height/2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n var img = createImg(file.data).hide();\n // Draw the image onto the canvas\n image(img, 0, 0, width, height);\n}\n
"],alt:"Canvas turns into whatever image is dragged/dropped onto it.",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Element.js",line:1031,description:"

Helper fxn for sharing pixel methods

\n",class:"p5.Element",module:"DOM",submodule:"DOM"},{file:"src/core/p5.Renderer.js",line:72,description:"

Resize our canvas element.

\n",class:"p5.Renderer",module:"Rendering",submodule:"Rendering"},{file:"src/core/p5.Renderer.js",line:146,description:"

Helper fxn to check font type (system or otf)

\n",class:"p5.Renderer",module:"Rendering",submodule:"Rendering"},{file:"src/core/p5.Renderer.js",line:202,description:'

Helper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178

\n',class:"p5.Renderer",module:"Rendering",submodule:"Rendering"},{file:"src/core/p5.Renderer2D.js",line:9,description:"

p5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer

\n",class:"p5",module:"Rendering"},{file:"src/core/p5.Renderer2D.js",line:356,description:"

Generate a cubic Bezier representing an arc on the unit circle of total\nangle size radians, beginning start radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.

\n

See www.joecridge.me/bezier.pdf for an explanation of the method.

\n",class:"p5",module:"Rendering"},{file:"src/core/rendering.js",line:14,description:"

Creates a canvas element in the document, and sets the dimensions of it\nin pixels. This method should be called only once at the start of setup.\nCalling createCanvas more than once in a sketch will result in very\nunpredicable behavior. If you want more than one drawing canvas\nyou could use createGraphics (hidden by default but it can be shown).\n

\nThe system variables width and height are set by the parameters passed\nto this function. If createCanvas() is not used, the window will be\ngiven a default size of 100x100 pixels.\n

\nFor more ways to position the canvas, see the\n\npositioning the canvas wiki page.

\n",itemtype:"method",name:"createCanvas",params:[{name:"w",description:"

width of the canvas

\n",type:"Number"},{name:"h",description:"

height of the canvas

\n",type:"Number"},{name:"renderer",description:"

either P2D or WEBGL

\n",type:"Constant",optional:!0}],return:{description:"canvas generated",type:"HTMLCanvasElement"},example:["\n
\n\nfunction setup() {\n createCanvas(100, 50);\n background(153);\n line(0, 0, width, height);\n}\n\n
"],alt:"Black line extending from top-left of canvas to bottom right.",class:"p5",module:"Rendering",submodule:"Rendering"},{file:"src/core/rendering.js",line:112,description:"

Resizes the canvas to given width and height. The canvas will be cleared\nand draw will be called immediately, allowing the sketch to re-render itself\nin the resized canvas.

\n",itemtype:"method",name:"resizeCanvas",params:[{name:"w",description:"

width of the canvas

\n",type:"Number"},{name:"h",description:"

height of the canvas

\n",type:"Number"},{name:"noRedraw",description:"

don't redraw the canvas immediately

\n",type:"Boolean",optional:!0}],example:['\n
\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
'],alt:"No image displayed.",class:"p5",module:"Rendering",submodule:"Rendering"},{file:"src/core/rendering.js",line:162,description:"

Removes the default canvas for a p5 sketch that doesn't\nrequire a canvas

\n",itemtype:"method",name:"noCanvas",example:["\n
\n\nfunction setup() {\n noCanvas();\n}\n\n
"],alt:"no image displayed",class:"p5",module:"Rendering",submodule:"Rendering"},{file:"src/core/rendering.js",line:185,description:"

Creates and returns a new p5.Renderer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels.

\n",itemtype:"method",name:"createGraphics",params:[{name:"w",description:"

width of the offscreen graphics buffer

\n",type:"Number"},{name:"h",description:"

height of the offscreen graphics buffer

\n",type:"Number"},{name:"renderer",description:"

either P2D or WEBGL\nundefined defaults to p2d

\n",type:"Constant",optional:!0}],return:{description:"offscreen graphics buffer",type:"p5.Graphics"},example:["\n
\n\nvar pg;\nfunction setup() {\n createCanvas(100, 100);\n pg = createGraphics(100, 100);\n}\nfunction draw() {\n background(200);\n pg.background(100);\n pg.noStroke();\n pg.ellipse(pg.width/2, pg.height/2, 50, 50);\n image(pg, 50, 50);\n image(pg, 0, 0, 50, 50);\n}\n\n
"],alt:"4 grey squares alternating light and dark grey. White quarter circle mid-left.",class:"p5",module:"Rendering",submodule:"Rendering"},{file:"src/core/rendering.js",line:223,description:"

Blends the pixels in the display window according to the defined mode.\nThere is a choice of the following modes to blend the source pixels (A)\nwith the ones of pixels already in the display window (B):

\n
    \n
  • BLEND - linear interpolation of colours: C =\nAfactor + B. This is the default blending mode.
  • \n
  • ADD - sum of A and B
  • \n
  • DARKEST - only the darkest colour succeeds: C =\nmin(Afactor, B).
  • \n
  • LIGHTEST - only the lightest colour succeeds: C =\nmax(A*factor, B).
  • \n
  • DIFFERENCE - subtract colors from underlying image.
  • \n
  • EXCLUSION - similar to DIFFERENCE, but less\nextreme.
  • \n
  • MULTIPLY - multiply the colors, result will always be\ndarker.
  • \n
  • SCREEN - opposite multiply, uses inverse values of the\ncolors.
  • \n
  • REPLACE - the pixels entirely replace the others and\ndon't utilize alpha (transparency) values.
  • \n
  • OVERLAY - mix of MULTIPLY and SCREEN\n. Multiplies dark values, and screens light values.
  • \n
  • HARD_LIGHT - SCREEN when greater than 50%\ngray, MULTIPLY when lower.
  • \n
  • SOFT_LIGHT - mix of DARKEST and\nLIGHTEST. Works like OVERLAY, but not as harsh.\n
  • \n
  • DODGE - lightens light tones and increases contrast,\nignores darks.
  • \n
  • BURN - darker areas are applied, increasing contrast,\nignores lights.
  • \n
",itemtype:"method",name:"blendMode",params:[{name:"mode",description:"

blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL

\n",type:"Constant"}],example:["\n
\n\nblendMode(LIGHTEST);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n\n
\n
\n\nblendMode(MULTIPLY);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n\n
"],alt:"translucent image thick red & blue diagonal rounded lines intersecting center\nThick red & blue diagonal rounded lines intersecting center. dark at overlap",class:"p5",module:"Rendering",submodule:"Rendering"},{file:"src/core/shim.js",line:65,description:'

shim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.

\n',class:"p5",module:"Rendering"},{file:"src/core/structure.js",line:15,description:"

Stops p5.js from continuously executing the code within draw().\nIf loop() is called, the code in draw() begins to run continuously again.\nIf using noLoop() in setup(), it should be the last line inside the block.\n

\nWhen noLoop() is used, it's not possible to manipulate or access the\nscreen inside event handling functions such as mousePressed() or\nkeyPressed(). Instead, use those functions to call redraw() or loop(),\nwhich will run draw(), which can update the screen properly. This means\nthat when noLoop() has been called, no drawing can happen, and functions\nlike saveFrame() or loadPixels() may not be used.\n

\nNote that if the sketch is resized, redraw() will be called to update\nthe sketch, even after noLoop() has been specified. Otherwise, the sketch\nwould enter an odd state until loop() was called.

\n",itemtype:"method",name:"noLoop",example:["\n
\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n noLoop();\n}\n\nfunction draw() {\n line(10, 10, 90, 90);\n}\n
\n\n
\nvar x = 0;\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n noLoop();\n}\n\nfunction mouseReleased() {\n loop();\n}\n
"],alt:"113 pixel long line extending from top-left to bottom right of canvas.\nhorizontal line moves slowly from left. Loops but stops on mouse press.",class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/structure.js",line:77,description:"

By default, p5.js loops through draw() continuously, executing the code\nwithin it. However, the draw() loop may be stopped by calling noLoop().\nIn that case, the draw() loop can be resumed with loop().

\n",itemtype:"method",name:"loop",example:["\n
\nvar x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n loop();\n}\n\nfunction mouseReleased() {\n noLoop();\n}\n
"],alt:"horizontal line moves slowly from left. Loops but stops on mouse press.",class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/structure.js",line:119,description:"

The push() function saves the current drawing style settings and\ntransformations, while pop() restores these settings. Note that these\nfunctions are always used together. They allow you to change the style\nand transformation settings and later return to what you had. When a new\nstate is started with push(), it builds on the current style and transform\ninformation. The push() and pop() functions can be embedded to provide\nmore control. (See the second example for a demonstration.)\n

\npush() stores information related to the current transformation state\nand style settings controlled by the following functions: fill(),\nstroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),\nimageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),\ntextFont(), textMode(), textSize(), textLeading().

\n",itemtype:"method",name:"push",example:["\n
\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\ntranslate(50, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
\n
\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
"],alt:"Gold ellipse + thick black outline @center 2 white ellipses on left and right.\n2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.",class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/structure.js",line:194,description:"

The push() function saves the current drawing style settings and\ntransformations, while pop() restores these settings. Note that these\nfunctions are always used together. They allow you to change the style\nand transformation settings and later return to what you had. When a new\nstate is started with push(), it builds on the current style and transform\ninformation. The push() and pop() functions can be embedded to provide\nmore control. (See the second example for a demonstration.)\n

\npush() stores information related to the current transformation state\nand style settings controlled by the following functions: fill(),\nstroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),\nimageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),\ntextFont(), textMode(), textSize(), textLeading().

\n",itemtype:"method",name:"pop",example:["\n
\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\ntranslate(50, 0);\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
\n
\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
"],alt:"Gold ellipse + thick black outline @center 2 white ellipses on left and right.\n2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.",class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/structure.js",line:266,description:"

Executes the code within draw() one time. This functions allows the\n program to update the display window only when necessary, for example\n when an event registered by mousePressed() or keyPressed() occurs.\n

\n In structuring a program, it only makes sense to call redraw() within\n events such as mousePressed(). This is because redraw() does not run\n draw() immediately (it only sets a flag that indicates an update is\n needed).\n

\n The redraw() function does not work properly when called inside draw().\n To enable/disable animations, use loop() and noLoop().\n

\n In addition you can set the number of redraws per method call. Just\n add an integer as single parameter for the number of redraws.

\n",itemtype:"method",name:"redraw",params:[{name:"n",description:"

Redraw for n-times. The default value is 1.

\n",type:"Integer",optional:!0}],example:["\n
\n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n x += 1;\n redraw();\n }\n
\n
\n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n x += 1;\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n redraw(5);\n }\n
"],alt:"black line on far left of canvas\n black line on far left of canvas",class:"p5",module:"Structure",submodule:"Structure"},{file:"src/core/transform.js",line:15,description:'

Multiplies the current matrix by the one specified through the parameters.\nThis is a powerful operation that can perform the equivalent of translate,\nscale, shear and rotate all at once. You can learn more about transformation\nmatrices on \nWikipedia.

\n

The naming of the arguments here follows the naming of the \nWHATWG specification and corresponds to a\ntransformation matrix of the\nform:

\n
\n

\n
\n',itemtype:"method",name:"applyMatrix",params:[{name:"a",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"b",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"c",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"d",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"e",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"f",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"}],chainable:1,example:["\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n // Equivalent to translate(x, y);\n applyMatrix(1, 0, 0, 1, 40 + step, 50);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n translate(50, 50);\n // Equivalent to scale(x, y);\n applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20\n var angle = map(step, 0, 20, 0, TWO_PI);\n var cos_a = cos(angle);\n var sin_a = sin(angle);\n background(200);\n translate(50, 50);\n // Equivalent to rotate(angle);\n applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20\n var angle = map(step, 0, 20, -PI/4, PI/4);\n background(200);\n translate(50, 50);\n // equivalent to shearX(angle);\n var shear_factor = 1 / tan(PI/2 - angle);\n applyMatrix(1, 0, shear_factor, 1, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
"],alt:"A rectangle translating to the right\nA rectangle shrinking to the center\nA rectangle rotating clockwise about the center\nA rectangle shearing",class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/transform.js",line:137,description:"

Replaces the current matrix with the identity matrix.

\n",itemtype:"method",name:"resetMatrix",chainable:1,example:["\n
\n\ntranslate(50, 50);\napplyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0);\nrect(0, 0, 20, 20);\n// Note that the translate is also reset.\nresetMatrix();\nrect(0, 0, 20, 20);\n\n
"],alt:"A rotated retangle in the center with another at the top left corner",class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/transform.js",line:163,description:"

Rotates a shape the amount specified by the angle parameter. This\nfunction accounts for angleMode, so angles can be entered in either\nRADIANS or DEGREES.\n

\nObjects are always rotated around their relative position to the\norigin and positive numbers rotate objects in a clockwise direction.\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nrotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).\nAll tranformations are reset when draw() begins again.\n

\nTechnically, rotate() multiplies the current transformation matrix\nby a rotation matrix. This function can be further controlled by\nthe push() and pop().

\n",itemtype:"method",name:"rotate",params:[{name:"angle", +description:"

the angle of rotation, specified in radians\n or degrees, depending on current angleMode

\n",type:"Number"},{name:"axis",description:"

(in 3d) the axis to rotate around

\n",type:"p5.Vector|Array",optional:!0}],chainable:1,example:["\n
\n\ntranslate(width/2, height/2);\nrotate(PI/3.0);\nrect(-26, -26, 52, 52);\n\n
"],alt:"white 52x52 rect with black outline at center rotated counter 45 degrees",class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/transform.js",line:218,description:"

Rotates around X axis.

\n",itemtype:"method",name:"rotateX",params:[{name:"rad",description:"

angles in radians

\n",type:"Number"}],chainable:1,class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/transform.js",line:233,description:"

Rotates around Y axis.

\n",itemtype:"method",name:"rotateY",params:[{name:"rad",description:"

angles in radians

\n",type:"Number"}],chainable:1,class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/transform.js",line:248,description:"

Rotates around Z axis. Webgl mode only.

\n",itemtype:"method",name:"rotateZ",params:[{name:"rad",description:"

angles in radians

\n",type:"Number"}],chainable:1,class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/transform.js",line:263,description:"

Increases or decreases the size of a shape by expanding and contracting\nvertices. Objects always scale from their relative origin to the\ncoordinate system. Scale values are specified as decimal percentages.\nFor example, the function call scale(2.0) increases the dimension of a\nshape by 200%.\n

\nTransformations apply to everything that happens after and subsequent\ncalls to the function multiply the effect. For example, calling scale(2.0)\nand then scale(1.5) is the same as scale(3.0). If scale() is called\nwithin draw(), the transformation is reset when the loop begins again.\n

\nUsing this function with the z parameter is only available in WEBGL mode.\nThis function can be further controlled with push() and pop().

\n",itemtype:"method",name:"scale",params:[{name:"s",description:"

percent to scale the object, or percentage to\n scale the object in the x-axis if multiple arguments\n are given

\n",type:"Number|p5.Vector|Array"},{name:"y",description:"

percent to scale the object in the y-axis

\n",type:"Number",optional:!0},{name:"z",description:"

percent to scale the object in the z-axis (webgl only)

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\ntranslate(width/2, height/2);\nrotate(PI/3.0);\nrect(-26, -26, 52, 52);\n\n
\n\n
\n\nrect(30, 20, 50, 50);\nscale(0.5, 1.3);\nrect(30, 20, 50, 50);\n\n
"],alt:"white 52x52 rect with black outline at center rotated counter 45 degrees\n2 white rects with black outline- 1 50x50 at center. other 25x65 bottom left",class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/transform.js",line:345,description:"

Shears a shape around the x-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode.\nObjects are always sheared around their relative position to the origin\nand positive numbers shear objects in a clockwise direction.\n

\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).\nIf shearX() is called within the draw(), the transformation is reset when\nthe loop begins again.\n

\nTechnically, shearX() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.

\n",itemtype:"method",name:"shearX",params:[{name:"angle",description:"

angle of shear specified in radians or degrees,\n depending on current angleMode

\n",type:"Number"}],chainable:1,example:["\n
\n\ntranslate(width/4, height/4);\nshearX(PI/4.0);\nrect(0, 0, 30, 30);\n\n
"],alt:"white irregular quadrilateral with black outline at top middle.",class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/transform.js",line:386,description:"

Shears a shape around the y-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode. Objects\nare always sheared around their relative position to the origin and\npositive numbers shear objects in a clockwise direction.\n

\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If\nshearY() is called within the draw(), the transformation is reset when\nthe loop begins again.\n

\nTechnically, shearY() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.

\n",itemtype:"method",name:"shearY",params:[{name:"angle",description:"

angle of shear specified in radians or degrees,\n depending on current angleMode

\n",type:"Number"}],chainable:1,example:["\n
\n\ntranslate(width/4, height/4);\nshearY(PI/4.0);\nrect(0, 0, 30, 30);\n\n
"],alt:"white irregular quadrilateral with black outline at middle bottom.",class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/transform.js",line:427,description:"

Specifies an amount to displace objects within the display window.\nThe x parameter specifies left/right translation, the y parameter\nspecifies up/down translation.\n

\nTransformations are cumulative and apply to everything that happens after\nand subsequent calls to the function accumulates the effect. For example,\ncalling translate(50, 0) and then translate(20, 0) is the same as\ntranslate(70, 0). If translate() is called within draw(), the\ntransformation is reset when the loop begins again. This function can be\nfurther controlled by using push() and pop().

\n",itemtype:"method",name:"translate",params:[{name:"x",description:"

left/right translation

\n",type:"Number"},{name:"y",description:"

up/down translation

\n",type:"Number"},{name:"z",description:"

forward/backward translation (webgl only)

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\ntranslate(30, 20);\nrect(0, 0, 55, 55);\n\n
\n\n
\n\nrect(0, 0, 55, 55); // Draw rect at original 0,0\ntranslate(30, 20);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\ntranslate(14, 14);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\n\n
"],alt:"white 55x55 rect with black outline at center right.\n3 white 55x55 rects with black outlines at top-l, center-r and bottom-r.",class:"p5",module:"Transform",submodule:"Transform"},{file:"src/core/vertex.js",line:22,description:"

Use the beginContour() and endContour() functions to create negative\nshapes within shapes such as the center of the letter 'O'. beginContour()\nbegins recording vertices for the shape and endContour() stops recording.\nThe vertices that define a negative shape must "wind" in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.\n

\nThese functions can only be used within a beginShape()/endShape() pair and\ntransformations such as translate(), rotate(), and scale() do not work\nwithin a beginContour()/endContour() pair. It is also not possible to use\nother shapes, such as ellipse() or rect() within.

\n",itemtype:"method",name:"beginContour",chainable:1,example:["\n
\n\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n\n
"],alt:"white rect and smaller grey rect with red outlines in center of canvas.",class:"p5",module:"Shape",submodule:"Vertex"},{file:"src/core/vertex.js",line:70,description:"

Using the beginShape() and endShape() functions allow creating more\ncomplex forms. beginShape() begins recording vertices for a shape and\nendShape() stops recording. The value of the kind parameter tells it which\ntypes of shapes to create from the provided vertices. With no mode\nspecified, the shape can be any irregular polygon.\n

\nThe parameters available for beginShape() are POINTS, LINES, TRIANGLES,\nTRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the\nbeginShape() function, a series of vertex() commands must follow. To stop\ndrawing the shape, call endShape(). Each shape will be outlined with the\ncurrent stroke color and filled with the fill color.\n

\nTransformations such as translate(), rotate(), and scale() do not work\nwithin beginShape(). It is also not possible to use other shapes, such as\nellipse() or rect() within beginShape().

\n",itemtype:"method",name:"beginShape",params:[{name:"kind",description:"

either POINTS, LINES, TRIANGLES, TRIANGLE_FAN\n TRIANGLE_STRIP, QUADS, or QUAD_STRIP

\n",type:"Constant",optional:!0}],chainable:1,example:["\n
\n\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n\n
\n\n
\n\n// currently not working\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n
\n\n
\n\nbeginShape(LINES);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n
\n\n
\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n
\n\n
\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n\n
\n\n
\n\nbeginShape(TRIANGLES);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nendShape();\n\n
\n\n
\n\nbeginShape(TRIANGLE_STRIP);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nvertex(90, 75);\nendShape();\n\n
\n\n
\n\nbeginShape(TRIANGLE_FAN);\nvertex(57.5, 50);\nvertex(57.5, 15);\nvertex(92, 50);\nvertex(57.5, 85);\nvertex(22, 50);\nvertex(57.5, 15);\nendShape();\n\n
\n\n
\n\nbeginShape(QUADS);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 75);\nvertex(50, 20);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 75);\nvertex(85, 20);\nendShape();\n\n
\n\n
\n\nbeginShape(QUAD_STRIP);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 20);\nvertex(50, 75);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 20);\nvertex(85, 75);\nendShape();\n\n
\n\n
\n\nbeginShape();\nvertex(20, 20);\nvertex(40, 20);\nvertex(40, 40);\nvertex(60, 40);\nvertex(60, 60);\nvertex(20, 60);\nendShape(CLOSE);\n\n
"],alt:"white square-shape with black outline in middle-right of canvas.\n4 black points in a square shape in middle-right of canvas.\n2 horizontal black lines. In the top-right and bottom-right of canvas.\n3 line shape with horizontal on top, vertical in middle and horizontal bottom.\nsquare line shape in middle-right of canvas.\n2 white triangle shapes mid-right canvas. left one pointing up and right down.\n5 horizontal interlocking and alternating white triangles in mid-right canvas.\n4 interlocking white triangles in 45 degree rotated square-shape.\n2 white rectangle shapes in mid-right canvas. Both 20x55.\n3 side-by-side white rectangles center rect is smaller in mid-right canvas.\nThick white l-shape with black outline mid-top-left of canvas.",class:"p5",module:"Shape",submodule:"Vertex"},{file:"src/core/vertex.js",line:267,description:"

Specifies vertex coordinates for Bezier curves. Each call to\nbezierVertex() defines the position of two control points and\none anchor point of a Bezier curve, adding a new segment to a\nline or shape.\n

\nThe first time bezierVertex() is used within a\nbeginShape() call, it must be prefaced with a call to vertex()\nto set the first anchor point. This function must be used between\nbeginShape() and endShape() and only when there is no MODE\nparameter specified to beginShape().

\n",itemtype:"method",name:"bezierVertex",params:[{name:"x2",description:"

x-coordinate for the first control point

\n",type:"Number"},{name:"y2",description:"

y-coordinate for the first control point

\n",type:"Number"},{name:"x3",description:"

x-coordinate for the second control point

\n",type:"Number"},{name:"y3",description:"

y-coordinate for the second control point

\n",type:"Number"},{name:"x4",description:"

x-coordinate for the anchor point

\n",type:"Number"},{name:"y4",description:"

y-coordinate for the anchor point

\n",type:"Number"}],chainable:1,example:["\n
\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nendShape();\n\n
\n\n
\n\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n\n
"],alt:"crescent-shaped line in middle of canvas. Points facing left.\nwhite crescent shape in middle of canvas. Points facing left.",class:"p5",module:"Shape",submodule:"Vertex"},{file:"src/core/vertex.js",line:332,description:"

Specifies vertex coordinates for curves. This function may only\nbe used between beginShape() and endShape() and only when there\nis no MODE parameter specified to beginShape().\n

\nThe first and last points in a series of curveVertex() lines will be used to\nguide the beginning and end of a the curve. A minimum of four\npoints is required to draw a tiny curve between the second and\nthird points. Adding a fifth point with curveVertex() will draw\nthe curve between the second, third, and fourth points. The\ncurveVertex() function is an implementation of Catmull-Rom\nsplines.

\n",itemtype:"method",name:"curveVertex",params:[{name:"x",description:"

x-coordinate of the vertex

\n",type:"Number"},{name:"y",description:"

y-coordinate of the vertex

\n",type:"Number"}],chainable:1,example:["\n
\n\nnoFill();\nbeginShape();\ncurveVertex(84, 91);\ncurveVertex(84, 91);\ncurveVertex(68, 19);\ncurveVertex(21, 17);\ncurveVertex(32, 100);\ncurveVertex(32, 100);\nendShape();\n\n
"],alt:"Upside-down u-shape line, mid canvas. left point extends beyond canvas view.",class:"p5",module:"Shape",submodule:"Vertex"},{file:"src/core/vertex.js",line:374,description:"

Use the beginContour() and endContour() functions to create negative\nshapes within shapes such as the center of the letter 'O'. beginContour()\nbegins recording vertices for the shape and endContour() stops recording.\nThe vertices that define a negative shape must "wind" in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.\n

\nThese functions can only be used within a beginShape()/endShape() pair and\ntransformations such as translate(), rotate(), and scale() do not work\nwithin a beginContour()/endContour() pair. It is also not possible to use\nother shapes, such as ellipse() or rect() within.

\n",itemtype:"method",name:"endContour",chainable:1,example:["\n
\n\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n\n
"],alt:"white rect and smaller grey rect with red outlines in center of canvas.",class:"p5",module:"Shape",submodule:"Vertex"},{file:"src/core/vertex.js",line:434,description:"

The endShape() function is the companion to beginShape() and may only be\ncalled after beginShape(). When endshape() is called, all of image data\ndefined since the previous call to beginShape() is written into the image\nbuffer. The constant CLOSE as the value for the MODE parameter to close\nthe shape (to connect the beginning and the end).

\n",itemtype:"method",name:"endShape",params:[{name:"mode",description:"

use CLOSE to close the shape

\n",type:"Constant",optional:!0}],chainable:1,example:["\n
\n\nnoFill();\n\nbeginShape();\nvertex(20, 20);\nvertex(45, 20);\nvertex(45, 80);\nendShape(CLOSE);\n\nbeginShape();\nvertex(50, 20);\nvertex(75, 20);\nvertex(75, 80);\nendShape();\n\n
"],alt:"Triangle line shape with smallest interior angle on bottom and upside-down L.",class:"p5",module:"Shape",submodule:"Vertex"},{file:"src/core/vertex.js",line:502,description:"

Specifies vertex coordinates for quadratic Bezier curves. Each call to\nquadraticVertex() defines the position of one control points and one\nanchor point of a Bezier curve, adding a new segment to a line or shape.\nThe first time quadraticVertex() is used within a beginShape() call, it\nmust be prefaced with a call to vertex() to set the first anchor point.\nThis function must be used between beginShape() and endShape() and only\nwhen there is no MODE parameter specified to beginShape().

\n",itemtype:"method",name:"quadraticVertex",params:[{name:"cx",description:"

x-coordinate for the control point

\n",type:"Number"},{name:"cy",description:"

y-coordinate for the control point

\n",type:"Number"},{name:"x3",description:"

x-coordinate for the anchor point

\n",type:"Number"},{name:"y3",description:"

y-coordinate for the anchor point

\n",type:"Number"}],chainable:1,example:["\n
\n\nnoFill();\nstrokeWeight(4);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nendShape();\n\n
\n\n
\n\nnoFill();\nstrokeWeight(4);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nquadraticVertex(20, 80, 80, 80);\nvertex(80, 60);\nendShape();\n\n
"],alt:"arched-shaped black line with 4 pixel thick stroke weight.\nbackwards s-shaped black line with 4 pixel thick stroke weight.",class:"p5",module:"Shape",submodule:"Vertex"},{file:"src/core/vertex.js",line:579,description:"

All shapes are constructed by connecting a series of vertices. vertex()\nis used to specify the vertex coordinates for points, lines, triangles,\nquads, and polygons. It is used exclusively within the beginShape() and\nendShape() functions.

\n",itemtype:"method",name:"vertex",params:[{name:"x",description:"

x-coordinate of the vertex

\n",type:"Number"},{name:"y",description:"

y-coordinate of the vertex

\n",type:"Number"},{name:"z",description:"

z-coordinate of the vertex

\n",type:"Number|Boolean",optional:!0}],chainable:1,example:["\n
\n\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n
"],alt:"4 black points in a square shape in middle-right of canvas.",class:"p5",module:"Shape",submodule:"Vertex"},{file:"src/data/p5.TypedDict.js",line:16,description:"

Creates a new instance of p5.StringDict using the key, value pair\n or object you provide.

\n",itemtype:"method",name:"createStringDict",params:[{name:"key",description:"

or object

\n",type:"String|Object"},{name:"value",description:"",type:"String"}],return:{description:"",type:"p5.StringDict"},class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:32,description:"

Creates a new instance of p5.NumberDict using the key, value pair\n or object you provide.

\n",itemtype:"method",name:"createNumberDict",params:[{name:"key",description:"

or object

\n",type:"Number|Object"},{name:"value",description:"",type:"Number"}],return:{description:"",type:"p5.NumberDict"},class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:68,description:"

Returns the number of key-value pairs currently in Dictionary object

\n",itemtype:"method",name:"size",return:{description:"the number of key-value pairs in Dictionary object",type:"Number"},example:['\n
\n\n\nfunction setup() {\n var myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n var amt = myDictionary.size(); // value of amt is 3\n}\n\n
\n'],class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:92,description:"

Returns true if key exists in Dictionary\notherwise returns false

\n",itemtype:"method",name:"hasKey",params:[{name:"key",description:"

that you want to access

\n",type:"Number|String"}],return:{description:"whether that key exists in Dictionary",type:"Boolean"},example:["\n
\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n\n
\n"],class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:117,description:"

Returns value stored at supplied key.

\n",itemtype:"method",name:"get",params:[{name:"key",description:"

that you want to access

\n",type:"Number|String"}],return:{description:"the value stored at that key",type:"Number|String"},example:["\n
\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n var myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n\n
\n"],class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:146,description:"

Changes the value of key if in it already exists in\nin the Dictionary otherwise makes a new key-value pair

\n",itemtype:"method",name:"set",params:[{name:"key",description:"",type:"Number|String"},{name:"value",description:"",type:"Number|String"}],example:["\n
\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print()\n // above logs \"key: p5 - value: JS\" to console\n}\n\n
\n"],class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:179,description:"

private helper function to handle the user passing objects in\nduring construction or calls to create()

\n",class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:194,description:"

Removes a key-value pair in the Dictionary

\n",itemtype:"method",name:"create",class:"p5.TypedDict",module:"Data",submodule:"Dictionary",overloads:[{line:194,params:[{name:"key",description:"",type:"Number|String"},{name:"value",description:"",type:"Number|String"}]},{line:201,params:[{name:"obj",description:"

key/value pair

\n",type:"Object"}]}]},{file:"src/data/p5.TypedDict.js",line:234,description:"

Empties Dictionary of all key-value pairs

\n",itemtype:"method",name:"clear",class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:245,description:"

Removes a key-value pair in the Dictionary

\n",itemtype:"method",name:"remove",params:[{name:"key",description:"

for the pair to remove

\n",type:"Number|String"}],example:["\n
\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print()\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n\n
\n"],class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:277,description:"

Logs the list of items currently in the Dictionary to the console

\n",itemtype:"method",name:"print",class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:289,description:"

Converts the Dictionary into a CSV file for local\nstorage.

\n",itemtype:"method",name:"saveTable",class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:310,description:"

Converts the Dictionary into a JSON file for local\nstorage.

\n",itemtype:"method",name:"saveJSON",class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:321,description:"

private helper function to ensure that the user passed in valid\nvalues for the Dictionary type

\n",class:"p5.TypedDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:368,description:"

private helper function to ensure that the user passed in valid\nvalues for the Dictionary type

\n",class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:377,description:"

Add to a value stored at a certain key\nThe sum is stored in that location in the Dictionary.

\n",itemtype:"method",name:"add",params:[{name:"Key",description:"

for value you wish to add to

\n",type:"Number"},{name:"Amount",description:"

to add to the value

\n",type:"Number"}],example:["\n
\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n console.log(myDictionary.get(2)); // logs 7 to console.\n}\n
\n\n"],class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:405,description:"

Subtract from a value stored at a certain key\nThe difference is stored in that location in the Dictionary.

\n",itemtype:"method",name:"sub",params:[{name:"Key",description:"

for value you wish to subtract from

\n",type:"Number"},{name:"Amount",description:"

to subtract from the value

\n",type:"Number"}],example:["\n
\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n console.log(myDictionary.get(2)); // logs 3 to console.\n}\n
\n\n"],class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:429,description:"

Multiply a value stored at a certain key\nThe product is stored in that location in the Dictionary.

\n",itemtype:"method",name:"mult",params:[{name:"Key",description:"

for value you wish to multiply

\n",type:"Number"},{name:"Amount",description:"

to multiply the value by

\n",type:"Number"}],example:["\n
\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n console.log(myDictionary.get(2)); // logs 8 to console.\n}\n
\n\n"],class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:457,description:"

Divide a value stored at a certain key\nThe quotient is stored in that location in the Dictionary.

\n",itemtype:"method",name:"div",params:[{name:"Key",description:"

for value you wish to divide

\n",type:"Number"},{name:"Amount",description:"

to divide the value by

\n",type:"Number"}],example:["\n
\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n console.log(myDictionary.get(2)); // logs 4 to console.\n}\n
\n\n"],class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:485,description:"

private helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'

\n",class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:508,description:"

Return the lowest value.

\n",itemtype:"method",name:"minValue",return:{description:"",type:"Number"},example:["\n
\n\nfunction setup() {\n var myDictionary = createNumberDict({2 : -10, 4 : 0.65, 1.2 : 3});\n var lowestValue = myDictionary.minValue(); // value is -10\n}\n
\n"],class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:528,description:"

Return the highest value.

\n",itemtype:"method",name:"maxValue",return:{description:"",type:"Number"},example:["\n
\n\nfunction setup() {\n var myDictionary = createNumberDict({2 : -10, 4 : 0.65, 1.2 : 3});\n var highestValue = myDictionary.maxValue(); // value is 3\n}\n
\n"],class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:548,description:"

private helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'

\n",class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:571,description:"

Return the lowest key.

\n",itemtype:"method",name:"minKey",return:{description:"",type:"Number"},example:["\n
\n\nfunction setup() {\n var myDictionary = createNumberDict({2 : 4, 4 : 6, 1.2 : 3});\n var lowestKey = myDictionary.minKey(); // value is 1.2\n}\n
\n"],class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/data/p5.TypedDict.js",line:591,description:"

Return the highest key.

\n",itemtype:"method",name:"maxKey",return:{description:"",type:"Number"},example:["\n
\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2 : 4, 4 : 6, 1.2 : 3});\n var highestKey = myDictionary.maxKey(); // value is 4\n}\n
\n"],class:"p5.NumberDict",module:"Data",submodule:"Dictionary"},{file:"src/events/acceleration.js",line:12,description:"

The system variable deviceOrientation always contains the orientation of\nthe device. The value of this variable will either be set 'landscape'\nor 'portrait'. If no data is available it will be set to 'undefined'.\neither LANDSCAPE or PORTRAIT.

\n",itemtype:"property",name:"deviceOrientation",type:"Constant",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:23,description:"

The system variable accelerationX always contains the acceleration of the\ndevice along the x axis. Value is represented as meters per second squared.

\n",itemtype:"property",name:"accelerationX",type:"Number",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:32,description:"

The system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared.

\n",itemtype:"property",name:"accelerationY",type:"Number",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:41,description:"

The system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared.

\n",itemtype:"property",name:"accelerationZ",type:"Number",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:50, +description:"

The system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared.

\n",itemtype:"property",name:"pAccelerationX",type:"Number",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:60,description:"

The system variable pAccelerationY always contains the acceleration of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as meters per second squared.

\n",itemtype:"property",name:"pAccelerationY",type:"Number",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:70,description:"

The system variable pAccelerationZ always contains the acceleration of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as meters per second squared.

\n",itemtype:"property",name:"pAccelerationZ",type:"Number",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:80,description:"

_updatePAccelerations updates the pAcceleration values

\n",access:"private",tagname:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:91,description:"

The system variable rotationX always contains the rotation of the\ndevice along the x axis. Value is represented as 0 to +/-180 degrees.\n

\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.

\n",example:["\n
\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
"],itemtype:"property",name:"rotationX",type:"Number",readonly:"",alt:"red horizontal line right, green vertical line bottom. black background.",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:125,description:"

The system variable rotationY always contains the rotation of the\ndevice along the y axis. Value is represented as 0 to +/-90 degrees.\n

\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.

\n",example:["\n
\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
"],itemtype:"property",name:"rotationY",type:"Number",readonly:"",alt:"red horizontal line right, green vertical line bottom. black background.",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:158,description:"

The system variable rotationZ always contains the rotation of the\ndevice along the z axis. Value is represented as 0 to 359 degrees.\n

\nUnlike rotationX and rotationY, this variable is available for devices\nwith a built-in compass only.\n

\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.

\n",example:["\n
\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
"],itemtype:"property",name:"rotationZ",type:"Number",readonly:"",alt:"red horizontal line right, green vertical line bottom. black background.",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:194,description:"

The system variable pRotationX always contains the rotation of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as 0 to +/-180 degrees.\n

\npRotationX can also be used with rotationX to determine the rotate\ndirection of the device along the X-axis.

\n",example:["\n
\n\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely neccessary but the logic\n// will be different in that case.\n\nvar rX = rotationX + 180;\nvar pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270)|| rX - pRX < -270){\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270){\n rotateDirection = 'counter-clockwise';\n}\n\n
"],alt:"no image to display.",itemtype:"property",name:"pRotationX",type:"Number",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:237,description:"

The system variable pRotationY always contains the rotation of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as 0 to +/-90 degrees.\n

\npRotationY can also be used with rotationY to determine the rotate\ndirection of the device along the Y-axis.

\n",example:["\n
\n\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely neccessary but the logic\n// will be different in that case.\n\nvar rY = rotationY + 180;\nvar pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270)|| rY - pRY < -270){\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270){\n rotateDirection = 'counter-clockwise';\n}\n\n
"],alt:"no image to display.",itemtype:"property",name:"pRotationY",type:"Number",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:280,description:"

The system variable pRotationZ always contains the rotation of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as 0 to 359 degrees.\n

\npRotationZ can also be used with rotationZ to determine the rotate\ndirection of the device along the Z-axis.

\n",example:["\n
\n\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\nif ((rotationZ - pRotationZ > 0 &&\n rotationZ - pRotationZ < 270)||\n rotationZ - pRotationZ < -270){\n\n rotateDirection = 'clockwise';\n\n} else if (rotationZ - pRotationZ < 0 ||\n rotationZ - pRotationZ > 270){\n\n rotateDirection = 'counter-clockwise';\n\n}\n\n
"],alt:"no image to display.",itemtype:"property",name:"pRotationZ",type:"Number",readonly:"",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:346,description:"

The setMoveThreshold() function is used to set the movement threshold for\nthe deviceMoved() function. The default threshold is set to 0.5.

\n",itemtype:"method",name:"setMoveThreshold",params:[{name:"value",description:"

The threshold value

\n",type:"Number"}],class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:359,description:"

The setShakeThreshold() function is used to set the movement threshold for\nthe deviceShaken() function. The default threshold is set to 30.

\n",itemtype:"method",name:"setShakeThreshold",params:[{name:"value",description:"

The threshold value

\n",type:"Number"}],class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:372,description:"

The deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to\n0.5.

\n",itemtype:"method",name:"deviceMoved",example:['\n
\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
'],alt:"50x50 black rect in center of canvas. turns white on mobile when device moves",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:403,description:"

The deviceTurned() function is called when the device rotates by\nmore than 90 degrees continuously.\n

\nThe axis that triggers the deviceTurned() method is stored in the turnAxis\nvariable. The deviceTurned() method can be locked to trigger on any axis:\nX, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.

\n",itemtype:"method",name:"deviceTurned",example:["\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (value == 0){\n value = 255\n } else if (value == 255) {\n value = 0;\n }\n}\n\n
\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (turnAxis == 'X'){\n if (value == 0){\n value = 255\n } else if (value == 255) {\n value = 0;\n }\n }\n}\n\n
"],alt:"50x50 black rect in center of canvas. turns white on mobile when device turns\n50x50 black rect in center of canvas. turns white on mobile when x-axis turns",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/acceleration.js",line:462,description:"

The deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.

\n",itemtype:"method",name:"deviceShaken",example:['\n
\n\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
'],alt:"50x50 black rect in center of canvas. turns white on mobile when device shakes",class:"p5",module:"Events",submodule:"Acceleration"},{file:"src/events/keyboard.js",line:12,description:"

Holds the key codes of currently pressed keys.

\n",access:"private",tagname:"",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/keyboard.js",line:18,description:"

The boolean system variable keyIsPressed is true if any key is pressed\nand false if no keys are pressed.

\n",itemtype:"property",name:"keyIsPressed",type:"Boolean",readonly:"",example:["\n
\n\nvar value = 0;\nfunction draw() {\n if (keyIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n rect(25, 25, 50, 50);\n}\n\n
"],alt:"50x50 white rect that turns black on keypress.",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/keyboard.js",line:46,description:"

The system variable key always contains the value of the most recent\nkey on the keyboard that was typed. To get the proper capitalization, it\nis best to use it within keyTyped(). For non-ASCII keys, use the keyCode\nvariable.

\n",itemtype:"property",name:"key",type:"String",readonly:"",example:["\n
\n// Click any key to display it!\n// (Not Guaranteed to be Case Sensitive)\nfunction setup() {\n fill(245, 123, 158);\n textSize(50);\n}\n\nfunction draw() {\n background(200);\n text(key, 33,65); // Display last key pressed.\n}\n
"],alt:"canvas displays any key value that is pressed in pink font.",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/keyboard.js",line:75,description:'

The variable keyCode is used to detect special keys such as BACKSPACE,\nDELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,\nDOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\nYou can also check for custom keys by looking up the keyCode of any key\non a site like this: keycode.info.

\n',itemtype:"property",name:"keyCode",type:"Number",readonly:"",example:["\n
\nvar fillVal = 126;\nfunction draw() {\n fill(fillVal);\n rect(25, 25, 50, 50);\n}\n\nfunction keyPressed() {\n if (keyCode == UP_ARROW) {\n fillVal = 255;\n } else if (keyCode == DOWN_ARROW) {\n fillVal = 0;\n }\n return false; // prevent default\n}\n
"],alt:"Grey rect center. turns white when up arrow pressed and black when down",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/keyboard.js",line:108,description:"

The keyPressed() function is called once every time a key is pressed. The\nkeyCode for the key that was pressed is stored in the keyCode variable.\n

\nFor non-ASCII keys, use the keyCode variable. You can check if the keyCode\nequals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,\nOPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\n

\nFor ASCII keys that was pressed is stored in the key variable. However, it\ndoes not distinguish between uppercase and lowercase. For this reason, it\nis recommended to use keyTyped() to read the key variable, in which the\ncase of the variable will be distinguished.\n

\nBecause of how operating systems handle key repeats, holding down a key\nmay cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.

\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n",itemtype:"method",name:"keyPressed",example:['\n
\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n
\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n}\n\n
\n
\n\nfunction keyPressed(){\n // Do something\n return false; // prevent any default behaviour\n}\n\n
'],alt:"black rect center. turns white when key pressed and black when released\nblack rect center. turns white when left arrow pressed and black when right.",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/keyboard.js",line:198,description:"

The keyReleased() function is called once every time a key is released.\nSee key and keyCode for more information.

\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n",itemtype:"method",name:"keyReleased",example:["\n
\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n return false; // prevent any default behavior\n}\n\n
"],alt:"black rect center. turns white when key pressed and black when pressed again",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/keyboard.js",line:254,description:"

The keyTyped() function is called once every time a key is pressed, but\naction keys such as Ctrl, Shift, and Alt are ignored. The most recent\nkey pressed will be stored in the key variable.\n

\nBecause of how operating systems handle key repeats, holding down a key\nwill cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.

\nBrowsers may have different default behaviors attached to various key\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.

\n",itemtype:"method",name:"keyTyped",example:["\n
\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // uncomment to prevent any default behavior\n // return false;\n}\n\n
"],alt:"black rect center. turns white when 'a' key typed and black when 'b' pressed",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/keyboard.js",line:307,description:"

The onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.

\n",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/keyboard.js",line:317,description:'

The keyIsDown() function checks if the key is currently down, i.e. pressed.\nIt can be used if you have an object that moves, and you want several keys\nto be able to affect its behaviour simultaneously, such as moving a\nsprite diagonally. You can put in any number representing the keyCode of\nthe key, or use any of the variable keyCode names listed\nhere.

\n',itemtype:"method",name:"keyIsDown",params:[{name:"code",description:"

The key to check for.

\n",type:"Number"}],return:{description:"whether key is down or not",type:"Boolean"},example:["\n
\nvar x = 100;\nvar y = 100;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n if (keyIsDown(LEFT_ARROW))\n x-=5;\n\n if (keyIsDown(RIGHT_ARROW))\n x+=5;\n\n if (keyIsDown(UP_ARROW))\n y-=5;\n\n if (keyIsDown(DOWN_ARROW))\n y+=5;\n\n clear();\n fill(255, 0, 0);\n ellipse(x, y, 50, 50);\n}\n
"],alt:"50x50 red ellipse moves left, right, up and down with arrow presses.",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/keyboard.js",line:364,description:"

The checkDownKeys function returns a boolean true if any keys pressed\nand a false if no keys are currently pressed.

\n

Helps avoid instances where a multiple keys are pressed simultaneously and\nreleasing a single key will then switch the\nkeyIsPressed property to true.

\n",access:"private",tagname:"",class:"p5",module:"Events",submodule:"Keyboard"},{file:"src/events/mouse.js",line:23,description:"

The system variable mouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the canvas. If touch is\nused instead of mouse input, mouseX will hold the x value of the most\nrecent touch point.

\n",itemtype:"property",name:"mouseX",type:"Number",readonly:"",example:["\n
\n\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, 0, mouseX, 100);\n}\n\n
"],alt:"horizontal black line moves left and right with mouse x-position",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:49,description:"

The system variable mouseY always contains the current vertical position\nof the mouse, relative to (0, 0) of the canvas. If touch is\nused instead of mouse input, mouseY will hold the y value of the most\nrecent touch point.

\n",itemtype:"property",name:"mouseY",type:"Number",readonly:"",example:["\n
\n\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(0, mouseY, 100, mouseY);\n}\n\n
"],alt:"vertical black line moves up and down with mouse y-position",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:75,description:"

The system variable pmouseX always contains the horizontal position of\nthe mouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas.

\n",itemtype:"property",name:"pmouseX",type:"Number",readonly:"",example:['\n
\n\n// Move the mouse across the canvas to leave a trail\nfunction setup() {\n //slow down the frameRate to make it more visible\n frameRate(10);\n}\n\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, mouseY, pmouseX, pmouseY);\n print(pmouseX + " -> " + mouseX);\n}\n\n\n
'],alt:"line trail is created from cursor movements. faster movement make longer line.",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:107,description:"

The system variable pmouseY always contains the vertical position of the\nmouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas.

\n",itemtype:"property",name:"pmouseY",type:"Number",readonly:"",example:['\n
\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n //draw a square only if the mouse is not moving\n if(mouseY == pmouseY && mouseX == pmouseX)\n rect(20,20,60,60);\n\n print(pmouseY + " -> " + mouseY);\n}\n\n\n
'],alt:"60x60 black rect center, fuschia background. rect flickers on mouse movement",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:137,description:"

The system variable winMouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the window.

\n",itemtype:"property",name:"winMouseX",type:"Number",readonly:"",example:["\n
\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the horizontal mouse position\n //relative to the window\n myCanvas.position(winMouseX+1, windowHeight/2);\n\n //the y of the square is relative to the canvas\n rect(20,mouseY,60,60);\n}\n\n\n
"],alt:"60x60 black rect y moves with mouse y and fuschia canvas moves with mouse x",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:175,description:"

The system variable winMouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the window.

\n",itemtype:"property",name:"winMouseY",type:"Number",readonly:"",example:["\n
\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the vertical mouse position\n //relative to the window\n myCanvas.position(windowWidth/2, winMouseY+1);\n\n //the x of the square is relative to the canvas\n rect(mouseX,20,60,60);\n}\n\n\n
"],alt:"60x60 black rect x moves with mouse x and fuschia canvas y moves with mouse y",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:213,description:"

The system variable pwinMouseX always contains the horizontal position\nof the mouse in the frame previous to the current frame, relative to\n(0, 0) of the window.

\n",itemtype:"property",name:"pwinMouseX",type:"Number",readonly:"",example:["\n
\n\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n }\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current x position is the horizontal mouse speed\n var speed = abs(winMouseX-pwinMouseX);\n //change the size of the circle\n //according to the horizontal speed\n ellipse(50, 50, 10+speed*5, 10+speed*5);\n //move the canvas to the mouse position\n myCanvas.position( winMouseX+1, winMouseY+1);\n}\n\n\n
"],alt:"fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:255,description:"

The system variable pwinMouseY always contains the vertical position of\nthe mouse in the frame previous to the current frame, relative to (0, 0)\nof the window.

\n",itemtype:"property",name:"pwinMouseY",type:"Number",readonly:"",example:["\n
\n\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n }\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current y position is the vertical mouse speed\n var speed = abs(winMouseY-pwinMouseY);\n //change the size of the circle\n //according to the vertical speed\n ellipse(50, 50, 10+speed*5, 10+speed*5);\n //move the canvas to the mouse position\n myCanvas.position( winMouseX+1, winMouseY+1);\n}\n\n\n
"],alt:"fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:298,description:"

Processing automatically tracks if the mouse button is pressed and which\nbutton is pressed. The value of the system variable mouseButton is either\nLEFT, RIGHT, or CENTER depending on which button was pressed last.\nWarning: different browsers may track mouseButton differently.

\n",itemtype:"property",name:"mouseButton",type:"Constant",readonly:"",example:["\n
\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n if (mouseButton == LEFT)\n ellipse(50, 50, 50, 50);\n if (mouseButton == RIGHT)\n rect(25, 25, 50, 50);\n if (mouseButton == CENTER)\n triangle(23, 75, 50, 20, 78, 75);\n }\n\n print(mouseButton);\n}\n\n
"],alt:"50x50 black ellipse appears on center of fuschia canvas on mouse click/press.",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:334,description:"

The boolean system variable mouseIsPressed is true if the mouse is pressed\nand false if not.

\n",itemtype:"property",name:"mouseIsPressed",type:"Boolean",readonly:"",example:["\n
\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed)\n ellipse(50, 50, 50, 50);\n else\n rect(25, 25, 50, 50);\n\n print(mouseIsPressed);\n}\n\n
"],alt:"black 50x50 rect becomes ellipse with mouse click/press. fuschia background.",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:416,description:"

The mouseMoved() function is called every time the mouse moves and a mouse\nbutton is not pressed.

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n",itemtype:"method",name:"mouseMoved",example:['\n
\n\n// Move the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
'],alt:"black 50x50 rect becomes lighter with mouse movements until white then resets\nno image displayed",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:460,description:"

The mouseDragged() function is called once every time the mouse moves and\na mouse button is pressed. If no mouseDragged() function is defined, the\ntouchMoved() function will be called instead if it is defined.

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n",itemtype:"method",name:"mouseDragged",example:['\n
\n\n// Drag the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseDragged() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
'],alt:"black 50x50 rect turns lighter with mouse click and drag until white, resets\nno image displayed",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:531,description:"

The mousePressed() function is called once after every time a mouse button\nis pressed. The mouseButton variable (see the related reference entry)\ncan be used to determine which button has been pressed. If no\nmousePressed() function is defined, the touchStarted() function will be\ncalled instead if it is defined.

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n",itemtype:"method",name:"mousePressed",example:['\n
\n\n// Click within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mousePressed() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
'],alt:"black 50x50 rect turns white with mouse click/press.\nno image displayed",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:597,description:"

The mouseReleased() function is called every time a mouse button is\nreleased. If no mouseReleased() function is defined, the touchEnded()\nfunction will be called instead if it is defined.

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n",itemtype:"method",name:"mouseReleased",example:['\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseReleased() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
'],alt:"black 50x50 rect turns white with mouse click/press.\nno image displayed",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:664, +description:"

The mouseClicked() function is called once after a mouse button has been\npressed and then released.

\nBrowsers handle clicks differently, so this function is only guaranteed to be\nrun when the left mouse button is clicked. To handle other mouse buttons\nbeing pressed or released, see mousePressed() or mouseReleased().

\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.

\n",itemtype:"method",name:"mouseClicked",example:['\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction mouseClicked() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
'],alt:"black 50x50 rect turns white with mouse click/press.\nno image displayed",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:723,description:'

The doubleClicked() function is executed every time a event\nlistener has detected a dblclick event which is a part of the\nDOM L3 specification. The doubleClicked event is fired when a\npointing device button (usually a mouse's primary button)\nis clicked twice on a single element. For more info on the\ndblclick event refer to mozilla's documentation here:\nhttps://developer.mozilla.org/en-US/docs/Web/Events/dblclick

\n',itemtype:"method",name:"doubleClicked",example:['\n
\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been double clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction doubleClicked() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction doubleClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
'],alt:"black 50x50 rect turns white with mouse doubleClick/press.\nno image displayed",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/mouse.js",line:781,description:"

The function mouseWheel() is executed every time a vertical mouse wheel\nevent is detected either triggered by an actual mouse wheel or by a\ntouchpad.

\nThe event.delta property returns the amount the mouse wheel\nhave scrolled. The values can be positive or negative depending on the\nscroll direction (on OS X with "natural" scrolling enabled, the signs\nare inverted).

\nBrowsers may have different default behaviors attached to various\nmouse events. To prevent any default behavior for this event, add\n"return false" to the end of the method.

\nDue to the current support of the "wheel" event on Safari, the function\nmay only work as expected if "return false" is included while using Safari.

\n",itemtype:"method",name:"mouseWheel",example:["\n
\n\nvar pos = 25;\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n rect(25, pos, 50, 50);\n}\n\nfunction mouseWheel(event) {\n print(event.delta);\n //move the square according to the vertical scroll amount\n pos += event.delta;\n //uncomment to block page scrolling\n //return false;\n}\n\n
"],alt:"black 50x50 rect moves up and down with vertical scroll. fuschia background",class:"p5",module:"Events",submodule:"Mouse"},{file:"src/events/touch.js",line:12,description:"

The system variable touches[] contains an array of the positions of all\ncurrent touch points, relative to (0, 0) of the canvas, and IDs identifying a\nunique touch as it moves. Each element in the array is an object with x, y,\nand id properties.

\n

The touches[] array is not supported on Safari and IE on touch-based\ndesktops (laptops).

\n",itemtype:"property",name:"touches",type:"Object[]",readonly:"",class:"p5",module:"Events",submodule:"Touch"},{file:"src/events/touch.js",line:53,description:"

The touchStarted() function is called once after every time a touch is\nregistered. If no touchStarted() function is defined, the mousePressed()\nfunction will be called instead if it is defined.

\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.

\n",itemtype:"method",name:"touchStarted",example:['\n
\n\n// Touch within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchStarted() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction touchStarted() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
'],alt:"50x50 black rect turns white with touch event.\nno image displayed",class:"p5",module:"Events",submodule:"Touch"},{file:"src/events/touch.js",line:116,description:"

The touchMoved() function is called every time a touch move is registered.\nIf no touchMoved() function is defined, the mouseDragged() function will\nbe called instead if it is defined.

\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.

\n",itemtype:"method",name:"touchMoved",example:['\n
\n\n// Move your finger across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction touchMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
'],alt:"50x50 black rect turns lighter with touch until white. resets\nno image displayed",class:"p5",module:"Events",submodule:"Touch"},{file:"src/events/touch.js",line:178,description:"

The touchEnded() function is called every time a touch ends. If no\ntouchEnded() function is defined, the mouseReleased() function will be\ncalled instead if it is defined.

\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.

\n",itemtype:"method",name:"touchEnded",example:['\n
\n\n// Release touch within the image to\n// change the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchEnded() {\n if (value == 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n
\n\nfunction touchEnded() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
'],alt:"50x50 black rect turns white with touch.\nno image displayed",class:"p5",module:"Events",submodule:"Touch"},{file:"src/image/filters.js",line:3,description:'

This module defines the filters for use with image buffers.

\n

This module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy.

\n

Generally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.

\n

A number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation.

\n',class:"p5",module:"Events"},{file:"src/image/filters.js",line:28,description:"

Returns the pixel buffer for a canvas

\n",access:"private",tagname:"",params:[{name:"canvas",description:"

the canvas to get pixels from

\n",type:"Canvas|ImageData"}],return:{description:"a one-dimensional array containing\n the data in thc RGBA order, with integer\n values between 0 and 255",type:"Uint8ClampedArray"},class:"p5",module:"Events"},{file:"src/image/filters.js",line:51,description:"

Returns a 32 bit number containing ARGB data at ith pixel in the\n1D array containing pixels data.

\n",access:"private",tagname:"",params:[{name:"data",description:"

array returned by _toPixels()

\n",type:"Uint8ClampedArray"},{name:"i",description:"

index of a 1D Image Array

\n",type:"Integer"}],return:{description:"32 bit integer value representing\n ARGB value.",type:"Integer"},class:"p5",module:"Events"},{file:"src/image/filters.js",line:70,description:"

Modifies pixels RGBA values to values contained in the data object.

\n",access:"private",tagname:"",params:[{name:"pixels",description:"

array returned by _toPixels()

\n",type:"Uint8ClampedArray"},{name:"data",description:"

source 1D array where each value\n represents ARGB values

\n",type:"Int32Array"}],class:"p5",module:"Events"},{file:"src/image/filters.js",line:90,description:'

Returns the ImageData object for a canvas\nhttps://developer.mozilla.org/en-US/docs/Web/API/ImageData

\n',access:"private",tagname:"",params:[{name:"canvas",description:"

canvas to get image data from

\n",type:"Canvas|ImageData"}],return:{description:"Holder of pixel data (and width and\n height) for a canvas",type:"ImageData"},class:"p5",module:"Events"},{file:"src/image/filters.js",line:113,description:"

Returns a blank ImageData object.

\n",access:"private",tagname:"",params:[{name:"width",description:"",type:"Integer"},{name:"height",description:"",type:"Integer"}],return:{description:"",type:"ImageData"},class:"p5",module:"Events"},{file:"src/image/filters.js",line:129,description:"

Applys a filter function to a canvas.

\n

The difference between this and the actual filter functions defined below\nis that the filter functions generally modify the pixel buffer but do\nnot actually put that data back to the canvas (where it would actually\nupdate what is visible). By contrast this method does make the changes\nactually visible in the canvas.

\n

The apply method is the method that callers of this module would generally\nuse. It has been separated from the actual filters to support an advanced\nuse case of creating a filter chain that executes without actually updating\nthe canvas in between everystep.

\n",params:[{name:"canvas",description:"

[description]

\n",type:"HTMLCanvasElement"},{name:"func",description:"

[description]

\n",type:"Function(ImageData,Object)"},{name:"filterParam",description:"

[description]

\n",type:"Object"}],class:"p5",module:"Events"},{file:"src/image/filters.js",line:167,description:'

Converts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.

\n

Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/

\n',params:[{name:"canvas",description:"",type:"Canvas"},{name:"level",description:"",type:"Float"}],class:"p5",module:"Events"},{file:"src/image/filters.js",line:202,description:'

Converts any colors in the image to grayscale equivalents.\nNo parameter is used.

\n

Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/

\n',params:[{name:"canvas",description:"",type:"Canvas"}],class:"p5",module:"Events"},{file:"src/image/filters.js",line:224,description:"

Sets the alpha channel to entirely opaque. No parameter is used.

\n",params:[{name:"canvas",description:"",type:"Canvas"}],class:"p5",module:"Events"},{file:"src/image/filters.js",line:239,description:"

Sets each pixel to its inverse value. No parameter is used.

\n",params:[{name:"canvas",description:"",type:"Canvas"}],class:"p5",module:"Events"},{file:"src/image/filters.js",line:255,description:"

Limits each channel of the image to the number of colors specified as\nthe parameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.

\n

Adapted from java based processing implementation

\n",params:[{name:"canvas",description:"",type:"Canvas"},{name:"level",description:"",type:"Integer"}],class:"p5",module:"Events"},{file:"src/image/filters.js",line:286,description:"

reduces the bright areas in an image

\n",params:[{name:"canvas",description:"",type:"Canvas"}],class:"p5",module:"Events"},{file:"src/image/filters.js",line:367,description:"

increases the bright areas in an image

\n",params:[{name:"canvas",description:"",type:"Canvas"}],class:"p5",module:"Events"},{file:"src/image/image.js",line:8,description:"

This module defines the p5 methods for the p5.Image class\nfor drawing images to the main display canvas.

\n",class:"p5",module:"Image",submodule:"Image"},{file:"src/image/image.js",line:24,description:"

Creates a new p5.Image (the datatype for storing images). This provides a\nfresh buffer of pixels to play with. Set the size of the buffer with the\nwidth and height parameters.\n

\n.pixels gives access to an array containing the values for all the pixels\nin the display window.\nThese values are numbers. This array is the size (including an appropriate\nfactor for the pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. See .pixels for\nmore info. It may also be simpler to use set() or get().\n

\nBefore accessing the pixels of an image, the data must loaded with the\nloadPixels() function. After the array data has been modified, the\nupdatePixels() function must be run to update the changes.

\n",itemtype:"method",name:"createImage",params:[{name:"width",description:"

width in pixels

\n",type:"Integer"},{name:"height",description:"

height in pixels

\n",type:"Integer"}],return:{description:"the p5.Image object",type:"p5.Image"},example:["\n
\n\nimg = createImage(66, 66);\nimg.loadPixels();\nfor (i = 0; i < img.width; i++) {\n for (j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
\n\n
\n\nimg = createImage(66, 66);\nimg.loadPixels();\nfor (i = 0; i < img.width; i++) {\n for (j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, i % img.width * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n
\n\n
\n\nvar pink = color(255, 102, 204);\nimg = createImage(66, 66);\nimg.loadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (width * d) * (height/2 * d);\nfor (var i = 0; i < halfImage; i+=4) {\n img.pixels[i] = red(pink);\n img.pixels[i+1] = green(pink);\n img.pixels[i+2] = blue(pink);\n img.pixels[i+3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
"],alt:"66x66 dark turquoise rect in center of canvas.\n2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas\nno image displayed",class:"p5",module:"Image",submodule:"Image"},{file:"src/image/image.js",line:103,description:"

Save the current canvas as an image. In Safari, this will open the\nimage in the window and the user must provide their own\nfilename on save-as. Other browsers will either save the\nfile immediately, or prompt the user with a dialogue window.

\n",itemtype:"method",name:"saveCanvas",class:"p5",module:"Image",submodule:"Image",overloads:[{line:103,params:[{name:"selectedCanvas",description:"

a variable\n representing a specific html5 canvas (optional)

\n",type:"p5.Element|HTMLCanvasElement"},{name:"filename",description:"",type:"String",optional:!0},{name:"extension",description:"

'jpg' or 'png'

\n",type:"String",optional:!0}]},{line:115,params:[{name:"filename",description:"",type:"String",optional:!0},{name:"extension",description:"",type:"String",optional:!0}]}]},{file:"src/image/image.js",line:233,description:'

Capture a sequence of frames that can be used to create a movie.\nAccepts a callback. For example, you may wish to send the frames\nto a server where they can be stored or converted into a movie.\nIf no callback is provided, the browser will pop up save dialogues in an\nattempt to download all of the images that have just been created. With the\ncallback provided the image data isn't saved by default but instead passed\nas an argument to the callback function as an array of objects, with the\nsize of array equal to the total number of frames.

\n

Note that saveFrames() will only save the first 15 frames of an animation.\nTo export longer animations, you might look into a library like\nccapture.js.

\n',itemtype:"method",name:"saveFrames",params:[{name:"filename",description:"",type:"String"},{name:"extension",description:"

'jpg' or 'png'

\n",type:"String"},{name:"duration",description:"

Duration in seconds to save the frames for.

\n",type:"Number"},{name:"framerate",description:"

Framerate to save the frames in.

\n",type:"Number"},{name:"callback",description:"

A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension.

\n",type:"Function(Array)",optional:!0}],example:['\n
\nfunction draw() {\n background(mouseX);\n}\n\nfunction mousePressed() {\n saveFrames("out", "png", 1, 25, function(data){\n print(data);\n });\n}\n
'],alt:"canvas background goes from light to dark with mouse x.",class:"p5",module:"Image",submodule:"Image"},{file:"src/image/loading_displaying.js",line:17,description:"

Loads an image from a path and creates a p5.Image from it.\n

\nThe image may not be immediately available for rendering\nIf you want to ensure that the image is ready before doing\nanything with it, place the loadImage() call in preload().\nYou may also supply a callback function to handle the image when it's ready.\n

\nThe path to the image should be relative to the HTML file\nthat links in your sketch. Loading an image from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.

\n",itemtype:"method",name:"loadImage",params:[{name:"path",description:"

Path of the image to be loaded

\n",type:"String"},{name:"successCallback",description:"

Function to be called once\n the image is loaded. Will be passed the\n p5.Image.

\n",type:"function(p5.Image)",optional:!0},{name:"failureCallback",description:"

called with event error if\n the image fails to load.

\n",type:"Function(Event)",optional:!0}],return:{description:"the p5.Image object",type:"p5.Image"},example:['\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/laDefense.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n}\n\n
\n
\n\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage("assets/laDefense.jpg", function(img) {\n image(img, 0, 0);\n });\n}\n\n
'],alt:"image of the underside of a white umbrella and grided ceililng above\nimage of the underside of a white umbrella and grided ceililng above",class:"p5",module:"Image",submodule:"Loading & Displaying"},{file:"src/image/loading_displaying.js",line:107,description:"

Validates clipping params. Per drawImage spec sWidth and sHight cannot be\nnegative or greater than image intrinsic width and height

\n",access:"private",tagname:"",params:[{name:"sVal",description:"",type:"Number"},{name:"iVal",description:"",type:"Number"}],return:{description:"",type:"Number"},class:"p5",module:"Image",submodule:"Loading & Displaying"},{file:"src/image/loading_displaying.js",line:125,description:'

Draw an image to the p5.js canvas.

\n

This function can be used with different numbers of parameters. The\nsimplest use requires only three parameters: img, x, and y—where (x, y) is\nthe position of the image. Two more parameters can optionally be added to\nspecify the width and height of the image.

\n

This function can also be used with all eight Number parameters. To\ndifferentiate between all these parameters, p5.js uses the language of\n"destination rectangle" (which corresponds to "dx", "dy", etc.) and "source\nimage" (which corresponds to "sx", "sy", etc.) below. Specifying the\n"source image" dimensions can be useful when you want to display a\nsubsection of the source image instead of the whole thing. Here's a diagram\nto explain further:\n

\n',itemtype:"method",name:"image",example:['\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/laDefense.jpg");\n}\nfunction setup() {\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img\'s original width and height\n image(img, 0, 0);\n}\n\n
\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/laDefense.jpg");\n}\nfunction setup() {\n background(50);\n // Top-left corner of the img is at (10, 10)\n // Width and height are 50 x 50\n image(img, 10, 10, 50, 50);\n}\n\n
\n
\n\nfunction setup() {\n // Here, we use a callback to display the image after loading\n loadImage("assets/laDefense.jpg", function(img) {\n image(img, 0, 0);\n });\n}\n\n
\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/gradient.png");\n}\nfunction setup() {\n // 1. Background image\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img\'s original width and height, 100 x 100\n image(img, 0, 0);\n // 2. Top right image\n // Top-left corner of destination rectangle is at (50, 0)\n // Destination rectangle width and height are 40 x 20\n // The next parameters are relative to the source image:\n // - Starting at position (50, 50) on the source image, capture a 50 x 50\n // subsection\n // - Draw this subsection to fill the dimensions of the destination rectangle\n image(img, 50, 0, 40, 20, 50, 50, 50, 50);\n}\n\n
'],alt:"image of the underside of a white umbrella and gridded ceiling above\nimage of the underside of a white umbrella and gridded ceiling above",class:"p5",module:"Image",submodule:"Loading & Displaying",overloads:[{line:125,params:[{name:"img",description:"

the image to display

\n",type:"p5.Image|p5.Graphics"},{name:"x",description:"

the x-coordinate of the top-left corner of the image

\n",type:"Number"},{name:"y",description:"

the y-coordinate of the top-left corner of the image

\n",type:"Number"},{name:"width",description:"

the width to draw the image

\n",type:"Number",optional:!0},{name:"height",description:"

the height to draw the image

\n",type:"Number",optional:!0}]},{line:213,params:[{name:"img",description:"",type:"p5.Image|p5.Graphics"},{name:"dx",description:"

the x-coordinate of the destination\n rectangle in which to draw the source image

\n",type:"Number"},{name:"dy",description:"

the y-coordinate of the destination\n rectangle in which to draw the source image

\n",type:"Number"},{name:"dWidth",description:"

the width of the destination rectangle

\n",type:"Number"},{name:"dHeight",description:"

the height of the destination rectangle

\n",type:"Number"},{name:"sx",description:"

the x-coordinate of the subsection of the source\nimage to draw into the destination rectangle

\n",type:"Number"},{name:"sy",description:"

the y-coordinate of the subsection of the source\nimage to draw into the destination rectangle

\n",type:"Number"},{name:"sWidth",description:"

the width of the subsection of the\n source image to draw into the destination\n rectangle

\n",type:"Number",optional:!0},{name:"sHeight",description:"

the height of the subsection of the\n source image to draw into the destination rectangle

\n",type:"Number",optional:!0}]}]},{file:"src/image/loading_displaying.js",line:289,description:"

Sets the fill value for displaying images. Images can be tinted to\nspecified colors or made transparent by including an alpha value.\n

\nTo apply transparency to an image without affecting its color, use\nwhite as the tint color and specify an alpha value. For instance,\ntint(255, 128) will make an image 50% transparent (assuming the default\nalpha range of 0-255, which can be changed with colorMode()).\n

\nThe value for the gray parameter must be less than or equal to the current\nmaximum value as specified by colorMode(). The default maximum value is\n255.

\n",itemtype:"method",name:"tint",class:"p5",module:"Image",submodule:"Loading & Displaying",overloads:[{line:289,params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}]},{line:313,params:[{name:"value",description:"

a color string

\n",type:"String"},{name:"alpha",description:"",type:"Number",optional:!0}]},{line:319,params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}]},{line:325,params:[{name:"color",description:"

the tint color

\n",type:"p5.Color"},{name:"alpha",description:"",type:"Number",optional:!0}]}]},{file:"src/image/loading_displaying.js",line:384,description:"

Removes the current fill value for displaying images and reverts to\ndisplaying images with their original hues.

\n",itemtype:"method",name:"noTint",example:['\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n tint(0, 153, 204); // Tint blue\n image(img, 0, 0);\n noTint(); // Disable tint\n image(img, 50, 0);\n}\n\n
'],alt:"2 side by side images of bricks, left image with blue tint",class:"p5",module:"Image",submodule:"Loading & Displaying"},{file:"src/image/loading_displaying.js",line:413,description:"

Apply the current tint color to the input image, return the resulting\ncanvas.

\n",params:[{name:"The",description:"

image to be tinted

\n",type:"p5.Image"}],return:{description:"The resulting tinted canvas",type:"Canvas"},class:"p5",module:"Image",submodule:"Loading & Displaying"},{file:"src/image/loading_displaying.js",line:449,description:"

Set image mode. Modifies the location from which images are drawn by\nchanging the way in which parameters given to image() are interpreted.\nThe default mode is imageMode(CORNER), which interprets the second and\nthird parameters of image() as the upper-left corner of the image. If\ntwo additional parameters are specified, they are used to set the image's\nwidth and height.\n

\nimageMode(CORNERS) interprets the second and third parameters of image()\nas the location of one corner, and the fourth and fifth parameters as the\nopposite corner.\n

\nimageMode(CENTER) interprets the second and third parameters of image()\nas the image's center point. If two additional parameters are specified,\nthey are used to set the image's width and height.

\n",itemtype:"method",name:"imageMode",params:[{name:"mode",description:"

either CORNER, CORNERS, or CENTER

\n",type:"Constant"}],example:['\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n imageMode(CORNER);\n image(img, 10, 10, 50, 50);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n imageMode(CORNERS);\n image(img, 10, 10, 90, 40);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n imageMode(CENTER);\n image(img, 50, 50, 80, 80);\n}\n\n
'],alt:"small square image of bricks\nhorizontal rectangle image of bricks\nlarge square image of bricks",class:"p5",module:"Image",submodule:"Loading & Displaying"},{file:"src/image/p5.Image.js",line:9,description:"

This module defines the p5.Image class and P5 methods for\ndrawing images to the main display canvas.

\n",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:45,description:"

Image width.

\n",itemtype:"property",name:"width",type:"Number",readonly:"",example:['\n
\nvar img;\nfunction preload() {\n img = loadImage("assets/rockies.jpg");\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i=0; i < img.width; i++) {\n var c = img.get(i, img.height/2);\n stroke(c);\n line(i, height/2, i, height);\n }\n}\n
'],alt:"rocky mountains in top and horizontal lines in corresponding colors in bottom.",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:72,description:"

Image height.

\n",itemtype:"property",name:"height",type:"Number",readonly:"",example:['\n
\nvar img;\nfunction preload() {\n img = loadImage("assets/rockies.jpg");\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i=0; i < img.height; i++) {\n var c = img.get(img.width/2, i);\n stroke(c);\n line(0, i, width/2, i);\n }\n}\n
'],alt:"rocky mountains on right and vertical lines in corresponding colors on left.",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:106, +description:'

Array containing the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh denisty displays may have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. With\npixelDensity = 2, there will be 160,000. The first four values\n(indices 0-3) in the array will be the R, G, B, A values of the pixel at\n(0, 0). The second four values (indices 4-7) will contain the R, G, B, A\nvalues of the pixel at (1, 0). More generally, to set values for a pixel\nat (x, y):

\n
var d = pixelDensity;\nfor (var i = 0; i < d; i++) {\n  for (var j = 0; j < d; j++) {\n    // loop over\n    idx = 4 * ((y * d + j) * width * d + (x * d + i));\n    pixels[idx] = r;\n    pixels[idx+1] = g;\n    pixels[idx+2] = b;\n    pixels[idx+3] = a;\n  }\n}\n
\n



\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.

\n',itemtype:"property",name:"pixels",type:"Number[]",example:["\n
\n\nimg = createImage(66, 66);\nimg.loadPixels();\nfor (i = 0; i < img.width; i++) {\n for (j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
\n
\n\nvar pink = color(255, 102, 204);\nimg = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < 4*(width*height/2); i+=4) {\n img.pixels[i] = red(pink);\n img.pixels[i+1] = green(pink);\n img.pixels[i+2] = blue(pink);\n img.pixels[i+3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
"],alt:"66x66 turquoise rect in center of canvas\n66x66 pink rect in center of canvas",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:177,description:"

Helper fxn for sharing pixel methods

\n",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:186,description:"

Loads the pixels data for this image into the [pixels] attribute.

\n",itemtype:"method",name:"loadPixels",example:['\n
\nvar myImage;\nvar halfImage;\n\nfunction preload() {\n myImage = loadImage("assets/rockies.jpg");\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * width * height/2;\n for(var i = 0; i < halfImage; i++){\n myImage.pixels[i+halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0);\n}\n
'],alt:"2 images of rocky mountains vertically stacked",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:222,description:"

Updates the backing canvas for this image with the contents of\nthe [pixels] array.

\n",itemtype:"method",name:"updatePixels",class:"p5.Image",module:"Image",submodule:"Image",overloads:[{line:222,params:[{name:"x",description:"

x-offset of the target update area for the\n underlying canvas

\n",type:"Integer"},{name:"y",description:"

y-offset of the target update area for the\n underlying canvas

\n",type:"Integer"},{name:"w",description:"

height of the target update area for the\n underlying canvas

\n",type:"Integer"},{name:"h",description:"

height of the target update area for the\n underlying canvas

\n",type:"Integer"}]},{line:236,params:[]}]},{file:"src/image/p5.Image.js",line:270,description:"

Get a region of pixels from an image.

\n

If no params are passed, those whole image is returned,\nif x and y are the only params passed a single pixel is extracted\nif all params are passed a rectangle region is extracted and a p5.Image\nis returned.

\n

Returns undefined if the region is outside the bounds of the image

\n",itemtype:"method",name:"get",params:[{name:"x",description:"

x-coordinate of the pixel

\n",type:"Number",optional:!0},{name:"y",description:"

y-coordinate of the pixel

\n",type:"Number",optional:!0},{name:"w",description:"

width

\n",type:"Number",optional:!0},{name:"h",description:"

height

\n",type:"Number",optional:!0}],return:{description:"color of pixel at x,y in array format\n [R, G, B, A] or p5.Image",type:"Number[]|Color|p5.Image"},example:['\n
\nvar myImage;\nvar c;\n\nfunction preload() {\n myImage = loadImage("assets/rockies.jpg");\n}\n\nfunction setup() {\n background(myImage);\n noStroke();\n c = myImage.get(60, 90);\n fill(c);\n rect(25, 25, 50, 50);\n}\n\n//get() returns color here\n
'],alt:"image of rocky mountains with 50x50 green rect in front",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:315,description:"

Set the color of a single pixel or write an image into\nthis p5.Image.

\n

Note that for a large number of pixels this will\nbe slower than directly manipulating the pixels array\nand then calling updatePixels().

\n",itemtype:"method",name:"set",params:[{name:"x",description:"

x-coordinate of the pixel

\n",type:"Number"},{name:"y",description:"

y-coordinate of the pixel

\n",type:"Number"},{name:"a",description:"

grayscale value | pixel array |\n a p5.Color | image to copy

\n",type:"Number|Array|Object"}],example:["\n
\n\nimg = createImage(66, 66);\nimg.loadPixels();\nfor (i = 0; i < img.width; i++) {\n for (j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, i % img.width * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n
"],alt:"2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:353,description:"

Resize the image to a new width and height. To make the image scale\nproportionally, use 0 as the value for the wide or high parameter.\nFor instance, to make the width of an image 150 pixels, and change\nthe height using the same proportion, use resize(150, 0).

\n",itemtype:"method",name:"resize",params:[{name:"width",description:"

the resized image width

\n",type:"Number"},{name:"height",description:"

the resized image height

\n",type:"Number"}],example:['\n
\nvar img;\n\nfunction setup() {\n img = loadImage("assets/rockies.jpg");\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n
'],alt:"image of rocky mountains. zoomed in",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:435,description:"

Copies a region of pixels from one image to another. If no\nsrcImage is specified this is used as the source. If the source\nand destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.

\n",itemtype:"method",name:"copy",params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image|p5.Graphics|undefined"},{name:"sx",description:"

X coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sy",description:"

Y coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sw",description:"

source image width

\n",type:"Integer"},{name:"sh",description:"

source image height

\n",type:"Integer"},{name:"dx",description:"

X coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dy",description:"

Y coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dw",description:"

destination image width

\n",type:"Integer"},{name:"dh",description:"

destination image height

\n",type:"Integer"}],example:['\n
\nvar photo;\nvar bricks;\nvar x;\nvar y;\n\nfunction preload() {\n photo = loadImage("assets/rockies.jpg");\n bricks = loadImage("assets/bricks.jpg");\n}\n\nfunction setup() {\n x = bricks.width/2;\n y = bricks.height/2;\n photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n image(photo, 0, 0);\n}\n
'],alt:"image of rocky mountains and smaller image on top of bricks at top left",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:480,description:"

Masks part of an image from displaying by loading another\nimage and using it's alpha channel as an alpha channel for\nthis image.

\n",itemtype:"method",name:"mask",params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image"}],example:['\n
\nvar photo, maskImage;\nfunction preload() {\n photo = loadImage("assets/rockies.jpg");\n maskImage = loadImage("assets/mask2.png");\n}\n\nfunction setup() {\n createCanvas(100, 100);\n photo.mask(maskImage);\n image(photo, 0, 0);\n}\n
'],alt:"image of rocky mountains with white at right\n\n\nhttp://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:543,description:"

Applies an image filter to a p5.Image

\n",itemtype:"method",name:"filter",params:[{name:"operation",description:"

one of threshold, gray, invert, posterize, opaque\n erode, dilate and blur. See Filters.js for docs on\n each available filter

\n",type:"String"},{name:"value",description:"",type:"Number|undefined"}],example:['\n
\nvar photo1;\nvar photo2;\n\nfunction preload() {\n photo1 = loadImage("assets/rockies.jpg");\n photo2 = loadImage("assets/rockies.jpg");\n}\n\nfunction setup() {\n photo2.filter("gray");\n image(photo1, 0, 0);\n image(photo2, width/2, 0);\n}\n
'],alt:"2 images of rocky mountains left one in color, right in black and white",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:577,description:"

Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.

\n",itemtype:"method",name:"blend",params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image|undefined"},{name:"sx",description:"

X coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sy",description:"

Y coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sw",description:"

source image width

\n",type:"Integer"},{name:"sh",description:"

source image height

\n",type:"Integer"},{name:"dx",description:"

X coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dy",description:"

Y coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dw",description:"

destination image width

\n",type:"Integer"},{name:"dh",description:"

destination image height

\n",type:"Integer"},{name:"blendMode",description:'

the blend mode

\n

Available blend modes are: normal | multiply | screen | overlay |\n darken | lighten | color-dodge | color-burn | hard-light |\n soft-light | difference | exclusion | hue | saturation |\n color | luminosity

\n

http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/

\n',type:"Integer"}],example:['\n
\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage("assets/rockies.jpg");\n bricks = loadImage("assets/bricks_third.jpg");\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\n
\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage("assets/rockies.jpg");\n bricks = loadImage("assets/bricks_third.jpg");\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\n
\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage("assets/rockies.jpg");\n bricks = loadImage("assets/bricks_third.jpg");\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
'],alt:"image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:658,description:"

helper method for web GL mode to indicate that an image has been\nchanged or unchanged since last upload. gl texture upload will\nset this value to false after uploading the texture.

\n",itemtype:"method",name:"setModified",params:[{name:"val",description:"

sets whether or not the image has been\nmodified.

\n",type:"Boolean"}],access:"private",tagname:"",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:671,description:"

helper method for web GL mode to figure out if the image\nhas been modified and might need to be re-uploaded to texture\nmemory between frames.

\n",itemtype:"method",name:"isModified",access:"private",tagname:"",return:{description:"a boolean indicating whether or not the\nimage has been updated or modified since last texture upload.",type:"Boolean"},class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/p5.Image.js",line:684,description:"

Saves the image to a file and force the browser to download it.\nAccepts two strings for filename and file extension\nSupports png (default) and jpg.

\n",itemtype:"method",name:"save",params:[{name:"filename",description:"

give your file a name

\n",type:"String"},{name:"extension",description:"

'png' or 'jpg'

\n",type:"String"}],example:['\n
\nvar photo;\n\nfunction preload() {\n photo = loadImage("assets/rockies.jpg");\n}\n\nfunction draw() {\n image(photo, 0, 0);\n}\n\nfunction keyTyped() {\n if (key == \'s\') {\n photo.save("photo", "png");\n }\n}\n
'],alt:"image of rocky mountains.",class:"p5.Image",module:"Image",submodule:"Image"},{file:"src/image/pixels.js",line:14,description:"

Uint8ClampedArray\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. On a\nretina display, there will be 160,000.\n

\nThe first four values (indices 0-3) in the array will be the R, G, B, A\nvalues of the pixel at (0, 0). The second four values (indices 4-7) will\ncontain the R, G, B, A values of the pixel at (1, 0). More generally, to\nset values for a pixel at (x, y):

\n
var d = pixelDensity();\nfor (var i = 0; i < d; i++) {\n  for (var j = 0; j < d; j++) {\n    // loop over\n    idx = 4 * ((y * d + j) * width * d + (x * d + i));\n    pixels[idx] = r;\n    pixels[idx+1] = g;\n    pixels[idx+2] = b;\n    pixels[idx+3] = a;\n  }\n}\n
\n

While the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that set() will automatically take care of\nsetting all the appropriate values in pixels[] for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.\n

\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.\n

\nNote that this is not a standard javascript array. This means that\nstandard javascript functions such as slice() or\narrayCopy() do not\nwork.

",itemtype:"property",name:"pixels",type:"Number[]",example:["\n
\n\nvar pink = color(255, 102, 204);\nloadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (width * d) * (height/2 * d);\nfor (var i = 0; i < halfImage; i+=4) {\n pixels[i] = red(pink);\n pixels[i+1] = green(pink);\n pixels[i+2] = blue(pink);\n pixels[i+3] = alpha(pink);\n}\nupdatePixels();\n\n
"],alt:"top half of canvas pink, bottom grey",class:"p5",module:"Image",submodule:"Pixels"},{file:"src/image/pixels.js",line:83,description:"

Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.

\nAvailable blend modes are: BLEND | DARKEST | LIGHTEST | DIFFERENCE |\nMULTIPLY| EXCLUSION | SCREEN | REPLACE | OVERLAY | HARD_LIGHT |\nSOFT_LIGHT | DODGE | BURN | ADD | NORMAL

\n",itemtype:"method",name:"blend",params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image|undefined"},{name:"sx",description:"

X coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sy",description:"

Y coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sw",description:"

source image width

\n",type:"Integer"},{name:"sh",description:"

source image height

\n",type:"Integer"},{name:"dx",description:"

X coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dy",description:"

Y coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dw",description:"

destination image width

\n",type:"Integer"},{name:"dh",description:"

destination image height

\n",type:"Integer"},{name:"blendMode",description:"

the blend mode

\n",type:"Integer"}],example:['\n
\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage("assets/rockies.jpg");\n img1 = loadImage("assets/bricks_third.jpg");\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n}\n
\n
\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage("assets/rockies.jpg");\n img1 = loadImage("assets/bricks_third.jpg");\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n}\n
\n
\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage("assets/rockies.jpg");\n img1 = loadImage("assets/bricks_third.jpg");\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n}\n
'],alt:"image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent",class:"p5",module:"Image",submodule:"Pixels"},{file:"src/image/pixels.js",line:165,description:"

Copies a region of the canvas to another region of the canvas\nand copies a region of pixels from an image used as the srcImg parameter\ninto the canvas srcImage is specified this is used as the source. If\nthe source and destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.

\n",itemtype:"method",name:"copy",params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image|undefined"},{name:"sx",description:"

X coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sy",description:"

Y coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sw",description:"

source image width

\n",type:"Integer"},{name:"sh",description:"

source image height

\n",type:"Integer"},{name:"dx",description:"

X coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dy",description:"

Y coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dw",description:"

destination image width

\n",type:"Integer"},{name:"dh",description:"

destination image height

\n",type:"Integer"}],example:['\n
\nvar img;\n\nfunction preload() {\n img = loadImage("assets/rockies.jpg");\n}\n\nfunction setup() {\n background(img);\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n stroke(255);\n noFill();\n // Rectangle shows area being copied\n rect(7, 22, 10, 10);\n}\n
'],alt:"image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent",class:"p5",module:"Image",submodule:"Pixels"},{file:"src/image/pixels.js",line:212,description:"

Applies a filter to the canvas.\n

\n

The presets options are:\n

\n

THRESHOLD\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.\n

\n

GRAY\nConverts any colors in the image to grayscale equivalents. No parameter\nis used.\n

\n

OPAQUE\nSets the alpha channel to entirely opaque. No parameter is used.\n

\n

INVERT\nSets each pixel to its inverse value. No parameter is used.\n

\n

POSTERIZE\nLimits each channel of the image to the number of colors specified as the\nparameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.\n

\n

BLUR\nExecutes a Guassian blur with the level parameter specifying the extent\nof the blurring. If no parameter is used, the blur is equivalent to\nGuassian blur of radius 1. Larger values increase the blur.\n

\n

ERODE\nReduces the light areas. No parameter is used.\n

\n

DILATE\nIncreases the light areas. No parameter is used.

\n",itemtype:"method",name:"filter",params:[{name:"filterType",description:"

either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE or DILATE

\n",type:"Constant"},{name:"filterParam",description:"

an optional parameter unique\n to each filter, see above

\n",type:"Number"}],example:['\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(GRAY);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(INVERT);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(POSTERIZE,3);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(BLUR,3);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/bricks.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n\n
'],alt:"black and white image of a brick wall.\ngreyscale image of a brickwall\nimage of a brickwall\njade colored image of a brickwall\nred and pink image of a brickwall\nimage of a brickwall\nblurry image of a brickwall\nimage of a brickwall\nimage of a brickwall with less detail",class:"p5",module:"Image",submodule:"Pixels"},{file:"src/image/pixels.js",line:390,description:"

Returns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().\n

\nIf the pixel requested is outside of the image window, [0,0,0,255] is\nreturned. To get the numbers scaled according to the current color ranges\nand taking into account colorMode, use getColor instead of get.\n

\nGetting the color of a single pixel with get(x, y) is easy, but not as fast\nas grabbing the data directly from pixels[]. The equivalent statement to\nget(x, y) using pixels[] with pixel density d is\n\nvar off = (y width + x) d * 4;\n[pixels[off],\npixels[off+1],\npixels[off+2],\npixels[off+3]]\n

\nSee the reference for pixels[] for more information.

\n",itemtype:"method",name:"get",params:[{name:"x",description:"

x-coordinate of the pixel

\n",type:"Number",optional:!0},{name:"y",description:"

y-coordinate of the pixel

\n",type:"Number",optional:!0},{name:"w",description:"

width

\n",type:"Number",optional:!0},{name:"h",description:"

height

\n",type:"Number",optional:!0}],return:{description:"values of pixel at x,y in array format\n [R, G, B, A] or p5.Image",type:"Number[]|p5.Image"},example:['\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/rockies.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get();\n image(c, width/2, 0);\n}\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/rockies.jpg");\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get(50, 90);\n fill(c);\n noStroke();\n rect(25, 25, 50, 50);\n}\n\n
'],alt:"2 images of the rocky mountains, side-by-side\nImage of the rocky mountains with 50x50 green rect in center of canvas",class:"p5",module:"Image",submodule:"Pixels"},{file:"src/image/pixels.js",line:461,description:"

Loads the pixel data for the display window into the pixels[] array. This\nfunction must always be called before reading from or writing to pixels[].\nNote that only changes made with set() or direct manipulation of pixels[]\nwill occur.

\n",itemtype:"method",name:"loadPixels",example:['\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/rockies.jpg");\n}\n\nfunction setup() {\n image(img, 0, 0);\n var d = pixelDensity();\n var halfImage = 4 * (img.width * d) *\n (img.height/2 * d);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i+halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n
'],alt:"two images of the rocky mountains. one on top, one on bottom of canvas.",class:"p5",module:"Image",submodule:"Pixels"},{file:"src/image/pixels.js",line:498,description:"

Changes the color of any pixel, or writes an image directly to the\ndisplay window.

\n

The x and y parameters specify the pixel to change and the c parameter\nspecifies the color value. This can be a p5.Color object, or [R, G, B, A]\npixel array. It can also be a single grayscale value.\nWhen setting an image, the x and y parameters define the coordinates for\nthe upper-left corner of the image, regardless of the current imageMode().\n

\n

\nAfter using set(), you must call updatePixels() for your changes to appear.\nThis should be called once all pixels have been set, and must be called before\ncalling .get() or drawing the image.\n

\n

Setting the color of a single pixel with set(x, y) is easy, but not as\nfast as putting the data directly into pixels[]. Setting the pixels[]\nvalues directly may be complicated when working with a retina display,\nbut will perform better when lots of pixels need to be set directly on\nevery loop.

\n

See the reference for pixels[] for more information.

",itemtype:"method",name:"set",params:[{name:"x",description:"

x-coordinate of the pixel

\n",type:"Number"},{name:"y",description:"

y-coordinate of the pixel

\n",type:"Number"},{name:"c",description:"

insert a grayscale value | a pixel array |\n a p5.Color object | a p5.Image to copy

\n",type:"Number|Array|Object"}],example:['\n
\n\nvar black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n\n
\n\n
\n\nfor (var i = 30; i < width-15; i++) {\n for (var j = 20; j < height-25; j++) {\n var c = color(204-j, 153-i, 0);\n set(i, j, c);\n }\n}\nupdatePixels();\n\n
\n\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/rockies.jpg");\n}\n\nfunction setup() {\n set(0, 0, img);\n updatePixels();\n line(0, 0, width, height);\n line(0, height, width, 0);\n}\n\n
'],alt:"4 black points in the shape of a square middle-right of canvas.\nsquare with orangey-brown gradient lightening at bottom right.\nimage of the rocky mountains. with lines like an 'x' through the center.",class:"p5",module:"Image",submodule:"Pixels"},{file:"src/image/pixels.js",line:572,description:"

Updates the display window with the data in the pixels[] array.\nUse in conjunction with loadPixels(). If you're only reading pixels from\nthe array, there's no need to call updatePixels() — updating is only\nnecessary to apply changes. updatePixels() should be called anytime the\npixels array is manipulated or set() is called, and only changes made with\nset() or direct changes to pixels[] will occur.

\n",itemtype:"method",name:"updatePixels",params:[{name:"x",description:"

x-coordinate of the upper-left corner of region\n to update

\n",type:"Number",optional:!0},{name:"y",description:"

y-coordinate of the upper-left corner of region\n to update

\n",type:"Number",optional:!0},{name:"w",description:"

width of region to update

\n",type:"Number",optional:!0},{name:"h",description:"

height of region to update

\n",type:"Number",optional:!0}],example:['\n
\n\nvar img;\nfunction preload() {\n img = loadImage("assets/rockies.jpg");\n}\n\nfunction setup() {\n image(img, 0, 0);\n var halfImage = 4 * (img.width * pixelDensity()) *\n (img.height * pixelDensity()/2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i+halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n
'],alt:"two images of the rocky mountains. one on top, one on bottom of canvas.",class:"p5",module:"Image",submodule:"Pixels"},{file:"src/io/files.js",line:19, +description:'

Loads a JSON file from a file or a URL, and returns an Object.\nNote that even if the JSON file contains an Array, an Object will be\nreturned with index numbers as keys.

\n

This method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. JSONP is supported via a polyfill and you\ncan pass in as the second argument an object with definitions of the json\ncallback following the syntax specified here.

\n',itemtype:"method",name:"loadJSON",params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"jsonpOptions",description:"

options object for jsonp related settings

\n",type:"Object",optional:!0},{name:"datatype",description:"

"json" or "jsonp"

\n",type:"String",optional:!0},{name:"callback",description:"

function to be executed after\n loadJSON() completes, data is passed\n in as first argument

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}],return:{description:"JSON data",type:"Object|Array"},example:["\n\n

Calling loadJSON() inside preload() guarantees to complete the\noperation before setup() and draw() are called.

\n\n
\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nvar earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n earthquakes = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width/2, height/2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
\n\n\n

Outside of preload(), you may supply a callback function to handle the\nobject:

\n
\nfunction setup() {\n noLoop();\n var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n loadJSON(url, drawEarthquake);\n}\n\nfunction draw() {\n background(200);\n}\n\nfunction drawEarthquake(earthquakes) {\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width/2, height/2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
"],alt:"50x50 ellipse that changes from black to white depending on the current humidity\n50x50 ellipse that changes from black to white depending on the current humidity",class:"p5",module:"IO",submodule:"Input"},{file:"src/io/files.js",line:145,description:"

Reads the contents of a file and creates a String array of its individual\nlines. If the name of the file is used as the parameter, as in the above\nexample, the file must be located in the sketch directory/folder.\n

\nAlternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.\n

\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed.

\n",itemtype:"method",name:"loadStrings",params:[{name:"filename",description:"

name of the file or url to load

\n",type:"String"},{name:"callback",description:"

function to be executed after loadStrings()\n completes, Array is passed in as first\n argument

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}],return:{description:"Array of Strings",type:"String[]"},example:["\n\n

Calling loadStrings() inside preload() guarantees to complete the\noperation before setup() and draw() are called.

\n\n
\nvar result;\nfunction preload() {\n result = loadStrings('assets/test.txt');\n}\n\nfunction setup() {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
\n\n

Outside of preload(), you may supply a callback function to handle the\nobject:

\n\n
\nfunction setup() {\n loadStrings('assets/test.txt', pickString);\n}\n\nfunction pickString(result) {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
"],alt:'randomly generated text from a file, for example "i smell like butter"\nrandomly generated text from a file, for example "i have three feet"',class:"p5",module:"IO",submodule:"Input"},{file:"src/io/files.js",line:237,description:"

Reads the contents of a file or URL and creates a p5.Table object with\nits values. If a file is specified, it must be located in the sketch's\n"data" folder. The filename parameter can also be a URL to a file found\nonline. By default, the file is assumed to be comma-separated (in CSV\nformat). Table only looks for a header row if the 'header' option is\nincluded.

\n\n

Possible options include:\n

    \n
  • csv - parse the table as comma-separated values
  • \n
  • tsv - parse the table as tab-separated values
  • \n
  • header - this table has a header (title) row
  • \n
\n

\n\n

When passing in multiple options, pass them in as separate parameters,\nseperated by commas. For example:\n

\n\n loadTable("my_csv_file.csv", "csv", "header")\n\n

\n\n

All files loaded and saved use UTF-8 encoding.

\n\n

This method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadTable() inside preload()\nguarantees to complete the operation before setup() and draw() are called.\n

Outside of preload(), you may supply a callback function to handle the\nobject:

\n

",itemtype:"method",name:"loadTable",params:[{name:"filename",description:"

name of the file or URL to load

\n",type:"String"},{name:"options",description:"

"header" "csv" "tsv"

\n",type:"String",optional:!0},{name:"callback",description:"

function to be executed after\n loadTable() completes. On success, the\n Table object is passed in as the\n first argument.

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}],return:{description:"Table object containing data",type:"Object"},example:['\n
\n\n// Given the following CSV file called "mammals.csv"\n// located in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n //the file can be remote\n //table = loadTable("http://p5js.org/reference/assets/mammals.csv",\n // "csv", "header");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + " total rows in table");\n print(table.getColumnCount() + " total columns in table");\n\n print(table.getColumn("name"));\n //["Goat", "Leopard", "Zebra"]\n\n //cycle through the table\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n}\n\n
'],alt:'randomly generated text from a file, for example "i smell like butter"\nrandomly generated text from a file, for example "i have three feet"',class:"p5",module:"IO",submodule:"Input"},{file:"src/io/files.js",line:558,description:"

Reads the contents of a file and creates an XML object with its values.\nIf the name of the file is used as the parameter, as in the above example,\nthe file must be located in the sketch directory/folder.

\n

Alternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.

\n

This method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadXML() inside preload()\nguarantees to complete the operation before setup() and draw() are called.

\n

Outside of preload(), you may supply a callback function to handle the\nobject.

\n",itemtype:"method",name:"loadXML",params:[{name:"filename",description:"

name of the file or URL to load

\n",type:"String"},{name:"callback",description:"

function to be executed after loadXML()\n completes, XML object is passed in as\n first argument

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}],return:{description:"XML object containing data",type:"Object"},example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var children = xml.getChildren("animal");\n\n for (var i = 0; i < children.length; i++) {\n var id = children[i].getNum("id");\n var coloring = children[i].getString("species");\n var name = children[i].getContent();\n print(id + ", " + coloring + ", " + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
'],alt:"no image displayed",class:"p5",module:"IO",submodule:"Input"},{file:"src/io/files.js",line:654,description:"

Method for executing an HTTP GET request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'GET').

\n",itemtype:"method",name:"httpGet",params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"datatype",description:"

"json", "jsonp", "xml", or "text"

\n",type:"String",optional:!0},{name:"data",description:"

param data passed sent with request

\n",type:"Object",optional:!0},{name:"callback",description:"

function to be executed after\n httpGet() completes, data is passed in\n as first argument

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}],example:["\n
\n // Examples use USGS Earthquake API:\n // https://earthquake.usgs.gov/fdsnws/event/1/#methods\n var earthquakes;\n function preload() {\n // Get the most recent earthquake in the database\n var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, \"jsonp\", false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n }\n\n function draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width/2, height/2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n }\n
"],class:"p5",module:"IO",submodule:"Input"},{file:"src/io/files.js",line:707,description:"

Method for executing an HTTP POST request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'POST').

\n",itemtype:"method",name:"httpPost",params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"datatype",description:"

"json", "jsonp", "xml", or "text".\n If omitted, httpPost() will guess.

\n",type:"String",optional:!0},{name:"data",description:"

param data passed sent with request

\n",type:"Object",optional:!0},{name:"callback",description:"

function to be executed after\n httpPost() completes, data is passed in\n as first argument

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}],example:["\n
\n\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nvar url = 'https://jsonplaceholder.typicode.com/posts';\nvar postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(url, 'json',\n postData,\n function (result) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n ellipse(mouseX, mouseY, 200, 200);\n text(result.body, mouseX, mouseY);\n });\n}\n\n
\n\n\n
\n\n var url = 'https://invalidURL'; // A bad URL that will cause errors\n var postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\n function setup() {\n createCanvas(800, 800);\n }\n\n function mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(url, 'json',\n postData,\n function (result) {\n // ... won't be called\n },\n function (error) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n text(error.toString(), mouseX, mouseY);\n });\n }\n\n\n
\n"],class:"p5",module:"IO",submodule:"Input"},{file:"src/io/files.js",line:794,description:"

Method for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.

\nFor more advanced use, you may also pass in the path as the first argument\nand a object as the second argument, the signature follows the one specified\nin the Fetch API specification.

\n",itemtype:"method",name:"httpDo",example:["\n
\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nvar earthquakes;\nvar eqFeatureIndex = 0;\n\nfunction preload() {\n var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n });\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n var feature = earthquakes.features[eqFeatureIndex];\n var mag = feature.properties.mag;\n var rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(\n width / 2 + random(-2, 2),\n height / 2 + random(-2, 2),\n rad, rad\n );\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n\n
"],class:"p5",module:"IO",submodule:"Input",overloads:[{line:794,params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"method",description:"

either "GET", "POST", or "PUT",\n defaults to "GET"

\n",type:"String",optional:!0},{name:"datatype",description:"

"json", "jsonp", "xml", or "text"

\n",type:"String",optional:!0},{name:"data",description:"

param data passed sent with request

\n",type:"Object",optional:!0},{name:"callback",description:"

function to be executed after\n httpGet() completes, data is passed in\n as first argument

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}]},{line:865,params:[{name:"path",description:"",type:"String"},{name:"options",description:'

Request object options as documented in the\n "fetch" API\nreference

\n',type:"Object"},{name:"callback",description:"",type:"Function",optional:!0},{name:"errorCallback",description:"",type:"Function",optional:!0}]}]},{file:"src/io/files.js",line:1077,description:"

Save an image, text, json, csv, wav, or html. Prompts download to\nthe client's computer. Note that it is not recommended to call save()\nwithin draw if it's looping, as the save() function will open a new save\ndialog every frame.

\n

The default behavior is to save the canvas as an image. You can\noptionally specify a filename.\nFor example:

\n
\nsave();\nsave('myCanvas.jpg'); // save a specific canvas with a filename\n
\n\n

Alternately, the first parameter can be a pointer to a canvas\np5.Element, an Array of Strings,\nan Array of JSON, a JSON object, a p5.Table, a p5.Image, or a\np5.SoundFile (requires p5.sound). The second parameter is a filename\n(including extension). The third parameter is for options specific\nto this type of object. This method will save a file that fits the\ngiven paramaters. For example:

\n\n
\n\nsave('myCanvas.jpg');           // Saves canvas as an image\n\nvar cnv = createCanvas(100, 100);\nsave(cnv, 'myCanvas.jpg');      // Saves canvas as an image\n\nvar gb = createGraphics(100, 100);\nsave(gb, 'myGraphics.jpg');      // Saves p5.Renderer object as an image\n\nsave(myTable, 'myTable.html');  // Saves table as html file\nsave(myTable, 'myTable.csv',);  // Comma Separated Values\nsave(myTable, 'myTable.tsv');   // Tab Separated Values\n\nsave(myJSON, 'my.json');        // Saves pretty JSON\nsave(myJSON, 'my.json', true);  // Optimizes JSON filesize\n\nsave(img, 'my.png');            // Saves pImage as a png image\n\nsave(arrayOfStrings, 'my.txt'); // Saves strings to a text file with line\n                                // breaks after each item in the array\n
",itemtype:"method",name:"save",params:[{name:"objectOrFilename",description:"

If filename is provided, will\n save canvas as an image with\n either png or jpg extension\n depending on the filename.\n If object is provided, will\n save depending on the object\n and filename (see examples\n above).

\n",type:"Object|String",optional:!0},{name:"filename",description:"

If an object is provided as the first\n parameter, then the second parameter\n indicates the filename,\n and should include an appropriate\n file extension (see examples above).

\n",type:"String",optional:!0},{name:"options",description:"

Additional options depend on\n filetype. For example, when saving JSON,\n true indicates that the\n output will be optimized for filesize,\n rather than readability.

\n",type:"Boolean|String",optional:!0}],class:"p5",module:"IO",submodule:"Output"},{file:"src/io/files.js",line:1194,description:"

Writes the contents of an Array or a JSON object to a .json file.\nThe file saving process and location of the saved file will\nvary between web browsers.

\n",itemtype:"method",name:"saveJSON",params:[{name:"json",description:"",type:"Array|Object"},{name:"filename",description:"",type:"String"},{name:"optimize",description:"

If true, removes line breaks\n and spaces from the output\n file to optimize filesize\n (but not readability).

\n",type:"Boolean",optional:!0}],example:['\n
\nvar json;\n\nfunction setup() {\n\n json = {}; // new JSON Object\n\n json.id = 0;\n json.species = \'Panthera leo\';\n json.name = \'Lion\';\n\n// To save, un-comment the line below, then click \'run\'\n// saveJSON(json, \'lion.json\');\n}\n\n// Saves the following to a file called "lion.json":\n// {\n// "id": 0,\n// "species": "Panthera leo",\n// "name": "Lion"\n// }\n
'],alt:"no image displayed",class:"p5",module:"IO",submodule:"Output"},{file:"src/io/files.js",line:1248,description:"

Writes an array of Strings to a text file, one line per String.\nThe file saving process and location of the saved file will\nvary between web browsers.

\n",itemtype:"method",name:"saveStrings",params:[{name:"list",description:"

string array to be written

\n",type:"Array"},{name:"filename",description:"

filename for output

\n",type:"String"}],example:["\n
\nvar words = 'apple bear cat dog';\n\n// .split() outputs an Array\nvar list = split(words, ' ');\n\n// To save the file, un-comment next line and click 'run'\n// saveStrings(list, 'nouns.txt');\n\n// Saves the following to a file called 'nouns.txt':\n//\n// apple\n// bear\n// cat\n// dog\n
"],alt:"no image displayed",class:"p5",module:"IO",submodule:"Output"},{file:"src/io/files.js",line:1306,description:"

Writes the contents of a Table object to a file. Defaults to a\ntext file with comma-separated-values ('csv') but can also\nuse tab separation ('tsv'), or generate an HTML table ('html').\nThe file saving process and location of the saved file will\nvary between web browsers.

\n",itemtype:"method",name:"saveTable",params:[{name:"Table",description:"

the Table object to save to a file

\n",type:"p5.Table"},{name:"filename",description:"

the filename to which the Table should be saved

\n",type:"String"},{name:"options",description:"

can be one of "tsv", "csv", or "html"

\n",type:"String",optional:!0}],example:["\n
\nvar table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n var newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n
"],alt:"no image displayed",class:"p5",module:"IO",submodule:"Output"},{file:"src/io/files.js",line:1433,description:"

Generate a blob of file data as a url to prepare for download.\nAccepts an array of data, a filename, and an extension (optional).\nThis is a private function because it does not do any formatting,\nbut it is used by saveStrings, saveJSON, saveTable etc.

\n",params:[{name:"dataToDownload",description:"",type:"Array"},{name:"filename",description:"",type:"String"},{name:"extension",description:"",type:"[String]"}],access:"private",tagname:"",class:"p5",module:"IO",submodule:"Output"},{file:"src/io/files.js",line:1456,description:"

Forces download. Accepts a url to filedata/blob, a filename,\nand an extension (optional).\nThis is a private function because it does not do any formatting,\nbut it is used by saveStrings, saveJSON, saveTable etc.

\n",params:[{name:"href",description:"

i.e. an href generated by createObjectURL

\n",type:"String"},{name:"filename",description:"",type:"[String]"},{name:"extension",description:"",type:"[String]"}],class:"p5",module:"IO",submodule:"Output"},{file:"src/io/files.js",line:1496,description:"

Returns a file extension, or another string\nif the provided parameter has no extension.

\n",params:[{name:"filename",description:"",type:"String"}],return:{description:"[fileName, fileExtension]",type:"String[]"},access:"private",tagname:"",class:"p5",module:"IO",submodule:"Output"},{file:"src/io/files.js",line:1528,description:"

Returns true if the browser is Safari, false if not.\nSafari makes trouble for downloading files.

\n",return:{description:"[description]",type:"Boolean"},access:"private",tagname:"",class:"p5",module:"IO",submodule:"Output"},{file:"src/io/files.js",line:1540,description:"

Helper function, a callback for download that deletes\nan invisible anchor element from the DOM once the file\nhas been automatically downloaded.

\n",access:"private",tagname:"",class:"p5",module:"IO",submodule:"Output"},{file:"src/io/p5.Table.js",line:12,description:'

Table Options

\n

Generic class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.

\n

CSV files are\n\ncomma separated values, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don't bother with the\nquotes.

\n

File names should end with .csv if they're comma separated.

\n

A rough "spec" for CSV can be found\nhere.

\n

To load files, use the loadTable method.

\n

To save tables to your computer, use the save method\n or the saveTable method.

\n\n

Possible options include:

\n
    \n
  • csv - parse the table as comma-separated values\n
  • tsv - parse the table as tab-separated values\n
  • header - this table has a header (title) row\n
',class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:46,itemtype:"property",name:"columns",type:"String[]",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:51,itemtype:"property",name:"rows",type:"p5.TableRow[]",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:58,description:"

Use addRow() to add a new row of data to a p5.Table object. By default,\nan empty row is created. Typically, you would store a reference to\nthe new row in a TableRow object (see newRow in the example above),\nand then set individual values using set().

\n

If a p5.TableRow object is included as a parameter, then that row is\nduplicated and added to the table.

\n",itemtype:"method",name:"addRow",params:[{name:"row",description:"

row to be added to the table

\n",type:"p5.TableRow",optional:!0}],example:['\n
\n \n // Given the CSV file "mammals.csv"\n // in the project\'s "assets" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n }\n\n function setup() {\n //add a row\n var newRow = table.addRow();\n newRow.setString("id", table.getRowCount() - 1);\n newRow.setString("species", "Canis Lupus");\n newRow.setString("name", "Wolf");\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:121,description:"

Removes a row from the table object.

\n",itemtype:"method",name:"removeRow",params:[{name:"id",description:"

ID number of the row to remove

\n",type:"Number"}],example:['\n
\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n}\n\nfunction setup() {\n //remove the first row\n var r = table.removeRow(0);\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:170,description:"

Returns a reference to the specified p5.TableRow. The reference\ncan then be used to get and set values of the selected row.

\n",itemtype:"method",name:"getRow",params:[{name:"rowID",description:"

ID number of the row to get

\n",type:"Number"}],return:{description:"p5.TableRow object",type:"p5.TableRow"}, +example:['\n
\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n}\n\nfunction setup() {\n var row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (var c = 0; c < table.getColumnCount(); c++)\n print(row.getString(c));\n}\n\n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:215,description:"

Gets all rows from the table. Returns an array of p5.TableRows.

\n",itemtype:"method",name:"getRows",return:{description:"Array of p5.TableRows",type:"p5.TableRow[]"},example:['\n
\n \n // Given the CSV file "mammals.csv"\n // in the project\'s "assets" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n }\n\n function setup() {\n var rows = table.getRows();\n\n //warning: rows is an array of objects\n for (var r = 0; r < rows.length; r++)\n rows[r].set("name", "Unicorn");\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:263,description:"

Finds the first row in the Table that contains the value\nprovided, and returns a reference to that row. Even if\nmultiple rows are possible matches, only the first matching\nrow is returned. The column to search may be specified by\neither its ID or title.

\n",itemtype:"method",name:"findRow",params:[{name:"value",description:"

The value to match

\n",type:"String"},{name:"column",description:"

ID number or title of the\n column to search

\n",type:"Number|String"}],return:{description:"",type:"p5.TableRow"},example:['\n
\n \n // Given the CSV file "mammals.csv"\n // in the project\'s "assets" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n }\n\n function setup() {\n //find the animal named zebra\n var row = table.findRow("Zebra", "name");\n //find the corresponding species\n print(row.getString("species"));\n }\n \n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:329,description:"

Finds the rows in the Table that contain the value\nprovided, and returns references to those rows. Returns an\nArray, so for must be used to iterate through all the rows,\nas shown in the example above. The column to search may be\nspecified by either its ID or title.

\n",itemtype:"method",name:"findRows",params:[{name:"value",description:"

The value to match

\n",type:"String"},{name:"column",description:"

ID number or title of the\n column to search

\n",type:"Number|String"}],return:{description:"An Array of TableRow objects",type:"p5.TableRow[]"},example:['\n
\n \n // Given the CSV file "mammals.csv"\n // in the project\'s "assets" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n }\n\n function setup() {\n //add another goat\n var newRow = table.addRow();\n newRow.setString("id", table.getRowCount() - 1);\n newRow.setString("species", "Scape Goat");\n newRow.setString("name", "Goat");\n\n //find the rows containing animals named Goat\n var rows = table.findRows("Goat", "name");\n print(rows.length + " Goats found");\n }\n \n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:399,description:"

Finds the first row in the Table that matches the regular\nexpression provided, and returns a reference to that row.\nEven if multiple rows are possible matches, only the first\nmatching row is returned. The column to search may be\nspecified by either its ID or title.

\n",itemtype:"method",name:"matchRow",params:[{name:"regexp",description:"

The regular expression to match

\n",type:"String"},{name:"column",description:"

The column ID (number) or\n title (string)

\n",type:"String|Number"}],return:{description:"TableRow object",type:"p5.TableRow"},class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:431,description:"

Finds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.

\n",itemtype:"method",name:"matchRows",params:[{name:"regexp",description:"

The regular expression to match

\n",type:"String"},{name:"column",description:"

The column ID (number) or\n title (string)

\n",type:"String|Number",optional:!0}],return:{description:"An Array of TableRow objects",type:"p5.TableRow[]"},example:["\nvar table;\n\nfunction setup() {\n\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n var rows = table.matchRows('R.*', 'type');\n for (var i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile"],class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:498,description:"

Retrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.

\n",itemtype:"method",name:"getColumn",params:[{name:"column",description:"

String or Number of the column to return

\n",type:"String|Number"}],return:{description:"Array of column values",type:"Array"},example:['\n
\n \n // Given the CSV file "mammals.csv"\n // in the project\'s "assets" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn("species"));\n //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"]\n }\n \n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:551,description:"

Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.

\n",itemtype:"method",name:"clearRows",example:['\n
\n \n // Given the CSV file "mammals.csv"\n // in the project\'s "assets" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + " total rows in table");\n print(table.getColumnCount() + " total columns in table");\n }\n \n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:593,description:"

Use addColumn() to add a new column to a Table object.\nTypically, you will want to specify a title, so the column\nmay be easily referenced later by name. (If no title is\nspecified, the new column's title will be null.)

\n",itemtype:"method",name:"addColumn",params:[{name:"title",description:"

title of the given column

\n",type:"String",optional:!0}],example:['\n
\n \n // Given the CSV file "mammals.csv"\n // in the project\'s "assets" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n }\n\n function setup() {\n table.addColumn("carnivore");\n table.set(0, "carnivore", "no");\n table.set(1, "carnivore", "yes");\n table.set(2, "carnivore", "no");\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:644,description:"

Returns the total number of columns in a Table.

\n",return:{description:"Number of columns in this table",type:"Number"},class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:653,description:"

Returns the total number of rows in a Table.

\n",itemtype:"method",name:"getRowCount",return:{description:"Number of rows in this table",type:"Number"},class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:664,description:"

Removes any of the specified characters (or "tokens").

\n\n

If no column is specified, then the values in all columns and\nrows are processed. A specific column may be referenced by\neither its ID or title.

",itemtype:"method",name:"removeTokens",params:[{name:"chars",description:"

String listing characters to be removed

\n",type:"String"},{name:"column",description:"

Column ID (number)\n or name (string)

\n",type:"String|Number",optional:!0}],class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:715,description:"

Trims leading and trailing whitespace, such as spaces and tabs,\nfrom String table values. If no column is specified, then the\nvalues in all columns and rows are trimmed. A specific column\nmay be referenced by either its ID or title.

\n",itemtype:"method",name:"trim",params:[{name:"column",description:"

Column ID (number)\n or name (string)

\n",type:"String|Number"}],class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:757,description:"

Use removeColumn() to remove an existing column from a Table\nobject. The column to be removed may be identified by either\nits title (a String) or its index value (an int).\nremoveColumn(0) would remove the first column, removeColumn(1)\nwould remove the second column, and so on.

\n",itemtype:"method",name:"removeColumn",params:[{name:"column",description:"

columnName (string) or ID (number)

\n",type:"String|Number"}],example:['\n
\n \n // Given the CSV file "mammals.csv"\n // in the project\'s "assets" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n }\n\n function setup() {\n table.removeColumn("id");\n print(table.getColumnCount());\n }\n \n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:826,description:"

Stores a value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.

\n",itemtype:"method",name:"set",params:[{name:"column",description:"

column ID (Number)\n or title (String)

\n",type:"String|Number"},{name:"value",description:"

value to assign

\n",type:"String|Number"}],example:['\n
\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n}\n\nfunction setup() {\n table.set(0, "species", "Canis Lupus");\n table.set(0, "name", "Wolf");\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:875,description:"

Stores a Float value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.

\n",itemtype:"method",name:"setNum",params:[{name:"row",description:"

row ID

\n",type:"Number"},{name:"column",description:"

column ID (Number)\n or title (String)

\n",type:"String|Number"},{name:"value",description:"

value to assign

\n",type:"Number"}],example:['\n
\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n}\n\nfunction setup() {\n table.setNum(1, "id", 1);\n\n print(table.getColumn(0));\n //["0", 1, "2"]\n}\n\n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:922,description:"

Stores a String value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.

\n",itemtype:"method",name:"setString",params:[{name:"row",description:"

row ID

\n",type:"Number"},{name:"column",description:"

column ID (Number)\n or title (String)

\n",type:"String|Number"},{name:"value",description:"

value to assign

\n",type:"String"}],class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:937,description:"

Retrieves a value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.

\n",itemtype:"method",name:"get",params:[{name:"row",description:"

row ID

\n",type:"Number"},{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Number"}],return:{description:"",type:"String|Number"},example:['\n
\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, "species"));\n //Capra hircus\n}\n\n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:984,description:"

Retrieves a Float value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.

\n",itemtype:"method",name:"getNum",params:[{name:"row",description:"

row ID

\n",type:"Number"},{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Number"}],return:{description:"",type:"Number"},example:['\n
\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n}\n\n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:1029,description:"

Retrieves a String value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.

\n",itemtype:"method",name:"getString",params:[{name:"row",description:"

row ID

\n",type:"Number"},{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Number"}],return:{description:"",type:"String"},example:['\n
\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n}\n\nfunction setup() {\n var tableArray = table.getArray();\n\n //output each row as array\n for (var i = 0; i < tableArray.length; i++)\n print(tableArray[i]);\n}\n\n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:1077,description:"

Retrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.

\n",itemtype:"method",name:"getObject",params:[{name:"headerColumn",description:"

Name of the column which should be used to\n title each row object (optional)

\n",type:"String"}],return:{description:"",type:"Object"},example:['\n
\n\n// Given the CSV file "mammals.csv"\n// in the project\'s "assets" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value "csv"\n //and has a header specifying the columns labels\n table = loadTable("assets/mammals.csv", "csv", "header");\n}\n\nfunction setup() {\n var tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n}\n\n
'],alt:"no image displayed",class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.Table.js",line:1141,description:"

Retrieves all table data and returns it as a multidimensional array.

\n",itemtype:"method",name:"getArray",return:{description:"",type:"Array"},class:"p5.Table",module:"IO",submodule:"Table"},{file:"src/io/p5.TableRow.js",line:43,description:"

Stores a value in the TableRow's specified column.\nThe column may be specified by either its ID or title.

\n",itemtype:"method",name:"set",params:[{name:"column",description:"

Column ID (Number)\n or Title (String)

\n",type:"String|Number"},{name:"value",description:"

The value to be stored

\n",type:"String|Number"}],class:"p5.TableRow",module:"IO",submodule:"Table"},{file:"src/io/p5.TableRow.js",line:79,description:"

Stores a Float value in the TableRow's specified column.\nThe column may be specified by either its ID or title.

\n",itemtype:"method",name:"setNum",params:[{name:"column",description:"

Column ID (Number)\n or Title (String)

\n",type:"String|Number"},{name:"value",description:"

The value to be stored\n as a Float

\n",type:"Number"}],class:"p5.TableRow",module:"IO",submodule:"Table"},{file:"src/io/p5.TableRow.js",line:95,description:"

Stores a String value in the TableRow's specified column.\nThe column may be specified by either its ID or title.

\n",itemtype:"method",name:"setString",params:[{name:"column",description:"

Column ID (Number)\n or Title (String)

\n",type:"String|Number"},{name:"value",description:"

The value to be stored\n as a String

\n",type:"String"}],class:"p5.TableRow",module:"IO",submodule:"Table"},{file:"src/io/p5.TableRow.js",line:110,description:"

Retrieves a value from the TableRow's specified column.\nThe column may be specified by either its ID or title.

\n",itemtype:"method",name:"get",params:[{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Number"}],return:{description:"",type:"String|Number"},class:"p5.TableRow",module:"IO",submodule:"Table"},{file:"src/io/p5.TableRow.js",line:127,description:"

Retrieves a Float value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.

\n",itemtype:"method",name:"getNum",params:[{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Number"}],return:{description:"Float Floating point number",type:"Number"},class:"p5.TableRow",module:"IO",submodule:"Table"},{file:"src/io/p5.TableRow.js",line:151,description:"

Retrieves an String value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.

\n",itemtype:"method",name:"getString",params:[{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Number"}],return:{description:"String",type:"String"},class:"p5.TableRow",module:"IO",submodule:"Table"},{file:"src/io/p5.XML.js",line:66,description:"

Gets a copy of the element's parent. Returns the parent as another\np5.XML object.

\n",itemtype:"method",name:"getParent",return:{description:"element parent",type:"p5.XML"},example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var children = xml.getChildren("animal");\n var parent = children[1].getParent();\n print(parent.getName());\n}\n\n// Sketch prints:\n// mammals\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:104,description:"

Gets the element's full name, which is returned as a String.

\n",itemtype:"method",name:"getName",return:{description:"the name of the node",type:"String"},example:['<animal\n
\n // The following short XML file called "mammals.xml" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id="0" species="Capra hircus">Goat</animal>\n // <animal id="1" species="Panthera pardus">Leopard</animal>\n // <animal id="2" species="Equus zebra">Zebra</animal>\n // </mammals>\n\n var xml;\n\n function preload() {\n xml = loadXML("assets/mammals.xml");\n }\n\n function setup() {\n print(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:139,description:"

Sets the element's name, which is specified as a String.

\n",itemtype:"method",name:"setName",params:[{name:"the",description:"

new name of the node

\n",type:"String"}],example:['<animal\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n print(xml.getName());\n xml.setName("fish");\n print(xml.getName());\n}\n\n// Sketch prints:\n// mammals\n// fish\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:177,description:"

Checks whether or not the element has any children, and returns the result\nas a boolean.

\n",itemtype:"method",name:"hasChildren",return:{description:"",type:"Boolean"},example:['<animal\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n print(xml.hasChildren());\n}\n\n// Sketch prints:\n// true\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:213,description:"

Get the names of all of the element's children, and returns the names as an\narray of Strings. This is the same as looping through and calling getName()\non each child element individually.

\n",itemtype:"method",name:"listChildren",return:{description:"names of the children of the element",type:"String[]"},example:['<animal\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n print(xml.listChildren());\n}\n\n// Sketch prints:\n// ["animal", "animal", "animal"]\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:250,description:"

Returns all of the element's children as an array of p5.XML objects. When\nthe name parameter is specified, then it will return all children that match\nthat name.

\n",itemtype:"method",name:"getChildren",params:[{name:"name",description:"

element name

\n",type:"String",optional:!0}],return:{description:"children of the element",type:"p5.XML[]"},example:['<animal\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var animals = xml.getChildren("animal");\n\n for (var i = 0; i < animals.length; i++) {\n print(animals[i].getContent());\n }\n}\n\n// Sketch prints:\n// "Goat"\n// "Leopard"\n// "Zebra"\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:299,description:"

Returns the first of the element's children that matches the name parameter\nor the child of the given index.It returns undefined if no matching\nchild is found.

\n",itemtype:"method",name:"getChild",params:[{name:"name",description:"

element name or index

\n",type:"String|Number"}],return:{description:"",type:"p5.XML"},example:['<animal\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var firstChild = xml.getChild("animal");\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// "Goat"\n
\n
\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var secondChild = xml.getChild(1);\n print(secondChild.getContent());\n}\n\n// Sketch prints:\n// "Leopard"\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:360,description:"

Appends a new child to the element. The child can be specified with\neither a String, which will be used as the new tag's name, or as a\nreference to an existing p5.XML object.\nA reference to the newly created child is returned as an p5.XML object.

\n",itemtype:"method",name:"addChild",params:[{name:"a",description:"

p5.XML Object which will be the child to be added

\n",type:"p5.XML"}],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:377,description:"

Removes the element specified by name or index.

\n",itemtype:"method",name:"removeChild",params:[{name:"name",description:"

element name or index

\n",type:"String|Number"}], +example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n xml.removeChild("animal");\n var children = xml.getChildren();\n for (var i=0; i
\n
\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n xml.removeChild(1);\n var children = xml.getChildren();\n for (var i=0; i
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:450,description:"

Counts the specified element's number of attributes, returned as an Number.

\n",itemtype:"method",name:"getAttributeCount",return:{description:"",type:"Number"},example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var firstChild = xml.getChild("animal");\n print(firstChild.getAttributeCount());\n}\n\n// Sketch prints:\n// 2\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:486,description:"

Gets all of the specified element's attributes, and returns them as an\narray of Strings.

\n",itemtype:"method",name:"listAttributes",return:{description:"an array of strings containing the names of attributes",type:"String[]"},example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var firstChild = xml.getChild("animal");\n print(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// ["id", "species"]\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:523,description:"

Checks whether or not an element has the specified attribute.

\n",itemtype:"method",name:"hasAttribute",params:[{name:"the",description:"

attribute to be checked

\n",type:"String"}],return:{description:"true if attribute found else false",type:"Boolean"},example:['\n
\n // The following short XML file called "mammals.xml" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id="0" species="Capra hircus">Goat</animal>\n // <animal id="1" species="Panthera pardus">Leopard</animal>\n // <animal id="2" species="Equus zebra">Zebra</animal>\n // </mammals>\n\n var xml;\n\n function preload() {\n xml = loadXML("assets/mammals.xml");\n }\n\n function setup() {\n var firstChild = xml.getChild("animal");\n print(firstChild.hasAttribute("species"));\n print(firstChild.hasAttribute("color"));\n }\n\n // Sketch prints:\n // true\n // false\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:562,description:"

Returns an attribute value of the element as an Number. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, the value 0 is returned.

\n",itemtype:"method",name:"getNum",params:[{name:"name",description:"

the non-null full name of the attribute

\n",type:"String"},{name:"defaultValue",description:"

the default value of the attribute

\n",type:"Number",optional:!0}],return:{description:"",type:"Number"},example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var firstChild = xml.getChild("animal");\n print(firstChild.getNum("id"));\n}\n\n// Sketch prints:\n// 0\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:603,description:"

Returns an attribute value of the element as an String. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, null is returned.

\n",itemtype:"method",name:"getString",params:[{name:"name",description:"

the non-null full name of the attribute

\n",type:"String"},{name:"defaultValue",description:"

the default value of the attribute

\n",type:"Number",optional:!0}],return:{description:"",type:"Number"},example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var firstChild = xml.getChild("animal");\n print(firstChild.getString("species"));\n}\n\n// Sketch prints:\n// "Capra hircus"\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:644,description:"

Sets the content of an element's attribute. The first parameter specifies\nthe attribute name, while the second specifies the new content.

\n",itemtype:"method",name:"setAttribute",params:[{name:"name",description:"

the full name of the attribute

\n",type:"String"},{name:"value",description:"

the value of the attribute

\n",type:"Number"}],example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var firstChild = xml.getChild("animal");\n print(firstChild.getString("species"));\n firstChild.setAttribute("species", "Jamides zebra");\n print(firstChild.getString("species"));\n}\n\n// Sketch prints:\n// "Capra hircus"\n// "Jamides zebra"\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:687,description:"

Returns the content of an element. If there is no such content,\ndefaultValue is returned if specified, otherwise null is returned.

\n",itemtype:"method",name:"getContent",params:[{name:"defaultValue",description:"

value returned if no content is found

\n",type:"String",optional:!0}],return:{description:"",type:"String"},example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var firstChild = xml.getChild("animal");\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// "Goat"\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:725,description:"

Sets the element's content.

\n",itemtype:"method",name:"setContent",params:[{name:"text",description:"

the new content

\n",type:"String"}],example:['\n
\n// The following short XML file called "mammals.xml" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id="0" species="Capra hircus">Goat</animal>\n// <animal id="1" species="Panthera pardus">Leopard</animal>\n// <animal id="2" species="Equus zebra">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML("assets/mammals.xml");\n}\n\nfunction setup() {\n var firstChild = xml.getChild("animal");\n print(firstChild.getContent());\n firstChild.setContent("Mountain Goat");\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// "Goat"\n// "Mountain Goat"\n
'],class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:767,description:"

This method is called while the parsing of XML (when loadXML() is\ncalled). The difference between this method and the setContent()\nmethod defined later is that this one is used to set the content\nwhen the node in question has more nodes under it and so on and\nnot directly text content. While in the other one is used when\nthe node in question directly has text inside it.

\n",class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/io/p5.XML.js",line:784,description:"

This method is called while the parsing of XML (when loadXML() is\ncalled). The XML node is passed and its attributes are stored in the\np5.XML's attribute Object.

\n",class:"p5.XML",module:"IO",submodule:"XML"},{file:"src/math/calculation.js",line:12,description:"

Calculates the absolute value (magnitude) of a number. Maps to Math.abs().\nThe absolute value of a number is always positive.

\n",itemtype:"method",name:"abs",params:[{name:"n",description:"

number to compute

\n",type:"Number"}],return:{description:"absolute value of given number",type:"Number"},example:['\n
\nfunction setup() {\n var x = -3;\n var y = abs(x);\n\n print(x); // -3\n print(y); // 3\n}\n
'],alt:"no image displayed",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:36,description:"

Calculates the closest int value that is greater than or equal to the\nvalue of the parameter. Maps to Math.ceil(). For example, ceil(9.03)\nreturns the value 10.

\n",itemtype:"method",name:"ceil",params:[{name:"n",description:"

number to round up

\n",type:"Number"}],return:{description:"rounded up number",type:"Number"},example:["\n
\nfunction draw() {\n background(200);\n // map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the ceiling of the mapped number.\n var bx = ceil(map(mouseX, 0, 100, 0,5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2,2), ax, ay - 5);\n text(nfc(bx,1,1), bx, by - 5);\n}\n
"],alt:"2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:76,description:"

Constrains a value between a minimum and maximum value.

\n",itemtype:"method",name:"constrain",params:[{name:"n",description:"

number to constrain

\n",type:"Number"},{name:"low",description:"

minimum limit

\n",type:"Number"},{name:"high",description:"

maximum limit

\n",type:"Number"}],return:{description:"constrained number",type:"Number"},example:["\n
\nfunction draw() {\n background(200);\n\n var leftWall = 25;\n var rightWall = 75;\n\n // xm is just the mouseX, while\n // xc is the mouseX, but constrained\n // between the leftWall and rightWall!\n var xm = mouseX;\n var xc = constrain(mouseX, leftWall, rightWall);\n\n // Draw the walls.\n stroke(150);\n line(leftWall, 0, leftWall, height);\n line(rightWall, 0, rightWall, height);\n\n // Draw xm and xc as circles.\n noStroke();\n fill(150);\n ellipse(xm, 33, 9,9); // Not Constrained\n fill(0);\n ellipse(xc, 66, 9,9); // Constrained\n}\n
"],alt:"2 vertical lines. 2 ellipses move with mouse X 1 does not move passed lines",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:120,description:"

Calculates the distance between two points.

\n",itemtype:"method",name:"dist",return:{description:"distance between the two points",type:"Number"},class:"p5",module:"Math",submodule:"Calculation",overloads:[{line:120,params:[{name:"x1",description:"

x-coordinate of the first point

\n",type:"Number"},{name:"y1",description:"

y-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"

x-coordinate of the second point

\n",type:"Number"},{name:"y2",description:"

y-coordinate of the second point

\n",type:"Number"}],return:{description:"distance between the two points",type:"Number"}},{line:130,params:[{name:"x1",description:"",type:"Number"},{name:"y1",description:"",type:"Number"},{name:"z1",description:"

z-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"",type:"Number"},{name:"y2",description:"",type:"Number"},{name:"z2",description:"

z-coordinate of the second point

\n",type:"Number"}],return:{description:"distance between the two points",type:"Number"}}]},{file:"src/math/calculation.js",line:184,description:"

Returns Euler's number e (2.71828...) raised to the power of the n\nparameter. Maps to Math.exp().

\n",itemtype:"method",name:"exp",params:[{name:"n",description:"

exponent to raise

\n",type:"Number"}],return:{description:"e^n",type:"Number"},example:['\n
\nfunction draw() {\n background(200);\n\n // Compute the exp() function with a value between 0 and 2\n var xValue = map(mouseX, 0, width, 0, 2);\n var yValue = exp(xValue);\n\n var y = map(yValue, 0, 8, height, 0);\n\n var legend = "exp (" + nfc(xValue, 3) +")\\n= " + nf(yValue, 1, 4);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse (mouseX,y, 7, 7);\n\n // Draw the exp(x) curve,\n // over the domain of x from 0 to 2\n noFill();\n stroke(0);\n beginShape();\n for (var x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, 2);\n yValue = exp(xValue);\n y = map(yValue, 0, 8, height, 0);\n vertex(x, y);\n }\n\n endShape();\n line(0, 0, 0, height);\n line(0, height-1, width, height-1);\n}\n
'],alt:"ellipse moves along a curve with mouse x. e^n displayed.",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:234,description:"

Calculates the closest int value that is less than or equal to the\nvalue of the parameter. Maps to Math.floor().

\n",itemtype:"method",name:"floor",params:[{name:"n",description:"

number to round down

\n",type:"Number"}],return:{description:"rounded down number",type:"Number"},example:["\n
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the floor of the mapped number.\n var bx = floor(map(mouseX, 0, 100, 0,5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2,2), ax, ay - 5);\n text(nfc(bx,1,1), bx, by - 5);\n}\n
"],alt:"2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:273,description:"

Calculates a number between two numbers at a specific increment. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first point, 0.1 is very near the first point, 0.5 is\nhalf-way in between, etc. The lerp function is convenient for creating\nmotion along a straight path and for drawing dotted lines.

\n",itemtype:"method",name:"lerp",params:[{name:"start",description:"

first value

\n",type:"Number"},{name:"stop",description:"

second value

\n",type:"Number"},{name:"amt",description:"

number between 0.0 and 1.0

\n",type:"Number"}],return:{description:"lerped value",type:"Number"},example:["\n
\nfunction setup() {\n background(200);\n var a = 20;\n var b = 80;\n var c = lerp(a,b, .2);\n var d = lerp(a,b, .5);\n var e = lerp(a,b, .8);\n\n var y = 50\n\n strokeWeight(5);\n stroke(0); // Draw the original points in black\n point(a, y);\n point(b, y);\n\n stroke(100); // Draw the lerp points in gray\n point(c, y);\n point(d, y);\n point(e, y);\n}\n
"],alt:"5 points horizontally staggered mid-canvas. mid 3 are grey, outer black",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:317,description:"

Calculates the natural logarithm (the base-e logarithm) of a number. This\nfunction expects the n parameter to be a value greater than 0.0. Maps to\nMath.log().

\n",itemtype:"method",name:"log",params:[{name:"n",description:"

number greater than 0

\n",type:"Number"}],return:{description:"natural logarithm of n",type:"Number"},example:['\n
\nfunction draw() {\n background(200);\n var maxX = 2.8;\n var maxY = 1.5;\n\n // Compute the natural log of a value between 0 and maxX\n var xValue = map(mouseX, 0, width, 0, maxX);\n if (xValue > 0) { // Cannot take the log of a negative number.\n var yValue = log(xValue);\n var y = map(yValue, -maxY, maxY, height, 0);\n\n // Display the calculation occurring.\n var legend = "log(" + nf(xValue, 1, 2) + ")\\n= " + nf(yValue, 1, 3);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text (legend, 5, 15);\n noStroke();\n ellipse (mouseX, y, 7, 7);\n }\n\n // Draw the log(x) curve,\n // over the domain of x from 0 to maxX\n noFill();\n stroke(0);\n beginShape();\n for(var x=0; x < width; x++) {\n xValue = map(x, 0, width, 0, maxX);\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n vertex(x, y);\n }\n endShape();\n line(0,0,0,height);\n line(0,height/2,width, height/2);\n}\n
'],alt:"ellipse moves along a curve with mouse x. natural logarithm of n displayed.",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:371,description:"

Calculates the magnitude (or length) of a vector. A vector is a direction\nin space commonly used in computer graphics and linear algebra. Because it\nhas no "start" position, the magnitude of a vector can be thought of as\nthe distance from the coordinate 0,0 to its x,y value. Therefore, mag() is\na shortcut for writing dist(0, 0, x, y).

\n",itemtype:"method",name:"mag",params:[{name:"a",description:"

first value

\n",type:"Number"},{name:"b",description:"

second value

\n",type:"Number"}],return:{description:"magnitude of vector from (0,0) to (a,b)",type:"Number"},example:['\n
\nfunction setup() {\n var x1 = 20;\n var x2 = 80;\n var y1 = 30;\n var y2 = 70;\n\n line(0, 0, x1, y1);\n print(mag(x1, y1)); // Prints "36.05551275463989"\n line(0, 0, x2, y1);\n print(mag(x2, y1)); // Prints "85.44003745317531"\n line(0, 0, x1, y2);\n print(mag(x1, y2)); // Prints "72.80109889280519"\n line(0, 0, x2, y2);\n print(mag(x2, y2)); // Prints "106.3014581273465"\n}\n
'],alt:"4 lines of different length radiate from top left of canvas.",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:409,description:"

Re-maps a number from one range to another.\n

\nIn the first example above, the number 25 is converted from a value in the\nrange of 0 to 100 into a value that ranges from the left edge of the\nwindow (0) to the right edge (width).

\n",itemtype:"method",name:"map",params:[{name:"value",description:"

the incoming value to be converted

\n",type:"Number"},{name:"start1",description:"

lower bound of the value's current range

\n",type:"Number"},{name:"stop1",description:"

upper bound of the value's current range

\n",type:"Number"},{name:"start2",description:"

lower bound of the value's target range

\n",type:"Number"},{name:"stop2",description:"

upper bound of the value's target range

\n",type:"Number"},{name:"withinBounds",description:"

constrain the value to the newly mapped range

\n",type:"Boolean",optional:!0}],return:{description:"remapped number",type:"Number"},example:["\n
\n var value = 25;\n var m = map(value, 0, 100, 0, width);\n ellipse(m, 50, 10, 10);\n
\n\n
\n function setup() {\n noStroke();\n }\n\n function draw() {\n background(204);\n var x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n //This ellipse is constrained to the 0-100 range\n //after setting withinBounds to true\n var x2 = map(mouseX, 0, width, 0, 100, true);\n ellipse(x2, 75, 25, 25);\n }\n
"],alt:"10 by 10 white ellipse with in mid left canvas\n2 25 by 25 white ellipses move with mouse x. Bottom has more range from X",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:464,description:"

Determines the largest value in a sequence of numbers, and then returns\nthat value. max() accepts any number of Number parameters, or an Array\nof any length.

\n",itemtype:"method",name:"max",params:[{name:"n0",description:"

Numbers to compare

\n",type:"Number|Array"}],return:{description:"maximum Number",type:"Number"},example:['\n
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n numArray = new Array(2,1,5,4,8,9);\n fill(0);\n noStroke();\n text("Array Elements", 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for(var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n maxX = 33;\n maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n}\n
'],alt:"Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 9",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:507,description:"

Determines the smallest value in a sequence of numbers, and then returns\nthat value. min() accepts any number of Number parameters, or an Array\nof any length.

\n",itemtype:"method",name:"min",params:[{name:"n0",description:"

Numbers to compare

\n",type:"Number|Array"}],return:{description:"minimum Number",type:"Number"},example:['\n
\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n numArray = new Array(2,1,5,4,8,9);\n fill(0);\n noStroke();\n text("Array Elements", 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for(var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n maxX = 33;\n maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n}\n
'],alt:"Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 1",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:550,description:"

Normalizes a number from another range into a value between 0 and 1.\nIdentical to map(value, low, high, 0, 1).\nNumbers outside of the range are not clamped to 0 and 1, because\nout-of-range values are often intentional and useful. (See the second\nexample above.)

\n",itemtype:"method",name:"norm",params:[{name:"value",description:"

incoming value to be normalized

\n",type:"Number"},{name:"start",description:"

lower bound of the value's current range

\n",type:"Number"},{name:"stop",description:"

upper bound of the value's current range

\n",type:"Number"}],return:{description:"normalized number",type:"Number"},example:['\n
\nfunction draw() {\n background(200);\n currentNum = mouseX;\n lowerBound = 0;\n upperBound = width; //100;\n normalized = norm(currentNum, lowerBound, upperBound);\n lineY = 70\n line(0, lineY, width, lineY);\n //Draw an ellipse mapped to the non-normalized value.\n noStroke();\n fill(50)\n var s = 7; // ellipse size\n ellipse(currentNum, lineY, s, s);\n\n // Draw the guide\n guideY = lineY + 15;\n text("0", 0, guideY);\n textAlign(RIGHT);\n text("100", width, guideY);\n\n // Draw the normalized value\n textAlign(LEFT);\n fill(0);\n textSize(32);\n normalY = 40;\n normalX = 20;\n text(normalized, normalX, normalY);\n}\n
'],alt:"ellipse moves with mouse. 0 shown left & 100 right and updating values center",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:602,description:"

Facilitates exponential expressions. The pow() function is an efficient\nway of multiplying numbers by themselves (or their reciprocals) in large\nquantities. For example, pow(3, 5) is equivalent to the expression\n33333 and pow(3, -5) is equivalent to 1 / 33333. Maps to\nMath.pow().

\n",itemtype:"method",name:"pow",params:[{name:"n",description:"

base of the exponential expression

\n",type:"Number"},{name:"e",description:"

power by which to raise the base

\n",type:"Number"}],return:{description:"n^e",type:"Number"},example:["\n
\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n eSize = 3; // Original Size\n eLoc = 10; // Original Location\n\n ellipse(eLoc, eLoc, eSize, eSize);\n\n ellipse(eLoc*2, eLoc*2, pow(eSize, 2), pow(eSize, 2));\n\n ellipse(eLoc*4, eLoc*4, pow(eSize, 3), pow(eSize, 3));\n\n ellipse(eLoc*8, eLoc*8, pow(eSize, 4), pow(eSize, 4));\n}\n
"],alt:"small to large ellipses radiating from top left of canvas",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:636,description:"

Calculates the integer closest to the n parameter. For example,\nround(133.8) returns the value 134. Maps to Math.round().

\n",itemtype:"method",name:"round",params:[{name:"n",description:"

number to round

\n",type:"Number"}],return:{description:"rounded number",type:"Number"},example:["\n
\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n // Round the mapped number.\n var bx = round(map(mouseX, 0, 100, 0,5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2,2), ax, ay - 5);\n text(nfc(bx,1,1), bx, by - 5);\n}\n
"],alt:"horizontal center line squared values displayed on top and regular on bottom.",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:675,description:"

Squares a number (multiplies a number by itself). The result is always a\npositive number, as multiplying two negative numbers always yields a\npositive result. For example, -1 * -1 = 1.

\n",itemtype:"method",name:"sq",params:[{name:"n",description:"

number to square

\n",type:"Number"}],return:{description:"squared number",type:"Number"},example:['\n
\nfunction draw() {\n background(200);\n eSize = 7;\n x1 = map(mouseX, 0, width, 0, 10);\n y1 = 80;\n x2 = sq(x1);\n y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100)\n line(0, height/2, width, height/2);\n\n // Draw text.\n var spacing = 15;\n noStroke();\n fill(0);\n text("x = " + x1, 0, y1 + spacing);\n text("sq(x) = " + x2, 0, y2 + spacing);\n}\n
'],alt:"horizontal center line squared values displayed on top and regular on bottom.",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/calculation.js",line:720,description:"

Calculates the square root of a number. The square root of a number is\nalways positive, even though there may be a valid negative root. The\nsquare root s of number a is such that s*s = a. It is the opposite of\nsquaring. Maps to Math.sqrt().

\n",itemtype:"method",name:"sqrt",params:[{name:"n",description:"

non-negative number to square root

\n",type:"Number"}],return:{description:"square root of number",type:"Number"},example:['\n
\nfunction draw() {\n background(200);\n eSize = 7;\n x1 = mouseX;\n y1 = 80;\n x2 = sqrt(x1);\n y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100)\n line(0, height/2, width, height/2);\n\n // Draw text.\n noStroke();\n fill(0);\n var spacing = 15;\n text("x = " + x1, 0, y1 + spacing);\n text("sqrt(x) = " + x2, 0, y2 + spacing);\n}\n
'],alt:"horizontal center line squareroot values displayed on top and regular on bottom.",class:"p5",module:"Math",submodule:"Calculation"},{file:"src/math/math.js",line:13,description:"

Creates a new p5.Vector (the datatype for storing vectors). This provides a\ntwo or three dimensional vector, specifically a Euclidean (also known as\ngeometric) vector. A vector is an entity that has both magnitude and\ndirection.

\n",itemtype:"method",name:"createVector",params:[{name:"x",description:"

x component of the vector

\n",type:"Number",optional:!0},{name:"y",description:"

y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

z component of the vector

\n",type:"Number",optional:!0}],return:{description:"",type:"p5.Vector"},class:"p5",module:"Math",submodule:"Math"},{file:"src/math/noise.js",line:41, +description:"

Returns the Perlin noise value at specified coordinates. Perlin noise is\na random sequence generator producing a more natural ordered, harmonic\nsuccession of numbers compared to the standard random() function.\nIt was invented by Ken Perlin in the 1980s and been used since in\ngraphical applications to produce procedural textures, natural motion,\nshapes, terrains etc.

The main difference to the\nrandom() function is that Perlin noise is defined in an infinite\nn-dimensional space where each pair of coordinates corresponds to a\nfixed semi-random value (fixed only for the lifespan of the program; see\nthe noiseSeed() function). p5.js can compute 1D, 2D and 3D noise,\ndepending on the number of coordinates given. The resulting value will\nalways be between 0.0 and 1.0. The noise value can be animated by moving\nthrough the noise space as demonstrated in the example above. The 2nd\nand 3rd dimension can also be interpreted as time.

The actual\nnoise is structured similar to an audio signal, in respect to the\nfunction's use of frequencies. Similar to the concept of harmonics in\nphysics, perlin noise is computed over several octaves which are added\ntogether for the final result.

Another way to adjust the\ncharacter of the resulting sequence is the scale of the input\ncoordinates. As the function works within an infinite space the value of\nthe coordinates doesn't matter as such, only the distance between\nsuccessive coordinates does (eg. when using noise() within a\nloop). As a general rule the smaller the difference between coordinates,\nthe smoother the resulting noise sequence will be. Steps of 0.005-0.03\nwork best for most applications, but this will differ depending on use.

\n",itemtype:"method",name:"noise",params:[{name:"x",description:"

x-coordinate in noise space

\n",type:"Number"},{name:"y",description:"

y-coordinate in noise space

\n",type:"Number",optional:!0},{name:"z",description:"

z-coordinate in noise space

\n",type:"Number",optional:!0}],return:{description:"Perlin noise value (between 0 and 1) at specified\n coordinates",type:"Number"},example:["\n
\nvar xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + .01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\n
\n
\nvar noiseScale=0.02;\n\nfunction draw() {\n background(0);\n for (var x=0; x < width; x++) {\n var noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);\n stroke(noiseVal*255);\n line(x, mouseY+noiseVal*80, x, height);\n }\n}\n\n
"],alt:"vertical line moves left to right with updating noise values.\nhorizontal wave pattern effected by mouse x-position & updating noise values.",class:"p5",module:"Math",submodule:"Noise"},{file:"src/math/noise.js",line:171,description:"

Adjusts the character and level of detail produced by the Perlin noise\n function. Similar to harmonics in physics, noise is computed over\n several octaves. Lower octaves contribute more to the output signal and\n as such define the overall intensity of the noise, whereas higher octaves\n create finer grained details in the noise sequence.\n

\n By default, noise is computed over 4 octaves with each octave contributing\n exactly half than its predecessor, starting at 50% strength for the 1st\n octave. This falloff amount can be changed by adding an additional function\n parameter. Eg. a falloff factor of 0.75 means each octave will now have\n 75% impact (25% less) of the previous lower octave. Any value between\n 0.0 and 1.0 is valid, however note that values greater than 0.5 might\n result in greater than 1.0 values returned by noise().\n

\n By changing these parameters, the signal created by the noise()\n function can be adapted to fit very specific needs and characteristics.

\n",itemtype:"method",name:"noiseDetail",params:[{name:"lod",description:"

number of octaves to be used by the noise

\n",type:"Number"},{name:"falloff",description:"

falloff factor for each octave

\n",type:"Number"}],example:["\n
\n \nvar noiseVal;\n var noiseScale=0.02;\nfunction setup() {\n createCanvas(100,100);\n }\nfunction draw() {\n background(0);\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width/2; x++) {\n noiseDetail(2,0.2);\n noiseVal = noise((mouseX+x) * noiseScale,\n (mouseY+y) * noiseScale);\n stroke(noiseVal*255);\n point(x,y);\n noiseDetail(8,0.65);\n noiseVal = noise((mouseX + x + width/2) * noiseScale,\n (mouseY + y) * noiseScale);\n stroke(noiseVal*255);\n point(x + width/2, y);\n }\n }\n }\n \n
"],alt:"2 vertical grey smokey patterns affected my mouse x-position and noise.",class:"p5",module:"Math",submodule:"Noise"},{file:"src/math/noise.js",line:233,description:"

Sets the seed value for noise(). By default, noise()\nproduces different results each time the program is run. Set the\nvalue parameter to a constant to return the same pseudo-random\nnumbers each time the software is run.

\n",itemtype:"method",name:"noiseSeed",params:[{name:"seed",description:"

the seed value

\n",type:"Number"}],example:["\n
\nvar xoff = 0.0;\n\nfunction setup() {\n noiseSeed(99);\n stroke(0, 10);\n}\n\nfunction draw() {\n xoff = xoff + .01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\n
"],alt:"vertical grey lines drawing in pattern affected by noise.",class:"p5",module:"Math",submodule:"Noise"},{file:"src/math/p5.Vector.js",line:69,description:"

The x component of the vector

\n",itemtype:"property",name:"x",type:"Number",class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:74,description:"

The y component of the vector

\n",itemtype:"property",name:"y",type:"Number",class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:79,description:"

The z component of the vector

\n",itemtype:"property",name:"z",type:"Number",class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:87,description:"

Returns a string representation of a vector v by calling String(v)\nor v.toString(). This method is useful for logging vectors in the\nconsole.

\n",itemtype:"method",name:"toString",example:['\n
\nfunction setup() {\n var v = createVector(20,30);\n print(String(v)); // prints "p5.Vector Object : [20, 30, 0]"\n}\n
\n'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:105,description:"

Sets the x, y, and z component of the vector using two or three separate\nvariables, the data from a p5.Vector, or the values from a float array.

\n",itemtype:"method",name:"set",params:[{name:"x",description:"

the x component of the vector or a\n p5.Vector or an Array

\n",type:"Number|p5.Vector|Array",optional:!0},{name:"y",description:"

the y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

the z component of the vector

\n",type:"Number",optional:!0}],chainable:1,example:['\n
\n\nfunction setup() {\n var v = createVector(1, 2, 3);\n v.set(4,5,6); // Sets vector to [4, 5, 6]\n\n var v1 = createVector(0, 0, 0);\n var arr = [1, 2, 3];\n v1.set(arr); // Sets vector to [1, 2, 3]\n}\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:147,description:"

Gets a copy of the vector, returns a p5.Vector object.

\n",itemtype:"method",name:"copy",return:{description:"the copy of the p5.Vector object",type:"p5.Vector"},example:['\n
\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = v1.copy();\nprint(v1.x == v2.x && v1.y == v2.y && v1.z == v2.z);\n// Prints "true"\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:170,description:"

Adds x, y, and z components to a vector, adds one vector to another, or\nadds two independent vectors together. The version of the method that adds\ntwo vectors together is a static method and returns a p5.Vector, the others\nacts directly on the vector. See the examples for more context.

\n",itemtype:"method",name:"add",chainable:1,example:['\n
\n\nvar v = createVector(1, 2, 3);\nv.add(4,5,6);\n// v\'s components are set to [5, 7, 9]\n\n
\n
\n\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nvar v3 = p5.Vector.add(v1, v2);\n// v3 has components [3, 5, 7]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math",overloads:[{line:170,params:[{name:"x",description:"

the x component of the vector to be\n added or a p5.Vector or an Array

\n",type:"Number|p5.Vector|Array"},{name:"y",description:"

the y component of the vector to be\n added

\n",type:"Number",optional:!0},{name:"z",description:"

the z component of the vector to be\n added

\n",type:"Number",optional:!0}],chainable:1},{line:907,params:[{name:"v1",description:"

a p5.Vector to add

\n",type:"p5.Vector"},{name:"v2",description:"

a p5.Vector to add

\n",type:"p5.Vector"},{name:"target",description:"

the vector to receive the result

\n",type:"p5.Vector"}],static:1},{line:914,params:[{name:"v1",description:"",type:"p5.Vector"},{name:"v2",description:"",type:"p5.Vector"}],static:1,return:{description:"the resulting p5.Vector",type:"p5.Vector"}}]},{file:"src/math/p5.Vector.js",line:222,description:"

Subtracts x, y, and z components from a vector, subtracts one vector from\nanother, or subtracts two independent vectors. The version of the method\nthat subtracts two vectors is a static method and returns a p5.Vector, the\nother acts directly on the vector. See the examples for more context.

\n",itemtype:"method",name:"sub",chainable:1,example:['\n
\n\nvar v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v\'s components are set to [3, 4, 5]\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(2, 3, 4);\nvar v2 = createVector(1, 2, 3);\n\nvar v3 = p5.Vector.sub(v1, v2);\n// v3 has components [1, 1, 1]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math",overloads:[{line:222,params:[{name:"x",description:"

the x component of the vector or a\n p5.Vector or an Array

\n",type:"Number|p5.Vector|Array"},{name:"y",description:"

the y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

the z component of the vector

\n",type:"Number",optional:!0}],chainable:1},{line:937,params:[{name:"v1",description:"

a p5.Vector to subtract from

\n",type:"p5.Vector"},{name:"v2",description:"

a p5.Vector to subtract

\n",type:"p5.Vector"},{name:"target",description:"

if undefined a new vector will be created

\n",type:"p5.Vector"}],static:1},{line:944,params:[{name:"v1",description:"",type:"p5.Vector"},{name:"v2",description:"",type:"p5.Vector"}],static:1,return:{description:"the resulting p5.Vector",type:"p5.Vector"}}]},{file:"src/math/p5.Vector.js",line:273,description:"

Multiply the vector by a scalar. The static version of this method\ncreates a new p5.Vector while the non static version acts on the vector\ndirectly. See the examples for more context.

\n",itemtype:"method",name:"mult",chainable:1,example:['\n
\n\nvar v = createVector(1, 2, 3);\nv.mult(2);\n// v\'s components are set to [2, 4, 6]\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = p5.Vector.mult(v1, 2);\n// v2 has components [2, 4, 6]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math",overloads:[{line:273,params:[{name:"n",description:"

the number to multiply with the vector

\n",type:"Number"}],chainable:1},{line:966,params:[{name:"v",description:"

the vector to multiply

\n",type:"p5.Vector"},{name:"n",description:"",type:"Number"},{name:"target",description:"

if undefined a new vector will be created

\n",type:"p5.Vector"}],static:1},{line:973,params:[{name:"v",description:"",type:"p5.Vector"},{name:"n",description:"",type:"Number"}],static:1,return:{description:"the resulting new p5.Vector",type:"p5.Vector"}}]},{file:"src/math/p5.Vector.js",line:306,description:"

Divide the vector by a scalar. The static version of this method creates a\nnew p5.Vector while the non static version acts on the vector directly.\nSee the examples for more context.

\n",itemtype:"method",name:"div",chainable:1,example:['\n
\n\nvar v = createVector(6, 4, 2);\nv.div(2); //v\'s components are set to [3, 2, 1]\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(6, 4, 2);\nvar v2 = p5.Vector.div(v, 2);\n// v2 has components [3, 2, 1]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math",overloads:[{line:306,params:[{name:"n",description:"

the number to divide the vector by

\n",type:"Number"}],chainable:1},{line:993,params:[{name:"v",description:"

the vector to divide

\n",type:"p5.Vector"},{name:"n",description:"",type:"Number"},{name:"target",description:"

if undefined a new vector will be created

\n",type:"p5.Vector"}],static:1},{line:1e3,params:[{name:"v",description:"",type:"p5.Vector"},{name:"n",description:"",type:"Number"}],static:1,return:{description:"the resulting new p5.Vector",type:"p5.Vector"}}]},{file:"src/math/p5.Vector.js",line:338,description:"

Calculates the magnitude (length) of the vector and returns the result as\na float (this is simply the equation sqrt(xx + yy + z*z).)

\n",itemtype:"method",name:"mag",return:{description:"magnitude of the vector",type:"Number"},example:['\n
\n\nvar v = createVector(20.0, 30.0, 40.0);\nvar m = v.mag();\nprint(m); // Prints "53.85164807134504"\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math",overloads:[{line:338,params:[],return:{description:"magnitude of the vector",type:"Number"}},{line:1091,params:[{name:"vecT",description:"

the vector to return the magnitude of

\n",type:"p5.Vector"}],static:1,return:{description:"the magnitude of vecT",type:"Number"}}]},{file:"src/math/p5.Vector.js",line:357,description:"

Calculates the squared magnitude of the vector and returns the result\nas a float (this is simply the equation (xx + yy + z*z).)\nFaster if the real length is not required in the\ncase of comparing vectors, etc.

\n",itemtype:"method",name:"magSq",return:{description:"squared magnitude of the vector",type:"Number"},example:['\n
\n\n// Static method\nvar v1 = createVector(6, 4, 2);\nprint(v1.magSq()); // Prints "56"\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:379,description:"

Calculates the dot product of two vectors. The version of the method\nthat computes the dot product of two independent vectors is a static\nmethod. See the examples for more context.

\n",itemtype:"method",name:"dot",return:{description:"the dot product",type:"Number"},example:['\n
\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nprint(v1.dot(v2)); // Prints "20"\n\n
\n\n
\n\n//Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(3, 2, 1);\nprint (p5.Vector.dot(v1, v2)); // Prints "10"\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math",overloads:[{line:379,params:[{name:"x",description:"

x component of the vector or a p5.Vector

\n",type:"Number|p5.Vector"},{name:"y",description:"

y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

z component of the vector

\n",type:"Number",optional:!0}],return:{description:"the dot product",type:"Number"}},{line:1021,params:[{name:"v1",description:"

the first p5.Vector

\n",type:"p5.Vector"},{name:"v2",description:"

the second p5.Vector

\n",type:"p5.Vector"}],static:1,return:{description:"the dot product",type:"Number"}}]},{file:"src/math/p5.Vector.js",line:419,description:"

Calculates and returns a vector composed of the cross product between\ntwo vectors. Both the static and non static methods return a new p5.Vector.\nSee the examples for more context.

\n",itemtype:"method",name:"cross",return:{description:"p5.Vector composed of cross product",type:"p5.Vector"},example:['\n
\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(1, 2, 3);\n\nv1.cross(v2); // v\'s components are [0, 0, 0]\n\n
\n\n
\n\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar crossProduct = p5.Vector.cross(v1, v2);\n// crossProduct has components [0, 0, 1]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math",overloads:[{line:419,params:[{name:"v",description:"

p5.Vector to be crossed

\n",type:"p5.Vector"}],return:{description:"p5.Vector composed of cross product",type:"p5.Vector"}},{line:1035,params:[{name:"v1",description:"

the first p5.Vector

\n",type:"p5.Vector"},{name:"v2",description:"

the second p5.Vector

\n",type:"p5.Vector"}],static:1,return:{description:"the cross product",type:"Number"}}]},{file:"src/math/p5.Vector.js",line:459,description:"

Calculates the Euclidean distance between two points (considering a\npoint as a vector object).

\n",itemtype:"method",name:"dist",return:{description:"the distance",type:"Number"},example:['\n
\n\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = v1.dist(v2); // distance is 1.4142...\n\n
\n
\n\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = p5.Vector.dist(v1,v2);\n// distance is 1.4142...\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math",overloads:[{line:459,params:[{name:"v",description:"

the x, y, and z coordinates of a p5.Vector

\n",type:"p5.Vector"}],return:{description:"the distance",type:"Number"}},{line:1050,params:[{name:"v1",description:"

the first p5.Vector

\n",type:"p5.Vector"},{name:"v2",description:"

the second p5.Vector

\n",type:"p5.Vector"}],static:1,return:{description:"the distance",type:"Number"}}]},{file:"src/math/p5.Vector.js",line:491,description:"

Normalize the vector to length 1 (make it a unit vector).

\n",itemtype:"method",name:"normalize",return:{description:"normalized p5.Vector",type:"p5.Vector"},example:['\n
\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.normalize();\n// v\'s components are set to\n// [0.4454354, 0.8908708, 0.089087084]\n\n
\n'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:512,description:"

Limit the magnitude of this vector to the value used for the max\nparameter.

\n",itemtype:"method",name:"limit",params:[{name:"max",description:"

the maximum magnitude for the vector

\n",type:"Number"}],chainable:1,example:['\n
\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.limit(5);\n// v\'s components are set to\n// [2.2271771, 4.4543543, 0.4454354]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:539,description:"

Set the magnitude of this vector to the value used for the len\nparameter.

\n",itemtype:"method",name:"setMag",params:[{name:"len",description:"

the new length for this vector

\n",type:"Number"}],chainable:1,example:['\n
\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.setMag(10);\n// v\'s components are set to [6.0, 8.0, 0.0]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:560,description:"

Calculate the angle of rotation for this vector (only 2D vectors)

\n",itemtype:"method",name:"heading",return:{description:"the angle of rotation",type:"Number"},example:['\n
\nfunction setup() {\n var v1 = createVector(30,50);\n print(v1.heading()); // 1.0303768265243125\n\n var v1 = createVector(40,50);\n print(v1.heading()); // 0.8960553845713439\n\n var v1 = createVector(30,70);\n print(v1.heading()); // 1.1659045405098132\n}\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:592,description:"

Rotate the vector by an angle (only 2D vectors), magnitude remains the\nsame

\n",itemtype:"method",name:"rotate",params:[{name:"angle",description:"

the angle of rotation

\n",type:"Number"}],chainable:1,example:['\n
\n\nvar v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v\'s components are set to [-20.0, 9.999999, 0.0]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:622,description:"

Calculates and returns the angle (in radians) between two vectors.

\n",itemtype:"method",name:"angleBetween",params:[{name:"the",description:"

x, y, and z components of a p5.Vector

\n",type:"p5.Vector"}],return:{description:"the angle between (in radians)",type:"Number"},example:['\n
\n\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar angle = v1.angleBetween(v2);\n// angle is PI/2\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:654,description:"

Linear interpolate the vector to another vector

\n",itemtype:"method",name:"lerp",chainable:1,class:"p5.Vector",module:"Math",submodule:"Math",overloads:[{line:654,params:[{name:"x",description:"

the x component

\n",type:"p5.Vector"},{name:"y",description:"

the y component

\n",type:"p5.Vector"},{name:"z",description:"

the z component

\n",type:"p5.Vector"},{name:"amt",description:"

the amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.9 is very near\n the new vector. 0.5 is halfway in between.

\n",type:"Number"}],chainable:1},{line:666,params:[{name:"v",description:"

the p5.Vector to lerp to

\n",type:"p5.Vector"},{name:"amt",description:"",type:"Number"}],chainable:1},{line:1065,params:[{name:"v1",description:"",type:"p5.Vector"},{name:"v2",description:"",type:"p5.Vector"},{name:"amt",description:"",type:"Number"},{name:"target",description:"

if undefined a new vector will be created

\n",type:"p5.Vector"}],static:1},{line:1073,params:[{name:"v1",description:"",type:"p5.Vector"},{name:"v2",description:"",type:"p5.Vector"},{name:"amt",description:"",type:"Number"}],static:1,return:{description:"the lerped value",type:"Number"}}]},{file:"src/math/p5.Vector.js",line:701,description:"

Return a representation of this vector as a float array. This is only\nfor temporary use. If used in any other fashion, the contents should be\ncopied by using the p5.Vector.copy() method to copy into your own\narray.

\n",itemtype:"method",name:"array",return:{description:"an Array with the 3 values",type:"Number[]"},example:['\n
\nfunction setup() {\n var v = createVector(20,30);\n print(v.array()); // Prints : Array [20, 30, 0]\n}\n
\n
\n\nvar v = createVector(10.0, 20.0, 30.0);\nvar f = v.array();\nprint(f[0]); // Prints "10.0"\nprint(f[1]); // Prints "20.0"\nprint(f[2]); // Prints "30.0"\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:730,description:"

Equality check against a p5.Vector

\n",itemtype:"method",name:"equals",params:[{name:"x",description:"

the x component of the vector or a\n p5.Vector or an Array

\n",type:"Number|p5.Vector|Array",optional:!0},{name:"y",description:"

the y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

the z component of the vector

\n",type:"Number",optional:!0}],return:{description:"whether the vectors are equals",type:"Boolean"},example:['\n
\nv1 = createVector(5,10,20);\nv2 = createVector(5,10,20);\nv3 = createVector(13,10,19);\n\nprint(v1.equals(v2.x,v2.y,v2.z)); // true\nprint(v1.equals(v3.x,v3.y,v3.z)); // false\n
\n
\n\nvar v1 = createVector(10.0, 20.0, 30.0);\nvar v2 = createVector(10.0, 20.0, 30.0);\nvar v3 = createVector(0.0, 0.0, 0.0);\nprint (v1.equals(v2)) // true\nprint (v1.equals(v3)) // false\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:780,description:"

Make a new 2D unit vector from an angle

\n",itemtype:"method",name:"fromAngle",static:1,params:[{name:"angle",description:"

the desired angle

\n",type:"Number"}],return:{description:"the new p5.Vector object",type:"p5.Vector"},example:['\n
\n\nfunction draw() {\n background (200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n angleMode(DEGREES);\n var myDegrees = map(mouseX, 0,width, 0,360);\n\n // Display that variable in an onscreen text.\n // (Note the nfc() function to truncate additional decimal places,\n // and the "\\xB0" character for the degree symbol.)\n var readout = "angle = " + nfc(myDegrees,1,1) + "\\xB0"\n noStroke();\n fill (0);\n text (readout, 5, 15);\n\n // Create a p5.Vector using the fromAngle function,\n // and extract its x and y components.\n var v = p5.Vector.fromAngle(radians(myDegrees));\n var vx = v.x;\n var vy = v.y;\n\n push();\n translate (width/2, height/2);\n noFill();\n stroke (150);\n line (0,0, 30,0);\n stroke (0);\n line (0,0, 30*vx, 30*vy);\n pop()\n}\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:837,description:"

Make a new 2D unit vector from a random angle

\n",itemtype:"method",name:"random2D",static:1,return:{description:"the new p5.Vector object",type:"p5.Vector"},example:['\n
\n\nvar v = p5.Vector.random2D();\n// May make v\'s attributes something like:\n// [0.61554617, -0.51195765, 0.0] or\n// [-0.4695841, -0.14366731, 0.0] or\n// [0.6091097, -0.22805278, 0.0]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:870,description:"

Make a new random 3D unit vector.

\n",itemtype:"method",name:"random3D",static:1,return:{description:"the new p5.Vector object",type:"p5.Vector"},example:['\n
\n\nvar v = p5.Vector.random3D();\n// May make v\'s attributes something like:\n// [0.61554617, -0.51195765, 0.599168] or\n// [-0.4695841, -0.14366731, -0.8711202] or\n// [0.6091097, -0.22805278, -0.7595902]\n\n
'],class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:963,description:"

Multiplies a vector by a scalar and returns a new vector.

\n",class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:990,description:"

Divides a vector by a scalar and returns a new vector.

\n",class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:1018,description:"

Calculates the dot product of two vectors.

\n",class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:1032,description:"

Calculates the cross product of two vectors.

\n",class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:1046,description:"

Calculates the Euclidean distance between two points (considering a\npoint as a vector object).

\n",class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/p5.Vector.js",line:1061,description:"

Linear interpolate a vector to another vector and return the result as a\nnew vector.

\n",class:"p5.Vector",module:"Math",submodule:"Math"},{file:"src/math/random.js",line:47,description:"

Sets the seed value for random().

\n

By default, random() produces different results each time the program\nis run. Set the seed parameter to a constant to return the same\npseudo-random numbers each time the software is run.

\n",itemtype:"method",name:"randomSeed",params:[{name:"seed",description:"

the seed value

\n",type:"Number"}],example:["\n
\n\nrandomSeed(99);\nfor (var i=0; i < 100; i++) {\n var r = random(0, 255);\n stroke(r);\n line(i, 0, i, 100);\n}\n\n
"],alt:"many vertical lines drawn in white, black or grey.",class:"p5",module:"Math",submodule:"Random"},{file:"src/math/random.js",line:78,description:"

Return a random floating-point number.

\n

Takes either 0, 1 or 2 arguments.

\n

If no argument is given, returns a random number from 0\nup to (but not including) 1.

\n

If one argument is given and it is a number, returns a random number from 0\nup to (but not including) the number.

\n

If one argument is given and it is an array, returns a random element from\nthat array.

\n

If two arguments are given, returns a random number from the\nfirst argument up to (but not including) the second argument.

\n",itemtype:"method",name:"random",return:{description:"the random number",type:"Number"},example:['\n
\n\nfor (var i = 0; i < 100; i++) {\n var r = random(50);\n stroke(r*5);\n line(50, i, 50+r, i);\n}\n\n
\n
\n\nfor (var i = 0; i < 100; i++) {\n var r = random(-50, 50);\n line(50,i,50+r,i);\n}\n\n
\n
\n\n// Get a random element from an array using the random(Array) syntax\nvar words = [ "apple", "bear", "cat", "dog" ];\nvar word = random(words); // select random word\ntext(word,10,50); // draw the word\n\n
'],alt:"100 horizontal lines from center canvas to right. size+fill change each time\n100 horizontal lines from center of canvas. height & side change each render\nword displayed at random. Either apple, bear, cat, or dog",class:"p5",module:"Math",submodule:"Random",overloads:[{line:78,params:[{name:"min",description:"

the lower bound (inclusive)

\n",type:"Number",optional:!0},{name:"max",description:"

the upper bound (exclusive)

\n",type:"Number",optional:!0}],return:{description:"the random number",type:"Number"}},{line:132,params:[{name:"choices",description:"

the array to choose from

\n",type:"Array"}],return:{description:"the random element from the array",type:"*"}}]},{file:"src/math/random.js",line:168,description:"

Returns a random number fitting a Gaussian, or\n normal, distribution. There is theoretically no minimum or maximum\n value that randomGaussian() might return. Rather, there is\n just a very low probability that values far from the mean will be\n returned; and a higher probability that numbers near the mean will\n be returned.\n

\n Takes either 0, 1 or 2 arguments.
\n If no args, returns a mean of 0 and standard deviation of 1.
\n If one arg, that arg is the mean (standard deviation is 1).
\n If two args, first is mean, second is standard deviation.

\n",itemtype:"method",name:"randomGaussian",params:[{name:"mean",description:"

the mean

\n",type:"Number"},{name:"sd",description:"

the standard deviation

\n",type:"Number"}],return:{ +description:"the random number",type:"Number"},example:["\n
\n for (var y = 0; y < 100; y++) {\n var x = randomGaussian(50,15);\n line(50, y, x, y);\n}\n \n
\n
\n \nvar distribution = new Array(360);\n\nfunction setup() {\n createCanvas(100, 100);\n for (var i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0,15));\n }\n}\n\nfunction draw() {\n background(204);\n translate(width/2, width/2);\n for (var i = 0; i < distribution.length; i++) {\n rotate(TWO_PI/distribution.length);\n stroke(0);\n var dist = abs(distribution[i]);\n line(0, 0, dist, 0);\n }\n}\n \n
"],alt:"100 horizontal lines from center of canvas. height & side change each render\n black lines radiate from center of canvas. size determined each render",class:"p5",module:"Math",submodule:"Random"},{file:"src/math/trigonometry.js",line:18,description:"

The inverse of cos(), returns the arc cosine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned in\nthe range 0 to PI (3.1415927).

\n",itemtype:"method",name:"acos",params:[{name:"value",description:"

the value whose arc cosine is to be returned

\n",type:"Number"}],return:{description:"the arc cosine of the given value",type:"Number"},example:['\n
\n\nvar a = PI;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: "3.1415927 : -1.0 : 3.1415927"\nprint(a + " : " + c + " : " + ac);\n\n
\n\n
\n\nvar a = PI + PI/4.0;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: "3.926991 : -0.70710665 : 2.3561943"\nprint(a + " : " + c + " : " + ac);\n\n
'],class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/math/trigonometry.js",line:56,description:"

The inverse of sin(), returns the arc sine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned\nin the range -PI/2 to PI/2.

\n",itemtype:"method",name:"asin",params:[{name:"value",description:"

the value whose arc sine is to be returned

\n",type:"Number"}],return:{description:"the arc sine of the given value",type:"Number"},example:['\n
\n\nvar a = PI + PI/3;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: "1.0471976 : 0.86602545 : 1.0471976"\nprint(a + " : " + s + " : " + as);\n\n
\n\n
\n\nvar a = PI + PI/3.0;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: "4.1887903 : -0.86602545 : -1.0471976"\nprint(a + " : " + s + " : " + as);\n\n
\n'],class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/math/trigonometry.js",line:95,description:"

The inverse of tan(), returns the arc tangent of a value. This function\nexpects the values in the range of -Infinity to Infinity (exclusive) and\nvalues are returned in the range -PI/2 to PI/2.

\n",itemtype:"method",name:"atan",params:[{name:"value",description:"

the value whose arc tangent is to be returned

\n",type:"Number"}],return:{description:"the arc tangent of the given value",type:"Number"},example:['\n
\n\nvar a = PI + PI/3;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: "1.0471976 : 1.7320509 : 1.0471976"\nprint(a + " : " + t + " : " + at);\n\n
\n\n
\n\nvar a = PI + PI/3.0;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: "4.1887903 : 1.7320513 : 1.0471977"\nprint(a + " : " + t + " : " + at);\n\n
\n'],class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/math/trigonometry.js",line:134,description:"

Calculates the angle (in radians) from a specified point to the coordinate\norigin as measured from the positive x-axis. Values are returned as a\nfloat in the range from PI to -PI. The atan2() function is most often used\nfor orienting geometry to the position of the cursor.\n

\nNote: The y-coordinate of the point is the first parameter, and the\nx-coordinate is the second parameter, due the the structure of calculating\nthe tangent.

\n",itemtype:"method",name:"atan2",params:[{name:"y",description:"

y-coordinate of the point

\n",type:"Number"},{name:"x",description:"

x-coordinate of the point

\n",type:"Number"}],return:{description:"the arc tangent of the given point",type:"Number"},example:["\n
\n\nfunction draw() {\n background(204);\n translate(width/2, height/2);\n var a = atan2(mouseY-height/2, mouseX-width/2);\n rotate(a);\n rect(-30, -5, 60, 10);\n}\n\n
"],alt:"60 by 10 rect at center of canvas rotates with mouse movements",class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/math/trigonometry.js",line:174,description:"

Calculates the cosine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.

\n",itemtype:"method",name:"cos",params:[{name:"angle",description:"

the angle

\n",type:"Number"}],return:{description:"the cosine of the angle",type:"Number"},example:["\n
\n\nvar a = 0.0;\nvar inc = TWO_PI/25.0;\nfor (var i = 0; i < 25; i++) {\n line(i*4, 50, i*4, 50+cos(a)*40.0);\n a = a + inc;\n}\n\n
"],alt:"vertical black lines form wave patterns, extend-down on left and right side",class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/math/trigonometry.js",line:206,description:"

Calculates the sine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.

\n",itemtype:"method",name:"sin",params:[{name:"angle",description:"

the angle

\n",type:"Number"}],return:{description:"the sine of the angle",type:"Number"},example:["\n
\n\nvar a = 0.0;\nvar inc = TWO_PI/25.0;\nfor (var i = 0; i < 25; i++) {\n line(i*4, 50, i*4, 50+sin(a)*40.0);\n a = a + inc;\n}\n\n
"],alt:"vertical black lines extend down and up from center to form wave pattern",class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/math/trigonometry.js",line:238,description:"

Calculates the tangent of an angle. This function takes into account\nthe current angleMode. Values are returned in the range -1 to 1.

\n",itemtype:"method",name:"tan",params:[{name:"angle",description:"

the angle

\n",type:"Number"}],return:{description:"the tangent of the angle",type:"Number"},example:["\n
\n\n var a = 0.0;\n var inc = TWO_PI/50.0;\n for (var i = 0; i < 100; i = i+2) {\n line(i, 50, i, 50+tan(a)*2.0);\n a = a + inc;\n }\n"],alt:"vertical black lines end down and up from center to form spike pattern",class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/math/trigonometry.js",line:270,description:"

Converts a radian measurement to its corresponding value in degrees.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964.

\n",itemtype:"method",name:"degrees",params:[{name:"radians",description:"

the radians value to convert to degrees

\n",type:"Number"}],return:{description:"the converted angle",type:"Number"},example:['\n
\n\nvar rad = PI/4;\nvar deg = degrees(rad);\nprint(rad + " radians is " + deg + " degrees");\n// Prints: 0.7853981633974483 radians is 45 degrees\n\n
\n'],class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/math/trigonometry.js",line:296,description:"

Converts a degree measurement to its corresponding value in radians.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964.

\n",itemtype:"method",name:"radians",params:[{name:"degrees",description:"

the degree value to convert to radians

\n",type:"Number"}],return:{description:"the converted angle",type:"Number"},example:['\n
\n\nvar deg = 45.0;\nvar rad = radians(deg);\nprint(deg + " degrees is " + rad + " radians");\n// Prints: 45 degrees is 0.7853981633974483 radians\n\n
'],class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/math/trigonometry.js",line:320,description:"

Sets the current mode of p5 to given mode. Default mode is RADIANS.

\n",itemtype:"method",name:"angleMode",params:[{name:"mode",description:"

either RADIANS or DEGREES

\n",type:"Constant"}],example:["\n
\n\nfunction draw(){\n background(204);\n angleMode(DEGREES); // Change the mode to DEGREES\n var a = atan2(mouseY-height/2, mouseX-width/2);\n translate(width/2, height/2);\n push();\n rotate(a);\n rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees\n pop();\n angleMode(RADIANS); // Change the mode to RADIANS\n rotate(a); // var a stays the same\n rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians\n}\n\n
"],alt:"40 by 10 rect in center rotates with mouse moves. 20 by 10 rect moves faster.",class:"p5",module:"Math",submodule:"Trigonometry"},{file:"src/typography/attributes.js",line:13,description:"

Sets the current alignment for drawing text. Accepts two\narguments: horizAlign (LEFT, CENTER, or RIGHT) and\nvertAlign (TOP, BOTTOM, CENTER, or BASELINE).

\n

The horizAlign parameter is in reference to the x value\nof the text() function, while the vertAlign parameter is\nin reference to the y value.

\n

So if you write textAlign(LEFT), you are aligning the left\nedge of your text to the x value you give in text(). If you\nwrite textAlign(RIGHT, TOP), you are aligning the right edge\nof your text to the x value and the top of edge of the text\nto the y value.

\n",itemtype:"method",name:"textAlign",params:[{name:"horizAlign",description:"

horizontal alignment, either LEFT,\n CENTER, or RIGHT

\n",type:"Constant"},{name:"vertAlign",description:"

vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE

\n",type:"Constant",optional:!0}],return:{description:"",type:"Number"},example:['\n
\n\ntextSize(16);\ntextAlign(RIGHT);\ntext("ABCD", 50, 30);\ntextAlign(CENTER);\ntext("EFGH", 50, 50);\ntextAlign(LEFT);\ntext("IJKL", 50, 70);\n\n
'],alt:"Letters ABCD displayed at top right, EFGH at center and IJKL at bottom left.",class:"p5",module:"Typography",submodule:"Attributes"},{file:"src/typography/attributes.js",line:55,description:"

Sets/gets the spacing, in pixels, between lines of text. This\nsetting will be used in all subsequent calls to the text() function.

\n",itemtype:"method",name:"textLeading",chainable:1,class:"p5",module:"Typography",submodule:"Attributes",overloads:[{line:55,params:[{name:"leading",description:"

the size in pixels for spacing between lines

\n",type:"Number"}],chainable:1},{line:63,params:[],return:{description:"",type:"Number"}}]},{file:"src/typography/attributes.js",line:92,description:"

Sets/gets the current font size. This size will be used in all subsequent\ncalls to the text() function. Font size is measured in pixels.

\n",itemtype:"method",name:"textSize",chainable:1,class:"p5",module:"Typography",submodule:"Attributes",overloads:[{line:92,params:[{name:"theSize",description:"

the size of the letters in units of pixels

\n",type:"Number"}],chainable:1},{line:100,params:[],return:{description:"",type:"Number"}}]},{file:"src/typography/attributes.js",line:123,description:"

Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD.\nNote: this may be is overridden by CSS styling. For non-system fonts\n(opentype, truetype, etc.) please load styled fonts instead.

\n",itemtype:"method",name:"textStyle",chainable:1,class:"p5",module:"Typography",submodule:"Attributes",overloads:[{line:123,params:[{name:"theStyle",description:"

styling for text, either NORMAL,\n ITALIC, or BOLD

\n",type:"Constant"}],chainable:1},{line:133,params:[],return:{description:"",type:"String"}}]},{file:"src/typography/attributes.js",line:158,description:"

Calculates and returns the width of any character or text string.

\n",itemtype:"method",name:"textWidth",params:[{name:"theText",description:"

the String of characters to measure

\n",type:"String"}],return:{description:"",type:"Number"},example:["\n
\n\ntextSize(28);\n\nvar aChar = 'P';\nvar cWidth = textWidth(aChar);\ntext(aChar, 0, 40);\nline(cWidth, 0, cWidth, 50);\n\nvar aString = \"p5.js\";\nvar sWidth = textWidth(aString);\ntext(aString, 0, 85);\nline(sWidth, 50, sWidth, 100);\n\n
"],alt:"Letter P and p5.js are displayed with vertical lines at end. P is wide",class:"p5",module:"Typography",submodule:"Attributes"},{file:"src/typography/attributes.js",line:192,description:"

Returns the ascent of the current font at its current size. The ascent\nrepresents the distance, in pixels, of the tallest character above\nthe baseline.

\n",itemtype:"method",name:"textAscent",return:{description:"",type:"Number"},example:['\n
\n\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar asc = textAscent() * scalar; // Calc ascent\nline(0, base - asc, width, base - asc);\ntext("dp", 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\nasc = textAscent() * scalar; // Recalc ascent\nline(40, base - asc, width, base - asc);\ntext("dp", 40, base); // Draw text on baseline\n\n
'],class:"p5",module:"Typography",submodule:"Attributes"},{file:"src/typography/attributes.js",line:220,description:"

Returns the descent of the current font at its current size. The descent\nrepresents the distance, in pixels, of the character with the longest\ndescender below the baseline.

\n",itemtype:"method",name:"textDescent",return:{description:"",type:"Number"},example:['\n
\n\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar desc = textDescent() * scalar; // Calc ascent\nline(0, base+desc, width, base+desc);\ntext("dp", 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\ndesc = textDescent() * scalar; // Recalc ascent\nline(40, base + desc, width, base + desc);\ntext("dp", 40, base); // Draw text on baseline\n\n
'],class:"p5",module:"Typography",submodule:"Attributes"},{file:"src/typography/attributes.js",line:248,description:"

Helper function to measure ascent and descent.

\n",class:"p5",module:"Typography",submodule:"Attributes"},{file:"src/typography/loading_displaying.js",line:16,description:"

Loads an opentype font file (.otf, .ttf) from a file or a URL,\nand returns a PFont Object. This method is asynchronous,\nmeaning it may not finish before the next line in your sketch\nis executed.\n

\nThe path to the font should be relative to the HTML file\nthat links in your sketch. Loading an from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.

\n",itemtype:"method",name:"loadFont",params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"callback",description:"

function to be executed after\n loadFont()\n completes

\n",type:"Function",optional:!0}],return:{description:"p5.Font object",type:"p5.Font"},example:["\n\n

Calling loadFont() inside preload() guarantees that the load\noperation will have completed before setup() and draw() are called.

\n\n
\nvar myFont;\nfunction preload() {\n myFont = loadFont('assets/AvenirNextLTPro-Demi.otf');\n}\n\nfunction setup() {\n fill('#ED225D');\n textFont(myFont);\n textSize(36);\n text('p5*js', 10, 50);\n}\n
\n\nOutside of preload(), you may supply a callback function to handle the\nobject:\n\n
\nfunction setup() {\n loadFont('assets/AvenirNextLTPro-Demi.otf', drawText);\n}\n\nfunction drawText(font) {\n fill('#ED225D');\n textFont(font, 36);\n text('p5*js', 10, 50);\n}\n\n
\n\n

You can also use the string name of the font to style other HTML\nelements.

\n\n
\nvar myFont;\n\nfunction preload() {\n myFont = loadFont('assets/Avenir.otf');\n}\n\nfunction setup() {\n var myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Avenir');\n}\n
"],alt:"p5*js in p5's theme dark pink\np5*js in p5's theme dark pink",class:"p5",module:"Typography",submodule:"Loading & Displaying"},{file:"src/typography/loading_displaying.js",line:135,description:"

Draws text to the screen. Displays the information specified in the first\nparameter on the screen in the position specified by the additional\nparameters. A default font will be used unless a font is set with the\ntextFont() function and a default size will be used unless a font is set\nwith textSize(). Change the color of the text with the fill() function.\nChange the outline of the text with the stroke() and strokeWeight()\nfunctions.\n

\nThe text displays in relation to the textAlign() function, which gives the\noption to draw to the left, right, and center of the coordinates.\n

\nThe x2 and y2 parameters define a rectangular area to display within and\nmay only be used with string data. When these parameters are specified,\nthey are interpreted based on the current rectMode() setting. Text that\ndoes not fit completely within the rectangle specified will not be drawn\nto the screen.

\n",itemtype:"method",name:"text",params:[{name:"str",description:"

the alphanumeric symbols to be displayed

\n",type:"String"},{name:"x",description:"

x-coordinate of text

\n",type:"Number"},{name:"y",description:"

y-coordinate of text

\n",type:"Number"},{name:"x2",description:"

by default, the width of the text box,\n see rectMode() for more info

\n",type:"Number",optional:!0},{name:"y2",description:"

by default, the height of the text box,\n see rectMode() for more info

\n",type:"Number",optional:!0}],return:{description:"this",type:"P5"},example:['\n
\n\ntextSize(32);\ntext("word", 10, 30);\nfill(0, 102, 153);\ntext("word", 10, 60);\nfill(0, 102, 153, 51);\ntext("word", 10, 90);\n\n
\n
\n\ns = "The quick brown fox jumped over the lazy dog.";\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n\n
'],alt:"'word' displayed 3 times going from black, blue to translucent blue\nThe quick brown fox jumped over the lazy dog.",class:"p5",module:"Typography",submodule:"Loading & Displaying"},{file:"src/typography/loading_displaying.js",line:191,description:"

Sets the current font that will be drawn with the text() function.

\n",itemtype:"method",name:"textFont",return:{description:"the current font",type:"Object"},class:"p5",module:"Typography",submodule:"Loading & Displaying",overloads:[{line:191,params:[],return:{description:"the current font",type:"Object"}},{line:197,params:[{name:"font",description:'

a font loaded via loadFont(), or a String\nrepresenting a web safe font (a font\nthat is generally available across all systems)

\n',type:"Object|String"},{name:"size",description:"

the font size to use

\n",type:"Number",optional:!0}],chainable:1}]},{file:"src/typography/p5.Font.js",line:33,description:"

Underlying opentype font implementation

\n",itemtype:"property",name:"font",class:"p5.Font",module:"Typography",submodule:"Font"},{file:"src/typography/p5.Font.js",line:47,description:"

Returns a tight bounding box for the given text string using this\nfont (currently only supports single lines)

\n",itemtype:"method",name:"textBounds",params:[{name:"line",description:"

a line of text

\n",type:"String"},{name:"x",description:"

x-position

\n",type:"Number"},{name:"y",description:"

y-position

\n",type:"Number"},{name:"fontSize",description:"

font size to use (optional)

\n",type:"Number"},{name:"options",description:"

opentype options (optional)

\n",type:"Object"}],return:{description:"a rectangle object with properties: x, y, w, h",type:"Object"},example:["\n
\n\nvar font;\nvar textString = 'Lorem ipsum dolor sit amet.';\nfunction preload() {\n font = loadFont('./assets/Regular.otf');\n};\nfunction setup() {\n background(210);\n\n var bbox = font.textBounds(textString, 10, 30, 12);\n fill(255);\n stroke(0);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n fill(0);\n noStroke();\n\n textFont(font);\n textSize(12);\n text(textString, 10, 30);\n};\n\n
"],alt:"words Lorem ipsum dol go off canvas and contained by white bounding box",class:"p5.Font",module:"Typography",submodule:"Font"},{file:"src/typography/p5.Font.js",line:148,description:"

Computes an array of points following the path for specified text

\n",itemtype:"method",name:"textToPoints",params:[{name:"txt",description:"

a line of text

\n",type:"String"},{name:"x",description:"

x-position

\n",type:"Number"},{name:"y",description:"

y-position

\n",type:"Number"},{name:"fontSize",description:"

font size to use (optional)

\n",type:"Number"},{name:"options",description:"

an (optional) object that can contain:

\n


sampleFactor - the ratio of path-length to number of samples\n(default=.25); higher values yield more points and are therefore\nmore precise

\n


simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear

\n",type:"Object"}],return:{description:"an array of points, each with x, y, alpha (the path angle)",type:"Array"},class:"p5.Font",module:"Typography",submodule:"Font"},{file:"src/typography/p5.Font.js",line:206,description:"

Returns the set of opentype glyphs for the supplied string.

\n

Note that there is not a strict one-to-one mapping between characters\nand glyphs, so the list of returned glyphs can be larger or smaller\n than the length of the given string.

\n",params:[{name:"str",description:"

the string to be converted

\n",type:"String"}],return:{description:"the opentype glyphs",type:"Array"},class:"p5.Font",module:"Typography",submodule:"Font"},{file:"src/typography/p5.Font.js",line:221,description:"

Returns an opentype path for the supplied string and position.

\n",params:[{name:"line",description:"

a line of text

\n",type:"String"},{name:"x",description:"

x-position

\n",type:"Number"},{name:"y",description:"

y-position

\n",type:"Number"},{name:"options",description:"

opentype options (optional)

\n",type:"Object"}],return:{description:"the opentype path",type:"Object"},class:"p5.Font",module:"Typography",submodule:"Font"},{file:"src/utilities/array_functions.js",line:12,description:"

Adds a value to the end of an array. Extends the length of\nthe array by one. Maps to Array.push().

\n",itemtype:"method",name:"append",params:[{name:"array",description:"

Array to append

\n",type:"Array"},{name:"value",description:"

to be added to the Array

\n",type:"Any"}],example:['\n
\nfunction setup() {\n\nvar myArray = new Array("Mango", "Apple", "Papaya")\nprint(myArray) // ["Mango", "Apple", "Papaya"]\n\nappend(myArray, "Peach")\nprint(myArray) // ["Mango", "Apple", "Papaya", "Peach"]\n\n}\n
'],class:"p5",module:"Data",submodule:"Array Functions"},{file:"src/utilities/array_functions.js",line:37,description:"

Copies an array (or part of an array) to another array. The src array is\ncopied to the dst array, beginning at the position specified by\nsrcPosition and into the position specified by dstPosition. The number of\nelements to copy is determined by length. Note that copying values\noverwrites existing values in the destination array. To append values\ninstead of overwriting them, use concat().\n

\nThe simplified version with only two arguments, arrayCopy(src, dst),\ncopies an entire array to another of the same size. It is equivalent to\narrayCopy(src, 0, dst, 0, src.length).\n

\nUsing this function is far more efficient for copying array data than\niterating through a for() loop and copying each element individually.

\n",itemtype:"method",name:"arrayCopy",class:"p5",module:"Data",submodule:"Array Functions",overloads:[{line:37,params:[{name:"src",description:"

the source Array

\n",type:"Array"},{name:"srcPosition",description:"

starting position in the source Array

\n",type:"Number"},{name:"dst",description:"

the destination Array

\n",type:"Array"},{name:"dstPosition",description:"

starting position in the destination Array

\n",type:"Number"},{name:"length",description:"

number of Array elements to be copied

\n",type:"Number"}]},{line:59,params:[{name:"src",description:"",type:"Array"},{name:"dst",description:"",type:"Array"},{name:"length",description:"",type:"Number",optional:!0}]}]},{file:"src/utilities/array_functions.js",line:124,description:"

Concatenates two arrays, maps to Array.concat(). Does not modify the\ninput arrays.

\n",itemtype:"method",name:"concat",params:[{name:"a",description:"

first Array to concatenate

\n",type:"Array"},{name:"b",description:"

second Array to concatenate

\n",type:"Array"}],return:{description:"concatenated array",type:"Array"},example:['\n
\nfunction setup() {\n var arr1 = new Array("A", "B", "C");\n var arr2 = new Array( 1 , 2 , 3 );\n\n print(arr1); // ["A","B","C"]\n print(arr2); // [1,2,3]\n\n var arr3 = concat(arr1, arr2);\n\n print(arr1); // ["A","B","C"]\n print(arr2); // [1,2,3]\n print(arr3); // ["A","B","C",1,2,3]\n\n}\n
'],class:"p5",module:"Data",submodule:"Array Functions"},{file:"src/utilities/array_functions.js",line:155,description:"

Reverses the order of an array, maps to Array.reverse()

\n",itemtype:"method",name:"reverse",params:[{name:"list",description:"

Array to reverse

\n",type:"Array"}],example:['\n
\nfunction setup() {\n var myArray = new Array("A", "B", "C");\n print(myArray); // ["A","B","C"]\n\n reverse(myArray);\n print(myArray); // ["C","B","A"]\n}\n
'],class:"p5",module:"Data",submodule:"Array Functions"},{file:"src/utilities/array_functions.js",line:175,description:"

Decreases an array by one element and returns the shortened array,\nmaps to Array.pop().

\n",itemtype:"method",name:"shorten",params:[{name:"list",description:"

Array to shorten

\n",type:"Array"}],return:{description:"shortened Array",type:"Array"},example:['\n
\nfunction setup() {\n var myArray = new Array("A", "B", "C");\n print(myArray); // ["A","B","C"]\n\n var newArray = shorten(myArray);\n print(myArray); // ["A","B","C"]\n print(newArray); // ["A","B"]\n}\n
'],class:"p5",module:"Data",submodule:"Array Functions"},{file:"src/utilities/array_functions.js",line:199,description:'

Randomizes the order of the elements of an array. Implements\n\nFisher-Yates Shuffle Algorithm.

\n',itemtype:"method",name:"shuffle",params:[{name:"array",description:"

Array to shuffle

\n",type:"Array"},{name:"bool",description:"

modify passed array

\n",type:"Boolean",optional:!0}],return:{description:"shuffled Array",type:"Array"},example:["\n
\nfunction setup() {\n var regularArr = ['ABC', 'def', createVector(), TAU, Math.E];\n print(regularArr);\n shuffle(regularArr, true); // force modifications to passed array\n print(regularArr);\n\n // By default shuffle() returns a shuffled cloned array:\n var newArr = shuffle(regularArr);\n print(regularArr);\n print(newArr);\n}\n
"],class:"p5",module:"Data",submodule:"Array Functions"},{file:"src/utilities/array_functions.js",line:239,description:"

Sorts an array of numbers from smallest to largest, or puts an array of\nwords in alphabetical order. The original array is not modified; a\nre-ordered array is returned. The count parameter states the number of\nelements to sort. For example, if there are 12 elements in an array and\ncount is set to 5, only the first 5 elements in the array will be sorted.

\n",itemtype:"method",name:"sort",params:[{name:"list",description:"

Array to sort

\n",type:"Array"},{name:"count",description:"

number of elements to sort, starting from 0

\n",type:"Number",optional:!0}],example:['\n
\nfunction setup() {\n var words = new Array("banana", "apple", "pear","lime");\n print(words); // ["banana", "apple", "pear", "lime"]\n var count = 4; // length of array\n\n words = sort(words, count);\n print(words); // ["apple", "banana", "lime", "pear"]\n}\n
\n
\nfunction setup() {\n var numbers = new Array(2,6,1,5,14,9,8,12);\n print(numbers); // [2,6,1,5,14,9,8,12]\n var count = 5; // Less than the length of the array\n\n numbers = sort(numbers, count);\n print(numbers); // [1,2,5,6,14,9,8,12]\n}\n
'],class:"p5",module:"Data",submodule:"Array Functions"},{file:"src/utilities/array_functions.js",line:283,description:"

Inserts a value or an array of values into an existing array. The first\nparameter specifies the initial array to be modified, and the second\nparameter defines the data to be inserted. The third parameter is an index\nvalue which specifies the array position from which to insert data.\n(Remember that array index numbering starts at zero, so the first position\nis 0, the second position is 1, and so on.)

\n",itemtype:"method",name:"splice",params:[{name:"list",description:"

Array to splice into

\n",type:"Array"},{name:"value",description:"

value to be spliced in

\n",type:"Any"},{name:"position",description:"

in the array from which to insert data

\n",type:"Number"}],example:['\n
\nfunction setup() {\n var myArray = new Array(0,1,2,3,4);\n var insArray = new Array("A","B","C");\n print(myArray); // [0,1,2,3,4]\n print(insArray); // ["A","B","C"]\n\n splice(myArray, insArray, 3);\n print(myArray); // [0,1,2,"A","B","C",3,4]\n}\n
'],class:"p5",module:"Data",submodule:"Array Functions"},{file:"src/utilities/array_functions.js",line:317,description:"

Extracts an array of elements from an existing array. The list parameter\ndefines the array from which the elements will be copied, and the start\nand count parameters specify which elements to extract. If no count is\ngiven, elements will be extracted from the start to the end of the array.\nWhen specifying the start, remember that the first array element is 0.\nThis function does not change the source array.

\n",itemtype:"method",name:"subset",params:[{name:"list",description:"

Array to extract from

\n",type:"Array"},{name:"start",description:"

position to begin

\n",type:"Number"},{name:"count",description:"

number of values to extract

\n",type:"Number",optional:!0}],return:{description:"Array of extracted elements",type:"Array"},example:['\n
\nfunction setup() {\n var myArray = new Array(1,2,3,4,5);\n print(myArray); // [1,2,3,4,5]\n\n var sub1 = subset(myArray, 0, 3);\n var sub2 = subset(myArray, 2, 2);\n print(sub1); // [1,2,3]\n print(sub2); // [3,4]\n}\n
'],class:"p5",module:"Data",submodule:"Array Functions"},{file:"src/utilities/conversion.js",line:12, +description:"

Converts a string to its floating point representation. The contents of a\nstring must resemble a number, or NaN (not a number) will be returned.\nFor example, float("1234.56") evaluates to 1234.56, but float("giraffe")\nwill return NaN.

\n

When an array of values is passed in, then an array of floats of the same\nlength is returned.

\n",itemtype:"method",name:"float",params:[{name:"str",description:"

float string to parse

\n",type:"String"}],return:{description:"floating point representation of string",type:"Number"},example:["\n
\nvar str = '20';\nvar diameter = float(str);\nellipse(width/2, height/2, diameter, diameter);\n
"],alt:"20 by 20 white ellipse in the center of the canvas",class:"p5",module:"Data",submodule:"Conversion"},{file:"src/utilities/conversion.js",line:42,description:"

Converts a boolean, string, or float to its integer representation.\nWhen an array of values is passed in, then an int array of the same length\nis returned.

\n",itemtype:"method",name:"int",return:{description:"integer representation of value",type:"Number"},class:"p5",module:"Data",submodule:"Conversion",overloads:[{line:42,params:[{name:"n",description:"

value to parse

\n",type:"String|Boolean|Number"}],return:{description:"integer representation of value",type:"Number"}},{line:51,params:[{name:"ns",description:"

values to parse

\n",type:"Array"}],return:{description:"integer representation of values",type:"Number[]"}}]},{file:"src/utilities/conversion.js",line:79,description:"

Converts a boolean, string or number to its string representation.\nWhen an array of values is passed in, then an array of strings of the same\nlength is returned.

\n",itemtype:"method",name:"str",params:[{name:"n",description:"

value to parse

\n",type:"String|Boolean|Number|Array"}],return:{description:"string representation of value",type:"String"},example:['\n
\nprint(str("10")); // "10"\nprint(str(10.31)); // "10.31"\nprint(str(-10)); // "-10"\nprint(str(true)); // "true"\nprint(str(false)); // "false"\nprint(str([true, "10.3", 9.8])); // [ "true", "10.3", "9.8" ]\n
'],class:"p5",module:"Data",submodule:"Conversion"},{file:"src/utilities/conversion.js",line:105,description:"

Converts a number or string to its boolean representation.\nFor a number, any non-zero value (positive or negative) evaluates to true,\nwhile zero evaluates to false. For a string, the value "true" evaluates to\ntrue, while any other value evaluates to false. When an array of number or\nstring values is passed in, then a array of booleans of the same length is\nreturned.

\n",itemtype:"method",name:"boolean",params:[{name:"n",description:"

value to parse

\n",type:"String|Boolean|Number|Array"}],return:{description:"boolean representation of value",type:"Boolean"},example:['\n
\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean("true")); // true\nprint(boolean("abcd")); // false\nprint(boolean([0, 12, "true"])); // [false, true, false]\n
'],class:"p5",module:"Data",submodule:"Conversion"},{file:"src/utilities/conversion.js",line:137,description:"

Converts a number, string or boolean to its byte representation.\nA byte can be only a whole number between -128 and 127, so when a value\noutside of this range is converted, it wraps around to the corresponding\nbyte representation. When an array of number, string or boolean values is\npassed in, then an array of bytes the same length is returned.

\n",itemtype:"method",name:"byte",return:{description:"byte representation of value",type:"Number"},class:"p5",module:"Data",submodule:"Conversion",overloads:[{line:137,params:[{name:"n",description:"

value to parse

\n",type:"String|Boolean|Number"}],return:{description:"byte representation of value",type:"Number"}},{line:148,params:[{name:"ns",description:"

values to parse

\n",type:"Array"}],return:{description:"array of byte representation of values",type:"Number[]"}}]},{file:"src/utilities/conversion.js",line:171,description:"

Converts a number or string to its corresponding single-character\nstring representation. If a string parameter is provided, it is first\nparsed as an integer and then translated into a single-character string.\nWhen an array of number or string values is passed in, then an array of\nsingle-character strings of the same length is returned.

\n",itemtype:"method",name:"char",return:{description:"string representation of value",type:"String"},class:"p5",module:"Data",submodule:"Conversion",overloads:[{line:171,params:[{name:"n",description:"

value to parse

\n",type:"String|Number"}],return:{description:"string representation of value",type:"String"}},{line:182,params:[{name:"ns",description:"

values to parse

\n",type:"Array"}],return:{description:"array of string representation of values",type:"String[]"}}]},{file:"src/utilities/conversion.js",line:204,description:"

Converts a single-character string to its corresponding integer\nrepresentation. When an array of single-character string values is passed\nin, then an array of integers of the same length is returned.

\n",itemtype:"method",name:"unchar",return:{description:"integer representation of value",type:"Number"},class:"p5",module:"Data",submodule:"Conversion",overloads:[{line:204,params:[{name:"n",description:"

value to parse

\n",type:"String"}],return:{description:"integer representation of value",type:"Number"}},{line:213,params:[{name:"ns",description:"

values to parse

\n",type:"Array"}],return:{description:"integer representation of values",type:"Number[]"}}]},{file:"src/utilities/conversion.js",line:232,description:"

Converts a number to a string in its equivalent hexadecimal notation. If a\nsecond parameter is passed, it is used to set the number of characters to\ngenerate in the hexadecimal notation. When an array is passed in, an\narray of strings in hexadecimal notation of the same length is returned.

\n",itemtype:"method",name:"hex",return:{description:"hexadecimal string representation of value",type:"String"},class:"p5",module:"Data",submodule:"Conversion",overloads:[{line:232,params:[{name:"n",description:"

value to parse

\n",type:"Number"},{name:"digits",description:"",type:"Number",optional:!0}],return:{description:"hexadecimal string representation of value",type:"String"}},{line:243,params:[{name:"ns",description:"

array of values to parse

\n",type:"Number[]"},{name:"digits",description:"",type:"Number",optional:!0}],return:{description:"hexadecimal string representation of values",type:"String[]"}}]},{file:"src/utilities/conversion.js",line:274,description:"

Converts a string representation of a hexadecimal number to its equivalent\ninteger value. When an array of strings in hexadecimal notation is passed\nin, an array of integers of the same length is returned.

\n",itemtype:"method",name:"unhex",return:{description:"integer representation of hexadecimal value",type:"Number"},class:"p5",module:"Data",submodule:"Conversion",overloads:[{line:274,params:[{name:"n",description:"

value to parse

\n",type:"String"}],return:{description:"integer representation of hexadecimal value",type:"Number"}},{line:283,params:[{name:"ns",description:"

values to parse

\n",type:"Array"}],return:{description:"integer representations of hexadecimal value",type:"Number[]"}}]},{file:"src/utilities/string_functions.js",line:15,description:"

Combines an array of Strings into one String, each separated by the\ncharacter(s) used for the separator parameter. To join arrays of ints or\nfloats, it's necessary to first convert them to Strings using nf() or\nnfs().

\n",itemtype:"method",name:"join",params:[{name:"list",description:"

array of Strings to be joined

\n",type:"Array"},{name:"separator",description:"

String to be placed between each item

\n",type:"String"}],return:{description:"joined String",type:"String"},example:['\n
\n\nvar array = ["Hello", "world!"]\nvar separator = " "\nvar message = join(array, separator);\ntext(message, 5, 50);\n\n
'],alt:'"hello world!" displayed middle left of canvas.',class:"p5",module:"Data",submodule:"String Functions"},{file:"src/utilities/string_functions.js",line:44,description:"

This function is used to apply a regular expression to a piece of text,\nand return matching groups (elements found inside parentheses) as a\nString array. If there are no matches, a null value will be returned.\nIf no groups are specified in the regular expression, but the sequence\nmatches, an array of length 1 (with the matched text as the first element\nof the array) will be returned.\n

\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, an array is returned.\n

\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nElement [0] of a regular expression match returns the entire matching\nstring, and the match groups start at element [1] (the first group is [1],\nthe second [2], and so on).

\n",itemtype:"method",name:"match",params:[{name:"str",description:"

the String to be searched

\n",type:"String"},{name:"regexp",description:"

the regexp to be used for matching

\n",type:"String"}],return:{description:"Array of Strings found",type:"String[]"},example:['\n
\n\nvar string = "Hello p5js*!"\nvar regexp = "p5js\\\\*"\nvar match = match(string, regexp);\ntext(match, 5, 50);\n\n
'],alt:'"p5js*" displayed middle left of canvas.',class:"p5",module:"Data",submodule:"String Functions"},{file:"src/utilities/string_functions.js",line:85,description:"

This function is used to apply a regular expression to a piece of text,\nand return a list of matching groups (elements found inside parentheses)\nas a two-dimensional String array. If there are no matches, a null value\nwill be returned. If no groups are specified in the regular expression,\nbut the sequence matches, a two dimensional array is still returned, but\nthe second dimension is only of length one.\n

\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, a 2D array is returned.\n

\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nAssuming a loop with counter variable i, element [i][0] of a regular\nexpression match returns the entire matching string, and the match groups\nstart at element [i][1] (the first group is [i][1], the second [i][2],\nand so on).

\n",itemtype:"method",name:"matchAll",params:[{name:"str",description:"

the String to be searched

\n",type:"String"},{name:"regexp",description:"

the regexp to be used for matching

\n",type:"String"}],return:{description:"2d Array of Strings found",type:"String[]"},example:['\n
\n\nvar string = "Hello p5js*! Hello world!"\nvar regexp = "Hello"\nmatchAll(string, regexp);\n\n
'],class:"p5",module:"Data",submodule:"String Functions"},{file:"src/utilities/string_functions.js",line:132,description:"

Utility function for formatting numbers into strings. There are two\nversions: one for formatting floats, and one for formatting ints.\nThe values for the digits, left, and right parameters should always\nbe positive integers.

\n",itemtype:"method",name:"nf",return:{description:"formatted String",type:"String"},class:"p5",module:"Data",submodule:"String Functions",overloads:[{line:132,params:[{name:"num",description:"

the Number to format

\n",type:"Number|String"},{name:"left",description:"

number of digits to the left of the\n decimal point

\n",type:"Number|String",optional:!0},{name:"right",description:"

number of digits to the right of the\n decimal point

\n",type:"Number|String",optional:!0}],return:{description:"formatted String",type:"String"}},{line:146,params:[{name:"nums",description:"

the Numbers to format

\n",type:"Array"},{name:"left",description:"",type:"Number|String",optional:!0},{name:"right",description:"",type:"Number|String",optional:!0}],return:{description:"formatted Strings\\",type:"Array"}}]},{file:"src/utilities/string_functions.js",line:245,description:"

Utility function for formatting numbers into strings and placing\nappropriate commas to mark units of 1000. There are two versions: one\nfor formatting ints, and one for formatting an array of ints. The value\nfor the right parameter should always be a positive integer.

\n",itemtype:"method",name:"nfc",return:{description:"formatted String",type:"String"},class:"p5",module:"Data",submodule:"String Functions",overloads:[{line:245,params:[{name:"num",description:"

the Number to format

\n",type:"Number|String"},{name:"right",description:"

number of digits to the right of the\n decimal point

\n",type:"Number|String",optional:!0}],return:{description:"formatted String",type:"String"}},{line:257,params:[{name:"nums",description:"

the Numbers to format

\n",type:"Array"},{name:"right",description:"",type:"Number|String",optional:!0}],return:{description:"formatted Strings",type:"Array"}}]},{file:"src/utilities/string_functions.js",line:324,description:"

Utility function for formatting numbers into strings. Similar to nf() but\nputs a "+" in front of positive numbers and a "-" in front of negative\nnumbers. There are two versions: one for formatting floats, and one for\nformatting ints. The values for left, and right parameters\nshould always be positive integers.

\n",itemtype:"method",name:"nfp",return:{description:"formatted String",type:"String"},class:"p5",module:"Data",submodule:"String Functions",overloads:[{line:324,params:[{name:"num",description:"

the Number to format

\n",type:"Number"},{name:"left",description:"

number of digits to the left of the decimal\n point

\n",type:"Number",optional:!0},{name:"right",description:"

number of digits to the right of the\n decimal point

\n",type:"Number",optional:!0}],return:{description:"formatted String",type:"String"}},{line:339,params:[{name:"nums",description:"

the Numbers to format

\n",type:"Number[]"},{name:"left",description:"",type:"Number",optional:!0},{name:"right",description:"",type:"Number",optional:!0}],return:{description:"formatted Strings",type:"String[]"}}]},{file:"src/utilities/string_functions.js",line:389,description:"

Utility function for formatting numbers into strings. Similar to nf() but\nputs a " " (space) in front of positive numbers and a "-" in front of\nnegative numbers. There are two versions: one for formatting floats, and\none for formatting ints. The values for the digits, left, and right\nparameters should always be positive integers.

\n",itemtype:"method",name:"nfs",return:{description:"formatted String",type:"String"},class:"p5",module:"Data",submodule:"String Functions",overloads:[{line:389,params:[{name:"num",description:"

the Number to format

\n",type:"Number"},{name:"left",description:"

number of digits to the left of the decimal\n point

\n",type:"Number",optional:!0},{name:"right",description:"

number of digits to the right of the\n decimal point

\n",type:"Number",optional:!0}],return:{description:"formatted String",type:"String"}},{line:404,params:[{name:"nums",description:"

the Numbers to format

\n",type:"Array"},{name:"left",description:"",type:"Number",optional:!0},{name:"right",description:"",type:"Number",optional:!0}],return:{description:"formatted Strings",type:"Array"}}]},{file:"src/utilities/string_functions.js",line:454,description:"

The split() function maps to String.split(), it breaks a String into\npieces using a character or string as the delimiter. The delim parameter\nspecifies the character or characters that mark the boundaries between\neach piece. A String[] array is returned that contains each of the pieces.

\n

The splitTokens() function works in a similar fashion, except that it\nsplits using a range of characters instead of a specific character or\nsequence.

\n",itemtype:"method",name:"split",params:[{name:"value",description:"

the String to be split

\n",type:"String"},{name:"delim",description:"

the String used to separate the data

\n",type:"String"}],return:{description:"Array of Strings",type:"String[]"},example:['\n
\n\nvar names = "Pat,Xio,Alex"\nvar splitString = split(names, ",");\ntext(splitString[0], 5, 30);\ntext(splitString[1], 5, 50);\ntext(splitString[2], 5, 70);\n\n
'],alt:'"pat" top left, "Xio" mid left and "Alex" displayed bottom left',class:"p5",module:"Data",submodule:"String Functions"},{file:"src/utilities/string_functions.js",line:488,description:"

The splitTokens() function splits a String at one or many character\ndelimiters or "tokens." The delim parameter specifies the character or\ncharacters to be used as a boundary.\n

\nIf no delim characters are specified, any whitespace character is used to\nsplit. Whitespace characters include tab (\\t), line feed (\\n), carriage\nreturn (\\r), form feed (\\f), and space.

\n",itemtype:"method",name:"splitTokens",params:[{name:"value",description:"

the String to be split

\n",type:"String"},{name:"delim",description:"

list of individual Strings that will be used as\n separators

\n",type:"String",optional:!0}],return:{description:"Array of Strings",type:"String[]"},example:['\n
\n\nfunction setup() {\n var myStr = "Mango, Banana, Lime";\n var myStrArr = splitTokens(myStr, ",");\n\n print(myStrArr); // prints : ["Mango"," Banana"," Lime"]\n}\n\n
'],class:"p5",module:"Data",submodule:"String Functions"},{file:"src/utilities/string_functions.js",line:541,description:"

Removes whitespace characters from the beginning and end of a String. In\naddition to standard whitespace characters such as space, carriage return,\nand tab, this function also removes the Unicode "nbsp" character.

\n",itemtype:"method",name:"trim",return:{description:"a trimmed String",type:"String"},class:"p5",module:"Data",submodule:"String Functions",overloads:[{line:541,params:[{name:"str",description:"

a String to be trimmed

\n",type:"String"}],return:{description:"a trimmed String",type:"String"}},{line:550,params:[{name:"strs",description:"

an Array of Strings to be trimmed

\n",type:"Array"}],return:{description:"an Array of trimmed Strings",type:"Array"}}]},{file:"src/utilities/time_date.js",line:12,description:"

p5.js communicates with the clock on your computer. The day() function\nreturns the current day as a value from 1 - 31.

\n",itemtype:"method",name:"day",return:{description:"the current day",type:"Number"},example:['\n
\n\nvar d = day();\ntext("Current day: \\n" + d, 5, 50);\n\n
'],alt:"Current day is displayed",class:"p5",module:"IO",submodule:"Time & Date"},{file:"src/utilities/time_date.js",line:34,description:"

p5.js communicates with the clock on your computer. The hour() function\nreturns the current hour as a value from 0 - 23.

\n",itemtype:"method",name:"hour",return:{description:"the current hour",type:"Number"},example:['\n
\n\nvar h = hour();\ntext("Current hour:\\n" + h, 5, 50);\n\n
'],alt:"Current hour is displayed",class:"p5",module:"IO",submodule:"Time & Date"},{file:"src/utilities/time_date.js",line:56,description:"

p5.js communicates with the clock on your computer. The minute() function\nreturns the current minute as a value from 0 - 59.

\n",itemtype:"method",name:"minute",return:{description:"the current minute",type:"Number"},example:['\n
\n\nvar m = minute();\ntext("Current minute: \\n" + m, 5, 50);\n\n
'],alt:"Current minute is displayed",class:"p5",module:"IO",submodule:"Time & Date"},{file:"src/utilities/time_date.js",line:78,description:"

Returns the number of milliseconds (thousandths of a second) since\nstarting the program. This information is often used for timing events and\nanimation sequences.

\n",itemtype:"method",name:"millis",return:{description:"the number of milliseconds since starting the program",type:"Number"},example:['\n
\n\nvar millisecond = millis();\ntext("Milliseconds \\nrunning: \\n" + millisecond, 5, 40);\n\n
'],alt:"number of milliseconds since program has started displayed",class:"p5",module:"IO",submodule:"Time & Date"},{file:"src/utilities/time_date.js",line:101,description:"

p5.js communicates with the clock on your computer. The month() function\nreturns the current month as a value from 1 - 12.

\n",itemtype:"method",name:"month",return:{description:"the current month",type:"Number"},example:['\n
\n\nvar m = month();\ntext("Current month: \\n" + m, 5, 50);\n\n
'],alt:"Current month is displayed",class:"p5",module:"IO",submodule:"Time & Date"},{file:"src/utilities/time_date.js",line:123,description:"

p5.js communicates with the clock on your computer. The second() function\nreturns the current second as a value from 0 - 59.

\n",itemtype:"method",name:"second",return:{description:"the current second",type:"Number"},example:['\n
\n\nvar s = second();\ntext("Current second: \\n" + s, 5, 50);\n\n
'],alt:"Current second is displayed",class:"p5",module:"IO",submodule:"Time & Date"},{file:"src/utilities/time_date.js",line:145,description:"

p5.js communicates with the clock on your computer. The year() function\nreturns the current year as an integer (2014, 2015, 2016, etc).

\n",itemtype:"method",name:"year",return:{description:"the current year",type:"Number"},example:['\n
\n\nvar y = year();\ntext("Current year: \\n" + y, 5, 50);\n\n
'],alt:"Current year is displayed",class:"p5",module:"IO",submodule:"Time & Date"},{file:"src/webgl/camera.js",line:12,description:"

Sets camera position for a 3D sketch. The function behaves similarly\ngluLookAt, except that it replaces the existing modelview matrix instead\nof applying any transformations calculated here on top of the existing\nmodel view.\nWhen called with no arguments, this function\nsets a default camera equivalent to calling\ncamera(0, 0, (height/2.0) / tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0);

\n",itemtype:"method",name:"camera",params:[{name:"x",description:"

camera position value on x axis

\n",type:"Number",optional:!0},{name:"y",description:"

camera position value on y axis

\n",type:"Number",optional:!0},{name:"z",description:"

camera position value on z axis

\n",type:"Number",optional:!0},{name:"centerX",description:"

x coordinate representing center of the sketch

\n",type:"Number",optional:!0},{name:"centerY",description:"

y coordinate representing center of the sketch

\n",type:"Number",optional:!0},{name:"centerZ",description:"

z coordinate representing center of the sketch

\n",type:"Number",optional:!0},{name:"upX",description:"

x component of direction 'up' from camera

\n",type:"Number",optional:!0},{name:"upY",description:"

y component of direction 'up' from camera

\n",type:"Number",optional:!0},{name:"upZ",description:"

z component of direction 'up' from camera

\n",type:"Number",optional:!0}],return:{description:"the p5 object",type:"P5"},example:["\n
\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n //move the camera away from the plane by a sin wave\n camera(0, 0, sin(frameCount * 0.01) * 100, 0, 0, 0, 0, 1, 0);\n plane(120, 120);\n}\n\n
"],alt:"blue square shrinks in size grows to fill canvas. disappears then loops.",class:"p5",module:"Lights, Camera",submodule:"Camera"},{file:"src/webgl/camera.js",line:160,description:"

Sets perspective camera. When called with no arguments, the defaults\nprovided are equivalent to\nperspective(PI/3.0, width/height, cameraZ/10.0, cameraZ10.0)\nwhere cameraZ is ((height/2.0) / tan(PI60.0/360.0));

\n",itemtype:"method",name:"perspective",params:[{name:"fovy",description:"

camera frustum vertical field of view,\n from bottom to top of view, in degrees

\n",type:"Number",optional:!0},{name:"aspect",description:"

camera frustum aspect ratio

\n",type:"Number",optional:!0},{name:"near",description:"

frustum near plane length

\n",type:"Number",optional:!0},{name:"far",description:"

frustum far plane length

\n",type:"Number",optional:!0}],return:{description:"the p5 object",type:"P5"},example:["\n
\n\n//drag mouse to toggle the world!\n//you will see there's a vanish point\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n var fov = 60 / 180 * PI;\n var cameraZ = (height/2.0) / tan(fov/2.0);\n perspective(60 / 180 * PI, width/height, cameraZ * 0.1, cameraZ * 10);\n}\nfunction draw(){\n background(200);\n orbitControl();\n for(var i = -1; i < 2; i++){\n for(var j = -2; j < 3; j++){\n push();\n translate(i*160, 0, j*160);\n box(40, 40, 40);\n pop();\n }\n }\n}\n\n
"],alt:"colored 3d boxes toggleable with mouse position",class:"p5",module:"Lights, Camera",submodule:"Camera"},{file:"src/webgl/camera.js",line:232,description:"

Setup ortho camera

\n",itemtype:"method",name:"ortho",params:[{name:"left",description:"

camera frustum left plane

\n",type:"Number"},{name:"right",description:"

camera frustum right plane

\n",type:"Number"},{name:"bottom",description:"

camera frustum bottom plane

\n",type:"Number"},{name:"top",description:"

camera frustum top plane

\n",type:"Number"},{name:"near",description:"

camera frustum near plane

\n",type:"Number"},{name:"far",description:"

camera frustum far plane

\n",type:"Number"}],return:{description:"the p5 object",type:"P5"},example:["\n
\n\n//drag mouse to toggle the world!\n//there's no vanish point\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n ortho(-width/2, width/2, height/2, -height/2, 0, 500);\n}\nfunction draw(){\n background(200);\n orbitControl();\n for(var i = -1; i < 2; i++){\n for(var j = -2; j < 3; j++){\n push();\n translate(i*160, 0, j*160);\n box(40, 40, 40);\n pop();\n }\n }\n}\n\n
"],alt:"3 3d boxes, reveal several more boxes on 3d plane when mouse used to toggle",class:"p5",module:"Lights, Camera",submodule:"Camera"},{file:"src/webgl/light.js",line:12,description:"

Creates an ambient light with a color

\n",itemtype:"method",name:"ambientLight",chainable:1,class:"p5",module:"Lights, Camera",submodule:"Lights",overloads:[{line:12,params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{line:26,params:[{name:"value",description:"

a color string

\n",type:"String"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{line:33,params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}],chainable:1},{line:40,params:[{name:"color",description:"

the ambient light color

\n",type:"p5.Color"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1}]},{file:"src/webgl/light.js",line:89,description:"

Creates a directional light with a color and a direction

\n",itemtype:"method",name:"directionalLight",params:[{name:"v1",description:"

gray value,\nred or hue value (depending on the current color mode),\nor color Array, or CSS color string

\n",type:"Number|Array|String|p5.Color"},{name:"v2",description:"

green or saturation value

\n",type:"Number",optional:!0},{name:"v3",description:"

blue or brightness value

\n",type:"Number",optional:!0},{name:"a",description:"

opacity

\n",type:"Number",optional:!0},{name:"x",description:"

x axis direction or a p5.Vector

\n",type:"Number|p5.Vector"},{name:"y",description:"

y axis direction

\n",type:"Number",optional:!0},{name:"z",description:"

z axis direction

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n background(0);\n //move your mouse to change light direction\n var dirX = (mouseX / width - 0.5) *2;\n var dirY = (mouseY / height - 0.5) *(-2);\n directionalLight(250, 250, 250, dirX, dirY, 0.25);\n ambientMaterial(250);\n sphere(50);\n}\n\n
"],alt:"light source on canvas changeable with mouse position",class:"p5",module:"Lights, Camera",submodule:"Lights"},{file:"src/webgl/light.js",line:168,description:"

Creates a point light with a color and a light position

\n",itemtype:"method",name:"pointLight",params:[{name:"v1",description:"

gray value,\nred or hue value (depending on the current color mode),\nor color Array, or CSS color string

\n",type:"Number|Array|String|p5.Color"},{name:"v2",description:"

green or saturation value

\n",type:"Number",optional:!0},{name:"v3",description:"

blue or brightness value

\n",type:"Number",optional:!0},{name:"a",description:"

opacity

\n",type:"Number",optional:!0},{name:"x",description:"

x axis position or a p5.Vector

\n",type:"Number|p5.Vector"},{name:"y",description:"

y axis position

\n",type:"Number",optional:!0},{name:"z",description:"

z axis position

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n background(0);\n //move your mouse to change light position\n var locY = (mouseY / height - 0.5) *(-2);\n var locX = (mouseX / width - 0.5) *2;\n //to set the light position,\n //think of the world's coordinate as:\n // -1,1 -------- 1,1\n // | |\n // | |\n // | |\n // -1,-1---------1,-1\n pointLight(250, 250, 250, locX, locY, 0);\n ambientMaterial(250);\n sphere(50);\n}\n\n
"],alt:"spot light on canvas changes position with mouse",class:"p5",module:"Lights, Camera",submodule:"Lights"},{file:"src/webgl/loading.js",line:14,description:"

Load a 3d model from an OBJ file.\n

\nOne of the limitations of the OBJ format is that it doesn't have a built-in\nsense of scale. This means that models exported from different programs might\nbe very different sizes. If your model isn't displaying, try calling\nloadModel() with the normalized parameter set to true. This will resize the\nmodel to a scale appropriate for p5. You can also make additional changes to\nthe final size of your model with the scale() function.

\n",itemtype:"method",name:"loadModel",return:{description:"the p5.Geometry object",type:"p5.Geometry"},class:"p5",module:"Shape",submodule:"3D Models",overloads:[{line:14,params:[{name:"path",description:"

Path of the model to be loaded

\n",type:"String"},{name:"normalize", +description:"

If true, scale the model to a\n standardized size when loading

\n",type:"Boolean"},{name:"successCallback",description:"

Function to be called\n once the model is loaded. Will be passed\n the 3D model object.

\n",type:"function(p5.Geometry)",optional:!0},{name:"failureCallback",description:"

called with event error if\n the image fails to load.

\n",type:"Function(Event)",optional:!0}],return:{description:"the p5.Geometry object",type:"p5.Geometry"}},{line:35,params:[{name:"path",description:"",type:"String"},{name:"successCallback",description:"",type:"function(p5.Geometry)",optional:!0},{name:"failureCallback",description:"",type:"Function(Event)",optional:!0}],return:{description:"the p5.Geometry object",type:"p5.Geometry"}}]},{file:"src/webgl/loading.js",line:98,description:"

Parse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:

\n

v -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5

\n

f 4 3 2 1

\n",class:"p5",module:"Shape",submodule:"3D Models"},{file:"src/webgl/loading.js",line:197,description:"

Render a 3d model to the screen.

\n",itemtype:"method",name:"model",params:[{name:"model",description:"

Loaded 3d model to be rendered

\n",type:"p5.Geometry"}],example:["\n
\n\n//draw a spinning teapot\nvar teapot;\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n\n teapot = loadModel('assets/teapot.obj');\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(teapot);\n}\n\n
"],alt:"Vertically rotating 3-d teapot with red, green and blue gradient.",class:"p5",module:"Shape",submodule:"3D Models"},{file:"src/webgl/material.js",line:15,description:"

Loads a custom shader from the provided vertex and fragment\nshader paths. The shader files are loaded asynchronously in the\nbackground, so this method should be used in preload().

\n

For now, there are three main types of shaders. p5 will automatically\nsupply appropriate vertices, normals, colors, and lighting attributes\nif the parameters defined in the shader match the names.

\n",itemtype:"method",name:"loadShader",params:[{name:"vertFilename",description:"

path to file containing vertex shader\nsource code

\n",type:"String",optional:!0},{name:"fragFilename",description:"

path to file containing fragment shader\nsource code

\n",type:"String",optional:!0}],return:{description:"a shader object created from the provided\nvertex and fragment shader files.",type:"p5.Shader"},class:"p5",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/material.js",line:58,description:"

The shader() function lets the user provide a custom shader\nto fill in shapes in WEBGL mode. Users can create their\nown shaders by loading vertex and fragment shaders with\nloadShader().

\n",itemtype:"method",name:"shader",chainable:1,params:[{name:"s",description:"

the desired p5.Shader to use for rendering\nshapes.

\n",type:"p5.Shader",optional:!0}],class:"p5",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/material.js",line:81,description:'

Normal material for geometry. You can view all\npossible materials in this\nexample.

\n',itemtype:"method",name:"normalMaterial",chainable:1,example:["\n
\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n normalMaterial();\n sphere(50);\n}\n\n
"],alt:"Red, green and blue gradient.",class:"p5",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/material.js",line:113,description:'

Texture for geometry. You can view other possible materials in this\nexample.

\n',itemtype:"method",name:"texture",params:[{name:"tex",description:"

2-dimensional graphics\n to render as texture

\n",type:"p5.Image|p5.MediaElement|p5.Graphics"}],chainable:1,example:['\n
\n\nvar img;\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n img = loadImage("assets/laDefense.jpg");\n}\n\nfunction draw(){\n background(0);\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n //pass image as texture\n texture(img);\n box(200, 200, 200);\n}\n\n
\n\n
\n\nvar pg;\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n pg = createGraphics(200, 200);\n pg.textSize(100);\n}\n\nfunction draw(){\n background(0);\n pg.background(255);\n pg.text(\'hello!\', 0, 100);\n //pass image as texture\n texture(pg);\n plane(200);\n}\n\n
\n\n
\n\nvar vid;\nfunction preload(){\n vid = createVideo("assets/fingers.mov");\n vid.hide();\n vid.loop();\n}\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(0);\n //pass video frame as texture\n texture(vid);\n plane(200);\n}\n\n
'],alt:"Rotating view of many images umbrella and grid roof on a 3d plane\nblack canvas\nblack canvas",class:"p5",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/material.js",line:210,description:'

Ambient material for geometry with a given color. You can view all\npossible materials in this\nexample.

\n',itemtype:"method",name:"ambientMaterial",params:[{name:"v1",description:"

gray value,\nred or hue value (depending on the current color mode),\nor color Array, or CSS color string

\n",type:"Number|Array|String|p5.Color"},{name:"v2",description:"

green or saturation value

\n",type:"Number",optional:!0},{name:"v3",description:"

blue or brightness value

\n",type:"Number",optional:!0},{name:"a",description:"

opacity

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n ambientMaterial(250);\n sphere(50);\n}\n\n
"],alt:"radiating light source from top right of canvas",class:"p5",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/material.js",line:253,description:'

Specular material for geometry with a given color. You can view all\npossible materials in this\nexample.

\n',itemtype:"method",name:"specularMaterial",params:[{name:"v1",description:"

gray value,\nred or hue value (depending on the current color mode),\nor color Array, or CSS color string

\n",type:"Number|Array|String|p5.Color"},{name:"v2",description:"

green or saturation value

\n",type:"Number",optional:!0},{name:"v3",description:"

blue or brightness value

\n",type:"Number",optional:!0},{name:"a",description:"

opacity

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\nfunction draw(){\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n specularMaterial(250);\n sphere(50);\n}\n\n
"],alt:"diffused radiating light source from top right of canvas",class:"p5",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/material.js",line:297,access:"private",tagname:"blends colors according to color components.\nIf alpha value is less than 1, we need to enable blending\non our gl context. Otherwise opaque objects need to a depthMask.",params:[{name:"v1",description:"

[description]

\n",type:"Number"},{name:"v2",description:"

[description]

\n",type:"Number"},{name:"v3",description:"

[description]

\n",type:"Number"},{name:"a",description:"

[description]

\n",type:"Number"}],return:{description:"Normalized numbers array",type:"[Number]"},class:"p5",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/p5.Geometry.js",line:86,description:"

computes smooth normals per vertex as an average of each\nface.

\n",chainable:1,class:"p5.Geometry",module:"Lights, Camera"},{file:"src/webgl/p5.Geometry.js",line:111,description:"

Averages the vertex normals. Used in curved\nsurfaces

\n",chainable:1,class:"p5.Geometry",module:"Lights, Camera"},{file:"src/webgl/p5.Geometry.js",line:130,description:"

Averages pole normals. Used in spherical primitives

\n",chainable:1,class:"p5.Geometry",module:"Lights, Camera"},{file:"src/webgl/p5.Geometry.js",line:161,description:"

Create a 2D array for establishing stroke connections

\n",return:{description:"",type:"p5.Geometry"},class:"p5.Geometry",module:"Lights, Camera"},{file:"src/webgl/p5.Geometry.js",line:182,description:"

Create 4 vertices for each stroke line, two at the beginning position\nand two at the end position. These vertices are displaced relative to\nthat line's normal on the GPU

\n",return:{description:"",type:"p5.Geometry"},class:"p5.Geometry",module:"Lights, Camera"},{file:"src/webgl/p5.Geometry.js",line:209,description:"

Modifies all vertices to be centered within the range -100 to 100.

\n",chainable:1,class:"p5.Geometry",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:1,requires:["constants"],todo:["see methods below needing further implementation.\nfuture consideration: implement SIMD optimizations\nwhen browser compatibility becomes available\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/\n Reference/Global_Objects/SIMD"],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:19,description:"

A class to describe a 4x4 matrix\nfor model and view matrix manipulation in the p5js webgl renderer.\nclass p5.Matrix

\n",is_constructor:1,params:[{name:"mat4",description:"

array literal of our 4x4 matrix

\n",type:"Array",optional:!0}],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:75,description:"

Sets the x, y, and z component of the vector using two or three separate\nvariables, the data from a p5.Matrix, or the values from a float array.

\n",params:[{name:"inMatrix",description:"

the input p5.Matrix or\n an Array of length 16

\n",type:"p5.Matrix|Float32Array|Array",optional:!0},{name:"n00..n33",description:"

16 numbers passed by value to avoid\n array copying.

\n",type:"Number",optional:!0}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:113,description:"

Gets a copy of the vector, returns a p5.Matrix object.

\n",return:{description:"the copy of the p5.Matrix object",type:"p5.Matrix"},class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:122,description:"

return a copy of a matrix

\n",return:{description:"the result matrix",type:"p5.Matrix"},class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:147,description:"

return an identity matrix

\n",return:{description:"the result matrix",type:"p5.Matrix"},class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:155,description:"

transpose according to a given matrix

\n",params:[{name:"a",description:"

the matrix to be based on to transpose

\n",type:"p5.Matrix|Float32Array|Array"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:215,description:"

invert matrix according to a give matrix

\n",params:[{name:"a",description:"

the matrix to be based on to invert

\n",type:"p5.Matrix|Float32Array|Array"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:300,description:"

Inverts a 3x3 matrix

\n",chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:336,description:"

transposes a 3x3 p5.Matrix by a mat3

\n",params:[{name:"mat3",description:"

1-dimensional array

\n",type:"[Number]"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:352,description:"

converts a 4x4 matrix to its 3x3 inverse tranform\ncommonly used in MVMatrix to NMatrix conversions.

\n",params:[{name:"mat4",description:"

the matrix to be based on to invert

\n",type:"p5.Matrix"}],chainable:1,todo:["finish implementation"],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:380,description:"

inspired by Toji's mat4 determinant

\n",return:{description:"Determinant of our 4x4 matrix",type:"Number"},class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:403,description:"

multiply two mat4s

\n",params:[{name:"multMatrix",description:"

The matrix\n we want to multiply by

\n",type:"p5.Matrix|Float32Array|Array"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:460,description:"

scales a p5.Matrix by scalars or a vector

\n",params:[{name:"s",description:"

vector to scale by

\n",type:"p5.Vector|Float32Array|Array"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:505,description:"

rotate our Matrix around an axis by the given angle.

\n",params:[{name:"a",description:"

The angle of rotation in radians

\n",type:"Number"},{name:"axis",description:"

the axis(es) to rotate around

\n",type:"p5.Vector|Array"}],chainable:"inspired by Toji's gl-matrix lib, mat4 rotation",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:584,todo:["finish implementing this method!\ntranslates"],params:[{name:"v",description:"

vector to translate by

\n",type:"Number[]"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:614,description:"

sets the perspective matrix

\n",params:[{name:"fovy",description:"

[description]

\n",type:"Number"},{name:"aspect",description:"

[description]

\n",type:"Number"},{name:"near",description:"

near clipping plane

\n",type:"Number"},{name:"far",description:"

far clipping plane

\n",type:"Number"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:648,description:"

sets the ortho matrix

\n",params:[{name:"left",description:"

[description]

\n",type:"Number"},{name:"right",description:"

[description]

\n",type:"Number"},{name:"bottom",description:"

[description]

\n",type:"Number"},{name:"top",description:"

[description]

\n",type:"Number"},{name:"near",description:"

near clipping plane

\n",type:"Number"},{name:"far",description:"

far clipping plane

\n",type:"Number"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Matrix.js",line:683,description:"

PRIVATE

\n",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.Immediate.js",line:1,description:"

Welcome to RendererGL Immediate Mode.\nImmediate mode is used for drawing custom shapes\nfrom a set of vertices. Immediate Mode is activated\nwhen you call beginShape() & de-activated when you call endShape().\nImmediate mode is a style of programming borrowed\nfrom OpenGL's (now-deprecated) immediate mode.\nIt differs from p5.js' default, Retained Mode, which caches\ngeometries and buffers on the CPU to reduce the number of webgl\ndraw calls. Retained mode is more efficient & performative,\nhowever, Immediate Mode is useful for sketching quick\ngeometric ideas.

\n",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.Immediate.js",line:19,description:"

Begin shape drawing. This is a helpful way of generating\ncustom shapes quickly. However in WEBGL mode, application\nperformance will likely drop as a result of too many calls to\nbeginShape() / endShape(). As a high performance alternative,\nplease use p5.js geometry primitives.

\n",params:[{name:"mode",description:"

webgl primitives mode. beginShape supports the\n following modes:\n POINTS,LINES,LINE_STRIP,LINE_LOOP,TRIANGLES,\n TRIANGLE_STRIP,and TRIANGLE_FAN.

\n",type:"Number"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.Immediate.js",line:60,description:"

adds a vertex to be drawn in a custom Shape.

\n",params:[{name:"x",description:"

x-coordinate of vertex

\n",type:"Number"},{name:"y",description:"

y-coordinate of vertex

\n",type:"Number"},{name:"z",description:"

z-coordinate of vertex

\n",type:"Number"}],chainable:1,todo:["implement handling of p5.Vector args"],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.Immediate.js",line:103,description:"

End shape drawing and render vertices to screen.

\n",chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.Retained.js",line:8,description:"

initializes buffer defaults. runs each time a new geometry is\nregistered

\n",params:[{name:"gId",description:"

key of the geometry object

\n",type:"String"}],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.Retained.js",line:33,description:"

createBuffers description

\n",params:[{name:"gId",description:"

key of the geometry object

\n",type:"String"},{name:"obj",description:"

contains geometry data

\n",type:"p5.Geometry"}],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.Retained.js",line:84,description:"

Draws buffers given a geometry key ID

\n",params:[{name:"gId",description:"

ID in our geom hash

\n",type:"String"}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:69,description:"

model view, projection, & normal\nmatrices

\n",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:184,description:"

Set attributes for the WebGL Drawing context.\n This is a way of adjusting ways that the WebGL\n renderer works to fine-tune the display and performance.\n This should be put in setup().\n The available attributes are:\n
\n alpha - indicates if the canvas contains an alpha buffer\n default is true\n

\n depth - indicates whether the drawing buffer has a depth buffer\n of at least 16 bits - default is true\n

\n stencil - indicates whether the drawing buffer has a stencil buffer\n of at least 8 bits\n

\n antialias - indicates whether or not to perform anti-aliasing\n default is false\n

\n premultipliedAlpha - indicates that the page compositor will assume\n the drawing buffer contains colors with pre-multiplied alpha\n default is false\n

\n preserveDrawingBuffer - if true the buffers will not be cleared and\n and will preserve their values until cleared or overwritten by author\n (note that p5 clears automatically on draw loop)\n default is true\n

\n
\n \n function setup() {\n createCanvas(150,150,WEBGL);\n }\n function draw() {\n background(255);\n push();\n rotateZ(frameCount 0.02);\n rotateX(frameCount 0.02);\n rotateY(frameCount 0.02);\n fill(0,0,0);\n box(50);\n pop();\n }\n \n
\n
\n Now with the antialias attribute set to true.\n
\n
\n \n function setup() {\n createCanvas(150,150,WEBGL);\n setAttributes('antialias', true);\n }\n function draw() {\n background(255);\n push();\n rotateZ(frameCount 0.02);\n rotateX(frameCount 0.02);\n rotateY(frameCount 0.02);\n fill(0,0,0);\n box(50);\n pop();\n }\n \n
",itemtype:"method",name:"setAttributes",params:[{name:"String",description:"

name of attribute or object with key-value pairs

\n",type:"String|Object"},{name:"New",description:"

value of named attribute

\n",type:"Boolean"}],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:331,description:"

[background description]

\n",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:352,description:"

Basic fill material for geometry with a given color

\n",itemtype:"method",name:"fill",params:[{name:"v1",description:"

gray value,\nred or hue value (depending on the current color mode),\nor color Array, or CSS color string

\n",type:"Number|Array|String|p5.Color"},{name:"v2",description:"

green or saturation value

\n",type:"Number",optional:!0},{name:"v3",description:"

blue or brightness value

\n",type:"Number",optional:!0},{name:"a",description:"

opacity

\n",type:"Number",optional:!0}],return:{description:"the p5 object",type:"P5"},example:["\n
\n\nfunction setup(){\n createCanvas(200, 200, WEBGL);\n}\n\nfunction draw(){\n background(0);\n noStroke();\n fill(100, 100, 240);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(75, 75, 75);\n}\n\n
"],alt:"black canvas with purple cube spinning",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:400,description:"

Does not render fill material

\n",itemtype:"method",name:"noFill",example:["\n
\n\nfunction setup(){\n createCanvas(200, 200, WEBGL);\n}\n\nfunction draw(){\n background(0);\n noFill();\n stroke(100, 100, 240);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(75, 75, 75);\n}\n\n
"],alt:"black canvas with purple cube wireframe spinning",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:431,description:"

Does not render stroke

\n",itemtype:"method",name:"noStroke",example:["\n
\n\nfunction setup(){\n createCanvas(200, 200, WEBGL);\n}\n\nfunction draw(){\n background(0);\n noStroke();\n fill(240, 150, 150);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(75, 75, 75);\n}\n\n
"],alt:"black canvas with pink cube spinning",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:460,description:"

Basic stroke material for geometry with a given color

\n",itemtype:"method",name:"stroke",params:[{name:"v1",description:"

gray value,\nred or hue value (depending on the current color mode),\nor color Array, or CSS color string

\n",type:"Number|Array|String|p5.Color"},{name:"v2",description:"

green or saturation value

\n",type:"Number",optional:!0},{name:"v3",description:"

blue or brightness value

\n",type:"Number",optional:!0},{name:"a",description:"

opacity

\n",type:"Number",optional:!0}],example:["\n
\n\nfunction setup(){\n createCanvas(200, 200, WEBGL);\n}\n\nfunction draw(){\n background(0);\n stroke(240, 150, 150);\n fill(100, 100, 240);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(75, 75, 75);\n}\n\n
"],alt:"black canvas with purple cube with pink outline spinning",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:505,description:"

Change weight of stroke

\n",itemtype:"method",name:"strokeWeight",params:[{name:"stroke",description:"

weight to be used for drawing

\n",type:"Number"}],example:["\n
\n\nfunction setup(){\n createCanvas(200, 400, WEBGL);\n setAttributes('antialias', true);\n}\n\nfunction draw(){\n background(0);\n noStroke();\n translate(0,-100,0);\n stroke(240,150,150);\n fill(100,100,240);\n push();\n strokeWeight(8);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n sphere(75);\n pop();\n push();\n translate(0,200,0);\n strokeWeight(1);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n sphere(75);\n pop();\n}\n\n\n
"],alt:"black canvas with two purple rotating spheres with pink\noutlines the sphere on top has much heavier outlines,",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:569,description:"

Returns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().\n

\nIf the pixel requested is outside of the image window, [0,0,0,255] is\nreturned.\n

\nGetting the color of a single pixel with get(x, y) is easy, but not as fast\nas grabbing the data directly from pixels[]. The equivalent statement to\nget(x, y) is using pixels[] with pixel density d

\n",itemtype:"method",name:"get",params:[{name:"x",description:"

x-coordinate of the pixel

\n",type:"Number",optional:!0},{name:"y",description:"

y-coordinate of the pixel

\n",type:"Number",optional:!0},{name:"w",description:"

width

\n",type:"Number",optional:!0},{name:"h",description:"

height

\n",type:"Number",optional:!0}],return:{description:"color of pixel at x,y in array format\n [R, G, B, A] or p5.Image",type:"Array|Color|p5.Image"},class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:597,description:"

Loads the pixels data for this canvas into the pixels[] attribute.\nNote that updatePixels() and set() do not work.\nAny pixel manipulation must be done directly to the pixels[] array.

\n",itemtype:"method",name:"loadPixels",params:[{name:"x",description:"

starting pixel x position, defaults to 0

\n",type:"Number",optional:!0},{name:"y",description:"

starting pixel y position, defaults to 0

\n",type:"Number",optional:!0},{name:"w",description:"

width of pixels to load, defaults to sketch width

\n",type:"Number",optional:!0},{name:"h",description:"

height of pixels to load, defaults to sketch height

\n",type:"Number",optional:!0}],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:642,description:"

[resize description]

\n",params:[{name:"w",description:"

[description]

\n",type:"Number"},{name:"h",description:"

[description]

\n",type:"Number"}],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:659,description:"

clears color and depth buffers\nwith r,g,b,a

\n",params:[{name:"r",description:"

normalized red val.

\n",type:"Number"},{name:"g",description:"

normalized green val.

\n",type:"Number"},{name:"b",description:"

normalized blue val.

\n",type:"Number"},{name:"a",description:"

normalized alpha val.

\n",type:"Number"}],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:675,description:"

[translate description]

\n",params:[{name:"x",description:"

[description]

\n",type:"Number"},{name:"y",description:"

[description]

\n",type:"Number"},{name:"z",description:"

[description]

\n",type:"Number"}],chainable:1,todo:["implement handle for components or vector as args"],class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:693,description:"

Scales the Model View Matrix by a vector

\n",params:[{name:"x",description:"

[description]

\n",type:"Number | p5.Vector | Array"},{name:"y",description:"

y-axis scalar

\n",type:"Number",optional:!0},{name:"z",description:"

z-axis scalar

\n",type:"Number",optional:!0}],chainable:1,class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:725,description:"

pushes a copy of the model view matrix onto the\nMV Matrix stack.

\n",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:734,description:"

[pop description]

\n",class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:904,description:"

turn a two dimensional array into one dimensional array

\n",params:[{name:"arr",description:"

2-dimensional array

\n",type:"Array"}],return:{description:"1-dimensional array\n[[1, 2, 3],[4, 5, 6]] -> [1, 2, 3, 4, 5, 6]",type:"Array"},class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.RendererGL.js",line:918,description:"

turn a p5.Vector Array into a one dimensional number array

\n",params:[{name:"arr",description:"

an array of p5.Vector

\n",type:"Array"}],return:{description:"a one dimensional array of numbers\n[p5.Vector(1, 2, 3), p5.Vector(4, 5, 6)] ->\n[1, 2, 3, 4, 5, 6]",type:"Array]"},class:"p5.RendererGL",module:"Lights, Camera"},{file:"src/webgl/p5.Shader.js",line:40,description:"

Creates, compiles, and links the shader based on its\nsources for the vertex and fragment shaders (provided\nto the constructor). Populates known attributes and\nuniforms from the shader.

\n",itemtype:"method",name:"init",chainable:1,access:"private",tagname:"",class:"p5.Shader",module:"Lights, Camera",submodule:"Shaders"},{file:"src/webgl/p5.Shader.js",line:98,description:"

Queries the active attributes for this shader and loads\ntheir names and locations into the attributes array.

\n",itemtype:"method",name:"_loadAttributes",access:"private",tagname:"",class:"p5.Shader",module:"Lights, Camera",submodule:"Shaders"},{file:"src/webgl/p5.Shader.js",line:130,description:"

Queries the active uniforms for this shader and loads\ntheir names and locations into the uniforms array.

\n",itemtype:"method",name:"_loadUniforms",access:"private",tagname:"",class:"p5.Shader",module:"Lights, Camera",submodule:"Shaders"},{file:"src/webgl/p5.Shader.js",line:179,description:"

initializes (if needed) and binds the shader program.

\n",itemtype:"method",name:"bindShader",access:"private",tagname:"",class:"p5.Shader",module:"Lights, Camera",submodule:"Shaders"},{file:"src/webgl/p5.Shader.js",line:202,itemtype:"method",name:"unbindShader",chainable:1,access:"private",tagname:"",class:"p5.Shader",module:"Lights, Camera",submodule:"Shaders"},{file:"src/webgl/p5.Shader.js",line:253,itemtype:"method",name:"useProgram",chainable:1,access:"private",tagname:"",class:"p5.Shader",module:"Lights, Camera",submodule:"Shaders"},{file:"src/webgl/p5.Shader.js",line:264,description:"

Wrapper around gl.uniform functions.\nAs we store uniform info in the shader we can use that\nto do type checking on the supplied data and call\nthe appropriate function.

\n",itemtype:"method",name:"setUniform",chainable:1,params:[{name:"uniformName",description:"

the name of the uniform in the\nshader program

\n",type:"String"},{name:"data",description:"

the data to be associated with that uniform; type\nvaries (could be a single numerical value, array, matrix, or\ntexture / sampler reference)

\n",type:"Object"}],class:"p5.Shader",module:"Lights, Camera",submodule:"Shaders"},{file:"src/webgl/p5.Shader.js",line:394,itemtype:"method",name:"enableAttrib",chainable:1,access:"private",tagname:"",class:"p5.Shader",module:"Lights, Camera",submodule:"Shaders"},{file:"src/webgl/p5.Texture.js",line:66,description:"

Initializes common texture parameters, creates a gl texture,\ntries to upload the texture for the first time if data is\nalready available.

\n",access:"private",tagname:"",itemtype:"method",name:"init",class:"p5.Texture",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/p5.Texture.js",line:98,description:"

Checks if the source data for this texture has changed (if it's\neasy to do so) and reuploads the texture if necessary. If it's not\npossible or to expensive to do a calculation to determine wheter or\nnot the data has occurred, this method simply re-uploads the texture.

\n",itemtype:"method",name:"update",class:"p5.Texture",module:"Lights, Camera",submodule:"Material"},{ +file:"src/webgl/p5.Texture.js",line:185,description:"

Binds the texture to the appropriate GL target.

\n",itemtype:"method",name:"bindTexture",class:"p5.Texture",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/p5.Texture.js",line:199,description:"

Unbinds the texture from the appropriate GL target.

\n",itemtype:"method",name:"unbindTexture",class:"p5.Texture",module:"Lights, Camera",submodule:"Material"},{file:"src/webgl/primitives.js",line:13,description:"

Draw a plane with given a width and height

\n",itemtype:"method",name:"plane",params:[{name:"width",description:"

width of the plane

\n",type:"Number"},{name:"height",description:"

height of the plane

\n",type:"Number"},{name:"detailX",description:"

Optional number of triangle\n subdivisions in x-dimension

\n",type:"Number",optional:!0},{name:"detailY",description:"

Optional number of triangle\n subdivisions in y-dimension

\n",type:"Number",optional:!0}],return:{description:"the p5 object",type:"P5"},example:["\n
\n\n//draw a plane with width 200 and height 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n plane(50, 50);\n}\n\n
"],alt:"Nothing displayed on canvas\nRotating interior view of a box with sides that change color.\n3d red and green gradient.\nRotating interior view of a cylinder with sides that change color.\nRotating view of a cylinder with sides that change color.\n3d red and green gradient.\nrotating view of a multi-colored cylinder with concave sides.",class:"p5",module:"Shape",submodule:"3D Primitives"},{file:"src/webgl/primitives.js",line:93,description:"

Draw a box with given width, height and depth

\n",itemtype:"method",name:"box",params:[{name:"width",description:"

width of the box

\n",type:"Number"},{name:"Height",description:"

height of the box

\n",type:"Number",optional:!0},{name:"depth",description:"

depth of the box

\n",type:"Number",optional:!0},{name:"detailX",description:"

Optional number of triangle\n subdivisions in x-dimension

\n",type:"Number",optional:!0},{name:"detailY",description:"

Optional number of triangle\n subdivisions in y-dimension

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\n//draw a spinning box with width, height and depth 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(200, 200, 200);\n}\n\n
"],class:"p5",module:"Shape",submodule:"3D Primitives"},{file:"src/webgl/primitives.js",line:190,description:"

Draw a sphere with given radius

\n",itemtype:"method",name:"sphere",params:[{name:"radius",description:"

radius of circle

\n",type:"Number"},{name:"detailX",description:"

number of segments,\n the more segments the smoother geometry\n default is 24

\n",type:"Number",optional:!0},{name:"detailY",description:"

number of segments,\n the more segments the smoother geometry\n default is 16

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\n// draw a sphere with radius 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n sphere(50);\n}\n\n
"],class:"p5",module:"Shape",submodule:"3D Primitives"},{file:"src/webgl/primitives.js",line:265,access:"private",tagname:"helper function for creating both cones and cyllinders",class:"p5",module:"Shape",submodule:"3D Primitives"},{file:"src/webgl/primitives.js",line:343,description:"

Draw a cylinder with given radius and height

\n",itemtype:"method",name:"cylinder",params:[{name:"radius",description:"

radius of the surface

\n",type:"Number"},{name:"height",description:"

height of the cylinder

\n",type:"Number"},{name:"detailX",description:"

number of segments,\n the more segments the smoother geometry\n default is 24

\n",type:"Number",optional:!0},{name:"detailY",description:"

number of segments in y-dimension,\n the more segments the smoother geometry\n default is 16

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\n//draw a spinning cylinder with radius 200 and height 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cylinder(200, 200);\n}\n\n
"],class:"p5",module:"Shape",submodule:"3D Primitives"},{file:"src/webgl/primitives.js",line:409,description:"

Draw a cone with given radius and height

\n",itemtype:"method",name:"cone",params:[{name:"radius",description:"

radius of the bottom surface

\n",type:"Number"},{name:"height",description:"

height of the cone

\n",type:"Number"},{name:"detailX",description:"

number of segments,\n the more segments the smoother geometry\n default is 24

\n",type:"Number",optional:!0},{name:"detailY",description:"

number of segments,\n the more segments the smoother geometry\n default is 16

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\n//draw a spinning cone with radius 200 and height 200\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cone(200, 200);\n}\n\n
"],class:"p5",module:"Shape",submodule:"3D Primitives"},{file:"src/webgl/primitives.js",line:475,description:"

Draw an ellipsoid with given radius

\n",itemtype:"method",name:"ellipsoid",params:[{name:"radiusx",description:"

xradius of circle

\n",type:"Number"},{name:"radiusy",description:"

yradius of circle

\n",type:"Number"},{name:"radiusz",description:"

zradius of circle

\n",type:"Number"},{name:"detailX",description:"

number of segments,\n the more segments the smoother geometry\n default is 24. Avoid detail number above\n 150, it may crash the browser.

\n",type:"Number",optional:!0},{name:"detailY",description:"

number of segments,\n the more segments the smoother geometry\n default is 16. Avoid detail number above\n 150, it may crash the browser.

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\n// draw an ellipsoid with radius 20, 30 and 40.\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n ellipsoid(20, 30, 40);\n}\n\n
"],class:"p5",module:"Shape",submodule:"3D Primitives"},{file:"src/webgl/primitives.js",line:556,description:"

Draw a torus with given radius and tube radius

\n",itemtype:"method",name:"torus",params:[{name:"radius",description:"

radius of the whole ring

\n",type:"Number"},{name:"tubeRadius",description:"

radius of the tube

\n",type:"Number"},{name:"detailX",description:"

number of segments in x-dimension,\n the more segments the smoother geometry\n default is 24

\n",type:"Number",optional:!0},{name:"detailY",description:"

number of segments in y-dimension,\n the more segments the smoother geometry\n default is 16

\n",type:"Number",optional:!0}],chainable:1,example:["\n
\n\n//draw a spinning torus with radius 200 and tube radius 60\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n torus(200, 60);\n}\n\n
"],class:"p5",module:"Shape",submodule:"3D Primitives"},{file:"src/webgl/primitives.js",line:860,description:"

Draw a line given two points

\n",params:[{name:"x0",description:"

x-coordinate of first vertex

\n",type:"Number"},{name:"y0",description:"

y-coordinate of first vertex

\n",type:"Number"},{name:"z0",description:"

z-coordinate of first vertex

\n",type:"Number"},{name:"x1",description:"

x-coordinate of second vertex

\n",type:"Number"},{name:"y1",description:"

y-coordinate of second vertex

\n",type:"Number"},{name:"z1",description:"

z-coordinate of second vertex

\n",type:"Number"}],chainable:1,example:["\n
\n\n//draw a line\nfunction setup(){\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw(){\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n // Use fill instead of stroke to change the color of shape.\n fill(255, 0, 0);\n line(10, 10, 0, 60, 60, 20);\n}\n\n
"],class:"p5",module:"Shape",submodule:"3D Primitives"},{file:"lib/addons/p5.dom.js",line:41,description:"

Searches the page for an element with the given ID, class, or tag name (using the '#' or '.'\nprefixes to specify an ID or class respectively, and none for a tag) and returns it as\na p5.Element. If a class or tag name is given with more than 1 element,\nonly the first element will be returned.\nThe DOM node itself can be accessed with .elt.\nReturns null if none found. You can also specify a container to search within.

\n",itemtype:"method",name:"select",params:[{name:"name",description:"

id, class, or tag name of element to search for

\n",type:"String"},{name:"container",description:"

id, p5.Element, or HTML element to search within

\n",type:"String",optional:!0}],return:{description:"p5.Element containing node found",type:"Object|p5.Element|Null"},example:["\n
\nfunction setup() {\n createCanvas(100,100);\n //translates canvas 50px down\n select('canvas').position(100, 100);\n}\n
\n
\n// these are all valid calls to select()\nvar a = select('#moo');\nvar b = select('#blah', '#myContainer');\nvar c = select('#foo', b);\nvar d = document.getElementById('beep');\nvar e = select('p', d);\n
\n"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:100,description:"

Searches the page for elements with the given class or tag name (using the '.' prefix\nto specify a class and no prefix for a tag) and returns them as p5.Elements\nin an array.\nThe DOM node itself can be accessed with .elt.\nReturns an empty array if none found.\nYou can also specify a container to search within.

\n",itemtype:"method",name:"selectAll",params:[{name:"name",description:"

class or tag name of elements to search for

\n",type:"String"},{name:"container",description:"

id, p5.Element, or HTML element to search within

\n",type:"String",optional:!0}],return:{description:"Array of p5.Elements containing nodes found",type:"Array"},example:["\n
\nfunction setup() {\n createButton('btn');\n createButton('2nd btn');\n createButton('3rd btn');\n var buttons = selectAll('button');\n\n for (var i = 0; i < buttons.length; i++){\n buttons[i].size(100,100);\n }\n}\n
\n
\n// these are all valid calls to selectAll()\nvar a = selectAll('.moo');\nvar b = selectAll('div');\nvar c = selectAll('button', '#myContainer');\nvar d = select('#container');\nvar e = selectAll('p', d);\nvar f = document.getElementById('beep');\nvar g = select('.blah', f);\n
\n"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:156,description:"

Helper function for select and selectAll

\n",class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:172,description:"

Helper function for getElement and getElements.

\n",class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:199,description:"

Removes all elements created by p5, except any canvas / graphics\nelements created by createCanvas or createGraphics.\nEvent handlers are removed, and element is removed from the DOM.

\n",itemtype:"method",name:"removeElements",example:["\n
\nfunction setup() {\n createCanvas(100, 100);\n createDiv('this is some text');\n createP('this is a paragraph');\n}\nfunction mousePressed() {\n removeElements(); // this will remove the div and p, not canvas\n}\n
\n"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:225,description:"

Helpers for create methods.

\n",class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:236,description:"

Creates a <div></div> element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n",itemtype:"method",name:"createDiv",params:[{name:"html",description:"

inner HTML for element created

\n",type:"String",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar myDiv;\nfunction setup() {\n myDiv = createDiv('this is some text');\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:253,description:"

Creates a <p></p> element in the DOM with given inner HTML. Used\nfor paragraph length text.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n",itemtype:"method",name:"createP",params:[{name:"html",description:"

inner HTML for element created

\n",type:"String",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar myP;\nfunction setup() {\n myP = createP('this is some text');\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:271,description:"

Creates a <span></span> element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n",itemtype:"method",name:"createSpan",params:[{name:"html",description:"

inner HTML for element created

\n",type:"String",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar mySpan;\nfunction setup() {\n mySpan = createSpan('this is some text');\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:297,description:"

Creates an <img> element in the DOM with given src and\nalternate text.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n",itemtype:"method",name:"createImg",params:[{name:"src",description:"

src path or url for image

\n",type:"String"},{name:"alt",description:"

alternate text to be used if image does not load

\n",type:"String",optional:!0},{name:"successCallback",description:"

callback to be called once image data is loaded

\n",type:"Function",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar img;\nfunction setup() {\n img = createImg('http://p5js.org/img/asterisk-01.png');\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:342,description:"

Creates an <a></a> element in the DOM for including a hyperlink.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n",itemtype:"method",name:"createA",params:[{name:"href",description:"

url of page to link to

\n",type:"String"},{name:"html",description:"

inner html of link element to display

\n",type:"String"},{name:"target",description:"

target where new link should open,\n could be _blank, _self, _parent, _top.

\n",type:"String",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar myLink;\nfunction setup() {\n myLink = createA('http://p5js.org/', 'this is a link');\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:369,class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:372,description:"

Creates a slider <input></input> element in the DOM.\nUse .size() to set the display length of the slider.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n",itemtype:"method",name:"createSlider",params:[{name:"min",description:"

minimum value of the slider

\n",type:"Number"},{name:"max",description:"

maximum value of the slider

\n",type:"Number"},{name:"value",description:"

default value of the slider

\n",type:"Number",optional:!0},{name:"step",description:"

step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value)

\n",type:"Number",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar slider;\nfunction setup() {\n slider = createSlider(0, 255, 100);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n var val = slider.value();\n background(val);\n}\n
\n\n
\nvar slider;\nfunction setup() {\n colorMode(HSB);\n slider = createSlider(0, 360, 60, 40);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n var val = slider.value();\n background(val, 100, 100, 1);\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:428,description:"

Creates a <button></button> element in the DOM.\nUse .size() to set the display size of the button.\nUse .mousePressed() to specify behavior on press.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n",itemtype:"method",name:"createButton",params:[{name:"label",description:"

label displayed on the button

\n",type:"String"},{name:"value",description:"

value of the button

\n",type:"String",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar button;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n button = createButton('click me');\n button.position(19, 19);\n button.mousePressed(changeBG);\n}\n\nfunction changeBG() {\n var val = random(255);\n background(val);\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:463,description:"

Creates a checkbox <input></input> element in the DOM.\nCalling .checked() on a checkbox returns if it is checked or not

\n",itemtype:"method",name:"createCheckbox",params:[{name:"label",description:"

label displayed after checkbox

\n",type:"String",optional:!0},{name:"value",description:"

value of the checkbox; checked is true, unchecked is false.Unchecked if no value given

\n",type:"Boolean",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar checkbox;\n\nfunction setup() {\n checkbox = createCheckbox('label', false);\n checkbox.changed(myCheckedEvent);\n}\n\nfunction myCheckedEvent() {\n if (this.checked()) {\n console.log(\"Checking!\");\n } else {\n console.log(\"Unchecking!\");\n }\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:528,description:"

Creates a dropdown menu <select></select> element in the DOM.\nIt also helps to assign select-box methods to p5.Element when selecting existing select box

\n",itemtype:"method",name:"createSelect",return:{description:"",type:"p5.Element"},example:["\n
\nvar sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n var item = sel.value();\n background(200);\n text(\"it's a \"+item+\"!\", 50, 50);\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom",overloads:[{line:528,params:[{name:"multiple",description:"

true if dropdown should support multiple selections

\n",type:"Boolean",optional:!0}],return:{description:"",type:"p5.Element"}},{line:556,params:[{name:"existing",description:"

DOM select element

\n",type:"Object"}],return:{description:"",type:"p5.Element"}}]},{file:"lib/addons/p5.dom.js",line:633,description:"

Creates a radio button <input></input> element in the DOM.\nThe .option() method can be used to set options for the radio after it is\ncreated. The .value() method will return the currently selected option.

\n",itemtype:"method",name:"createRadio",params:[{name:"divId",description:"

the id and name of the created div and input field respectively

\n",type:"String",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option(\"black\");\n radio.option(\"white\");\n radio.option(\"gray\");\n radio.style('width', '60px');\n textAlign(CENTER);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n var val = radio.value();\n background(val);\n text(val, width/2, height/2);\n}\n
\n
\nvar radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('apple', 1);\n radio.option('bread', 2);\n radio.option('juice', 3);\n radio.style('width', '60px');\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n var val = radio.value();\n if (val) {\n text('item cost is $'+val, width/2, height/2);\n }\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:759,description:"

Creates an <input></input> element in the DOM for text input.\nUse .size() to set the display length of the box.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n",itemtype:"method",name:"createInput",params:[{name:"value",description:"

default value of the input box

\n",type:"Number",optional:!0},{name:"type",description:"

type of text, ie text, password etc. Defaults to text

\n",type:"String",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nfunction setup(){\n var inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent(){\n console.log('you are typing: ', this.value());\n}\n\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:789,description:"

Creates an <input></input> element in the DOM of type 'file'.\nThis allows users to select local files for use in a sketch.

\n",itemtype:"method",name:"createFileInput",params:[{name:"callback",description:"

callback function for when a file loaded

\n",type:"Function",optional:!0},{name:"multiple",description:"

optional to allow multiple files selected

\n",type:"String",optional:!0}],return:{description:"pointer to p5.Element holding created DOM element",type:"Object|p5.Element"},example:["\nvar input;\nvar img;\n\nfunction setup() {\n input = createFileInput(handleFile);\n input.position(0, 0);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction handleFile(file) {\n print(file);\n if (file.type === 'image') {\n img = createImg(file.data);\n img.hide();\n }\n}"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:874,class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:911,description:'

Creates an HTML5 <video> element in the DOM for simple playback\nof audio/video. Shown by default, can be hidden with .hide()\nand drawn into canvas using video(). Appends to the container\nnode if one is specified, otherwise appends to body. The first parameter\ncan be either a single string path to a video file, or an array of string\npaths to different formats of the same video. This is useful for ensuring\nthat your video can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats.

\n',itemtype:"method",name:"createVideo",params:[{name:"src",description:"

path to a video file, or array of paths for\n supporting different browsers

\n",type:"String|Array"},{name:"callback",description:"

callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content

\n",type:"Object",optional:!0}],return:{description:"pointer to video p5.Element",type:"p5.MediaElement|p5.Element"},class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:937,class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:939,description:'

Creates a hidden HTML5 <audio> element in the DOM for simple audio\nplayback. Appends to the container node if one is specified,\notherwise appends to body. The first parameter\ncan be either a single string path to a audio file, or an array of string\npaths to different formats of the same audio. This is useful for ensuring\nthat your audio can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats.

\n',itemtype:"method",name:"createAudio",params:[{name:"src",description:"

path to an audio file, or array of paths for\n supporting different browsers

\n",type:"String|Array"},{name:"callback",description:"

callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content

\n",type:"Object",optional:!0}],return:{description:"pointer to audio p5.Element",type:"p5.MediaElement|p5.Element"},class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:965,class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:998,description:'

Creates a new <video> element that contains the audio/video feed\nfrom a webcam. This can be drawn onto the canvas using video().

\n

More specific properties of the feed can be passing in a Constraints object.\nSee the\n W3C\nspec for possible properties. Note that not all of these are supported\nby all browsers.

\n

Security note: A new browser security specification requires that getUserMedia,\nwhich is behind createCapture(), only works when you're running the code locally,\nor on HTTPS. Learn more here\nand here.

',itemtype:"method",name:"createCapture",params:[{name:"type",description:"

type of capture, either VIDEO or\n AUDIO if none specified, default both,\n or a Constraints object

\n",type:"String|Constant|Object"},{name:"callback",description:"

function to be called once\n stream has loaded

\n",type:"Function"}],return:{description:"capture video p5.Element",type:"Object|p5.Element"},example:["\n
\nvar capture;\n\nfunction setup() {\n createCanvas(480, 120);\n capture = createCapture(VIDEO);\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width*capture.height/capture.width);\n filter(INVERT);\n}\n
\n
\nfunction setup() {\n createCanvas(480, 120);\n var constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [\n { maxFrameRate: 10 }\n ]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1111,description:"

Creates element with given tag in the DOM with given content.\nAppends to the container node if one is specified, otherwise\nappends to body.

\n",itemtype:"method",name:"createElement",params:[{name:"tag",description:"

tag for the new element

\n",type:"String"},{name:"content",description:"

html content to be inserted into the element

\n",type:"String",optional:!0}],return:{description:"pointer to p5.Element holding created node",type:"Object|p5.Element"},example:["\n
\nvar h2 = createElement('h2','im an h2 p5.element!');\n
"],class:"p5.dom",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1137,description:"

Adds specified class to the element.

\n",itemtype:"method",name:"addClass",params:[{name:"class",description:"

name of class to add

\n",type:"String"}],return:{description:"",type:"Object|p5.Element"},example:["\n
\n var div = createDiv('div');\n div.addClass('myClass');\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1164,description:"

Removes specified class from the element.

\n",itemtype:"method",name:"removeClass",params:[{name:"class",description:"

name of class to remove

\n",type:"String"}],return:{description:"",type:"Object|p5.Element"},class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1179,description:"

Attaches the element as a child to the parent specified.\n Accepts either a string ID, DOM node, or p5.Element.\n If no argument is specified, an array of children DOM nodes is returned.

\n",itemtype:"method",name:"child",params:[{name:"child",description:"

the ID, DOM node, or p5.Element\n to add to the current element

\n",type:"String|Object|p5.Element",optional:!0}],return:{description:"",type:"p5.Element"}, +example:["\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div0.child(div1); // use p5.Element\n
\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.id('apples');\n div0.child('apples'); // use id\n
\n
\n var div0 = createDiv('this is the parent');\n var elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1223,description:"

Centers a p5 Element either vertically, horizontally,\nor both, relative to its parent or according to\nthe body if the Element has no parent. If no argument is passed\nthe Element is aligned both vertically and horizontally.

\n",params:[{name:"align",description:"

passing 'vertical', 'horizontal' aligns element accordingly

\n",type:"String"}],return:{description:"pointer to p5.Element",type:"Object|p5.Element"},example:["\n
\nfunction setup() {\n var div = createDiv('').size(10,10);\n div.style('background-color','orange');\n div.center();\n\n}\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1276,description:"

If an argument is given, sets the inner HTML of the element,\n replacing any existing html. If true is included as a second\n argument, html is appended instead of replacing existing html.\n If no arguments are given, returns\n the inner HTML of the element.

\n",itemtype:"method",name:"html",params:[{name:"html",description:"

the HTML to be placed inside the element

\n",type:"String",optional:!0},{name:"append",description:"

whether to append HTML to existing

\n",type:"Boolean",optional:!0}],return:{description:"",type:"Object|p5.Element|String"},example:["\n
\n var div = createDiv('').size(100,100);\n div.html('hi');\n
\n
\n var div = createDiv('Hello ').size(100,100);\n div.html('World', true);\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1311,description:"

Sets the position of the element relative to (0, 0) of the\n window. Essentially, sets position:absolute and left and top\n properties of style. If no arguments given returns the x and y position\n of the element in an object.

\n",itemtype:"method",name:"position",params:[{name:"x",description:"

x-position relative to upper left of window

\n",type:"Number",optional:!0},{name:"y",description:"

y-position relative to upper left of window

\n",type:"Number",optional:!0}],return:{description:"",type:"Object|p5.Element"},example:["\n
\n function setup() {\n var cnv = createCanvas(100, 100);\n // positions canvas 50px to the right and 100px\n // below upper left corner of the window\n cnv.position(50, 100);\n }\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1392,description:"

Sets the given style (css) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if the single argument\nis given in css syntax ('text-align:center'), .style() sets the css\nappropriatly. .style() also handles 2d and 3d css transforms. If\nthe 1st arg is 'rotate', 'translate', or 'position', the following arguments\naccept Numbers as values. ('translate', 10, 100, 50);

\n",itemtype:"method",name:"style",params:[{name:"property",description:"

property to be set

\n",type:"String"},{name:"value",description:"

value to assign to property (only String|Number for rotate/translate)

\n",type:"String|Number|p5.Color",optional:!0}],return:{description:"value of property, if no value is specified\nor p5.Element",type:"String|Object|p5.Element"},example:['\n
\nvar myDiv = createDiv("I like pandas.");\nmyDiv.style("font-size", "18px");\nmyDiv.style("color", "#ff0000");\n
\n
\nvar col = color(25,23,200,50);\nvar button = createButton("button");\nbutton.style("background-color", col);\nbutton.position(10, 10);\n
\n
\nvar myDiv = createDiv("I like lizards.");\nmyDiv.style("position", 20, 20);\nmyDiv.style("rotate", 45);\n
\n
\nvar myDiv;\nfunction setup() {\n background(200);\n myDiv = createDiv("I like gray.");\n myDiv.position(20, 20);\n}\n\nfunction draw() {\n myDiv.style("font-size", mouseX+"px");\n}\n
'],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1474,description:"

Adds a new attribute or changes the value of an existing attribute\n on the specified element. If no value is specified, returns the\n value of the given attribute, or null if attribute is not set.

\n",itemtype:"method",name:"attribute",params:[{name:"attr",description:"

attribute to set

\n",type:"String"},{name:"value",description:"

value to assign to attribute

\n",type:"String",optional:!0}],return:{description:"value of attribute, if no value is\n specified or p5.Element",type:"String|Object|p5.Element"},example:['\n
\n var myDiv = createDiv("I like pandas.");\n myDiv.attribute("align", "center");\n
'],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1514,description:"

Removes an attribute on the specified element.

\n",itemtype:"method",name:"removeAttribute",params:[{name:"attr",description:"

attribute to remove

\n",type:"String"}],return:{description:"",type:"Object|p5.Element"},example:["\n
\n var button;\n var checkbox;\nfunction setup() {\n checkbox = createCheckbox('enable', true);\n checkbox.changed(enableButton);\n button = createButton('button');\n button.position(10, 10);\n }\nfunction enableButton() {\n if( this.checked() ) {\n // Re-enable the button\n button.removeAttribute('disabled');\n } else {\n // Disable the button\n button.attribute('disabled','');\n }\n }\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1558,description:"

Either returns the value of the element if no arguments\ngiven, or sets the value of the element.

\n",itemtype:"method",name:"value",params:[{name:"value",description:"",type:"String|Number",optional:!0}],return:{description:"value of element if no value is specified or p5.Element",type:"String|Object|p5.Element"},example:["\n
\n// gets the value\nvar inp;\nfunction setup() {\n inp = createInput('');\n}\n\nfunction mousePressed() {\n print(inp.value());\n}\n
\n
\n// sets the value\nvar inp;\nfunction setup() {\n inp = createInput('myValue');\n}\n\nfunction mousePressed() {\n inp.value(\"myValue\");\n}\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1601,description:"

Shows the current element. Essentially, setting display:block for the style.

\n",itemtype:"method",name:"show",return:{description:"",type:"Object|p5.Element"},example:["\n
\n var div = createDiv('div');\n div.style(\"display\", \"none\");\n div.show(); // turns display to block\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1619,description:"

Hides the current element. Essentially, setting display:none for the style.

\n",itemtype:"method",name:"hide",return:{description:"",type:"Object|p5.Element"},example:["\n
\nvar div = createDiv('this is a div');\ndiv.hide();\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1635,description:"

Sets the width and height of the element. AUTO can be used to\n only adjust one dimension. If no arguments given returns the width and height\n of the element in an object.

\n",itemtype:"method",name:"size",params:[{name:"w",description:"

width of the element

\n",type:"Number",optional:!0},{name:"h",description:"

height of the element

\n",type:"Number",optional:!0}],return:{description:"",type:"Object|p5.Element"},example:["\n
\n var div = createDiv('this is a div');\n div.size(100, 100);\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1701,description:"

Removes the element and deregisters all listeners.

\n",itemtype:"method",name:"remove",example:["\n
\nvar myDiv = createDiv('this is some text');\nmyDiv.remove();\n
"],class:"p5.Element",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1750,description:"

Path to the media element source.

\n",itemtype:"property",name:"src",return:{description:"src",type:"String"},example:["\n
\nvar ele;\n\nfunction setup() {\n background(250);\n\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/beat.mp3');\n\n //We'll set up our example so that\n //when you click on the text,\n //an alert box displays the MediaElement's\n //src field.\n textAlign(CENTER);\n text(\"Click Me!\", width/2, height/2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if(mouseX >= 0 && mouseX <= width &&\n mouseY >= 0 && mouseY <= height) {\n //Show our p5.MediaElement's src field\n alert(ele.src);\n }\n}\n\n
"],class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1820,description:"

Play an HTML5 media element.

\n",itemtype:"method",name:"play",return:{description:"",type:"Object|p5.Element"},example:['\n
\nvar ele;\n\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio(\'assets/beat.mp3\');\n\n background(250);\n textAlign(CENTER);\n text("Click to Play!", width/2, height/2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it\'s clicked\n if(mouseX >= 0 && mouseX <= width &&\n mouseY >= 0 && mouseY <= height) {\n\n //Here we call the play() function on\n //the p5.MediaElement we created above.\n //This will start the audio sample.\n ele.play();\n\n background(200);\n text("You clicked Play!", width/2, height/2);\n }\n}\n
'],class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1875,description:"

Stops an HTML5 media element (sets current time to zero).

\n",itemtype:"method",name:"stop",return:{description:"",type:"Object|p5.Element"},example:['\n
\n\n//This example both starts \n//and stops a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n\n//while our audio is playing,\n//this will be set to true\nvar sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio(\'assets/beat.mp3\');\n background(200);\n textAlign(CENTER);\n text("Click to play!", width/2, height/2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it\'s clicked\n if(mouseX >= 0 && mouseX <= width &&\n mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if(sampleIsPlaying) {\n //if the sample is currently playing\n //calling the stop() function on\n //our p5.MediaElement will stop\n //it and reset its current\n //time to 0 (i.e. it will start\n //at the beginning the next time\n //you play it)\n ele.stop();\n\n sampleIsPlaying = false;\n text("Click to play!", width/2, height/2);\n } else {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop(); \n\n sampleIsPlaying = true;\n text("Click to stop!", width/2, height/2);\n }\n }\n}\n\n
'],class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:1942,description:"

Pauses an HTML5 media element.

\n",itemtype:"method",name:"pause",return:{description:"",type:"Object|p5.Element"},example:['\n
\n//This example both starts\n//and pauses a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n\n//while our audio is playing,\n//this will be set to true\nvar sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio(\'assets/lucky_dragons_-_power_melody.mp3\');\n background(200);\n textAlign(CENTER);\n text("Click to play!", width/2, height/2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it\'s clicked\n if(mouseX >= 0 && mouseX <= width &&\n mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if(sampleIsPlaying) {\n //Calling pause() on our\n //p5.MediaElement will stop it\n //playing, but when we call the\n //loop() or play() functions\n //the sample will start from\n //where we paused it.\n ele.pause();\n\n sampleIsPlaying = false;\n text("Click to resume!", width/2, height/2);\n } else {\n //loop our sound element until we\n //call ele.pause() on it.\n ele.loop(); \n\n sampleIsPlaying = true;\n text("Click to pause!", width/2, height/2);\n }\n }\n}\n\n
'],class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2006,description:"

Set 'loop' to true for an HTML5 media element, and starts playing.

\n",itemtype:"method",name:"loop",return:{description:"",type:"Object|p5.Element"},example:['\n
\n//Clicking the canvas will loop\n//the audio sample until the user\n//clicks again to stop it\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n\n//while our audio is playing,\n//this will be set to true\nvar sampleIsLooping = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio(\'assets/lucky_dragons_-_power_melody.mp3\');\n background(200);\n textAlign(CENTER);\n text("Click to loop!", width/2, height/2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it\'s clicked\n if(mouseX >= 0 && mouseX <= width &&\n mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if(sampleIsLooping == false) {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop();\n\n sampleIsLooping = true;\n text("Click to stop!", width/2, height/2);\n } else {\n ele.stop();\n\n sampleIsLooping = false;\n text("Click to loop!", width/2, height/2);\n }\n }\n}\n\n
'],class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2064,description:"

Set 'loop' to false for an HTML5 media element. Element will stop\nwhen it reaches the end.

\n",itemtype:"method",name:"noLoop",return:{description:"",type:"Object|p5.Element"},class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2077,description:"

Set HTML5 media element to autoplay or not.

\n",itemtype:"method",name:"autoplay",params:[{name:"autoplay",description:"

whether the element should autoplay

\n",type:"Boolean"}],return:{description:"",type:"Object|p5.Element"},class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2089,description:"

Sets volume for this HTML5 media element. If no argument is given,\nreturns the current volume.

\n",params:[{name:"val",description:"

volume between 0.0 and 1.0

\n",type:"Number",optional:!0}],return:{description:"current volume or p5.MediaElement",type:"Number|p5.MediaElement"},itemtype:"method",name:"volume",class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2105,description:"

If no arguments are given, returns the current playback speed of the\nelement. The speed parameter sets the speed where 2.0 will play the\nelement twice as fast, 0.5 will play at half the speed, and -1 will play\nthe element in normal speed in reverse.(Note that not all browsers support\nbackward playback and even if they do, playback might not be smooth.)

\n",itemtype:"method",name:"speed",params:[{name:"speed",description:"

speed multiplier for element playback

\n",type:"Number",optional:!0}],return:{description:"current playback speed or p5.MediaElement",type:"Number|Object|p5.MediaElement"},class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2124,description:"

If no arguments are given, returns the current time of the element.\nIf an argument is given the current time of the element is set to it.

\n",itemtype:"method",name:"time",params:[{name:"time",description:"

time to jump to (in seconds)

\n",type:"Number",optional:!0}],return:{description:"current time (in seconds)\n or p5.MediaElement",type:"Number|Object|p5.MediaElement"},class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2141,description:"

Returns the duration of the HTML5 media element.

\n",itemtype:"method",name:"duration",return:{description:"duration",type:"Number"},class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2201,description:"

helper method for web GL mode to figure out if the element\nhas been modified and might need to be re-uploaded to texture\nmemory between frames.

\n",itemtype:"method",name:"isModified",access:"private",tagname:"",return:{description:"a boolean indicating whether or not the\nimage has been updated or modified since last texture upload.",type:"Boolean"},class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2213,description:"

helper method for web GL mode to indicate that an element has been\nchanged or unchanged since last upload. gl texture upload will\nset this value to false after uploading the texture; or might set\nit to true if metadata has become available but there is no actual\ntexture data available yet..

\n",itemtype:"method",name:"setModified",params:[{name:"val",description:"

sets whether or not the element has been\nmodified.

\n",type:"Boolean"}],access:"private",tagname:"",class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2227,description:"

Schedule an event to be called when the audio or video\nelement reaches the end. If the element is looping,\nthis will not be called. The element is passed in\nas the argument to the onended callback.

\n",itemtype:"method",name:"onended",params:[{name:"callback",description:"

function to call when the\n soundfile has ended. The\n media element will be passed\n in as the argument to the\n callback.

\n",type:"Function"}],return:{description:"",type:"Object|p5.MediaElement"},example:["\n
\nfunction setup() {\n audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls(true);\n audioEl.onended(sayDone);\n}\n\nfunction sayDone(elt) {\n alert('done playing ' + elt.src );\n}\n
"],class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2259,class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2261,description:"

Send the audio output of this element to a specified audioNode or\np5.sound object. If no element is provided, connects to p5's master\noutput. That connection is established when this method is first called.\nAll connections are removed by the .disconnect() method.

\n

This method is meant to be used with the p5.sound.js addon library.

\n",itemtype:"method",name:"connect",params:[{name:"audioNode",description:"

AudioNode from the Web Audio API,\nor an object from the p5.sound library

\n",type:"AudioNode|Object"}],class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2313,description:"

Disconnect all Web Audio routing, including to master output.\nThis is useful if you want to re-route the output through\naudio effects, for example.

\n",itemtype:"method",name:"disconnect",class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2329,class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2331,description:"

Show the default MediaElement controls, as determined by the web browser.

\n",itemtype:"method",name:"showControls",class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2342,description:"

Hide the default mediaElement controls.

\n",itemtype:"method",name:"hideControls",class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2351,class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2353,description:"

Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.

\n

Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.

\n

Time will be passed as the first parameter to the callback function,\nand param will be the second parameter.

\n",itemtype:"method",name:"addCue",params:[{name:"time",description:"

Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.

\n",type:"Number"},{name:"callback",description:"

Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.

\n",type:"Function"},{name:"value",description:"

An object to be passed as the\n second parameter to the\n callback function.

\n",type:"Object",optional:!0}],return:{description:"id ID of this cue,\n useful for removeCue(id)",type:"Number"},example:["\n
\nfunction setup() {\n background(255,255,255);\n\n audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n\n // schedule three calls to changeBackground\n audioEl.addCue(0.5, changeBackground, color(255,0,0) );\n audioEl.addCue(1.0, changeBackground, color(0,255,0) );\n audioEl.addCue(2.5, changeBackground, color(0,0,255) );\n audioEl.addCue(3.0, changeBackground, color(0,255,255) );\n audioEl.addCue(4.2, changeBackground, color(255,255,0) );\n audioEl.addCue(5.0, changeBackground, color(255,255,0) );\n}\n\nfunction changeBackground(val) {\n background(val);\n}\n
"],class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2415,description:"

Remove a callback based on its ID. The ID is returned by the\naddCue method.

\n",itemtype:"method",name:"removeCue",params:[{name:"id",description:"

ID of the cue, as returned by addCue

\n",type:"Number"}],class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2435,description:"

Remove all of the callbacks that had originally been scheduled\nvia the addCue method.

\n",itemtype:"method",name:"clearCues",class:"p5.MediaElement",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2491,description:"

Underlying File object. All normal File methods can be called on this.

\n",itemtype:"property",name:"file",class:"p5.File",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2503,description:"

File type (image, text, etc.)

\n",itemtype:"property",name:"type",class:"p5.File",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2509,description:"

File subtype (usually the file extension jpg, png, xml, etc.)

\n",itemtype:"property",name:"subtype",class:"p5.File",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2515,description:"

File name

\n",itemtype:"property",name:"name",class:"p5.File",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2521,description:"

File size

\n",itemtype:"property",name:"size",class:"p5.File",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.dom.js",line:2528,description:"

URL string containing image data.

\n",itemtype:"property",name:"data",class:"p5.File",module:"p5.dom",submodule:"p5.dom"},{file:"lib/addons/p5.sound.js",line:46,description:'

p5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound

\n

From the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors

\n

MIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE

\n

Some of the many audio libraries & resources that inspire p5.sound:

\n\n',class:"p5.sound",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:212,description:"

Returns the Audio Context for this sketch. Useful for users\nwho would like to dig deeper into the Web Audio API\n.

",itemtype:"method",name:"getAudioContext",return:{description:"AudioContext for this sketch",type:"Object"},class:"p5.sound",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:226,description:"

Determine which filetypes are supported (inspired by buzz.js)\nThe audio element (el) will only be used to test browser support for various audio formats

\n",class:"p5.sound",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:296,description:"

Master contains AudioContext and the master sound output.

\n",class:"p5.sound",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:331,description:"

Returns a number representing the master amplitude (volume) for sound\nin this sketch.

\n",itemtype:"method",name:"getMasterVolume",return:{description:"Master amplitude (volume) for sound in this sketch.\n Should be between 0.0 (silence) and 1.0.",type:"Number"},class:"p5.sound",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:342,description:"

Scale the output of all sound in this sketch

\nScaled between 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a rampTime parameter. For more\ncomplex fades, see the Env class.\n\nAlternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.\n\n

How This Works: When you load the p5.sound module, it\ncreates a single instance of p5sound. All sound objects in this\nmodule output to p5sound before reaching your computer's output.\nSo if you change the amplitude of p5sound, it impacts all of the\nsound in this module.

\n\n

If no value is provided, returns a Web Audio API Gain Node

",itemtype:"method",name:"masterVolume",params:[{name:"volume",description:"

Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator

\n",type:"Number|Object"},{name:"rampTime",description:"

Fade for t seconds

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

Schedule this event to happen at\n t seconds in the future

\n",type:"Number",optional:!0}],class:"p5.sound",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:384,description:"

p5.soundOut is the p5.sound master output. It sends output to\nthe destination of this window's web audio context. It contains\nWeb Audio API nodes including a dyanmicsCompressor (.limiter),\nand Gain Nodes for .input and .output.

\n",itemtype:"property",name:"soundOut",type:"Object",class:"p5.sound",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:393,description:"

a silent connection to the DesinationNode\nwhich will ensure that anything connected to it\nwill not be garbage collected

\n",access:"private",tagname:"",class:"p5.sound",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:412,description:"

Returns a number representing the sample rate, in samples per second,\nof all sound objects in this audio context. It is determined by the\nsampling rate of your operating system's sound card, and it is not\ncurrently possile to change.\nIt is often 44100, or twice the range of human hearing.

\n",itemtype:"method",name:"sampleRate",return:{description:"samplerate samples per second",type:"Number"},class:"p5",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:425,description:"

Returns the closest MIDI note value for\na given frequency.

\n",params:[{name:"frequency",description:"

A freqeuncy, for example, the "A"\n above Middle C is 440Hz

\n",type:"Number"}],return:{description:"MIDI note value",type:"Number"},class:"p5",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:438, +description:"

Returns the frequency value of a MIDI note value.\nGeneral MIDI treats notes as integers where middle C\nis 60, C# is 61, D is 62 etc. Useful for generating\nmusical frequencies with oscillators.

\n",itemtype:"method",name:"midiToFreq",params:[{name:"midiNote",description:"

The number of a MIDI note

\n",type:"Number"}],return:{description:"Frequency value of the given MIDI note",type:"Number"},example:["\n
\nvar notes = [60, 64, 67, 72];\nvar i = 0;\n\nfunction setup() {\n osc = new p5.Oscillator('Triangle');\n osc.start();\n frameRate(1);\n}\n\nfunction draw() {\n var freq = midiToFreq(notes[i]);\n osc.freq(freq);\n i++;\n if (i >= notes.length){\n i = 0;\n }\n}\n
"],class:"p5",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:471,description:'

List the SoundFile formats that you will include. LoadSound\nwill search your directory for these extensions, and will pick\na format that is compatable with the client's web browser.\nHere is a free online file\nconverter.

\n',itemtype:"method",name:"soundFormats",params:[{name:"formats",description:"

i.e. 'mp3', 'wav', 'ogg'

\n",type:"String",optional:!0,multiple:!0}],example:["\n
\nfunction preload() {\n // set the global sound formats\n soundFormats('mp3', 'ogg');\n\n // load either beatbox.mp3, or .ogg, depending on browser\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n mySound.play();\n}\n
"],class:"p5",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:584,description:"

Used by Osc and Env to chain signal math

\n",class:"p5",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:869,description:'

loadSound() returns a new p5.SoundFile from a specified\npath. If called during preload(), the p5.SoundFile will be ready\nto play in time for setup() and draw(). If called outside of\npreload, the p5.SoundFile will not be ready immediately, so\nloadSound accepts a callback as the second parameter. Using a\n\nlocal server is recommended when loading external files.

\n',itemtype:"method",name:"loadSound",params:[{name:"path",description:"

Path to the sound file, or an array with\n paths to soundfiles in multiple formats\n i.e. ['sound.ogg', 'sound.mp3'].\n Alternately, accepts an object: either\n from the HTML5 File API, or a p5.File.

\n",type:"String|Array"},{name:"successCallback",description:"

Name of a function to call once file loads

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

Name of a function to call if there is\n an error loading the file.

\n",type:"Function",optional:!0},{name:"whileLoading",description:"

Name of a function to call while file is loading.\n This function will receive the percentage loaded\n so far, from 0.0 to 1.0.

\n",type:"Function",optional:!0}],return:{description:"Returns a p5.SoundFile",type:"SoundFile"},example:["\n
\nfunction preload() {\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\n
"],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:917,description:"

This is a helper function that the p5.SoundFile calls to load\nitself. Accepts a callback (the name of another function)\nas an optional parameter.

\n",access:"private",tagname:"",params:[{name:"successCallback",description:"

Name of a function to call once file loads

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

Name of a function to call if there is an error

\n",type:"Function",optional:!0}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1009,description:"

Returns true if the sound file finished loading successfully.

\n",itemtype:"method",name:"isLoaded",return:{description:"",type:"Boolean"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1022,description:"

Play the p5.SoundFile

\n",itemtype:"method",name:"play",params:[{name:"startTime",description:"

(optional) schedule playback to start (in seconds from now).

\n",type:"Number",optional:!0},{name:"rate",description:"

(optional) playback rate

\n",type:"Number",optional:!0},{name:"amp",description:"

(optional) amplitude (volume)\n of playback

\n",type:"Number",optional:!0},{name:"cueStart",description:"

(optional) cue start time in seconds

\n",type:"Number",optional:!0},{name:"duration",description:"

(optional) duration of playback in seconds

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1119,description:"

p5.SoundFile has two play modes: restart and\nsustain. Play Mode determines what happens to a\np5.SoundFile if it is triggered while in the middle of playback.\nIn sustain mode, playback will continue simultaneous to the\nnew playback. In restart mode, play() will stop playback\nand start over. Sustain is the default mode.

\n",itemtype:"method",name:"playMode",params:[{name:"str",description:"

'restart' or 'sustain'

\n",type:"String"}],example:["\n
\nfunction setup(){\n mySound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\nfunction mouseClicked() {\n mySound.playMode('sustain');\n mySound.play();\n}\nfunction keyPressed() {\n mySound.playMode('restart');\n mySound.play();\n}\n\n
"],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1161,description:"

Pauses a file that is currently playing. If the file is not\nplaying, then nothing will happen.

\n

After pausing, .play() will resume from the paused\nposition.\nIf p5.SoundFile had been set to loop before it was paused,\nit will continue to loop after it is unpaused with .play().

\n",itemtype:"method",name:"pause",params:[{name:"startTime",description:"

(optional) schedule event to occur\n seconds from now

\n",type:"Number",optional:!0}],example:["\n
\nvar soundFile;\n\nfunction preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3');\n}\nfunction setup() {\n background(0, 255, 0);\n soundFile.setVolume(0.1);\n soundFile.loop();\n}\nfunction keyTyped() {\n if (key == 'p') {\n soundFile.pause();\n background(255, 0, 0);\n }\n}\n\nfunction keyReleased() {\n if (key == 'p') {\n soundFile.play();\n background(0, 255, 0);\n }\n}\n\n
"],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1217,description:"

Loop the p5.SoundFile. Accepts optional parameters to set the\nplayback rate, playback volume, loopStart, loopEnd.

\n",itemtype:"method",name:"loop",params:[{name:"startTime",description:"

(optional) schedule event to occur\n seconds from now

\n",type:"Number",optional:!0},{name:"rate",description:"

(optional) playback rate

\n",type:"Number",optional:!0},{name:"amp",description:"

(optional) playback volume

\n",type:"Number",optional:!0},{name:"cueLoopStart",description:"

(optional) startTime in seconds

\n",type:"Number",optional:!0},{name:"duration",description:"

(optional) loop duration in seconds

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1233,description:"

Set a p5.SoundFile's looping flag to true or false. If the sound\nis currently playing, this change will take effect when it\nreaches the end of the current playback.

\n",params:[{name:"Boolean",description:"

set looping to true or false

\n",type:"Boolean"}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1253,description:"

Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.

\n",return:{description:"",type:"Boolean"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1267,description:"

Returns true if a p5.SoundFile is playing, false if not (i.e.\npaused or stopped).

\n",itemtype:"method",name:"isPlaying",return:{description:"",type:"Boolean"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1277,description:"

Returns true if a p5.SoundFile is paused, false if not (i.e.\nplaying or stopped).

\n",itemtype:"method",name:"isPaused",return:{description:"",type:"Boolean"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1287,description:"

Stop soundfile playback.

\n",itemtype:"method",name:"stop",params:[{name:"startTime",description:"

(optional) schedule event to occur\n in seconds from now

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1311,description:"

Stop playback on all of this soundfile's sources.

\n",access:"private",tagname:"",class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1333,description:"

Multiply the output volume (amplitude) of a sound file\nbetween 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a rampTime parameter. For more\ncomplex fades, see the Env class.

\n

Alternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.

\n",itemtype:"method",name:"setVolume",params:[{name:"volume",description:"

Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator

\n",type:"Number|Object"},{name:"rampTime",description:"

Fade for t seconds

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

Schedule this event to happen at\n t seconds in the future

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1374,description:"

Set the stereo panning of a p5.sound object to\na floating point number between -1.0 (left) and 1.0 (right).\nDefault is 0.0 (center).

\n",itemtype:"method",name:"pan",params:[{name:"panValue",description:"

Set the stereo panner

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],example:["\n
\n\n var ball = {};\n var soundFile;\n\n function setup() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/beatbox.mp3');\n }\n\n function draw() {\n background(0);\n ball.x = constrain(mouseX, 0, width);\n ellipse(ball.x, height/2, 20, 20)\n }\n\n function mousePressed(){\n // map the ball's x location to a panning degree\n // between -1.0 (left) and 1.0 (right)\n var panning = map(ball.x, 0., width,-1.0, 1.0);\n soundFile.pan(panning);\n soundFile.play();\n }\n
"],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1413,description:"

Returns the current stereo pan position (-1.0 to 1.0)

\n",return:{description:"Returns the stereo pan setting of the Oscillator\n as a number between -1.0 (left) and 1.0 (right).\n 0.0 is center and default.",type:"Number"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1423,description:"

Set the playback rate of a sound file. Will change the speed and the pitch.\nValues less than zero will reverse the audio buffer.

\n",itemtype:"method",name:"rate",params:[{name:"playbackRate",description:"

Set the playback rate. 1.0 is normal,\n .5 is half-speed, 2.0 is twice as fast.\n Values less than zero play backwards.

\n",type:"Number",optional:!0}],example:["\n
\nvar song;\n\nfunction preload() {\n song = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n song.loop();\n}\n\nfunction draw() {\n background(200);\n\n // Set the rate to a range between 0.1 and 4\n // Changing the rate also alters the pitch\n var speed = map(mouseY, 0.1, height, 0, 2);\n speed = constrain(speed, 0.01, 4);\n song.rate(speed);\n\n // Draw a circle to show what is going on\n stroke(0);\n fill(51, 100);\n ellipse(mouseX, 100, 48, 48);\n}\n\n \n
\n"],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1495,description:"

Returns the duration of a sound file in seconds.

\n",itemtype:"method",name:"duration",return:{description:"The duration of the soundFile in seconds.",type:"Number"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1509,description:"

Return the current position of the p5.SoundFile playhead, in seconds.\nNote that if you change the playbackRate while the p5.SoundFile is\nplaying, the results may not be accurate.

\n",itemtype:"method",name:"currentTime",return:{description:"currentTime of the soundFile in seconds.",type:"Number"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1525,description:"

Move the playhead of the song to a position, in seconds. Start timing\nand playback duration. If none are given, will reset the file to play\nentire duration from start to finish.

\n",itemtype:"method",name:"jump",params:[{name:"cueTime",description:"

cueTime of the soundFile in seconds.

\n",type:"Number"},{name:"duration",description:"

duration in seconds.

\n",type:"Number"}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1548,description:"

Return the number of channels in a sound file.\nFor example, Mono = 1, Stereo = 2.

\n",itemtype:"method",name:"channels",return:{description:"[channels]",type:"Number"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1558,description:"

Return the sample rate of the sound file.

\n",itemtype:"method",name:"sampleRate",return:{description:"[sampleRate]",type:"Number"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1567,description:"

Return the number of samples in a sound file.\nEqual to sampleRate * duration.

\n",itemtype:"method",name:"frames",return:{description:"[sampleCount]",type:"Number"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1577,description:"

Returns an array of amplitude peaks in a p5.SoundFile that can be\nused to draw a static waveform. Scans through the p5.SoundFile's\naudio buffer to find the greatest amplitudes. Accepts one\nparameter, 'length', which determines size of the array.\nLarger arrays result in more precise waveform visualizations.

\n

Inspired by Wavesurfer.js.

\n",itemtype:"method",name:"getPeaks",params:[{name:"length",description:"

length is the size of the returned array.\n Larger length results in more precision.\n Defaults to 5*width of the browser window.

\n",type:"Number",optional:!0}],return:{description:"Array of peaks.",type:"Float32Array"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1629,description:"

Reverses the p5.SoundFile's buffer source.\nPlayback must be handled separately (see example).

\n",itemtype:"method",name:"reverseBuffer",example:["\n
\nvar drum;\n\nfunction preload() {\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n drum.reverseBuffer();\n drum.play();\n}\n\n \n
"],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1664,description:"

Schedule an event to be called when the soundfile\nreaches the end of a buffer. If the soundfile is\nplaying through once, this will be called when it\nends. If it is looping, it will be called when\nstop is called.

\n",itemtype:"method",name:"onended",params:[{name:"callback",description:"

function to call when the\n soundfile has ended.

\n",type:"Function"}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1717,description:"

Connects the output of a p5sound object to input of another\np5.sound object. For example, you may connect a p5.SoundFile to an\nFFT or an Effect. If no parameter is given, it will connect to\nthe master output. Most p5sound objects connect to the master\noutput when they are created.

\n",itemtype:"method",name:"connect",params:[{name:"object",description:"

Audio object that accepts an input

\n",type:"Object",optional:!0}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1738,description:"

Disconnects the output of this p5sound object.

\n",itemtype:"method",name:"disconnect",class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1746,class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1751,description:"

Reset the source for this SoundFile to a\nnew path (URL).

\n",itemtype:"method",name:"setPath",params:[{name:"path",description:"

path to audio file

\n",type:"String"},{name:"callback",description:"

Callback

\n",type:"Function"}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1764,description:"

Replace the current Audio Buffer with a new Buffer.

\n",params:[{name:"buf",description:"

Array of Float32 Array(s). 2 Float32 Arrays\n will create a stereo source. 1 will create\n a mono source.

\n",type:"Array"}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:1835,description:"

processPeaks returns an array of timestamps where it thinks there is a beat.

\n

This is an asynchronous function that processes the soundfile in an offline audio context,\nand sends the results to your callback function.

\n

The process involves running the soundfile through a lowpass filter, and finding all of the\npeaks above the initial threshold. If the total number of peaks are below the minimum number of peaks,\nit decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached.

\n",itemtype:"method",name:"processPeaks",params:[{name:"callback",description:"

a function to call once this data is returned

\n",type:"Function"},{name:"initThreshold",description:"

initial threshold defaults to 0.9

\n",type:"Number",optional:!0},{name:"minThreshold",description:"

minimum threshold defaults to 0.22

\n",type:"Number",optional:!0},{name:"minPeaks",description:"

minimum number of peaks defaults to 200

\n",type:"Number",optional:!0}],return:{description:"Array of timestamped peaks",type:"Array"},class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2026,class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2035,description:"

Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.

\n

Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.

\n

Time will be passed as the first parameter to the callback function,\nand param will be the second parameter.

\n",itemtype:"method",name:"addCue",params:[{name:"time",description:"

Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.

\n",type:"Number"},{name:"callback",description:"

Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.

\n",type:"Function"},{name:"value",description:"

An object to be passed as the\n second parameter to the\n callback function.

\n",type:"Object",optional:!0}],return:{description:"id ID of this cue,\n useful for removeCue(id)",type:"Number"},example:['\n
\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text(\'click to play\', width/2, height/2);\n\n mySound = loadSound(\'assets/beat.mp3\');\n\n // schedule calls to changeText\n mySound.addCue(0.50, changeText, "hello" );\n mySound.addCue(1.00, changeText, "p5" );\n mySound.addCue(1.50, changeText, "what" );\n mySound.addCue(2.00, changeText, "do" );\n mySound.addCue(2.50, changeText, "you" );\n mySound.addCue(3.00, changeText, "want" );\n mySound.addCue(4.00, changeText, "to" );\n mySound.addCue(5.00, changeText, "make" );\n mySound.addCue(6.00, changeText, "?" );\n}\n\nfunction changeText(val) {\n background(0);\n text(val, width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (mySound.isPlaying() ) {\n mySound.stop();\n } else {\n mySound.play();\n }\n }\n}\n
'],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2110,description:"

Remove a callback based on its ID. The ID is returned by the\naddCue method.

\n",itemtype:"method",name:"removeCue",params:[{name:"id",description:"

ID of the cue, as returned by addCue

\n",type:"Number"}],class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2128,description:"

Remove all of the callbacks that had originally been scheduled\nvia the addCue method.

\n",itemtype:"method",name:"clearCues",class:"p5.SoundFile",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2236,description:"

Connects to the p5sound instance (master output) by default.\nOptionally, you can pass in a specific source (i.e. a soundfile).

\n",itemtype:"method",name:"setInput",params:[{name:"snd",description:"

set the sound source\n (optional, defaults to\n master output)

\n",type:"SoundObject|undefined",optional:!0},{name:"smoothing",description:"

a range between 0.0 and 1.0\n to smooth amplitude readings

\n",type:"Number|undefined",optional:!0}],example:["\n
\nfunction preload(){\n sound1 = loadSound('assets/beat.mp3');\n sound2 = loadSound('assets/drum.mp3');\n}\nfunction setup(){\n amplitude = new p5.Amplitude();\n sound1.play();\n sound2.play();\n amplitude.setInput(sound2);\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound1.stop();\n sound2.stop();\n}\n
"],class:"p5.Amplitude",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2341,description:"

Returns a single Amplitude reading at the moment it is called.\nFor continuous readings, run in the draw loop.

\n",itemtype:"method",name:"getLevel",params:[{name:"channel",description:"

Optionally return only channel 0 (left) or 1 (right)

\n",type:"Number",optional:!0}],return:{description:"Amplitude as a number between 0.0 and 1.0",type:"Number"},example:["\n
\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n amplitude = new p5.Amplitude();\n sound.play();\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound.stop();\n}\n
"],class:"p5.Amplitude",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2382,description:"

Determines whether the results of Amplitude.process() will be\nNormalized. To normalize, Amplitude finds the difference the\nloudest reading it has processed and the maximum amplitude of\n1.0. Amplitude adds this difference to all values to produce\nresults that will reliably map between 0.0 and 1.0. However,\nif a louder moment occurs, the amount that Normalize adds to\nall the values will change. Accepts an optional boolean parameter\n(true or false). Normalizing is off by default.

\n",itemtype:"method",name:"toggleNormalize",params:[{name:"boolean",description:"

set normalize to true (1) or false (0)

\n",type:"Boolean",optional:!0}],class:"p5.Amplitude",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2402,description:"

Smooth Amplitude analysis by averaging with the last analysis\nframe. Off by default.

\n",itemtype:"method",name:"smooth",params:[{name:"set",description:"

smoothing from 0.0 <= 1

\n",type:"Number"}],class:"p5.Amplitude",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2571,description:"

Set the input source for the FFT analysis. If no source is\nprovided, FFT will analyze all sound in the sketch.

\n",itemtype:"method",name:"setInput",params:[{name:"source",description:"

p5.sound object (or web audio API source node)

\n",type:"Object",optional:!0}],class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2590,description:"

Returns an array of amplitude values (between -1.0 and +1.0) that represent\na snapshot of amplitude readings in a single buffer. Length will be\nequal to bins (defaults to 1024). Can be used to draw the waveform\nof a sound.

\n",itemtype:"method",name:"waveform",params:[{name:"bins",description:"

Must be a power of two between\n 16 and 1024. Defaults to 1024.

\n",type:"Number",optional:!0},{name:"precision",description:"

If any value is provided, will return results\n in a Float32 Array which is more precise\n than a regular array.

\n",type:"String",optional:!0}],return:{description:"Array Array of amplitude values (-1 to 1)\n over time. Array length = bins.",type:"Array"},class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2633,description:"

Returns an array of amplitude values (between 0 and 255)\nacross the frequency spectrum. Length is equal to FFT bins\n(1024 by default). The array indices correspond to frequencies\n(i.e. pitches), from the lowest to the highest that humans can\nhear. Each value represents amplitude at that slice of the\nfrequency spectrum. Must be called prior to using\ngetEnergy().

\n",itemtype:"method",name:"analyze",params:[{name:"bins",description:"

Must be a power of two between\n 16 and 1024. Defaults to 1024.

\n",type:"Number",optional:!0},{name:"scale",description:"

If "dB," returns decibel\n float measurements between\n -140 and 0 (max).\n Otherwise returns integers from 0-255.

\n",type:"Number",optional:!0}],return:{description:"spectrum Array of energy (amplitude/volume)\n values across the frequency spectrum.\n Lowest energy (silence) = 0, highest\n possible is 255.",type:"Array"},example:["\n
\nvar osc;\nvar fft;\n\nfunction setup(){\n createCanvas(100,100);\n osc = new p5.Oscillator();\n osc.amp(0);\n osc.start();\n fft = new p5.FFT();\n}\n\nfunction draw(){\n background(0);\n\n var freq = map(mouseX, 0, 800, 20, 15000);\n freq = constrain(freq, 1, 20000);\n osc.freq(freq);\n\n var spectrum = fft.analyze();\n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h );\n }\n\n stroke(255);\n text('Freq: ' + round(freq)+'Hz', 10, 10);\n\n isMouseOverCanvas();\n}\n\n// only play sound when mouse is over canvas\nfunction isMouseOverCanvas() {\n var mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n osc.amp(0.5, 0.2);\n } else {\n osc.amp(0, 0.2);\n }\n}\n
\n\n"],class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2725,description:'

Returns the amount of energy (volume) at a specific\n\nfrequency, or the average amount of energy between two\nfrequencies. Accepts Number(s) corresponding\nto frequency (in Hz), or a String corresponding to predefined\nfrequency ranges ("bass", "lowMid", "mid", "highMid", "treble").\nReturns a range between 0 (no energy/volume at that frequency) and\n255 (maximum energy).\nNOTE: analyze() must be called prior to getEnergy(). Analyze()\ntells the FFT to analyze frequency data, and getEnergy() uses\nthe results determine the value at a specific frequency or\nrange of frequencies.

\n',itemtype:"method",name:"getEnergy",params:[{name:"frequency1",description:"

Will return a value representing\n energy at this frequency. Alternately,\n the strings "bass", "lowMid" "mid",\n "highMid", and "treble" will return\n predefined frequency ranges.

\n",type:"Number|String"},{name:"frequency2",description:"

If a second frequency is given,\n will return average amount of\n energy that exists between the\n two frequencies.

\n",type:"Number",optional:!0}],return:{description:"Energy Energy (volume/amplitude) from\n 0 and 255.",type:"Number"},class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2805,description:'

Returns the\n\nspectral centroid of the input signal.\nNOTE: analyze() must be called prior to getCentroid(). Analyze()\ntells the FFT to analyze frequency data, and getCentroid() uses\nthe results determine the spectral centroid.

\n',itemtype:"method",name:"getCentroid",return:{description:"Spectral Centroid Frequency Frequency of the spectral centroid in Hz.",type:"Number"}, +example:['\n
\n\n\nfunction setup(){\ncnv = createCanvas(800,400);\nsound = new p5.AudioIn();\nsound.start();\nfft = new p5.FFT();\nsound.connect(fft);\n}\n\n\nfunction draw(){\n\nvar centroidplot = 0.0;\nvar spectralCentroid = 0;\n\n\nbackground(0);\nstroke(0,255,0);\nvar spectrum = fft.analyze();\nfill(0,255,0); // spectrum is green\n\n//draw the spectrum\n\nfor (var i = 0; i< spectrum.length; i++){\n var x = map(log(i), 0, log(spectrum.length), 0, width);\n var h = map(spectrum[i], 0, 255, 0, height);\n var rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length));\n rect(x, height, rectangle_width, -h )\n}\n\nvar nyquist = 22050;\n\n// get the centroid\nspectralCentroid = fft.getCentroid();\n\n// the mean_freq_index calculation is for the display.\nvar mean_freq_index = spectralCentroid/(nyquist/spectrum.length);\n\ncentroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width);\n\n\nstroke(255,0,0); // the line showing where the centroid is will be red\n\nrect(centroidplot, 0, width / spectrum.length, height)\nnoStroke();\nfill(255,255,255); // text is white\ntextSize(40);\ntext("centroid: "+round(spectralCentroid)+" Hz", 10, 40);\n}\n
'],class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2886,description:"

Smooth FFT analysis by averaging with the last analysis frame.

\n",itemtype:"method",name:"smooth",params:[{name:"smoothing",description:"

0.0 < smoothing < 1.0.\n Defaults to 0.8.

\n",type:"Number"}],class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2906,description:"

Returns an array of average amplitude values for a given number\nof frequency bands split equally. N defaults to 16.\nNOTE: analyze() must be called prior to linAverages(). Analyze()\ntells the FFT to analyze frequency data, and linAverages() uses\nthe results to group them into a smaller set of averages.

\n",itemtype:"method",name:"linAverages",params:[{name:"N",description:"

Number of returned frequency groups

\n",type:"Number"}],return:{description:"linearAverages Array of average amplitude values for each group",type:"Array"},class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2936,description:'

Returns an array of average amplitude values of the spectrum, for a given\nset of \nOctave Bands\nNOTE: analyze() must be called prior to logAverages(). Analyze()\ntells the FFT to analyze frequency data, and logAverages() uses\nthe results to group them into a smaller set of averages.

\n',itemtype:"method",name:"logAverages",params:[{name:"octaveBands",description:"

Array of Octave Bands objects for grouping

\n",type:"Array"}],return:{description:"logAverages Array of average amplitude values for each group",type:"Array"},class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:2966,description:'

Calculates and Returns the 1/N\nOctave Bands\nN defaults to 3 and minimum central frequency to 15.625Hz.\n(1/3 Octave Bands ~= 31 Frequency Bands)\nSetting fCtr0 to a central value of a higher octave will ignore the lower bands\nand produce less frequency groups.

\n',itemtype:"method",name:"getOctaveBands",params:[{name:"N",description:"

Specifies the 1/N type of generated octave bands

\n",type:"Number"},{name:"fCtr0",description:"

Minimum central frequency for the lowest band

\n",type:"Number"}],return:{description:"octaveBands Array of octave band objects with their bounds",type:"Array"},class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:3024,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:3427,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:3448,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:3507,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:3960,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4097,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4130,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4176,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4197,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4217,class:"p5.FFT",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4319,description:"

Fade to value, for smooth transitions

\n",itemtype:"method",name:"fade",params:[{name:"value",description:"

Value to set this signal

\n",type:"Number"},{name:"secondsFromNow",description:"

Length of fade, in seconds from now

\n",type:"Number",optional:!0}],class:"p5.Signal",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4330,description:"

Connect a p5.sound object or Web Audio node to this\np5.Signal so that its amplitude values can be scaled.

\n",params:[{name:"input",description:"",type:"Object"}],class:"p5.Signal",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4343,description:"

Add a constant value to this audio signal,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalAdd.

\n",itemtype:"method",name:"add",params:[{name:"number",description:"",type:"Number"}],return:{description:"object",type:"p5.SignalAdd"},class:"p5.Signal",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4362,description:"

Multiply this signal by a constant value,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalMult.

\n",itemtype:"method",name:"mult",params:[{name:"number",description:"

to multiply

\n",type:"Number"}],return:{description:"object",type:"Tone.Multiply"},class:"p5.Signal",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4381,description:"

Scale this signal value to a given range,\nand return the result as an audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalScale.

\n",itemtype:"method",name:"scale",params:[{name:"number",description:"

to multiply

\n",type:"Number"},{name:"inMin",description:"

input range minumum

\n",type:"Number"},{name:"inMax",description:"

input range maximum

\n",type:"Number"},{name:"outMin",description:"

input range minumum

\n",type:"Number"},{name:"outMax",description:"

input range maximum

\n",type:"Number"}],return:{description:"object",type:"p5.SignalScale"},class:"p5.Signal",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4515,description:"

Start an oscillator. Accepts an optional parameter to\ndetermine how long (in seconds from now) until the\noscillator starts.

\n",itemtype:"method",name:"start",params:[{name:"time",description:"

startTime in seconds from now.

\n",type:"Number",optional:!0},{name:"frequency",description:"

frequency in Hz.

\n",type:"Number",optional:!0}],class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4555,description:"

Stop an oscillator. Accepts an optional parameter\nto determine how long (in seconds from now) until the\noscillator stops.

\n",itemtype:"method",name:"stop",params:[{name:"secondsFromNow",description:"

Time, in seconds from now.

\n",type:"Number"}],class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4571,description:"

Set the amplitude between 0 and 1.0. Or, pass in an object\nsuch as an oscillator to modulate amplitude with an audio signal.

\n",itemtype:"method",name:"amp",params:[{name:"vol",description:"

between 0 and 1.0\n or a modulating signal/oscillator

\n",type:"Number|Object"},{name:"rampTime",description:"

create a fade that lasts rampTime

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],return:{description:"gain If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's\n gain/amplitude/volume)",type:"AudioParam"},class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4606,description:"

Set frequency of an oscillator to a value. Or, pass in an object\nsuch as an oscillator to modulate the frequency with an audio signal.

\n",itemtype:"method",name:"freq",params:[{name:"Frequency",description:"

Frequency in Hz\n or modulating signal/oscillator

\n",type:"Number|Object"},{name:"rampTime",description:"

Ramp time (in seconds)

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

Schedule this event to happen\n at x seconds from now

\n",type:"Number",optional:!0}],return:{description:"Frequency If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's frequency",type:"AudioParam"},example:["\n
\nvar osc = new p5.Oscillator(300);\nosc.start();\nosc.freq(40, 10);\n
"],class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4665,description:"

Set type to 'sine', 'triangle', 'sawtooth' or 'square'.

\n",itemtype:"method",name:"setType",params:[{name:"type",description:"

'sine', 'triangle', 'sawtooth' or 'square'.

\n",type:"String"}],class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4677,description:"

Connect to a p5.sound / Web Audio object.

\n",itemtype:"method",name:"connect",params:[{name:"unit",description:"

A p5.sound or Web Audio object

\n",type:"Object"}],class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4694,description:"

Disconnect all outputs

\n",itemtype:"method",name:"disconnect",class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4705,description:"

Pan between Left (-1) and Right (1)

\n",itemtype:"method",name:"pan",params:[{name:"panning",description:"

Number between -1 and 1

\n",type:"Number"},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number"}],class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4737,description:"

Set the phase of an oscillator between 0.0 and 1.0.\nIn this implementation, phase is a delay time\nbased on the oscillator's current frequency.

\n",itemtype:"method",name:"phase",params:[{name:"phase",description:"

float between 0.0 and 1.0

\n",type:"Number"}],class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4791,description:"

Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method again\nwill override the initial add() with a new value.

\n",itemtype:"method",name:"add",params:[{name:"number",description:"

Constant number to add

\n",type:"Number"}],return:{description:"Oscillator Returns this oscillator\n with scaled output",type:"p5.Oscillator"},class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4808,description:"

Multiply the p5.Oscillator's output amplitude\nby a fixed value (i.e. turn it up!). Calling this method\nagain will override the initial mult() with a new value.

\n",itemtype:"method",name:"mult",params:[{name:"number",description:"

Constant number to multiply

\n",type:"Number"}],return:{description:"Oscillator Returns this oscillator\n with multiplied output",type:"p5.Oscillator"},class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4824,description:"

Scale this oscillator's amplitude values to a given\nrange, and return the oscillator. Calling this method\nagain will override the initial scale() with new values.

\n",itemtype:"method",name:"scale",params:[{name:"inMin",description:"

input range minumum

\n",type:"Number"},{name:"inMax",description:"

input range maximum

\n",type:"Number"},{name:"outMin",description:"

input range minumum

\n",type:"Number"},{name:"outMax",description:"

input range maximum

\n",type:"Number"}],return:{description:"Oscillator Returns this oscillator\n with scaled output",type:"p5.Oscillator"},class:"p5.Oscillator",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:4923,class:"p5.SqrOsc",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5109,class:"p5.SqrOsc",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5333,description:"

Time until envelope reaches attackLevel

\n",itemtype:"property",name:"attackTime",class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5338,description:"

Level once attack is complete.

\n",itemtype:"property",name:"attackLevel",class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5343,description:"

Time until envelope reaches decayLevel.

\n",itemtype:"property",name:"decayTime",class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5348,description:"

Level after decay. The envelope will sustain here until it is released.

\n",itemtype:"property",name:"decayLevel",class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5353,description:"

Duration of the release portion of the envelope.

\n",itemtype:"property",name:"releaseTime",class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5358,description:"

Level at the end of the release.

\n",itemtype:"property",name:"releaseLevel",class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5394,description:"

Reset the envelope with a series of time/value pairs.

\n",itemtype:"method",name:"set",params:[{name:"attackTime",description:"

Time (in seconds) before level\n reaches attackLevel

\n",type:"Number"},{name:"attackLevel",description:"

Typically an amplitude between\n 0.0 and 1.0

\n",type:"Number"},{name:"decayTime",description:"

Time

\n",type:"Number"},{name:"decayLevel",description:"

Amplitude (In a standard ADSR envelope,\n decayLevel = sustainLevel)

\n",type:"Number"},{name:"releaseTime",description:"

Release Time (in seconds)

\n",type:"Number"},{name:"releaseLevel",description:"

Amplitude

\n",type:"Number"}],example:["\n
\nvar t1 = 0.1; // attack time in seconds\nvar l1 = 0.7; // attack level 0.0 to 1.0\nvar t2 = 0.3; // decay time in seconds\nvar l2 = 0.1; // decay level 0.0 to 1.0\nvar t3 = 0.2; // sustain time in seconds\nvar l3 = dL; // sustain level 0.0 to 1.0\n// release level defaults to zero\n\nvar env;\nvar triOsc;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env(t1, l1, t2, l2, t3, l3);\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env); // give the env control of the triOsc's amp\n triOsc.start();\n}\n\n// mouseClick triggers envelope if over canvas\nfunction mouseClicked() {\n // is mouse over canvas?\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n env.play(triOsc);\n }\n}\n
\n"],class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5453,description:'

Set values like a traditional\n\nADSR envelope\n.

\n',itemtype:"method",name:"setADSR",params:[{name:"attackTime",description:"

Time (in seconds before envelope\n reaches Attack Level

\n",type:"Number"},{name:"decayTime",description:"

Time (in seconds) before envelope\n reaches Decay/Sustain Level

\n",type:"Number",optional:!0},{name:"susRatio",description:"

Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.

\n",type:"Number",optional:!0},{name:"releaseTime",description:"

Time in seconds from now (defaults to 0)

\n",type:"Number",optional:!0}],example:["\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
"],class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5518,description:"

Set max (attackLevel) and min (releaseLevel) of envelope.

\n",itemtype:"method",name:"setRange",params:[{name:"aLevel",description:"

attack level (defaults to 1)

\n",type:"Number"},{name:"rLevel",description:"

release level (defaults to 0)

\n",type:"Number"}],example:["\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
"],class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5597,description:"

Assign a parameter to be controlled by this envelope.\nIf a p5.Sound object is given, then the p5.Env will control its\noutput gain. If multiple inputs are provided, the env will\ncontrol all of them.

\n",itemtype:"method",name:"setInput",params:[{name:"inputs",description:"

A p5.sound object or\n Web Audio Param.

\n",type:"Object",optional:!0,multiple:!0}],class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5612,description:"

Set whether the envelope ramp is linear (default) or exponential.\nExponential ramps can be useful because we perceive amplitude\nand frequency logarithmically.

\n",itemtype:"method",name:"setExp",params:[{name:"isExp",description:"

true is exponential, false is linear

\n",type:"Boolean"}],class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5630,description:'

Play tells the envelope to start acting on a given input.\nIf the input is a p5.sound object (i.e. AudioIn, Oscillator,\nSoundFile), then Env will control its output volume.\nEnvelopes can also be used to control any \nWeb Audio Audio Param.

\n',itemtype:"method",name:"play",params:[{name:"unit",description:"

A p5.sound object or\n Web Audio Param.

\n",type:"Object"},{name:"startTime",description:"

time from now (in seconds) at which to play

\n",type:"Number",optional:!0},{name:"sustainTime",description:"

time to sustain before releasing the envelope

\n",type:"Number",optional:!0}],example:["\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n // trigger env on triOsc, 0 seconds from now\n // After decay, sustain for 0.2 seconds before release\n env.play(triOsc, 0, 0.2);\n}\n
"],class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5691,description:'

Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go. Input can be\nany p5.sound object, or a \nWeb Audio Param.

\n',itemtype:"method",name:"triggerAttack",params:[{name:"unit",description:"

p5.sound Object or Web Audio Param

\n",type:"Object"},{name:"secondsFromNow",description:"

time from now (in seconds)

\n",type:"Number"}],example:["\n
\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack(){\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n
"],class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5800,description:"

Trigger the Release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.

\n",itemtype:"method",name:"triggerRelease",params:[{name:"unit",description:"

p5.sound Object or Web Audio Param

\n",type:"Object"},{name:"secondsFromNow",description:"

time to trigger the release

\n",type:"Number"}],example:["\n
\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack(){\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n
"],class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:5899,description:'

Exponentially ramp to a value using the first two\nvalues from setADSR(attackTime, decayTime)\nas \ntime constants for simple exponential ramps.\nIf the value is higher than current value, it uses attackTime,\nwhile a decrease uses decayTime.

\n',itemtype:"method",name:"ramp",params:[{name:"unit",description:"

p5.sound Object or Web Audio Param

\n",type:"Object"},{name:"secondsFromNow",description:"

When to trigger the ramp

\n",type:"Number"},{name:"v",description:"

Target value

\n",type:"Number"},{name:"v2",description:"

Second target value (optional)

\n",type:"Number",optional:!0}],example:["\n
\nvar env, osc, amp, cnv;\n\nvar attackTime = 0.001;\nvar decayTime = 0.2;\nvar attackLevel = 1;\nvar decayLevel = 0;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n fill(0,255,0);\n noStroke();\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime);\n\n osc = new p5.Oscillator();\n osc.amp(env);\n osc.start();\n\n amp = new p5.Amplitude();\n\n cnv.mousePressed(triggerRamp);\n}\n\nfunction triggerRamp() {\n env.ramp(osc, 0, attackLevel, decayLevel);\n}\n\nfunction draw() {\n background(20,20,20);\n text('click me', 10, 20);\n var h = map(amp.getLevel(), 0, 0.4, 0, height);;\n\n rect(0, height, width, -h);\n}\n
"],class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6004,description:"

Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method\nagain will override the initial add() with new values.

\n",itemtype:"method",name:"add",params:[{name:"number",description:"

Constant number to add

\n",type:"Number"}],return:{description:"Envelope Returns this envelope\n with scaled output",type:"p5.Env"},class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6020,description:"

Multiply the p5.Env's output amplitude\nby a fixed value. Calling this method\nagain will override the initial mult() with new values.

\n",itemtype:"method",name:"mult",params:[{name:"number",description:"

Constant number to multiply

\n",type:"Number"}],return:{description:"Envelope Returns this envelope\n with scaled output",type:"p5.Env"},class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6036,description:"

Scale this envelope's amplitude values to a given\nrange, and return the envelope. Calling this method\nagain will override the initial scale() with new values.

\n",itemtype:"method",name:"scale",params:[{name:"inMin",description:"

input range minumum

\n",type:"Number"},{name:"inMax",description:"

input range maximum

\n",type:"Number"},{name:"outMin",description:"

input range minumum

\n",type:"Number"},{name:"outMax",description:"

input range maximum

\n",type:"Number"}],return:{description:"Envelope Returns this envelope\n with scaled output",type:"p5.Env"},class:"p5.Env",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6140,description:"

Set the width of a Pulse object (an oscillator that implements\nPulse Width Modulation).

\n",itemtype:"method",name:"width",params:[{name:"width",description:"

Width between the pulses (0 to 1.0,\n defaults to 0)

\n",type:"Number",optional:!0}],class:"p5.Pulse",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6325,description:"

Set type of noise to 'white', 'pink' or 'brown'.\nWhite is the default.

\n",itemtype:"method",name:"setType",params:[{name:"type",description:"

'white', 'pink' or 'brown'

\n",type:"String",optional:!0}],class:"p5.Noise",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6355,description:"

Start the noise

\n",itemtype:"method",name:"start",class:"p5.Noise",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6372,description:"

Stop the noise.

\n",itemtype:"method",name:"stop",class:"p5.Noise",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6384,description:"

Pan the noise.

\n",itemtype:"method",name:"pan",params:[{name:"panning",description:"

Number between -1 (left)\n and 1 (right)

\n",type:"Number"},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number"}],class:"p5.Noise",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6393,description:"

Set the amplitude of the noise between 0 and 1.0. Or,\nmodulate amplitude with an audio signal such as an oscillator.

\n",params:[{name:"volume",description:"

amplitude between 0 and 1.0\n or modulating signal/oscillator

\n",type:"Number|Object"},{name:"rampTime",description:"

create a fade that lasts rampTime

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Noise",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6403,description:"

Send output to a p5.sound or web audio object

\n",itemtype:"method",name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.Noise",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6409,description:"

Disconnect all output.

\n",itemtype:"method",name:"disconnect",class:"p5.Noise",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6481,description:"

Client must allow browser to access their microphone / audioin source.\nDefault: false. Will become true when the client enables acces.

\n",itemtype:"property",name:"enabled",type:"Boolean",class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6506,description:"

Start processing audio input. This enables the use of other\nAudioIn methods like getLevel(). Note that by default, AudioIn\nis not connected to p5.sound's output. So you won't hear\nanything unless you use the connect() method.

\n

Certain browsers limit access to the user's microphone. For example,\nChrome only allows access from localhost and over https. For this reason,\nyou may want to include an errorCallback—a function that is called in case\nthe browser won't provide mic access.

\n",itemtype:"method",name:"start",params:[{name:"successCallback", +description:"

Name of a function to call on\n success.

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

Name of a function to call if\n there was an error. For example,\n some browsers do not support\n getUserMedia.

\n",type:"Function",optional:!0}],class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6571,description:"

Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().\nIf re-starting, the user may be prompted for permission access.

\n",itemtype:"method",name:"stop",class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6583,description:"

Connect to an audio unit. If no parameter is provided, will\nconnect to the master output (i.e. your speakers).

\n",itemtype:"method",name:"connect",params:[{name:"unit",description:"

An object that accepts audio input,\n such as an FFT

\n",type:"Object",optional:!0}],class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6604,description:"

Disconnect the AudioIn from all audio units. For example, if\nconnect() had been called, disconnect() will stop sending\nsignal to your speakers.

\n",itemtype:"method",name:"disconnect",class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6616,description:"

Read the Amplitude (volume level) of an AudioIn. The AudioIn\nclass contains its own instance of the Amplitude class to help\nmake it easy to get a microphone's volume level. Accepts an\noptional smoothing value (0.0 < 1.0). NOTE: AudioIn must\n.start() before using .getLevel().

\n",itemtype:"method",name:"getLevel",params:[{name:"smoothing",description:"

Smoothing is 0.0 by default.\n Smooths values based on previous values.

\n",type:"Number",optional:!0}],return:{description:"Volume level (between 0.0 and 1.0)",type:"Number"},class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6634,description:"

Add input sources to the list of available sources.

\n",access:"private",tagname:"",class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6649,description:"

Set amplitude (volume) of a mic input between 0 and 1.0.

\n",itemtype:"method",name:"amp",params:[{name:"vol",description:"

between 0 and 1.0

\n",type:"Number"},{name:"time",description:"

ramp time (optional)

\n",type:"Number",optional:!0}],class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6677,description:'

Chrome only. Returns a list of available input sources\nand allows the user to set the media source. Firefox allows\nthe user to choose from input sources in the permissions dialogue\ninstead of enumerating available sources and selecting one.\nNote: in order to have descriptive media names your page must be\nserved over a secure (HTTPS) connection and the page should\nrequest user media before enumerating devices. Otherwise device\nID will be a long device ID number and does not specify device\ntype. For example see\nhttps://simpl.info/getusermedia/sources/index.html vs.\nhttp://simpl.info/getusermedia/sources/index.html

\n',itemtype:"method",name:"getSources",params:[{name:"callback",description:"

a callback to handle the sources\n when they have been enumerated

\n",type:"Function"}],example:["\n
\n var audiograb;\n\n function setup(){\n //new audioIn\n audioGrab = new p5.AudioIn();\n\n audioGrab.getSources(function(sourceList) {\n //print out the array of available sources\n console.log(sourceList);\n //set the source to the first item in the inputSources array\n audioGrab.setSource(0);\n });\n }\n
"],class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6726,description:"

Set the input source. Accepts a number representing a\nposition in the array returned by listSources().\nThis is only available in browsers that support\nMediaStreamTrack.getSources(). Instead, some browsers\ngive users the option to set their own media source.

\n",itemtype:"method",name:"setSource",params:[{name:"num",description:"

position of input source in the array

\n",type:"Number"}],class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6763,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6779,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6803,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6829,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6858,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6888,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6936,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6959,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:6984,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7005,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7012,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7034,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7063,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7090,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7118,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7146,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7192,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7223,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7241,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7629,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7651,class:"p5.AudioIn",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7721,description:"

The p5.Effect class is built\n using Tone.js CrossFade

\n",access:"private",tagname:"",class:"p5.Effect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7727,description:"

In classes that extend\np5.Effect, connect effect nodes\nto the wet parameter

\n",class:"p5.Effect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7740,description:"

Set the output volume of the filter.

\n",itemtype:"method",name:"amp",params:[{name:"vol",description:"

amplitude between 0 and 1.0

\n",type:"Number",optional:!0},{name:"rampTime",description:"

create a fade that lasts until rampTime

\n",type:"Number",optional:!0},{name:"tFromNow",description:"

schedule this event to happen in tFromNow seconds

\n",type:"Number",optional:!0}],class:"p5.Effect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7757,description:"

Link effects together in a chain
Example usage: filter.chain(reverb, delay, panner);\nMay be used with an open-ended number of arguments

\n",itemtype:"method",name:"chain",params:[{name:"arguments",description:"

Chain together multiple sound objects

\n",type:"Object",optional:!0}],class:"p5.Effect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7774,description:"

Adjust the dry/wet value.

\n",itemtype:"method",name:"drywet",params:[{name:"fade",description:"

The desired drywet value (0 - 1.0)

\n",type:"Number",optional:!0}],class:"p5.Effect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7786,description:"

Send output to a p5.js-sound, Web Audio Node, or use signal to\ncontrol an AudioParam

\n",itemtype:"method",name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.Effect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7797,description:"

Disconnect all output.

\n",itemtype:"method",name:"disconnect",class:"p5.Effect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7904,description:'

The p5.Filter is built with a\n\nWeb Audio BiquadFilter Node.

\n',itemtype:"property",name:"biquadFilter",type:"DelayNode",class:"p5.Filter",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7919,description:"

Filter an audio signal according to a set\nof filter parameters.

\n",itemtype:"method",name:"process",params:[{name:"Signal",description:"

An object that outputs audio

\n",type:"Object"},{name:"freq",description:"

Frequency in Hz, from 10 to 22050

\n",type:"Number",optional:!0},{name:"res",description:"

Resonance/Width of the filter frequency\n from 0.001 to 1000

\n",type:"Number",optional:!0}],class:"p5.Filter",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7933,description:"

Set the frequency and the resonance of the filter.

\n",itemtype:"method",name:"set",params:[{name:"freq",description:"

Frequency in Hz, from 10 to 22050

\n",type:"Number",optional:!0},{name:"res",description:"

Resonance (Q) from 0.001 to 1000

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Filter",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7950,description:"

Set the filter frequency, in Hz, from 10 to 22050 (the range of\nhuman hearing, although in reality most people hear in a narrower\nrange).

\n",itemtype:"method",name:"freq",params:[{name:"freq",description:"

Filter Frequency

\n",type:"Number"},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],return:{description:"value Returns the current frequency value",type:"Number"},class:"p5.Filter",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7975,description:"

Controls either width of a bandpass frequency,\nor the resonance of a low/highpass cutoff frequency.

\n",itemtype:"method",name:"res",params:[{name:"res",description:"

Resonance/Width of filter freq\n from 0.001 to 1000

\n",type:"Number"},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],return:{description:"value Returns the current res value",type:"Number"},class:"p5.Filter",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:7997,description:"

Set the type of a p5.Filter. Possible types include:\n"lowpass" (default), "highpass", "bandpass",\n"lowshelf", "highshelf", "peaking", "notch",\n"allpass".

\n",itemtype:"method",name:"setType",params:[{name:"t",description:"",type:"String"}],class:"p5.Filter",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8124,description:'

The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.

\n',itemtype:"property",name:"leftDelay",type:"DelayNode",class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8132,description:'

The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.

\n',itemtype:"property",name:"rightDelay",type:"DelayNode",class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8164,description:"

Add delay to an audio signal according to a set\nof delay parameters.

\n",itemtype:"method",name:"process",params:[{name:"Signal",description:"

An object that outputs audio

\n",type:"Object"},{name:"delayTime",description:"

Time (in seconds) of the delay/echo.\n Some browsers limit delayTime to\n 1 second.

\n",type:"Number",optional:!0},{name:"feedback",description:"

sends the delay back through itself\n in a loop that decreases in volume\n each time.

\n",type:"Number",optional:!0},{name:"lowPass",description:"

Cutoff frequency. Only frequencies\n below the lowPass will be part of the\n delay.

\n",type:"Number",optional:!0}],class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8199,description:"

Set the delay (echo) time, in seconds. Usually this value will be\na floating point number between 0.0 and 1.0.

\n",itemtype:"method",name:"delayTime",params:[{name:"delayTime",description:"

Time (in seconds) of the delay

\n",type:"Number"}],class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8218,description:"

Feedback occurs when Delay sends its signal back through its input\nin a loop. The feedback amount determines how much signal to send each\ntime through the loop. A feedback greater than 1.0 is not desirable because\nit will increase the overall output each time through the loop,\ncreating an infinite feedback loop. The default value is 0.5

\n",itemtype:"method",name:"feedback",params:[{name:"feedback",description:"

0.0 to 1.0, or an object such as an\n Oscillator that can be used to\n modulate this param

\n",type:"Number|Object"}],return:{description:"Feedback value",type:"Number"},class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8246,description:"

Set a lowpass filter frequency for the delay. A lowpass filter\nwill cut off any frequencies higher than the filter frequency.

\n",itemtype:"method",name:"filter",params:[{name:"cutoffFreq",description:"

A lowpass filter will cut off any\n frequencies higher than the filter frequency.

\n",type:"Number|Object"},{name:"res",description:"

Resonance of the filter frequency\n cutoff, or an object (i.e. a p5.Oscillator)\n that can be used to modulate this parameter.\n High numbers (i.e. 15) will produce a resonance,\n low numbers (i.e. .2) will produce a slope.

\n",type:"Number|Object"}],class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8263,description:"

Choose a preset type of delay. 'pingPong' bounces the signal\nfrom the left to the right channel to produce a stereo effect.\nAny other parameter will revert to the default delay setting.

\n",itemtype:"method",name:"setType",params:[{name:"type",description:"

'pingPong' (1) or 'default' (0)

\n",type:"String|Number"}],class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8296,description:"

Set the output level of the delay effect.

\n",itemtype:"method",name:"amp",params:[{name:"volume",description:"

amplitude between 0 and 1.0

\n",type:"Number"},{name:"rampTime",description:"

create a fade that lasts rampTime

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8305,description:"

Send output to a p5.sound or web audio object

\n",itemtype:"method",name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8311,description:"

Disconnect all output.

\n",itemtype:"method",name:"disconnect",class:"p5.Delay",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8390,description:"

Connect a source to the reverb, and assign reverb parameters.

\n",itemtype:"method",name:"process",params:[{name:"src",description:"

p5.sound / Web Audio object with a sound\n output.

\n",type:"Object"},{name:"seconds",description:"

Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.

\n",type:"Number",optional:!0},{name:"decayRate",description:"

Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.

\n",type:"Number",optional:!0},{name:"reverse",description:"

Play the reverb backwards or forwards.

\n",type:"Boolean",optional:!0}],class:"p5.Reverb",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8419,description:"

Set the reverb settings. Similar to .process(), but without\nassigning a new input.

\n",itemtype:"method",name:"set",params:[{name:"seconds",description:"

Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.

\n",type:"Number",optional:!0},{name:"decayRate",description:"

Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.

\n",type:"Number",optional:!0},{name:"reverse",description:"

Play the reverb backwards or forwards.

\n",type:"Boolean",optional:!0}],class:"p5.Reverb",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8447,description:"

Set the output level of the reverb effect.

\n",itemtype:"method",name:"amp",params:[{name:"volume",description:"

amplitude between 0 and 1.0

\n",type:"Number"},{name:"rampTime",description:"

create a fade that lasts rampTime

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Reverb",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8456,description:"

Send output to a p5.sound or web audio object

\n",itemtype:"method",name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.Reverb",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8462,description:"

Disconnect all output.

\n",itemtype:"method",name:"disconnect",class:"p5.Reverb",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8467,description:'

Inspired by Simple Reverb by Jordan Santell\nhttps://github.com/web-audio-components/simple-reverb/blob/master/index.js

\n

Utility function for building an impulse response\nbased on the module parameters.

\n',access:"private",tagname:"",class:"p5.Reverb",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8556,description:'

Internally, the p5.Convolver uses the a\n\nWeb Audio Convolver Node.

\n',itemtype:"property",name:"convolverNod",type:"ConvolverNode",class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8581,description:"

Create a p5.Convolver. Accepts a path to a soundfile\nthat will be used to generate an impulse response.

\n",itemtype:"method",name:"createConvolver",params:[{name:"path",description:"

path to a sound file

\n",type:"String"},{name:"callback",description:"

function to call if loading is successful.\n The object will be passed in as the argument\n to the callback function.

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to call if loading is not successful.\n A custom error will be passed in as the argument\n to the callback function.

\n",type:"Function",optional:!0}],return:{description:"",type:"p5.Convolver"},example:["\n
\nvar cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons_-_power_melody'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\n
"],class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8631,description:"

Private method to load a buffer as an Impulse Response,\nassign it to the convolverNode, and add to the Array of .impulses.

\n",params:[{name:"path",description:"",type:"String"},{name:"callback",description:"",type:"Function"},{name:"errorCallback",description:"",type:"Function"}],access:"private",tagname:"",class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8697,description:"

Connect a source to the reverb, and assign reverb parameters.

\n",itemtype:"method",name:"process",params:[{name:"src",description:"

p5.sound / Web Audio object with a sound\n output.

\n",type:"Object"}],example:["\n
\nvar cVerb, sound;\nfunction preload() {\n soundFormats('ogg', 'mp3');\n\n cVerb = createConvolver('assets/concrete-tunnel.mp3');\n\n sound = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with (i.e. connect to) cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\n
"],class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8729,description:"

If you load multiple impulse files using the .addImpulse method,\nthey will be stored as Objects in this Array. Toggle between them\nwith the toggleImpulse(id) method.

\n",itemtype:"property",name:"impulses",type:"Array",class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8737,description:"

Load and assign a new Impulse Response to the p5.Convolver.\nThe impulse is added to the .impulses array. Previous\nimpulses can be accessed with the .toggleImpulse(id)\nmethod.

\n",itemtype:"method",name:"addImpulse",params:[{name:"path",description:"

path to a sound file

\n",type:"String"},{name:"callback",description:"

function (optional)

\n",type:"Function"},{name:"errorCallback",description:"

function (optional)

\n",type:"Function"}],class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8755,description:"

Similar to .addImpulse, except that the .impulses\nArray is reset to save memory. A new .impulses\narray is created with this impulse as the only item.

\n",itemtype:"method",name:"resetImpulse",params:[{name:"path",description:"

path to a sound file

\n",type:"String"},{name:"callback",description:"

function (optional)

\n",type:"Function"},{name:"errorCallback",description:"

function (optional)

\n",type:"Function"}],class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8773,description:'

If you have used .addImpulse() to add multiple impulses\nto a p5.Convolver, then you can use this method to toggle between\nthe items in the .impulses Array. Accepts a parameter\nto identify which impulse you wish to use, identified either by its\noriginal filename (String) or by its position in the .impulses\n Array (Number).
\nYou can access the objects in the .impulses Array directly. Each\nObject has two attributes: an .audioBuffer (type:\nWeb Audio \nAudioBuffer) and a .name, a String that corresponds\nwith the original filename.

\n',itemtype:"method",name:"toggleImpulse",params:[{name:"id",description:"

Identify the impulse by its original filename\n (String), or by its position in the\n .impulses Array (Number).

\n",type:"String|Number"}],class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8817,class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:8842,class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9059,description:"

Set the global tempo, in beats per minute, for all\np5.Parts. This method will impact all active p5.Parts.

\n",params:[{name:"BPM",description:"

Beats Per Minute

\n",type:"Number"},{name:"rampTime",description:"

Seconds from now

\n",type:"Number"}],class:"p5.Convolver",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9148,description:"

Array of values to pass into the callback\nat each step of the phrase. Depending on the callback\nfunction's requirements, these values may be numbers,\nstrings, or an object with multiple parameters.\nZero (0) indicates a rest.

\n",itemtype:"property",name:"sequence",type:"Array",class:"p5.Phrase",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9236,description:"

Set the tempo of this part, in Beats Per Minute.

\n",itemtype:"method",name:"setBPM",params:[{name:"BPM",description:"

Beats Per Minute

\n",type:"Number"},{name:"rampTime",description:"

Seconds from now

\n",type:"Number",optional:!0}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9246,description:"

Returns the Beats Per Minute of this currently part.

\n",itemtype:"method",name:"getBPM",return:{description:"",type:"Number"},class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9255,description:"

Start playback of this part. It will play\nthrough all of its phrases at a speed\ndetermined by setBPM.

\n",itemtype:"method",name:"start",params:[{name:"time",description:"

seconds from now

\n",type:"Number",optional:!0}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9271,description:"

Loop playback of this part. It will begin\nlooping through all of its phrases at a speed\ndetermined by setBPM.

\n",itemtype:"method",name:"loop",params:[{name:"time",description:"

seconds from now

\n",type:"Number",optional:!0}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9288,description:"

Tell the part to stop looping.

\n",itemtype:"method",name:"noLoop",class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9300,description:"

Stop the part and cue it to step 0.

\n",itemtype:"method",name:"stop",params:[{name:"time",description:"

seconds from now

\n",type:"Number",optional:!0}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9310,description:"

Pause the part. Playback will resume\nfrom the current step.

\n",itemtype:"method",name:"pause",params:[{name:"time",description:"

seconds from now

\n",type:"Number"}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9322,description:"

Add a p5.Phrase to this Part.

\n",itemtype:"method",name:"addPhrase",params:[{name:"phrase",description:"

reference to a p5.Phrase

\n",type:"p5.Phrase"}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9343,description:"

Remove a phrase from this part, based on the name it was\ngiven when it was created.

\n",itemtype:"method",name:"removePhrase",params:[{name:"phraseName",description:"",type:"String"}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9357,description:"

Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.

\n",itemtype:"method",name:"getPhrase",params:[{name:"phraseName",description:"",type:"String"}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9371,description:"

Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.

\n",itemtype:"method",name:"replaceSequence",params:[{name:"phraseName",description:"",type:"String"},{name:"sequence",description:"

Array of values to pass into the callback\n at each step of the phrase.

\n",type:"Array"}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9399,description:"

Fire a callback function at every step.

\n",itemtype:"method",name:"onStep",params:[{name:"callback",description:"

The name of the callback\n you want to fire\n on every beat/tatum.

\n",type:"Function"}],class:"p5.Part",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9452,description:"

Start playback of the score.

\n",itemtype:"method",name:"start",class:"p5.Score",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9461,description:"

Stop playback of the score.

\n",itemtype:"method",name:"stop",class:"p5.Score",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9471,description:"

Pause playback of the score.

\n",itemtype:"method",name:"pause",class:"p5.Score",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9479,description:"

Loop playback of the score.

\n",itemtype:"method",name:"loop",class:"p5.Score",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9488,description:"

Stop looping playback of the score. If it\nis currently playing, this will go into effect\nafter the current round of playback completes.

\n",itemtype:"method",name:"noLoop",class:"p5.Score",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9513,description:"

Set the tempo for all parts in the score

\n",params:[{name:"BPM",description:"

Beats Per Minute

\n",type:"Number"},{name:"rampTime",description:"

Seconds from now

\n",type:"Number"}],class:"p5.Score",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9567, +description:'

The p5.Compressor is built with a Web Audio Dynamics Compressor Node\n

\n',itemtype:"property",name:"compressor",type:"WebAudioNode",class:"p5.Compressor",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9578,description:"

Performs the same function as .connect, but also accepts\noptional parameters to set compressor's audioParams

\n",itemtype:"method",name:"process",params:[{name:"src",description:"

Sound source to be connected

\n",type:"Object"},{name:"attack",description:"

The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1

\n",type:"Number",optional:!0},{name:"knee",description:"

A decibel value representing the range above the \n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40

\n",type:"Number",optional:!0},{name:"ratio",description:"

The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20

\n",type:"Number",optional:!0},{name:"threshold",description:"

The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0

\n",type:"Number",optional:!0},{name:"release",description:"

The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9601,description:"

Set the paramters of a compressor.

\n",itemtype:"method",name:"set",params:[{name:"attack",description:"

The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1

\n",type:"Number"},{name:"knee",description:"

A decibel value representing the range above the \n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40

\n",type:"Number"},{name:"ratio",description:"

The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20

\n",type:"Number"},{name:"threshold",description:"

The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0

\n",type:"Number"},{name:"release",description:"

The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1

\n",type:"Number"}],class:"p5.Compressor",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9633,description:"

Get current attack or set value w/ time ramp

\n",itemtype:"method",name:"attack",params:[{name:"attack",description:"

Attack is the amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1

\n",type:"Number",optional:!0},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9653,description:"

Get current knee or set value w/ time ramp

\n",itemtype:"method",name:"knee",params:[{name:"knee",description:"

A decibel value representing the range above the \n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40

\n",type:"Number",optional:!0},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9673,description:"

Get current ratio or set value w/ time ramp

\n",itemtype:"method",name:"ratio",params:[{name:"ratio",description:"

The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20

\n",type:"Number",optional:!0},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9692,description:"

Get current threshold or set value w/ time ramp

\n",itemtype:"method",name:"threshold",params:[{name:"threshold",description:"

The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0

\n",type:"Number"},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9711,description:"

Get current release or set value w/ time ramp

\n",itemtype:"method",name:"release",params:[{name:"release",description:"

The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1

\n",type:"Number"},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9731,description:"

Return the current reduction value

\n",return:{description:"Value of the amount of gain reduction that is applied to the signal",type:"Number"},class:"p5.Compressor",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9828,description:"

callback invoked when the recording is over

\n",access:"private",tagname:"",type:"Function(Float32Array)",class:"p5.SoundRecorder",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9841,description:"

Connect a specific device to the p5.SoundRecorder.\nIf no parameter is given, p5.SoundRecorer will record\nall audible p5.sound from your sketch.

\n",itemtype:"method",name:"setInput",params:[{name:"unit",description:"

p5.sound object or a web audio unit\n that outputs sound

\n",type:"Object",optional:!0}],class:"p5.SoundRecorder",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9862,description:"

Start recording. To access the recording, provide\na p5.SoundFile as the first parameter. The p5.SoundRecorder\nwill send its recording to that p5.SoundFile for playback once\nrecording is complete. Optional parameters include duration\n(in seconds) of the recording, and a callback function that\nwill be called once the complete recording has been\ntransfered to the p5.SoundFile.

\n",itemtype:"method",name:"record",params:[{name:"soundFile",description:"

p5.SoundFile

\n",type:"p5.SoundFile"},{name:"duration",description:"

Time (in seconds)

\n",type:"Number",optional:!0},{name:"callback",description:"

The name of a function that will be\n called once the recording completes

\n",type:"Function",optional:!0}],class:"p5.SoundRecorder",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9895,description:"

Stop the recording. Once the recording is stopped,\nthe results will be sent to the p5.SoundFile that\nwas given on .record(), and if a callback function\nwas provided on record, that function will be called.

\n",itemtype:"method",name:"stop",class:"p5.SoundRecorder",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9914,description:"

internal method called on audio process

\n",access:"private",tagname:"",params:[{name:"event",description:"",type:"AudioProcessorEvent"}],class:"p5.SoundRecorder",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:9968,description:"

Save a p5.SoundFile as a .wav audio file.

\n",itemtype:"method",name:"saveSound",params:[{name:"soundFile",description:"

p5.SoundFile that you wish to save

\n",type:"p5.SoundFile"},{name:"name",description:"

name of the resulting .wav file.

\n",type:"String"}],class:"p5.SoundRecorder",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10144,description:"

isDetected is set to true when a peak is detected.

\n",itemtype:"attribute",name:"isDetected",type:"Boolean",default:"false",class:"p5.PeakDetect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10157,description:"

The update method is run in the draw loop.

\n

Accepts an FFT object. You must call .analyze()\non the FFT object prior to updating the peakDetect\nbecause it relies on a completed FFT analysis.

\n",itemtype:"method",name:"update",params:[{name:"fftObject",description:"

A p5.FFT object

\n",type:"p5.FFT"}],class:"p5.PeakDetect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10188,description:"

onPeak accepts two arguments: a function to call when\na peak is detected. The value of the peak,\nbetween 0.0 and 1.0, is passed to the callback.

\n",itemtype:"method",name:"onPeak",params:[{name:"callback",description:"

Name of a function that will\n be called when a peak is\n detected.

\n",type:"Function"},{name:"val",description:"

Optional value to pass\n into the function when\n a peak is detected.

\n",type:"Object",optional:!0}],example:["\n
\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 0;\n\nfunction setup() {\n cnv = createCanvas(100,100);\n textAlign(CENTER);\n\n soundFile = loadSound('assets/beat.mp3');\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n\n setupSound();\n\n // when a beat is detected, call triggerBeat()\n peakDetect.onPeak(triggerBeat);\n}\n\nfunction draw() {\n background(0);\n fill(255);\n text('click to play', width/2, height/2);\n\n fft.analyze();\n peakDetect.update(fft);\n\n ellipseWidth *= 0.95;\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// this function is called by peakDetect.onPeak\nfunction triggerBeat() {\n ellipseWidth = 50;\n}\n\n// mouseclick starts/stops sound\nfunction setupSound() {\n cnv.mouseClicked( function() {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n });\n}\n
"],class:"p5.PeakDetect",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10334,description:"

Connect a source to the gain node.

\n",itemtype:"method",name:"setInput",params:[{name:"src",description:"

p5.sound / Web Audio object with a sound\n output.

\n",type:"Object"}],class:"p5.Gain",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10344,description:"

Send output to a p5.sound or web audio object

\n",itemtype:"method",name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.Gain",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10354,description:"

Disconnect all output.

\n",itemtype:"method",name:"disconnect",class:"p5.Gain",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10362,description:"

Set the output level of the gain node.

\n",itemtype:"method",name:"amp",params:[{name:"volume",description:"

amplitude between 0 and 1.0

\n",type:"Number"},{name:"rampTime",description:"

create a fade that lasts rampTime

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Gain",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10443,description:'

The p5.Distortion is built with a\n\nWeb Audio WaveShaper Node.

\n',itemtype:"property",name:"WaveShaperNode",type:"AudioNode",class:"p5.Distortion",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10458,description:"

Process a sound source, optionally specify amount and oversample values.

\n",itemtype:"method",name:"process",params:[{name:"amount",description:"

Unbounded distortion amount.\n Normal values range from 0-1.

\n",type:"Number",optional:!0,optdefault:"0.25"},{name:"oversample",description:"

'none', '2x', or '4x'.

\n",type:"String",optional:!0,optdefault:"'none'"}],class:"p5.Distortion",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10470,description:"

Set the amount and oversample of the waveshaper distortion.

\n",itemtype:"method",name:"set",params:[{name:"amount",description:"

Unbounded distortion amount.\n Normal values range from 0-1.

\n",type:"Number",optional:!0,optdefault:"0.25"},{name:"oversample",description:"

'none', '2x', or '4x'.

\n",type:"String",optional:!0,optdefault:"'none'"}],class:"p5.Distortion",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10488,description:"

Return the distortion amount, typically between 0-1.

\n",itemtype:"method",name:"getAmount",return:{description:"Unbounded distortion amount.\n Normal values range from 0-1.",type:"Number"},class:"p5.Distortion",module:"p5.sound",submodule:"p5.sound"},{file:"lib/addons/p5.sound.js",line:10498,description:"

Return the oversampling.

\n",itemtype:"method",name:"getOversample",return:{description:"Oversample can either be 'none', '2x', or '4x'.",type:"String"},class:"p5.Distortion",module:"p5.sound",submodule:"p5.sound"}],warnings:[{message:"unknown tag: alt",line:" src/color/creating_reading.js:16"},{message:"unknown tag: alt",line:" src/color/creating_reading.js:60"},{message:"unknown tag: alt",line:" src/color/creating_reading.js:89"},{message:"unknown tag: alt",line:" src/color/creating_reading.js:118"},{message:"unknown tag: alt",line:" src/color/creating_reading.js:326"},{message:"unknown tag: alt",line:" src/color/creating_reading.js:356"},{message:"unknown tag: alt",line:" src/color/creating_reading.js:392"},{message:"unknown tag: alt",line:" src/color/creating_reading.js:489"},{message:"unknown tag: alt",line:" src/color/creating_reading.js:518"},{message:"unknown tag: alt",line:" src/color/creating_reading.js:557"},{message:"unknown tag: alt",line:" src/color/p5.Color.js:447"},{message:"unknown tag: alt",line:" src/color/setting.js:15"},{message:"unknown tag: alt",line:" src/color/setting.js:178"},{message:"unknown tag: alt",line:" src/color/setting.js:235"},{message:"unknown tag: alt",line:" src/color/setting.js:373"},{message:"unknown tag: alt",line:" src/color/setting.js:489"},{message:"unknown tag: alt",line:" src/color/setting.js:514"},{message:"unknown tag: alt",line:" src/color/setting.js:581"},{message:"unknown tag: alt",line:" src/core/2d_primitives.js:16"},{message:"unknown tag: alt",line:" src/core/2d_primitives.js:132"},{message:"unknown tag: alt",line:" src/core/2d_primitives.js:187"},{message:"unknown tag: alt",line:" src/core/2d_primitives.js:262"},{message:"unknown tag: alt",line:" src/core/2d_primitives.js:313"},{message:"unknown tag: alt",line:" src/core/2d_primitives.js:393"},{message:"unknown tag: alt",line:" src/core/2d_primitives.js:477"},{message:"unknown tag: alt",line:" src/core/attributes.js:14"},{message:"unknown tag: alt",line:" src/core/attributes.js:80"},{message:"unknown tag: alt",line:" src/core/attributes.js:108"},{message:"unknown tag: alt",line:" src/core/attributes.js:174"},{message:"unknown tag: alt",line:" src/core/attributes.js:203"},{message:"unknown tag: alt",line:" src/core/attributes.js:237"},{message:"unknown tag: alt",line:" src/core/attributes.js:301"},{message:"unknown tag: alt",line:" src/core/constants.js:33"},{message:"unknown tag: alt",line:" src/core/constants.js:52"},{message:"unknown tag: alt",line:" src/core/constants.js:71"},{message:"unknown tag: alt",line:" src/core/constants.js:90"},{message:"unknown tag: alt",line:" src/core/constants.js:109"},{message:"unknown tag: alt",line:" src/core/core.js:49"},{message:"unknown tag: alt",line:" src/core/core.js:85"},{message:"unknown tag: alt",line:" src/core/core.js:116"},{message:"unknown tag: alt",line:" src/core/core.js:393"},{message:"unknown tag: alt",line:" src/core/curves.js:16"},{message:"unknown tag: alt",line:" src/core/curves.js:99"},{message:"unknown tag: alt",line:" src/core/curves.js:124"},{message:"unknown tag: alt",line:" src/core/curves.js:175"},{message:"unknown tag: alt",line:" src/core/curves.js:256"},{message:"unknown tag: alt",line:" src/core/curves.js:308"},{message:"unknown tag: alt",line:" src/core/curves.js:353"},{message:"unknown tag: alt",line:" src/core/curves.js:378"},{message:"unknown tag: alt",line:" src/core/curves.js:476"},{message:"unknown tag: alt",line:" src/core/environment.js:22"},{message:"unknown tag: alt",line:" src/core/environment.js:51"},{message:"unknown tag: alt",line:" src/core/environment.js:79"},{message:"unknown tag: alt",line:" src/core/environment.js:110"},{message:"unknown tag: alt",line:" src/core/environment.js:188"},{message:"unknown tag: alt",line:" src/core/environment.js:262"},{message:"unknown tag: alt",line:" src/core/environment.js:288"},{message:"unknown tag: alt",line:" src/core/environment.js:305"},{message:"unknown tag: alt",line:" src/core/environment.js:322"},{message:"unknown tag: alt",line:" src/core/environment.js:338"},{message:"unknown tag: alt",line:" src/core/environment.js:354"},{message:"unknown tag: alt",line:" src/core/environment.js:428"},{message:"replacing incorrect tag: returns with return",line:" src/core/environment.js:475"},{message:"unknown tag: alt",line:" src/core/environment.js:475"},{message:"replacing incorrect tag: returns with return",line:" src/core/environment.js:520"},{message:"unknown tag: alt",line:" src/core/environment.js:520"},{message:"unknown tag: alt",line:" src/core/environment.js:577"},{message:"unknown tag: alt",line:" src/core/environment.js:608"},{message:"unknown tag: alt",line:" src/core/environment.js:629"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:53"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:112"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:163"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:213"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:263"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:329"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:383"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:437"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:496"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:541"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:608"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:643"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:686"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:735"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:776"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:828"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:866"},{message:"unknown tag: alt",line:" src/core/p5.Element.js:904"},{message:"unknown tag: alt",line:" src/core/rendering.js:14"},{message:"unknown tag: alt",line:" src/core/rendering.js:112"},{message:"unknown tag: alt",line:" src/core/rendering.js:162"},{message:"unknown tag: alt",line:" src/core/rendering.js:185"},{message:"unknown tag: alt",line:" src/core/rendering.js:223"},{message:"unknown tag: alt",line:" src/core/structure.js:15"},{message:"unknown tag: alt",line:" src/core/structure.js:77"},{message:"unknown tag: alt",line:" src/core/structure.js:119"},{message:"unknown tag: alt",line:" src/core/structure.js:194"},{message:"unknown tag: alt",line:" src/core/structure.js:266"},{message:"unknown tag: alt",line:" src/core/transform.js:15"},{message:"unknown tag: alt",line:" src/core/transform.js:137"},{message:"unknown tag: alt",line:" src/core/transform.js:163"},{message:"unknown tag: alt",line:" src/core/transform.js:263"},{message:"unknown tag: alt",line:" src/core/transform.js:345"},{message:"unknown tag: alt",line:" src/core/transform.js:386"},{message:"unknown tag: alt",line:" src/core/transform.js:427"},{message:"unknown tag: alt",line:" src/core/vertex.js:22"},{message:"unknown tag: alt",line:" src/core/vertex.js:70"},{message:"unknown tag: alt",line:" src/core/vertex.js:267"},{message:"unknown tag: alt",line:" src/core/vertex.js:332"},{message:"unknown tag: alt",line:" src/core/vertex.js:374"},{message:"unknown tag: alt",line:" src/core/vertex.js:434"},{message:"unknown tag: alt",line:" src/core/vertex.js:502"},{message:"unknown tag: alt",line:" src/core/vertex.js:579"},{message:"unknown tag: alt",line:" src/events/acceleration.js:91"},{message:"unknown tag: alt",line:" src/events/acceleration.js:125"},{message:"unknown tag: alt",line:" src/events/acceleration.js:158"},{message:"unknown tag: alt",line:" src/events/acceleration.js:194"},{message:"unknown tag: alt",line:" src/events/acceleration.js:237"},{message:"unknown tag: alt",line:" src/events/acceleration.js:280"},{message:"unknown tag: alt",line:" src/events/acceleration.js:372"},{message:"unknown tag: alt",line:" src/events/acceleration.js:403"},{message:"unknown tag: alt",line:" src/events/acceleration.js:462"},{message:"unknown tag: alt",line:" src/events/keyboard.js:18"},{message:"unknown tag: alt",line:" src/events/keyboard.js:46"},{message:"unknown tag: alt",line:" src/events/keyboard.js:75"},{message:"unknown tag: alt",line:" src/events/keyboard.js:108"},{message:"unknown tag: alt",line:" src/events/keyboard.js:198"},{message:"unknown tag: alt",line:" src/events/keyboard.js:254"},{message:"unknown tag: alt",line:" src/events/keyboard.js:317"},{message:"unknown tag: alt",line:" src/events/mouse.js:23"},{message:"unknown tag: alt",line:" src/events/mouse.js:49"},{message:"unknown tag: alt",line:" src/events/mouse.js:75"},{message:"unknown tag: alt",line:" src/events/mouse.js:107"},{message:"unknown tag: alt",line:" src/events/mouse.js:137"},{message:"unknown tag: alt",line:" src/events/mouse.js:175"},{message:"unknown tag: alt",line:" src/events/mouse.js:213"},{message:"unknown tag: alt",line:" src/events/mouse.js:255"},{message:"unknown tag: alt",line:" src/events/mouse.js:298"},{message:"unknown tag: alt",line:" src/events/mouse.js:334"},{message:"unknown tag: alt",line:" src/events/mouse.js:416"},{message:"unknown tag: alt",line:" src/events/mouse.js:460"},{message:"unknown tag: alt",line:" src/events/mouse.js:531"},{message:"unknown tag: alt",line:" src/events/mouse.js:597"},{message:"unknown tag: alt",line:" src/events/mouse.js:664"},{message:"unknown tag: alt",line:" src/events/mouse.js:723"},{message:"unknown tag: alt",line:" src/events/mouse.js:781"},{message:"unknown tag: alt",line:" src/events/touch.js:53"},{message:"unknown tag: alt",line:" src/events/touch.js:116"},{message:"unknown tag: alt",line:" src/events/touch.js:178"},{message:"unknown tag: alt",line:" src/image/image.js:24"},{message:"unknown tag: alt",line:" src/image/image.js:115"},{message:"unknown tag: alt",line:" src/image/image.js:233"},{message:"unknown tag: alt",line:" src/image/loading_displaying.js:17"},{message:"replacing incorrect tag: returns with return",line:" src/image/loading_displaying.js:107"},{message:"unknown tag: alt",line:" src/image/loading_displaying.js:125"},{message:"unknown tag: alt",line:" src/image/loading_displaying.js:325"},{message:"unknown tag: alt",line:" src/image/loading_displaying.js:384"},{message:"unknown tag: alt",line:" src/image/loading_displaying.js:449"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:45"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:72"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:106"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:186"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:236"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:270"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:315"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:353"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:435"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:480"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:543"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:577"},{message:"unknown tag: alt",line:" src/image/p5.Image.js:684"},{message:"unknown tag: alt",line:" src/image/pixels.js:14"},{message:"unknown tag: alt",line:" src/image/pixels.js:83"},{message:"unknown tag: alt",line:" src/image/pixels.js:165"},{message:"unknown tag: alt",line:" src/image/pixels.js:212"},{message:"unknown tag: alt",line:" src/image/pixels.js:390"},{message:"unknown tag: alt",line:" src/image/pixels.js:461"},{message:"unknown tag: alt",line:" src/image/pixels.js:498"},{message:"unknown tag: alt",line:" src/image/pixels.js:572"},{message:"unknown tag: alt",line:" src/io/files.js:19"},{message:"unknown tag: alt",line:" src/io/files.js:145"},{message:"unknown tag: alt",line:" src/io/files.js:237"},{message:"unknown tag: alt",line:" src/io/files.js:558"},{message:"unknown tag: alt",line:" src/io/files.js:1194"},{message:"unknown tag: alt",line:" src/io/files.js:1248"},{message:"unknown tag: alt",line:" src/io/files.js:1306"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:58"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:121"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:170"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:215"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:263"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:329"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:498"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:551"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:593"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:757"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:826"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:875"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:937"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:984"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:1029"},{message:"unknown tag: alt",line:" src/io/p5.Table.js:1077"},{message:"unknown tag: alt",line:" src/io/p5.XML.js:11"},{message:"unknown tag: alt",line:" src/math/calculation.js:12"},{message:"unknown tag: alt",line:" src/math/calculation.js:36"},{message:"unknown tag: alt",line:" src/math/calculation.js:76"},{message:"unknown tag: alt",line:" src/math/calculation.js:130"},{message:"unknown tag: alt",line:" src/math/calculation.js:184"},{message:"unknown tag: alt",line:" src/math/calculation.js:234"},{message:"unknown tag: alt",line:" src/math/calculation.js:273"},{message:"unknown tag: alt",line:" src/math/calculation.js:317"},{message:"unknown tag: alt",line:" src/math/calculation.js:371"},{message:"unknown tag: alt",line:" src/math/calculation.js:409"},{message:"unknown tag: alt",line:" src/math/calculation.js:464"},{message:"unknown tag: alt",line:" src/math/calculation.js:507"},{message:"unknown tag: alt",line:" src/math/calculation.js:550"},{message:"unknown tag: alt",line:" src/math/calculation.js:602"},{message:"unknown tag: alt",line:" src/math/calculation.js:636"},{message:"unknown tag: alt",line:" src/math/calculation.js:675"},{message:"unknown tag: alt",line:" src/math/calculation.js:720"},{message:"unknown tag: alt",line:" src/math/noise.js:41"},{message:"unknown tag: alt",line:" src/math/noise.js:171"},{message:"unknown tag: alt",line:" src/math/noise.js:233"},{message:"unknown tag: alt",line:" src/math/p5.Vector.js:13"},{message:"unknown tag: alt",line:" src/math/random.js:47"},{message:"unknown tag: alt",line:" src/math/random.js:78"},{message:"unknown tag: alt",line:" src/math/random.js:168"},{message:"unknown tag: alt",line:" src/math/trigonometry.js:134"},{message:"unknown tag: alt",line:" src/math/trigonometry.js:174"},{message:"unknown tag: alt",line:" src/math/trigonometry.js:206"},{message:"unknown tag: alt",line:" src/math/trigonometry.js:238"},{message:"unknown tag: alt",line:" src/math/trigonometry.js:320"},{message:"unknown tag: alt",line:" src/typography/attributes.js:13"},{message:"unknown tag: alt",line:" src/typography/attributes.js:63"},{message:"unknown tag: alt",line:" src/typography/attributes.js:100"},{message:"unknown tag: alt",line:" src/typography/attributes.js:133"},{message:"unknown tag: alt",line:" src/typography/attributes.js:158"},{message:"unknown tag: alt",line:" src/typography/loading_displaying.js:16"},{message:"unknown tag: alt",line:" src/typography/loading_displaying.js:135"},{message:"unknown tag: alt",line:" src/typography/loading_displaying.js:197"},{message:"unknown tag: alt",line:" src/typography/p5.Font.js:47"},{message:"unknown tag: alt",line:" src/utilities/conversion.js:12"},{message:"unknown tag: alt",line:" src/utilities/string_functions.js:15"},{message:"unknown tag: alt",line:" src/utilities/string_functions.js:44"},{message:"unknown tag: alt",line:" src/utilities/string_functions.js:146"},{message:"unknown tag: alt",line:" src/utilities/string_functions.js:257"},{message:"unknown tag: alt",line:" src/utilities/string_functions.js:339"},{message:"unknown tag: alt",line:" src/utilities/string_functions.js:404"},{message:"unknown tag: alt",line:" src/utilities/string_functions.js:454"},{message:"unknown tag: alt",line:" src/utilities/string_functions.js:550"},{message:"unknown tag: alt",line:" src/utilities/time_date.js:12"},{message:"unknown tag: alt",line:" src/utilities/time_date.js:34"},{message:"unknown tag: alt",line:" src/utilities/time_date.js:56"},{message:"unknown tag: alt",line:" src/utilities/time_date.js:78"},{message:"unknown tag: alt",line:" src/utilities/time_date.js:101"},{message:"unknown tag: alt",line:" src/utilities/time_date.js:123"},{message:"unknown tag: alt",line:" src/utilities/time_date.js:145"},{message:"unknown tag: alt",line:" src/webgl/camera.js:12"},{message:"unknown tag: alt",line:" src/webgl/camera.js:160"},{message:"unknown tag: alt",line:" src/webgl/camera.js:232"},{message:"unknown tag: alt",line:" src/webgl/light.js:40"},{message:"unknown tag: alt",line:" src/webgl/light.js:89"},{message:"unknown tag: alt",line:" src/webgl/light.js:168"},{message:"unknown tag: alt",line:" src/webgl/loading.js:35"},{message:"unknown tag: alt",line:" src/webgl/loading.js:197"},{message:"unknown tag: alt",line:" src/webgl/material.js:81"},{message:"unknown tag: alt",line:" src/webgl/material.js:113"},{message:"unknown tag: alt",line:" src/webgl/material.js:210"},{message:"unknown tag: alt",line:" src/webgl/material.js:253"},{message:"unknown tag: alt",line:" src/webgl/p5.RendererGL.js:352"},{message:"unknown tag: alt",line:" src/webgl/p5.RendererGL.js:400"},{message:"unknown tag: alt",line:" src/webgl/p5.RendererGL.js:431"},{message:"unknown tag: alt",line:" src/webgl/p5.RendererGL.js:460"},{message:"unknown tag: alt",line:" src/webgl/p5.RendererGL.js:505"},{message:"unknown tag: alt",line:" src/webgl/primitives.js:13"},{message:"replacing incorrect tag: params with param",line:" lib/addons/p5.sound.js:1577"},{message:"replacing incorrect tag: returns with return",line:" lib/addons/p5.sound.js:1577"},{message:"replacing incorrect tag: returns with return",line:" lib/addons/p5.sound.js:8218"},{ +message:"Missing item type\nConversions adapted from .\n\nIn these functions, hue is always in the range [0,1); all other components\nare in the range [0,1]. 'Brightness' and 'value' are used interchangeably.",line:" src/color/color_conversion.js:10"},{message:"Missing item type\nConvert an HSBA array to HSLA.",line:" src/color/color_conversion.js:20"},{message:"Missing item type\nConvert an HSBA array to RGBA.",line:" src/color/color_conversion.js:46"},{message:"Missing item type\nConvert an HSLA array to HSBA.",line:" src/color/color_conversion.js:95"},{message:"Missing item type\nConvert an HSLA array to RGBA.\n\nWe need to change basis from HSLA to something that can be more easily be\nprojected onto RGBA. We will choose hue and brightness as our first two\ncomponents, and pick a convenient third one ('zest') so that we don't need\nto calculate formal HSBA saturation.",line:" src/color/color_conversion.js:118"},{message:"Missing item type\nConvert an RGBA array to HSBA.",line:" src/color/color_conversion.js:176"},{message:"Missing item type\nConvert an RGBA array to HSLA.",line:" src/color/color_conversion.js:211"},{message:"Missing item type\nHue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.",line:" src/color/p5.Color.js:118"},{message:"Missing item type\nSaturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise.",line:" src/color/p5.Color.js:149"},{message:"Missing item type\nCSS named colors.",line:" src/color/p5.Color.js:168"},{message:"Missing item type\nThese regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code.\n\nNote that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.",line:" src/color/p5.Color.js:321"},{message:"Missing item type\nFull color string patterns. The capture groups are necessary.",line:" src/color/p5.Color.js:334"},{message:"Missing item type\nFor a number of different inputs, returns a color formatted as [r, g, b, a]\narrays, with each component normalized between 0 and 1.",line:" src/color/p5.Color.js:447"},{message:"Missing item type\nFor HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum.",line:" src/color/p5.Color.js:638"},{message:"Missing item type",line:" src/core/canvas.js:1"},{message:'Missing item type\nThis is the p5 instance constructor.\n\nA p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set preload(), setup(), and/or\ndraw() properties on it for running a sketch.\n\nA p5 sketch can run in "global" or "instance" mode:\n"global" - all properties and methods are attached to the window\n"instance" - all properties and methods are bound to this p5 object',line:" src/core/core.js:15"},{message:"Missing item type\nSets the resolution at which Beziers display.\n\nThe default value is 20.",line:" src/core/curves.js:99"},{message:"Missing item type\nSets the resolution at which curves display.\n\nThe default value is 20.",line:" src/core/curves.js:353"},{message:"Missing item type\nReturns the current framerate.",line:" src/core/environment.js:238"},{message:"Missing item type\nSpecifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default rate is 60 frames per second.\n\nCalling frameRate() with no arguments returns the current framerate.",line:" src/core/environment.js:247"},{message:"Missing item type",line:" src/core/error_helpers.js:1"},{message:"Missing item type\nPrints out a fancy, colorful message to the console log",line:" src/core/error_helpers.js:34"},{message:'Missing item type\nValidates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments\n\nexample:\n var a;\n ellipse(10,10,a,5);\nconsole ouput:\n "It looks like ellipse received an empty variable in spot #2."\n\nexample:\n ellipse(10,"foo",5,5);\nconsole output:\n "ellipse was expecting a number for parameter #1,\n received "foo" instead."',line:" src/core/error_helpers.js:106"},{message:"Missing item type\nPrints out all the colors in the color pallete with white text.\nFor color blindness testing.",line:" src/core/error_helpers.js:273"},{message:'Missing item type\n_globalInit\n\nTODO: ???\nif sketch is on window\nassume "global" mode\nand instantiate p5 automatically\notherwise do nothing',line:" src/core/init.js:5"},{message:"Missing item type\nHelper fxn for sharing pixel methods",line:" src/core/p5.Element.js:1031"},{message:"Missing item type\nResize our canvas element.",line:" src/core/p5.Renderer.js:72"},{message:"Missing item type\nHelper fxn to check font type (system or otf)",line:" src/core/p5.Renderer.js:146"},{message:"Missing item type\nHelper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178",line:" src/core/p5.Renderer.js:202"},{message:"Missing item type\np5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer",line:" src/core/p5.Renderer2D.js:9"},{message:"Missing item type\nGenerate a cubic Bezier representing an arc on the unit circle of total\nangle `size` radians, beginning `start` radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.\n\nSee www.joecridge.me/bezier.pdf for an explanation of the method.",line:" src/core/p5.Renderer2D.js:356"},{message:"Missing item type\nshim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.",line:" src/core/shim.js:65"},{message:"Missing item type\nprivate helper function to handle the user passing objects in\nduring construction or calls to create()",line:" src/data/p5.TypedDict.js:179"},{message:"Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type",line:" src/data/p5.TypedDict.js:321"},{message:"Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type",line:" src/data/p5.TypedDict.js:368"},{message:"Missing item type\nprivate helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'",line:" src/data/p5.TypedDict.js:485"},{message:"Missing item type\nprivate helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'",line:" src/data/p5.TypedDict.js:548"},{message:"Missing item type\n_updatePAccelerations updates the pAcceleration values",line:" src/events/acceleration.js:80"},{message:"Missing item type\nHolds the key codes of currently pressed keys.",line:" src/events/keyboard.js:12"},{message:"Missing item type\nThe onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.",line:" src/events/keyboard.js:307"},{message:"Missing item type\nThe checkDownKeys function returns a boolean true if any keys pressed\nand a false if no keys are currently pressed.\n\nHelps avoid instances where a multiple keys are pressed simultaneously and\nreleasing a single key will then switch the\nkeyIsPressed property to true.",line:" src/events/keyboard.js:364"},{message:"Missing item type\nThis module defines the filters for use with image buffers.\n\nThis module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy.\n\nGenerally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.\n\nA number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation.",line:" src/image/filters.js:3"},{message:"Missing item type\nReturns the pixel buffer for a canvas",line:" src/image/filters.js:28"},{message:"Missing item type\nReturns a 32 bit number containing ARGB data at ith pixel in the\n1D array containing pixels data.",line:" src/image/filters.js:51"},{message:"Missing item type\nModifies pixels RGBA values to values contained in the data object.",line:" src/image/filters.js:70"},{message:"Missing item type\nReturns the ImageData object for a canvas\nhttps://developer.mozilla.org/en-US/docs/Web/API/ImageData",line:" src/image/filters.js:90"},{message:"Missing item type\nReturns a blank ImageData object.",line:" src/image/filters.js:113"},{message:"Missing item type\nApplys a filter function to a canvas.\n\nThe difference between this and the actual filter functions defined below\nis that the filter functions generally modify the pixel buffer but do\nnot actually put that data back to the canvas (where it would actually\nupdate what is visible). By contrast this method does make the changes\nactually visible in the canvas.\n\nThe apply method is the method that callers of this module would generally\nuse. It has been separated from the actual filters to support an advanced\nuse case of creating a filter chain that executes without actually updating\nthe canvas in between everystep.",line:" src/image/filters.js:129"},{message:"Missing item type\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.\n\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/",line:" src/image/filters.js:167"},{message:"Missing item type\nConverts any colors in the image to grayscale equivalents.\nNo parameter is used.\n\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/",line:" src/image/filters.js:202"},{message:"Missing item type\nSets the alpha channel to entirely opaque. No parameter is used.",line:" src/image/filters.js:224"},{message:"Missing item type\nSets each pixel to its inverse value. No parameter is used.",line:" src/image/filters.js:239"},{message:"Missing item type\nLimits each channel of the image to the number of colors specified as\nthe parameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.\n\nAdapted from java based processing implementation",line:" src/image/filters.js:255"},{message:"Missing item type\nreduces the bright areas in an image",line:" src/image/filters.js:286"},{message:"Missing item type\nincreases the bright areas in an image",line:" src/image/filters.js:367"},{message:"Missing item type\nThis module defines the p5 methods for the p5.Image class\nfor drawing images to the main display canvas.",line:" src/image/image.js:8"},{message:"Missing item type\nValidates clipping params. Per drawImage spec sWidth and sHight cannot be\nnegative or greater than image intrinsic width and height",line:" src/image/loading_displaying.js:107"},{message:"Missing item type\nApply the current tint color to the input image, return the resulting\ncanvas.",line:" src/image/loading_displaying.js:413"},{message:"Missing item type\nThis module defines the p5.Image class and P5 methods for\ndrawing images to the main display canvas.",line:" src/image/p5.Image.js:9"},{message:"Missing item type\nHelper fxn for sharing pixel methods",line:" src/image/p5.Image.js:177"},{message:"Missing item type\nGenerate a blob of file data as a url to prepare for download.\nAccepts an array of data, a filename, and an extension (optional).\nThis is a private function because it does not do any formatting,\nbut it is used by saveStrings, saveJSON, saveTable etc.",line:" src/io/files.js:1433"},{message:"Missing item type\nForces download. Accepts a url to filedata/blob, a filename,\nand an extension (optional).\nThis is a private function because it does not do any formatting,\nbut it is used by saveStrings, saveJSON, saveTable etc.",line:" src/io/files.js:1456"},{message:"Missing item type\nReturns a file extension, or another string\nif the provided parameter has no extension.",line:" src/io/files.js:1496"},{message:"Missing item type\nReturns true if the browser is Safari, false if not.\nSafari makes trouble for downloading files.",line:" src/io/files.js:1528"},{message:"Missing item type\nHelper function, a callback for download that deletes\nan invisible anchor element from the DOM once the file\nhas been automatically downloaded.",line:" src/io/files.js:1540"},{message:'Missing item type\nTable Options\n

Generic class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.

\n

CSV files are\n\ncomma separated values, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don\'t bother with the\nquotes.

\n

File names should end with .csv if they\'re comma separated.

\n

A rough "spec" for CSV can be found\nhere.

\n

To load files, use the loadTable method.

\n

To save tables to your computer, use the save method\n or the saveTable method.

\n\nPossible options include:\n
    \n
  • csv - parse the table as comma-separated values\n
  • tsv - parse the table as tab-separated values\n
  • header - this table has a header (title) row\n
',line:" src/io/p5.Table.js:12"},{message:"Missing item type\nReturns the total number of columns in a Table.",line:" src/io/p5.Table.js:644"},{message:"Missing item type\nThis method is called while the parsing of XML (when loadXML() is\ncalled). The difference between this method and the setContent()\nmethod defined later is that this one is used to set the content\nwhen the node in question has more nodes under it and so on and\nnot directly text content. While in the other one is used when\nthe node in question directly has text inside it.",line:" src/io/p5.XML.js:767"},{message:"Missing item type\nThis method is called while the parsing of XML (when loadXML() is\ncalled). The XML node is passed and its attributes are stored in the\np5.XML's attribute Object.",line:" src/io/p5.XML.js:784"},{message:"Missing item type\nMultiplies a vector by a scalar and returns a new vector.",line:" src/math/p5.Vector.js:963"},{message:"Missing item type\nDivides a vector by a scalar and returns a new vector.",line:" src/math/p5.Vector.js:990"},{message:"Missing item type\nCalculates the dot product of two vectors.",line:" src/math/p5.Vector.js:1018"},{message:"Missing item type\nCalculates the cross product of two vectors.",line:" src/math/p5.Vector.js:1032"},{message:"Missing item type\nCalculates the Euclidean distance between two points (considering a\npoint as a vector object).",line:" src/math/p5.Vector.js:1046"},{message:"Missing item type\nLinear interpolate a vector to another vector and return the result as a\nnew vector.",line:" src/math/p5.Vector.js:1061"},{message:"Missing item type\nHelper function to measure ascent and descent.",line:" src/typography/attributes.js:248"},{message:"Missing item type\nReturns the set of opentype glyphs for the supplied string.\n\nNote that there is not a strict one-to-one mapping between characters\nand glyphs, so the list of returned glyphs can be larger or smaller\n than the length of the given string.",line:" src/typography/p5.Font.js:206"},{message:"Missing item type\nReturns an opentype path for the supplied string and position.",line:" src/typography/p5.Font.js:221"},{message:"Missing item type\nParse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:\n\nv -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5\n\nf 4 3 2 1",line:" src/webgl/loading.js:98"},{message:"Missing item type",line:" src/webgl/material.js:297"},{message:"Missing item type\ncomputes smooth normals per vertex as an average of each\nface.",line:" src/webgl/p5.Geometry.js:86"},{message:"Missing item type\nAverages the vertex normals. Used in curved\nsurfaces",line:" src/webgl/p5.Geometry.js:111"},{message:"Missing item type\nAverages pole normals. Used in spherical primitives",line:" src/webgl/p5.Geometry.js:130"},{message:"Missing item type\nCreate a 2D array for establishing stroke connections",line:" src/webgl/p5.Geometry.js:161"},{message:"Missing item type\nCreate 4 vertices for each stroke line, two at the beginning position\nand two at the end position. These vertices are displaced relative to\nthat line's normal on the GPU",line:" src/webgl/p5.Geometry.js:182"},{message:"Missing item type\nModifies all vertices to be centered within the range -100 to 100.",line:" src/webgl/p5.Geometry.js:209"},{message:"Missing item type",line:" src/webgl/p5.Matrix.js:1"},{message:"Missing item type\nA class to describe a 4x4 matrix\nfor model and view matrix manipulation in the p5js webgl renderer.\nclass p5.Matrix",line:" src/webgl/p5.Matrix.js:19"},{message:"Missing item type\nSets the x, y, and z component of the vector using two or three separate\nvariables, the data from a p5.Matrix, or the values from a float array.",line:" src/webgl/p5.Matrix.js:75"},{message:"Missing item type\nGets a copy of the vector, returns a p5.Matrix object.",line:" src/webgl/p5.Matrix.js:113"},{message:"Missing item type\nreturn a copy of a matrix",line:" src/webgl/p5.Matrix.js:122"},{message:"Missing item type\nreturn an identity matrix",line:" src/webgl/p5.Matrix.js:147"},{message:"Missing item type\ntranspose according to a given matrix",line:" src/webgl/p5.Matrix.js:155"},{message:"Missing item type\ninvert matrix according to a give matrix",line:" src/webgl/p5.Matrix.js:215"},{message:"Missing item type\nInverts a 3x3 matrix",line:" src/webgl/p5.Matrix.js:300"},{message:"Missing item type\ntransposes a 3x3 p5.Matrix by a mat3",line:" src/webgl/p5.Matrix.js:336"},{message:"Missing item type\nconverts a 4x4 matrix to its 3x3 inverse tranform\ncommonly used in MVMatrix to NMatrix conversions.",line:" src/webgl/p5.Matrix.js:352"},{message:"Missing item type\ninspired by Toji's mat4 determinant",line:" src/webgl/p5.Matrix.js:380"},{message:"Missing item type\nmultiply two mat4s",line:" src/webgl/p5.Matrix.js:403"},{message:"Missing item type\nscales a p5.Matrix by scalars or a vector",line:" src/webgl/p5.Matrix.js:460"},{message:"Missing item type\nrotate our Matrix around an axis by the given angle.",line:" src/webgl/p5.Matrix.js:505"},{message:"Missing item type",line:" src/webgl/p5.Matrix.js:584"},{message:"Missing item type\nsets the perspective matrix",line:" src/webgl/p5.Matrix.js:614"},{message:"Missing item type\nsets the ortho matrix",line:" src/webgl/p5.Matrix.js:648"},{message:"Missing item type\nPRIVATE",line:" src/webgl/p5.Matrix.js:683"},{message:"Missing item type\nWelcome to RendererGL Immediate Mode.\nImmediate mode is used for drawing custom shapes\nfrom a set of vertices. Immediate Mode is activated\nwhen you call beginShape() & de-activated when you call endShape().\nImmediate mode is a style of programming borrowed\nfrom OpenGL's (now-deprecated) immediate mode.\nIt differs from p5.js' default, Retained Mode, which caches\ngeometries and buffers on the CPU to reduce the number of webgl\ndraw calls. Retained mode is more efficient & performative,\nhowever, Immediate Mode is useful for sketching quick\ngeometric ideas.",line:" src/webgl/p5.RendererGL.Immediate.js:1"},{message:"Missing item type\nBegin shape drawing. This is a helpful way of generating\ncustom shapes quickly. However in WEBGL mode, application\nperformance will likely drop as a result of too many calls to\nbeginShape() / endShape(). As a high performance alternative,\nplease use p5.js geometry primitives.",line:" src/webgl/p5.RendererGL.Immediate.js:19"},{message:"Missing item type\nadds a vertex to be drawn in a custom Shape.",line:" src/webgl/p5.RendererGL.Immediate.js:60"},{message:"Missing item type\nEnd shape drawing and render vertices to screen.",line:" src/webgl/p5.RendererGL.Immediate.js:103"},{message:"Missing item type\ninitializes buffer defaults. runs each time a new geometry is\nregistered",line:" src/webgl/p5.RendererGL.Retained.js:8"},{message:"Missing item type\ncreateBuffers description",line:" src/webgl/p5.RendererGL.Retained.js:33"},{message:"Missing item type\nDraws buffers given a geometry key ID",line:" src/webgl/p5.RendererGL.Retained.js:84"},{message:"Missing item type\nmodel view, projection, & normal\nmatrices",line:" src/webgl/p5.RendererGL.js:69"},{message:"Missing item type\n[background description]",line:" src/webgl/p5.RendererGL.js:331"},{message:"Missing item type\n[resize description]",line:" src/webgl/p5.RendererGL.js:642"},{message:"Missing item type\nclears color and depth buffers\nwith r,g,b,a",line:" src/webgl/p5.RendererGL.js:659"},{message:"Missing item type\n[translate description]",line:" src/webgl/p5.RendererGL.js:675"},{message:"Missing item type\nScales the Model View Matrix by a vector",line:" src/webgl/p5.RendererGL.js:693"},{message:"Missing item type\npushes a copy of the model view matrix onto the\nMV Matrix stack.",line:" src/webgl/p5.RendererGL.js:725"},{message:"Missing item type\n[pop description]",line:" src/webgl/p5.RendererGL.js:734"},{message:"Missing item type\nturn a two dimensional array into one dimensional array",line:" src/webgl/p5.RendererGL.js:904"},{message:"Missing item type\nturn a p5.Vector Array into a one dimensional number array",line:" src/webgl/p5.RendererGL.js:918"},{message:"Missing item type",line:" src/webgl/primitives.js:265"},{message:"Missing item type\nDraw a line given two points",line:" src/webgl/primitives.js:860"},{message:"Missing item type\nHelper function for select and selectAll",line:" lib/addons/p5.dom.js:156"},{message:"Missing item type\nHelper function for getElement and getElements.",line:" lib/addons/p5.dom.js:172"},{message:"Missing item type\nHelpers for create methods.",line:" lib/addons/p5.dom.js:225"},{message:"Missing item type",line:" lib/addons/p5.dom.js:369"},{message:"Missing item type",line:" lib/addons/p5.dom.js:874"},{message:"Missing item type",line:" lib/addons/p5.dom.js:937"},{message:"Missing item type",line:" lib/addons/p5.dom.js:965"},{message:"Missing item type\nCenters a p5 Element either vertically, horizontally,\nor both, relative to its parent or according to\nthe body if the Element has no parent. If no argument is passed\nthe Element is aligned both vertically and horizontally.",line:" lib/addons/p5.dom.js:1223"},{message:"Missing item type",line:" lib/addons/p5.dom.js:2259"},{message:"Missing item type",line:" lib/addons/p5.dom.js:2329"},{message:"Missing item type",line:" lib/addons/p5.dom.js:2351"},{message:"Missing item type\np5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound\n\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors\n\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE\n\nSome of the many audio libraries & resources that inspire p5.sound:\n - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js\n - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/\n - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0\n - wavesurfer.js https://github.com/katspaugh/wavesurfer.js\n - Web Audio Components by Jordan Santell https://github.com/web-audio-components\n - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound\n\n Web Audio API: http://w3.org/TR/webaudio/",line:" lib/addons/p5.sound.js:46"},{message:"Missing item type\nDetermine which filetypes are supported (inspired by buzz.js)\nThe audio element (el) will only be used to test browser support for various audio formats",line:" lib/addons/p5.sound.js:226"},{message:"Missing item type\nMaster contains AudioContext and the master sound output.",line:" lib/addons/p5.sound.js:296"},{message:"Missing item type\na silent connection to the DesinationNode\nwhich will ensure that anything connected to it\nwill not be garbage collected",line:" lib/addons/p5.sound.js:393"},{message:"Missing item type\nReturns the closest MIDI note value for\na given frequency.",line:" lib/addons/p5.sound.js:425"},{message:"Missing item type\nUsed by Osc and Env to chain signal math",line:" lib/addons/p5.sound.js:584"},{message:"Missing item type\nThis is a helper function that the p5.SoundFile calls to load\nitself. Accepts a callback (the name of another function)\nas an optional parameter.",line:" lib/addons/p5.sound.js:917"},{message:"Missing item type\nSet a p5.SoundFile's looping flag to true or false. If the sound\nis currently playing, this change will take effect when it\nreaches the end of the current playback.",line:" lib/addons/p5.sound.js:1233"},{message:"Missing item type\nReturns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.",line:" lib/addons/p5.sound.js:1253"},{message:"Missing item type\nStop playback on all of this soundfile's sources.",line:" lib/addons/p5.sound.js:1311"},{message:"Missing item type\nReturns the current stereo pan position (-1.0 to 1.0)",line:" lib/addons/p5.sound.js:1413"},{message:"Missing item type",line:" lib/addons/p5.sound.js:1746"},{message:"Missing item type\nReplace the current Audio Buffer with a new Buffer.",line:" lib/addons/p5.sound.js:1764"},{message:"Missing item type",line:" lib/addons/p5.sound.js:2026"},{message:"Missing item type",line:" lib/addons/p5.sound.js:3024"},{message:"Missing item type",line:" lib/addons/p5.sound.js:3427"},{message:"Missing item type",line:" lib/addons/p5.sound.js:3448"},{message:"Missing item type",line:" lib/addons/p5.sound.js:3507"},{message:"Missing item type",line:" lib/addons/p5.sound.js:3960"},{message:"Missing item type",line:" lib/addons/p5.sound.js:4097"},{message:"Missing item type",line:" lib/addons/p5.sound.js:4130"},{message:"Missing item type",line:" lib/addons/p5.sound.js:4176"},{message:"Missing item type",line:" lib/addons/p5.sound.js:4197"},{message:"Missing item type",line:" lib/addons/p5.sound.js:4217"},{message:"Missing item type\nConnect a p5.sound object or Web Audio node to this\np5.Signal so that its amplitude values can be scaled.",line:" lib/addons/p5.sound.js:4330"},{message:"Missing item type",line:" lib/addons/p5.sound.js:4923"},{message:"Missing item type",line:" lib/addons/p5.sound.js:5109"},{message:"Missing item type\nSet the amplitude of the noise between 0 and 1.0. Or,\nmodulate amplitude with an audio signal such as an oscillator.",line:" lib/addons/p5.sound.js:6393"},{message:"Missing item type\nAdd input sources to the list of available sources.",line:" lib/addons/p5.sound.js:6634"},{message:"Missing item type",line:" lib/addons/p5.sound.js:6763"},{message:"Missing item type",line:" lib/addons/p5.sound.js:6779"},{message:"Missing item type",line:" lib/addons/p5.sound.js:6803"},{message:"Missing item type",line:" lib/addons/p5.sound.js:6829"},{message:"Missing item type",line:" lib/addons/p5.sound.js:6858"},{message:"Missing item type",line:" lib/addons/p5.sound.js:6888"},{message:"Missing item type",line:" lib/addons/p5.sound.js:6936"},{message:"Missing item type",line:" lib/addons/p5.sound.js:6959"},{message:"Missing item type",line:" lib/addons/p5.sound.js:6984"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7005"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7012"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7034"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7063"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7090"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7118"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7146"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7192"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7223"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7241"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7629"},{message:"Missing item type",line:" lib/addons/p5.sound.js:7651"},{message:"Missing item type\nThe p5.Effect class is built\n using Tone.js CrossFade",line:" lib/addons/p5.sound.js:7721"},{message:"Missing item type\nIn classes that extend\np5.Effect, connect effect nodes\nto the wet parameter",line:" lib/addons/p5.sound.js:7727"},{message:"Missing item type\nInspired by Simple Reverb by Jordan Santell\nhttps://github.com/web-audio-components/simple-reverb/blob/master/index.js\n\nUtility function for building an impulse response\nbased on the module parameters.",line:" lib/addons/p5.sound.js:8467"},{message:"Missing item type\nPrivate method to load a buffer as an Impulse Response,\nassign it to the convolverNode, and add to the Array of .impulses.",line:" lib/addons/p5.sound.js:8631"},{message:"Missing item type",line:" lib/addons/p5.sound.js:8817"},{message:"Missing item type",line:" lib/addons/p5.sound.js:8842"},{message:"Missing item type\nSet the global tempo, in beats per minute, for all\np5.Parts. This method will impact all active p5.Parts.",line:" lib/addons/p5.sound.js:9059"},{message:"Missing item type\nSet the tempo for all parts in the score",line:" lib/addons/p5.sound.js:9513"},{message:"Missing item type\nReturn the current reduction value",line:" lib/addons/p5.sound.js:9731"},{message:"Missing item type\ncallback invoked when the recording is over",line:" lib/addons/p5.sound.js:9828"},{message:"Missing item type\ninternal method called on audio process",line:" lib/addons/p5.sound.js:9914"}]}},{}],2:[function(a,b,c){!function(a){"use strict";function b(a){var b=a.charCodeAt(0);return b===f||b===k?62:b===g||b===l?63:b0)throw new Error("Invalid string. Length must be a multiple of 4");var k=a.length;i="="===a.charAt(k-2)?2:"="===a.charAt(k-1)?1:0,j=new e(3*a.length/4-i),g=i>0?a.length-4:a.length;var l=0;for(d=0,f=0;d>16),c((65280&h)>>8),c(255&h);return 2===i?(h=b(a.charAt(d))<<2|b(a.charAt(d+1))>>4,c(255&h)):1===i&&(h=b(a.charAt(d))<<10|b(a.charAt(d+1))<<4|b(a.charAt(d+2))>>2,c(h>>8&255),c(255&h)),j}function d(a){function b(a){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(a)}function c(a){return b(a>>18&63)+b(a>>12&63)+b(a>>6&63)+b(63&a)}var d,e,f,g=a.length%3,h="";for(d=0,f=a.length-g;d>2),h+=b(e<<4&63),h+="==";break;case 2:e=(a[a.length-2]<<8)+a[a.length-1],h+=b(e>>10),h+=b(e>>4&63),h+=b(e<<2&63),h+="="}return h} +var e="undefined"!=typeof Uint8Array?Uint8Array:Array,f="+".charCodeAt(0),g="/".charCodeAt(0),h="0".charCodeAt(0),i="a".charCodeAt(0),j="A".charCodeAt(0),k="-".charCodeAt(0),l="_".charCodeAt(0);a.toByteArray=c,a.fromByteArray=d}(void 0===c?this.base64js={}:c)},{}],3:[function(a,b,c){},{}],4:[function(a,b,c){(function(b){"use strict";function d(){function a(){}try{var b=new Uint8Array(1);return b.foo=function(){return 42},b.constructor=a,42===b.foo()&&b.constructor===a&&"function"==typeof b.subarray&&0===b.subarray(1,1).byteLength}catch(a){return!1}}function e(){return f.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function f(a){return this instanceof f?(f.TYPED_ARRAY_SUPPORT||(this.length=0,this.parent=void 0),"number"==typeof a?g(this,a):"string"==typeof a?h(this,a,arguments.length>1?arguments[1]:"utf8"):i(this,a)):arguments.length>1?new f(a,arguments[1]):new f(a)}function g(a,b){if(a=p(a,b<0?0:0|q(b)),!f.TYPED_ARRAY_SUPPORT)for(var c=0;c>>1&&(a.parent=Z),a}function q(a){if(a>=e())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+e().toString(16)+" bytes");return 0|a}function r(a,b){if(!(this instanceof r))return new r(a,b);var c=new f(a,b);return delete c.parent,c}function s(a,b){"string"!=typeof a&&(a=""+a);var c=a.length;if(0===c)return 0;for(var d=!1;;)switch(b){case"ascii":case"binary":case"raw":case"raws":return c;case"utf8":case"utf-8":return R(a).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*c;case"hex":return c>>>1;case"base64":return U(a).length;default:if(d)return R(a).length;b=(""+b).toLowerCase(),d=!0}}function t(a,b,c){var d=!1;if(b|=0,c=void 0===c||c===1/0?this.length:0|c,a||(a="utf8"),b<0&&(b=0),c>this.length&&(c=this.length),c<=b)return"";for(;;)switch(a){case"hex":return F(this,b,c);case"utf8":case"utf-8":return B(this,b,c);case"ascii":return D(this,b,c);case"binary":return E(this,b,c);case"base64":return A(this,b,c);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G(this,b,c);default:if(d)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase(),d=!0}}function u(a,b,c,d){c=Number(c)||0;var e=a.length-c;d?(d=Number(d))>e&&(d=e):d=e;var f=b.length;if(f%2!=0)throw new Error("Invalid hex string");d>f/2&&(d=f/2);for(var g=0;g239?4:f>223?3:f>191?2:1;if(e+h<=c){var i,j,k,l;switch(h){case 1:f<128&&(g=f);break;case 2:i=a[e+1],128==(192&i)&&(l=(31&f)<<6|63&i)>127&&(g=l);break;case 3:i=a[e+1],j=a[e+2],128==(192&i)&&128==(192&j)&&(l=(15&f)<<12|(63&i)<<6|63&j)>2047&&(l<55296||l>57343)&&(g=l);break;case 4:i=a[e+1],j=a[e+2],k=a[e+3],128==(192&i)&&128==(192&j)&&128==(192&k)&&(l=(15&f)<<18|(63&i)<<12|(63&j)<<6|63&k)>65535&&l<1114112&&(g=l)}}null===g?(g=65533,h=1):g>65535&&(g-=65536,d.push(g>>>10&1023|55296),g=56320|1023&g),d.push(g),e+=h}return C(d)}function C(a){var b=a.length;if(b<=$)return String.fromCharCode.apply(String,a);for(var c="",d=0;dd)&&(c=d);for(var e="",f=b;fc)throw new RangeError("Trying to access beyond buffer length")}function I(a,b,c,d,e,g){if(!f.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>e||ba.length)throw new RangeError("index out of range")}function J(a,b,c,d){b<0&&(b=65535+b+1);for(var e=0,f=Math.min(a.length-c,2);e>>8*(d?e:1-e)}function K(a,b,c,d){b<0&&(b=4294967295+b+1);for(var e=0,f=Math.min(a.length-c,4);e>>8*(d?e:3-e)&255}function L(a,b,c,d,e,f){if(b>e||ba.length)throw new RangeError("index out of range");if(c<0)throw new RangeError("index out of range")}function M(a,b,c,d,e){return e||L(a,b,c,4,3.4028234663852886e38,-3.4028234663852886e38),X.write(a,b,c,d,23,4),c+4}function N(a,b,c,d,e){return e||L(a,b,c,8,1.7976931348623157e308,-1.7976931348623157e308),X.write(a,b,c,d,52,8),c+8}function O(a){if(a=P(a).replace(aa,""),a.length<2)return"";for(;a.length%4!=0;)a+="=";return a}function P(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")}function Q(a){return a<16?"0"+a.toString(16):a.toString(16)}function R(a,b){b=b||1/0;for(var c,d=a.length,e=null,f=[],g=0;g55295&&c<57344){if(!e){if(c>56319){(b-=3)>-1&&f.push(239,191,189);continue}if(g+1===d){(b-=3)>-1&&f.push(239,191,189);continue}e=c;continue}if(c<56320){(b-=3)>-1&&f.push(239,191,189),e=c;continue}c=65536+(e-55296<<10|c-56320)}else e&&(b-=3)>-1&&f.push(239,191,189);if(e=null,c<128){if((b-=1)<0)break;f.push(c)}else if(c<2048){if((b-=2)<0)break;f.push(c>>6|192,63&c|128)}else if(c<65536){if((b-=3)<0)break;f.push(c>>12|224,c>>6&63|128,63&c|128)}else{if(!(c<1114112))throw new Error("Invalid code point");if((b-=4)<0)break;f.push(c>>18|240,c>>12&63|128,c>>6&63|128,63&c|128)}}return f}function S(a){for(var b=[],c=0;c>8,e=c%256,f.push(e),f.push(d);return f}function U(a){return W.toByteArray(O(a))}function V(a,b,c,d){for(var e=0;e=b.length||e>=a.length);e++)b[e+c]=a[e];return e}var W=a("base64-js"),X=a("ieee754"),Y=a("isarray");c.Buffer=f,c.SlowBuffer=r,c.INSPECT_MAX_BYTES=50,f.poolSize=8192;var Z={};f.TYPED_ARRAY_SUPPORT=void 0!==b.TYPED_ARRAY_SUPPORT?b.TYPED_ARRAY_SUPPORT:d(),f.TYPED_ARRAY_SUPPORT?(f.prototype.__proto__=Uint8Array.prototype,f.__proto__=Uint8Array):(f.prototype.length=void 0,f.prototype.parent=void 0),f.isBuffer=function(a){return!(null==a||!a._isBuffer)},f.compare=function(a,b){if(!f.isBuffer(a)||!f.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var c=a.length,d=b.length,e=0,g=Math.min(c,d);e0&&(a=this.toString("hex",0,b).match(/.{2}/g).join(" "),this.length>b&&(a+=" ... ")),""},f.prototype.compare=function(a){if(!f.isBuffer(a))throw new TypeError("Argument must be a Buffer");return this===a?0:f.compare(this,a)},f.prototype.indexOf=function(a,b){function c(a,b,c){for(var d=-1,e=0;c+e2147483647?b=2147483647:b<-2147483648&&(b=-2147483648),b>>=0,0===this.length)return-1;if(b>=this.length)return-1;if(b<0&&(b=Math.max(this.length+b,0)),"string"==typeof a)return 0===a.length?-1:String.prototype.indexOf.call(this,a,b);if(f.isBuffer(a))return c(this,a,b);if("number"==typeof a)return f.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,a,b):c(this,[a],b);throw new TypeError("val must be string, number or Buffer")},f.prototype.get=function(a){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(a)},f.prototype.set=function(a,b){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(a,b)},f.prototype.write=function(a,b,c,d){if(void 0===b)d="utf8",c=this.length,b=0;else if(void 0===c&&"string"==typeof b)d=b,c=this.length,b=0;else if(isFinite(b))b|=0,isFinite(c)?(c|=0,void 0===d&&(d="utf8")):(d=c,c=void 0);else{var e=d;d=b,b=0|c,c=e}var f=this.length-b;if((void 0===c||c>f)&&(c=f),a.length>0&&(c<0||b<0)||b>this.length)throw new RangeError("attempt to write outside buffer bounds");d||(d="utf8");for(var g=!1;;)switch(d){case"hex":return u(this,a,b,c);case"utf8":case"utf-8":return v(this,a,b,c);case"ascii":return w(this,a,b,c);case"binary":return x(this,a,b,c);case"base64":return y(this,a,b,c);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,a,b,c);default:if(g)throw new TypeError("Unknown encoding: "+d);d=(""+d).toLowerCase(),g=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var $=4096;f.prototype.slice=function(a,b){var c=this.length;a=~~a,b=void 0===b?c:~~b,a<0?(a+=c)<0&&(a=0):a>c&&(a=c),b<0?(b+=c)<0&&(b=0):b>c&&(b=c),b0&&(e*=256);)d+=this[a+--b]*e;return d},f.prototype.readUInt8=function(a,b){return b||H(a,1,this.length),this[a]},f.prototype.readUInt16LE=function(a,b){return b||H(a,2,this.length),this[a]|this[a+1]<<8},f.prototype.readUInt16BE=function(a,b){return b||H(a,2,this.length),this[a]<<8|this[a+1]},f.prototype.readUInt32LE=function(a,b){return b||H(a,4,this.length),(this[a]|this[a+1]<<8|this[a+2]<<16)+16777216*this[a+3]},f.prototype.readUInt32BE=function(a,b){return b||H(a,4,this.length),16777216*this[a]+(this[a+1]<<16|this[a+2]<<8|this[a+3])},f.prototype.readIntLE=function(a,b,c){a|=0,b|=0,c||H(a,b,this.length);for(var d=this[a],e=1,f=0;++f=e&&(d-=Math.pow(2,8*b)),d},f.prototype.readIntBE=function(a,b,c){a|=0,b|=0,c||H(a,b,this.length);for(var d=b,e=1,f=this[a+--d];d>0&&(e*=256);)f+=this[a+--d]*e;return e*=128,f>=e&&(f-=Math.pow(2,8*b)),f},f.prototype.readInt8=function(a,b){return b||H(a,1,this.length),128&this[a]?(255-this[a]+1)*-1:this[a]},f.prototype.readInt16LE=function(a,b){b||H(a,2,this.length);var c=this[a]|this[a+1]<<8;return 32768&c?4294901760|c:c},f.prototype.readInt16BE=function(a,b){b||H(a,2,this.length);var c=this[a+1]|this[a]<<8;return 32768&c?4294901760|c:c},f.prototype.readInt32LE=function(a,b){return b||H(a,4,this.length),this[a]|this[a+1]<<8|this[a+2]<<16|this[a+3]<<24},f.prototype.readInt32BE=function(a,b){return b||H(a,4,this.length),this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]},f.prototype.readFloatLE=function(a,b){return b||H(a,4,this.length),X.read(this,a,!0,23,4)},f.prototype.readFloatBE=function(a,b){return b||H(a,4,this.length),X.read(this,a,!1,23,4)},f.prototype.readDoubleLE=function(a,b){return b||H(a,8,this.length),X.read(this,a,!0,52,8)},f.prototype.readDoubleBE=function(a,b){return b||H(a,8,this.length),X.read(this,a,!1,52,8)},f.prototype.writeUIntLE=function(a,b,c,d){a=+a,b|=0,c|=0,d||I(this,a,b,c,Math.pow(2,8*c),0);var e=1,f=0;for(this[b]=255&a;++f=0&&(f*=256);)this[b+e]=a/f&255;return b+c},f.prototype.writeUInt8=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,1,255,0),f.TYPED_ARRAY_SUPPORT||(a=Math.floor(a)),this[b]=255&a,b+1},f.prototype.writeUInt16LE=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,2,65535,0),f.TYPED_ARRAY_SUPPORT?(this[b]=255&a,this[b+1]=a>>>8):J(this,a,b,!0),b+2},f.prototype.writeUInt16BE=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,2,65535,0),f.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=255&a):J(this,a,b,!1),b+2},f.prototype.writeUInt32LE=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,4,4294967295,0),f.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=255&a):K(this,a,b,!0),b+4},f.prototype.writeUInt32BE=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,4,4294967295,0),f.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=255&a):K(this,a,b,!1),b+4},f.prototype.writeIntLE=function(a,b,c,d){if(a=+a,b|=0,!d){var e=Math.pow(2,8*c-1);I(this,a,b,c,e-1,-e)}var f=0,g=1,h=a<0?1:0;for(this[b]=255&a;++f>0)-h&255;return b+c},f.prototype.writeIntBE=function(a,b,c,d){if(a=+a,b|=0,!d){var e=Math.pow(2,8*c-1);I(this,a,b,c,e-1,-e)}var f=c-1,g=1,h=a<0?1:0;for(this[b+f]=255&a;--f>=0&&(g*=256);)this[b+f]=(a/g>>0)-h&255;return b+c},f.prototype.writeInt8=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,1,127,-128),f.TYPED_ARRAY_SUPPORT||(a=Math.floor(a)),a<0&&(a=255+a+1),this[b]=255&a,b+1},f.prototype.writeInt16LE=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,2,32767,-32768),f.TYPED_ARRAY_SUPPORT?(this[b]=255&a,this[b+1]=a>>>8):J(this,a,b,!0),b+2},f.prototype.writeInt16BE=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,2,32767,-32768),f.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=255&a):J(this,a,b,!1),b+2},f.prototype.writeInt32LE=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,4,2147483647,-2147483648),f.TYPED_ARRAY_SUPPORT?(this[b]=255&a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):K(this,a,b,!0),b+4},f.prototype.writeInt32BE=function(a,b,c){return a=+a,b|=0,c||I(this,a,b,4,2147483647,-2147483648),a<0&&(a=4294967295+a+1),f.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=255&a):K(this,a,b,!1),b+4},f.prototype.writeFloatLE=function(a,b,c){return M(this,a,b,!0,c)},f.prototype.writeFloatBE=function(a,b,c){return M(this,a,b,!1,c)},f.prototype.writeDoubleLE=function(a,b,c){return N(this,a,b,!0,c)},f.prototype.writeDoubleBE=function(a,b,c){return N(this,a,b,!1,c)},f.prototype.copy=function(a,b,c,d){if(c||(c=0),d||0===d||(d=this.length),b>=a.length&&(b=a.length),b||(b=0),d>0&&d=this.length)throw new RangeError("sourceStart out of bounds");if(d<0)throw new RangeError("sourceEnd out of bounds");d>this.length&&(d=this.length),a.length-b=0;e--)a[e+b]=this[e+c];else if(g<1e3||!f.TYPED_ARRAY_SUPPORT)for(e=0;e=this.length)throw new RangeError("start out of bounds");if(c<0||c>this.length)throw new RangeError("end out of bounds");var d;if("number"==typeof a)for(d=b;d>1,k=-7,l=c?e-1:0,m=c?-1:1,n=a[b+l];for(l+=m,f=n&(1<<-k)-1,n>>=-k,k+=h;k>0;f=256*f+a[b+l],l+=m,k-=8);for(g=f&(1<<-k)-1,f>>=-k,k+=d;k>0;g=256*g+a[b+l],l+=m,k-=8);if(0===f)f=1-j;else{if(f===i)return g?NaN:1/0*(n?-1:1);g+=Math.pow(2,d),f-=j}return(n?-1:1)*g*Math.pow(2,f-d)},c.write=function(a,b,c,d,e,f){var g,h,i,j=8*f-e-1,k=(1<>1,m=23===e?Math.pow(2,-24)-Math.pow(2,-77):0,n=d?0:f-1,o=d?1:-1,p=b<0||0===b&&1/b<0?1:0;for(b=Math.abs(b),isNaN(b)||b===1/0?(h=isNaN(b)?1:0,g=k):(g=Math.floor(Math.log(b)/Math.LN2),b*(i=Math.pow(2,-g))<1&&(g--,i*=2),b+=g+l>=1?m/i:m*Math.pow(2,1-l),b*i>=2&&(g++,i/=2),g+l>=k?(h=0,g=k):g+l>=1?(h=(b*i-1)*Math.pow(2,e),g+=l):(h=b*Math.pow(2,l-1)*Math.pow(2,e),g=0));e>=8;a[c+n]=255&h,n+=o,h/=256,e-=8);for(g=g<0;a[c+n]=255&g,n+=o,g/=256,j-=8);a[c+n-o]|=128*p}},{}],8:[function(a,b,c){var d={}.toString;b.exports=Array.isArray||function(a){return"[object Array]"==d.call(a)}},{}],9:[function(a,b,c){"use strict";function d(a,b,c,d,e){return Math.pow(1-e,3)*a+3*Math.pow(1-e,2)*e*b+3*(1-e)*Math.pow(e,2)*c+Math.pow(e,3)*d}function e(){this.x1=Number.NaN,this.y1=Number.NaN,this.x2=Number.NaN,this.y2=Number.NaN}e.prototype.isEmpty=function(){return isNaN(this.x1)||isNaN(this.y1)||isNaN(this.x2)||isNaN(this.y2)},e.prototype.addPoint=function(a,b){"number"==typeof a&&((isNaN(this.x1)||isNaN(this.x2))&&(this.x1=a,this.x2=a),athis.x2&&(this.x2=a)),"number"==typeof b&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=b,this.y2=b),bthis.y2&&(this.y2=b))},e.prototype.addX=function(a){this.addPoint(a,null)},e.prototype.addY=function(a){this.addPoint(null,a)},e.prototype.addBezier=function(a,b,c,e,f,g,h,i){var j=[a,b],k=[c,e],l=[f,g],m=[h,i];this.addPoint(a,b),this.addPoint(h,i);for(var n=0;n<=1;n++){var o=6*j[n]-12*k[n]+6*l[n],p=-3*j[n]+9*k[n]-9*l[n]+3*m[n],q=3*k[n]-3*j[n];if(0!==p){var r=Math.pow(o,2)-4*q*p;if(!(r<0)){var s=(-o+Math.sqrt(r))/(2*p);00,"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(){return console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead."),this.toArrayBuffer()},d.prototype.toArrayBuffer=function(){for(var a=this.toTables(),b=a.encode(),c=new ArrayBuffer(b.length),d=new Uint8Array(c),e=0;e=176&&c<=183)e+=c-176+1;else if(c>=184&&c<=191)e+=2*(c-184+1);else if(b&&1===f&&27===c)break}while(f>0);a.ip=e}function t(a,b){lb&&console.log(b.step,"SVTCA["+a.axis+"]"),b.fv=b.pv=b.dpv=a}function u(a,b){lb&&console.log(b.step,"SPVTCA["+a.axis+"]"),b.pv=b.dpv=a}function v(a,b){lb&&console.log(b.step,"SFVTCA["+a.axis+"]"),b.fv=a}function w(a,b){var c=b.stack,d=c.pop(),e=c.pop(),f=b.z2[d],g=b.z1[e];lb&&console.log("SPVTL["+a+"]",d,e);var h,i;a?(h=f.y-g.y,i=g.x-f.x):(h=g.x-f.x,i=g.y-f.y),b.pv=b.dpv=l(h,i)}function x(a,b){var c=b.stack,d=c.pop(),e=c.pop(),f=b.z2[d],g=b.z1[e];lb&&console.log("SFVTL["+a+"]",d,e);var h,i;a?(h=f.y-g.y,i=g.x-f.x):(h=g.x-f.x,i=g.y-f.y),b.fv=l(h,i)}function y(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"SPVFS[]",c,d),a.pv=a.dpv=l(d,c)}function z(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"SPVFS[]",c,d),a.fv=l(d,c)}function A(a){var b=a.stack,c=a.pv;lb&&console.log(a.step,"GPV[]"),b.push(16384*c.x),b.push(16384*c.y)}function B(a){var b=a.stack,c=a.fv;lb&&console.log(a.step,"GFV[]"),b.push(16384*c.x),b.push(16384*c.y)}function C(a){a.fv=a.pv,lb&&console.log(a.step,"SFVTPV[]")}function D(a){var b=a.stack,c=b.pop(),d=b.pop(),e=b.pop(),f=b.pop(),g=b.pop(),h=a.z0,i=a.z1,j=h[c],k=h[d],l=i[e],m=i[f],n=a.z2[g];lb&&console.log("ISECT[], ",c,d,e,f,g);var o=j.x,p=j.y,q=k.x,r=k.y,s=l.x,t=l.y,u=m.x,v=m.y,w=(o-q)*(t-v)-(p-r)*(s-u),x=o*r-p*q,y=s*v-t*u;n.x=(x*(s-u)-y*(o-q))/w,n.y=(x*(t-v)-y*(p-r))/w}function E(a){a.rp0=a.stack.pop(),lb&&console.log(a.step,"SRP0[]",a.rp0)}function F(a){a.rp1=a.stack.pop(),lb&&console.log(a.step,"SRP1[]",a.rp1)}function G(a){a.rp2=a.stack.pop(),lb&&console.log(a.step,"SRP2[]",a.rp2)}function H(a){var b=a.stack.pop();switch(lb&&console.log(a.step,"SZP0[]",b),a.zp0=b,b){case 0:a.tZone||r(a),a.z0=a.tZone;break;case 1:a.z0=a.gZone;break;default:throw new Error("Invalid zone pointer")}}function I(a){var b=a.stack.pop();switch(lb&&console.log(a.step,"SZP1[]",b),a.zp1=b,b){case 0:a.tZone||r(a),a.z1=a.tZone;break;case 1:a.z1=a.gZone;break;default:throw new Error("Invalid zone pointer")}}function J(a){var b=a.stack.pop();switch(lb&&console.log(a.step,"SZP2[]",b),a.zp2=b,b){case 0:a.tZone||r(a),a.z2=a.tZone;break;case 1:a.z2=a.gZone;break;default:throw new Error("Invalid zone pointer")}}function K(a){var b=a.stack.pop();switch(lb&&console.log(a.step,"SZPS[]",b),a.zp0=a.zp1=a.zp2=b,b){case 0:a.tZone||r(a),a.z0=a.z1=a.z2=a.tZone;break;case 1:a.z0=a.z1=a.z2=a.gZone;break;default:throw new Error("Invalid zone pointer")}}function L(a){a.loop=a.stack.pop(),lb&&console.log(a.step,"SLOOP[]",a.loop)}function M(a){lb&&console.log(a.step,"RTG[]"),a.round=f}function N(a){lb&&console.log(a.step,"RTHG[]"),a.round=h}function O(a){var b=a.stack.pop();lb&&console.log(a.step,"SMD[]",b),a.minDis=b/64}function P(a){lb&&console.log(a.step,"ELSE[]"),s(a,!1)}function Q(a){var b=a.stack.pop();lb&&console.log(a.step,"JMPR[]",b),a.ip+=b-1}function R(a){var b=a.stack.pop();lb&&console.log(a.step,"SCVTCI[]",b),a.cvCutIn=b/64}function S(a){var b=a.stack;lb&&console.log(a.step,"DUP[]"),b.push(b[b.length-1])}function T(a){lb&&console.log(a.step,"POP[]"),a.stack.pop()}function U(a){lb&&console.log(a.step,"CLEAR[]"),a.stack.length=0}function V(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"SWAP[]"),b.push(c),b.push(d)}function W(a){var b=a.stack;lb&&console.log(a.step,"DEPTH[]"),b.push(b.length)}function X(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"LOOPCALL[]",c,d);var e=a.ip,f=a.prog;a.prog=a.funcs[c];for(var g=0;g1?"loop "+(b.loop-h)+": ":"")+"SHP["+(a?"rp1":"rp2")+"]",j)}b.loop=1}function da(a,b){var c=b.stack,d=a?b.rp1:b.rp2,e=(a?b.z0:b.z1)[d],f=b.fv,g=b.pv,h=c.pop(),i=b.z2[b.contours[h]],j=i;lb&&console.log(b.step,"SHC["+a+"]",h);var k=g.distance(e,e,!1,!0);do{j!==e&&f.setRelative(j,j,k,g),j=j.nextPointOnContour}while(j!==i)}function ea(a,b){var c=b.stack,d=a?b.rp1:b.rp2,e=(a?b.z0:b.z1)[d],f=b.fv,g=b.pv,h=c.pop();lb&&console.log(b.step,"SHZ["+a+"]",h);var i;switch(h){case 0:i=b.tZone;break;case 1:i=b.gZone;break;default:throw new Error("Invalid zone")}for(var j,k=g.distance(e,e,!1,!0),l=i.length-2,m=0;m1?"loop "+(a.loop-c)+": ":"")+"SHPIX[]",g,e),d.setRelative(h,h,e),d.touch(h)}a.loop=1}function ga(a){for(var b=a.stack,c=a.rp1,d=a.rp2,e=a.loop,f=a.z0[c],g=a.z1[d],h=a.fv,i=a.dpv,j=a.z2;e--;){var k=b.pop(),l=j[k];lb&&console.log(a.step,(a.loop>1?"loop "+(a.loop-e)+": ":"")+"IP[]",k,c,"<->",d),h.interpolate(l,f,g,i),h.touch(l)}a.loop=1}function ha(a,b){var c=b.stack,d=c.pop()/64,e=c.pop(),f=b.z1[e],g=b.z0[b.rp0],h=b.fv,i=b.pv;h.setRelative(f,g,d,i),h.touch(f),lb&&console.log(b.step,"MSIRP["+a+"]",d,e),b.rp1=b.rp0,b.rp2=e,a&&(b.rp0=e)}function ia(a){for(var b=a.stack,c=a.rp0,d=a.z0[c],e=a.loop,f=a.fv,g=a.pv,h=a.z1;e--;){var i=b.pop(),j=h[i];lb&&console.log(a.step,(a.loop>1?"loop "+(a.loop-e)+": ":"")+"ALIGNRP[]",i),f.setRelative(j,d,0,g),f.touch(j)}a.loop=1}function ja(a){lb&&console.log(a.step,"RTDG[]"),a.round=g}function ka(a,b){var c=b.stack,d=c.pop(),e=c.pop(),f=b.z0[e],g=b.fv,h=b.pv,i=b.cvt[d];a&&(i=b.round(i)), +lb&&console.log(b.step,"MIAP["+a+"]",d,"(",i,")",e),g.setRelative(f,pb,i,h),0===b.zp0&&(f.xo=f.x,f.yo=f.y),g.touch(f),b.rp0=b.rp1=e}function la(a){var b=a.prog,c=a.ip,d=a.stack,e=b[++c];lb&&console.log(a.step,"NPUSHB[]",e);for(var f=0;f",h),b.stack.push(Math.round(64*h))}function ta(a){lb&&console.log(a.step,"MPPEM[]"),a.stack.push(a.ppem)}function ua(a){lb&&console.log(a.step,"FLIPON[]"),a.autoFlip=!0}function va(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"LT[]",c,d),b.push(dc?1:0)}function ya(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"GTEQ[]",c,d),b.push(d>=c?1:0)}function za(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"EQ[]",c,d),b.push(c===d?1:0)}function Aa(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"NEQ[]",c,d),b.push(c!==d?1:0)}function Ba(a){var b=a.stack,c=b.pop();lb&&console.log(a.step,"ODD[]",c),b.push(Math.trunc(c)%2?1:0)}function Ca(a){var b=a.stack,c=b.pop();lb&&console.log(a.step,"EVEN[]",c),b.push(Math.trunc(c)%2?0:1)}function Da(a){var b,c=a.stack.pop();lb&&console.log(a.step,"IF[]",c),c||(s(a,!0),lb&&console.log(a.step,27===b?"ELSE[]":"EIF[]"))}function Ea(a){lb&&console.log(a.step,"EIF[]")}function Fa(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"AND[]",c,d),b.push(c&&d?1:0)}function Ga(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"OR[]",c,d),b.push(c||d?1:0)}function Ha(a){var b=a.stack,c=b.pop();lb&&console.log(a.step,"NOT[]",c),b.push(c?0:1)}function Ia(a,b){var c=b.stack,d=c.pop(),e=b.fv,f=b.pv,g=b.ppem,h=b.deltaBase+16*(a-1),i=b.deltaShift,j=b.z0;lb&&console.log(b.step,"DELTAP["+a+"]",d,c);for(var k=0;k>4)===g){var n=(15&m)-8;n>=0&&n++,lb&&console.log(b.step,"DELTAPFIX",l,"by",n*i);var o=j[l];e.setRelative(o,o,n*i,f)}}}function Ja(a){var b=a.stack,c=b.pop();lb&&console.log(a.step,"SDB[]",c),a.deltaBase=c}function Ka(a){var b=a.stack,c=b.pop();lb&&console.log(a.step,"SDS[]",c),a.deltaShift=Math.pow(.5,c)}function La(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"ADD[]",c,d),b.push(d+c)}function Ma(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"SUB[]",c,d),b.push(d-c)}function Na(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"DIV[]",c,d),b.push(64*d/c)}function Oa(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"MUL[]",c,d),b.push(d*c/64)}function Pa(a){var b=a.stack,c=b.pop();lb&&console.log(a.step,"ABS[]",c),b.push(Math.abs(c))}function Qa(a){var b=a.stack,c=b.pop();lb&&console.log(a.step,"NEG[]",c),b.push(-c)}function Ra(a){var b=a.stack,c=b.pop();lb&&console.log(a.step,"FLOOR[]",c),b.push(64*Math.floor(c/64))}function Sa(a){var b=a.stack,c=b.pop();lb&&console.log(a.step,"CEILING[]",c),b.push(64*Math.ceil(c/64))}function Ta(a,b){var c=b.stack,d=c.pop();lb&&console.log(b.step,"ROUND[]"),c.push(64*b.round(d/64))}function Ua(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"WCVTF[]",c,d),a.cvt[d]=c*a.ppem/a.font.unitsPerEm}function Va(a,b){var c=b.stack,d=c.pop(),e=b.ppem,f=b.deltaBase+16*(a-1),g=b.deltaShift;lb&&console.log(b.step,"DELTAC["+a+"]",d,c);for(var h=0;h>4)===e){var k=(15&j)-8;k>=0&&k++;var l=k*g;lb&&console.log(b.step,"DELTACFIX",i,"by",l),b.cvt[i]+=l}}}function Wa(a){var b=a.stack.pop();lb&&console.log(a.step,"SROUND[]",b),a.round=mb;var c;switch(192&b){case 0:c=.5;break;case 64:c=1;break;case 128:c=2;break;default:throw new Error("invalid SROUND value")}switch(a.srPeriod=c,48&b){case 0:a.srPhase=0;break;case 16:a.srPhase=.25*c;break;case 32:a.srPhase=.5*c;break;case 48:a.srPhase=.75*c;break;default:throw new Error("invalid SROUND value")}b&=15,a.srThreshold=0===b?0:(b/8-.5)*c}function Xa(a){var b=a.stack.pop();lb&&console.log(a.step,"S45ROUND[]",b),a.round=mb;var c;switch(192&b){case 0:c=Math.sqrt(2)/2;break;case 64:c=Math.sqrt(2);break;case 128:c=2*Math.sqrt(2);break;default:throw new Error("invalid S45ROUND value")}switch(a.srPeriod=c,48&b){case 0:a.srPhase=0;break;case 16:a.srPhase=.25*c;break;case 32:a.srPhase=.5*c;break;case 48:a.srPhase=.75*c;break;default:throw new Error("invalid S45ROUND value")}b&=15,a.srThreshold=0===b?0:(b/8-.5)*c}function Ya(a){lb&&console.log(a.step,"ROFF[]"),a.round=e}function Za(a){lb&&console.log(a.step,"RUTG[]"),a.round=i}function $a(a){lb&&console.log(a.step,"RDTG[]"),a.round=j}function _a(a){var b=a.stack.pop();lb&&console.log(a.step,"SCANCTRL[]",b)}function ab(a,b){var c=b.stack,d=c.pop(),e=c.pop(),f=b.z2[d],g=b.z1[e];lb&&console.log("SDPVTL["+a+"]",d,e);var h,i;a?(h=f.y-g.y,i=g.x-f.x):(h=g.x-f.x,i=g.y-f.y),b.dpv=l(h,i)}function bb(a){var b=a.stack,c=b.pop(),d=0;lb&&console.log(a.step,"GETINFO[]",c),1&c&&(d=35),32&c&&(d|=4096),b.push(d)}function cb(a){var b=a.stack,c=b.pop(),d=b.pop(),e=b.pop();lb&&console.log(a.step,"ROLL[]"),b.push(d),b.push(c),b.push(e)}function db(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"MAX[]",c,d),b.push(Math.max(d,c))}function eb(a){var b=a.stack,c=b.pop(),d=b.pop();lb&&console.log(a.step,"MIN[]",c,d),b.push(Math.min(d,c))}function fb(a){var b=a.stack.pop();lb&&console.log(a.step,"SCANTYPE[]",b)}function gb(a){var b=a.stack.pop(),c=a.stack.pop();switch(lb&&console.log(a.step,"INSTCTRL[]",b,c),b){case 1:return void(a.inhibitGridFit=!!c);case 2:return void(a.ignoreCvt=!!c);default:throw new Error("invalid INSTCTRL[] selector")}}function hb(a,b){var c=b.stack,d=b.prog,e=b.ip;lb&&console.log(b.step,"PUSHB["+a+"]");for(var f=0;f=0?1:-1,h=Math.abs(h),a&&(j=f.cvt[l],d&&Math.abs(h-j)":"_")+(d?"R":"_")+(0===e?"Gr":1===e?"Bl":2===e?"Wh":"")+"]",a?l+"("+f.cvt[l]+","+j+")":"",m,"(d =",g,"->",i*h,")"),f.rp1=f.rp0,f.rp2=m,b&&(f.rp0=m)}var kb,q,p,o,lb=!1,mb=function(a){var b=this.srPeriod,c=this.srPhase,d=this.srThreshold,e=1;return a<0&&(a=-a,e=-1),a+=d-c,a=Math.trunc(a/b)*b,a+=c,e>0&&a<0?c:e<0&&a>0?-c:a*e},nb={x:1,y:0,axis:"x",distance:function(a,b,c,d){return(c?a.xo:a.x)-(d?b.xo:b.x)},interpolate:function(a,b,c,d){var e,f,g,h,i,j,k;return d&&d!==this?(e=d.distance(a,b,!0,!0),f=d.distance(a,c,!0,!0),i=d.distance(b,b,!1,!0),j=d.distance(c,c,!1,!0),g=Math.abs(e),h=Math.abs(f),0===(k=g+h)?void nb.setRelative(a,a,(i+j)/2,d,!0):void nb.setRelative(a,a,(i*h+j*g)/k,d,!0)):(e=a.xo-b.xo,f=a.xo-c.xo,i=b.x-b.xo,j=c.x-c.xo,g=Math.abs(e),h=Math.abs(f),0===(k=g+h)?void(a.x=a.xo+(i+j)/2):void(a.x=a.xo+(i*h+j*g)/k))},normalSlope:Number.NEGATIVE_INFINITY,setRelative:function(a,b,c,d,e){if(!d||d===this)return void(a.x=(e?b.xo:b.x)+c);var f=e?b.xo:b.x,g=e?b.yo:b.y,h=f+c*d.x,i=g+c*d.y;a.x=h+(a.y-i)/d.normalSlope},slope:0,touch:function(a){a.xTouched=!0},touched:function(a){return a.xTouched},untouch:function(a){a.xTouched=!1}},ob={x:0,y:1,axis:"y",distance:function(a,b,c,d){return(c?a.yo:a.y)-(d?b.yo:b.y)},interpolate:function(a,b,c,d){var e,f,g,h,i,j,k;return d&&d!==this?(e=d.distance(a,b,!0,!0),f=d.distance(a,c,!0,!0),i=d.distance(b,b,!1,!0),j=d.distance(c,c,!1,!0),g=Math.abs(e),h=Math.abs(f),0===(k=g+h)?void ob.setRelative(a,a,(i+j)/2,d,!0):void ob.setRelative(a,a,(i*h+j*g)/k,d,!0)):(e=a.yo-b.yo,f=a.yo-c.yo,i=b.y-b.yo,j=c.y-c.yo,g=Math.abs(e),h=Math.abs(f),0===(k=g+h)?void(a.y=a.yo+(i+j)/2):void(a.y=a.yo+(i*h+j*g)/k))},normalSlope:0,setRelative:function(a,b,c,d,e){if(!d||d===this)return void(a.y=(e?b.yo:b.y)+c);var f=e?b.xo:b.x,g=e?b.yo:b.y,h=f+c*d.x,i=g+c*d.y;a.y=i+d.normalSlope*(a.x-h)},slope:Number.POSITIVE_INFINITY,touch:function(a){a.yTouched=!0},touched:function(a){return a.yTouched},untouch:function(a){a.yTouched=!1}};Object.freeze(nb),Object.freeze(ob),k.prototype.distance=function(a,b,c,d){return this.x*nb.distance(a,b,c,d)+this.y*ob.distance(a,b,c,d)},k.prototype.interpolate=function(a,b,c,d){var e,f,g,h,i,j,k;if(g=d.distance(a,b,!0,!0),h=d.distance(a,c,!0,!0),e=d.distance(b,b,!1,!0),f=d.distance(c,c,!1,!0),i=Math.abs(g),j=Math.abs(h),0===(k=i+j))return void this.setRelative(a,a,(e+f)/2,d,!0);this.setRelative(a,a,(e*j+f*i)/k,d,!0)},k.prototype.setRelative=function(a,b,c,d,e){d=d||this;var f=e?b.xo:b.x,g=e?b.yo:b.y,h=f+c*d.x,i=g+c*d.y,j=d.normalSlope,k=this.slope,l=a.x,m=a.y;a.x=(k*l-j*h+i-m)/(k-j),a.y=k*(a.x-l)+m},k.prototype.touch=function(a){a.xTouched=!0,a.yTouched=!0},m.prototype.nextTouched=function(a){for(var b=this.nextPointOnContour;!a.touched(b)&&b!==this;)b=b.nextPointOnContour;return b},m.prototype.prevTouched=function(a){for(var b=this.prevPointOnContour;!a.touched(b)&&b!==this;)b=b.prevPointOnContour;return b};var pb=Object.freeze(new m(0,0)),qb={cvCutIn:17/16,deltaBase:9,deltaShift:.125,loop:1,minDis:1,autoFlip:!0};d.prototype.exec=function(a,b){if("number"!=typeof b)throw new Error("Point size is not a number!");if(!(this._errorState>2)){var c=this.font,d=this._prepState;if(!d||d.ppem!==b){var e=this._fpgmState;if(!e){n.prototype=qb,e=this._fpgmState=new n("fpgm",c.tables.fpgm),e.funcs=[],e.font=c,lb&&(console.log("---EXEC FPGM---"),e.step=-1);try{q(e)}catch(a){return console.log("Hinting error in FPGM:"+a),void(this._errorState=3)}}n.prototype=e,d=this._prepState=new n("prep",c.tables.prep),d.ppem=b;var f=c.tables.cvt;if(f)for(var g=d.cvt=new Array(f.length),h=b/c.unitsPerEm,i=0;i1))try{return o(a,d)}catch(a){return this._errorState<1&&(console.log("Hinting error:"+a),console.log("Note: further hinting errors are silenced")),void(this._errorState=1)}}},kb=[t.bind(void 0,ob),t.bind(void 0,nb),u.bind(void 0,ob),u.bind(void 0,nb),v.bind(void 0,ob),v.bind(void 0,nb),w.bind(void 0,0),w.bind(void 0,1),x.bind(void 0,0),x.bind(void 0,1),y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,void 0,void 0,S,T,U,V,W,Z,$,void 0,void 0,void 0,X,Y,_,void 0,aa.bind(void 0,0),aa.bind(void 0,1),ba.bind(void 0,ob),ba.bind(void 0,nb),ca.bind(void 0,0),ca.bind(void 0,1),da.bind(void 0,0),da.bind(void 0,1),ea.bind(void 0,0),ea.bind(void 0,1),fa,ga,ha.bind(void 0,0),ha.bind(void 0,1),ia,ja,ka.bind(void 0,0),ka.bind(void 0,1),la,ma,na,oa,pa,qa,ra.bind(void 0,0),ra.bind(void 0,1),void 0,sa.bind(void 0,0),sa.bind(void 0,1),ta,void 0,ua,void 0,void 0,va,wa,xa,ya,za,Aa,Ba,Ca,Da,Ea,Fa,Ga,Ha,Ia.bind(void 0,1),Ja,Ka,La,Ma,Na,Oa,Pa,Qa,Ra,Sa,Ta.bind(void 0,0),Ta.bind(void 0,1),Ta.bind(void 0,2),Ta.bind(void 0,3),void 0,void 0,void 0,void 0,Ua,Ia.bind(void 0,2),Ia.bind(void 0,3),Va.bind(void 0,1),Va.bind(void 0,2),Va.bind(void 0,3),Wa,Xa,void 0,void 0,Ya,void 0,Za,$a,T,T,void 0,void 0,void 0,void 0,void 0,_a,ab.bind(void 0,0),ab.bind(void 0,1),bb,void 0,cb,db,eb,fb,gb,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,hb.bind(void 0,1),hb.bind(void 0,2),hb.bind(void 0,3),hb.bind(void 0,4),hb.bind(void 0,5),hb.bind(void 0,6),hb.bind(void 0,7),hb.bind(void 0,8),ib.bind(void 0,1),ib.bind(void 0,2),ib.bind(void 0,3),ib.bind(void 0,4),ib.bind(void 0,5),ib.bind(void 0,6),ib.bind(void 0,7),ib.bind(void 0,8),jb.bind(void 0,0,0,0,0,0),jb.bind(void 0,0,0,0,0,1),jb.bind(void 0,0,0,0,0,2),jb.bind(void 0,0,0,0,0,3),jb.bind(void 0,0,0,0,1,0),jb.bind(void 0,0,0,0,1,1),jb.bind(void 0,0,0,0,1,2),jb.bind(void 0,0,0,0,1,3),jb.bind(void 0,0,0,1,0,0),jb.bind(void 0,0,0,1,0,1),jb.bind(void 0,0,0,1,0,2),jb.bind(void 0,0,0,1,0,3),jb.bind(void 0,0,0,1,1,0),jb.bind(void 0,0,0,1,1,1),jb.bind(void 0,0,0,1,1,2),jb.bind(void 0,0,0,1,1,3),jb.bind(void 0,0,1,0,0,0),jb.bind(void 0,0,1,0,0,1),jb.bind(void 0,0,1,0,0,2),jb.bind(void 0,0,1,0,0,3),jb.bind(void 0,0,1,0,1,0),jb.bind(void 0,0,1,0,1,1),jb.bind(void 0,0,1,0,1,2),jb.bind(void 0,0,1,0,1,3),jb.bind(void 0,0,1,1,0,0),jb.bind(void 0,0,1,1,0,1),jb.bind(void 0,0,1,1,0,2),jb.bind(void 0,0,1,1,0,3),jb.bind(void 0,0,1,1,1,0),jb.bind(void 0,0,1,1,1,1),jb.bind(void 0,0,1,1,1,2),jb.bind(void 0,0,1,1,1,3),jb.bind(void 0,1,0,0,0,0),jb.bind(void 0,1,0,0,0,1),jb.bind(void 0,1,0,0,0,2),jb.bind(void 0,1,0,0,0,3),jb.bind(void 0,1,0,0,1,0),jb.bind(void 0,1,0,0,1,1),jb.bind(void 0,1,0,0,1,2),jb.bind(void 0,1,0,0,1,3),jb.bind(void 0,1,0,1,0,0),jb.bind(void 0,1,0,1,0,1),jb.bind(void 0,1,0,1,0,2),jb.bind(void 0,1,0,1,0,3),jb.bind(void 0,1,0,1,1,0),jb.bind(void 0,1,0,1,1,1),jb.bind(void 0,1,0,1,1,2),jb.bind(void 0,1,0,1,1,3),jb.bind(void 0,1,1,0,0,0),jb.bind(void 0,1,1,0,0,1),jb.bind(void 0,1,1,0,0,2),jb.bind(void 0,1,1,0,0,3),jb.bind(void 0,1,1,0,1,0),jb.bind(void 0,1,1,0,1,1),jb.bind(void 0,1,1,0,1,2),jb.bind(void 0,1,1,0,1,3),jb.bind(void 0,1,1,1,0,0),jb.bind(void 0,1,1,1,0,1),jb.bind(void 0,1,1,1,0,2),jb.bind(void 0,1,1,1,0,3),jb.bind(void 0,1,1,1,1,0),jb.bind(void 0,1,1,1,1,1),jb.bind(void 0,1,1,1,1,2),jb.bind(void 0,1,1,1,1,3)],b.exports=d},{}],17:[function(a,b,c){"use strict";function d(a,b){for(var c=0,d=a.length-1;c<=d;){var e=c+d>>>1,f=a[e].tag;if(f===b)return e;f>>1,f=a[e];if(f===b)return e;f=0)return e[f].script;if(b){var g={tag:a,script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}};return e.splice(-1-f,0,g),g.script}}},getLangSysTable:function(a,b,c){var e=this.getScriptTable(a,c);if(e){if(!b||"dflt"===b||"DFLT"===b)return e.defaultLangSys;var f=d(e.langSysRecords,b);if(f>=0)return e.langSysRecords[f].langSys;if(c){var g={tag:b,langSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]}};return e.langSysRecords.splice(-1-f,0,g),g.langSys}}},getFeatureTable:function(a,b,c,d){var e=this.getLangSysTable(a,b,d);if(e){for(var f,h=e.featureIndexes,i=this.font.tables[this.tableName].features,j=0;j=i[k-1].tag,"Features must be added in alphabetical order."),f={tag:c,feature:{params:0,lookupListIndexes:[]}},i.push(f),h.push(k),f.feature}}},getLookupTables:function(a,b,c,d,e){var f=this.getFeatureTable(a,b,c,e),g=[];if(f){for(var h,i=f.lookupListIndexes,j=this.font.tables[this.tableName].lookups,k=0;k0)return new e(this.data,this.offset+b).parseStruct(a)},e.prototype.parseListOfLists=function(a){for(var b=this.parseOffset16List(),c=b.length,d=this.relativeOffset,e=new Array(c),f=0;f=0&&c>0&&(a+=" "),a+=b(d)}return a}a=void 0!==a?a:2;for(var d="",e=0;e=0){for(var m=h.ligatureSets[l],n=0;n>4,g=15&e;if(f===c)break;if(b+=d[f],g===c)break;b+=d[g]}return parseFloat(b)}function h(a,b){var c,d,e,f;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(),f=a.parseByte(),c<<24|d<<16|e<<8|f;if(30===b)return g(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 i(a){for(var b={},c=0;c>1,p.length=0,r=!0}function f(c){for(var m,v,w,y,z,A,B,C,D,E,F,G,H=0;H1&&!r&&(x=p.shift()+n,r=!0),u+=p.pop(),d(t,u);break;case 5:for(;p.length>0;)t+=p.shift(),u+=p.shift(),o.lineTo(t,u);break;case 6:for(;p.length>0&&(t+=p.shift(),o.lineTo(t,u),0!==p.length);)u+=p.shift(),o.lineTo(t,u);break;case 7:for(;p.length>0&&(u+=p.shift(),o.lineTo(t,u),0!==p.length);)t+=p.shift(),o.lineTo(t,u);break;case 8:for(;p.length>0;)g=t+p.shift(),h=u+p.shift(),i=g+p.shift(),j=h+p.shift(),t=i+p.shift(),u=j+p.shift(),o.curveTo(g,h,i,j,t,u);break;case 10:z=p.pop()+l,A=k[z],A&&f(A);break;case 11:return;case 12:switch(I=c[H],H+=1,I){case 35:g=t+p.shift(),h=u+p.shift(),i=g+p.shift(),j=h+p.shift(),B=i+p.shift(),C=j+p.shift(),D=B+p.shift(),E=C+p.shift(),F=D+p.shift(),G=E+p.shift(),t=F+p.shift(),u=G+p.shift(),p.shift(),o.curveTo(g,h,i,j,B,C),o.curveTo(D,E,F,G,t,u);break;case 34:g=t+p.shift(),h=u,i=g+p.shift(),j=h+p.shift(),B=i+p.shift(),C=j,D=B+p.shift(),E=j,F=D+p.shift(),G=u,t=F+p.shift(),o.curveTo(g,h,i,j,B,C),o.curveTo(D,E,F,G,t,u);break;case 36:g=t+p.shift(),h=u+p.shift(),i=g+p.shift(),j=h+p.shift(),B=i+p.shift(),C=j,D=B+p.shift(),E=j,F=D+p.shift(),G=E+p.shift(),t=F+p.shift(),o.curveTo(g,h,i,j,B,C),o.curveTo(D,E,F,G,t,u);break;case 37:g=t+p.shift(),h=u+p.shift(),i=g+p.shift(),j=h+p.shift(),B=i+p.shift(),C=j+p.shift(),D=B+p.shift(),E=C+p.shift(),F=D+p.shift(),G=E+p.shift(),Math.abs(F-t)>Math.abs(G-u)?t=F+p.shift():u=G+p.shift(),o.curveTo(g,h,i,j,B,C),o.curveTo(D,E,F,G,t,u);break;default:console.log("Glyph "+b.index+": unknown operator 1200"+I),p.length=0}break;case 14:p.length>0&&!r&&(x=p.shift()+n,r=!0),s&&(o.closePath(),s=!1);break;case 18:e();break;case 19:case 20:e(),H+=q+7>>3;break;case 21:p.length>2&&!r&&(x=p.shift()+n,r=!0),u+=p.pop(),t+=p.pop(),d(t,u);break;case 22:p.length>1&&!r&&(x=p.shift()+n,r=!0),t+=p.pop(),d(t,u);break;case 23:e();break;case 24:for(;p.length>2;)g=t+p.shift(),h=u+p.shift(),i=g+p.shift(),j=h+p.shift(),t=i+p.shift(),u=j+p.shift(),o.curveTo(g,h,i,j,t,u);t+=p.shift(),u+=p.shift(),o.lineTo(t,u);break;case 25:for(;p.length>6;)t+=p.shift(),u+=p.shift(),o.lineTo(t,u);g=t+p.shift(),h=u+p.shift(),i=g+p.shift(),j=h+p.shift(),t=i+p.shift(),u=j+p.shift(),o.curveTo(g,h,i,j,t,u);break;case 26:for(p.length%2&&(t+=p.shift());p.length>0;)g=t,h=u+p.shift(),i=g+p.shift(),j=h+p.shift(),t=i,u=j+p.shift(),o.curveTo(g,h,i,j,t,u);break;case 27:for(p.length%2&&(u+=p.shift());p.length>0;)g=t+p.shift(),h=u,i=g+p.shift(),j=h+p.shift(),t=i+p.shift(),u=j,o.curveTo(g,h,i,j,t,u);break;case 28:m=c[H],v=c[H+1],p.push((m<<24|v<<16)>>16),H+=2;break;case 29:z=p.pop()+a.gsubrsBias,A=a.gsubrs[z],A&&f(A);break;case 30:for(;p.length>0&&(g=t,h=u+p.shift(),i=g+p.shift(),j=h+p.shift(),t=i+p.shift(),u=j+(1===p.length?p.shift():0),o.curveTo(g,h,i,j,t,u),0!==p.length);)g=t+p.shift(),h=u,i=g+p.shift(),j=h+p.shift(),u=j+p.shift(),t=i+(1===p.length?p.shift():0),o.curveTo(g,h,i,j,t,u);break;case 31:for(;p.length>0&&(g=t+p.shift(),h=u,i=g+p.shift(),j=h+p.shift(),u=j+p.shift(),t=i+(1===p.length?p.shift():0),o.curveTo(g,h,i,j,t,u),0!==p.length);)g=t,h=u+p.shift(),i=g+p.shift(),j=h+p.shift(),t=i+p.shift(),u=j+(1===p.length?p.shift():0),o.curveTo(g,h,i,j,t,u);break;default:I<32?console.log("Glyph "+b.index+": unknown operator "+I):I<247?p.push(I-139):I<251?(m=c[H],H+=1,p.push(256*(I-247)+m+108)):I<255?(m=c[H],H+=1,p.push(256*-(I-251)-m-108)):(m=c[H],v=c[H+1],w=c[H+2],y=c[H+3],H+=4,p.push((m<<24|v<<16|w<<8|y)/65536))}}}var g,h,i,j,k,l,m,n,o=new L.Path,p=[],q=0,r=!1,s=!1,t=0,u=0;if(a.isCIDFont){var v=a.tables.cff.topDict._fdSelect[b.index],w=a.tables.cff.topDict._fdArray[v];k=w._subrs,l=w._subrsBias,m=w._defaultWidthX,n=w._nominalWidthX}else k=a.tables.cff.topDict._subrs,l=a.tables.cff.topDict._subrsBias,m=a.tables.cff.topDict._defaultWidthX,n=a.tables.cff.topDict._nominalWidthX;var x=m;return f(c),b.advanceWidth=x,o}function t(a,b,c,d){var e,f=[],g=new K.Parser(a,b),h=g.parseCard8();if(0===h)for(var i=0;i=d)throw new Error("CFF table CID Font FDSelect has bad FD index value "+e+" (FD count "+d+")");f.push(e)}else{if(3!==h)throw new Error("CFF Table CID Font FDSelect table has unsupported format "+h);var j=g.parseCard16(),k=g.parseCard16();if(0!==k)throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID "+k);for(var l,m=0;m=d)throw new Error("CFF table CID Font FDSelect has bad FD index value "+e+" (FD count "+d+")");if(l>c)throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID "+l);for(;k=0&&(c=d),d=b.indexOf(a),d>=0?c=d+I.cffStandardStrings.length:(c=I.cffStandardStrings.length+b.length,b.push(a)),c}function w(){return new M.Record("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 x(a){var b=new M.Record("Name INDEX",[{name:"names",type:"INDEX",value:[]}]);b.names=[];for(var c=0;c>1,b.skip("uShort",3),a.glyphIndexMap={};var h=new k.Parser(c,d+e+14),i=new k.Parser(c,d+e+16+2*g),j=new k.Parser(c,d+e+16+4*g),l=new k.Parser(c,d+e+16+6*g),m=d+e+16+8*g;for(f=0;f=0;c-=1){var h=k.getUShort(a,b+4+8*c),i=k.getUShort(a,b+4+8*c+2);if(3===h&&(0===i||1===i||10===i)){g=k.getULong(a,b+4+8*c+4);break}}if(g===-1)throw new Error("No valid cmap sub-tables found.");var l=new k.Parser(a,b+g);if(f.format=l.parseUShort(),12===f.format)d(f,l);else{if(4!==f.format)throw new Error("Only format 4 and 12 cmap tables are supported (found format "+f.format+").");e(f,l,a,b,g)}return f}function g(a,b,c){a.segments.push({end:b,start:b,delta:-(b-c),offset:0})}function h(a){a.segments.push({end:65535,start:65535,delta:1,offset:0})}function i(a){var b,c=new l.Table("cmap",[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:1},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:12},{name:"format",type:"USHORT",value:4},{name:"length",type:"USHORT",value:0},{name:"language",type:"USHORT",value:0},{name:"segCountX2",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);for(c.segments=[],b=0;b0?(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,h;if(a.numberOfContours>0){var 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?(2&f)>0?(t.dx=e.parseShort(),t.dy=e.parseShort()):t.matchedPoints=[e.parseUShort(),e.parseUShort()]:(2&f)>0?(t.dx=e.parseChar(),t.dy=e.parseChar()):t.matchedPoints=[e.parseByte(),e.parseByte()],(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)}if(256&f)for(a.instructionLength=e.parseUShort(),a.instructions=[],h=0;hb.points.length-1||d.matchedPoints[1]>e.points.length-1)throw Error("Matched points out of range in "+b.name);var i=b.points[d.matchedPoints[0]],j=e.points[d.matchedPoints[1]],k={xScale:d.xScale,scale01:d.scale01,scale10:d.scale10,yScale:d.yScale,dx:0,dy:0};j=f([j],k)[0],k.dx=i.x-j.x,k.dy=i.y-j.y,g=f(e.points,k)}b.points=b.points.concat(g)}}return h(b.points)}function j(a,b,c,d){var f,g=new l.GlyphSet(d);for(f=0;f>1;a1&&console.warn("Only the first kern subtable is supported."),a.skip("uLong");var c=a.parseUShort(),d=255&c;if(a.skip("uShort"),0===d){var e=a.parseUShort();a.skip("uShort",3);for(var f=0;f=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":19,"../table":22}],39:[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;cG||void 0===b)&&G>0&&(b=G),z 123 are reserved for internal usage");D|=1<0?r.make(W):void 0,Z=v.make(),$=n.make(a.glyphs,{version:a.getEnglishName("version"),fullName:S,familyName:Q,weightName:R,postScriptName:T,unitsPerEm:a.unitsPerEm,fontBBox:[0,J.yMin,J.ascender,J.advanceWidthMax]}),_=a.metas&&Object.keys(a.metas).length>0?x.make(a.metas):void 0,aa=[K,L,M,N,X,P,Z,$,O];Y&&aa.push(Y),a.tables.gsub&&aa.push(w.make(a.tables.gsub)),_&&aa.push(_);var ba=g(aa),ca=ba.encode(),da=e(ca),ea=ba.fields,fa=!1;for(E=0;E=-128&&a<=127}function f(a,b,c){for(var d=0,e=a.length;b>8&255,j+256&255)}return g}var i=a("./check"),j=32768,k=2147483648,l={},m={},n={};m.BYTE=function(a){return i.argument(a>=0&&a<=255,"Byte value should be between 0 and 255."),[a]},n.BYTE=d(1),m.CHAR=function(a){return[a.charCodeAt(0)]},n.CHAR=d(1),m.CHARARRAY=function(a){for(var b=[],c=0;c>8&255,255&a]},n.USHORT=d(2),m.SHORT=function(a){return a>=j&&(a=-(2*j-a)),[a>>8&255,255&a]},n.SHORT=d(2),m.UINT24=function(a){return[a>>16&255,a>>8&255,255&a]},n.UINT24=d(3),m.ULONG=function(a){return[a>>24&255,a>>16&255,a>>8&255,255&a]},n.ULONG=d(4),m.LONG=function(a){return a>=k&&(a=-(2*k-a)),[a>>24&255,a>>16&255,a>>8&255,255&a]},n.LONG=d(4),m.FIXED=m.ULONG,n.FIXED=n.ULONG,m.FWORD=m.SHORT,n.FWORD=n.SHORT,m.UFWORD=m.USHORT,n.UFWORD=n.USHORT,m.LONGDATETIME=function(a){return[0,0,0,0,a>>24&255,a>>16&255,a>>8&255,255&a]},n.LONGDATETIME=d(8),m.TAG=function(a){return i.argument(4===a.length,"Tag should be exactly 4 ASCII characters."),[a.charCodeAt(0),a.charCodeAt(1),a.charCodeAt(2),a.charCodeAt(3)]},n.TAG=d(4),m.Card8=m.BYTE,n.Card8=n.BYTE,m.Card16=m.USHORT,n.Card16=n.USHORT,m.OffSize=m.BYTE,n.OffSize=n.BYTE,m.SID=m.USHORT,n.SID=n.USHORT,m.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?m.NUMBER16(a):m.NUMBER32(a)},n.NUMBER=function(a){return m.NUMBER(a).length},m.NUMBER16=function(a){return[28,a>>8&255,255&a]},n.NUMBER16=d(3),m.NUMBER32=function(a){return[29,a>>24&255,a>>16&255,a>>8&255,255&a]},n.NUMBER32=d(5),m.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[b.length]=255&d}return b},n.UTF16=function(a){return 2*a.length};var o={"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":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};l.MACSTRING=function(a,b,c,d){var e=o[d];if(void 0!==e){for(var f="",g=0;g=128&&void 0===(f=c[f]))return;d[e]=f}return d}},n.MACSTRING=function(a,b){var c=m.MACSTRING(a,b);return void 0!==c?c.length:0},m.VARDELTAS=function(a){for(var b=0,c=[];b=-128&&d<=127?g(a,b,c):h(a,b,c)}return c},m.INDEX=function(a){var b,c=1,d=[c],e=[];for(b=0;b>8,c[l+1]=255&n,c=c.concat(e[b])}return c},n.TABLE=function(a){for(var b=0,c=a.fields.length,d=0;d1)for(var c=1;c>>=1,b}function j(a,b,c){if(!b)return c;for(;a.bitcount<24;)a.tag|=a.source[a.sourceIndex++]<>>16-b;return a.tag>>>=b,a.bitcount-=b,d+c}function k(a,b){for(;a.bitcount<24;)a.tag|=a.source[a.sourceIndex++]<>>=1,++e,c+=b.table[e],d-=b.table[e]}while(d>=0);return a.tag=f,a.bitcount-=e,b.trans[c+d]}function l(a,b,c){var d,e,f,g,i,l;for(d=j(a,5,257),e=j(a,5,1),f=j(a,4,4),g=0;g<19;++g)z[g]=0;for(g=0;g8;)a.sourceIndex--,a.bitcount-=8;if(b=a.source[a.sourceIndex+1],b=256*b+a.source[a.sourceIndex],c=a.source[a.sourceIndex+3],c=256*c+a.source[a.sourceIndex+2],b!==(65535&~c))return q;for(a.sourceIndex+=4,d=b;d;--d)a.dest[a.destLen++]=a.source[a.sourceIndex++];return a.bitcount=0,p}function o(a,b){var c,d,f=new e(a,b);do{switch(c=i(f),j(f,2,0)){case 0:d=n(f);break;case 1:d=m(f,r,s);break;case 2:l(f,f.ltree,f.dtree),d=m(f,f.ltree,f.dtree);break;default:d=q}if(d!==p)throw new Error("Data error")}while(!c);return f.destLen-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)},{}],46:[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("./data/p5.TypedDict"),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/p5.Shader"),a("./webgl/camera"),a("./webgl/interaction"),a("./core/init.js"),b.exports=d},{"./color/creating_reading":48,"./color/p5.Color":49,"./color/setting":50,"./core/2d_primitives":51,"./core/attributes":52,"./core/constants":54,"./core/core":55,"./core/curves":56,"./core/environment":57,"./core/init.js":59,"./core/p5.Element":60,"./core/p5.Graphics":61,"./core/p5.Renderer2D":63,"./core/rendering":64,"./core/structure":66,"./core/transform":67,"./core/vertex":68,"./data/p5.TypedDict":69,"./events/acceleration":70,"./events/keyboard":71,"./events/mouse":72,"./events/touch":73,"./image/image":75,"./image/loading_displaying":76,"./image/p5.Image":77,"./image/pixels":78,"./io/files":79,"./io/p5.Table":80,"./io/p5.TableRow":81,"./io/p5.XML":82,"./math/calculation":83,"./math/math":84,"./math/noise":85,"./math/p5.Vector":86,"./math/random":88,"./math/trigonometry":89,"./typography/attributes":90,"./typography/loading_displaying":91,"./typography/p5.Font":92,"./utilities/array_functions":93,"./utilities/conversion":94,"./utilities/string_functions":95,"./utilities/time_date":96,"./webgl/camera":97,"./webgl/interaction":98,"./webgl/light":99,"./webgl/loading":100,"./webgl/material":101,"./webgl/p5.Geometry":102,"./webgl/p5.Matrix":103,"./webgl/p5.RendererGL":106,"./webgl/p5.RendererGL.Immediate":104,"./webgl/p5.RendererGL.Retained":105,"./webgl/p5.Shader":107,"./webgl/primitives":109}],47:[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":55}],48:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("../core/constants");a("./p5.Color"),a("../core/error_helpers"),d.prototype.alpha=function(a){return d._validateParameters("alpha",arguments),this.color(a)._getAlpha()},d.prototype.blue=function(a){return d._validateParameters("blue",arguments),this.color(a)._getBlue()},d.prototype.brightness=function(a){return d._validateParameters("brightness",arguments),this.color(a)._getBrightness()},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]):(d._validateParameters("color",arguments),this instanceof d.Renderer?new d.Color(this,arguments):new d.Color(this._renderer,arguments))},d.prototype.green=function(a){return d._validateParameters("green",arguments),this.color(a)._getGreen()},d.prototype.hue=function(a){return d._validateParameters("hue",arguments),this.color(a)._getHue()},d.prototype.lerpColor=function(a,b,c){d._validateParameters("lerpColor",arguments);var f,g,h,i,j,k,l=this._renderer._colorMode,m=this._renderer._colorMaxes;if(l===e.RGB)j=arguments[0].levels.map(function(a){return a/255}),k=arguments[1].levels.map(function(a){return a/255});else if(l===e.HSB)arguments[0]._getBrightness(),arguments[1]._getBrightness(),j=arguments[0].hsba,k=arguments[1].hsba;else{if(l!==e.HSL)throw new Error(l+"cannot be used for interpolation.");arguments[0]._getLightness(),arguments[1]._getLightness(),j=arguments[0].hsla,k=arguments[1].hsla}return c=Math.max(Math.min(arguments[2],1),0),void 0===this.lerp&&(this.lerp=function(a,b,c){return c*(b-a)+a}),f=this.lerp(j[0],k[0],c),g=this.lerp(j[1],k[1],c),h=this.lerp(j[2],k[2],c),i=this.lerp(j[3],k[3],c),f*=m[l][0],g*=m[l][1],h*=m[l][2],i*=m[l][3],this.color(f,g,h,i)},d.prototype.lightness=function(a){return d._validateParameters("lightness",arguments),this.color(a)._getLightness()},d.prototype.red=function(a){return d._validateParameters("red",arguments),this.color(a)._getRed()},d.prototype.saturation=function(a){return d._validateParameters("saturation",arguments),this.color(a)._getSaturation()},b.exports=d},{"../core/constants":54,"../core/core":55,"../core/error_helpers":58,"./p5.Color":49}],49:[function(a,b,c){var d=a("../core/core"),e=a("../core/constants"),f=a("./color_conversion");d.Color=function(a,b){if(this._storeModeAndMaxes(a._colorMode,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(this,b),this._calculateLevels(),this.name="p5.Color",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.setRed=function(a){this._array[0]=a/this.maxes[e.RGB][0],this._calculateLevels()},d.Color.prototype.setGreen=function(a){this._array[1]=a/this.maxes[e.RGB][1],this._calculateLevels()},d.Color.prototype.setBlue=function(a){this._array[2]=a/this.maxes[e.RGB][2],this._calculateLevels()},d.Color.prototype.setAlpha=function(a){this._array[3]=a/this.maxes[this.mode][3],this._calculateLevels()},d.Color.prototype._calculateLevels=function(){this.levels=this._array.map(function(a){return Math.round(255*a)})},d.Color.prototype._getAlpha=function(){return this._array[3]*this.maxes[this.mode][3]},d.Color.prototype._storeModeAndMaxes=function(a,b){this.mode=a,this.maxes=b},d.Color.prototype._getMode=function(){return this.mode},d.Color.prototype._getMaxes=function(){return this.maxes},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,HEX4:/^#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])$/i,HEX6:/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i,HEX8:/^#([a-f0-9]{2})([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.mode,c=this.maxes,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.HEX4.test(i))return h=l.HEX4.exec(i).slice(1).map(function(a){return parseInt(a+a,16)/255});if(l.HEX8.test(i))return h=l.HEX8.exec(i).slice(1).map(function(a){return parseInt(a,16)/255});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":54,"../core/core":55,"./color_conversion":47}],50:[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.isP3D&&this._renderer.noFill(),this._renderer._setProperty("_doFill",!1),this},d.prototype.noStroke=function(){return this._renderer.isP3D&&this._renderer.noStroke(),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":54,"../core/core":55,"./p5.Color":49}],51:[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,f,g,h,i){for(var j=new Array(arguments.length),k=0;ke.HALF_PI&&g<=3*e.HALF_PI?Math.atan(c/f*Math.tan(g))+e.PI:Math.atan(c/f*Math.tan(g))+e.TWO_PI,h=h<=e.HALF_PI?Math.atan(c/f*Math.tan(h)):h>e.HALF_PI&&h<=3*e.HALF_PI?Math.atan(c/f*Math.tan(h))+e.PI:Math.atan(c/f*Math.tan(h))+e.TWO_PI,g>h&&(h+=e.TWO_PI),c=Math.abs(c),f=Math.abs(f),this._renderer.arc(a,b,c,f,g,h,i),this},d.prototype.ellipse=function(){for(var a=new Array(arguments.length),b=0;b=c-5)&&(this.redraw(),this._frameRate=1e3/(a-this._lastFrameTime),this._lastFrameTime=a,void 0!==this._updateMouseCoords&&this._updateMouseCoords()),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;b-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":54,"./core":55}],58:[function(a,b,c){"use strict";function d(a,b,c){m&&(i(),m=!1),"undefined"===t(c)?c="#B40033":"number"===t(c)&&(c=v[c]),"load"===b.substring(0,4)?console.log("> p5.js says: "+a+"[https://github.com/processing/p5.js/wiki/Local-server]"):console.log("> p5.js says: "+a+" [http://p5js.org/reference/#p5/"+b+"]")}function e(a){var b=o.classitems.filter(function(b){return b.name===a});if(b[0].hasOwnProperty("overloads")){for(var c=[],d=0;d p5.js says: Welcome! This is your friendly debugger. To turn me off switch to using “p5.min.js”.")}function j(){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}})};x=[].concat(c(l.prototype),c(a("./constants"))),x.sort(function(a,b){return b.name.length-a.name.length})}function k(a,b){b||(b=console.log.bind(console)),x||j(),x.some(function(c){if(a.message&&null!==a.message.match("\\W?"+c.name+"\\W"))return b("Did 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: "+y),!0})}for(var l=a("./core"),m=!1,n=a("../../docs/reference/data.json"),o=JSON.parse(JSON.stringify(n)),p={},q=p.toString,r=["Boolean","Number","String","Function","Array","Date","RegExp","Object","Error"],s=0;s1){for(var h=0;hi.length&&(g=i.length,d=i)}for(var j=0;j1&&e("drop",b,this),e("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},g.Element.prototype._setProperty=function(a,b){this[a]=b},b.exports=g.Element},{"./core":55}],61:[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.name="p5.Graphics",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":54,"./core":55}],62:[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.name="p5.Renderer",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":54,"./core":55}],63:[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.name="p5.Renderer2D",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._cachedFillStyle=this._cachedStrokeStyle=void 0,this._setFill(f._DEFAULT_FILL),this._setStroke(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._getFill(),b=this._pInst.color.apply(this,arguments),c=b.toString();this._setFill(c),this.drawingContext.fillRect(0,0,this.width,this.height),this._setFill(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._pInst.color.apply(this,arguments);this._setFill(a.toString())},d.Renderer2D.prototype.stroke=function(){var a=this._pInst.color.apply(this,arguments);this._setStroke(a.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||this instanceof d.RendererGL){var j=Math.min(c,f.width),k=Math.min(e,f.height),l=j*g,m=k*g,n=new d.Image(j,k);return n.canvas.getContext("2d").drawImage(this.canvas,h,i,l,m,0,0,j,k),n}var o=this.drawingContext.getImageData(h,i,1,1).data;return[o[0],o[1],o[2],o[3]]},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(this._getFill()===h)return this}else if(!c&&d&&this._getStroke()===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?this._getStroke()===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;if(!this._doStroke)return this;if(this._getStroke()===h)return this;var d=this._getStroke(),e=this._getFill();a=Math.round(a),b=Math.round(b),this._setFill(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),this._setFill(e)},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(this._getFill()===h)return this}else if(!k&&l&&this._getStroke()===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(this._getFill()===h)return this}else if(!l&&m&&this._getStroke()===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(this._getFill()===h)return this}else if(!c&&d&&this._getStroke()===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(),k=2;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._fillSet||this._setFill(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||"normal")+" "+(this._textSize||12)+"px "+(a||"sans-serif"),b},d.Renderer2D.prototype.push=function(){this.drawingContext.save()},d.Renderer2D.prototype.pop=function(){this.drawingContext.restore(),this._cachedFillStyle=this.drawingContext.fillStyle,this._cachedStrokeStyle=this.drawingContext.strokeStyle},b.exports=d.Renderer2D},{"../image/filters":74,"./canvas":53,"./constants":54,"./core":55,"./p5.Renderer":62}],64:[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=c||e.P2D;if(h===e.WEBGL)g=document.getElementById(f),g&&(g.parentNode.removeChild(g),this._elements=this._elements.filter(function(a){return a!==this._renderer})),g=document.createElement("canvas"),g.id=f;else if(this._defaultGraphicsCreated)g=this.canvas;else{g=document.createElement("canvas");for(var i=0;document.getElementById("defaultCanvas"+i);)i++;f="defaultCanvas"+i,g.id=f}return this._setupDone||(g.dataset.hidden=!0,g.style.visibility="hidden"),this._userNode?this._userNode.appendChild(g):document.body.appendChild(g),h===e.WEBGL?(this._setProperty("_renderer",new d.RendererGL(g,this,!0)),this._elements.push(this._renderer)):this._defaultGraphicsCreated||(this._setProperty("_renderer",new d.Renderer2D(g,this,!0)),this._defaultGraphicsCreated=!0,this._elements.push(this._renderer)),this._renderer.resize(a,b),this._renderer._applyDefaults(),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":106,"./constants":54,"./core":55,"./p5.Graphics":61,"./p5.Renderer2D":63}],65:[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})}()},{}],66:[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(c,d[1]):this._renderer.rotate(c),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":55}],71:[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":55}],72:[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._doubleClicked=function(a){var b=this._isGlobal?window:this;if("function"==typeof b.doubleClicked){b.ondblclick(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":54,"../core/core":55}],73:[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(),this.setModified(!0)},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,this.setModified(!0)},d.Image.prototype.filter=function(a,b){e.apply(this.canvas,e[a.toLowerCase()],b),this.setModified(!0)},d.Image.prototype.blend=function(){d.prototype.blend.apply(this,arguments),this.setModified(!0)},d.Image.prototype.setModified=function(a){this._modified=a},d.Image.prototype.isModified=function(){return this._modified},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":55,"./filters":74}],78:[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":49,"../core/core":55,"./filters":74}],79:[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");a("whatwg-fetch"),a("es6-promise").polyfill();var i=a("fetch-jsonp");a("../core/error_helpers"),h.prototype.loadJSON=function(){for(var a,b,c,d=arguments[0],e={},f="json",g=1;g0&&"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 j,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":55,"../core/error_helpers":58,"es6-promise":5,"fetch-jsonp":6,"whatwg-fetch":45}],80:[function(a,b,c){"use strict";var d=a("../core/core");d.Table=function(a){this.columns=[],this.rows=[],this.name="p5.Table"},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=this.dot(a)/(this.mag()*a.mag()),c=Math.acos(Math.min(1,Math.max(-1,b)));return this.p5&&this.p5._angleMode===f.DEGREES&&(c=e.radiansToDegrees(c)),c},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":54,"../core/core":55,"./polargeometry":87}],87:[function(a,b,c){b.exports={degreesToRadians:function(a){return 2*Math.PI*a/360},radiansToDegrees:function(a){return 360*a/(2*Math.PI)}}},{}],88:[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":55}],89:[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":54,"../core/core":55,"./polargeometry":87}],90:[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":55}],91:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("../core/constants"),f=a("opentype.js");a("../core/error_helpers"),d.prototype.loadFont=function(a,b,c){var e=new d.Font(this),g=this;return f.load(a,function(f,h){if(f)return void 0!==c?c(f):(d._friendlyFileLoadError(4,a),void console.error(f,a));e.font=h,void 0!==b&&b(e),g._decrementPreload();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))}),e},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":54,"../core/core":55,"../core/error_helpers":58,"opentype.js":18}],92:[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;if(!a)return b;"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":55}],94:[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":55}],95:[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");a("../core/error_helpers"),h.prototype.join=function(a,b){return h._validateParameters("join",arguments),a.join(b)},h.prototype.match=function(a,b){return h._validateParameters("match",arguments),a.match(b)},h.prototype.matchAll=function(a,b){h._validateParameters("matchAll",arguments);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(h._validateParameters("nf",arguments),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(h._validateParameters("nfc",arguments),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(){h._validateParameters("nfp",arguments);var a=h.prototype.nf.apply(this,arguments);return a instanceof Array?a.map(f):f(a)},h.prototype.nfs=function(){h._validateParameters("nfs",arguments);var a=h.prototype.nf.apply(this,arguments);return a instanceof Array?a.map(g):g(a)},h.prototype.split=function(a,b){return h._validateParameters("split",arguments),a.split(b)},h.prototype.splitTokens=function(){h._validateParameters("splitTokens",arguments);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 h._validateParameters("trim",arguments),a instanceof Array?a.map(this.trim):a.trim()},b.exports=h},{"../core/core":55,"../core/error_helpers":58}],96:[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":55}],97:[function(a,b,c){"use strict";var d=a("../core/core");d.prototype.camera=function(){return this._renderer.camera.apply(this._renderer,arguments),this},d.RendererGL.prototype.camera=function(){var a,b,c,d,e,f,g,h,i;0===arguments.length?(a=this.defaultCameraX,b=this.defaultCameraY,c=this.defaultCameraZ,d=a,e=b,f=0,g=0,h=1,i=0):(a=arguments[0],b=arguments[1],c=arguments[2],d=arguments[3],e=arguments[4],f=arguments[5],g=arguments[6],h=arguments[7],i=arguments[8]),this.cameraX=a,this.cameraY=b,this.cameraZ=c;var j=a-d,k=b-e,l=c-f;this.eyeDist=Math.sqrt(j*j+k*k+l*l),0!==this.eyeDist&&(j/=this.eyeDist,k/=this.eyeDist,l/=this.eyeDist);var m=g,n=h,o=i,p=n*l-o*k,q=-m*l+o*j,r=m*k-n*j;m=k*r-l*q,n=-j*r+l*p,o=j*q-k*p;var s=Math.sqrt(p*p+q*q+r*r);0!==s&&(p/=s,q/=s,r/=s);var t=Math.sqrt(m*m+n*n+o*o);0!==t&&(m/=t,n/=t,o/=t),this.cameraMatrix.set(p,m,j,0,q,n,k,0,r,o,l,0,0,0,0,1);var u=-a,v=-b,w=-c;return this.cameraMatrix.translate([u,v,w]),this.uMVMatrix.set(this.cameraMatrix.mat4[0],this.cameraMatrix.mat4[1],this.cameraMatrix.mat4[2],this.cameraMatrix.mat4[3],this.cameraMatrix.mat4[4],this.cameraMatrix.mat4[5],this.cameraMatrix.mat4[6],this.cameraMatrix.mat4[7],this.cameraMatrix.mat4[8],this.cameraMatrix.mat4[9],this.cameraMatrix.mat4[10],this.cameraMatrix.mat4[11],this.cameraMatrix.mat4[12],this.cameraMatrix.mat4[13],this.cameraMatrix.mat4[14],this.cameraMatrix.mat4[15]),this},d.prototype.perspective=function(){return this._renderer.perspective.apply(this._renderer,arguments),this},d.RendererGL.prototype.perspective=function(){var a=arguments[0]||this.defaultCameraFOV,b=arguments[1]||this.defaultCameraAspect,c=arguments[2]||this.defaultCameraNear,e=arguments[3]||this.defaultCameraFar;this.cameraFOV=a,this.cameraAspect=b,this.cameraNear=c,this.cameraFar=e,this.uPMatrix=d.Matrix.identity();var f=1/Math.tan(this.cameraFOV/2),g=1/(this.cameraNear-this.cameraFar);this.uPMatrix.set(f/b,0,0,0,0,-f,0,0,0,0,(e+c)*g,-1,0,0,2*e*c*g,0),this._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();var h=b-a,i=e-c,j=g-f,k=2/h,l=2/i,m=-2/j,n=-(b+a)/h,o=-(e+c)/i,p=-(g+f)/j;this._renderer.uPMatrix.set(k,0,0,0,0,-l,0,0,0,0,m,0,n,o,p,1),this._renderer._curCamera="custom"},b.exports=d},{"../core/core":55}],98:[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":55}],99:[function(a,b,c){"use strict";var d=a("../core/core");d.prototype.ambientLight=function(a,b,c,d){this._renderer.curFillShader.isLightShader()||this._renderer.setFillShader(this._renderer._getLightShader());var e=this._renderer._pInst.color.apply(this._renderer._pInst,arguments),f=new Float32Array(e._array.slice(0,3));return this._renderer.curFillShader.setUniform("uAmbientColor",f),this._renderer.curFillShader.setUniform("uUseLighting",!0),this._renderer.ambientLightCount++,this._renderer.curFillShader.setUniform("uMaterialColor",this._renderer.curFillColor),this._renderer.curFillShader.setUniform("uAmbientLightCount",this._renderer.ambientLightCount),this},d.prototype.directionalLight=function(a,b,c,d,e,f){this._renderer.curFillShader.isLightShader()||this._renderer.setFillShader(this._renderer._getLightShader());var g=this._renderer._pInst.color.apply(this._renderer._pInst,[a,b,c]),h=new Float32Array(g._array.slice(0,3));this._renderer.curFillShader.setUniform("uDirectionalColor",h);for(var i,j,k,l=new Array(arguments.length),m=0;m0)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)||(a._makeTriangleEdges(),this._renderer._edgesToVertices(a),this._renderer.createBuffers(a.gid,a)),this._renderer.drawBuffers(a.gid))},b.exports=e},{"../core/core":55,"./p5.Geometry":102}],101:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("../core/constants");a("./p5.Texture"),d.prototype.loadShader=function(a,b){var c=new d.Shader,e=this,f=!1,g=!1;return this.loadStrings(b,function(a){c._fragSrc=a.join("\n"),f=!0,g||e._incrementPreload()}),this.loadStrings(a,function(a){c._vertSrc=a.join("\n"),g=!0,f||e._incrementPreload()}),c},d.prototype.shader=function(a){return void 0===a._renderer&&(a._renderer=this._renderer),a.isStrokeShader()?this._renderer.setStrokeShader(a):this._renderer.setFillShader(a),this},d.prototype.normalMaterial=function(){return this._renderer.drawMode=e.FILL,this._renderer.setFillShader(this._renderer._getNormalShader()),this._renderer.noStroke(),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._makeTriangleEdges=function(){if(Array.isArray(this.strokeIndices))for(var a=0,b=this.strokeIndices.length;a0){for(var a=this.vertices[0].copy(),b=this.vertices[0].copy(),c=0;c1e3){var b=Object.keys(this.gHash)[0];delete this.gHash[b],e--}var c=this.GL;this.gHash[a]={},this.gHash[a].vertexBuffer=c.createBuffer(),this.gHash[a].normalBuffer=c.createBuffer(),this.gHash[a].lineNormalBuffer=c.createBuffer(),this.gHash[a].uvBuffer=c.createBuffer(),this.gHash[a].indexBuffer=c.createBuffer(),this.gHash[a].lineVertexBuffer=c.createBuffer()},d.RendererGL.prototype.createBuffers=function(a,b){var c=this.GL;this._setDefaultCamera(),this._initBufferDefaults(a),this.gHash[a].numberOfItems=3*b.faces.length,this.gHash[a].lineVertexCount=b.lineVertices.length,this.curFillShader===this._getImmediateModeShader()&&this.setFillShader(this._getColorShader()),this._bindBuffer(this.gHash[a].lineVertexBuffer,c.ARRAY_BUFFER,this._flatten(b.lineVertices),Float32Array,c.STATIC_DRAW),this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aPosition.location,3,c.FLOAT,!1,0,0),this._bindBuffer(this.gHash[a].lineNormalBuffer,c.ARRAY_BUFFER,this._flatten(b.lineNormals),Float32Array,c.STATIC_DRAW),this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aDirection.location,4,c.FLOAT,!1,0,0),this._bindBuffer(this.gHash[a].vertexBuffer,c.ARRAY_BUFFER,this._vToNArray(b.vertices),Float32Array,c.STATIC_DRAW),this.curFillShader.enableAttrib(this.curFillShader.attributes.aPosition.location,3,c.FLOAT,!1,0,0),this._bindBuffer(this.gHash[a].indexBuffer,c.ELEMENT_ARRAY_BUFFER,this._flatten(b.faces),Uint16Array,c.STATIC_DRAW),this._bindBuffer(this.gHash[a].normalBuffer,c.ARRAY_BUFFER,this._vToNArray(b.vertexNormals),Float32Array,c.STATIC_DRAW),this.curFillShader.enableAttrib(this.curFillShader.attributes.aNormal.location,3,c.FLOAT,!1,0,0),this._bindBuffer(this.gHash[a].uvBuffer,c.ARRAY_BUFFER,this._flatten(b.uvs),Float32Array,c.STATIC_DRAW),this.curFillShader.enableAttrib(this.curFillShader.attributes.aTexCoord.location,2,c.FLOAT,!1,0,0)},d.RendererGL.prototype.drawBuffers=function(a){this._setDefaultCamera();var b=this.GL;return this.curFillShader===this._getImmediateModeShader()&&this.setFillShader(this._getColorShader()),this.curStrokeShader.active!==!1&&this.gHash[a].lineVertexCount>0&&(this.curStrokeShader.bindShader(),this._bindBuffer(this.gHash[a].lineVertexBuffer,b.ARRAY_BUFFER),this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aPosition.location,3,b.FLOAT,!1,0,0),this._bindBuffer(this.gHash[a].lineNormalBuffer,b.ARRAY_BUFFER),this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aDirection.location,4,b.FLOAT,!1,0,0),this._drawArrays(b.TRIANGLES,a),this.curStrokeShader.unbindShader()),this.curFillShader.active!==!1&&(this.curFillShader.bindShader(),this._bindBuffer(this.gHash[a].vertexBuffer,b.ARRAY_BUFFER),this.curFillShader.enableAttrib(this.curFillShader.attributes.aPosition.location,3,b.FLOAT,!1,0,0),this._bindBuffer(this.gHash[a].indexBuffer,b.ELEMENT_ARRAY_BUFFER),this._bindBuffer(this.gHash[a].normalBuffer,b.ARRAY_BUFFER),this.curFillShader.enableAttrib(this.curFillShader.attributes.aNormal.location,3,b.FLOAT,!1,0,0),this._bindBuffer(this.gHash[a].uvBuffer,b.ARRAY_BUFFER),this.curFillShader.enableAttrib(this.curFillShader.attributes.aTexCoord.location,2,b.FLOAT,!1,0,0),this._drawElements(b.TRIANGLES,a),this.curFillShader.unbindShader()),this},d.RendererGL.prototype._drawArrays=function(a,b){return this.GL.drawArrays(a,0,this.gHash[b].lineVertexCount),this},d.RendererGL.prototype._drawElements=function(a,b){this.GL.drawElements(a,this.gHash[b].numberOfItems,this.GL.UNSIGNED_SHORT,0)},b.exports=d.RendererGL},{"../core/core":55}],106:[function(a,b,c){"use strict";var d=a("../core/core"),e=a("../core/constants");a("./p5.Shader"),a("../core/p5.Renderer"),a("./p5.Matrix");var f=[],g=[],h={immediateVert:"attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uResolution;\nuniform float uPointSize;\n\nvarying vec4 vColor;\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n gl_PointSize = uPointSize;\n}\n",vertexColorVert:"attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nvarying vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n}\n",vertexColorFrag:"precision mediump float;\nvarying vec4 vColor;\nvoid main(void) {\n gl_FragColor = vColor;\n}",normalVert:"attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvarying vec3 vVertexNormal;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = vec3( uNormalMatrix * aNormal );\n vVertTexCoord = aTexCoord;\n}\n",normalFrag:"precision mediump float;\nvarying vec3 vVertexNormal;\nvoid main(void) {\n gl_FragColor = vec4(vVertexNormal, 1.0);\n}",basicFrag:"precision mediump float;\nvarying vec3 vVertexNormal;\nuniform vec4 uMaterialColor;\nvoid main(void) {\n gl_FragColor = uMaterialColor;\n}",lightVert:"attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nuniform vec3 uAmbientColor[8];\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\n\nvarying vec3 vVertexNormal;\nvarying vec2 vVertTexCoord;\nvarying vec3 vLightWeighting;\n\nvec3 ambientLightFactor = vec3(0.0, 0.0, 0.0);\nvec3 directionalLightFactor = vec3(0.0, 0.0, 0.0);\nvec3 pointLightFactor = vec3(0.0, 0.0, 0.0);\nvec3 pointLightFactor2 = vec3(0.0, 0.0, 0.0);\n\nvoid main(void){\n\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\n vec3 vertexNormal = vec3( uNormalMatrix * aNormal );\n vVertexNormal = vertexNormal;\n vVertTexCoord = aTexCoord;\n\n vec4 mvPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n vec3 eyeDirection = normalize(-mvPosition.xyz);\n\n float shininess = 32.0;\n float specularFactor = 2.0;\n float diffuseFactor = 0.3;\n\n for(int i = 0; i < 8; i++){\n if(uAmbientLightCount == i) break;\n ambientLightFactor += uAmbientColor[i];\n }\n\n for(int j = 0; j < 8; j++){\n if(uDirectionalLightCount == j) break;\n vec3 dir = uLightingDirection[j];\n float directionalLightWeighting = max(dot(vertexNormal, dir), 0.0);\n directionalLightFactor += uDirectionalColor[j] * directionalLightWeighting;\n }\n\n for(int k = 0; k < 8; k++){\n if(uPointLightCount == k) break;\n vec3 loc = uPointLightLocation[k];\n vec3 lightDirection = normalize(loc - mvPosition.xyz);\n\n float directionalLightWeighting = max(dot(vertexNormal, lightDirection), 0.0);\n pointLightFactor += uPointLightColor[k] * directionalLightWeighting;\n\n //factor2 for specular\n vec3 reflectionDirection = reflect(-lightDirection, vertexNormal);\n float specularLightWeighting = pow(max(dot(reflectionDirection, eyeDirection), 0.0), shininess);\n\n pointLightFactor2 += uPointLightColor[k] * (specularFactor * specularLightWeighting\n + directionalLightWeighting * diffuseFactor);\n }\n\n if(!uSpecular){\n vLightWeighting = ambientLightFactor + directionalLightFactor + pointLightFactor;\n }else{\n vLightWeighting = ambientLightFactor + directionalLightFactor + pointLightFactor2;\n }\n\n}\n",lightTextureFrag:"precision mediump float;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uUseLighting;\n\nvarying vec3 vLightWeighting;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n if(!isTexture){\n gl_FragColor = vec4(vec3(uMaterialColor.rgb * vLightWeighting), uMaterialColor.a);\n }else{\n vec4 textureColor = texture2D(uSampler, vVertTexCoord);\n if(!uUseLighting){\n gl_FragColor = textureColor;\n }else{\n gl_FragColor = vec4(vec3(textureColor.rgb * vLightWeighting), textureColor.a);\n }\n }\n}",lineVert:"uniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nuniform vec4 uViewport;\n\nuniform float uStrokeWeight;\n\nattribute vec4 aPosition;\nattribute vec4 aDirection;\n\n\nvec3 clipToWindow(vec4 clip, vec4 viewport) {\n vec3 post_div = clip.xyz / clip.w;\n vec2 xypos = (post_div.xy + vec2(1.0, 1.0)) * 0.5 * viewport.zw;\n return vec3(xypos, post_div.z * 0.5 + 0.5);\n}\n\nvec4 windowToClipVector(vec2 window, vec4 viewport, float clip_w) {\n vec2 xypos = (window / viewport.zw) * 2.0;\n return vec4(xypos, 0.0, 0.0) * clip_w;\n}\n\nvoid main() {\n vec4 posMV = uModelViewMatrix * aPosition;\n posMV.xyz = posMV.xyz * vec3(0.999,0.999,0.999);\n vec4 clipp = uProjectionMatrix * posMV;\n float displace = aDirection.w;\n\n vec4 posq = uModelViewMatrix * vec4(aDirection.xyz, 0.0);\n posq.xyz = posq.xyz * vec3(0.999,0.999,0.999);\n vec4 clipq = uProjectionMatrix * posq;\n clipq.w = 1.0;\n\n vec3 window_p = clipToWindow(clipp, uViewport);\n vec3 window_q = clipToWindow(clipq, uViewport);\n vec3 tangent = window_q - window_p;\n vec2 perp = normalize(vec2(-tangent.y, tangent.x));\n float halfStroke = uStrokeWeight/2.0;\n vec2 offset = vec2(halfStroke,halfStroke) * displace * perp;\n gl_Position.xy = clipp.xy + offset.xy;\n gl_Position.zw = clipp.zw;\n}\n",lineFrag:"precision mediump float;\nprecision mediump int;\n\nuniform vec4 uMaterialColor;\n\nvoid main() {\n gl_FragColor = uMaterialColor;\n}"};d.RendererGL=function(a,b,c,e){return d.Renderer.call(this,a,b,c),this.attributes={},e=e||{},this.attributes.alpha=void 0===e.alpha||e.alpha,this.attributes.depth=void 0===e.depth||e.depth,this.attributes.stencil=void 0===e.stencil||e.stencil,this.attributes.antialias=void 0!==e.antialias&&e.antialias,this.attributes.premultipliedAlpha=void 0!==e.premultipliedAlpha&&e.premultipliedAlpha,this.attributes.preserveDrawingBuffer=void 0===e.preserveDrawingBuffer||e.preserveDrawingBuffer,this._initContext(),this.isP3D=!0,this.GL=this.drawingContext,this.ambientLightCount=0,this.directionalLightCount=0,this.pointLightCount=0,this.uMVMatrix=new d.Matrix,this.uPMatrix=new d.Matrix,this.uNMatrix=new d.Matrix("mat3"),this._curCamera=null,this._computeCameraDefaultSettings(),this.cameraFOV=this.defaultCameraFOV,this.cameraAspect=this.defaultAspect,this.cameraX=this.defaultCameraX,this.cameraY=this.defaultCameraY,this.cameraZ=this.defaultCameraZ,this.cameraNear=this.defaultCameraNear,this.cameraFar=this.defaultCameraFar,this.cameraMatrix=new d.Matrix,this.camera(),this.gHash={},this._defaultLightShader=void 0,this._defaultImmediateModeShader=void 0,this._defaultNormalShader=void 0,this._defaultColorShader=void 0,this.curFillShader={},this.curStrokeShader={},this.setFillShader(this._getColorShader()),this.setStrokeShader(this._getLineShader()),this.isImmediateDrawing=!1,this.immediateMode={},this.fill(255,255,255,255),this.pointSize=5,this.curStrokeWeight=2,this.curStrokeColor=[0,0,0,1],this._setStrokeWeight(),this._setStrokeColor(),this.textures=[],this.name="p5.RendererGL",this},d.RendererGL.prototype=Object.create(d.Renderer.prototype),d.RendererGL.prototype._initContext=function(){try{if(this.drawingContext=this.canvas.getContext("webgl",this.attributes)||this.canvas.getContext("experimental-webgl",this.attributes),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._resetContext=function(a,b,c){var e=this.width,f=this.height,g=this.canvas.id,h=this.canvas;h&&h.parentNode.removeChild(h),h=document.createElement("canvas"),h.id=g,this._pInst._userNode?this._pInst._userNode.appendChild(h):document.body.appendChild(h),this._pInst.canvas=h,this._pInst._setProperty("_renderer",new d.RendererGL(this._pInst.canvas,this._pInst,!0,a)),this._pInst._renderer.resize(e,f),this._pInst._renderer._applyDefaults(),this._pInst._elements.push(this._renderer),"function"==typeof c&&setTimeout(function(){c.apply(window._renderer,b)},0)},d.prototype.setAttributes=function(){var a={};2===arguments.length?a[arguments[0]]=arguments[1]:1===arguments.length&&(a=arguments[0]),this._renderer._resetContext(a)},d.RendererGL.prototype._computeCameraDefaultSettings=function(){this.defaultCameraFOV=60/180*Math.PI,this.defaultCameraAspect=this.width/this.height,this.defaultCameraX=0,this.defaultCameraY=0,this.defaultCameraZ=this.height/2/Math.tan(this.defaultCameraFOV/2),this.defaultCameraNear=.1*this.defaultCameraZ,this.defaultCameraFar=10*this.defaultCameraZ},d.RendererGL.prototype._setDefaultCamera=function(){null===this._curCamera&&(this._computeCameraDefaultSettings(),this.cameraFOV=this.defaultCameraFOV,this.cameraAspect=this.defaultAspect,this.cameraX=this.defaultCameraX,this.cameraY=this.defaultCameraY,this.cameraZ=this.defaultCameraZ,this.cameraNear=this.defaultCameraNear,this.cameraFar=this.defaultCameraFar,this.perspective(),this.camera(),this._curCamera="default")},d.RendererGL.prototype._update=function(){this.uMVMatrix.set(this.cameraMatrix.mat4[0],this.cameraMatrix.mat4[1],this.cameraMatrix.mat4[2],this.cameraMatrix.mat4[3],this.cameraMatrix.mat4[4],this.cameraMatrix.mat4[5],this.cameraMatrix.mat4[6],this.cameraMatrix.mat4[7],this.cameraMatrix.mat4[8],this.cameraMatrix.mat4[9],this.cameraMatrix.mat4[10],this.cameraMatrix.mat4[11],this.cameraMatrix.mat4[12],this.cameraMatrix.mat4[13],this.cameraMatrix.mat4[14],this.cameraMatrix.mat4[15]),this.ambientLightCount=0,this.directionalLightCount=0,this.pointLightCount=0},d.RendererGL.prototype.background=function(){var a=this._pInst.color.apply(this._pInst,arguments),b=a.levels[0]/255,c=a.levels[1]/255,d=a.levels[2]/255,e=a.levels[3]/255;this.GL.clearColor(b,c,d,e),this.GL.clear(this.GL.COLOR_BUFFER_BIT|this.GL.DEPTH_BUFFER_BIT)},d.RendererGL.prototype.fill=function(a,b,c,d){var f=this._applyColorBlend.apply(this,arguments);this.curFillColor=f,this.curFillShader.active===!1&&(this.curFillShader.active=!0),this.isImmediateDrawing?this.setFillShader(this._getImmediateModeShader()):this.setFillShader(this._getColorShader()),this.drawMode=e.FILL,this.curFillShader.setUniform("uMaterialColor",f)},d.RendererGL.prototype.noFill=function(){this.curFillShader.active=!1},d.RendererGL.prototype.noStroke=function(){this.curStrokeShader.active=!1},d.RendererGL.prototype.stroke=function(a,b,c,d){this.curStrokeShader.active===!1&&(this.curStrokeShader.active=!0),arguments[3]=255;var e=this._applyColorBlend.apply(this,arguments);this.curStrokeColor!==e&&(this.curStrokeColor=e,this._setStrokeColor())},d.RendererGL.prototype.strokeWeight=function(a){this.curStrokeShader.active===!1&&(this.curStrokeShader.active=!0),this.curStrokeWeight!==a&&(this.pointSize=a,this.curStrokeWeight=a,this.curStrokeShader.setUniform("uStrokeWeight",a))},d.RendererGL.prototype._setStrokeWeight=function(){this.curStrokeShader.setUniform("uStrokeWeight",this.curStrokeWeight)},d.RendererGL.prototype._setStrokeColor=function(){this.curStrokeShader.setUniform("uMaterialColor",this.curStrokeColor)},d.RendererGL.prototype.get=function(a,b,c,e){return d.Renderer2D.prototype.get.apply(this,[a,b,c,e])},d.RendererGL.prototype.loadPixels=function(){if(this.attributes.preserveDrawingBuffer!==!0)return void console.log("loadPixels only works in WebGL when preserveDrawingBuffer is true.");var a=this._pInst._pixelDensity,b=arguments[0]||0,c=arguments[1]||0,d=arguments[2]||this.width,e=arguments[3]||this.height;d*=a,e*=a;var f=new Uint8Array(this.GL.drawingBufferWidth*this.GL.drawingBufferHeight*4);this.GL.readPixels(b,c,d,e,this.GL.RGBA,this.GL.UNSIGNED_BYTE,f),this._pInst._setProperty("pixels",f)},d.RendererGL.prototype.geometryInHash=function(a){return void 0!==this.gHash[a]},d.RendererGL.prototype.resize=function(a,b){d.Renderer.prototype.resize.call(this,a,b),this.GL.viewport(0,0,this.GL.drawingBufferWidth,this.GL.drawingBufferHeight),null!==this._curCamera&&"default"!==this._curCamera||(this._curCamera=null,this._setDefaultCamera())},d.RendererGL.prototype.clear=function(){this.GL.clearColor(arguments[0],arguments[1],arguments[2],arguments[3]),this.GL.clear(this.GL.COLOR_BUFFER_BIT|this.GL.DEPTH_BUFFER_BIT)},d.RendererGL.prototype.translate=function(a,b,c){return a instanceof d.Vector&&(c=a.z,b=a.y,a=a.x),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()),g.push(this.cameraMatrix.copy())},d.RendererGL.prototype.pop=function(){if(0===f.length)throw new Error("Invalid popMatrix!");if(this.uMVMatrix=f.pop(),0===g.length)throw new Error("Invalid popMatrix!");this.cameraMatrix=g.pop()},d.RendererGL.prototype.resetMatrix=function(){return this.uMVMatrix=d.Matrix.identity(),this},d.RendererGL.prototype._applyTextProperties=function(){console.error("text commands not yet implemented in webgl")},d.RendererGL.prototype.setFillShader=function(a){return this.curFillShader!==a&&(this.curFillShader=a,this.curFillShader.init(),this.curFillShader.useProgram(),this.curFillShader.active=!0),this.curFillShader},d.RendererGL.prototype.setStrokeShader=function(a){return this.curStrokeShader!==a&&(this.curStrokeShader=a,this.curStrokeShader.init(),this.curStrokeShader.useProgram(),this.curStrokeShader.active=!0),this.curStrokeShader},d.RendererGL.prototype._getLightShader=function(){return void 0===this._defaultLightShader&&(this._defaultLightShader=new d.Shader(this,h.lightVert,h.lightTextureFrag)),this._defaultLightShader},d.RendererGL.prototype._getImmediateModeShader=function(){return void 0===this._defaultImmediateModeShader&&(this._defaultImmediateModeShader=new d.Shader(this,h.immediateVert,h.vertexColorFrag)),this._defaultImmediateModeShader},d.RendererGL.prototype._getNormalShader=function(){return void 0===this._defaultNormalShader&&(this._defaultNormalShader=new d.Shader(this,h.normalVert,h.normalFrag)),this._defaultNormalShader},d.RendererGL.prototype._getColorShader=function(){return void 0===this._defaultColorShader&&(this._defaultColorShader=new d.Shader(this,h.normalVert,h.basicFrag)),this._defaultColorShader},d.RendererGL.prototype._getLineShader=function(){return void 0===this._defaultLineShader&&(this._defaultLineShader=new d.Shader(this,h.lineVert,h.lineFrag)),this._defaultLineShader},d.RendererGL.prototype._getEmptyTexture=function(){if(void 0===this._emptyTexture){var a=new d.Image(1,1);a.set(0,0,255),this._emptyTexture=new d.Texture(this,a)}return this._emptyTexture},d.RendererGL.prototype.getTexture=function(a){var b=function(b){return b.src===a},c=this.textures.find(b);return void 0===c&&(c=new d.Texture(this,a),this.textures.push(c)),c},d.RendererGL.prototype._bindBuffer=function(a,b,c,d,e){if(this.GL.bindBuffer(b,a),void 0!==c){var f=new d(c);this.GL.bufferData(b,f,e)}},d.RendererGL.prototype._flatten=function(a){return a.length>0?[].concat.apply([],a):[]},d.RendererGL.prototype._vToNArray=function(a){return this._flatten(a.map(function(a){return[a.x,a.y,a.z]}))},b.exports=d.RendererGL},{"../core/constants":54,"../core/core":55,"../core/p5.Renderer":62,"./p5.Matrix":103,"./p5.Shader":107}],107:[function(a,b,c){var d=a("../core/core");d.Shader=function(a,b,c){return this._renderer=a,this._vertSrc=b,this._fragSrc=c,this._vertShader=-1,this._fragShader=-1,this._glProgram=0,this._loadedAttributes=!1,this.attributes={},this._loadedUniforms=!1,this.uniforms={},this._bound=!1,this.samplers=[],this},d.Shader.prototype.init=function(){if(0===this._glProgram){var a=this._renderer.GL;if(this._vertShader=a.createShader(a.VERTEX_SHADER),a.shaderSource(this._vertShader,this._vertSrc),a.compileShader(this._vertShader),!a.getShaderParameter(this._vertShader,a.COMPILE_STATUS))return console.error("Yikes! An error occurred compiling the vertex shader:"+a.getShaderInfoLog(this._vertShader)),null;if(this._fragShader=a.createShader(a.FRAGMENT_SHADER),a.shaderSource(this._fragShader,this._fragSrc),a.compileShader(this._fragShader),!a.getShaderParameter(this._fragShader,a.COMPILE_STATUS))return console.error("Darn! An error occurred compiling the fragment shader:"+a.getShaderInfoLog(this._fragShader)),null;this._glProgram=a.createProgram(),a.attachShader(this._glProgram,this._vertShader),a.attachShader(this._glProgram,this._fragShader),a.linkProgram(this._glProgram),a.getProgramParameter(this._glProgram,a.LINK_STATUS)||console.error("Snap! Error linking shader program: "+a.getProgramInfoLog(this._glProgram)),this._loadAttributes(),this._loadUniforms()}return this},d.Shader.prototype._loadAttributes=function(){if(!this._loadedAttributes){this.attributes={};for(var a=this._renderer.GL,b=a.getProgramParameter(this._glProgram,a.ACTIVE_ATTRIBUTES),c=0;c1&&(g=g.substring(0,g.indexOf("[0]"))),f.name=g,f.type=e.type,f.type===a.SAMPLER_2D&&(f.samplerIndex=c,c++,this.samplers.push(f)),this.uniforms[g]=f}this._loadedUniforms=!0}},d.Shader.prototype.compile=function(){},d.Shader.prototype.bindShader=function(){this.init(),this._bound||(this.useProgram(),this._bound=!0,this.bindTextures(),this._loadAttributes(),this._loadUniforms(),this._renderer._setDefaultCamera(),this._setMatrixUniforms(),this===this._renderer.curStrokeShader&&this._setViewportUniform())},d.Shader.prototype.unbindShader=function(){return this._bound&&(this.unbindTextures(),this._bound=!1),this},d.Shader.prototype.bindTextures=function(){for(var a=this._renderer.GL,b=0;b1?c.uniform1fv(e,b):c.uniform1f(e,b);break;case c.FLOAT_MAT3:c.uniformMatrix3fv(e,!1,b);break;case c.FLOAT_MAT4:c.uniformMatrix4fv(e,!1,b);break;case c.FLOAT_VEC2:d.size>1?c.uniform2fv(e,b):c.uniform2f(e,b[0],b[1]);break;case c.FLOAT_VEC3:d.size>1?c.uniform3fv(e,b):c.uniform3f(e,b[0],b[1],b[2]);break;case c.FLOAT_VEC4:d.size>1?c.uniform4fv(e,b):c.uniform4f(e,b[0],b[1],b[2],b[3]);break;case c.SAMPLER_2D:c.activeTexture(c.TEXTURE0+d.samplerIndex),d.texture=this._renderer.getTexture(b),c.uniform1i(d.location,d.samplerIndex)}return this}},d.Shader.prototype.isLightShader=function(){return void 0!==this.uniforms.uUseLighting||void 0!==this.uniforms.uAmbientLightCount||void 0!==this.uniforms.uDirectionalLightCount||void 0!==this.uniforms.uPointLightCount||void 0!==this.uniforms.uAmbientColor||void 0!==this.uniforms.uDirectionalColor||void 0!==this.uniforms.uPointLightLocation||void 0!==this.uniforms.uPointLightColor||void 0!==this.uniforms.uLightingDirection||void 0!==this.uniforms.uSpecular},d.Shader.prototype.isTextureShader=function(){return this.samplerIndex>0},d.Shader.prototype.isColorShader=function(){return void 0!==this.attributes.aVertexColor||void 0!==this.uniforms.uMaterialColor},d.Shader.prototype.isTexLightShader=function(){return this.isLightShader()&&this.isTextureShader()},d.Shader.prototype.isStrokeShader=function(){return void 0!==this.uniforms.uStrokeWeight},d.Shader.prototype.enableAttrib=function(a,b,c,d,e,f){var g=this._renderer.GL;return a!==-1&&(g.enableVertexAttribArray(a),g.vertexAttribPointer(a,b,c,d,e,f)),this},b.exports=d.Shader},{"../core/core":55}],108:[function(a,b,c){var d=a("../core/core");d.Texture=function(a,b){this._renderer=a;var c=this._renderer.GL;this.src=b,this.glTex=void 0,this.glTarget=c.TEXTURE_2D,this.glFormat=c.RGBA,this.mipmaps=!1,this.glMinFilter=c.LINEAR,this.glMagFilter=c.LINEAR,this.glWrapS=c.CLAMP_TO_EDGE,this.glWrapT=c.CLAMP_TO_EDGE,this.isSrcMediaElement=void 0!==d.MediaElement&&b instanceof d.MediaElement,this._videoPrevUpdateTime=0,this.isSrcHTMLElement=void 0!==d.Element&&b instanceof d.Element,this.isSrcP5Image=b instanceof d.Image,this.isSrcP5Graphics=b instanceof d.Graphics;var e=this._getTextureDataFromSource();return this.height=e.width,this.width=e.height,this.init(e),this},d.Texture.prototype._getTextureDataFromSource=function(){var a;return this.isSrcP5Image?a=this.src.canvas:(this.isSrcMediaElement||this.isSrcP5Graphics||this.isSrcHTMLElement)&&(a=this.src.elt),a},d.Texture.prototype.init=function(a){var b=this._renderer.GL;if(this.glTex=b.createTexture(),this.bindTexture(),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,this.glMagFilter),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,this.glMinFilter),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,this.glWrapS),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,this.glWrapT),0===this.width||0===this.height||this.isSrcMediaElement&&!this.src.loadedmetadata){var c=new Uint8Array([1,1,1,1]);b.texImage2D(this.glTarget,0,b.RGBA,1,1,0,this.glFormat,b.UNSIGNED_BYTE,c)}else b.texImage2D(this.glTarget,0,this.glFormat,this.glFormat,b.UNSIGNED_BYTE,a)},d.Texture.prototype.update=function(){var a=this.src;if(0!==a.width&&0!==a.height){var b=this._getTextureDataFromSource(),c=this._renderer.GL;if(b.width!==this.width||b.height!==this.height)this.width=b.width,this.height=b.height,this.bindTexture(),c.texImage2D(this.glTarget,0,this.glFormat,this.glFormat,c.UNSIGNED_BYTE,b),this.isSrcP5Image?a.setModified(!1):(this.isSrcMediaElement||this.isSrcHTMLElement)&&a.setModified(!0);else if(this.isSrcP5Image)a.isModified()&&(this.bindTexture(),c.texImage2D(this.glTarget,0,this.glFormat,this.glFormat,c.UNSIGNED_BYTE,b),a.setModified(!1));else if(this.isSrcMediaElement){var d=!1;a.isModified()?(d=!0,a.setModified(!1)):a.loadedmetadata&&this._videoPrevUpdateTime!==a.time()&&(this._videoPrevUpdateTime=a.time(),d=!0),d&&(this.bindTexture(),c.texImage2D(this.glTarget,0,this.glFormat,this.glFormat,c.UNSIGNED_BYTE,b))}else c.texImage2D(this.glTarget,0,this.glFormat,this.glFormat,c.UNSIGNED_BYTE,b)}},d.Texture.prototype.bindTexture=function(){return this._renderer.GL.bindTexture(this.glTarget,this.glTex),this},d.Texture.prototype.unbindTexture=function(){this._renderer.GL.bindTexture(this.glTarget,null)},b.exports=d.Texture},{"../core/core":55}],109:[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;ip5.sound extends p5 with Web Audio functionality including audio input, + * playback, analysis and synthesis. + *

+ *
    + *
  • p5.SoundFile: Load and play sound files.
  • + *
  • p5.Amplitude: Get the current volume of a sound.
  • + *
  • p5.AudioIn: Get sound from an input source, typically + * a computer microphone.
  • + *
  • p5.FFT: Analyze the frequency of sound. Returns + * results from the frequency spectrum or time domain (waveform).
  • + *
  • p5.Oscillator: Generate Sine, + * Triangle, Square and Sawtooth waveforms. Base class of + *
  • p5.Noise and p5.Pulse. + *
  • + *
  • + * p5.MonoSynth and p5.PolySynth: Play musical notes + *
  • + *
  • p5.Envelope: An Envelope is a series + * of fades over time. Often used to control an object's + * output gain level as an "ADSR Envelope" (Attack, Decay, + * Sustain, Release). Can also modulate other parameters.
  • + *
  • p5.Delay: A delay effect with + * parameters for feedback, delayTime, and lowpass filter.
  • + *
  • p5.Filter: Filter the frequency range of a + * sound. + *
  • + *
  • p5.Reverb: Add reverb to a sound by specifying + * duration and decay.
  • + *
  • p5.Convolver: Extends + * p5.Reverb to simulate the sound of real + * physical spaces through convolution.
  • + *
  • p5.SoundRecorder: Record sound for playback + * / save the .wav file. + *
  • p5.SoundLoop, p5.Phrase, p5.Part and + * p5.Score: Compose musical sequences. + *
  • + *
  • userStartAudio: Enable audio in a + * browser- and user-friendly way. + *

    p5.sound is on GitHub. + * Download the latest version + * here.

    + * + * @module p5.sound + * @submodule p5.sound + * @for p5.sound + * @main + */ + +/** + * p5.sound + * https://p5js.org/reference/#/libraries/p5.sound + * + * From the Processing Foundation and contributors + * https://github.com/processing/p5.js-sound/graphs/contributors + * + * MIT License (MIT) + * https://github.com/processing/p5.js-sound/blob/master/LICENSE + * + * Some of the many audio libraries & resources that inspire p5.sound: + * - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js + * - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/ + * - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0 + * - wavesurfer.js https://github.com/katspaugh/wavesurfer.js + * - Web Audio Components by Jordan Santell https://github.com/web-audio-components + * - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound + * + * Web Audio API: http://w3.org/TR/webaudio/ + */ + + (function(modules) { + var installedModules = {}; + function __webpack_require__(moduleId) { + if(installedModules[moduleId]) { + return installedModules[moduleId].exports; + } + var module = installedModules[moduleId] = { + i: moduleId, + l: false, + exports: {} + }; + modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + module.l = true; + return module.exports; + } + __webpack_require__.m = modules; + __webpack_require__.c = installedModules; + __webpack_require__.d = function(exports, name, getter) { + if(!__webpack_require__.o(exports, name)) { + Object.defineProperty(exports, name, { enumerable: true, get: getter }); + } + }; + __webpack_require__.r = function(exports) { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); + }; + __webpack_require__.t = function(value, mode) { + if(mode & 1) value = __webpack_require__(value); + if(mode & 8) return value; + if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; + var ns = Object.create(null); + __webpack_require__.r(ns); + Object.defineProperty(ns, 'default', { enumerable: true, value: value }); + if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); + return ns; + }; + __webpack_require__.n = function(module) { + var getter = module && module.__esModule ? + function getDefault() { return module['default']; } : + function getModuleExports() { return module; }; + __webpack_require__.d(getter, 'a', getter); + return getter; + }; + __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + __webpack_require__.p = ""; + return __webpack_require__(__webpack_require__.s = 40); + }) + ([ + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = (function(){"use strict";function a(t,e){this.isUndef(t)||1===t?this.input=this.context.createGain():1Returns the Audio Context for this sketch. Useful for users + * who would like to dig deeper into the Web Audio API + * .

    + * + *

    Some browsers require users to startAudioContext + * with a user gesture, such as touchStarted in the example below.

    + * + * @for p5 + * @method getAudioContext + * @return {Object} AudioContext for this sketch + * @example + *
    + * function draw() { + * background(255); + * textAlign(CENTER); + * + * if (getAudioContext().state !== 'running') { + * text('click to start audio', width/2, height/2); + * } else { + * text('audio is enabled', width/2, height/2); + * } + * } + * + * function touchStarted() { + * if (getAudioContext().state !== 'running') { + * getAudioContext().resume(); + * } + * var synth = new p5.MonoSynth(); + * synth.play('A4', 0.5, 0, 0.2); + * } + * + *
    + */ + +function getAudioContext() { + return audiocontext; +} +/** + *

    It is not only a good practice to give users control over starting + * audio. This policy is enforced by many web browsers, including iOS and + * Google Chrome, which create the Web Audio API's + * Audio Context + * in a suspended state.

    + * + *

    In these browser-specific policies, sound will not play until a user + * interaction event (i.e. mousePressed()) explicitly resumes + * the AudioContext, or starts an audio node. This can be accomplished by + * calling start() on a p5.Oscillator, + * play() on a p5.SoundFile, or simply + * userStartAudio().

    + * + *

    userStartAudio() starts the AudioContext on a user + * gesture. The default behavior will enable audio on any + * mouseUp or touchEnd event. It can also be placed in a specific + * interaction function, such as mousePressed() as in the + * example below. This method utilizes + * StartAudioContext + * , a library by Yotam Mann (MIT Licence, 2016).

    + * @param {Element|Array} [element(s)] This argument can be an Element, + * Selector String, NodeList, p5.Element, + * jQuery Element, or an Array of any of those. + * @param {Function} [callback] Callback to invoke when the AudioContext + * has started + * @return {Promise} Returns a Promise that resolves when + * the AudioContext state is 'running' + * @method userStartAudio + * @for p5 + * @example + *
    + * function setup() { + * // mimics the autoplay policy + * getAudioContext().suspend(); + * + * let mySynth = new p5.MonoSynth(); + * + * // This won't play until the context has resumed + * mySynth.play('A6'); + * } + * function draw() { + * background(220); + * textAlign(CENTER, CENTER); + * text(getAudioContext().state, width/2, height/2); + * } + * function mousePressed() { + * userStartAudio(); + * } + *
    + */ + +function userStartAudio(elements, callback) { + var elt = elements; + + if (elements instanceof p5.Element) { + elt = elements.elt; + } else if (elements instanceof Array && elements[0] instanceof p5.Element) { + elt = elements.map(function (e) { + return e.elt; + }); + } + + return startaudiocontext__WEBPACK_IMPORTED_MODULE_0___default()(audiocontext, elt, callback); +} + __webpack_exports__["a"] = (audiocontext); +}.call(this, __webpack_require__(26))) + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0),__webpack_require__(2),__webpack_require__(10)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(i){"use strict";return i.Add=function(t){this.createInsOuts(2,0),this._sum=this.input[0]=this.input[1]=this.output=new i.Gain,this._param=this.input[1]=new i.Signal(t),this._param.connect(this._sum)},i.extend(i.Add,i.Signal),i.Add.prototype.dispose=function(){return i.prototype.dispose.call(this),this._sum.dispose(),this._sum=null,this._param.dispose(),this._param=null,this},i.Add}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + }), + (function(module, exports) { + +module.exports = { + recorderProcessor: 'recorder-processor', + soundFileProcessor: 'sound-file-processor', + amplitudeProcessor: 'amplitude-processor' +}; + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0),__webpack_require__(15)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(e){"use strict";return e.WaveShaper=function(e,t){this._shaper=this.input=this.output=this.context.createWaveShaper(),this._curve=null,Array.isArray(e)?this.curve=e:isFinite(e)||this.isUndef(e)?this._curve=new Float32Array(this.defaultArg(e,1024)):this.isFunction(e)&&(this._curve=new Float32Array(this.defaultArg(t,1024)),this.setMap(e))},e.extend(e.WaveShaper,e.SignalBase),e.WaveShaper.prototype.setMap=function(e){for(var t=0,r=this._curve.length;te)this.cancelScheduledValues(e),this.linearRampToValueAtTime(t,e);else{var n=this._searchAfter(e);n&&(this.cancelScheduledValues(e),n.type===o.TimelineSignal.Type.Linear?this.linearRampToValueAtTime(t,e):n.type===o.TimelineSignal.Type.Exponential&&this.exponentialRampToValueAtTime(t,e)),this.setValueAtTime(t,e)}return this},o.TimelineSignal.prototype.linearRampToValueBetween=function(e,t,i){return this.setRampPoint(t),this.linearRampToValueAtTime(e,i),this},o.TimelineSignal.prototype.exponentialRampToValueBetween=function(e,t,i){return this.setRampPoint(t),this.exponentialRampToValueAtTime(e,i),this},o.TimelineSignal.prototype._searchBefore=function(e){return this._events.get(e)},o.TimelineSignal.prototype._searchAfter=function(e){return this._events.getAfter(e)},o.TimelineSignal.prototype.getValueAtTime=function(e){e=this.toSeconds(e);var t=this._searchAfter(e),i=this._searchBefore(e),n=this._initial;if(null===i)n=this._initial;else if(i.type===o.TimelineSignal.Type.Target){var a,l=this._events.getBefore(i.time);a=null===l?this._initial:l.value,n=this._exponentialApproach(i.time,a,i.value,i.constant,e)}else n=i.type===o.TimelineSignal.Type.Curve?this._curveInterpolate(i.time,i.value,i.duration,e):null===t?i.value:t.type===o.TimelineSignal.Type.Linear?this._linearInterpolate(i.time,i.value,t.time,t.value,e):t.type===o.TimelineSignal.Type.Exponential?this._exponentialInterpolate(i.time,i.value,t.time,t.value,e):i.value;return n},o.TimelineSignal.prototype.connect=o.SignalBase.prototype.connect,o.TimelineSignal.prototype._exponentialApproach=function(e,t,i,n,a){return i+(t-i)*Math.exp(-(a-e)/n)},o.TimelineSignal.prototype._linearInterpolate=function(e,t,i,n,a){return t+(a-e)/(i-e)*(n-t)},o.TimelineSignal.prototype._exponentialInterpolate=function(e,t,i,n,a){return(t=Math.max(this._minOutput,t))*Math.pow(n/t,(a-e)/(i-e))},o.TimelineSignal.prototype._curveInterpolate=function(e,t,i,n){var a=t.length;if(e+i<=n)return t[a-1];if(n<=e)return t[0];var l=(n-e)/i,s=Math.floor((a-1)*l),r=Math.ceil((a-1)*l),o=t[s],p=t[r];return r===s?o:this._linearInterpolate(s,o,r,p,l*(a-1))},o.TimelineSignal.prototype.dispose=function(){o.Signal.prototype.dispose.call(this),o.Param.prototype.dispose.call(this),this._events.dispose(),this._events=null},o.TimelineSignal}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0),__webpack_require__(4),__webpack_require__(1),__webpack_require__(2)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(i){"use strict";return i.Scale=function(t,e){this._outputMin=this.defaultArg(t,0),this._outputMax=this.defaultArg(e,1),this._scale=this.input=new i.Multiply(1),this._add=this.output=new i.Add(0),this._scale.connect(this._add),this._setRange()},i.extend(i.Scale,i.SignalBase),Object.defineProperty(i.Scale.prototype,"min",{get:function(){return this._outputMin},set:function(t){this._outputMin=t,this._setRange()}}),Object.defineProperty(i.Scale.prototype,"max",{get:function(){return this._outputMax},set:function(t){this._outputMax=t,this._setRange()}}),i.Scale.prototype._setRange=function(){this._add.value=this._outputMin,this._scale.value=this._outputMax-this._outputMin},i.Scale.prototype.dispose=function(){return i.prototype.dispose.call(this),this._add.dispose(),this._add=null,this._scale.dispose(),this._scale=null,this},i.Scale}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0),__webpack_require__(16),__webpack_require__(30),__webpack_require__(31),__webpack_require__(12)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(t){return t.Type={Default:"number",Time:"time",Frequency:"frequency",TransportTime:"transportTime",Ticks:"ticks",NormalRange:"normalRange",AudioRange:"audioRange",Decibels:"db",Interval:"interval",BPM:"bpm",Positive:"positive",Cents:"cents",Degrees:"degrees",MIDI:"midi",BarsBeatsSixteenths:"barsBeatsSixteenths",Samples:"samples",Hertz:"hertz",Note:"note",Milliseconds:"milliseconds",Seconds:"seconds",Notation:"notation"},t.prototype.toSeconds=function(e){return this.isNumber(e)?e:this.isUndef(e)?this.now():this.isString(e)?new t.Time(e).toSeconds():e instanceof t.TimeBase?e.toSeconds():void 0},t.prototype.toFrequency=function(e){return this.isNumber(e)?e:this.isString(e)||this.isUndef(e)?new t.Frequency(e).valueOf():e instanceof t.TimeBase?e.toFrequency():void 0},t.prototype.toTicks=function(e){return this.isNumber(e)||this.isString(e)?new t.TransportTime(e).toTicks():this.isUndef(e)?t.Transport.ticks:e instanceof t.TimeBase?e.toTicks():void 0},t}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0),__webpack_require__(18),__webpack_require__(9)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(i){"use strict";return window.GainNode&&!AudioContext.prototype.createGain&&(AudioContext.prototype.createGain=AudioContext.prototype.createGainNode),i.Gain=function(){var t=this.optionsObject(arguments,["gain","units"],i.Gain.defaults);this.input=this.output=this._gainNode=this.context.createGain(),this.gain=new i.Param({param:this._gainNode.gain,units:t.units,value:t.gain,convert:t.convert}),this._readOnly("gain")},i.extend(i.Gain),i.Gain.defaults={gain:1,convert:!0},i.Gain.prototype.dispose=function(){i.Param.prototype.dispose.call(this),this._gainNode.disconnect(),this._gainNode=null,this._writable("gain"),this.gain.dispose(),this.gain=null},i.prototype.createInsOuts=function(t,n){1===t?this.input=new i.Gain:1this._nextTick&&this._state;){var e=this._state.getValueAtTime(this._nextTick);if(e!==this._lastState){this._lastState=e;var i=this._state.get(this._nextTick);e===o.State.Started?(this._nextTick=i.time,this.isUndef(i.offset)||(this.ticks=i.offset),this.emit("start",i.time,this.ticks)):e===o.State.Stopped?(this.ticks=0,this.emit("stop",i.time)):e===o.State.Paused&&this.emit("pause",i.time)}var s=this._nextTick;this.frequency&&(this._nextTick+=1/this.frequency.getValueAtTime(this._nextTick),e===o.State.Started&&(this.callback(s),this.ticks++))}},o.Clock.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)},o.Clock.prototype.dispose=function(){o.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},o.Clock}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0),__webpack_require__(14)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(o){function t(e,t,n){if(e.input)Array.isArray(e.input)?(o.prototype.isUndef(n)&&(n=0),this.connect(e.input[n])):this.connect(e.input,t,n);else try{e instanceof AudioNode?i.call(this,e,t,n):i.call(this,e,t)}catch(t){throw new Error("error connecting to node: "+e+"\n"+t)}}var i,r;return!window.hasOwnProperty("AudioContext")&&window.hasOwnProperty("webkitAudioContext")&&(window.AudioContext=window.webkitAudioContext),o.Context=function(t){for(var e in o.Emitter.call(this),t=t||new window.AudioContext,this._context=t,this._context)this._defineProperty(this._context,e);this._latencyHint="interactive",this._lookAhead=.1,this._updateInterval=this._lookAhead/3,this._computedUpdateInterval=0,this._worker=this._createWorker(),this._constants={}},o.extend(o.Context,o.Emitter),o.Emitter.mixin(o.Context),o.Context.prototype._defineProperty=function(e,n){this.isUndef(this[n])&&Object.defineProperty(this,n,{get:function(){return"function"==typeof e[n]?e[n].bind(e):e[n]},set:function(t){e[n]=t}})},o.Context.prototype.now=function(){return this._context.currentTime},o.Context.prototype._createWorker=function(){window.URL=window.URL||window.webkitURL;var t=new Blob(["var timeoutTime = "+(1e3*this._updateInterval).toFixed(1)+";self.onmessage = function(msg){\ttimeoutTime = parseInt(msg.data);};function tick(){\tsetTimeout(tick, timeoutTime);\tself.postMessage('tick');}tick();"]),e=URL.createObjectURL(t),n=new Worker(e);return n.addEventListener("message",function(){this.emit("tick")}.bind(this)),n.addEventListener("message",function(){var t=this.now();if(this.isNumber(this._lastUpdate)){var e=t-this._lastUpdate;this._computedUpdateInterval=Math.max(e,.97*this._computedUpdateInterval)}this._lastUpdate=t}.bind(this)),n},o.Context.prototype.getConstant=function(t){if(this._constants[t])return this._constants[t];for(var e=this._context.createBuffer(1,128,this._context.sampleRate),n=e.getChannelData(0),o=0;othis.memory){var t=this.length-this.memory;this._timeline.splice(0,t)}return this},i.Timeline.prototype.remove=function(e){if(this._iterating)this._toRemove.push(e);else{var i=this._timeline.indexOf(e);-1!==i&&this._timeline.splice(i,1)}return this},i.Timeline.prototype.get=function(e){var i=this._search(e);return-1!==i?this._timeline[i]:null},i.Timeline.prototype.peek=function(){return this._timeline[0]},i.Timeline.prototype.shift=function(){return this._timeline.shift()},i.Timeline.prototype.getAfter=function(e){var i=this._search(e);return i+1=e&&(this._timeline=[]);return this},i.Timeline.prototype.cancelBefore=function(e){if(this._timeline.length){var i=this._search(e);0<=i&&(this._timeline=this._timeline.slice(i+1))}return this},i.Timeline.prototype._search=function(e){var i=0,t=this._timeline.length,n=t;if(0e)return r;s.time>e?n=r:s.time=e;)t--;return this._iterate(i,t+1),this},i.Timeline.prototype.forEachAtTime=function(i,t){var e=this._search(i);return-1!==e&&this._iterate(function(e){e.time===i&&t(e)},0,e),this},i.Timeline.prototype.dispose=function(){i.prototype.dispose.call(this),this._timeline=null,this._toRemove=null},i.Timeline}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0),__webpack_require__(1),__webpack_require__(2)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(t){"use strict";return t.Negate=function(){this._multiply=this.input=this.output=new t.Multiply(-1)},t.extend(t.Negate,t.SignalBase),t.Negate.prototype.dispose=function(){return t.prototype.dispose.call(this),this._multiply.dispose(),this._multiply=null,this},t.Negate}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0),__webpack_require__(2),__webpack_require__(1),__webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(e){"use strict";return e.GreaterThanZero=function(){this._thresh=this.output=new e.WaveShaper(function(e){return e<=0?0:1},127),this._scale=this.input=new e.Multiply(1e4),this._scale.connect(this._thresh)},e.extend(e.GreaterThanZero,e.SignalBase),e.GreaterThanZero.prototype.dispose=function(){return e.prototype.dispose.call(this),this._scale.dispose(),this._scale=null,this._thresh.dispose(),this._thresh=null,this},e.GreaterThanZero}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!function(e,t){ true?!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (t), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)):undefined}(this,function(){var r=function(e,t){this._dragged=!1,this._element=e,this._bindedMove=this._moved.bind(this),this._bindedEnd=this._ended.bind(this,t),e.addEventListener("touchstart",this._bindedEnd),e.addEventListener("touchmove",this._bindedMove),e.addEventListener("touchend",this._bindedEnd),e.addEventListener("mouseup",this._bindedEnd)};function o(e){return"running"===e.state}return r.prototype._moved=function(e){this._dragged=!0},r.prototype._ended=function(e){this._dragged||function(e){var t=e.createBuffer(1,1,e.sampleRate),n=e.createBufferSource();n.buffer=t,n.connect(e.destination),n.start(0),e.resume&&e.resume()}(e),this._dragged=!1},r.prototype.dispose=function(){this._element.removeEventListener("touchstart",this._bindedEnd),this._element.removeEventListener("touchmove",this._bindedMove),this._element.removeEventListener("touchend",this._bindedEnd),this._element.removeEventListener("mouseup",this._bindedEnd),this._bindedMove=null,this._bindedEnd=null,this._element=null},function(t,e,n){var i=new Promise(function(e){!function(t,n){o(t)?n():function e(){o(t)?n():(requestAnimationFrame(e),t.resume&&t.resume())}()}(t,e)}),d=[];return function e(t,n,i){if(Array.isArray(t)||NodeList&&t instanceof NodeList)for(var d=0;d= this._length) {\n this._writeIndex = 0;\n } // For excessive frames, the buffer will be overwritten.\n\n\n this._framesAvailable += sourceLength;\n\n if (this._framesAvailable > this._length) {\n this._framesAvailable = this._length;\n }\n }\n /**\n * Pull data out of buffer and fill a given sequence of Float32Arrays.\n *\n * @param {array} arraySequence An array of Float32Arrays.\n */\n\n }, {\n key: \"pull\",\n value: function pull(arraySequence) {\n // The channel count of arraySequence and the length of each channel must\n // match with this buffer obejct.\n // If the FIFO is completely empty, do nothing.\n if (this._framesAvailable === 0) {\n return;\n }\n\n var destinationLength = arraySequence[0].length; // Transfer data from the internal buffer to the |arraySequence| storage.\n\n for (var i = 0; i < destinationLength; ++i) {\n var readIndex = (this._readIndex + i) % this._length;\n\n for (var channel = 0; channel < this._channelCount; ++channel) {\n arraySequence[channel][i] = this._channelData[channel][readIndex];\n }\n }\n\n this._readIndex += destinationLength;\n\n if (this._readIndex >= this._length) {\n this._readIndex = 0;\n }\n\n this._framesAvailable -= destinationLength;\n\n if (this._framesAvailable < 0) {\n this._framesAvailable = 0;\n }\n }\n }, {\n key: \"framesAvailable\",\n get: function get() {\n return this._framesAvailable;\n }\n }]);\n\n return RingBuffer;\n }()\n}[\"default\"];\n\nvar RecorderProcessor =\n/*#__PURE__*/\nfunction (_AudioWorkletProcesso) {\n _inherits(RecorderProcessor, _AudioWorkletProcesso);\n\n function RecorderProcessor(options) {\n var _this;\n\n _classCallCheck(this, RecorderProcessor);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(RecorderProcessor).call(this));\n var processorOptions = options.processorOptions || {};\n _this.numOutputChannels = options.outputChannelCount || 2;\n _this.numInputChannels = processorOptions.numInputChannels || 2;\n _this.bufferSize = processorOptions.bufferSize || 1024;\n _this.recording = false;\n\n _this.clear();\n\n _this.port.onmessage = function (event) {\n var data = event.data;\n\n if (data.name === 'start') {\n _this.record(data.duration);\n } else if (data.name === 'stop') {\n _this.stop();\n }\n };\n\n return _this;\n }\n\n _createClass(RecorderProcessor, [{\n key: \"process\",\n value: function process(inputs) {\n if (!this.recording) {\n return true;\n } else if (this.sampleLimit && this.recordedSamples >= this.sampleLimit) {\n this.stop();\n return true;\n }\n\n var input = inputs[0];\n this.inputRingBuffer.push(input);\n\n if (this.inputRingBuffer.framesAvailable >= this.bufferSize) {\n this.inputRingBuffer.pull(this.inputRingBufferArraySequence);\n\n for (var channel = 0; channel < this.numOutputChannels; ++channel) {\n var inputChannelCopy = this.inputRingBufferArraySequence[channel].slice();\n\n if (channel === 0) {\n this.leftBuffers.push(inputChannelCopy);\n\n if (this.numInputChannels === 1) {\n this.rightBuffers.push(inputChannelCopy);\n }\n } else if (channel === 1 && this.numInputChannels > 1) {\n this.rightBuffers.push(inputChannelCopy);\n }\n }\n\n this.recordedSamples += this.bufferSize;\n }\n\n return true;\n }\n }, {\n key: \"record\",\n value: function record(duration) {\n if (duration) {\n this.sampleLimit = Math.round(duration * sampleRate);\n }\n\n this.recording = true;\n }\n }, {\n key: \"stop\",\n value: function stop() {\n this.recording = false;\n var buffers = this.getBuffers();\n var leftBuffer = buffers[0].buffer;\n var rightBuffer = buffers[1].buffer;\n this.port.postMessage({\n name: 'buffers',\n leftBuffer: leftBuffer,\n rightBuffer: rightBuffer\n }, [leftBuffer, rightBuffer]);\n this.clear();\n }\n }, {\n key: \"getBuffers\",\n value: function getBuffers() {\n var buffers = [];\n buffers.push(this.mergeBuffers(this.leftBuffers));\n buffers.push(this.mergeBuffers(this.rightBuffers));\n return buffers;\n }\n }, {\n key: \"mergeBuffers\",\n value: function mergeBuffers(channelBuffer) {\n var result = new Float32Array(this.recordedSamples);\n var offset = 0;\n var lng = channelBuffer.length;\n\n for (var i = 0; i < lng; i++) {\n var buffer = channelBuffer[i];\n result.set(buffer, offset);\n offset += buffer.length;\n }\n\n return result;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n var _this2 = this;\n\n this.leftBuffers = [];\n this.rightBuffers = [];\n this.inputRingBuffer = new RingBuffer(this.bufferSize, this.numInputChannels);\n this.inputRingBufferArraySequence = new Array(this.numInputChannels).fill(null).map(function () {\n return new Float32Array(_this2.bufferSize);\n });\n this.recordedSamples = 0;\n this.sampleLimit = null;\n }\n }]);\n\n return RecorderProcessor;\n}(_wrapNativeSuper(AudioWorkletProcessor));\n\nregisterProcessor(processorNames.recorderProcessor, RecorderProcessor);"); + + }), + (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + __webpack_exports__["default"] = ("function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== \"function\") { throw new TypeError(\"Super expression must either be null or a function\"); } if (typeof _cache !== \"undefined\") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }\n\nfunction isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\n\nfunction _isNativeFunction(fn) { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n// import dependencies via preval.require so that they're available as values at compile time\nvar processorNames = {\n \"recorderProcessor\": \"recorder-processor\",\n \"soundFileProcessor\": \"sound-file-processor\",\n \"amplitudeProcessor\": \"amplitude-processor\"\n};\nvar RingBuffer = {\n \"default\":\n /*#__PURE__*/\n function () {\n /**\n * @constructor\n * @param {number} length Buffer length in frames.\n * @param {number} channelCount Buffer channel count.\n */\n function RingBuffer(length, channelCount) {\n _classCallCheck(this, RingBuffer);\n\n this._readIndex = 0;\n this._writeIndex = 0;\n this._framesAvailable = 0;\n this._channelCount = channelCount;\n this._length = length;\n this._channelData = [];\n\n for (var i = 0; i < this._channelCount; ++i) {\n this._channelData[i] = new Float32Array(length);\n }\n }\n /**\n * Getter for Available frames in buffer.\n *\n * @return {number} Available frames in buffer.\n */\n\n\n _createClass(RingBuffer, [{\n key: \"push\",\n\n /**\n * Push a sequence of Float32Arrays to buffer.\n *\n * @param {array} arraySequence A sequence of Float32Arrays.\n */\n value: function push(arraySequence) {\n // The channel count of arraySequence and the length of each channel must\n // match with this buffer obejct.\n // Transfer data from the |arraySequence| storage to the internal buffer.\n var sourceLength = arraySequence[0] ? arraySequence[0].length : 0;\n\n for (var i = 0; i < sourceLength; ++i) {\n var writeIndex = (this._writeIndex + i) % this._length;\n\n for (var channel = 0; channel < this._channelCount; ++channel) {\n this._channelData[channel][writeIndex] = arraySequence[channel][i];\n }\n }\n\n this._writeIndex += sourceLength;\n\n if (this._writeIndex >= this._length) {\n this._writeIndex = 0;\n } // For excessive frames, the buffer will be overwritten.\n\n\n this._framesAvailable += sourceLength;\n\n if (this._framesAvailable > this._length) {\n this._framesAvailable = this._length;\n }\n }\n /**\n * Pull data out of buffer and fill a given sequence of Float32Arrays.\n *\n * @param {array} arraySequence An array of Float32Arrays.\n */\n\n }, {\n key: \"pull\",\n value: function pull(arraySequence) {\n // The channel count of arraySequence and the length of each channel must\n // match with this buffer obejct.\n // If the FIFO is completely empty, do nothing.\n if (this._framesAvailable === 0) {\n return;\n }\n\n var destinationLength = arraySequence[0].length; // Transfer data from the internal buffer to the |arraySequence| storage.\n\n for (var i = 0; i < destinationLength; ++i) {\n var readIndex = (this._readIndex + i) % this._length;\n\n for (var channel = 0; channel < this._channelCount; ++channel) {\n arraySequence[channel][i] = this._channelData[channel][readIndex];\n }\n }\n\n this._readIndex += destinationLength;\n\n if (this._readIndex >= this._length) {\n this._readIndex = 0;\n }\n\n this._framesAvailable -= destinationLength;\n\n if (this._framesAvailable < 0) {\n this._framesAvailable = 0;\n }\n }\n }, {\n key: \"framesAvailable\",\n get: function get() {\n return this._framesAvailable;\n }\n }]);\n\n return RingBuffer;\n }()\n}[\"default\"];\n\nvar SoundFileProcessor =\n/*#__PURE__*/\nfunction (_AudioWorkletProcesso) {\n _inherits(SoundFileProcessor, _AudioWorkletProcesso);\n\n function SoundFileProcessor(options) {\n var _this;\n\n _classCallCheck(this, SoundFileProcessor);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(SoundFileProcessor).call(this));\n var processorOptions = options.processorOptions || {};\n _this.bufferSize = processorOptions.bufferSize || 256;\n _this.inputRingBuffer = new RingBuffer(_this.bufferSize, 1);\n _this.inputRingBufferArraySequence = [new Float32Array(_this.bufferSize)];\n return _this;\n }\n\n _createClass(SoundFileProcessor, [{\n key: \"process\",\n value: function process(inputs) {\n var input = inputs[0]; // we only care about the first input channel, because that contains the position data\n\n this.inputRingBuffer.push([input[0]]);\n\n if (this.inputRingBuffer.framesAvailable >= this.bufferSize) {\n this.inputRingBuffer.pull(this.inputRingBufferArraySequence);\n var inputChannel = this.inputRingBufferArraySequence[0];\n var position = inputChannel[inputChannel.length - 1] || 0;\n this.port.postMessage({\n name: 'position',\n position: position\n });\n }\n\n return true;\n }\n }]);\n\n return SoundFileProcessor;\n}(_wrapNativeSuper(AudioWorkletProcessor));\n\nregisterProcessor(processorNames.soundFileProcessor, SoundFileProcessor);"); + + }), + (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + __webpack_exports__["default"] = ("function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== \"function\") { throw new TypeError(\"Super expression must either be null or a function\"); } if (typeof _cache !== \"undefined\") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }\n\nfunction isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\n\nfunction _isNativeFunction(fn) { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n// import dependencies via preval.require so that they're available as values at compile time\nvar processorNames = {\n \"recorderProcessor\": \"recorder-processor\",\n \"soundFileProcessor\": \"sound-file-processor\",\n \"amplitudeProcessor\": \"amplitude-processor\"\n};\nvar RingBuffer = {\n \"default\":\n /*#__PURE__*/\n function () {\n /**\n * @constructor\n * @param {number} length Buffer length in frames.\n * @param {number} channelCount Buffer channel count.\n */\n function RingBuffer(length, channelCount) {\n _classCallCheck(this, RingBuffer);\n\n this._readIndex = 0;\n this._writeIndex = 0;\n this._framesAvailable = 0;\n this._channelCount = channelCount;\n this._length = length;\n this._channelData = [];\n\n for (var i = 0; i < this._channelCount; ++i) {\n this._channelData[i] = new Float32Array(length);\n }\n }\n /**\n * Getter for Available frames in buffer.\n *\n * @return {number} Available frames in buffer.\n */\n\n\n _createClass(RingBuffer, [{\n key: \"push\",\n\n /**\n * Push a sequence of Float32Arrays to buffer.\n *\n * @param {array} arraySequence A sequence of Float32Arrays.\n */\n value: function push(arraySequence) {\n // The channel count of arraySequence and the length of each channel must\n // match with this buffer obejct.\n // Transfer data from the |arraySequence| storage to the internal buffer.\n var sourceLength = arraySequence[0] ? arraySequence[0].length : 0;\n\n for (var i = 0; i < sourceLength; ++i) {\n var writeIndex = (this._writeIndex + i) % this._length;\n\n for (var channel = 0; channel < this._channelCount; ++channel) {\n this._channelData[channel][writeIndex] = arraySequence[channel][i];\n }\n }\n\n this._writeIndex += sourceLength;\n\n if (this._writeIndex >= this._length) {\n this._writeIndex = 0;\n } // For excessive frames, the buffer will be overwritten.\n\n\n this._framesAvailable += sourceLength;\n\n if (this._framesAvailable > this._length) {\n this._framesAvailable = this._length;\n }\n }\n /**\n * Pull data out of buffer and fill a given sequence of Float32Arrays.\n *\n * @param {array} arraySequence An array of Float32Arrays.\n */\n\n }, {\n key: \"pull\",\n value: function pull(arraySequence) {\n // The channel count of arraySequence and the length of each channel must\n // match with this buffer obejct.\n // If the FIFO is completely empty, do nothing.\n if (this._framesAvailable === 0) {\n return;\n }\n\n var destinationLength = arraySequence[0].length; // Transfer data from the internal buffer to the |arraySequence| storage.\n\n for (var i = 0; i < destinationLength; ++i) {\n var readIndex = (this._readIndex + i) % this._length;\n\n for (var channel = 0; channel < this._channelCount; ++channel) {\n arraySequence[channel][i] = this._channelData[channel][readIndex];\n }\n }\n\n this._readIndex += destinationLength;\n\n if (this._readIndex >= this._length) {\n this._readIndex = 0;\n }\n\n this._framesAvailable -= destinationLength;\n\n if (this._framesAvailable < 0) {\n this._framesAvailable = 0;\n }\n }\n }, {\n key: \"framesAvailable\",\n get: function get() {\n return this._framesAvailable;\n }\n }]);\n\n return RingBuffer;\n }()\n}[\"default\"];\n\nvar AmplitudeProcessor =\n/*#__PURE__*/\nfunction (_AudioWorkletProcesso) {\n _inherits(AmplitudeProcessor, _AudioWorkletProcesso);\n\n function AmplitudeProcessor(options) {\n var _this;\n\n _classCallCheck(this, AmplitudeProcessor);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(AmplitudeProcessor).call(this));\n var processorOptions = options.processorOptions || {};\n _this.numOutputChannels = options.outputChannelCount || 1;\n _this.numInputChannels = processorOptions.numInputChannels || 2;\n _this.normalize = processorOptions.normalize || false;\n _this.smoothing = processorOptions.smoothing || 0;\n _this.bufferSize = processorOptions.bufferSize || 2048;\n _this.inputRingBuffer = new RingBuffer(_this.bufferSize, _this.numInputChannels);\n _this.outputRingBuffer = new RingBuffer(_this.bufferSize, _this.numOutputChannels);\n _this.inputRingBufferArraySequence = new Array(_this.numInputChannels).fill(null).map(function () {\n return new Float32Array(_this.bufferSize);\n });\n _this.stereoVol = [0, 0];\n _this.stereoVolNorm = [0, 0];\n _this.volMax = 0.001;\n\n _this.port.onmessage = function (event) {\n var data = event.data;\n\n if (data.name === 'toggleNormalize') {\n _this.normalize = data.normalize;\n } else if (data.name === 'smoothing') {\n _this.smoothing = Math.max(0, Math.min(1, data.smoothing));\n }\n };\n\n return _this;\n } // TO DO make this stereo / dependent on # of audio channels\n\n\n _createClass(AmplitudeProcessor, [{\n key: \"process\",\n value: function process(inputs, outputs) {\n var input = inputs[0];\n var output = outputs[0];\n var smoothing = this.smoothing;\n this.inputRingBuffer.push(input);\n\n if (this.inputRingBuffer.framesAvailable >= this.bufferSize) {\n this.inputRingBuffer.pull(this.inputRingBufferArraySequence);\n\n for (var channel = 0; channel < this.numInputChannels; ++channel) {\n var inputBuffer = this.inputRingBufferArraySequence[channel];\n var bufLength = inputBuffer.length;\n var sum = 0;\n\n for (var i = 0; i < bufLength; i++) {\n var x = inputBuffer[i];\n\n if (this.normalize) {\n sum += Math.max(Math.min(x / this.volMax, 1), -1) * Math.max(Math.min(x / this.volMax, 1), -1);\n } else {\n sum += x * x;\n }\n } // ... then take the square root of the sum.\n\n\n var rms = Math.sqrt(sum / bufLength);\n this.stereoVol[channel] = Math.max(rms, this.stereoVol[channel] * smoothing);\n this.volMax = Math.max(this.stereoVol[channel], this.volMax);\n } // calculate stero normalized volume and add volume from all channels together\n\n\n var volSum = 0;\n\n for (var index = 0; index < this.stereoVol.length; index++) {\n this.stereoVolNorm[index] = Math.max(Math.min(this.stereoVol[index] / this.volMax, 1), 0);\n volSum += this.stereoVol[index];\n } // volume is average of channels\n\n\n var volume = volSum / this.stereoVol.length; // normalized value\n\n var volNorm = Math.max(Math.min(volume / this.volMax, 1), 0);\n this.port.postMessage({\n name: 'amplitude',\n volume: volume,\n volNorm: volNorm,\n stereoVol: this.stereoVol,\n stereoVolNorm: this.stereoVolNorm\n }); // pass input through to output\n\n this.outputRingBuffer.push(this.inputRingBufferArraySequence);\n } // pull 128 frames out of the ring buffer\n // if the ring buffer does not have enough frames, the output will be silent\n\n\n this.outputRingBuffer.pull(output);\n return true;\n }\n }]);\n\n return AmplitudeProcessor;\n}(_wrapNativeSuper(AudioWorkletProcessor));\n\nregisterProcessor(processorNames.amplitudeProcessor, AmplitudeProcessor);"); + + }), + (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0),__webpack_require__(17)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(o){o.Frequency=function(e,t){if(!(this instanceof o.Frequency))return new o.Frequency(e,t);o.TimeBase.call(this,e,t)},o.extend(o.Frequency,o.TimeBase),o.Frequency.prototype._primaryExpressions=Object.create(o.TimeBase.prototype._primaryExpressions),o.Frequency.prototype._primaryExpressions.midi={regexp:/^(\d+(?:\.\d+)?midi)/,method:function(e){return this.midiToFrequency(e)}},o.Frequency.prototype._primaryExpressions.note={regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method:function(e,t){var r=n[e.toLowerCase()]+12*(parseInt(t)+1);return this.midiToFrequency(r)}},o.Frequency.prototype._primaryExpressions.tr={regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(e,t,r){var n=1;return e&&"0"!==e&&(n*=this._beatsToUnits(this._timeSignature()*parseFloat(e))),t&&"0"!==t&&(n*=this._beatsToUnits(parseFloat(t))),r&&"0"!==r&&(n*=this._beatsToUnits(parseFloat(r)/4)),n}},o.Frequency.prototype.transpose=function(e){return this._expr=function(e,t){return e()*this.intervalToFrequencyRatio(t)}.bind(this,this._expr,e),this},o.Frequency.prototype.harmonize=function(e){return this._expr=function(e,t){for(var r=e(),n=[],o=0;oScale the output of all sound in this sketch

    + * Scaled between 0.0 (silence) and 1.0 (full volume). + * 1.0 is the maximum amplitude of a digital sound, so multiplying + * by greater than 1.0 may cause digital distortion. To + * fade, provide a rampTime parameter. For more + * complex fades, see the Envelope class. + * + * Alternately, you can pass in a signal source such as an + * oscillator to modulate the amplitude with an audio signal. + * + *

    How This Works: When you load the p5.sound module, it + * creates a single instance of p5sound. All sound objects in this + * module output to p5sound before reaching your computer's output. + * So if you change the amplitude of p5sound, it impacts all of the + * sound in this module.

    + * + *

    If no value is provided, returns a Web Audio API Gain Node

    + * + * @method masterVolume + * @param {Number|Object} volume Volume (amplitude) between 0.0 + * and 1.0 or modulating signal/oscillator + * @param {Number} [rampTime] Fade for t seconds + * @param {Number} [timeFromNow] Schedule this event to happen at + * t seconds in the future + */ + + +p5.prototype.masterVolume = function (vol) { + var rampTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var tFromNow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + if (typeof vol === 'number') { + var now = p5sound.audiocontext.currentTime; + var currentVol = p5sound.output.gain.value; + p5sound.output.gain.cancelScheduledValues(now + tFromNow); + p5sound.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); + p5sound.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); + } else if (vol) { + vol.connect(p5sound.output.gain); + } else { + return p5sound.output.gain; + } +}; +/** + * `p5.soundOut` is the p5.sound master output. It sends output to + * the destination of this window's web audio context. It contains + * Web Audio API nodes including a dyanmicsCompressor (.limiter), + * and Gain Nodes for .input and .output. + * + * @property {Object} soundOut + */ + + +p5.prototype.soundOut = p5.soundOut = p5sound; + +p5.soundOut._silentNode = p5sound.audiocontext.createGain(); +p5.soundOut._silentNode.gain.value = 0; + +p5.soundOut._silentNode.connect(p5sound.audiocontext.destination); + + var master = (p5sound); +var processorNames = __webpack_require__(5); +var processorNames_default = __webpack_require__.n(processorNames); + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + + +/** + * @for p5 + */ + +/** + * Returns a number representing the sample rate, in samples per second, + * of all sound objects in this audio context. It is determined by the + * sampling rate of your operating system's sound card, and it is not + * currently possile to change. + * It is often 44100, or twice the range of human hearing. + * + * @method sampleRate + * @return {Number} samplerate samples per second + */ + +function sampleRate() { + return master.audiocontext.sampleRate; +} +/** + * Returns the closest MIDI note value for + * a given frequency. + * + * @method freqToMidi + * @param {Number} frequency A freqeuncy, for example, the "A" + * above Middle C is 440Hz + * @return {Number} MIDI note value + */ + + +function freqToMidi(f) { + var mathlog2 = Math.log(f / 440) / Math.log(2); + var m = Math.round(12 * mathlog2) + 69; + return m; +} +/** + * Returns the frequency value of a MIDI note value. + * General MIDI treats notes as integers where middle C + * is 60, C# is 61, D is 62 etc. Useful for generating + * musical frequencies with oscillators. + * + * @method midiToFreq + * @param {Number} midiNote The number of a MIDI note + * @return {Number} Frequency value of the given MIDI note + * @example + *
    + * let midiNotes = [60, 64, 67, 72]; + * let noteIndex = 0; + * let midiVal, freq; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(startSound); + * osc = new p5.TriOsc(); + * env = new p5.Envelope(); + * } + * + * function draw() { + * background(220); + * text('tap to play', 10, 20); + * if (midiVal) { + * text('MIDI: ' + midiVal, 10, 40); + * text('Freq: ' + freq, 10, 60); + * } + * } + * + * function startSound() { + * // see also: userStartAudio(); + * osc.start(); + * + * midiVal = midiNotes[noteIndex % midiNotes.length]; + * freq = midiToFreq(midiVal); + * osc.freq(freq); + * env.ramp(osc, 0, 1.0, 0); + * + * noteIndex++; + * } + *
    + */ + + +function midiToFreq(m) { + return 440 * Math.pow(2, (m - 69) / 12.0); +} + + +function noteToFreq(note) { + if (typeof note !== 'string') { + return note; + } + + var wholeNotes = { + A: 21, + B: 23, + C: 24, + D: 26, + E: 28, + F: 29, + G: 31 + }; + var value = wholeNotes[note[0].toUpperCase()]; + var octave = ~~note.slice(-1); + value += 12 * (octave - 1); + + switch (note[1]) { + case '#': + value += 1; + break; + + case 'b': + value -= 1; + break; + + default: + break; + } + + return midiToFreq(value); +} +/** + * List the SoundFile formats that you will include. LoadSound + * will search your directory for these extensions, and will pick + * a format that is compatable with the client's web browser. + * Here is a free online file + * converter. + * + * @method soundFormats + * @param {String} [...formats] i.e. 'mp3', 'wav', 'ogg' + * @example + *
    + * function preload() { + * // set the global sound formats + * soundFormats('mp3', 'ogg'); + * + * // load either beatbox.mp3, or .ogg, depending on browser + * mySound = loadSound('assets/beatbox.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * background(220); + * text('sound loaded! tap to play', 10, 20, width - 20); + * cnv.mousePressed(function() { + * mySound.play(); + * }); + * } + *
    + */ + + +function soundFormats() { + master.extensions = []; + + for (var i = 0; i < arguments.length; i++) { + arguments[i] = arguments[i].toLowerCase(); + + if (['mp3', 'wav', 'ogg', 'm4a', 'aac'].indexOf(arguments[i]) > -1) { + master.extensions.push(arguments[i]); + } else { + throw arguments[i] + ' is not a valid sound format!'; + } + } +} + +function disposeSound() { + for (var i = 0; i < master.soundArray.length; i++) { + master.soundArray[i].dispose(); + } +} + +function _checkFileFormats(paths) { + var path; + + if (typeof paths === 'string') { + path = paths; + + var extTest = path.split('.').pop(); + + if (['mp3', 'wav', 'ogg', 'm4a', 'aac'].indexOf(extTest) > -1) { + if (!p5.prototype.isFileSupported(extTest)) { + var pathSplit = path.split('.'); + var pathCore = pathSplit[pathSplit.length - 1]; + + for (var _i = 0; _i < master.extensions.length; _i++) { + var _extension = master.extensions[_i]; + + var _supported = p5.prototype.isFileSupported(_extension); + + if (_supported) { + pathCore = ''; + + if (pathSplit.length === 2) { + pathCore += pathSplit[0]; + } + + for (var _i2 = 1; _i2 <= pathSplit.length - 2; _i2++) { + var p = pathSplit[_i2]; + pathCore += '.' + p; + } + + path = pathCore += '.'; + path = path += _extension; + break; + } + } + } + } + else { + for (var _i3 = 0; _i3 < master.extensions.length; _i3++) { + var _extension2 = master.extensions[_i3]; + + var _supported2 = p5.prototype.isFileSupported(_extension2); + + if (_supported2) { + path = path + '.' + _extension2; + break; + } + } + } + } + else if (_typeof(paths) === 'object') { + for (var i = 0; i < paths.length; i++) { + var extension = paths[i].split('.').pop(); + var supported = p5.prototype.isFileSupported(extension); + + if (supported) { + path = paths[i]; + break; + } + } + } + + return path; +} +/** + * Used by Osc and Envelope to chain signal math + */ + + +function _mathChain(o, math, thisChain, nextChain, type) { + for (var i in o.mathOps) { + if (o.mathOps[i] instanceof type) { + o.mathOps[i].dispose(); + thisChain = i; + + if (thisChain < o.mathOps.length - 1) { + nextChain = o.mathOps[i + 1]; + } + } + } + + o.mathOps[thisChain - 1].disconnect(); + o.mathOps[thisChain - 1].connect(math); + math.connect(nextChain); + o.mathOps[thisChain] = math; + return o; +} + + +function convertToWav(audioBuffer) { + var leftChannel, rightChannel; + leftChannel = audioBuffer.getChannelData(0); + + if (audioBuffer.numberOfChannels > 1) { + rightChannel = audioBuffer.getChannelData(1); + } else { + rightChannel = leftChannel; + } + + var interleaved = interleave(leftChannel, rightChannel); + + var buffer = new window.ArrayBuffer(44 + interleaved.length * 2); + var view = new window.DataView(buffer); + + writeUTFBytes(view, 0, 'RIFF'); + view.setUint32(4, 36 + interleaved.length * 2, true); + writeUTFBytes(view, 8, 'WAVE'); + + writeUTFBytes(view, 12, 'fmt '); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + + view.setUint16(22, 2, true); + view.setUint32(24, master.audiocontext.sampleRate, true); + view.setUint32(28, master.audiocontext.sampleRate * 4, true); + view.setUint16(32, 4, true); + view.setUint16(34, 16, true); + + writeUTFBytes(view, 36, 'data'); + view.setUint32(40, interleaved.length * 2, true); + + var lng = interleaved.length; + var index = 44; + var volume = 1; + + for (var i = 0; i < lng; i++) { + view.setInt16(index, interleaved[i] * (0x7fff * volume), true); + index += 2; + } + + return view; +} + + +function interleave(leftChannel, rightChannel) { + var length = leftChannel.length + rightChannel.length; + var result = new Float32Array(length); + var inputIndex = 0; + + for (var index = 0; index < length;) { + result[index++] = leftChannel[inputIndex]; + result[index++] = rightChannel[inputIndex]; + inputIndex++; + } + + return result; +} + +function writeUTFBytes(view, offset, string) { + var lng = string.length; + + for (var i = 0; i < lng; i++) { + view.setUint8(offset + i, string.charCodeAt(i)); + } +} + +function safeBufferSize(idealBufferSize) { + var bufferSize = idealBufferSize; + + var tempAudioWorkletNode = new AudioWorkletNode(master.audiocontext, processorNames_default.a.soundFileProcessor); + + if (tempAudioWorkletNode instanceof ScriptProcessorNode) { + bufferSize = tempAudioWorkletNode.bufferSize; + } + + tempAudioWorkletNode.disconnect(); + tempAudioWorkletNode = null; + return bufferSize; +} +/** + * Save a p5.SoundFile as a .wav file. The browser will prompt the user + * to download the file to their device. + * For uploading audio to a server, use + * `p5.SoundFile.saveBlob`. + * + * @for p5 + * @method saveSound + * @param {p5.SoundFile} soundFile p5.SoundFile that you wish to save + * @param {String} fileName name of the resulting .wav file. + */ + + +function saveSound(soundFile, fileName) { + var dataView = convertToWav(soundFile.buffer); + p5.prototype.writeFile([dataView], fileName, 'wav'); +} + + +var CustomError = function CustomError(name, errorTrace, failedPath) { + var err = new Error(); + var tempStack, splitStack; + err.name = name; + err.originalStack = err.stack + errorTrace; + tempStack = err.stack + errorTrace; + err.failedPath = failedPath; + + splitStack = tempStack.split('\n').filter(function (ln) { + return !ln.match(/(p5.|native code|globalInit)/g); + }); + err.stack = splitStack.join('\n'); + return err; +}; + + var errorHandler = (CustomError); + +var moduleSources = [__webpack_require__(27)["default"], __webpack_require__(28)["default"], __webpack_require__(29)["default"]]; +var audioWorklet_ac = master.audiocontext; + +function loadAudioWorkletModules() { + return Promise.all(moduleSources.map(function (moduleSrc) { + var blob = new Blob([moduleSrc], { + type: 'application/javascript' + }); + var objectURL = URL.createObjectURL(blob); + return audioWorklet_ac.audioWorklet.addModule(objectURL); + })); +} + +p5.prototype.registerMethod('init', function () { + if (!this.preload && !window.preload) { + this.preload = function () {}; + } + + + this._incrementPreload(); + + var onWorkletModulesLoad = function () { + this._decrementPreload(); + }.bind(this); + + loadAudioWorkletModules().then(onWorkletModulesLoad); +}); +function panner_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + + +var panner_ac = master.audiocontext; +var panner; + +if (typeof panner_ac.createStereoPanner !== 'undefined') { + var Panner = + function () { + function Panner(input, output) { + panner_classCallCheck(this, Panner); + + this.stereoPanner = this.input = panner_ac.createStereoPanner(); + input.connect(this.stereoPanner); + this.stereoPanner.connect(output); + } + + _createClass(Panner, [{ + key: "pan", + value: function pan(val, tFromNow) { + var time = tFromNow || 0; + var t = panner_ac.currentTime + time; + this.stereoPanner.pan.linearRampToValueAtTime(val, t); + } + + }, { + key: "inputChannels", + value: function inputChannels() {} + }, { + key: "connect", + value: function connect(obj) { + this.stereoPanner.connect(obj); + } + }, { + key: "disconnect", + value: function disconnect() { + if (this.stereoPanner) { + this.stereoPanner.disconnect(); + } + } + }]); + + return Panner; + }(); + + panner = Panner; +} else { + var _Panner = + function () { + function _Panner(input, output, numInputChannels) { + panner_classCallCheck(this, _Panner); + + this.input = panner_ac.createGain(); + input.connect(this.input); + this.left = panner_ac.createGain(); + this.right = panner_ac.createGain(); + this.left.channelInterpretation = 'discrete'; + this.right.channelInterpretation = 'discrete'; + + if (numInputChannels > 1) { + this.splitter = panner_ac.createChannelSplitter(2); + this.input.connect(this.splitter); + this.splitter.connect(this.left, 1); + this.splitter.connect(this.right, 0); + } else { + this.input.connect(this.left); + this.input.connect(this.right); + } + + this.output = panner_ac.createChannelMerger(2); + this.left.connect(this.output, 0, 1); + this.right.connect(this.output, 0, 0); + this.output.connect(output); + } + + + _createClass(_Panner, [{ + key: "pan", + value: function pan(val, tFromNow) { + var time = tFromNow || 0; + var t = panner_ac.currentTime + time; + var v = (val + 1) / 2; + var rightVal = Math.cos(v * Math.PI / 2); + var leftVal = Math.sin(v * Math.PI / 2); + this.left.gain.linearRampToValueAtTime(leftVal, t); + this.right.gain.linearRampToValueAtTime(rightVal, t); + } + }, { + key: "inputChannels", + value: function inputChannels(numChannels) { + if (numChannels === 1) { + this.input.disconnect(); + this.input.connect(this.left); + this.input.connect(this.right); + } else if (numChannels === 2) { + if (typeof this.splitter === 'undefined') { + this.splitter = panner_ac.createChannelSplitter(2); + } + + this.input.disconnect(); + this.input.connect(this.splitter); + this.splitter.connect(this.left, 1); + this.splitter.connect(this.right, 0); + } + } + }, { + key: "connect", + value: function connect(obj) { + this.output.connect(obj); + } + }, { + key: "disconnect", + value: function disconnect() { + if (this.output) { + this.output.disconnect(); + } + } + }]); + + return _Panner; + }(); + + panner = _Panner; +} + + var panner_0 = (panner); +function soundfile_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { soundfile_typeof = function _typeof(obj) { return typeof obj; }; } else { soundfile_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return soundfile_typeof(obj); } + +function soundfile_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function soundfile_createClass(Constructor, protoProps, staticProps) { if (protoProps) soundfile_defineProperties(Constructor.prototype, protoProps); if (staticProps) soundfile_defineProperties(Constructor, staticProps); return Constructor; } + +function soundfile_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + + + + +var soundfile_ac = master.audiocontext; + +var _createCounterBuffer = function _createCounterBuffer(buffer) { + var len = buffer.length; + var audioBuf = soundfile_ac.createBuffer(1, buffer.length, soundfile_ac.sampleRate); + var arrayBuffer = audioBuf.getChannelData(0); + + for (var index = 0; index < len; index++) { + arrayBuffer[index] = index; + } + + return audioBuf; +}; + + +var Peak = function Peak(amp, i) { + soundfile_classCallCheck(this, Peak); + + this.sampleIndex = i; + this.amplitude = amp; + this.tempos = []; + this.intervals = []; +}; + + +function getPeaksAtThreshold(data, threshold) { + var peaksObj = {}; + var length = data.length; + + for (var i = 0; i < length; i++) { + if (data[i] > threshold) { + var amp = data[i]; + var peak = new Peak(amp, i); + peaksObj[i] = peak; + + i += 6000; + } + + i++; + } + + return peaksObj; +} + + +function countIntervalsBetweenNearbyPeaks(peaksObj) { + var intervalCounts = []; + var peaksArray = Object.keys(peaksObj).sort(); + + for (var index = 0; index < peaksArray.length; index++) { + for (var i = 0; i < 10; i++) { + var startPeak = peaksObj[peaksArray[index]]; + var endPeak = peaksObj[peaksArray[index + i]]; + + if (startPeak && endPeak) { + var startPos = startPeak.sampleIndex; + var endPos = endPeak.sampleIndex; + var interval = endPos - startPos; + + if (interval > 0) { + startPeak.intervals.push(interval); + } + + + var foundInterval = intervalCounts.some(function (intervalCount) { + if (intervalCount.interval === interval) { + intervalCount.count++; + return intervalCount; + } + }); + + if (!foundInterval) { + intervalCounts.push({ + interval: interval, + count: 1 + }); + } + } + } + } + + return intervalCounts; +} + + +function groupNeighborsByTempo(intervalCounts, sampleRate) { + var tempoCounts = []; + intervalCounts.forEach(function (intervalCount) { + try { + var theoreticalTempo = Math.abs(60 / (intervalCount.interval / sampleRate)); + theoreticalTempo = mapTempo(theoreticalTempo); + var foundTempo = tempoCounts.some(function (tempoCount) { + if (tempoCount.tempo === theoreticalTempo) return tempoCount.count += intervalCount.count; + }); + + if (!foundTempo) { + if (isNaN(theoreticalTempo)) { + return; + } + + tempoCounts.push({ + tempo: Math.round(theoreticalTempo), + count: intervalCount.count + }); + } + } catch (e) { + throw e; + } + }); + return tempoCounts; +} + + +function getPeaksAtTopTempo(peaksObj, tempo, sampleRate, bpmVariance) { + var peaksAtTopTempo = []; + var peaksArray = Object.keys(peaksObj).sort(); + + for (var i = 0; i < peaksArray.length; i++) { + var key = peaksArray[i]; + var peak = peaksObj[key]; + + for (var j = 0; j < peak.intervals.length; j++) { + var intervalBPM = Math.round(Math.abs(60 / (peak.intervals[j] / sampleRate))); + intervalBPM = mapTempo(intervalBPM); + + if (Math.abs(intervalBPM - tempo) < bpmVariance) { + peaksAtTopTempo.push(peak.sampleIndex / sampleRate); + } + } + } + + + peaksAtTopTempo = peaksAtTopTempo.filter(function (peakTime, index, arr) { + var dif = arr[index + 1] - peakTime; + + if (dif > 0.01) { + return true; + } + }); + return peaksAtTopTempo; +} + + +function mapTempo(theoreticalTempo) { + if (!isFinite(theoreticalTempo) || theoreticalTempo === 0) { + return; + } + + + while (theoreticalTempo < 90) { + theoreticalTempo *= 2; + } + + while (theoreticalTempo > 180 && theoreticalTempo > 90) { + theoreticalTempo /= 2; + } + + return theoreticalTempo; +} + + +var Cue = function Cue(callback, time, id, val) { + soundfile_classCallCheck(this, Cue); + + this.callback = callback; + this.time = time; + this.id = id; + this.val = val; +}; + + +function _clearOnEnd(e) { + var thisBufferSourceNode = e.target; + var soundFile = this; + + thisBufferSourceNode._playing = false; + thisBufferSourceNode.removeEventListener('ended', soundFile._clearOnEnd); + + soundFile._onended(soundFile); + + + soundFile.bufferSourceNodes.map(function (_, i) { + return i; + }).reverse().forEach(function (i) { + var n = soundFile.bufferSourceNodes[i]; + + if (n._playing === false) { + soundFile.bufferSourceNodes.splice(i, 1); + } + }); + + if (soundFile.bufferSourceNodes.length === 0) { + soundFile._playing = false; + } +} +/** + *

    SoundFile object with a path to a file.

    + * + *

    The p5.SoundFile may not be available immediately because + * it loads the file information asynchronously.

    + * + *

    To do something with the sound as soon as it loads + * pass the name of a function as the second parameter.

    + * + *

    Only one file path is required. However, audio file formats + * (i.e. mp3, ogg, wav and m4a/aac) are not supported by all + * web browsers. If you want to ensure compatability, instead of a single + * file path, you may include an Array of filepaths, and the browser will + * choose a format that works.

    + * + * @class p5.SoundFile + * @constructor + * @param {String|Array} path path to a sound file (String). Optionally, + * you may include multiple file formats in + * an array. Alternately, accepts an object + * from the HTML5 File API, or a p5.File. + * @param {Function} [successCallback] Name of a function to call once file loads + * @param {Function} [errorCallback] Name of a function to call if file fails to + * load. This function will receive an error or + * XMLHttpRequest object with information + * about what went wrong. + * @param {Function} [whileLoadingCallback] Name of a function to call while file + * is loading. That function will + * receive progress of the request to + * load the sound file + * (between 0 and 1) as its first + * parameter. This progress + * does not account for the additional + * time needed to decode the audio data. + * + * @example + *
    + * let mySound; + * function preload() { + * soundFormats('mp3', 'ogg'); + * mySound = loadSound('assets/doorbell'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * background(220); + * text('tap here to play', 10, 20); + * } + * + * function canvasPressed() { + * // playing a sound file on a user gesture + * // is equivalent to `userStartAudio()` + * mySound.play(); + * } + *
    + */ + + +var soundfile_SoundFile = +function () { + function SoundFile(paths, onload, onerror, whileLoading) { + soundfile_classCallCheck(this, SoundFile); + + if (typeof paths !== 'undefined') { + if (typeof paths === 'string' || typeof paths[0] === 'string') { + var path = p5.prototype._checkFileFormats(paths); + + this.url = path; + } else if (soundfile_typeof(paths) === 'object') { + if (!(window.File && window.FileReader && window.FileList && window.Blob)) { + throw 'Unable to load file because the File API is not supported'; + } + } + + + if (paths.file) { + paths = paths.file; + } + + this.file = paths; + } + + + this._onended = function () {}; + + this._looping = false; + this._playing = false; + this._paused = false; + this._pauseTime = 0; + + this._cues = []; + this._cueIDCounter = 0; + + this._lastPos = 0; + this._counterNode = null; + this._workletNode = null; + + this.bufferSourceNodes = []; + + this.bufferSourceNode = null; + this.buffer = null; + this.playbackRate = 1; + this.input = master.audiocontext.createGain(); + this.output = master.audiocontext.createGain(); + this.reversed = false; + + this.startTime = 0; + this.endTime = null; + this.pauseTime = 0; + + this.mode = 'sustain'; + + this.startMillis = null; + + this.panPosition = 0.0; + this.panner = new panner_0(this.output, master.input, 2); + + if (this.url || this.file) { + this.load(onload, onerror); + } + + + master.soundArray.push(this); + + if (typeof whileLoading === 'function') { + this._whileLoading = whileLoading; + } else { + this._whileLoading = function () {}; + } + + this._clearOnEnd = _clearOnEnd.bind(this); + + this.amp = this.setVolume; + + this.fade = this.setVolume; + } + /** + * This is a helper function that the p5.SoundFile calls to load + * itself. Accepts a callback (the name of another function) + * as an optional parameter. + * + * @private + * @for p5.SoundFile + * @param {Function} [successCallback] Name of a function to call once file loads + * @param {Function} [errorCallback] Name of a function to call if there is an error + */ + + + soundfile_createClass(SoundFile, [{ + key: "load", + value: function load(callback, errorCallback) { + var self = this; + var errorTrace = new Error().stack; + + if (this.url !== undefined && this.url !== '') { + var request = new XMLHttpRequest(); + request.addEventListener('progress', function (evt) { + self._updateProgress(evt); + }, false); + request.open('GET', this.url, true); + request.responseType = 'arraybuffer'; + + request.onload = function () { + if (request.status === 200) { + if (!self.panner) return; + soundfile_ac.decodeAudioData(request.response, + function (buff) { + if (!self.panner) return; + self.buffer = buff; + self.panner.inputChannels(buff.numberOfChannels); + + if (callback) { + callback(self); + } + }, + function () { + if (!self.panner) return; + var err = new errorHandler('decodeAudioData', errorTrace, self.url); + var msg = 'AudioContext error at decodeAudioData for ' + self.url; + + if (errorCallback) { + err.msg = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + }); + } + else { + if (!self.panner) return; + var err = new errorHandler('loadSound', errorTrace, self.url); + var msg = 'Unable to load ' + self.url + '. The request status was: ' + request.status + ' (' + request.statusText + ')'; + + if (errorCallback) { + err.message = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + } + }; + + + request.onerror = function () { + var err = new errorHandler('loadSound', errorTrace, self.url); + var msg = 'There was no response from the server at ' + self.url + '. Check the url and internet connectivity.'; + + if (errorCallback) { + err.message = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + }; + + request.send(); + } else if (this.file !== undefined) { + var reader = new FileReader(); + + reader.onload = function () { + if (!self.panner) return; + soundfile_ac.decodeAudioData(reader.result, function (buff) { + if (!self.panner) return; + self.buffer = buff; + self.panner.inputChannels(buff.numberOfChannels); + + if (callback) { + callback(self); + } + }); + }; + + reader.onerror = function (e) { + if (!self.panner) return; + + if (onerror) { + onerror(e); + } + }; + + reader.readAsArrayBuffer(this.file); + } + } + + }, { + key: "_updateProgress", + value: function _updateProgress(evt) { + if (evt.lengthComputable) { + var percentComplete = evt.loaded / evt.total * 0.99; + + this._whileLoading(percentComplete, evt); + + } else { + this._whileLoading('size unknown'); + } + } + /** + * Returns true if the sound file finished loading successfully. + * + * @method isLoaded + * @for p5.SoundFile + * @return {Boolean} + */ + + }, { + key: "isLoaded", + value: function isLoaded() { + if (this.buffer) { + return true; + } else { + return false; + } + } + /** + * Play the p5.SoundFile + * + * @method play + * @for p5.SoundFile + * @param {Number} [startTime] (optional) schedule playback to start (in seconds from now). + * @param {Number} [rate] (optional) playback rate + * @param {Number} [amp] (optional) amplitude (volume) + * of playback + * @param {Number} [cueStart] (optional) cue start time in seconds + * @param {Number} [duration] (optional) duration of playback in seconds + */ + + }, { + key: "play", + value: function play(startTime, rate, amp, _cueStart, duration) { + if (!this.output) { + console.warn('SoundFile.play() called after dispose'); + return; + } + + var now = master.audiocontext.currentTime; + var cueStart, cueEnd; + var time = startTime || 0; + + if (time < 0) { + time = 0; + } + + time = time + now; + + if (typeof rate !== 'undefined') { + this.rate(rate); + } + + if (typeof amp !== 'undefined') { + this.setVolume(amp); + } + + + if (this.buffer) { + this._pauseTime = 0; + + if (this.mode === 'restart' && this.buffer && this.bufferSourceNode) { + this.bufferSourceNode.stop(time); + + this._counterNode.stop(time); + } + + + if (this.mode === 'untildone' && this.isPlaying()) { + return; + } + + + this.bufferSourceNode = this._initSourceNode(); + + delete this._counterNode; + this._counterNode = this._initCounterNode(); + + if (_cueStart) { + if (_cueStart >= 0 && _cueStart < this.buffer.duration) { + cueStart = _cueStart; + } else { + throw 'start time out of range'; + } + } else { + cueStart = 0; + } + + if (duration) { + duration = duration <= this.buffer.duration - cueStart ? duration : this.buffer.duration; + } + + + if (this._paused) { + this.bufferSourceNode.start(time, this.pauseTime, duration); + + this._counterNode.start(time, this.pauseTime, duration); + } else { + this.bufferSourceNode.start(time, cueStart, duration); + + this._counterNode.start(time, cueStart, duration); + } + + this._playing = true; + this._paused = false; + + this.bufferSourceNodes.push(this.bufferSourceNode); + this.bufferSourceNode._arrayIndex = this.bufferSourceNodes.length - 1; + this.bufferSourceNode.addEventListener('ended', this._clearOnEnd); + } + else { + throw 'not ready to play file, buffer has yet to load. Try preload()'; + } + + + this.bufferSourceNode.loop = this._looping; + this._counterNode.loop = this._looping; + + if (this._looping === true) { + cueEnd = duration ? duration : cueStart - 0.000000000000001; + this.bufferSourceNode.loopStart = cueStart; + this.bufferSourceNode.loopEnd = cueEnd; + this._counterNode.loopStart = cueStart; + this._counterNode.loopEnd = cueEnd; + } + } + /** + * p5.SoundFile has two play modes: restart and + * sustain. Play Mode determines what happens to a + * p5.SoundFile if it is triggered while in the middle of playback. + * In sustain mode, playback will continue simultaneous to the + * new playback. In restart mode, play() will stop playback + * and start over. With untilDone, a sound will play only if it's + * not already playing. Sustain is the default mode. + * + * @method playMode + * @for p5.SoundFile + * @param {String} str 'restart' or 'sustain' or 'untilDone' + * @example + *
    + * let mySound; + * function preload(){ + * mySound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * noFill(); + * rect(0, height/2, width - 1, height/2 - 1); + * rect(0, 0, width - 1, height/2); + * textAlign(CENTER, CENTER); + * fill(20); + * text('restart', width/2, 1 * height/4); + * text('sustain', width/2, 3 * height/4); + * } + * function canvasPressed() { + * if (mouseX < height/2) { + * mySound.playMode('restart'); + * } else { + * mySound.playMode('sustain'); + * } + * mySound.play(); + * } + * + *
    + */ + + }, { + key: "playMode", + value: function playMode(str) { + var s = str.toLowerCase(); + + if (s === 'restart' && this.buffer && this.bufferSourceNode) { + for (var i = 0; i < this.bufferSourceNodes.length - 1; i++) { + var now = master.audiocontext.currentTime; + this.bufferSourceNodes[i].stop(now); + } + } + + + if (s === 'restart' || s === 'sustain' || s === 'untildone') { + this.mode = s; + } else { + throw 'Invalid play mode. Must be either "restart" or "sustain"'; + } + } + /** + * Pauses a file that is currently playing. If the file is not + * playing, then nothing will happen. + * + * After pausing, .play() will resume from the paused + * position. + * If p5.SoundFile had been set to loop before it was paused, + * it will continue to loop after it is unpaused with .play(). + * + * @method pause + * @for p5.SoundFile + * @param {Number} [startTime] (optional) schedule event to occur + * seconds from now + * @example + *
    + * let soundFile; + * function preload() { + * soundFormats('ogg', 'mp3'); + * soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3'); + * } + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * background(220); + * text('tap to play, release to pause', 10, 20, width - 20); + * } + * function canvasPressed() { + * soundFile.loop(); + * background(0, 200, 50); + * } + * function mouseReleased() { + * soundFile.pause(); + * background(220); + * } + * + *
    + */ + + }, { + key: "pause", + value: function pause(startTime) { + var now = master.audiocontext.currentTime; + var time = startTime || 0; + var pTime = time + now; + + if (this.isPlaying() && this.buffer && this.bufferSourceNode) { + this._paused = true; + this._playing = false; + this.pauseTime = this.currentTime(); + this.bufferSourceNode.stop(pTime); + + this._counterNode.stop(pTime); + + this._pauseTime = this.currentTime(); + } else { + this._pauseTime = 0; + } + } + /** + * Loop the p5.SoundFile. Accepts optional parameters to set the + * playback rate, playback volume, loopStart, loopEnd. + * + * @method loop + * @for p5.SoundFile + * @param {Number} [startTime] (optional) schedule event to occur + * seconds from now + * @param {Number} [rate] (optional) playback rate + * @param {Number} [amp] (optional) playback volume + * @param {Number} [cueLoopStart] (optional) startTime in seconds + * @param {Number} [duration] (optional) loop duration in seconds + * @example + *
    + * let soundFile; + * let loopStart = 0.5; + * let loopDuration = 0.2; + * function preload() { + * soundFormats('ogg', 'mp3'); + * soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3'); + * } + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * background(220); + * text('tap to play, release to pause', 10, 20, width - 20); + * } + * function canvasPressed() { + * soundFile.loop(); + * background(0, 200, 50); + * } + * function mouseReleased() { + * soundFile.pause(); + * background(220); + * } + * + *
    + */ + + }, { + key: "loop", + value: function loop(startTime, rate, amp, loopStart, duration) { + this._looping = true; + this.play(startTime, rate, amp, loopStart, duration); + } + /** + * Set a p5.SoundFile's looping flag to true or false. If the sound + * is currently playing, this change will take effect when it + * reaches the end of the current playback. + * + * @method setLoop + * @for p5.SoundFile + * @param {Boolean} Boolean set looping to true or false + */ + + }, { + key: "setLoop", + value: function setLoop(bool) { + if (bool === true) { + this._looping = true; + } else if (bool === false) { + this._looping = false; + } else { + throw 'Error: setLoop accepts either true or false'; + } + + if (this.bufferSourceNode) { + this.bufferSourceNode.loop = this._looping; + this._counterNode.loop = this._looping; + } + } + /** + * Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not. + * + * @method isLooping + * @for p5.SoundFile + * @return {Boolean} + */ + + }, { + key: "isLooping", + value: function isLooping() { + if (!this.bufferSourceNode) { + return false; + } + + if (this._looping === true && this.isPlaying() === true) { + return true; + } + + return false; + } + /** + * Returns true if a p5.SoundFile is playing, false if not (i.e. + * paused or stopped). + * + * @method isPlaying + * @for p5.SoundFile + * @return {Boolean} + */ + + }, { + key: "isPlaying", + value: function isPlaying() { + return this._playing; + } + /** + * Returns true if a p5.SoundFile is paused, false if not (i.e. + * playing or stopped). + * + * @method isPaused + * @for p5.SoundFile + * @return {Boolean} + */ + + }, { + key: "isPaused", + value: function isPaused() { + return this._paused; + } + /** + * Stop soundfile playback. + * + * @method stop + * @for p5.SoundFile + * @param {Number} [startTime] (optional) schedule event to occur + * in seconds from now + */ + + }, { + key: "stop", + value: function stop(timeFromNow) { + var time = timeFromNow || 0; + + if (this.mode === 'sustain' || this.mode === 'untildone') { + this.stopAll(time); + this._playing = false; + this.pauseTime = 0; + this._paused = false; + } else if (this.buffer && this.bufferSourceNode) { + var now = master.audiocontext.currentTime; + var t = time || 0; + this.pauseTime = 0; + this.bufferSourceNode.stop(now + t); + + this._counterNode.stop(now + t); + + this._playing = false; + this._paused = false; + } + } + /** + * Stop playback on all of this soundfile's sources. + * @private + */ + + }, { + key: "stopAll", + value: function stopAll(_time) { + var now = master.audiocontext.currentTime; + var time = _time || 0; + + if (this.buffer && this.bufferSourceNode) { + for (var i in this.bufferSourceNodes) { + var bufferSourceNode = this.bufferSourceNodes[i]; + + if (bufferSourceNode) { + try { + bufferSourceNode.stop(now + time); + } catch (e) { + } + } + } + + this._counterNode.stop(now + time); + + this._onended(this); + } + } + }, { + key: "getVolume", + value: function getVolume() { + return this.output.gain.value; + } + /** + * Set the stereo panning of a p5.sound object to + * a floating point number between -1.0 (left) and 1.0 (right). + * Default is 0.0 (center). + * + * @method pan + * @for p5.SoundFile + * @param {Number} [panValue] Set the stereo panner + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + * @example + *
    + * let ballX = 0; + * let soundFile; + * + * function preload() { + * soundFormats('ogg', 'mp3'); + * soundFile = loadSound('assets/beatbox.mp3'); + * } + * + * function draw() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * background(220); + * ballX = constrain(mouseX, 0, width); + * ellipse(ballX, height/2, 20, 20); + * } + * + * function canvasPressed(){ + * // map the ball's x location to a panning degree + * // between -1.0 (left) and 1.0 (right) + * let panning = map(ballX, 0., width,-1.0, 1.0); + * soundFile.pan(panning); + * soundFile.play(); + * } + *
    + */ + + }, { + key: "pan", + value: function pan(pval, tFromNow) { + this.panPosition = pval; + this.panner.pan(pval, tFromNow); + } + /** + * Returns the current stereo pan position (-1.0 to 1.0) + * + * @method getPan + * @for p5.SoundFile + * @return {Number} Returns the stereo pan setting of the Oscillator + * as a number between -1.0 (left) and 1.0 (right). + * 0.0 is center and default. + */ + + }, { + key: "getPan", + value: function getPan() { + return this.panPosition; + } + /** + * Set the playback rate of a sound file. Will change the speed and the pitch. + * Values less than zero will reverse the audio buffer. + * + * @method rate + * @for p5.SoundFile + * @param {Number} [playbackRate] Set the playback rate. 1.0 is normal, + * .5 is half-speed, 2.0 is twice as fast. + * Values less than zero play backwards. + * @example + *
    + * let mySound; + * + * function preload() { + * mySound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * } + * function canvasPressed() { + * mySound.loop(); + * } + * function mouseReleased() { + * mySound.pause(); + * } + * function draw() { + * background(220); + * + * // Set the rate to a range between 0.1 and 4 + * // Changing the rate also alters the pitch + * let playbackRate = map(mouseY, 0.1, height, 2, 0); + * playbackRate = constrain(playbackRate, 0.01, 4); + * mySound.rate(playbackRate); + * + * line(0, mouseY, width, mouseY); + * text('rate: ' + round(playbackRate * 100) + '%', 10, 20); + * } + * + * + *
    + * + */ + + }, { + key: "rate", + value: function rate(playbackRate) { + var reverse = false; + + if (typeof playbackRate === 'undefined') { + return this.playbackRate; + } + + this.playbackRate = playbackRate; + + if (playbackRate === 0) { + playbackRate = 0.0000000000001; + } else if (playbackRate < 0 && !this.reversed) { + playbackRate = Math.abs(playbackRate); + reverse = true; + } else if (playbackRate > 0 && this.reversed) { + reverse = true; + } + + if (this.bufferSourceNode) { + var now = master.audiocontext.currentTime; + this.bufferSourceNode.playbackRate.cancelScheduledValues(now); + this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(playbackRate), now); + + this._counterNode.playbackRate.cancelScheduledValues(now); + + this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(playbackRate), now); + } + + if (reverse) { + this.reverseBuffer(); + } + + return this.playbackRate; + } + + }, { + key: "setPitch", + value: function setPitch(num) { + var newPlaybackRate = midiToFreq(num) / midiToFreq(60); + this.rate(newPlaybackRate); + } + }, { + key: "getPlaybackRate", + value: function getPlaybackRate() { + return this.playbackRate; + } + /** + * Multiply the output volume (amplitude) of a sound file + * between 0.0 (silence) and 1.0 (full volume). + * 1.0 is the maximum amplitude of a digital sound, so multiplying + * by greater than 1.0 may cause digital distortion. To + * fade, provide a rampTime parameter. For more + * complex fades, see the Envelope class. + * + * Alternately, you can pass in a signal source such as an + * oscillator to modulate the amplitude with an audio signal. + * + * @method setVolume + * @for p5.SoundFile + * @param {Number|Object} volume Volume (amplitude) between 0.0 + * and 1.0 or modulating signal/oscillator + * @param {Number} [rampTime] Fade for t seconds + * @param {Number} [timeFromNow] Schedule this event to happen at + * t seconds in the future + */ + + }, { + key: "setVolume", + value: function setVolume(vol, _rampTime, _tFromNow) { + if (typeof vol === 'number') { + var rampTime = _rampTime || 0; + var tFromNow = _tFromNow || 0; + var now = master.audiocontext.currentTime; + var currentVol = this.output.gain.value; + this.output.gain.cancelScheduledValues(now + tFromNow); + this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); + this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); + } else if (vol) { + vol.connect(this.output.gain); + } else { + return this.output.gain; + } + } + /** + * Returns the duration of a sound file in seconds. + * + * @method duration + * @for p5.SoundFile + * @return {Number} The duration of the soundFile in seconds. + */ + + }, { + key: "duration", + value: function duration() { + if (this.buffer) { + return this.buffer.duration; + } else { + return 0; + } + } + /** + * Return the current position of the p5.SoundFile playhead, in seconds. + * Time is relative to the normal buffer direction, so if `reverseBuffer` + * has been called, currentTime will count backwards. + * + * @method currentTime + * @for p5.SoundFile + * @return {Number} currentTime of the soundFile in seconds. + */ + + }, { + key: "currentTime", + value: function currentTime() { + return this.reversed ? Math.abs(this._lastPos - this.buffer.length) / soundfile_ac.sampleRate : this._lastPos / soundfile_ac.sampleRate; + } + /** + * Move the playhead of a soundfile that is currently playing to a + * new position and a new duration, in seconds. + * If none are given, will reset the file to play entire duration + * from start to finish. To set the position of a soundfile that is + * not currently playing, use the `play` or `loop` methods. + * + * @method jump + * @for p5.SoundFile + * @param {Number} cueTime cueTime of the soundFile in seconds. + * @param {Number} duration duration in seconds. + */ + + }, { + key: "jump", + value: function jump(cueTime, duration) { + if (cueTime < 0 || cueTime > this.buffer.duration) { + throw 'jump time out of range'; + } + + if (duration > this.buffer.duration - cueTime) { + throw 'end time out of range'; + } + + var cTime = cueTime || 0; + var dur = duration || undefined; + + if (this.isPlaying()) { + this.stop(0); + this.play(0, this.playbackRate, this.output.gain.value, cTime, dur); + } + } + /** + * Return the number of channels in a sound file. + * For example, Mono = 1, Stereo = 2. + * + * @method channels + * @for p5.SoundFile + * @return {Number} [channels] + */ + + }, { + key: "channels", + value: function channels() { + return this.buffer.numberOfChannels; + } + /** + * Return the sample rate of the sound file. + * + * @method sampleRate + * @for p5.SoundFile + * @return {Number} [sampleRate] + */ + + }, { + key: "sampleRate", + value: function sampleRate() { + return this.buffer.sampleRate; + } + /** + * Return the number of samples in a sound file. + * Equal to sampleRate * duration. + * + * @method frames + * @for p5.SoundFile + * @return {Number} [sampleCount] + */ + + }, { + key: "frames", + value: function frames() { + return this.buffer.length; + } + /** + * Returns an array of amplitude peaks in a p5.SoundFile that can be + * used to draw a static waveform. Scans through the p5.SoundFile's + * audio buffer to find the greatest amplitudes. Accepts one + * parameter, 'length', which determines size of the array. + * Larger arrays result in more precise waveform visualizations. + * + * Inspired by Wavesurfer.js. + * + * @method getPeaks + * @for p5.SoundFile + * @params {Number} [length] length is the size of the returned array. + * Larger length results in more precision. + * Defaults to 5*width of the browser window. + * @returns {Float32Array} Array of peaks. + */ + + }, { + key: "getPeaks", + value: function getPeaks(length) { + if (this.buffer) { + if (!length) { + length = window.width * 5; + } + + if (this.buffer) { + var buffer = this.buffer; + var sampleSize = buffer.length / length; + var sampleStep = ~~(sampleSize / 10) || 1; + var channels = buffer.numberOfChannels; + var peaks = new Float32Array(Math.round(length)); + + for (var c = 0; c < channels; c++) { + var chan = buffer.getChannelData(c); + + for (var i = 0; i < length; i++) { + var start = ~~(i * sampleSize); + var end = ~~(start + sampleSize); + var max = 0; + + for (var j = start; j < end; j += sampleStep) { + var value = chan[j]; + + if (value > max) { + max = value; + } else if (-value > max) { + max = value; + } + } + + if (c === 0 || Math.abs(max) > peaks[i]) { + peaks[i] = max; + } + } + } + + return peaks; + } + } else { + throw 'Cannot load peaks yet, buffer is not loaded'; + } + } + /** + * Reverses the p5.SoundFile's buffer source. + * Playback must be handled separately (see example). + * + * @method reverseBuffer + * @for p5.SoundFile + * @example + *
    + * let drum; + * function preload() { + * drum = loadSound('assets/drum.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * background(220); + * text('tap to play', 20, 20); + * } + * + * function canvasPressed() { + * drum.stop(); + * drum.reverseBuffer(); + * drum.play(); + * } + * + *
    + */ + + }, { + key: "reverseBuffer", + value: function reverseBuffer() { + if (this.buffer) { + var currentPos = this._lastPos / soundfile_ac.sampleRate; + var curVol = this.getVolume(); + this.setVolume(0, 0.001); + var numChannels = this.buffer.numberOfChannels; + + for (var i = 0; i < numChannels; i++) { + this.buffer.getChannelData(i).reverse(); + } + + + this.reversed = !this.reversed; + + if (this.isPlaying() && currentPos) { + this.jump(this.duration() - currentPos); + } + + this.setVolume(curVol, 0.001); + } else { + throw 'SoundFile is not done loading'; + } + } + /** + * Schedule an event to be called when the soundfile + * reaches the end of a buffer. If the soundfile is + * playing through once, this will be called when it + * ends. If it is looping, it will be called when + * stop is called. + * + * @method onended + * @for p5.SoundFile + * @param {Function} callback function to call when the + * soundfile has ended. + */ + + }, { + key: "onended", + value: function onended(callback) { + this._onended = callback; + return this; + } + }, { + key: "add", + value: function add() { + } + }, { + key: "dispose", + value: function dispose() { + var now = master.audiocontext.currentTime; + + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + this.stop(now); + + if (this.buffer && this.bufferSourceNode) { + for (var i = 0; i < this.bufferSourceNodes.length - 1; i++) { + if (this.bufferSourceNodes[i] !== null) { + this.bufferSourceNodes[i].disconnect(); + + try { + this.bufferSourceNodes[i].stop(now); + } catch (e) { + console.warn('no buffer source node to dispose'); + } + + this.bufferSourceNodes[i] = null; + } + } + + if (this.isPlaying()) { + try { + this._counterNode.stop(now); + } catch (e) { + console.log(e); + } + + this._counterNode = null; + } + } + + if (this.output) { + this.output.disconnect(); + this.output = null; + } + + if (this.panner) { + this.panner.disconnect(); + this.panner = null; + } + } + /** + * Connects the output of a p5sound object to input of another + * p5.sound object. For example, you may connect a p5.SoundFile to an + * FFT or an Effect. If no parameter is given, it will connect to + * the master output. Most p5sound objects connect to the master + * output when they are created. + * + * @method connect + * @for p5.SoundFile + * @param {Object} [object] Audio object that accepts an input + */ + + }, { + key: "connect", + value: function connect(unit) { + if (!unit) { + this.panner.connect(master.input); + } else { + if (unit.hasOwnProperty('input')) { + this.panner.connect(unit.input); + } else { + this.panner.connect(unit); + } + } + } + /** + * Disconnects the output of this p5sound object. + * + * @method disconnect + * @for p5.SoundFile + */ + + }, { + key: "disconnect", + value: function disconnect() { + if (this.panner) { + this.panner.disconnect(); + } + } + /** + */ + + }, { + key: "getLevel", + value: function getLevel() { + console.warn('p5.SoundFile.getLevel has been removed from the library. Use p5.Amplitude instead'); + } + /** + * Reset the source for this SoundFile to a + * new path (URL). + * + * @method setPath + * @for p5.SoundFile + * @param {String} path path to audio file + * @param {Function} callback Callback + */ + + }, { + key: "setPath", + value: function setPath(p, callback) { + var path = p5.prototype._checkFileFormats(p); + + this.url = path; + this.load(callback); + } + /** + * Replace the current Audio Buffer with a new Buffer. + * + * @method setBuffer + * @for p5.SoundFile + * @param {Array} buf Array of Float32 Array(s). 2 Float32 Arrays + * will create a stereo source. 1 will create + * a mono source. + */ + + }, { + key: "setBuffer", + value: function setBuffer(buf) { + var numChannels = buf.length; + var size = buf[0].length; + var newBuffer = soundfile_ac.createBuffer(numChannels, size, soundfile_ac.sampleRate); + + if (!(buf[0] instanceof Float32Array)) { + buf[0] = new Float32Array(buf[0]); + } + + for (var channelNum = 0; channelNum < numChannels; channelNum++) { + var channel = newBuffer.getChannelData(channelNum); + channel.set(buf[channelNum]); + } + + this.buffer = newBuffer; + + this.panner.inputChannels(numChannels); + } + + }, { + key: "_initCounterNode", + value: function _initCounterNode() { + var _this = this; + + var self = this; + var now = soundfile_ac.currentTime; + var cNode = soundfile_ac.createBufferSource(); + var workletBufferSize = safeBufferSize(256); + + if (self._workletNode) { + self._workletNode.disconnect(); + + delete self._workletNode; + } + + self._workletNode = new AudioWorkletNode(soundfile_ac, processorNames_default.a.soundFileProcessor, { + processorOptions: { + bufferSize: workletBufferSize + } + }); + + self._workletNode.port.onmessage = function (event) { + if (event.data.name === 'position') { + if (event.data.position === 0) { + return; + } + + _this._lastPos = event.data.position; + + _this._onTimeUpdate(self._lastPos); + } + }; + + + cNode.buffer = _createCounterBuffer(self.buffer); + cNode.playbackRate.setValueAtTime(self.playbackRate, now); + cNode.connect(self._workletNode); + + self._workletNode.connect(p5.soundOut._silentNode); + + return cNode; + } + + }, { + key: "_initSourceNode", + value: function _initSourceNode() { + var bufferSourceNode = soundfile_ac.createBufferSource(); + bufferSourceNode.buffer = this.buffer; + bufferSourceNode.playbackRate.value = this.playbackRate; + bufferSourceNode.connect(this.output); + return bufferSourceNode; + } + /** + * processPeaks returns an array of timestamps where it thinks there is a beat. + * + * This is an asynchronous function that processes the soundfile in an offline audio context, + * and sends the results to your callback function. + * + * The process involves running the soundfile through a lowpass filter, and finding all of the + * peaks above the initial threshold. If the total number of peaks are below the minimum number of peaks, + * it decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached. + * + * @method processPeaks + * @for p5.SoundFile + * @param {Function} callback a function to call once this data is returned + * @param {Number} [initThreshold] initial threshold defaults to 0.9 + * @param {Number} [minThreshold] minimum threshold defaults to 0.22 + * @param {Number} [minPeaks] minimum number of peaks defaults to 200 + * @return {Array} Array of timestamped peaks + */ + + }, { + key: "processPeaks", + value: function processPeaks(callback, _initThreshold, _minThreshold, _minPeaks) { + var bufLen = this.buffer.length; + var sampleRate = this.buffer.sampleRate; + var buffer = this.buffer; + var allPeaks = []; + var initialThreshold = _initThreshold || 0.9, + threshold = initialThreshold, + minThreshold = _minThreshold || 0.22, + minPeaks = _minPeaks || 200; + + var offlineContext = new window.OfflineAudioContext(1, bufLen, sampleRate); + + var source = offlineContext.createBufferSource(); + source.buffer = buffer; + + var filter = offlineContext.createBiquadFilter(); + filter.type = 'lowpass'; + source.connect(filter); + filter.connect(offlineContext.destination); + + source.start(0); + offlineContext.startRendering(); + + offlineContext.oncomplete = function (e) { + if (!self.panner) return; + var filteredBuffer = e.renderedBuffer; + var bufferData = filteredBuffer.getChannelData(0); + + do { + allPeaks = getPeaksAtThreshold(bufferData, threshold); + threshold -= 0.005; + } while (Object.keys(allPeaks).length < minPeaks && threshold >= minThreshold); + + + var intervalCounts = countIntervalsBetweenNearbyPeaks(allPeaks); + + var groups = groupNeighborsByTempo(intervalCounts, filteredBuffer.sampleRate); + + var topTempos = groups.sort(function (intA, intB) { + return intB.count - intA.count; + }).splice(0, 5); + + this.tempo = topTempos[0].tempo; + + var bpmVariance = 5; + var tempoPeaks = getPeaksAtTopTempo(allPeaks, topTempos[0].tempo, filteredBuffer.sampleRate, bpmVariance); + callback(tempoPeaks); + }; + } + /** + * Schedule events to trigger every time a MediaElement + * (audio/video) reaches a playback cue point. + * + * Accepts a callback function, a time (in seconds) at which to trigger + * the callback, and an optional parameter for the callback. + * + * Time will be passed as the first parameter to the callback function, + * and param will be the second parameter. + * + * + * @method addCue + * @for p5.SoundFile + * @param {Number} time Time in seconds, relative to this media + * element's playback. For example, to trigger + * an event every time playback reaches two + * seconds, pass in the number 2. This will be + * passed as the first parameter to + * the callback function. + * @param {Function} callback Name of a function that will be + * called at the given time. The callback will + * receive time and (optionally) param as its + * two parameters. + * @param {Object} [value] An object to be passed as the + * second parameter to the + * callback function. + * @return {Number} id ID of this cue, + * useful for removeCue(id) + * @example + *
    + * let mySound; + * function preload() { + * mySound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * background(220); + * text('tap to play', 10, 20); + * + * // schedule calls to changeText + * mySound.addCue(0, changeText, "hello" ); + * mySound.addCue(0.5, changeText, "hello," ); + * mySound.addCue(1, changeText, "hello, p5!"); + * mySound.addCue(1.5, changeText, "hello, p5!!"); + * mySound.addCue(2, changeText, "hello, p5!!!!!"); + * } + * + * function changeText(val) { + * background(220); + * text(val, 10, 20); + * } + * + * function canvasPressed() { + * mySound.play(); + * } + *
    + */ + + }, { + key: "addCue", + value: function addCue(time, callback, val) { + var id = this._cueIDCounter++; + var cue = new Cue(callback, time, id, val); + + this._cues.push(cue); + + + return id; + } + /** + * Remove a callback based on its ID. The ID is returned by the + * addCue method. + * + * @method removeCue + * @for p5.SoundFile + * @param {Number} id ID of the cue, as returned by addCue + */ + + }, { + key: "removeCue", + value: function removeCue(id) { + var cueLength = this._cues.length; + + for (var i = 0; i < cueLength; i++) { + var cue = this._cues[i]; + + if (cue.id === id) { + this._cues.splice(i, 1); + + break; + } + } + + if (this._cues.length === 0) { + } + } + /** + * Remove all of the callbacks that had originally been scheduled + * via the addCue method. + * + * @method clearCues + */ + + }, { + key: "clearCues", + value: function clearCues() { + this._cues = []; + } + + }, { + key: "_onTimeUpdate", + value: function _onTimeUpdate(position) { + var playbackTime = position / this.buffer.sampleRate; + var cueLength = this._cues.length; + + for (var i = 0; i < cueLength; i++) { + var cue = this._cues[i]; + var callbackTime = cue.time; + var val = cue.val; + var leftLimit = this._prevUpdateTime || 0; + var rightLimit = playbackTime; + + if (leftLimit <= callbackTime && callbackTime <= rightLimit) { + cue.callback(val); + } + } + + this._prevUpdateTime = playbackTime; + } + /** + * Save a p5.SoundFile as a .wav file. The browser will prompt the user + * to download the file to their device. To upload a file to a server, see + * getBlob + * + * @method save + * @for p5.SoundFile + * @param {String} [fileName] name of the resulting .wav file. + * @example + *
    + * let mySound; + * function preload() { + * mySound = loadSound('assets/doorbell.mp3'); + * } + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * background(220); + * text('tap to download', 10, 20); + * } + * + * function canvasPressed() { + * mySound.save('my cool filename'); + * } + *
    + */ + + }, { + key: "save", + value: function save(fileName) { + p5.prototype.saveSound(this, fileName, 'wav'); + } + /** + * This method is useful for sending a SoundFile to a server. It returns the + * .wav-encoded audio data as a "Blob". + * A Blob is a file-like data object that can be uploaded to a server + * with an http request. We'll + * use the `httpDo` options object to send a POST request with some + * specific options: we encode the request as `multipart/form-data`, + * and attach the blob as one of the form values using `FormData`. + * + * + * @method getBlob + * @for p5.SoundFile + * @returns {Blob} A file-like data object + * @example + *
    + * function preload() { + * mySound = loadSound('assets/doorbell.mp3'); + * } + * + * function setup() { + * noCanvas(); + * let soundBlob = mySound.getBlob(); + * + * // Now we can send the blob to a server... + * let serverUrl = 'https://jsonplaceholder.typicode.com/posts'; + * let httpRequestOptions = { + * method: 'POST', + * body: new FormData().append('soundBlob', soundBlob), + * headers: new Headers({ + * 'Content-Type': 'multipart/form-data' + * }) + * }; + * httpDo(serverUrl, httpRequestOptions); + * + * // We can also create an `ObjectURL` pointing to the Blob + * let blobUrl = URL.createObjectURL(soundBlob); + * + * // The `
    + */ + + }, { + key: "getBlob", + value: function getBlob() { + var dataView = convertToWav(this.buffer); + return new Blob([dataView], { + type: 'audio/wav' + }); + } + }]); + + return SoundFile; +}(); +/** + * loadSound() returns a new p5.SoundFile from a specified + * path. If called during preload(), the p5.SoundFile will be ready + * to play in time for setup() and draw(). If called outside of + * preload, the p5.SoundFile will not be ready immediately, so + * loadSound accepts a callback as the second parameter. Using a + * + * local server is recommended when loading external files. + * + * @method loadSound + * @for p5 + * @param {String|Array} path Path to the sound file, or an array with + * paths to soundfiles in multiple formats + * i.e. ['sound.ogg', 'sound.mp3']. + * Alternately, accepts an object: either + * from the HTML5 File API, or a p5.File. + * @param {Function} [successCallback] Name of a function to call once file loads + * @param {Function} [errorCallback] Name of a function to call if there is + * an error loading the file. + * @param {Function} [whileLoading] Name of a function to call while file is loading. + * This function will receive the percentage loaded + * so far, from 0.0 to 1.0. + * @return {SoundFile} Returns a p5.SoundFile + * @example + *
    + * let mySound; + * function preload() { + * soundFormats('mp3', 'ogg'); + * mySound = loadSound('assets/doorbell'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * background(220); + * text('tap here to play', 10, 20); + * } + * + * function canvasPressed() { + * // playing a sound file on a user gesture + * // is equivalent to `userStartAudio()` + * mySound.play(); + * } + *
    + */ + + +function loadSound(path, callback, onerror, whileLoading) { + if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { + window.alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); + } + + var self = this; + var s = new soundfile_SoundFile(path, function () { + if (typeof callback === 'function') { + callback.apply(self, arguments); + } + + if (typeof self._decrementPreload === 'function') { + self._decrementPreload(); + } + }, onerror, whileLoading); + return s; +} + + var soundfile = (soundfile_SoundFile); + +function amplitude_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function amplitude_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function amplitude_createClass(Constructor, protoProps, staticProps) { if (protoProps) amplitude_defineProperties(Constructor.prototype, protoProps); if (staticProps) amplitude_defineProperties(Constructor, staticProps); return Constructor; } + + + + +/** + * Amplitude measures volume between 0.0 and 1.0. + * Listens to all p5sound by default, or use setInput() + * to listen to a specific sound source. Accepts an optional + * smoothing value, which defaults to 0. + * + * @class p5.Amplitude + * @constructor + * @param {Number} [smoothing] between 0.0 and .999 to smooth + * amplitude readings (defaults to 0) + * @example + *
    + * let sound, amplitude; + * + * function preload(){ + * sound = loadSound('assets/beat.mp3'); + * } + * function setup() { + * let cnv = createCanvas(100,100); + * cnv.mouseClicked(toggleSound); + * amplitude = new p5.Amplitude(); + * } + * + * function draw() { + * background(220); + * text('tap to play', 20, 20); + * + * let level = amplitude.getLevel(); + * let size = map(level, 0, 1, 0, 200); + * ellipse(width/2, height/2, size, size); + * } + * + * function togglePlay() { + * if (sound.isPlaying() ){ + * sound.pause(); + * } else { + * sound.loop(); + * amplitude = new p5.Amplitude(); + * amplitude.setInput(sound); + * } + * } + * + *
    + */ + +var amplitude_Amplitude = +function () { + function Amplitude(smoothing) { + amplitude_classCallCheck(this, Amplitude); + + this.bufferSize = safeBufferSize(2048); + + this.audiocontext = master.audiocontext; + this._workletNode = new AudioWorkletNode(this.audiocontext, processorNames_default.a.amplitudeProcessor, { + outputChannelCount: [1], + parameterData: { + smoothing: smoothing || 0 + }, + processorOptions: { + normalize: false, + smoothing: smoothing || 0, + numInputChannels: 2, + bufferSize: this.bufferSize + } + }); + + this._workletNode.port.onmessage = function (event) { + if (event.data.name === 'amplitude') { + this.volume = event.data.volume; + this.volNorm = event.data.volNorm; + this.stereoVol = event.data.stereoVol; + this.stereoVolNorm = event.data.stereoVolNorm; + } + }.bind(this); + + + this.input = this._workletNode; + this.output = this.audiocontext.createGain(); + + this.volume = 0; + this.volNorm = 0; + this.stereoVol = [0, 0]; + this.stereoVolNorm = [0, 0]; + this.normalize = false; + + this._workletNode.connect(this.output); + + this.output.gain.value = 0; + + this.output.connect(this.audiocontext.destination); + + master.meter.connect(this._workletNode); + + master.soundArray.push(this); + } + /** + * Connects to the p5sound instance (master output) by default. + * Optionally, you can pass in a specific source (i.e. a soundfile). + * + * @method setInput + * @for p5.Amplitude + * @param {soundObject|undefined} [snd] set the sound source + * (optional, defaults to + * master output) + * @param {Number|undefined} [smoothing] a range between 0.0 and 1.0 + * to smooth amplitude readings + * @example + *
    + * function preload(){ + * sound1 = loadSound('assets/beat.mp3'); + * sound2 = loadSound('assets/drum.mp3'); + * } + * function setup(){ + * cnv = createCanvas(100, 100); + * cnv.mouseClicked(toggleSound); + * + * amplitude = new p5.Amplitude(); + * amplitude.setInput(sound2); + * } + * + * function draw() { + * background(220); + * text('tap to play', 20, 20); + * + * let level = amplitude.getLevel(); + * let size = map(level, 0, 1, 0, 200); + * ellipse(width/2, height/2, size, size); + * } + * + * function toggleSound(){ + * if (sound1.isPlaying() && sound2.isPlaying()) { + * sound1.stop(); + * sound2.stop(); + * } else { + * sound1.play(); + * sound2.play(); + * } + * } + *
    + */ + + + amplitude_createClass(Amplitude, [{ + key: "setInput", + value: function setInput(source, smoothing) { + master.meter.disconnect(); + + if (smoothing) { + this._workletNode.parameters.get('smoothing').value = smoothing; + } + + + if (source == null) { + console.log('Amplitude input source is not ready! Connecting to master output instead'); + master.meter.connect(this._workletNode); + } + else if (source) { + source.connect(this._workletNode); + + this._workletNode.disconnect(); + + this._workletNode.connect(this.output); + } + else { + master.meter.connect(this._workletNode); + } + } + }, { + key: "connect", + value: function connect(unit) { + if (unit) { + if (unit.hasOwnProperty('input')) { + this.output.connect(unit.input); + } else { + this.output.connect(unit); + } + } else { + this.output.connect(this.panner.connect(master.input)); + } + } + }, { + key: "disconnect", + value: function disconnect() { + if (this.output) { + this.output.disconnect(); + } + } + /** + * Returns a single Amplitude reading at the moment it is called. + * For continuous readings, run in the draw loop. + * + * @method getLevel + * @for p5.Amplitude + * @param {Number} [channel] Optionally return only channel 0 (left) or 1 (right) + * @return {Number} Amplitude as a number between 0.0 and 1.0 + * @example + *
    + * function preload(){ + * sound = loadSound('assets/beat.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mouseClicked(toggleSound); + * amplitude = new p5.Amplitude(); + * } + * + * function draw() { + * background(220, 150); + * textAlign(CENTER); + * text('tap to play', width/2, 20); + * + * let level = amplitude.getLevel(); + * let size = map(level, 0, 1, 0, 200); + * ellipse(width/2, height/2, size, size); + * } + * + * function toggleSound(){ + * if (sound.isPlaying()) { + * sound.stop(); + * } else { + * sound.play(); + * } + * } + *
    + */ + + }, { + key: "getLevel", + value: function getLevel(channel) { + if (typeof channel !== 'undefined') { + if (this.normalize) { + return this.stereoVolNorm[channel]; + } else { + return this.stereoVol[channel]; + } + } else if (this.normalize) { + return this.volNorm; + } else { + return this.volume; + } + } + /** + * Determines whether the results of Amplitude.process() will be + * Normalized. To normalize, Amplitude finds the difference the + * loudest reading it has processed and the maximum amplitude of + * 1.0. Amplitude adds this difference to all values to produce + * results that will reliably map between 0.0 and 1.0. However, + * if a louder moment occurs, the amount that Normalize adds to + * all the values will change. Accepts an optional boolean parameter + * (true or false). Normalizing is off by default. + * + * @method toggleNormalize + * @for p5.Amplitude + * @param {boolean} [boolean] set normalize to true (1) or false (0) + */ + + }, { + key: "toggleNormalize", + value: function toggleNormalize(bool) { + if (typeof bool === 'boolean') { + this.normalize = bool; + } else { + this.normalize = !this.normalize; + } + + this._workletNode.port.postMessage({ + name: 'toggleNormalize', + normalize: this.normalize + }); + } + /** + * Smooth Amplitude analysis by averaging with the last analysis + * frame. Off by default. + * + * @method smooth + * @for p5.Amplitude + * @param {Number} set smoothing from 0.0 <= 1 + */ + + }, { + key: "smooth", + value: function smooth(s) { + if (s >= 0 && s < 1) { + this._workletNode.port.postMessage({ + name: 'smoothing', + smoothing: s + }); + } else { + console.log('Error: smoothing must be between 0 and 1'); + } + } + }, { + key: "dispose", + value: function dispose() { + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + + if (this.input) { + this.input.disconnect(); + delete this.input; + } + + if (this.output) { + this.output.disconnect(); + delete this.output; + } + + this._workletNode.disconnect(); + + delete this._workletNode; + } + }]); + + return Amplitude; +}(); + + var amplitude = (amplitude_Amplitude); +function fft_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function fft_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function fft_createClass(Constructor, protoProps, staticProps) { if (protoProps) fft_defineProperties(Constructor.prototype, protoProps); if (staticProps) fft_defineProperties(Constructor, staticProps); return Constructor; } + + +/** + *

    FFT (Fast Fourier Transform) is an analysis algorithm that + * isolates individual + * + * audio frequencies within a waveform.

    + * + *

    Once instantiated, a p5.FFT object can return an array based on + * two types of analyses:
    FFT.waveform() computes + * amplitude values along the time domain. The array indices correspond + * to samples across a brief moment in time. Each value represents + * amplitude of the waveform at that sample of time.
    + * • FFT.analyze() computes amplitude values along the + * frequency domain. The array indices correspond to frequencies (i.e. + * pitches), from the lowest to the highest that humans can hear. Each + * value represents amplitude at that slice of the frequency spectrum. + * Use with getEnergy() to measure amplitude at specific + * frequencies, or within a range of frequencies.

    + * + *

    FFT analyzes a very short snapshot of sound called a sample + * buffer. It returns an array of amplitude measurements, referred + * to as bins. The array is 1024 bins long by default. + * You can change the bin array length, but it must be a power of 2 + * between 16 and 1024 in order for the FFT algorithm to function + * correctly. The actual size of the FFT buffer is twice the + * number of bins, so given a standard sample rate, the buffer is + * 2048/44100 seconds long.

    + * + * + * @class p5.FFT + * @constructor + * @param {Number} [smoothing] Smooth results of Freq Spectrum. + * 0.0 < smoothing < 1.0. + * Defaults to 0.8. + * @param {Number} [bins] Length of resulting array. + * Must be a power of two between + * 16 and 1024. Defaults to 1024. + * @example + *
    + * function preload(){ + * sound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup(){ + * let cnv = createCanvas(100,100); + * cnv.mouseClicked(togglePlay); + * fft = new p5.FFT(); + * sound.amp(0.2); + * } + * + * function draw(){ + * background(220); + * + * let spectrum = fft.analyze(); + * noStroke(); + * fill(255, 0, 255); + * for (let i = 0; i< spectrum.length; i++){ + * let x = map(i, 0, spectrum.length, 0, width); + * let h = -height + map(spectrum[i], 0, 255, height, 0); + * rect(x, height, width / spectrum.length, h ) + * } + * + * let waveform = fft.waveform(); + * noFill(); + * beginShape(); + * stroke(20); + * for (let i = 0; i < waveform.length; i++){ + * let x = map(i, 0, waveform.length, 0, width); + * let y = map( waveform[i], -1, 1, 0, height); + * vertex(x,y); + * } + * endShape(); + * + * text('tap to play', 20, 20); + * } + * + * function togglePlay() { + * if (sound.isPlaying()) { + * sound.pause(); + * } else { + * sound.loop(); + * } + * } + *
    + */ + +var fft_FFT = +function () { + function FFT(smoothing, bins) { + fft_classCallCheck(this, FFT); + + this.input = this.analyser = master.audiocontext.createAnalyser(); + Object.defineProperties(this, { + bins: { + get: function get() { + return this.analyser.fftSize / 2; + }, + set: function set(b) { + this.analyser.fftSize = b * 2; + }, + configurable: true, + enumerable: true + }, + smoothing: { + get: function get() { + return this.analyser.smoothingTimeConstant; + }, + set: function set(s) { + this.analyser.smoothingTimeConstant = s; + }, + configurable: true, + enumerable: true + } + }); + + this.smooth(smoothing); + this.bins = bins || 1024; + + master.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, 14000]; + + master.soundArray.push(this); + } + /** + * Set the input source for the FFT analysis. If no source is + * provided, FFT will analyze all sound in the sketch. + * + * @method setInput + * @for p5.FFT + * @param {Object} [source] p5.sound object (or web audio API source node) + */ + + + fft_createClass(FFT, [{ + key: "setInput", + value: function setInput(source) { + if (!source) { + master.fftMeter.connect(this.analyser); + } else { + if (source.output) { + source.output.connect(this.analyser); + } else if (source.connect) { + source.connect(this.analyser); + } + + master.fftMeter.disconnect(); + } + } + /** + * Returns an array of amplitude values (between -1.0 and +1.0) that represent + * a snapshot of amplitude readings in a single buffer. Length will be + * equal to bins (defaults to 1024). Can be used to draw the waveform + * of a sound. + * + * @method waveform + * @for p5.FFT + * @param {Number} [bins] Must be a power of two between + * 16 and 1024. Defaults to 1024. + * @param {String} [precision] If any value is provided, will return results + * in a Float32 Array which is more precise + * than a regular array. + * @return {Array} Array Array of amplitude values (-1 to 1) + * over time. Array length = bins. + * + */ + + }, { + key: "waveform", + value: function waveform() { + var bins, mode; + var normalArray = new Array(); + + for (var i = 0; i < arguments.length; i++) { + if (typeof arguments[i] === 'number') { + bins = arguments[i]; + this.analyser.fftSize = bins * 2; + } + + if (typeof arguments[i] === 'string') { + mode = arguments[i]; + } + } + + + if (mode && !p5.prototype._isSafari()) { + timeToFloat(this, this.timeDomain); + this.analyser.getFloatTimeDomainData(this.timeDomain); + return this.timeDomain; + } else { + timeToInt(this, this.timeDomain); + this.analyser.getByteTimeDomainData(this.timeDomain); + + for (var j = 0; j < this.timeDomain.length; j++) { + var scaled = p5.prototype.map(this.timeDomain[j], 0, 255, -1, 1); + normalArray.push(scaled); + } + + return normalArray; + } + } + /** + * Returns an array of amplitude values (between 0 and 255) + * across the frequency spectrum. Length is equal to FFT bins + * (1024 by default). The array indices correspond to frequencies + * (i.e. pitches), from the lowest to the highest that humans can + * hear. Each value represents amplitude at that slice of the + * frequency spectrum. Must be called prior to using + * getEnergy(). + * + * @method analyze + * @for p5.FFT + * @param {Number} [bins] Must be a power of two between + * 16 and 1024. Defaults to 1024. + * @param {Number} [scale] If "dB," returns decibel + * float measurements between + * -140 and 0 (max). + * Otherwise returns integers from 0-255. + * @return {Array} spectrum Array of energy (amplitude/volume) + * values across the frequency spectrum. + * Lowest energy (silence) = 0, highest + * possible is 255. + * @example + *
    + * let osc, fft; + * + * function setup(){ + * let cnv = createCanvas(100,100); + * cnv.mousePressed(startSound); + * osc = new p5.Oscillator(); + * osc.amp(0); + * fft = new p5.FFT(); + * } + * + * function draw(){ + * background(220); + * + * let freq = map(mouseX, 0, windowWidth, 20, 10000); + * freq = constrain(freq, 1, 20000); + * osc.freq(freq); + * + * let spectrum = fft.analyze(); + * noStroke(); + * fill(255, 0, 255); + * for (let i = 0; i< spectrum.length; i++){ + * let x = map(i, 0, spectrum.length, 0, width); + * let h = -height + map(spectrum[i], 0, 255, height, 0); + * rect(x, height, width / spectrum.length, h ); + * } + * + * stroke(255); + * if (!osc.started) { + * text('tap here and drag to change frequency', 10, 20, width - 20); + * } else { + * text(round(freq)+'Hz', 10, 20); + * } + * } + * + * function startSound() { + * osc.start(); + * osc.amp(0.5, 0.2); + * } + * + * function mouseReleased() { + * osc.amp(0, 0.2); + * } + *
    + * + * + */ + + }, { + key: "analyze", + value: function analyze() { + var mode; + + for (var i = 0; i < arguments.length; i++) { + if (typeof arguments[i] === 'number') { + this.bins = arguments[i]; + this.analyser.fftSize = this.bins * 2; + } + + if (typeof arguments[i] === 'string') { + mode = arguments[i]; + } + } + + if (mode && mode.toLowerCase() === 'db') { + freqToFloat(this); + this.analyser.getFloatFrequencyData(this.freqDomain); + return this.freqDomain; + } else { + freqToInt(this, this.freqDomain); + this.analyser.getByteFrequencyData(this.freqDomain); + var normalArray = Array.apply([], this.freqDomain); + return normalArray; + } + } + /** + * Returns the amount of energy (volume) at a specific + * + * frequency, or the average amount of energy between two + * frequencies. Accepts Number(s) corresponding + * to frequency (in Hz), or a "string" corresponding to predefined + * frequency ranges ("bass", "lowMid", "mid", "highMid", "treble"). + * Returns a range between 0 (no energy/volume at that frequency) and + * 255 (maximum energy). + * NOTE: analyze() must be called prior to getEnergy(). analyze() + * tells the FFT to analyze frequency data, and getEnergy() uses + * the results to determine the value at a specific frequency or + * range of frequencies.

    + * + * @method getEnergy + * @for p5.FFT + * @param {Number|String} frequency1 Will return a value representing + * energy at this frequency. Alternately, + * the strings "bass", "lowMid" "mid", + * "highMid", and "treble" will return + * predefined frequency ranges. + * @param {Number} [frequency2] If a second frequency is given, + * will return average amount of + * energy that exists between the + * two frequencies. + * @return {Number} Energy Energy (volume/amplitude) from + * 0 and 255. + * + */ + + }, { + key: "getEnergy", + value: function getEnergy(frequency1, frequency2) { + var nyquist = master.audiocontext.sampleRate / 2; + + if (frequency1 === 'bass') { + frequency1 = this.bass[0]; + frequency2 = this.bass[1]; + } else if (frequency1 === 'lowMid') { + frequency1 = this.lowMid[0]; + frequency2 = this.lowMid[1]; + } else if (frequency1 === 'mid') { + frequency1 = this.mid[0]; + frequency2 = this.mid[1]; + } else if (frequency1 === 'highMid') { + frequency1 = this.highMid[0]; + frequency2 = this.highMid[1]; + } else if (frequency1 === 'treble') { + frequency1 = this.treble[0]; + frequency2 = this.treble[1]; + } + + if (typeof frequency1 !== 'number') { + throw 'invalid input for getEnergy()'; + } else if (!frequency2) { + var index = Math.round(frequency1 / nyquist * this.freqDomain.length); + return this.freqDomain[index]; + } else if (frequency1 && frequency2) { + if (frequency1 > frequency2) { + var swap = frequency2; + frequency2 = frequency1; + frequency1 = swap; + } + + var lowIndex = Math.round(frequency1 / nyquist * this.freqDomain.length); + var highIndex = Math.round(frequency2 / nyquist * this.freqDomain.length); + var total = 0; + var numFrequencies = 0; + + for (var i = lowIndex; i <= highIndex; i++) { + total += this.freqDomain[i]; + numFrequencies += 1; + } + + + var toReturn = total / numFrequencies; + return toReturn; + } else { + throw 'invalid input for getEnergy()'; + } + } + + }, { + key: "getFreq", + value: function getFreq(freq1, freq2) { + console.log('getFreq() is deprecated. Please use getEnergy() instead.'); + var x = this.getEnergy(freq1, freq2); + return x; + } + /** + * Returns the + * + * spectral centroid of the input signal. + * NOTE: analyze() must be called prior to getCentroid(). Analyze() + * tells the FFT to analyze frequency data, and getCentroid() uses + * the results determine the spectral centroid.

    + * + * @method getCentroid + * @for p5.FFT + * @return {Number} Spectral Centroid Frequency of the spectral centroid in Hz. + * + * + * @example + *
    + * function setup(){ + * cnv = createCanvas(100,100); + * cnv.mousePressed(userStartAudio); + * sound = new p5.AudioIn(); + * sound.start(); + * fft = new p5.FFT(); + * sound.connect(fft); + *} + * + *function draw() { + * if (getAudioContext().state !== 'running') { + * background(220); + * text('tap here and enable mic to begin', 10, 20, width - 20); + * return; + * } + * let centroidplot = 0.0; + * let spectralCentroid = 0; + * + * background(0); + * stroke(0,255,0); + * let spectrum = fft.analyze(); + * fill(0,255,0); // spectrum is green + * + * //draw the spectrum + * for (let i = 0; i < spectrum.length; i++){ + * let x = map(log(i), 0, log(spectrum.length), 0, width); + * let h = map(spectrum[i], 0, 255, 0, height); + * let rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length)); + * rect(x, height, rectangle_width, -h ) + * } + * let nyquist = 22050; + * + * // get the centroid + * spectralCentroid = fft.getCentroid(); + * + * // the mean_freq_index calculation is for the display. + * let mean_freq_index = spectralCentroid/(nyquist/spectrum.length); + * + * centroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width); + * + * stroke(255,0,0); // the line showing where the centroid is will be red + * + * rect(centroidplot, 0, width / spectrum.length, height) + * noStroke(); + * fill(255,255,255); // text is white + * text('centroid: ', 10, 20); + * text(round(spectralCentroid)+' Hz', 10, 40); + *} + *
    + */ + + }, { + key: "getCentroid", + value: function getCentroid() { + var nyquist = master.audiocontext.sampleRate / 2; + var cumulative_sum = 0; + var centroid_normalization = 0; + + for (var i = 0; i < this.freqDomain.length; i++) { + cumulative_sum += i * this.freqDomain[i]; + centroid_normalization += this.freqDomain[i]; + } + + var mean_freq_index = 0; + + if (centroid_normalization !== 0) { + mean_freq_index = cumulative_sum / centroid_normalization; + } + + var spec_centroid_freq = mean_freq_index * (nyquist / this.freqDomain.length); + return spec_centroid_freq; + } + /** + * Smooth FFT analysis by averaging with the last analysis frame. + * + * @method smooth + * @param {Number} smoothing 0.0 < smoothing < 1.0. + * Defaults to 0.8. + */ + + }, { + key: "smooth", + value: function smooth(s) { + if (typeof s !== 'undefined') { + this.smoothing = s; + } + + return this.smoothing; + } + }, { + key: "dispose", + value: function dispose() { + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + + if (this.analyser) { + this.analyser.disconnect(); + delete this.analyser; + } + } + /** + * Returns an array of average amplitude values for a given number + * of frequency bands split equally. N defaults to 16. + * NOTE: analyze() must be called prior to linAverages(). Analyze() + * tells the FFT to analyze frequency data, and linAverages() uses + * the results to group them into a smaller set of averages.

    + * + * @method linAverages + * @for p5.FFT + * @param {Number} N Number of returned frequency groups + * @return {Array} linearAverages Array of average amplitude values for each group + */ + + }, { + key: "linAverages", + value: function linAverages(_N) { + var N = _N || 16; + + var spectrum = this.freqDomain; + var spectrumLength = spectrum.length; + var spectrumStep = Math.floor(spectrumLength / N); + var linearAverages = new Array(N); + + var groupIndex = 0; + + for (var specIndex = 0; specIndex < spectrumLength; specIndex++) { + linearAverages[groupIndex] = linearAverages[groupIndex] !== undefined ? (linearAverages[groupIndex] + spectrum[specIndex]) / 2 : spectrum[specIndex]; + + if (specIndex % spectrumStep === spectrumStep - 1) { + groupIndex++; + } + } + + return linearAverages; + } + /** + * Returns an array of average amplitude values of the spectrum, for a given + * set of + * Octave Bands + * NOTE: analyze() must be called prior to logAverages(). Analyze() + * tells the FFT to analyze frequency data, and logAverages() uses + * the results to group them into a smaller set of averages.

    + * + * @method logAverages + * @for p5.FFT + * @param {Array} octaveBands Array of Octave Bands objects for grouping + * @return {Array} logAverages Array of average amplitude values for each group + */ + + }, { + key: "logAverages", + value: function logAverages(octaveBands) { + var nyquist = master.audiocontext.sampleRate / 2; + var spectrum = this.freqDomain; + var spectrumLength = spectrum.length; + var logAverages = new Array(octaveBands.length); + + var octaveIndex = 0; + + for (var specIndex = 0; specIndex < spectrumLength; specIndex++) { + var specIndexFrequency = Math.round(specIndex * nyquist / this.freqDomain.length); + + if (specIndexFrequency > octaveBands[octaveIndex].hi) { + octaveIndex++; + } + + logAverages[octaveIndex] = logAverages[octaveIndex] !== undefined ? (logAverages[octaveIndex] + spectrum[specIndex]) / 2 : spectrum[specIndex]; + } + + return logAverages; + } + /** + * Calculates and Returns the 1/N + * Octave Bands + * N defaults to 3 and minimum central frequency to 15.625Hz. + * (1/3 Octave Bands ~= 31 Frequency Bands) + * Setting fCtr0 to a central value of a higher octave will ignore the lower bands + * and produce less frequency groups. + * + * @method getOctaveBands + * @for p5.FFT + * @param {Number} N Specifies the 1/N type of generated octave bands + * @param {Number} fCtr0 Minimum central frequency for the lowest band + * @return {Array} octaveBands Array of octave band objects with their bounds + */ + + }, { + key: "getOctaveBands", + value: function getOctaveBands(_N, _fCtr0) { + var N = _N || 3; + + var fCtr0 = _fCtr0 || 15.625; + + var octaveBands = []; + var lastFrequencyBand = { + lo: fCtr0 / Math.pow(2, 1 / (2 * N)), + ctr: fCtr0, + hi: fCtr0 * Math.pow(2, 1 / (2 * N)) + }; + octaveBands.push(lastFrequencyBand); + var nyquist = master.audiocontext.sampleRate / 2; + + while (lastFrequencyBand.hi < nyquist) { + var newFrequencyBand = {}; + newFrequencyBand.lo = lastFrequencyBand.hi; + newFrequencyBand.ctr = lastFrequencyBand.ctr * Math.pow(2, 1 / N); + newFrequencyBand.hi = newFrequencyBand.ctr * Math.pow(2, 1 / (2 * N)); + octaveBands.push(newFrequencyBand); + lastFrequencyBand = newFrequencyBand; + } + + return octaveBands; + } + }]); + + return FFT; +}(); + + +function freqToFloat(fft) { + if (fft.freqDomain instanceof Float32Array === false) { + fft.freqDomain = new Float32Array(fft.analyser.frequencyBinCount); + } +} + +function freqToInt(fft) { + if (fft.freqDomain instanceof Uint8Array === false) { + fft.freqDomain = new Uint8Array(fft.analyser.frequencyBinCount); + } +} + +function timeToFloat(fft) { + if (fft.timeDomain instanceof Float32Array === false) { + fft.timeDomain = new Float32Array(fft.analyser.frequencyBinCount); + } +} + +function timeToInt(fft) { + if (fft.timeDomain instanceof Uint8Array === false) { + fft.timeDomain = new Uint8Array(fft.analyser.frequencyBinCount); + } +} + + var fft = (fft_FFT); +var Add = __webpack_require__(4); +var Add_default = __webpack_require__.n(Add); + +var Multiply = __webpack_require__(1); +var Multiply_default = __webpack_require__.n(Multiply); + +var Scale = __webpack_require__(8); +var Scale_default = __webpack_require__.n(Scale); + +function oscillator_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { oscillator_typeof = function _typeof(obj) { return typeof obj; }; } else { oscillator_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return oscillator_typeof(obj); } + +function _possibleConstructorReturn(self, call) { if (call && (oscillator_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function oscillator_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function oscillator_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function oscillator_createClass(Constructor, protoProps, staticProps) { if (protoProps) oscillator_defineProperties(Constructor.prototype, protoProps); if (staticProps) oscillator_defineProperties(Constructor, staticProps); return Constructor; } + + + + + + +function sigChain(o, mathObj, thisChain, nextChain, type) { + var chainSource = o.oscillator; + + for (var i in o.mathOps) { + if (o.mathOps[i] instanceof type) { + chainSource.disconnect(); + o.mathOps[i].dispose(); + thisChain = i; + + if (thisChain < o.mathOps.length - 2) { + nextChain = o.mathOps[i + 1]; + } + } + } + + if (thisChain === o.mathOps.length - 1) { + o.mathOps.push(nextChain); + } + + + if (i > 0) { + chainSource = o.mathOps[i - 1]; + } + + chainSource.disconnect(); + chainSource.connect(mathObj); + mathObj.connect(nextChain); + o.mathOps[thisChain] = mathObj; + return o; +} +/** + *

    Creates a signal that oscillates between -1.0 and 1.0. + * By default, the oscillation takes the form of a sinusoidal + * shape ('sine'). Additional types include 'triangle', + * 'sawtooth' and 'square'. The frequency defaults to + * 440 oscillations per second (440Hz, equal to the pitch of an + * 'A' note).

    + * + *

    Set the type of oscillation with setType(), or by instantiating a + * specific oscillator: p5.SinOsc, p5.TriOsc, p5.SqrOsc, or p5.SawOsc. + *

    + * + * @class p5.Oscillator + * @constructor + * @param {Number} [freq] frequency defaults to 440Hz + * @param {String} [type] type of oscillator. Options: + * 'sine' (default), 'triangle', + * 'sawtooth', 'square' + * @example + *
    + * let osc, playing, freq, amp; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playOscillator); + * osc = new p5.Oscillator('sine'); + * } + * + * function draw() { + * background(220) + * freq = constrain(map(mouseX, 0, width, 100, 500), 100, 500); + * amp = constrain(map(mouseY, height, 0, 0, 1), 0, 1); + * + * text('tap to play', 20, 20); + * text('freq: ' + freq, 20, 40); + * text('amp: ' + amp, 20, 60); + * + * if (playing) { + * // smooth the transitions by 0.1 seconds + * osc.freq(freq, 0.1); + * osc.amp(amp, 0.1); + * } + * } + * + * function playOscillator() { + * // starting an oscillator on a user gesture will enable audio + * // in browsers that have a strict autoplay policy. + * // See also: userStartAudio(); + * osc.start(); + * playing = true; + * } + * + * function mouseReleased() { + * // ramp amplitude to 0 over 0.5 seconds + * osc.amp(0, 0.5); + * playing = false; + * } + *
    + */ + + +var oscillator_Oscillator = +function () { + function Oscillator(freq, type) { + oscillator_classCallCheck(this, Oscillator); + + if (typeof freq === 'string') { + var f = type; + type = freq; + freq = f; + } + + if (typeof type === 'number') { + var _f = type; + type = freq; + freq = _f; + } + + this.started = false; + + this.phaseAmount = undefined; + this.oscillator = master.audiocontext.createOscillator(); + this.f = freq || 440.0; + + this.oscillator.type = type || 'sine'; + this.oscillator.frequency.setValueAtTime(this.f, master.audiocontext.currentTime); + + this.output = master.audiocontext.createGain(); + this._freqMods = []; + + this.output.gain.value = 0.5; + this.output.gain.setValueAtTime(0.5, master.audiocontext.currentTime); + this.oscillator.connect(this.output); + + this.panPosition = 0.0; + this.connection = master.input; + + this.panner = new panner_0(this.output, this.connection, 1); + + this.mathOps = [this.output]; + + master.soundArray.push(this); + + this.fade = this.amp; + } + /** + * Start an oscillator. + * + * Starting an oscillator on a user gesture will enable audio in browsers + * that have a strict autoplay policy, including Chrome and most mobile + * devices. See also: `userStartAudio()`. + * + * @method start + * @for p5.Oscillator + * @param {Number} [time] startTime in seconds from now. + * @param {Number} [frequency] frequency in Hz. + */ + + + oscillator_createClass(Oscillator, [{ + key: "start", + value: function start(time, f) { + if (this.started) { + var now = master.audiocontext.currentTime; + this.stop(now); + } + + if (!this.started) { + var freq = f || this.f; + var type = this.oscillator.type; + + if (this.oscillator) { + this.oscillator.disconnect(); + delete this.oscillator; + } + + + this.oscillator = master.audiocontext.createOscillator(); + this.oscillator.frequency.value = Math.abs(freq); + this.oscillator.type = type; + + this.oscillator.connect(this.output); + time = time || 0; + this.oscillator.start(time + master.audiocontext.currentTime); + this.freqNode = this.oscillator.frequency; + + for (var i in this._freqMods) { + if (typeof this._freqMods[i].connect !== 'undefined') { + this._freqMods[i].connect(this.oscillator.frequency); + } + } + + this.started = true; + } + } + /** + * Stop an oscillator. Accepts an optional parameter + * to determine how long (in seconds from now) until the + * oscillator stops. + * + * @method stop + * @for p5.Oscillator + * @param {Number} secondsFromNow Time, in seconds from now. + */ + + }, { + key: "stop", + value: function stop(time) { + if (this.started) { + var t = time || 0; + var now = master.audiocontext.currentTime; + this.oscillator.stop(t + now); + this.started = false; + } + } + /** + * Set the amplitude between 0 and 1.0. Or, pass in an object + * such as an oscillator to modulate amplitude with an audio signal. + * + * @method amp + * @for p5.Oscillator + * @param {Number|Object} vol between 0 and 1.0 + * or a modulating signal/oscillator + * @param {Number} [rampTime] create a fade that lasts rampTime + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + * @return {AudioParam} gain If no value is provided, + * returns the Web Audio API + * AudioParam that controls + * this oscillator's + * gain/amplitude/volume) + */ + + }, { + key: "amp", + value: function amp(vol) { + var rampTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var tFromNow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + if (typeof vol === 'number') { + var now = master.audiocontext.currentTime; + this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); + } else if (vol) { + vol.connect(this.output.gain); + } else { + return this.output.gain; + } + } + /** + * Returns the value of output gain + * + * @method getAmp + * @for p5.Oscillator + * + * @returns {number} Amplitude value between 0.0 and 1.0 + */ + + }, { + key: "getAmp", + value: function getAmp() { + return this.output.gain.value; + } + /** + * Set frequency of an oscillator to a value. Or, pass in an object + * such as an oscillator to modulate the frequency with an audio signal. + * + * @method freq + * @for p5.Oscillator + * @param {Number|Object} Frequency Frequency in Hz + * or modulating signal/oscillator + * @param {Number} [rampTime] Ramp time (in seconds) + * @param {Number} [timeFromNow] Schedule this event to happen + * at x seconds from now + * @return {AudioParam} Frequency If no value is provided, + * returns the Web Audio API + * AudioParam that controls + * this oscillator's frequency + * @example + *
    + * let osc; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playOscillator); + * osc = new p5.Oscillator(300); + * background(220); + * text('tap to play', 20, 20); + * } + * + * function playOscillator() { + * osc.start(); + * osc.amp(0.5); + * // start at 700Hz + * osc.freq(700); + * // ramp to 60Hz over 0.7 seconds + * osc.freq(60, 0.7); + * osc.amp(0, 0.1, 0.7); + * } + *
    + */ + + }, { + key: "freq", + value: function freq(val) { + var rampTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var tFromNow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + if (typeof val === 'number' && !isNaN(val)) { + this.f = val; + var now = master.audiocontext.currentTime; + + if (rampTime === 0) { + this.oscillator.frequency.setValueAtTime(val, tFromNow + now); + } else { + if (val > 0) { + this.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); + } else { + this.oscillator.frequency.linearRampToValueAtTime(val, tFromNow + rampTime + now); + } + } + + + if (this.phaseAmount) { + this.phase(this.phaseAmount); + } + } else if (val) { + if (val.output) { + val = val.output; + } + + val.connect(this.oscillator.frequency); + + this._freqMods.push(val); + } else { + return this.oscillator.frequency; + } + } + /** + * Returns the value of frequency of oscillator + * + * @method getFreq + * @for p5.Oscillator + * @returns {number} Frequency of oscillator in Hertz + */ + + }, { + key: "getFreq", + value: function getFreq() { + return this.oscillator.frequency.value; + } + /** + * Set type to 'sine', 'triangle', 'sawtooth' or 'square'. + * + * @method setType + * @for p5.Oscillator + * @param {String} type 'sine', 'triangle', 'sawtooth' or 'square'. + */ + + }, { + key: "setType", + value: function setType(type) { + this.oscillator.type = type; + } + /** + * Returns current type of oscillator eg. 'sine', 'triangle', 'sawtooth' or 'square'. + * + * @method getType + * @for p5.Oscillator + * @returns {String} type of oscillator eg . 'sine', 'triangle', 'sawtooth' or 'square'. + */ + + }, { + key: "getType", + value: function getType() { + return this.oscillator.type; + } + /** + * Connect to a p5.sound / Web Audio object. + * + * @method connect + * @for p5.Oscillator + * @param {Object} unit A p5.sound or Web Audio object + */ + + }, { + key: "connect", + value: function connect(unit) { + if (!unit) { + this.panner.connect(master.input); + } else if (unit.hasOwnProperty('input')) { + this.panner.connect(unit.input); + this.connection = unit.input; + } else { + this.panner.connect(unit); + this.connection = unit; + } + } + /** + * Disconnect all outputs + * + * @method disconnect + * @for p5.Oscillator + */ + + }, { + key: "disconnect", + value: function disconnect() { + if (this.output) { + this.output.disconnect(); + } + + if (this.panner) { + this.panner.disconnect(); + + if (this.output) { + this.output.connect(this.panner); + } + } + + this.oscMods = []; + } + /** + * Pan between Left (-1) and Right (1) + * + * @method pan + * @for p5.Oscillator + * @param {Number} panning Number between -1 and 1 + * @param {Number} timeFromNow schedule this event to happen + * seconds from now + */ + + }, { + key: "pan", + value: function pan(pval, tFromNow) { + this.panPosition = pval; + this.panner.pan(pval, tFromNow); + } + /** + * Returns the current value of panPosition , between Left (-1) and Right (1) + * + * @method getPan + * @for p5.Oscillator + * + * @returns {number} panPosition of oscillator , between Left (-1) and Right (1) + */ + + }, { + key: "getPan", + value: function getPan() { + return this.panPosition; + } + + }, { + key: "dispose", + value: function dispose() { + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + + if (this.oscillator) { + var now = master.audiocontext.currentTime; + this.stop(now); + this.disconnect(); + this.panner = null; + this.oscillator = null; + } + + + if (this.osc2) { + this.osc2.dispose(); + } + } + /** + * Set the phase of an oscillator between 0.0 and 1.0. + * In this implementation, phase is a delay time + * based on the oscillator's current frequency. + * + * @method phase + * @for p5.Oscillator + * @param {Number} phase float between 0.0 and 1.0 + */ + + }, { + key: "phase", + value: function phase(p) { + var delayAmt = p5.prototype.map(p, 0, 1.0, 0, 1 / this.f); + var now = master.audiocontext.currentTime; + this.phaseAmount = p; + + if (!this.dNode) { + this.dNode = master.audiocontext.createDelay(); + + this.oscillator.disconnect(); + this.oscillator.connect(this.dNode); + this.dNode.connect(this.output); + } + + + this.dNode.delayTime.setValueAtTime(delayAmt, now); + } + /** + * Add a value to the p5.Oscillator's output amplitude, + * and return the oscillator. Calling this method again + * will override the initial add() with a new value. + * + * @method add + * @for p5.Oscillator + * @param {Number} number Constant number to add + * @return {p5.Oscillator} Oscillator Returns this oscillator + * with scaled output + * + */ + + }, { + key: "add", + value: function add(num) { + var add = new Add_default.a(num); + var thisChain = this.mathOps.length - 1; + var nextChain = this.output; + return sigChain(this, add, thisChain, nextChain, Add_default.a); + } + /** + * Multiply the p5.Oscillator's output amplitude + * by a fixed value (i.e. turn it up!). Calling this method + * again will override the initial mult() with a new value. + * + * @method mult + * @for p5.Oscillator + * @param {Number} number Constant number to multiply + * @return {p5.Oscillator} Oscillator Returns this oscillator + * with multiplied output + */ + + }, { + key: "mult", + value: function mult(num) { + var mult = new Multiply_default.a(num); + var thisChain = this.mathOps.length - 1; + var nextChain = this.output; + return sigChain(this, mult, thisChain, nextChain, Multiply_default.a); + } + /** + * Scale this oscillator's amplitude values to a given + * range, and return the oscillator. Calling this method + * again will override the initial scale() with new values. + * + * @method scale + * @for p5.Oscillator + * @param {Number} inMin input range minumum + * @param {Number} inMax input range maximum + * @param {Number} outMin input range minumum + * @param {Number} outMax input range maximum + * @return {p5.Oscillator} Oscillator Returns this oscillator + * with scaled output + */ + + }, { + key: "scale", + value: function scale(inMin, inMax, outMin, outMax) { + var mapOutMin, mapOutMax; + + if (arguments.length === 4) { + mapOutMin = p5.prototype.map(outMin, inMin, inMax, 0, 1) - 0.5; + + mapOutMax = p5.prototype.map(outMax, inMin, inMax, 0, 1) - 0.5; + } else { + mapOutMin = arguments[0]; + mapOutMax = arguments[1]; + } + + var scale = new Scale_default.a(mapOutMin, mapOutMax); + var thisChain = this.mathOps.length - 1; + var nextChain = this.output; + return sigChain(this, scale, thisChain, nextChain, Scale_default.a); + } + }]); + + return Oscillator; +}(); + +/** + * Constructor: new p5.SinOsc(). + * This creates a Sine Wave Oscillator and is + * equivalent to new p5.Oscillator('sine') + * or creating a p5.Oscillator and then calling + * its method setType('sine'). + * See p5.Oscillator for methods. + * + * @class p5.SinOsc + * @constructor + * @extends p5.Oscillator + * @param {Number} [freq] Set the frequency + */ + + +var SinOsc = +function (_Oscillator) { + _inherits(SinOsc, _Oscillator); + + function SinOsc(freq) { + oscillator_classCallCheck(this, SinOsc); + + return _possibleConstructorReturn(this, _getPrototypeOf(SinOsc).call(this, freq, 'sine')); + } + + return SinOsc; +}(oscillator_Oscillator); +/** + * Constructor: new p5.TriOsc(). + * This creates a Triangle Wave Oscillator and is + * equivalent to new p5.Oscillator('triangle') + * or creating a p5.Oscillator and then calling + * its method setType('triangle'). + * See p5.Oscillator for methods. + * + * @class p5.TriOsc + * @constructor + * @extends p5.Oscillator + * @param {Number} [freq] Set the frequency + */ + + +var TriOsc = +function (_Oscillator2) { + _inherits(TriOsc, _Oscillator2); + + function TriOsc(freq) { + oscillator_classCallCheck(this, TriOsc); + + return _possibleConstructorReturn(this, _getPrototypeOf(TriOsc).call(this, freq, 'triangle')); + } + + return TriOsc; +}(oscillator_Oscillator); +/** + * Constructor: new p5.SawOsc(). + * This creates a SawTooth Wave Oscillator and is + * equivalent to new p5.Oscillator('sawtooth') + * or creating a p5.Oscillator and then calling + * its method setType('sawtooth'). + * See p5.Oscillator for methods. + * + * @class p5.SawOsc + * @constructor + * @extends p5.Oscillator + * @param {Number} [freq] Set the frequency + */ + + +var SawOsc = +function (_Oscillator3) { + _inherits(SawOsc, _Oscillator3); + + function SawOsc(freq) { + oscillator_classCallCheck(this, SawOsc); + + return _possibleConstructorReturn(this, _getPrototypeOf(SawOsc).call(this, freq, 'sawtooth')); + } + + return SawOsc; +}(oscillator_Oscillator); +/** + * Constructor: new p5.SqrOsc(). + * This creates a Square Wave Oscillator and is + * equivalent to new p5.Oscillator('square') + * or creating a p5.Oscillator and then calling + * its method setType('square'). + * See p5.Oscillator for methods. + * + * @class p5.SqrOsc + * @constructor + * @extends p5.Oscillator + * @param {Number} [freq] Set the frequency + */ + + +var SqrOsc = +function (_Oscillator4) { + _inherits(SqrOsc, _Oscillator4); + + function SqrOsc(freq) { + oscillator_classCallCheck(this, SqrOsc); + + return _possibleConstructorReturn(this, _getPrototypeOf(SqrOsc).call(this, freq, 'square')); + } + + return SqrOsc; +}(oscillator_Oscillator); + + var oscillator = (oscillator_Oscillator); + +var TimelineSignal = __webpack_require__(7); +var TimelineSignal_default = __webpack_require__.n(TimelineSignal); + + + + + + +/** + *

    Envelopes are pre-defined amplitude distribution over time. + * Typically, envelopes are used to control the output volume + * of an object, a series of fades referred to as Attack, Decay, + * Sustain and Release ( + * ADSR + * ). Envelopes can also control other Web Audio Parameters—for example, a p5.Envelope can + * control an Oscillator's frequency like this: osc.freq(env).

    + *

    Use setRange to change the attack/release level. + * Use setADSR to change attackTime, decayTime, sustainPercent and releaseTime.

    + *

    Use the play method to play the entire envelope, + * the ramp method for a pingable trigger, + * or triggerAttack/ + * triggerRelease to trigger noteOn/noteOff.

    + * + * @class p5.Envelope + * @constructor + * @example + *
    + * let t1 = 0.1; // attack time in seconds + * let l1 = 0.7; // attack level 0.0 to 1.0 + * let t2 = 0.3; // decay time in seconds + * let l2 = 0.1; // decay level 0.0 to 1.0 + * + * let env; + * let triOsc; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * background(220); + * text('tap to play', 20, 20); + * cnv.mousePressed(playSound); + * + * env = new p5.Envelope(t1, l1, t2, l2); + * triOsc = new p5.Oscillator('triangle'); + * } + * + * function playSound() { + * // starting the oscillator ensures that audio is enabled. + * triOsc.start(); + * env.play(triOsc); + * } + *
    + */ + +p5.Envelope = function (t1, l1, t2, l2, t3, l3) { + /** + * Time until envelope reaches attackLevel + * @property attackTime + */ + this.aTime = t1 || 0.1; + /** + * Level once attack is complete. + * @property attackLevel + */ + + this.aLevel = l1 || 1; + /** + * Time until envelope reaches decayLevel. + * @property decayTime + */ + + this.dTime = t2 || 0.5; + /** + * Level after decay. The envelope will sustain here until it is released. + * @property decayLevel + */ + + this.dLevel = l2 || 0; + /** + * Duration of the release portion of the envelope. + * @property releaseTime + */ + + this.rTime = t3 || 0; + /** + * Level at the end of the release. + * @property releaseLevel + */ + + this.rLevel = l3 || 0; + this._rampHighPercentage = 0.98; + this._rampLowPercentage = 0.02; + this.output = master.audiocontext.createGain(); + this.control = new TimelineSignal_default.a(); + + this._init(); + + + this.control.connect(this.output); + + this.connection = null; + + this.mathOps = [this.control]; + + this.isExponential = false; + + this.sourceToClear = null; + + this.wasTriggered = false; + + master.soundArray.push(this); +}; + + +p5.Envelope.prototype._init = function () { + var now = master.audiocontext.currentTime; + var t = now; + this.control.setTargetAtTime(0.00001, t, 0.001); + + this._setRampAD(this.aTime, this.dTime); +}; +/** + * Reset the envelope with a series of time/value pairs. + * + * @method set + * @for p5.Envelope + * @param {Number} attackTime Time (in seconds) before level + * reaches attackLevel + * @param {Number} attackLevel Typically an amplitude between + * 0.0 and 1.0 + * @param {Number} decayTime Time + * @param {Number} decayLevel Amplitude (In a standard ADSR envelope, + * decayLevel = sustainLevel) + * @param {Number} releaseTime Release Time (in seconds) + * @param {Number} releaseLevel Amplitude + * @example + *
    + * let attackTime; + * let l1 = 0.7; // attack level 0.0 to 1.0 + * let t2 = 0.3; // decay time in seconds + * let l2 = 0.1; // decay level 0.0 to 1.0 + * let l3 = 0.2; // release time in seconds + * + * let env, triOsc; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playSound); + * + * env = new p5.Envelope(); + * triOsc = new p5.Oscillator('triangle'); + * } + * + * function draw() { + * background(220); + * text('tap here to play', 5, 20); + * + * attackTime = map(mouseX, 0, width, 0.0, 1.0); + * text('attack time: ' + attackTime, 5, height - 20); + * } + * + * // mouseClick triggers envelope if over canvas + * function playSound() { + * env.set(attackTime, l1, t2, l2, l3); + * + * triOsc.start(); + * env.play(triOsc); + * } + *
    + * + */ + + +p5.Envelope.prototype.set = function (t1, l1, t2, l2, t3, l3) { + this.aTime = t1; + this.aLevel = l1; + this.dTime = t2 || 0; + this.dLevel = l2 || 0; + this.rTime = t3 || 0; + this.rLevel = l3 || 0; + + this._setRampAD(t1, t2); +}; +/** + * Set values like a traditional + * + * ADSR envelope + * . + * + * @method setADSR + * @for p5.Envelope + * @param {Number} attackTime Time (in seconds before envelope + * reaches Attack Level + * @param {Number} [decayTime] Time (in seconds) before envelope + * reaches Decay/Sustain Level + * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, + * where 1.0 = attackLevel, 0.0 = releaseLevel. + * The susRatio determines the decayLevel and the level at which the + * sustain portion of the envelope will sustain. + * For example, if attackLevel is 0.4, releaseLevel is 0, + * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is + * increased to 1.0 (using setRange), + * then decayLevel would increase proportionally, to become 0.5. + * @param {Number} [releaseTime] Time in seconds from now (defaults to 0) + * @example + *
    + * let attackLevel = 1.0; + * let releaseLevel = 0; + * + * let attackTime = 0.001; + * let decayTime = 0.2; + * let susPercent = 0.2; + * let releaseTime = 0.5; + * + * let env, triOsc; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playEnv); + * + * env = new p5.Envelope(); + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); + * triOsc.freq(220); + * } + * + * function draw() { + * background(220); + * text('tap here to play', 5, 20); + * attackTime = map(mouseX, 0, width, 0, 1.0); + * text('attack time: ' + attackTime, 5, height - 40); + * } + * + * function playEnv() { + * triOsc.start(); + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.play(); + * } + *
    + */ + + +p5.Envelope.prototype.setADSR = function (aTime, dTime, sPercent, rTime) { + this.aTime = aTime; + this.dTime = dTime || 0; + + this.sPercent = sPercent || 0; + this.dLevel = typeof sPercent !== 'undefined' ? sPercent * (this.aLevel - this.rLevel) + this.rLevel : 0; + this.rTime = rTime || 0; + + this._setRampAD(aTime, dTime); +}; +/** + * Set max (attackLevel) and min (releaseLevel) of envelope. + * + * @method setRange + * @for p5.Envelope + * @param {Number} aLevel attack level (defaults to 1) + * @param {Number} rLevel release level (defaults to 0) + * @example + *
    + * let attackLevel = 1.0; + * let releaseLevel = 0; + * + * let attackTime = 0.001; + * let decayTime = 0.2; + * let susPercent = 0.2; + * let releaseTime = 0.5; + * + * let env, triOsc; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playEnv); + * + * env = new p5.Envelope(); + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); + * triOsc.freq(220); + * } + * + * function draw() { + * background(220); + * text('tap here to play', 5, 20); + * attackLevel = map(mouseY, height, 0, 0, 1.0); + * text('attack level: ' + attackLevel, 5, height - 20); + * } + * + * function playEnv() { + * triOsc.start(); + * env.setRange(attackLevel, releaseLevel); + * env.play(); + * } + *
    + */ + + +p5.Envelope.prototype.setRange = function (aLevel, rLevel) { + this.aLevel = aLevel || 1; + this.rLevel = rLevel || 0; +}; + + +p5.Envelope.prototype._setRampAD = function (t1, t2) { + this._rampAttackTime = this.checkExpInput(t1); + this._rampDecayTime = this.checkExpInput(t2); + var TCDenominator = 1.0; + + TCDenominator = Math.log(1.0 / this.checkExpInput(1.0 - this._rampHighPercentage)); + this._rampAttackTC = t1 / this.checkExpInput(TCDenominator); + TCDenominator = Math.log(1.0 / this._rampLowPercentage); + this._rampDecayTC = t2 / this.checkExpInput(TCDenominator); +}; + + +p5.Envelope.prototype.setRampPercentages = function (p1, p2) { + this._rampHighPercentage = this.checkExpInput(p1); + this._rampLowPercentage = this.checkExpInput(p2); + var TCDenominator = 1.0; + + TCDenominator = Math.log(1.0 / this.checkExpInput(1.0 - this._rampHighPercentage)); + this._rampAttackTC = this._rampAttackTime / this.checkExpInput(TCDenominator); + TCDenominator = Math.log(1.0 / this._rampLowPercentage); + this._rampDecayTC = this._rampDecayTime / this.checkExpInput(TCDenominator); +}; +/** + * Assign a parameter to be controlled by this envelope. + * If a p5.Sound object is given, then the p5.Envelope will control its + * output gain. If multiple inputs are provided, the env will + * control all of them. + * + * @method setInput + * @for p5.Envelope + * @param {Object} [...inputs] A p5.sound object or + * Web Audio Param. + */ + + +p5.Envelope.prototype.setInput = function () { + for (var i = 0; i < arguments.length; i++) { + this.connect(arguments[i]); + } +}; +/** + * Set whether the envelope ramp is linear (default) or exponential. + * Exponential ramps can be useful because we perceive amplitude + * and frequency logarithmically. + * + * @method setExp + * @for p5.Envelope + * @param {Boolean} isExp true is exponential, false is linear + */ + + +p5.Envelope.prototype.setExp = function (isExp) { + this.isExponential = isExp; +}; + + +p5.Envelope.prototype.checkExpInput = function (value) { + if (value <= 0) { + value = 0.00000001; + } + + return value; +}; +/** + *

    Play tells the envelope to start acting on a given input. + * If the input is a p5.sound object (i.e. AudioIn, Oscillator, + * SoundFile), then Envelope will control its output volume. + * Envelopes can also be used to control any + * Web Audio Audio Param.

    + * + * @method play + * @for p5.Envelope + * @param {Object} unit A p5.sound object or + * Web Audio Param. + * @param {Number} [startTime] time from now (in seconds) at which to play + * @param {Number} [sustainTime] time to sustain before releasing the envelope + * @example + *
    + * let attackLevel = 1.0; + * let releaseLevel = 0; + * + * let attackTime = 0.001; + * let decayTime = 0.2; + * let susPercent = 0.2; + * let releaseTime = 0.5; + * + * let env, triOsc; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playEnv); + * + * env = new p5.Envelope(); + * triOsc = new p5.Oscillator('triangle'); + * triOsc.amp(env); + * triOsc.freq(220); + * triOsc.start(); + * } + * + * function draw() { + * background(220); + * text('tap here to play', 5, 20); + * attackTime = map(mouseX, 0, width, 0, 1.0); + * attackLevel = map(mouseY, height, 0, 0, 1.0); + * text('attack time: ' + attackTime, 5, height - 40); + * text('attack level: ' + attackLevel, 5, height - 20); + * } + * + * function playEnv() { + * // ensure that audio is enabled + * userStartAudio(); + * + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.setRange(attackLevel, releaseLevel); + * env.play(); + * } + *
    + */ + + +p5.Envelope.prototype.play = function (unit, secondsFromNow, susTime) { + var tFromNow = secondsFromNow || 0; + + if (unit) { + if (this.connection !== unit) { + this.connect(unit); + } + } + + this.triggerAttack(unit, tFromNow); + this.triggerRelease(unit, tFromNow + this.aTime + this.dTime + ~~susTime); +}; +/** + * Trigger the Attack, and Decay portion of the Envelope. + * Similar to holding down a key on a piano, but it will + * hold the sustain level until you let go. Input can be + * any p5.sound object, or a + * Web Audio Param. + * + * @method triggerAttack + * @for p5.Envelope + * @param {Object} unit p5.sound Object or Web Audio Param + * @param {Number} secondsFromNow time from now (in seconds) + * @example + *
    + * let attackTime = 0.001; + * let decayTime = 0.2; + * let susPercent = 0.3; + * let releaseTime = 0.4; + * let env, triOsc; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * background(220); + * textAlign(CENTER); + * textSize(10); + * text('tap to triggerAttack', width/2, height/2); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.setRange(1.0, 0.0); + * triOsc = new p5.Oscillator('triangle'); + * triOsc.freq(220); + * + * cnv.mousePressed(envAttack); + * } + * + * function envAttack() { + * background(0, 255, 255); + * text('release to release', width/2, height/2); + * + * // ensures audio is enabled. See also: `userStartAudio` + * triOsc.start(); + * + * env.triggerAttack(triOsc); + * } + * + * function mouseReleased() { + * background(220); + * text('tap to triggerAttack', width/2, height/2); + * + * env.triggerRelease(triOsc); + * } + *
    + */ + + +p5.Envelope.prototype.triggerAttack = function (unit, secondsFromNow) { + var now = master.audiocontext.currentTime; + var tFromNow = secondsFromNow || 0; + var t = now + tFromNow; + this.lastAttack = t; + this.wasTriggered = true; + + if (unit) { + if (this.connection !== unit) { + this.connect(unit); + } + } + + + var valToSet = this.control.getValueAtTime(t); + + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(valToSet), t); + } else { + this.control.linearRampToValueAtTime(valToSet, t); + } + + + t += this.aTime; + + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(this.aLevel), t); + valToSet = this.checkExpInput(this.control.getValueAtTime(t)); + this.control.cancelScheduledValues(t); + this.control.exponentialRampToValueAtTime(valToSet, t); + } else { + this.control.linearRampToValueAtTime(this.aLevel, t); + valToSet = this.control.getValueAtTime(t); + this.control.cancelScheduledValues(t); + this.control.linearRampToValueAtTime(valToSet, t); + } + + + t += this.dTime; + + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(this.dLevel), t); + valToSet = this.checkExpInput(this.control.getValueAtTime(t)); + this.control.cancelScheduledValues(t); + this.control.exponentialRampToValueAtTime(valToSet, t); + } else { + this.control.linearRampToValueAtTime(this.dLevel, t); + valToSet = this.control.getValueAtTime(t); + this.control.cancelScheduledValues(t); + this.control.linearRampToValueAtTime(valToSet, t); + } +}; +/** + * Trigger the Release of the Envelope. This is similar to releasing + * the key on a piano and letting the sound fade according to the + * release level and release time. + * + * @method triggerRelease + * @for p5.Envelope + * @param {Object} unit p5.sound Object or Web Audio Param + * @param {Number} secondsFromNow time to trigger the release + * @example + *
    + * let attackTime = 0.001; + * let decayTime = 0.2; + * let susPercent = 0.3; + * let releaseTime = 0.4; + * let env, triOsc; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * background(220); + * textAlign(CENTER); + * textSize(10); + * text('tap to triggerAttack', width/2, height/2); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime, susPercent, releaseTime); + * env.setRange(1.0, 0.0); + * triOsc = new p5.Oscillator('triangle'); + * triOsc.freq(220); + * + * cnv.mousePressed(envAttack); + * } + * + * function envAttack() { + * background(0, 255, 255); + * text('release to release', width/2, height/2); + * + * // ensures audio is enabled. See also: `userStartAudio` + * triOsc.start(); + * + * env.triggerAttack(triOsc); + * } + * + * function mouseReleased() { + * background(220); + * text('tap to triggerAttack', width/2, height/2); + * + * env.triggerRelease(triOsc); + * } + *
    + */ + + +p5.Envelope.prototype.triggerRelease = function (unit, secondsFromNow) { + if (!this.wasTriggered) { + return; + } + + var now = master.audiocontext.currentTime; + var tFromNow = secondsFromNow || 0; + var t = now + tFromNow; + + if (unit) { + if (this.connection !== unit) { + this.connect(unit); + } + } + + + var valToSet = this.control.getValueAtTime(t); + + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(valToSet), t); + } else { + this.control.linearRampToValueAtTime(valToSet, t); + } + + + t += this.rTime; + + if (this.isExponential === true) { + this.control.exponentialRampToValueAtTime(this.checkExpInput(this.rLevel), t); + valToSet = this.checkExpInput(this.control.getValueAtTime(t)); + this.control.cancelScheduledValues(t); + this.control.exponentialRampToValueAtTime(valToSet, t); + } else { + this.control.linearRampToValueAtTime(this.rLevel, t); + valToSet = this.control.getValueAtTime(t); + this.control.cancelScheduledValues(t); + this.control.linearRampToValueAtTime(valToSet, t); + } + + this.wasTriggered = false; +}; +/** + * Exponentially ramp to a value using the first two + * values from setADSR(attackTime, decayTime) + * as + * time constants for simple exponential ramps. + * If the value is higher than current value, it uses attackTime, + * while a decrease uses decayTime. + * + * @method ramp + * @for p5.Envelope + * @param {Object} unit p5.sound Object or Web Audio Param + * @param {Number} secondsFromNow When to trigger the ramp + * @param {Number} v Target value + * @param {Number} [v2] Second target value + * @example + *
    + * let env, osc, amp; + * + * let attackTime = 0.001; + * let decayTime = 0.2; + * let attackLevel = 1; + * let decayLevel = 0; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * fill(0,255,0); + * noStroke(); + * + * env = new p5.Envelope(); + * env.setADSR(attackTime, decayTime); + * osc = new p5.Oscillator(); + * osc.amp(env); + * amp = new p5.Amplitude(); + * + * cnv.mousePressed(triggerRamp); + * } + * + * function triggerRamp() { + * // ensures audio is enabled. See also: `userStartAudio` + * osc.start(); + * + * env.ramp(osc, 0, attackLevel, decayLevel); + * } + * + * function draw() { + * background(20); + * text('tap to play', 10, 20); + * let h = map(amp.getLevel(), 0, 0.4, 0, height);; + * rect(0, height, width, -h); + * } + *
    + */ + + +p5.Envelope.prototype.ramp = function (unit, secondsFromNow, v1, v2) { + var now = master.audiocontext.currentTime; + var tFromNow = secondsFromNow || 0; + var t = now + tFromNow; + var destination1 = this.checkExpInput(v1); + var destination2 = typeof v2 !== 'undefined' ? this.checkExpInput(v2) : undefined; + + if (unit) { + if (this.connection !== unit) { + this.connect(unit); + } + } + + + var currentVal = this.checkExpInput(this.control.getValueAtTime(t)); + + if (destination1 > currentVal) { + this.control.setTargetAtTime(destination1, t, this._rampAttackTC); + t += this._rampAttackTime; + } + else if (destination1 < currentVal) { + this.control.setTargetAtTime(destination1, t, this._rampDecayTC); + t += this._rampDecayTime; + } + + + if (destination2 === undefined) return; + + if (destination2 > destination1) { + this.control.setTargetAtTime(destination2, t, this._rampAttackTC); + } + else if (destination2 < destination1) { + this.control.setTargetAtTime(destination2, t, this._rampDecayTC); + } +}; + +p5.Envelope.prototype.connect = function (unit) { + this.connection = unit; + + if (unit instanceof p5.Oscillator || unit instanceof p5.SoundFile || unit instanceof p5.AudioIn || unit instanceof p5.Reverb || unit instanceof p5.Noise || unit instanceof p5.Filter || unit instanceof p5.Delay) { + unit = unit.output.gain; + } + + if (unit instanceof AudioParam) { + unit.setValueAtTime(0, master.audiocontext.currentTime); + } + + this.output.connect(unit); +}; + +p5.Envelope.prototype.disconnect = function () { + if (this.output) { + this.output.disconnect(); + } +}; + +/** + * Add a value to the p5.Oscillator's output amplitude, + * and return the oscillator. Calling this method + * again will override the initial add() with new values. + * + * @method add + * @for p5.Envelope + * @param {Number} number Constant number to add + * @return {p5.Envelope} Envelope Returns this envelope + * with scaled output + */ + + +p5.Envelope.prototype.add = function (num) { + var add = new Add_default.a(num); + var thisChain = this.mathOps.length; + var nextChain = this.output; + return p5.prototype._mathChain(this, add, thisChain, nextChain, Add_default.a); +}; +/** + * Multiply the p5.Envelope's output amplitude + * by a fixed value. Calling this method + * again will override the initial mult() with new values. + * + * @method mult + * @for p5.Envelope + * @param {Number} number Constant number to multiply + * @return {p5.Envelope} Envelope Returns this envelope + * with scaled output + */ + + +p5.Envelope.prototype.mult = function (num) { + var mult = new Multiply_default.a(num); + var thisChain = this.mathOps.length; + var nextChain = this.output; + return p5.prototype._mathChain(this, mult, thisChain, nextChain, Multiply_default.a); +}; +/** + * Scale this envelope's amplitude values to a given + * range, and return the envelope. Calling this method + * again will override the initial scale() with new values. + * + * @method scale + * @for p5.Envelope + * @param {Number} inMin input range minumum + * @param {Number} inMax input range maximum + * @param {Number} outMin input range minumum + * @param {Number} outMax input range maximum + * @return {p5.Envelope} Envelope Returns this envelope + * with scaled output + */ + + +p5.Envelope.prototype.scale = function (inMin, inMax, outMin, outMax) { + var scale = new Scale_default.a(inMin, inMax, outMin, outMax); + var thisChain = this.mathOps.length; + var nextChain = this.output; + return p5.prototype._mathChain(this, scale, thisChain, nextChain, Scale_default.a); +}; + + +p5.Envelope.prototype.dispose = function () { + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + this.disconnect(); + + if (this.control) { + this.control.dispose(); + this.control = null; + } + + for (var i = 1; i < this.mathOps.length; i++) { + this.mathOps[i].dispose(); + } +}; + + +p5.Env = function (t1, l1, t2, l2, t3, l3) { + console.warn('WARNING: p5.Env is now deprecated and may be removed in future versions. ' + 'Please use the new p5.Envelope instead.'); + p5.Envelope.call(this, t1, l1, t2, l2, t3, l3); +}; + +p5.Env.prototype = Object.create(p5.Envelope.prototype); +var Envelope = p5.Envelope; + var envelope = (Envelope); +function noise_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { noise_typeof = function _typeof(obj) { return typeof obj; }; } else { noise_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return noise_typeof(obj); } + +function noise_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function noise_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function noise_createClass(Constructor, protoProps, staticProps) { if (protoProps) noise_defineProperties(Constructor.prototype, protoProps); if (staticProps) noise_defineProperties(Constructor, staticProps); return Constructor; } + +function noise_possibleConstructorReturn(self, call) { if (call && (noise_typeof(call) === "object" || typeof call === "function")) { return call; } return noise_assertThisInitialized(self); } + +function noise_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function noise_getPrototypeOf(o) { noise_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return noise_getPrototypeOf(o); } + +function noise_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) noise_setPrototypeOf(subClass, superClass); } + +function noise_setPrototypeOf(o, p) { noise_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return noise_setPrototypeOf(o, p); } + + + +var _whiteNoiseBuffer = function () { + var bufferSize = 2 * master.audiocontext.sampleRate; + var whiteBuffer = master.audiocontext.createBuffer(1, bufferSize, master.audiocontext.sampleRate); + var noiseData = whiteBuffer.getChannelData(0); + + for (var i = 0; i < bufferSize; i++) { + noiseData[i] = Math.random() * 2 - 1; + } + + whiteBuffer.type = 'white'; + return whiteBuffer; +}(); + +var _pinkNoiseBuffer = function () { + var bufferSize = 2 * master.audiocontext.sampleRate; + var pinkBuffer = master.audiocontext.createBuffer(1, bufferSize, master.audiocontext.sampleRate); + var noiseData = pinkBuffer.getChannelData(0); + var b0, b1, b2, b3, b4, b5, b6; + b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0.0; + + for (var i = 0; i < bufferSize; i++) { + var white = Math.random() * 2 - 1; + b0 = 0.99886 * b0 + white * 0.0555179; + b1 = 0.99332 * b1 + white * 0.0750759; + b2 = 0.969 * b2 + white * 0.153852; + b3 = 0.8665 * b3 + white * 0.3104856; + b4 = 0.55 * b4 + white * 0.5329522; + b5 = -0.7616 * b5 - white * 0.016898; + noiseData[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362; + noiseData[i] *= 0.11; + + b6 = white * 0.115926; + } + + pinkBuffer.type = 'pink'; + return pinkBuffer; +}(); + +var _brownNoiseBuffer = function () { + var bufferSize = 2 * master.audiocontext.sampleRate; + var brownBuffer = master.audiocontext.createBuffer(1, bufferSize, master.audiocontext.sampleRate); + var noiseData = brownBuffer.getChannelData(0); + var lastOut = 0.0; + + for (var i = 0; i < bufferSize; i++) { + var white = Math.random() * 2 - 1; + noiseData[i] = (lastOut + 0.02 * white) / 1.02; + lastOut = noiseData[i]; + noiseData[i] *= 3.5; + } + + brownBuffer.type = 'brown'; + return brownBuffer; +}(); +/** + * Noise is a type of oscillator that generates a buffer with random values. + * + * @class p5.Noise + * @extends p5.Oscillator + * @constructor + * @param {String} type Type of noise can be 'white' (default), + * 'brown' or 'pink'. + */ + + +var noise_Noise = +function (_Oscillator) { + noise_inherits(Noise, _Oscillator); + + function Noise(type) { + var _this; + + noise_classCallCheck(this, Noise); + + _this = noise_possibleConstructorReturn(this, noise_getPrototypeOf(Noise).call(this)); + var assignType; + delete _this.f; + delete _this.freq; + delete _this.oscillator; + + if (type === 'brown') { + assignType = _brownNoiseBuffer; + } else if (type === 'pink') { + assignType = _pinkNoiseBuffer; + } else { + assignType = _whiteNoiseBuffer; + } + + _this.buffer = assignType; + return _this; + } + /** + * Set type of noise to 'white', 'pink' or 'brown'. + * White is the default. + * + * @method setType + * @param {String} [type] 'white', 'pink' or 'brown' + */ + + + noise_createClass(Noise, [{ + key: "setType", + value: function setType(type) { + switch (type) { + case 'white': + this.buffer = _whiteNoiseBuffer; + break; + + case 'pink': + this.buffer = _pinkNoiseBuffer; + break; + + case 'brown': + this.buffer = _brownNoiseBuffer; + break; + + default: + this.buffer = _whiteNoiseBuffer; + } + + if (this.started) { + var now = master.audiocontext.currentTime; + this.stop(now); + this.start(now + 0.01); + } + } + }, { + key: "getType", + value: function getType() { + return this.buffer.type; + } + }, { + key: "start", + value: function start() { + if (this.started) { + this.stop(); + } + + this.noise = master.audiocontext.createBufferSource(); + this.noise.buffer = this.buffer; + this.noise.loop = true; + this.noise.connect(this.output); + var now = master.audiocontext.currentTime; + this.noise.start(now); + this.started = true; + } + }, { + key: "stop", + value: function stop() { + var now = master.audiocontext.currentTime; + + if (this.noise) { + this.noise.stop(now); + this.started = false; + } + } + }, { + key: "dispose", + value: function dispose() { + var now = master.audiocontext.currentTime; + + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + + if (this.noise) { + this.noise.disconnect(); + this.stop(now); + } + + if (this.output) { + this.output.disconnect(); + } + + if (this.panner) { + this.panner.disconnect(); + } + + this.output = null; + this.panner = null; + this.buffer = null; + this.noise = null; + } + }]); + + return Noise; +}(oscillator); + + var noise = (noise_Noise); +var Signal = __webpack_require__(2); +var Signal_default = __webpack_require__.n(Signal); + +function pulse_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { pulse_typeof = function _typeof(obj) { return typeof obj; }; } else { pulse_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return pulse_typeof(obj); } + +function pulse_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function pulse_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function pulse_createClass(Constructor, protoProps, staticProps) { if (protoProps) pulse_defineProperties(Constructor.prototype, protoProps); if (staticProps) pulse_defineProperties(Constructor, staticProps); return Constructor; } + +function pulse_possibleConstructorReturn(self, call) { if (call && (pulse_typeof(call) === "object" || typeof call === "function")) { return call; } return pulse_assertThisInitialized(self); } + +function pulse_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function pulse_getPrototypeOf(o) { pulse_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return pulse_getPrototypeOf(o); } + +function pulse_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) pulse_setPrototypeOf(subClass, superClass); } + +function pulse_setPrototypeOf(o, p) { pulse_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return pulse_setPrototypeOf(o, p); } + + + + + +/** + * Creates a Pulse object, an oscillator that implements + * Pulse Width Modulation. + * The pulse is created with two oscillators. + * Accepts a parameter for frequency, and to set the + * width between the pulses. See + * p5.Oscillator for a full list of methods. + * + * @class p5.Pulse + * @extends p5.Oscillator + * @constructor + * @param {Number} [freq] Frequency in oscillations per second (Hz) + * @param {Number} [w] Width between the pulses (0 to 1.0, + * defaults to 0) + * @example + *
    + * let pulse; + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(startPulse); + * background(220); + * + * pulse = new p5.Pulse(); + * pulse.amp(0.5); + * pulse.freq(220); + * } + * function startPulse() { + * pulse.start(); + * pulse.amp(0.5, 0.02); + * } + * function mouseReleased() { + * pulse.amp(0, 0.2); + * } + * function draw() { + * background(220); + * text('tap to play', 5, 20, width - 20); + * let w = map(mouseX, 0, width, 0, 1); + * w = constrain(w, 0, 1); + * pulse.width(w); + * text('pulse width: ' + w, 5, height - 20); + * } + *
    + */ + +var pulse_Pulse = +function (_Oscillator) { + pulse_inherits(Pulse, _Oscillator); + + function Pulse(freq, w) { + var _this; + + pulse_classCallCheck(this, Pulse); + + _this = pulse_possibleConstructorReturn(this, pulse_getPrototypeOf(Pulse).call(this, freq, 'sawtooth')); + + _this.w = w || 0; + + _this.osc2 = new SawOsc(freq); + + _this.dNode = master.audiocontext.createDelay(); + + _this.dcOffset = createDCOffset(); + _this.dcGain = master.audiocontext.createGain(); + + _this.dcOffset.connect(_this.dcGain); + + _this.dcGain.connect(_this.output); + + + _this.f = freq || 440; + var mW = _this.w / _this.oscillator.frequency.value; + _this.dNode.delayTime.value = mW; + _this.dcGain.gain.value = 1.7 * (0.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); + + return _this; + } + /** + * Set the width of a Pulse object (an oscillator that implements + * Pulse Width Modulation). + * + * @method width + * @param {Number} [width] Width between the pulses (0 to 1.0, + * defaults to 0) + */ + + + pulse_createClass(Pulse, [{ + key: "width", + value: function width(w) { + if (typeof w === 'number') { + if (w <= 1.0 && w >= 0.0) { + this.w = w; + + var mW = this.w / this.oscillator.frequency.value; + this.dNode.delayTime.value = mW; + } + + this.dcGain.gain.value = 1.7 * (0.5 - this.w); + } else { + w.connect(this.dNode.delayTime); + var sig = new Signal_default.a(-0.5); + + w.connect(sig); + var mult1 = new Multiply_default.a(-1); + var mult2 = new Multiply_default.a(1.7); + sig = sig.connect(mult1).connect(mult2); + sig.connect(this.dcGain.gain); + } + } + }, { + key: "start", + value: function start(f, time) { + var now = master.audiocontext.currentTime; + var t = time || 0; + + if (!this.started) { + var freq = f || this.f; + var type = this.oscillator.type; + this.oscillator = master.audiocontext.createOscillator(); + this.oscillator.frequency.setValueAtTime(freq, now); + this.oscillator.type = type; + this.oscillator.connect(this.output); + this.oscillator.start(t + now); + + this.osc2.oscillator = master.audiocontext.createOscillator(); + this.osc2.oscillator.frequency.setValueAtTime(freq, t + now); + this.osc2.oscillator.type = type; + this.osc2.oscillator.connect(this.osc2.output); + this.osc2.start(t + now); + this.freqNode = [this.oscillator.frequency, this.osc2.oscillator.frequency]; + + this.dcOffset = createDCOffset(); + this.dcOffset.connect(this.dcGain); + this.dcOffset.start(t + now); + + if (this.mods !== undefined && this.mods.frequency !== undefined) { + this.mods.frequency.connect(this.freqNode[0]); + this.mods.frequency.connect(this.freqNode[1]); + } + + this.started = true; + this.osc2.started = true; + } + } + }, { + key: "stop", + value: function stop(time) { + if (this.started) { + var t = time || 0; + var now = master.audiocontext.currentTime; + this.oscillator.stop(t + now); + + if (this.osc2.oscillator) { + this.osc2.oscillator.stop(t + now); + } + + this.dcOffset.stop(t + now); + this.started = false; + this.osc2.started = false; + } + } + }, { + key: "freq", + value: function freq(val) { + var rampTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var tFromNow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + if (typeof val === 'number') { + this.f = val; + var now = master.audiocontext.currentTime; + var currentFreq = this.oscillator.frequency.value; + this.oscillator.frequency.cancelScheduledValues(now); + this.oscillator.frequency.setValueAtTime(currentFreq, now + tFromNow); + this.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); + this.osc2.oscillator.frequency.cancelScheduledValues(now); + this.osc2.oscillator.frequency.setValueAtTime(currentFreq, now + tFromNow); + this.osc2.oscillator.frequency.exponentialRampToValueAtTime(val, tFromNow + rampTime + now); + + if (this.freqMod) { + this.freqMod.output.disconnect(); + this.freqMod = null; + } + } else if (val.output) { + val.output.disconnect(); + val.output.connect(this.oscillator.frequency); + val.output.connect(this.osc2.oscillator.frequency); + this.freqMod = val; + } + } + }]); + + return Pulse; +}(oscillator); + + +function createDCOffset() { + var ac = master.audiocontext; + var buffer = ac.createBuffer(1, 2048, ac.sampleRate); + var data = buffer.getChannelData(0); + + for (var i = 0; i < 2048; i++) { + data[i] = 1.0; + } + + var bufferSource = ac.createBufferSource(); + bufferSource.buffer = buffer; + bufferSource.loop = true; + return bufferSource; +} + + var pulse = (pulse_Pulse); +function audioin_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function audioin_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function audioin_createClass(Constructor, protoProps, staticProps) { if (protoProps) audioin_defineProperties(Constructor.prototype, protoProps); if (staticProps) audioin_defineProperties(Constructor, staticProps); return Constructor; } + + + +master.inputSources = []; +/** + *

    Get audio from an input, i.e. your computer's microphone.

    + * + *

    Turn the mic on/off with the start() and stop() methods. When the mic + * is on, its volume can be measured with getLevel or by connecting an + * FFT object.

    + * + *

    If you want to hear the AudioIn, use the .connect() method. + * AudioIn does not connect to p5.sound output by default to prevent + * feedback.

    + * + *

    Note: This uses the getUserMedia/ + * Stream API, which is not supported by certain browsers. Access in Chrome browser + * is limited to localhost and https, but access over http may be limited.

    + * + * @class p5.AudioIn + * @constructor + * @param {Function} [errorCallback] A function to call if there is an error + * accessing the AudioIn. For example, + * Safari and iOS devices do not + * currently allow microphone access. + * @example + *
    + * let mic; + * + * function setup(){ + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(useraudiocontextStartAudio); + * textAlign(CENTER); + * mic = new p5.AudioIn(); + * mic.start(); + * } + * + * function draw(){ + * background(0); + * fill(255); + * text('tap to start', width/2, 20); + * + * micLevel = mic.getLevel(); + * let y = height - micLevel * height; + * ellipse(width/2, y, 10, 10); + * } + *
    + */ + +var audioin_AudioIn = +function () { + function AudioIn(errorCallback) { + audioin_classCallCheck(this, AudioIn); + + + /** + * @property {GainNode} input + */ + this.input = master.audiocontext.createGain(); + /** + * @property {GainNode} output + */ + + this.output = master.audiocontext.createGain(); + /** + * @property {MediaStream|null} stream + */ + + this.stream = null; + /** + * @property {MediaStreamAudioSourceNode|null} mediaStream + */ + + this.mediaStream = null; + /** + * @property {Number|null} currentSource + */ + + this.currentSource = null; + /** + * Client must allow browser to access their microphone / audioin source. + * Default: false. Will become true when the client enables access. + * + * @property {Boolean} enabled + */ + + this.enabled = false; + /** + * Input amplitude, connect to it by default but not to master out + * + * @property {p5.Amplitude} amplitude + */ + + this.amplitude = new amplitude(); + this.output.connect(this.amplitude.input); + + if (!window.MediaStreamTrack || !window.navigator.mediaDevices || !window.navigator.mediaDevices.getUserMedia) { + errorCallback ? errorCallback() : window.alert('This browser does not support MediaStreamTrack and mediaDevices'); + } + + + master.soundArray.push(this); + } + /** + * Start processing audio input. This enables the use of other + * AudioIn methods like getLevel(). Note that by default, AudioIn + * is not connected to p5.sound's output. So you won't hear + * anything unless you use the connect() method.
    + * + * Certain browsers limit access to the user's microphone. For example, + * Chrome only allows access from localhost and over https. For this reason, + * you may want to include an errorCallback—a function that is called in case + * the browser won't provide mic access. + * + * @method start + * @for p5.AudioIn + * @param {Function} [successCallback] Name of a function to call on + * success. + * @param {Function} [errorCallback] Name of a function to call if + * there was an error. For example, + * some browsers do not support + * getUserMedia. + */ + + + audioin_createClass(AudioIn, [{ + key: "start", + value: function start(successCallback, errorCallback) { + var self = this; + + if (this.stream) { + this.stop(); + } + + + var audioSource = master.inputSources[self.currentSource]; + var constraints = { + audio: { + sampleRate: master.audiocontext.sampleRate, + echoCancellation: false + } + }; + + if (master.inputSources[this.currentSource]) { + constraints.audio.deviceId = audioSource.deviceId; + } + + window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { + self.stream = stream; + self.enabled = true; + + self.mediaStream = master.audiocontext.createMediaStreamSource(stream); + self.mediaStream.connect(self.output); + + self.amplitude.setInput(self.output); + if (successCallback) successCallback(); + })["catch"](function (err) { + if (errorCallback) errorCallback(err);else console.error(err); + }); + } + /** + * Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel(). + * If re-starting, the user may be prompted for permission access. + * + * @method stop + * @for p5.AudioIn + */ + + }, { + key: "stop", + value: function stop() { + if (this.stream) { + this.stream.getTracks().forEach(function (track) { + track.stop(); + }); + this.mediaStream.disconnect(); + delete this.mediaStream; + delete this.stream; + } + } + /** + * Connect to an audio unit. If no parameter is provided, will + * connect to the master output (i.e. your speakers).
    + * + * @method connect + * @for p5.AudioIn + * @param {Object} [unit] An object that accepts audio input, + * such as an FFT + */ + + }, { + key: "connect", + value: function connect(unit) { + if (unit) { + if (unit.hasOwnProperty('input')) { + this.output.connect(unit.input); + } else if (unit.hasOwnProperty('analyser')) { + this.output.connect(unit.analyser); + } else { + this.output.connect(unit); + } + } else { + this.output.connect(master.input); + } + } + /** + * Disconnect the AudioIn from all audio units. For example, if + * connect() had been called, disconnect() will stop sending + * signal to your speakers.
    + * + * @method disconnect + * @for p5.AudioIn + */ + + }, { + key: "disconnect", + value: function disconnect() { + if (this.output) { + this.output.disconnect(); + + this.output.connect(this.amplitude.input); + } + } + /** + * Read the Amplitude (volume level) of an AudioIn. The AudioIn + * class contains its own instance of the Amplitude class to help + * make it easy to get a microphone's volume level. Accepts an + * optional smoothing value (0.0 < 1.0). NOTE: AudioIn must + * .start() before using .getLevel().
    + * + * @method getLevel + * @for p5.AudioIn + * @param {Number} [smoothing] Smoothing is 0.0 by default. + * Smooths values based on previous values. + * @return {Number} Volume level (between 0.0 and 1.0) + */ + + }, { + key: "getLevel", + value: function getLevel(smoothing) { + if (smoothing) { + this.amplitude.smoothing = smoothing; + } + + return this.amplitude.getLevel(); + } + /** + * Set amplitude (volume) of a mic input between 0 and 1.0.
    + * + * @method amp + * @for p5.AudioIn + * @param {Number} vol between 0 and 1.0 + * @param {Number} [time] ramp time (optional) + */ + + }, { + key: "amp", + value: function amp(vol, t) { + if (t) { + var rampTime = t || 0; + var currentVol = this.output.gain.value; + this.output.gain.cancelScheduledValues(master.audiocontext.currentTime); + this.output.gain.setValueAtTime(currentVol, master.audiocontext.currentTime); + this.output.gain.linearRampToValueAtTime(vol, rampTime + master.audiocontext.currentTime); + } else { + this.output.gain.cancelScheduledValues(master.audiocontext.currentTime); + this.output.gain.setValueAtTime(vol, master.audiocontext.currentTime); + } + } + /** + * Returns a list of available input sources. This is a wrapper + * for + * MediaDevices.enumerateDevices() - Web APIs | MDN + * and it returns a Promise. + * @method getSources + * @for p5.AudioIn + * @param {Function} [successCallback] This callback function handles the sources when they + * have been enumerated. The callback function + * receives the deviceList array as its only argument + * @param {Function} [errorCallback] This optional callback receives the error + * message as its argument. + * @returns {Promise} Returns a Promise that can be used in place of the callbacks, similar + * to the enumerateDevices() method + * @example + *
    + * let audioIn; + * + * function setup(){ + * text('getting sources...', 0, 20); + * audioIn = new p5.AudioIn(); + * audioIn.getSources(gotSources); + * } + * + * function gotSources(deviceList) { + * if (deviceList.length > 0) { + * //set the source to the first item in the deviceList array + * audioIn.setSource(0); + * let currentSource = deviceList[audioIn.currentSource]; + * text('set source to: ' + currentSource.deviceId, 5, 20, width); + * } + * } + *
    + */ + + }, { + key: "getSources", + value: function getSources(onSuccess, onError) { + return new Promise(function (resolve, reject) { + window.navigator.mediaDevices.enumerateDevices().then(function (devices) { + master.inputSources = devices.filter(function (device) { + return device.kind === 'audioinput'; + }); + resolve(master.inputSources); + + if (onSuccess) { + onSuccess(master.inputSources); + } + })["catch"](function (error) { + reject(error); + + if (onError) { + onError(error); + } else { + console.error('This browser does not support MediaStreamTrack.getSources()'); + } + }); + }); + } + /** + * Set the input source. Accepts a number representing a + * position in the array returned by getSources(). + * This is only available in browsers that support + * + * navigator.mediaDevices.enumerateDevices() + * + * @method setSource + * @for p5.AudioIn + * @param {number} num position of input source in the array + * @example + *
    + * let audioIn; + * + * function setup(){ + * text('getting sources...', 0, 20); + * audioIn = new p5.AudioIn(); + * audioIn.getSources(gotSources); + * } + * + * function gotSources(deviceList) { + * if (deviceList.length > 0) { + * //set the source to the first item in the deviceList array + * audioIn.setSource(0); + * let currentSource = deviceList[audioIn.currentSource]; + * text('set source to: ' + currentSource.deviceId, 5, 20, width); + * } + * } + *
    + */ + + }, { + key: "setSource", + value: function setSource(num) { + if (master.inputSources.length > 0 && num < master.inputSources.length) { + this.currentSource = num; + console.log('set source to ', master.inputSources[this.currentSource]); + } else { + console.log('unable to set input source'); + } + + + if (this.stream && this.stream.active) { + this.start(); + } + } + + }, { + key: "dispose", + value: function dispose() { + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + this.stop(); + + if (this.output) { + this.output.disconnect(); + } + + if (this.amplitude) { + this.amplitude.disconnect(); + } + + delete this.amplitude; + delete this.output; + } + }]); + + return AudioIn; +}(); + + var audioin = (audioin_AudioIn); +var CrossFade = __webpack_require__(23); +var CrossFade_default = __webpack_require__.n(CrossFade); + +function effect_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function effect_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function effect_createClass(Constructor, protoProps, staticProps) { if (protoProps) effect_defineProperties(Constructor.prototype, protoProps); if (staticProps) effect_defineProperties(Constructor, staticProps); return Constructor; } + + + +/** + * Effect is a base class for audio effects in p5.
    + * This module handles the nodes and methods that are + * common and useful for current and future effects. + * + * + * This class is extended by p5.Distortion, + * p5.Compressor, + * p5.Delay, + * p5.Filter, + * p5.Reverb. + * + * @class p5.Effect + * @constructor + * + * @param {Object} [ac] Reference to the audio context of the p5 object + * @param {AudioNode} [input] Gain Node effect wrapper + * @param {AudioNode} [output] Gain Node effect wrapper + * @param {Object} [_drywet] Tone.JS CrossFade node (defaults to value: 1) + * @param {AudioNode} [wet] Effects that extend this class should connect + * to the wet signal to this gain node, so that dry and wet + * signals are mixed properly. + */ + +var effect_Effect = +function () { + function Effect() { + effect_classCallCheck(this, Effect); + + this.ac = master.audiocontext; + this.input = this.ac.createGain(); + this.output = this.ac.createGain(); + /** + * The p5.Effect class is built + * using Tone.js CrossFade + * @private + */ + + this._drywet = new CrossFade_default.a(1); + /** + * In classes that extend + * p5.Effect, connect effect nodes + * to the wet parameter + */ + + this.wet = this.ac.createGain(); + this.input.connect(this._drywet.a); + this.wet.connect(this._drywet.b); + + this._drywet.connect(this.output); + + this.connect(); + + master.soundArray.push(this); + } + /** + * Set the output volume of the filter. + * + * @method amp + * @for p5.Effect + * @param {Number} [vol] amplitude between 0 and 1.0 + * @param {Number} [rampTime] create a fade that lasts until rampTime + * @param {Number} [tFromNow] schedule this event to happen in tFromNow seconds + */ + + + effect_createClass(Effect, [{ + key: "amp", + value: function amp(vol) { + var rampTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var tFromNow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var now = master.audiocontext.currentTime; + var startTime = now + tFromNow; + var endTime = startTime + rampTime + 0.001; + var currentVol = this.output.gain.value; + this.output.gain.cancelScheduledValues(now); + this.output.gain.linearRampToValueAtTime(currentVol, startTime + 0.001); + this.output.gain.linearRampToValueAtTime(vol, endTime); + } + /** + * Link effects together in a chain + * Example usage: filter.chain(reverb, delay, panner); + * May be used with an open-ended number of arguments + * + * @method chain + * @for p5.Effect + * @param {Object} [arguments] Chain together multiple sound objects + */ + + }, { + key: "chain", + value: function chain() { + if (arguments.length > 0) { + this.connect(arguments[0]); + + for (var i = 1; i < arguments.length; i += 1) { + arguments[i - 1].connect(arguments[i]); + } + } + + return this; + } + /** + * Adjust the dry/wet value. + * + * @method drywet + * @for p5.Effect + * @param {Number} [fade] The desired drywet value (0 - 1.0) + */ + + }, { + key: "drywet", + value: function drywet() { + if (typeof fade !== 'undefined') { + this._drywet.fade.value = fade; + } + + return this._drywet.fade.value; + } + /** + * Send output to a p5.js-sound, Web Audio Node, or use signal to + * control an AudioParam + * + * @method connect + * @for p5.Effect + * @param {Object} unit + */ + + }, { + key: "connect", + value: function connect(unit) { + var u = unit || p5.soundOut.input; + this.output.connect(u.input ? u.input : u); + } + /** + * Disconnect all output. + * @method disconnect + * @for p5.Effect + */ + + }, { + key: "disconnect", + value: function disconnect() { + if (this.output) { + this.output.disconnect(); + } + } + }, { + key: "dispose", + value: function dispose() { + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + + if (this.input) { + this.input.disconnect(); + delete this.input; + } + + if (this.output) { + this.output.disconnect(); + delete this.output; + } + + if (this._drywet) { + this._drywet.disconnect(); + + delete this._drywet; + } + + if (this.wet) { + this.wet.disconnect(); + delete this.wet; + } + + this.ac = undefined; + } + }]); + + return Effect; +}(); + + var effect = (effect_Effect); +function filter_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { filter_typeof = function _typeof(obj) { return typeof obj; }; } else { filter_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return filter_typeof(obj); } + +function filter_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function filter_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function filter_createClass(Constructor, protoProps, staticProps) { if (protoProps) filter_defineProperties(Constructor.prototype, protoProps); if (staticProps) filter_defineProperties(Constructor, staticProps); return Constructor; } + +function filter_possibleConstructorReturn(self, call) { if (call && (filter_typeof(call) === "object" || typeof call === "function")) { return call; } return filter_assertThisInitialized(self); } + +function filter_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = filter_getPrototypeOf(object); if (object === null) break; } return object; } + +function filter_getPrototypeOf(o) { filter_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return filter_getPrototypeOf(o); } + +function filter_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) filter_setPrototypeOf(subClass, superClass); } + +function filter_setPrototypeOf(o, p) { filter_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return filter_setPrototypeOf(o, p); } + + +/** + *

    A p5.Filter uses a Web Audio Biquad Filter to filter + * the frequency response of an input source. Subclasses + * include:

    + * p5.LowPass: + * Allows frequencies below the cutoff frequency to pass through, + * and attenuates frequencies above the cutoff.
    + * p5.HighPass: + * The opposite of a lowpass filter.
    + * p5.BandPass: + * Allows a range of frequencies to pass through and attenuates + * the frequencies below and above this frequency range.
    + * + * The .res() method controls either width of the + * bandpass, or resonance of the low/highpass cutoff frequency. + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.Filter + * @extends p5.Effect + * @constructor + * @param {String} [type] 'lowpass' (default), 'highpass', 'bandpass' + * @example + *
    + * let fft, noise, filter; + * + * function setup() { + * let cnv = createCanvas(100,100); + * cnv.mousePressed(makeNoise); + * fill(255, 0, 255); + * + * filter = new p5.BandPass(); + * noise = new p5.Noise(); + * noise.disconnect(); + * noise.connect(filter); + * + * fft = new p5.FFT(); + * } + * + * function draw() { + * background(220); + * + * // set the BandPass frequency based on mouseX + * let freq = map(mouseX, 0, width, 20, 10000); + * freq = constrain(freq, 0, 22050); + * filter.freq(freq); + * // give the filter a narrow band (lower res = wider bandpass) + * filter.res(50); + * + * // draw filtered spectrum + * let spectrum = fft.analyze(); + * noStroke(); + * for (let i = 0; i < spectrum.length; i++) { + * let x = map(i, 0, spectrum.length, 0, width); + * let h = -height + map(spectrum[i], 0, 255, height, 0); + * rect(x, height, width/spectrum.length, h); + * } + * if (!noise.started) { + * text('tap here and drag to change frequency', 10, 20, width - 20); + * } else { + * text('Frequency: ' + round(freq)+'Hz', 20, 20, width - 20); + * } + * } + * + * function makeNoise() { + * // see also: `userStartAudio()` + * noise.start(); + * noise.amp(0.5, 0.2); + * } + * + * function mouseReleased() { + * noise.amp(0, 0.2); + * } + * + *
    + */ + +var Filter = +function (_Effect) { + filter_inherits(Filter, _Effect); + + function Filter(type) { + var _this; + + filter_classCallCheck(this, Filter); + + _this = filter_possibleConstructorReturn(this, filter_getPrototypeOf(Filter).call(this)); + + /** + * The p5.Filter is built with a + * + * Web Audio BiquadFilter Node. + * + * @property {DelayNode} biquadFilter + */ + + _this.biquad = _this.ac.createBiquadFilter(); + + _this.input.connect(_this.biquad); + + _this.biquad.connect(_this.wet); + + if (type) { + _this.setType(type); + } + + + _this._on = true; + _this._untoggledType = _this.biquad.type; + return _this; + } + /** + * Filter an audio signal according to a set + * of filter parameters. + * + * @method process + * @param {Object} Signal An object that outputs audio + * @param {Number} [freq] Frequency in Hz, from 10 to 22050 + * @param {Number} [res] Resonance/Width of the filter frequency + * from 0.001 to 1000 + */ + + + filter_createClass(Filter, [{ + key: "process", + value: function process(src, freq, res, time) { + src.connect(this.input); + this.set(freq, res, time); + } + /** + * Set the frequency and the resonance of the filter. + * + * @method set + * @param {Number} [freq] Frequency in Hz, from 10 to 22050 + * @param {Number} [res] Resonance (Q) from 0.001 to 1000 + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + */ + + }, { + key: "set", + value: function set(freq, res, time) { + if (freq) { + this.freq(freq, time); + } + + if (res) { + this.res(res, time); + } + } + /** + * Set the filter frequency, in Hz, from 10 to 22050 (the range of + * human hearing, although in reality most people hear in a narrower + * range). + * + * @method freq + * @param {Number} freq Filter Frequency + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + * @return {Number} value Returns the current frequency value + */ + + }, { + key: "freq", + value: function freq(_freq, time) { + var t = time || 0; + + if (_freq <= 0) { + _freq = 1; + } + + if (typeof _freq === 'number') { + this.biquad.frequency.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.biquad.frequency.exponentialRampToValueAtTime(_freq, this.ac.currentTime + 0.02 + t); + } else if (_freq) { + _freq.connect(this.biquad.frequency); + } + + return this.biquad.frequency.value; + } + /** + * Controls either width of a bandpass frequency, + * or the resonance of a low/highpass cutoff frequency. + * + * @method res + * @param {Number} res Resonance/Width of filter freq + * from 0.001 to 1000 + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + * @return {Number} value Returns the current res value + */ + + }, { + key: "res", + value: function res(_res, time) { + var t = time || 0; + + if (typeof _res === 'number') { + this.biquad.Q.value = _res; + this.biquad.Q.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.biquad.Q.linearRampToValueAtTime(_res, this.ac.currentTime + 0.02 + t); + } else if (_res) { + _res.connect(this.biquad.Q); + } + + return this.biquad.Q.value; + } + /** + * Controls the gain attribute of a Biquad Filter. + * This is distinctly different from .amp() which is inherited from p5.Effect + * .amp() controls the volume via the output gain node + * p5.Filter.gain() controls the gain parameter of a Biquad Filter node. + * + * @method gain + * @param {Number} gain + * @return {Number} Returns the current or updated gain value + */ + + }, { + key: "gain", + value: function gain(_gain, time) { + var t = time || 0; + + if (typeof _gain === 'number') { + this.biquad.gain.value = _gain; + this.biquad.gain.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.biquad.gain.linearRampToValueAtTime(_gain, this.ac.currentTime + 0.02 + t); + } else if (_gain) { + _gain.connect(this.biquad.gain); + } + + return this.biquad.gain.value; + } + /** + * Toggle function. Switches between the specified type and allpass + * + * @method toggle + * @return {boolean} [Toggle value] + */ + + }, { + key: "toggle", + value: function toggle() { + this._on = !this._on; + + if (this._on === true) { + this.biquad.type = this._untoggledType; + } else if (this._on === false) { + this.biquad.type = 'allpass'; + } + + return this._on; + } + /** + * Set the type of a p5.Filter. Possible types include: + * "lowpass" (default), "highpass", "bandpass", + * "lowshelf", "highshelf", "peaking", "notch", + * "allpass". + * + * @method setType + * @param {String} t + */ + + }, { + key: "setType", + value: function setType(t) { + this.biquad.type = t; + this._untoggledType = this.biquad.type; + } + }, { + key: "dispose", + value: function dispose() { + _get(filter_getPrototypeOf(Filter.prototype), "dispose", this).call(this); + + if (this.biquad) { + this.biquad.disconnect(); + delete this.biquad; + } + } + }]); + + return Filter; +}(effect); +/** + * Constructor: new p5.LowPass() Filter. + * This is the same as creating a p5.Filter and then calling + * its method setType('lowpass'). + * See p5.Filter for methods. + * + * @class p5.LowPass + * @constructor + * @extends p5.Filter + */ + + +var LowPass = +function (_Filter) { + filter_inherits(LowPass, _Filter); + + function LowPass() { + filter_classCallCheck(this, LowPass); + + return filter_possibleConstructorReturn(this, filter_getPrototypeOf(LowPass).call(this, 'lowpass')); + } + + return LowPass; +}(Filter); +/** + * Constructor: new p5.HighPass() Filter. + * This is the same as creating a p5.Filter and then calling + * its method setType('highpass'). + * See p5.Filter for methods. + * + * @class p5.HighPass + * @constructor + * @extends p5.Filter + */ + + +var HighPass = +function (_Filter2) { + filter_inherits(HighPass, _Filter2); + + function HighPass() { + filter_classCallCheck(this, HighPass); + + return filter_possibleConstructorReturn(this, filter_getPrototypeOf(HighPass).call(this, 'highpass')); + } + + return HighPass; +}(Filter); +/** + * Constructor: new p5.BandPass() Filter. + * This is the same as creating a p5.Filter and then calling + * its method setType('bandpass'). + * See p5.Filter for methods. + * + * @class p5.BandPass + * @constructor + * @extends p5.Filter + */ + + +var BandPass = +function (_Filter3) { + filter_inherits(BandPass, _Filter3); + + function BandPass() { + filter_classCallCheck(this, BandPass); + + return filter_possibleConstructorReturn(this, filter_getPrototypeOf(BandPass).call(this, 'bandpass')); + } + + return BandPass; +}(Filter); + + var filter = (Filter); + +function eqFilter_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { eqFilter_typeof = function _typeof(obj) { return typeof obj; }; } else { eqFilter_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return eqFilter_typeof(obj); } + +function eqFilter_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function eqFilter_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function eqFilter_createClass(Constructor, protoProps, staticProps) { if (protoProps) eqFilter_defineProperties(Constructor.prototype, protoProps); if (staticProps) eqFilter_defineProperties(Constructor, staticProps); return Constructor; } + +function eqFilter_possibleConstructorReturn(self, call) { if (call && (eqFilter_typeof(call) === "object" || typeof call === "function")) { return call; } return eqFilter_assertThisInitialized(self); } + +function eqFilter_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function eqFilter_getPrototypeOf(o) { eqFilter_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return eqFilter_getPrototypeOf(o); } + +function eqFilter_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) eqFilter_setPrototypeOf(subClass, superClass); } + +function eqFilter_setPrototypeOf(o, p) { eqFilter_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return eqFilter_setPrototypeOf(o, p); } + + + +/** + * EQFilter extends p5.Filter with constraints + * necessary for the p5.EQ + * + * @private + */ + +var eqFilter_EQFilter = +function (_Filter) { + eqFilter_inherits(EQFilter, _Filter); + + function EQFilter(freq, res) { + var _this; + + eqFilter_classCallCheck(this, EQFilter); + + _this = eqFilter_possibleConstructorReturn(this, eqFilter_getPrototypeOf(EQFilter).call(this, 'peaking')); + + _this.disconnect(); + + _this.set(freq, res); + + _this.biquad.gain.value = 0; + delete _this.input; + delete _this.output; + delete _this._drywet; + delete _this.wet; + return _this; + } + + eqFilter_createClass(EQFilter, [{ + key: "amp", + value: function amp() { + console.warn('`amp()` is not available for p5.EQ bands. Use `.gain()`'); + } + }, { + key: "drywet", + value: function drywet() { + console.warn('`drywet()` is not available for p5.EQ bands.'); + } + }, { + key: "connect", + value: function connect(unit) { + var u = unit || p5.soundOut.input; + + if (this.biquad) { + this.biquad.connect(u.input ? u.input : u); + } else { + this.output.connect(u.input ? u.input : u); + } + } + }, { + key: "disconnect", + value: function disconnect() { + if (this.biquad) { + this.biquad.disconnect(); + } + } + }, { + key: "dispose", + value: function dispose() { + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + this.disconnect(); + delete this.biquad; + } + }]); + + return EQFilter; +}(filter); + + var eqFilter = (eqFilter_EQFilter); +function eq_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { eq_typeof = function _typeof(obj) { return typeof obj; }; } else { eq_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return eq_typeof(obj); } + +function eq_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function eq_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function eq_createClass(Constructor, protoProps, staticProps) { if (protoProps) eq_defineProperties(Constructor.prototype, protoProps); if (staticProps) eq_defineProperties(Constructor, staticProps); return Constructor; } + +function eq_possibleConstructorReturn(self, call) { if (call && (eq_typeof(call) === "object" || typeof call === "function")) { return call; } return eq_assertThisInitialized(self); } + +function eq_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function eq_get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { eq_get = Reflect.get; } else { eq_get = function _get(target, property, receiver) { var base = eq_superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return eq_get(target, property, receiver || target); } + +function eq_superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = eq_getPrototypeOf(object); if (object === null) break; } return object; } + +function eq_getPrototypeOf(o) { eq_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return eq_getPrototypeOf(o); } + +function eq_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) eq_setPrototypeOf(subClass, superClass); } + +function eq_setPrototypeOf(o, p) { eq_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return eq_setPrototypeOf(o, p); } + + + +/** + * p5.EQ is an audio effect that performs the function of a multiband + * audio equalizer. Equalization is used to adjust the balance of + * frequency compoenents of an audio signal. This process is commonly used + * in sound production and recording to change the waveform before it reaches + * a sound output device. EQ can also be used as an audio effect to create + * interesting distortions by filtering out parts of the spectrum. p5.EQ is + * built using a chain of Web Audio Biquad Filter Nodes and can be + * instantiated with 3 or 8 bands. Bands can be added or removed from + * the EQ by directly modifying p5.EQ.bands (the array that stores filters). + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.EQ + * @constructor + * @extends p5.Effect + * @param {Number} [_eqsize] Constructor will accept 3 or 8, defaults to 3 + * @return {Object} p5.EQ object + * + * @example + *
    + * let eq, soundFile + * let eqBandIndex = 0; + * let eqBandNames = ['lows', 'mids', 'highs']; + * + * function preload() { + * soundFormats('mp3', 'ogg'); + * soundFile = loadSound('assets/beat'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(toggleSound); + * + * eq = new p5.EQ(eqBandNames.length); + * soundFile.disconnect(); + * eq.process(soundFile); + * } + * + * function draw() { + * background(30); + * noStroke(); + * fill(255); + * textAlign(CENTER); + * text('filtering ', 50, 25); + * + * fill(255, 40, 255); + * textSize(26); + * text(eqBandNames[eqBandIndex], 50, 55); + * + * fill(255); + * textSize(9); + * + * if (!soundFile.isPlaying()) { + * text('tap to play', 50, 80); + * } else { + * text('tap to filter next band', 50, 80) + * } + * } + * + * function toggleSound() { + * if (!soundFile.isPlaying()) { + * soundFile.play(); + * } else { + * eqBandIndex = (eqBandIndex + 1) % eq.bands.length; + * } + * + * for (let i = 0; i < eq.bands.length; i++) { + * eq.bands[i].gain(0); + * } + * // filter the band we want to filter + * eq.bands[eqBandIndex].gain(-40); + * } + *
    + */ + +var eq_EQ = +function (_Effect) { + eq_inherits(EQ, _Effect); + + function EQ(_eqsize) { + var _this; + + eq_classCallCheck(this, EQ); + + _this = eq_possibleConstructorReturn(this, eq_getPrototypeOf(EQ).call(this)); + + _eqsize = _eqsize === 3 || _eqsize === 8 ? _eqsize : 3; + var factor; + _eqsize === 3 ? factor = Math.pow(2, 3) : factor = 2; + /** + * The p5.EQ is built with abstracted p5.Filter objects. + * To modify any bands, use methods of the + * p5.Filter API, especially `gain` and `freq`. + * Bands are stored in an array, with indices 0 - 3, or 0 - 7 + * @property {Array} bands + * + */ + + _this.bands = []; + var freq, res; + + for (var i = 0; i < _eqsize; i++) { + if (i === _eqsize - 1) { + freq = 21000; + res = 0.01; + } else if (i === 0) { + freq = 100; + res = 0.1; + } else if (i === 1) { + freq = _eqsize === 3 ? 360 * factor : 360; + res = 1; + } else { + freq = _this.bands[i - 1].freq() * factor; + res = 1; + } + + _this.bands[i] = _this._newBand(freq, res); + + if (i > 0) { + _this.bands[i - 1].connect(_this.bands[i].biquad); + } else { + _this.input.connect(_this.bands[i].biquad); + } + } + + _this.bands[_eqsize - 1].connect(_this.output); + + return _this; + } + /** + * Process an input by connecting it to the EQ + * @method process + * @param {Object} src Audio source + */ + + + eq_createClass(EQ, [{ + key: "process", + value: function process(src) { + src.connect(this.input); + } + // * Set the frequency and gain of each band in the EQ. This method should be + // * called with 3 or 8 frequency and gain pairs, depending on the size of the EQ. + // * ex. eq.set(freq0, gain0, freq1, gain1, freq2, gain2); + // * + // * @method set + // * @for p5.EQ + // * @param {Number} [freq0] Frequency value for band with index 0 + // * @param {Number} [gain0] Gain value for band with index 0 + // * @param {Number} [freq1] Frequency value for band with index 1 + // * @param {Number} [gain1] Gain value for band with index 1 + // * @param {Number} [freq2] Frequency value for band with index 2 + // * @param {Number} [gain2] Gain value for band with index 2 + // * @param {Number} [freq3] Frequency value for band with index 3 + // * @param {Number} [gain3] Gain value for band with index 3 + // * @param {Number} [freq4] Frequency value for band with index 4 + // * @param {Number} [gain4] Gain value for band with index 4 + // * @param {Number} [freq5] Frequency value for band with index 5 + // * @param {Number} [gain5] Gain value for band with index 5 + // * @param {Number} [freq6] Frequency value for band with index 6 + // * @param {Number} [gain6] Gain value for band with index 6 + // * @param {Number} [freq7] Frequency value for band with index 7 + // * @param {Number} [gain7] Gain value for band with index 7 + // */ + + }, { + key: "set", + value: function set() { + if (arguments.length === this.bands.length * 2) { + for (var i = 0; i < arguments.length; i += 2) { + this.bands[i / 2].freq(arguments[i]); + this.bands[i / 2].gain(arguments[i + 1]); + } + } else { + console.error('Argument mismatch. .set() should be called with ' + this.bands.length * 2 + ' arguments. (one frequency and gain value pair for each band of the eq)'); + } + } + /** + * Add a new band. Creates a p5.Filter and strips away everything but + * the raw biquad filter. This method returns an abstracted p5.Filter, + * which can be added to p5.EQ.bands, in order to create new EQ bands. + * @private + * @for p5.EQ + * @method _newBand + * @param {Number} freq + * @param {Number} res + * @return {Object} Abstracted Filter + */ + + }, { + key: "_newBand", + value: function _newBand(freq, res) { + return new eqFilter(freq, res); + } + }, { + key: "dispose", + value: function dispose() { + eq_get(eq_getPrototypeOf(EQ.prototype), "dispose", this).call(this); + + if (this.bands) { + while (this.bands.length > 0) { + delete this.bands.pop().dispose(); + } + + delete this.bands; + } + } + }]); + + return EQ; +}(effect); + + var eq = (eq_EQ); +function listener3d_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function listener3d_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function listener3d_createClass(Constructor, protoProps, staticProps) { if (protoProps) listener3d_defineProperties(Constructor.prototype, protoProps); if (staticProps) listener3d_defineProperties(Constructor, staticProps); return Constructor; } + +// * listener is a class that can construct both a Spatial Panner +// * and a Spatial Listener. The panner is based on the +// * Web Audio Spatial Panner Node +// * https://www.w3.org/TR/webaudio/#the-listenernode-interface +// * This panner is a spatial processing node that allows audio to be positioned +// * and oriented in 3D space. +// * +// * The Listener modifies the properties of the Audio Context Listener. +// * Both objects types use the same methods. The default is a spatial panner. +// * +// * p5.Panner3D - Constructs a Spatial Panner
    +// * p5.Listener3D - Constructs a Spatial Listener
    +// * +// * @class listener +// * @constructor +// * @return {Object} p5.Listener3D Object +// * +// * @param {Web Audio Node} listener Web Audio Spatial Panning Node +// * @param {AudioParam} listener.panningModel "equal power" or "HRTF" +// * @param {AudioParam} listener.distanceModel "linear", "inverse", or "exponential" +// * @param {String} [type] [Specify construction of a spatial panner or listener] +// */ + +var listener3d_Listener3D = +function () { + function Listener3D(type) { + listener3d_classCallCheck(this, Listener3D); + + this.ac = master.audiocontext; + this.listener = this.ac.listener; + } + // * Connect an audio sorce + // * @param {Object} src Input source + // */ + + + listener3d_createClass(Listener3D, [{ + key: "process", + value: function process(src) { + src.connect(this.input); + } + // * Set the X,Y,Z position of the Panner + // * @param {[Number]} xVal + // * @param {[Number]} yVal + // * @param {[Number]} zVal + // * @param {[Number]} time + // * @return {[Array]} [Updated x, y, z values as an array] + // */ + + }, { + key: "position", + value: function position(xVal, yVal, zVal, time) { + this.positionX(xVal, time); + this.positionY(yVal, time); + this.positionZ(zVal, time); + return [this.listener.positionX.value, this.listener.positionY.value, this.listener.positionZ.value]; + } + // * Getter and setter methods for position coordinates + // * @return {Number} [updated coordinate value] + // */ + + }, { + key: "positionX", + value: function positionX(xVal, time) { + var t = time || 0; + + if (typeof xVal === 'number') { + this.listener.positionX.value = xVal; + this.listener.positionX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.positionX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.listener.positionX); + } + + return this.listener.positionX.value; + } + }, { + key: "positionY", + value: function positionY(yVal, time) { + var t = time || 0; + + if (typeof yVal === 'number') { + this.listener.positionY.value = yVal; + this.listener.positionY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.positionY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.listener.positionY); + } + + return this.listener.positionY.value; + } + }, { + key: "positionZ", + value: function positionZ(zVal, time) { + var t = time || 0; + + if (typeof zVal === 'number') { + this.listener.positionZ.value = zVal; + this.listener.positionZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.positionZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.listener.positionZ); + } + + return this.listener.positionZ.value; + } + // * Overrides the listener orient() method because Listener has slightly + // * different params. In human terms, Forward vectors are the direction the + // * nose is pointing. Up vectors are the direction of the top of the head. + // * + // * @method orient + // * @param {Number} xValF Forward vector X direction + // * @param {Number} yValF Forward vector Y direction + // * @param {Number} zValF Forward vector Z direction + // * @param {Number} xValU Up vector X direction + // * @param {Number} yValU Up vector Y direction + // * @param {Number} zValU Up vector Z direction + // * @param {Number} time + // * @return {Array} All orienation params + // */ + + }, { + key: "orient", + value: function orient(xValF, yValF, zValF, xValU, yValU, zValU, time) { + if (arguments.length === 3 || arguments.length === 4) { + time = arguments[3]; + this.orientForward(xValF, yValF, zValF, time); + } else if (arguments.length === 6 || arguments === 7) { + this.orientForward(xValF, yValF, zValF); + this.orientUp(xValU, yValU, zValU, time); + } + + return [this.listener.forwardX.value, this.listener.forwardY.value, this.listener.forwardZ.value, this.listener.upX.value, this.listener.upY.value, this.listener.upZ.value]; + } + }, { + key: "orientForward", + value: function orientForward(xValF, yValF, zValF, time) { + this.forwardX(xValF, time); + this.forwardY(yValF, time); + this.forwardZ(zValF, time); + return [this.listener.forwardX, this.listener.forwardY, this.listener.forwardZ]; + } + }, { + key: "orientUp", + value: function orientUp(xValU, yValU, zValU, time) { + this.upX(xValU, time); + this.upY(yValU, time); + this.upZ(zValU, time); + return [this.listener.upX, this.listener.upY, this.listener.upZ]; + } + // * Getter and setter methods for orient coordinates + // * @return {Number} [updated coordinate value] + // */ + + }, { + key: "forwardX", + value: function forwardX(xVal, time) { + var t = time || 0; + + if (typeof xVal === 'number') { + this.listener.forwardX.value = xVal; + this.listener.forwardX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.forwardX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.listener.forwardX); + } + + return this.listener.forwardX.value; + } + }, { + key: "forwardY", + value: function forwardY(yVal, time) { + var t = time || 0; + + if (typeof yVal === 'number') { + this.listener.forwardY.value = yVal; + this.listener.forwardY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.forwardY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.listener.forwardY); + } + + return this.listener.forwardY.value; + } + }, { + key: "forwardZ", + value: function forwardZ(zVal, time) { + var t = time || 0; + + if (typeof zVal === 'number') { + this.listener.forwardZ.value = zVal; + this.listener.forwardZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.forwardZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.listener.forwardZ); + } + + return this.listener.forwardZ.value; + } + }, { + key: "upX", + value: function upX(xVal, time) { + var t = time || 0; + + if (typeof xVal === 'number') { + this.listener.upX.value = xVal; + this.listener.upX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.upX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.listener.upX); + } + + return this.listener.upX.value; + } + }, { + key: "upY", + value: function upY(yVal, time) { + var t = time || 0; + + if (typeof yVal === 'number') { + this.listener.upY.value = yVal; + this.listener.upY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.upY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.listener.upY); + } + + return this.listener.upY.value; + } + }, { + key: "upZ", + value: function upZ(zVal, time) { + var t = time || 0; + + if (typeof zVal === 'number') { + this.listener.upZ.value = zVal; + this.listener.upZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.listener.upZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.listener.upZ); + } + + return this.listener.upZ.value; + } + }]); + + return Listener3D; +}(); + + var listener3d = (listener3d_Listener3D); +function panner3d_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { panner3d_typeof = function _typeof(obj) { return typeof obj; }; } else { panner3d_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return panner3d_typeof(obj); } + +function panner3d_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function panner3d_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function panner3d_createClass(Constructor, protoProps, staticProps) { if (protoProps) panner3d_defineProperties(Constructor.prototype, protoProps); if (staticProps) panner3d_defineProperties(Constructor, staticProps); return Constructor; } + +function panner3d_possibleConstructorReturn(self, call) { if (call && (panner3d_typeof(call) === "object" || typeof call === "function")) { return call; } return panner3d_assertThisInitialized(self); } + +function panner3d_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function panner3d_get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { panner3d_get = Reflect.get; } else { panner3d_get = function _get(target, property, receiver) { var base = panner3d_superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return panner3d_get(target, property, receiver || target); } + +function panner3d_superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = panner3d_getPrototypeOf(object); if (object === null) break; } return object; } + +function panner3d_getPrototypeOf(o) { panner3d_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return panner3d_getPrototypeOf(o); } + +function panner3d_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) panner3d_setPrototypeOf(subClass, superClass); } + +function panner3d_setPrototypeOf(o, p) { panner3d_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return panner3d_setPrototypeOf(o, p); } + + +/** + * Panner3D is based on the + * Web Audio Spatial Panner Node. + * This panner is a spatial processing node that allows audio to be positioned + * and oriented in 3D space. + * + * The position is relative to an + * Audio Context Listener, which can be accessed + * by p5.soundOut.audiocontext.listener + * + * + * @class p5.Panner3D + * @constructor + */ + +var Panner3D = +function (_Effect) { + panner3d_inherits(Panner3D, _Effect); + + function Panner3D() { + var _this; + + panner3d_classCallCheck(this, Panner3D); + + _this = panner3d_possibleConstructorReturn(this, panner3d_getPrototypeOf(Panner3D).call(this)); + /** + * + * Web Audio Spatial Panner Node + * + * Properties include
    + * [Panning Model](https://www.w3.org/TR/webaudio/#idl-def-PanningModelType) + * : "equal power" or "HRTF"
    + * [DistanceModel](https://www.w3.org/TR/webaudio/#idl-def-DistanceModelType) + * : "linear", "inverse", or "exponential" + * + * @property {AudioNode} panner + * + */ + + _this.panner = _this.ac.createPanner(); + _this.panner.panningModel = 'HRTF'; + _this.panner.distanceModel = 'linear'; + + _this.panner.connect(_this.output); + + _this.input.connect(_this.panner); + + return _this; + } + /** + * Connect an audio sorce + * + * @method process + * @for p5.Panner3D + * @param {Object} src Input source + */ + + + panner3d_createClass(Panner3D, [{ + key: "process", + value: function process(src) { + src.connect(this.input); + } + /** + * Set the X,Y,Z position of the Panner + * @method set + * @for p5.Panner3D + * @param {Number} xVal + * @param {Number} yVal + * @param {Number} zVal + * @param {Number} time + * @return {Array} Updated x, y, z values as an array + */ + + }, { + key: "set", + value: function set(xVal, yVal, zVal, time) { + this.positionX(xVal, time); + this.positionY(yVal, time); + this.positionZ(zVal, time); + return [this.panner.positionX.value, this.panner.positionY.value, this.panner.positionZ.value]; + } + /** + * Getter and setter methods for position coordinates + * @method positionX + * @for p5.Panner3D + * @return {Number} updated coordinate value + */ + + /** + * Getter and setter methods for position coordinates + * @method positionY + * @for p5.Panner3D + * @return {Number} updated coordinate value + */ + + /** + * Getter and setter methods for position coordinates + * @method positionZ + * @for p5.Panner3D + * @return {Number} updated coordinate value + */ + + }, { + key: "positionX", + value: function positionX(xVal, time) { + var t = time || 0; + + if (typeof xVal === 'number') { + this.panner.positionX.value = xVal; + this.panner.positionX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.positionX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.panner.positionX); + } + + return this.panner.positionX.value; + } + }, { + key: "positionY", + value: function positionY(yVal, time) { + var t = time || 0; + + if (typeof yVal === 'number') { + this.panner.positionY.value = yVal; + this.panner.positionY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.positionY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.panner.positionY); + } + + return this.panner.positionY.value; + } + }, { + key: "positionZ", + value: function positionZ(zVal, time) { + var t = time || 0; + + if (typeof zVal === 'number') { + this.panner.positionZ.value = zVal; + this.panner.positionZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.positionZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.panner.positionZ); + } + + return this.panner.positionZ.value; + } + /** + * Set the X,Y,Z position of the Panner + * @method orient + * @for p5.Panner3D + * @param {Number} xVal + * @param {Number} yVal + * @param {Number} zVal + * @param {Number} time + * @return {Array} Updated x, y, z values as an array + */ + + }, { + key: "orient", + value: function orient(xVal, yVal, zVal, time) { + this.orientX(xVal, time); + this.orientY(yVal, time); + this.orientZ(zVal, time); + return [this.panner.orientationX.value, this.panner.orientationY.value, this.panner.orientationZ.value]; + } + /** + * Getter and setter methods for orient coordinates + * @method orientX + * @for p5.Panner3D + * @return {Number} updated coordinate value + */ + + /** + * Getter and setter methods for orient coordinates + * @method orientY + * @for p5.Panner3D + * @return {Number} updated coordinate value + */ + + /** + * Getter and setter methods for orient coordinates + * @method orientZ + * @for p5.Panner3D + * @return {Number} updated coordinate value + */ + + }, { + key: "orientX", + value: function orientX(xVal, time) { + var t = time || 0; + + if (typeof xVal === 'number') { + this.panner.orientationX.value = xVal; + this.panner.orientationX.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.orientationX.linearRampToValueAtTime(xVal, this.ac.currentTime + 0.02 + t); + } else if (xVal) { + xVal.connect(this.panner.orientationX); + } + + return this.panner.orientationX.value; + } + }, { + key: "orientY", + value: function orientY(yVal, time) { + var t = time || 0; + + if (typeof yVal === 'number') { + this.panner.orientationY.value = yVal; + this.panner.orientationY.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.orientationY.linearRampToValueAtTime(yVal, this.ac.currentTime + 0.02 + t); + } else if (yVal) { + yVal.connect(this.panner.orientationY); + } + + return this.panner.orientationY.value; + } + }, { + key: "orientZ", + value: function orientZ(zVal, time) { + var t = time || 0; + + if (typeof zVal === 'number') { + this.panner.orientationZ.value = zVal; + this.panner.orientationZ.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.panner.orientationZ.linearRampToValueAtTime(zVal, this.ac.currentTime + 0.02 + t); + } else if (zVal) { + zVal.connect(this.panner.orientationZ); + } + + return this.panner.orientationZ.value; + } + /** + * Set the rolloff factor and max distance + * @method setFalloff + * @for p5.Panner3D + * @param {Number} [maxDistance] + * @param {Number} [rolloffFactor] + */ + + }, { + key: "setFalloff", + value: function setFalloff(maxDistance, rolloffFactor) { + this.maxDist(maxDistance); + this.rolloff(rolloffFactor); + } + /** + * Maxium distance between the source and the listener + * @method maxDist + * @for p5.Panner3D + * @param {Number} maxDistance + * @return {Number} updated value + */ + + }, { + key: "maxDist", + value: function maxDist(maxDistance) { + if (typeof maxDistance === 'number') { + this.panner.maxDistance = maxDistance; + } + + return this.panner.maxDistance; + } + /** + * How quickly the volume is reduced as the source moves away from the listener + * @method rollof + * @for p5.Panner3D + * @param {Number} rolloffFactor + * @return {Number} updated value + */ + + }, { + key: "rolloff", + value: function rolloff(rolloffFactor) { + if (typeof rolloffFactor === 'number') { + this.panner.rolloffFactor = rolloffFactor; + } + + return this.panner.rolloffFactor; + } + }, { + key: "dispose", + value: function dispose() { + panner3d_get(panner3d_getPrototypeOf(Panner3D.prototype), "dispose", this).call(this); + + if (this.panner) { + this.panner.disconnect(); + delete this.panner; + } + } + }]); + + return Panner3D; +}(effect); + + var panner3d = (Panner3D); +function delay_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { delay_typeof = function _typeof(obj) { return typeof obj; }; } else { delay_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return delay_typeof(obj); } + +function delay_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function delay_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function delay_createClass(Constructor, protoProps, staticProps) { if (protoProps) delay_defineProperties(Constructor.prototype, protoProps); if (staticProps) delay_defineProperties(Constructor, staticProps); return Constructor; } + +function delay_possibleConstructorReturn(self, call) { if (call && (delay_typeof(call) === "object" || typeof call === "function")) { return call; } return delay_assertThisInitialized(self); } + +function delay_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function delay_get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { delay_get = Reflect.get; } else { delay_get = function _get(target, property, receiver) { var base = delay_superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return delay_get(target, property, receiver || target); } + +function delay_superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = delay_getPrototypeOf(object); if (object === null) break; } return object; } + +function delay_getPrototypeOf(o) { delay_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return delay_getPrototypeOf(o); } + +function delay_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) delay_setPrototypeOf(subClass, superClass); } + +function delay_setPrototypeOf(o, p) { delay_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return delay_setPrototypeOf(o, p); } + + + +/** + * Delay is an echo effect. It processes an existing sound source, + * and outputs a delayed version of that sound. The p5.Delay can + * produce different effects depending on the delayTime, feedback, + * filter, and type. In the example below, a feedback of 0.5 (the + * default value) will produce a looping delay that decreases in + * volume by 50% each repeat. A filter will cut out the high + * frequencies so that the delay does not sound as piercing as the + * original source. + * + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * @class p5.Delay + * @extends p5.Effect + * @constructor + * @example + *
    + * let osc; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * background(220); + * textAlign(CENTER); + * text('tap to play', width/2, height/2); + * + * osc = new p5.Oscillator('square'); + * osc.amp(0.5); + * delay = new p5.Delay(); + * + * // delay.process() accepts 4 parameters: + * // source, delayTime (in seconds), feedback, filter frequency + * delay.process(osc, 0.12, .7, 2300); + * + * cnv.mousePressed(oscStart); + * } + * + * function oscStart() { + * osc.start(); + * } + * + * function mouseReleased() { + * osc.stop(); + * } + *
    + */ + +var delay_Delay = +function (_Effect) { + delay_inherits(Delay, _Effect); + + function Delay() { + var _this; + + delay_classCallCheck(this, Delay); + + _this = delay_possibleConstructorReturn(this, delay_getPrototypeOf(Delay).call(this)); + _this._split = _this.ac.createChannelSplitter(2); + _this._merge = _this.ac.createChannelMerger(2); + _this._leftGain = _this.ac.createGain(); + _this._rightGain = _this.ac.createGain(); + /** + * The p5.Delay is built with two + * + * Web Audio Delay Nodes, one for each stereo channel. + * + * @for p5.Delay + * @property {DelayNode} leftDelay + */ + + _this.leftDelay = _this.ac.createDelay(); + /** + * The p5.Delay is built with two + * + * Web Audio Delay Nodes, one for each stereo channel. + * @for p5.Delay + * @property {DelayNode} rightDelay + */ + + _this.rightDelay = _this.ac.createDelay(); + _this._leftFilter = new filter(); + _this._rightFilter = new filter(); + + _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(0.3, _this.ac.currentTime); + + _this._rightFilter.biquad.Q.setValueAtTime(0.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(0.5); + + return _this; + } + /** + * Add delay to an audio signal according to a set + * of delay parameters. + * + * @method process + * @for p5.Delay + * @param {Object} Signal An object that outputs audio + * @param {Number} [delayTime] Time (in seconds) of the delay/echo. + * Some browsers limit delayTime to + * 1 second. + * @param {Number} [feedback] sends the delay back through itself + * in a loop that decreases in volume + * each time. + * @param {Number} [lowPass] Cutoff frequency. Only frequencies + * below the lowPass will be part of the + * delay. + */ + + + delay_createClass(Delay, [{ + key: "process", + value: function process(src, _delayTime, _feedback, _filter) { + var feedback = _feedback || 0; + var delayTime = _delayTime || 0; + + if (feedback >= 1.0) { + throw new Error('Feedback value will force a positive feedback loop.'); + } + + if (delayTime >= this._maxDelay) { + throw new Error('Delay Time exceeds maximum delay time of ' + this._maxDelay + ' second.'); + } + + src.connect(this.input); + this.leftDelay.delayTime.setValueAtTime(delayTime, this.ac.currentTime); + this.rightDelay.delayTime.setValueAtTime(delayTime, this.ac.currentTime); + this._leftGain.gain.value = feedback; + this._rightGain.gain.value = feedback; + + if (_filter) { + this._leftFilter.freq(_filter); + + this._rightFilter.freq(_filter); + } + } + /** + * Set the delay (echo) time, in seconds. Usually this value will be + * a floating point number between 0.0 and 1.0. + * + * @method delayTime + * @for p5.Delay + * @param {Number} delayTime Time (in seconds) of the delay + */ + + }, { + key: "delayTime", + value: function delayTime(t) { + if (typeof t !== 'number') { + t.connect(this.leftDelay.delayTime); + t.connect(this.rightDelay.delayTime); + } else { + 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); + } + } + /** + * Feedback occurs when Delay sends its signal back through its input + * in a loop. The feedback amount determines how much signal to send each + * time through the loop. A feedback greater than 1.0 is not desirable because + * it will increase the overall output each time through the loop, + * creating an infinite feedback loop. The default value is 0.5 + * + * @method feedback + * @for p5.Delay + * @param {Number|Object} feedback 0.0 to 1.0, or an object such as an + * Oscillator that can be used to + * modulate this param + * @returns {Number} Feedback value + * + */ + + }, { + key: "feedback", + value: function feedback(f) { + if (f && typeof f !== 'number') { + f.connect(this._leftGain.gain); + f.connect(this._rightGain.gain); + } else if (f >= 1.0) { + throw new Error('Feedback value will force a positive feedback loop.'); + } else if (typeof f === 'number') { + this._leftGain.gain.value = f; + this._rightGain.gain.value = f; + } + + + return this._leftGain.gain.value; + } + /** + * Set a lowpass filter frequency for the delay. A lowpass filter + * will cut off any frequencies higher than the filter frequency. + * + * @method filter + * @for p5.Delay + * @param {Number|Object} cutoffFreq A lowpass filter will cut off any + * frequencies higher than the filter frequency. + * @param {Number|Object} res Resonance of the filter frequency + * cutoff, or an object (i.e. a p5.Oscillator) + * that can be used to modulate this parameter. + * High numbers (i.e. 15) will produce a resonance, + * low numbers (i.e. .2) will produce a slope. + */ + + }, { + key: "filter", + value: function filter(freq, q) { + this._leftFilter.set(freq, q); + + this._rightFilter.set(freq, q); + } + /** + * Choose a preset type of delay. 'pingPong' bounces the signal + * from the left to the right channel to produce a stereo effect. + * Any other parameter will revert to the default delay setting. + * + * @method setType + * @for p5.Delay + * @param {String|Number} type 'pingPong' (1) or 'default' (0) + */ + + }, { + key: "setType", + value: function setType(t) { + if (t === 1) { + t = 'pingPong'; + } + + this._split.disconnect(); + + this._leftFilter.disconnect(); + + this._rightFilter.disconnect(); + + this._split.connect(this.leftDelay, 0); + + this._split.connect(this.rightDelay, 1); + + switch (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); + + } + } + + /** + * Set the output level of the delay effect. + * + * @method amp + * @for p5.Delay + * @param {Number} volume amplitude between 0 and 1.0 + * @param {Number} [rampTime] create a fade that lasts rampTime + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + */ + + /** + * Send output to a p5.sound or web audio object + * + * @method connect + * @for p5.Delay + * @param {Object} unit + */ + + /** + * Disconnect all output. + * + * @method disconnect + * @for p5.Delay + */ + + }, { + key: "dispose", + value: function dispose() { + delay_get(delay_getPrototypeOf(Delay.prototype), "dispose", this).call(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 = undefined; + this._leftFilter = undefined; + this._rightFilter = undefined; + this._merge = undefined; + this._leftGain = undefined; + this._rightGain = undefined; + this.leftDelay = undefined; + this.rightDelay = undefined; + } + }]); + + return Delay; +}(effect); + + var delay = (delay_Delay); +function reverb_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { reverb_typeof = function _typeof(obj) { return typeof obj; }; } else { reverb_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return reverb_typeof(obj); } + +function reverb_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function reverb_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function reverb_createClass(Constructor, protoProps, staticProps) { if (protoProps) reverb_defineProperties(Constructor.prototype, protoProps); if (staticProps) reverb_defineProperties(Constructor, staticProps); return Constructor; } + +function reverb_possibleConstructorReturn(self, call) { if (call && (reverb_typeof(call) === "object" || typeof call === "function")) { return call; } return reverb_assertThisInitialized(self); } + +function reverb_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function reverb_get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { reverb_get = Reflect.get; } else { reverb_get = function _get(target, property, receiver) { var base = reverb_superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return reverb_get(target, property, receiver || target); } + +function reverb_superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = reverb_getPrototypeOf(object); if (object === null) break; } return object; } + +function reverb_getPrototypeOf(o) { reverb_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return reverb_getPrototypeOf(o); } + +function reverb_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) reverb_setPrototypeOf(subClass, superClass); } + +function reverb_setPrototypeOf(o, p) { reverb_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return reverb_setPrototypeOf(o, p); } + + + + +/** + * Reverb adds depth to a sound through a large number of decaying + * echoes. It creates the perception that sound is occurring in a + * physical space. The p5.Reverb has paramters for Time (how long does the + * reverb last) and decayRate (how much the sound decays with each echo) + * that can be set with the .set() or .process() methods. The p5.Convolver + * extends p5.Reverb allowing you to recreate the sound of actual physical + * spaces through convolution. + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.Reverb + * @extends p5.Effect + * @constructor + * @example + *
    + * let soundFile, reverb; + * function preload() { + * soundFile = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playSound); + * + * reverb = new p5.Reverb(); + * soundFile.disconnect(); // so we'll only hear reverb... + * + * // connect soundFile to reverb, process w/ + * // 3 second reverbTime, decayRate of 2% + * reverb.process(soundFile, 3, 2); + * } + * + * function draw() { + * let dryWet = constrain(map(mouseX, 0, width, 0, 1), 0, 1); + * // 1 = all reverb, 0 = no reverb + * reverb.drywet(dryWet); + * + * background(220); + * text('tap to play', 10, 20); + * text('dry/wet: ' + round(dryWet * 100) + '%', 10, height - 20); + * } + * + * function playSound() { + * soundFile.play(); + * } + *
    + */ + +var Reverb = +function (_Effect) { + reverb_inherits(Reverb, _Effect); + + function Reverb() { + var _this; + + reverb_classCallCheck(this, Reverb); + + _this = reverb_possibleConstructorReturn(this, reverb_getPrototypeOf(Reverb).call(this)); + + _this._initConvolverNode(); + + + _this.input.gain.value = 0.5; + + _this._seconds = 3; + _this._decay = 2; + _this._reverse = false; + + _this._buildImpulse(); + + return _this; + } + + reverb_createClass(Reverb, [{ + key: "_initConvolverNode", + value: function _initConvolverNode() { + this.convolverNode = this.ac.createConvolver(); + this.input.connect(this.convolverNode); + this.convolverNode.connect(this.wet); + } + }, { + key: "_teardownConvolverNode", + value: function _teardownConvolverNode() { + if (this.convolverNode) { + this.convolverNode.disconnect(); + delete this.convolverNode; + } + } + }, { + key: "_setBuffer", + value: function _setBuffer(audioBuffer) { + this._teardownConvolverNode(); + + this._initConvolverNode(); + + this.convolverNode.buffer = audioBuffer; + } + /** + * Connect a source to the reverb, and assign reverb parameters. + * + * @method process + * @for p5.Reverb + * @param {Object} src p5.sound / Web Audio object with a sound + * output. + * @param {Number} [seconds] Duration of the reverb, in seconds. + * Min: 0, Max: 10. Defaults to 3. + * @param {Number} [decayRate] Percentage of decay with each echo. + * Min: 0, Max: 100. Defaults to 2. + * @param {Boolean} [reverse] Play the reverb backwards or forwards. + */ + + }, { + key: "process", + value: function process(src, seconds, decayRate, reverse) { + src.connect(this.input); + var rebuild = false; + + if (seconds) { + this._seconds = seconds; + rebuild = true; + } + + if (decayRate) { + this._decay = decayRate; + } + + if (reverse) { + this._reverse = reverse; + } + + if (rebuild) { + this._buildImpulse(); + } + } + /** + * Set the reverb settings. Similar to .process(), but without + * assigning a new input. + * + * @method set + * @for p5.Reverb + * @param {Number} [seconds] Duration of the reverb, in seconds. + * Min: 0, Max: 10. Defaults to 3. + * @param {Number} [decayRate] Percentage of decay with each echo. + * Min: 0, Max: 100. Defaults to 2. + * @param {Boolean} [reverse] Play the reverb backwards or forwards. + */ + + }, { + key: "set", + value: function set(seconds, decayRate, reverse) { + var rebuild = false; + + if (seconds) { + this._seconds = seconds; + rebuild = true; + } + + if (decayRate) { + this._decay = decayRate; + } + + if (reverse) { + this._reverse = reverse; + } + + if (rebuild) { + this._buildImpulse(); + } + } + + /** + * Set the output level of the reverb effect. + * + * @method amp + * @for p5.Reverb + * @param {Number} volume amplitude between 0 and 1.0 + * @param {Number} [rampTime] create a fade that lasts rampTime + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + */ + + /** + * Send output to a p5.sound or web audio object + * + * @method connect + * @for p5.Reverb + * @param {Object} unit + */ + + /** + * Disconnect all output. + * + * @method disconnect + * @for p5.Reverb + */ + + /** + * Inspired by Simple Reverb by Jordan Santell + * https://github.com/web-audio-components/simple-reverb/blob/master/index.js + * + * Utility function for building an impulse response + * based on the module parameters. + * + * @private + */ + + }, { + key: "_buildImpulse", + value: function _buildImpulse() { + var rate = this.ac.sampleRate; + var length = rate * this._seconds; + var decay = this._decay; + var impulse = this.ac.createBuffer(2, length, rate); + var impulseL = impulse.getChannelData(0); + var impulseR = impulse.getChannelData(1); + var n, i; + + for (i = 0; i < length; i++) { + n = this._reverse ? length - i : i; + impulseL[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay); + impulseR[i] = (Math.random() * 2 - 1) * Math.pow(1 - n / length, decay); + } + + this._setBuffer(impulse); + } + }, { + key: "dispose", + value: function dispose() { + reverb_get(reverb_getPrototypeOf(Reverb.prototype), "dispose", this).call(this); + + this._teardownConvolverNode(); + } + }]); + + return Reverb; +}(effect); + +/** + *

    p5.Convolver extends p5.Reverb. It can emulate the sound of real + * physical spaces through a process called + * convolution.

    + * + *

    Convolution multiplies any audio input by an "impulse response" + * to simulate the dispersion of sound over time. The impulse response is + * generated from an audio file that you provide. One way to + * generate an impulse response is to pop a balloon in a reverberant space + * and record the echo. Convolution can also be used to experiment with + * sound.

    + * + *

    Use the method createConvolution(path) to instantiate a + * p5.Convolver with a path to your impulse response audio file.

    + * + * @class p5.Convolver + * @extends p5.Effect + * @constructor + * @param {String} path path to a sound file + * @param {Function} [callback] function to call when loading succeeds + * @param {Function} [errorCallback] function to call if loading fails. + * This function will receive an error or + * XMLHttpRequest object with information + * about what went wrong. + * @example + *
    + * let cVerb, sound; + * function preload() { + * // We have both MP3 and OGG versions of all sound assets + * soundFormats('ogg', 'mp3'); + * + * // Try replacing 'bx-spring' with other soundfiles like + * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' + * cVerb = createConvolver('assets/bx-spring.mp3'); + * + * // Try replacing 'Damscray_DancingTiger' with + * // 'beat', 'doorbell', lucky_dragons_-_power_melody' + * sound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playSound); + * background(220); + * text('tap to play', 20, 20); + * + * // disconnect from master output... + * sound.disconnect(); + * + * // ...and process with cVerb + * // so that we only hear the convolution + * cVerb.process(sound); + * } + * + * function playSound() { + * sound.play(); + * } + *
    + */ + + +var reverb_Convolver = +function (_Reverb) { + reverb_inherits(Convolver, _Reverb); + + function Convolver(path, callback, errorCallback) { + var _this2; + + reverb_classCallCheck(this, Convolver); + + _this2 = reverb_possibleConstructorReturn(this, reverb_getPrototypeOf(Convolver).call(this)); + /** + * Internally, the p5.Convolver uses the a + * + * Web Audio Convolver Node. + * + * @property {ConvolverNode} convolverNode + */ + + _this2._initConvolverNode(); + + + _this2.input.gain.value = 0.5; + + if (path) { + _this2.impulses = []; + + _this2._loadBuffer(path, callback, errorCallback); + } else { + _this2._seconds = 3; + _this2._decay = 2; + _this2._reverse = false; + + _this2._buildImpulse(); + } + /** + * If you load multiple impulse files using the .addImpulse method, + * they will be stored as Objects in this Array. Toggle between them + * with the toggleImpulse(id) method. + * + * @property {Array} impulses + * @for p5.Convolver + */ + + + _this2.impulses = []; + _this2.set = null; + return _this2; + } + /** + * Private method to load a buffer as an Impulse Response, + * assign it to the convolverNode, and add to the Array of .impulses. + * + * @param {String} path + * @param {Function} callback + * @param {Function} errorCallback + * @private + */ + + + reverb_createClass(Convolver, [{ + key: "_loadBuffer", + value: function _loadBuffer(_path, callback, errorCallback) { + var path = p5.prototype._checkFileFormats(_path); + + var self = this; + var errorTrace = new Error().stack; + var ac = Object(audiocontext["b" ])(); + var request = new XMLHttpRequest(); + request.open('GET', path, true); + request.responseType = 'arraybuffer'; + + request.onload = function () { + if (request.status === 200) { + ac.decodeAudioData(request.response, function (buff) { + var buffer = {}; + var chunks = path.split('/'); + buffer.name = chunks[chunks.length - 1]; + buffer.audioBuffer = buff; + self.impulses.push(buffer); + + self._setBuffer(buffer.audioBuffer); + + if (callback) { + callback(buffer); + } + }, + function () { + var err = new errorHandler('decodeAudioData', errorTrace, self.url); + var msg = 'AudioContext error at decodeAudioData for ' + self.url; + + if (errorCallback) { + err.msg = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + }); + } + else { + var err = new errorHandler('loadConvolver', errorTrace, self.url); + var msg = 'Unable to load ' + self.url + '. The request status was: ' + request.status + ' (' + request.statusText + ')'; + + if (errorCallback) { + err.message = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + } + }; + + + request.onerror = function () { + var err = new errorHandler('loadConvolver', errorTrace, self.url); + var msg = 'There was no response from the server at ' + self.url + '. Check the url and internet connectivity.'; + + if (errorCallback) { + err.message = msg; + errorCallback(err); + } else { + console.error(msg + '\n The error stack trace includes: \n' + err.stack); + } + }; + + request.send(); + } + /** + * Connect a source to the convolver. + * + * @method process + * @for p5.Convolver + * @param {Object} src p5.sound / Web Audio object with a sound + * output. + * @example + *
    + * let cVerb, sound; + * function preload() { + * // We have both MP3 and OGG versions of all sound assets + * soundFormats('ogg', 'mp3'); + * + * // Try replacing 'bx-spring' with other soundfiles like + * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' + * cVerb = createConvolver('assets/bx-spring.mp3'); + * + * // Try replacing 'Damscray_DancingTiger' with + * // 'beat', 'doorbell', lucky_dragons_-_power_melody' + * sound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playSound); + * background(220); + * text('tap to play', 20, 20); + * + * // disconnect from master output... + * sound.disconnect(); + * + * // ...and process with cVerb + * // so that we only hear the convolution + * cVerb.process(sound); + * } + * + * function playSound() { + * sound.play(); + * } + * + *
    + */ + + }, { + key: "process", + value: function process(src) { + src.connect(this.input); + } + /** + * Load and assign a new Impulse Response to the p5.Convolver. + * The impulse is added to the .impulses array. Previous + * impulses can be accessed with the .toggleImpulse(id) + * method. + * + * @method addImpulse + * @for p5.Convolver + * @param {String} path path to a sound file + * @param {Function} callback function (optional) + * @param {Function} errorCallback function (optional) + */ + + }, { + key: "addImpulse", + value: function addImpulse(path, callback, errorCallback) { + if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { + alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); + } + + this._loadBuffer(path, callback, errorCallback); + } + /** + * Similar to .addImpulse, except that the .impulses + * Array is reset to save memory. A new .impulses + * array is created with this impulse as the only item. + * + * @method resetImpulse + * @for p5.Convolver + * @param {String} path path to a sound file + * @param {Function} callback function (optional) + * @param {Function} errorCallback function (optional) + */ + + }, { + key: "resetImpulse", + value: function resetImpulse(path, callback, errorCallback) { + if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { + alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); + } + + this.impulses = []; + + this._loadBuffer(path, callback, errorCallback); + } + /** + * If you have used .addImpulse() to add multiple impulses + * to a p5.Convolver, then you can use this method to toggle between + * the items in the .impulses Array. Accepts a parameter + * to identify which impulse you wish to use, identified either by its + * original filename (String) or by its position in the .impulses + * Array (Number).
    + * You can access the objects in the .impulses Array directly. Each + * Object has two attributes: an .audioBuffer (type: + * Web Audio + * AudioBuffer) and a .name, a String that corresponds + * with the original filename. + * + * @method toggleImpulse + * @for p5.Convolver + * @param {String|Number} id Identify the impulse by its original filename + * (String), or by its position in the + * .impulses Array (Number). + */ + + }, { + key: "toggleImpulse", + value: function toggleImpulse(id) { + if (typeof id === 'number' && id < this.impulses.length) { + this._setBuffer(this.impulses[id].audioBuffer); + } + + if (typeof id === 'string') { + for (var i = 0; i < this.impulses.length; i++) { + if (this.impulses[i].name === id) { + this._setBuffer(this.impulses[i].audioBuffer); + + break; + } + } + } + } + }, { + key: "dispose", + value: function dispose() { + reverb_get(reverb_getPrototypeOf(Convolver.prototype), "dispose", this).call(this); + + + for (var i in this.impulses) { + if (this.impulses[i]) { + this.impulses[i] = null; + } + } + } + }]); + + return Convolver; +}(Reverb); +/** + * Create a p5.Convolver. Accepts a path to a soundfile + * that will be used to generate an impulse response. + * + * @method createConvolver + * @for p5 + * @param {String} path path to a sound file + * @param {Function} [callback] function to call if loading is successful. + * The object will be passed in as the argument + * to the callback function. + * @param {Function} [errorCallback] function to call if loading is not successful. + * A custom error will be passed in as the argument + * to the callback function. + * @return {p5.Convolver} + * @example + *
    + * let cVerb, sound; + * function preload() { + * // We have both MP3 and OGG versions of all sound assets + * soundFormats('ogg', 'mp3'); + * + * // Try replacing 'bx-spring' with other soundfiles like + * // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox' + * cVerb = createConvolver('assets/bx-spring.mp3'); + * + * // Try replacing 'Damscray_DancingTiger' with + * // 'beat', 'doorbell', lucky_dragons_-_power_melody' + * sound = loadSound('assets/Damscray_DancingTiger.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playSound); + * background(220); + * text('tap to play', 20, 20); + * + * // disconnect from master output... + * sound.disconnect(); + * + * // ...and process with cVerb + * // so that we only hear the convolution + * cVerb.process(sound); + * } + * + * function playSound() { + * sound.play(); + * } + *
    + */ + + +function createConvolver(path, callback, errorCallback) { + if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') { + alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS'); + } + + var self = this; + var cReverb = new reverb_Convolver(path, function (buffer) { + if (typeof callback === 'function') { + callback(buffer); + } + + if (typeof self._decrementPreload === 'function') { + self._decrementPreload(); + } + }, errorCallback); + cReverb.impulses = []; + return cReverb; +} + + +var Clock = __webpack_require__(11); +var Clock_default = __webpack_require__.n(Clock); + +function metro_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function metro_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function metro_createClass(Constructor, protoProps, staticProps) { if (protoProps) metro_defineProperties(Constructor.prototype, protoProps); if (staticProps) metro_defineProperties(Constructor, staticProps); return Constructor; } + + + + +var metro_Metro = +function () { + function Metro() { + metro_classCallCheck(this, Metro); + + this.clock = new Clock_default.a({ + callback: this.ontick.bind(this) + }); + this.syncedParts = []; + this.bpm = 120; + + this._init(); + + this.prevTick = 0; + this.tatumTime = 0; + + this.tickCallback = function () {}; + } + + metro_createClass(Metro, [{ + key: "ontick", + value: function ontick(tickTime) { + var elapsedTime = tickTime - this.prevTick; + var secondsFromNow = tickTime - master.audiocontext.currentTime; + + if (elapsedTime - this.tatumTime <= -0.02) { + return; + } else { + this.prevTick = tickTime; + + var self = this; + this.syncedParts.forEach(function (thisPart) { + if (!thisPart.isPlaying) return; + thisPart.incrementStep(secondsFromNow); + + thisPart.phrases.forEach(function (thisPhrase) { + var phraseArray = thisPhrase.sequence; + var bNum = self.metroTicks % phraseArray.length; + + if (phraseArray[bNum] !== 0 && (self.metroTicks < phraseArray.length || !thisPhrase.looping)) { + thisPhrase.callback(secondsFromNow, phraseArray[bNum]); + } + }); + }); + this.metroTicks += 1; + this.tickCallback(secondsFromNow); + } + } + }, { + key: "setBPM", + value: function setBPM(bpm) { + var rampTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var beatTime = 60 / (bpm * this.tatums); + var now = master.audiocontext.currentTime; + this.tatumTime = beatTime; + this.clock.frequency.setValueAtTime(this.clock.frequency.value, now); + this.clock.frequency.linearRampToValueAtTime(bpm, now + rampTime); + this.bpm = bpm; + } + }, { + key: "getBPM", + value: function getBPM() { + return this.clock.getRate() / this.tatums * 60; + } + }, { + key: "_init", + value: function _init() { + this.metroTicks = 0; + } + + }, { + key: "resetSync", + value: function resetSync(part) { + this.syncedParts = [part]; + } + + }, { + key: "pushSync", + value: function pushSync(part) { + this.syncedParts.push(part); + } + }, { + key: "start", + value: function start(timeFromNow) { + var t = timeFromNow || 0; + var now = master.audiocontext.currentTime; + this.clock.start(now + t); + this.setBPM(this.bpm); + } + }, { + key: "stop", + value: function stop(timeFromNow) { + var t = timeFromNow || 0; + var now = master.audiocontext.currentTime; + this.clock.stop(now + t); + } + }, { + key: "beatLength", + value: function beatLength(tatums) { + this.tatums = 1 / tatums / 4; + } + }]); + + return Metro; +}(); + + var metro = (metro_Metro); +function looper_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function looper_createClass(Constructor, protoProps, staticProps) { if (protoProps) looper_defineProperties(Constructor.prototype, protoProps); if (staticProps) looper_defineProperties(Constructor, staticProps); return Constructor; } + +function looper_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + +var BPM = 120; +/** + * Set the global tempo, in beats per minute, for all + * p5.Parts. This method will impact all active p5.Parts. + * + * @method setBPM + * @for p5 + * @param {Number} BPM Beats Per Minute + * @param {Number} rampTime Seconds from now + */ + +p5.prototype.setBPM = function (bpm, rampTime) { + BPM = bpm; + + for (var i in master.parts) { + if (master.parts[i]) { + master.parts[i].setBPM(bpm, rampTime); + } + } +}; +/** + *

    A phrase is a pattern of musical events over time, i.e. + * a series of notes and rests.

    + * + *

    Phrases must be added to a p5.Part for playback, and + * each part can play multiple phrases at the same time. + * For example, one Phrase might be a kick drum, another + * could be a snare, and another could be the bassline.

    + * + *

    The first parameter is a name so that the phrase can be + * modified or deleted later. The callback is a a function that + * this phrase will call at every step—for example it might be + * called playNote(value){}. The array determines + * which value is passed into the callback at each step of the + * phrase. It can be numbers, an object with multiple numbers, + * or a zero (0) indicates a rest so the callback won't be called).

    + * + * @class p5.Phrase + * @constructor + * @param {String} name Name so that you can access the Phrase. + * @param {Function} callback The name of a function that this phrase + * will call. Typically it will play a sound, + * and accept two parameters: a time at which + * to play the sound (in seconds from now), + * and a value from the sequence array. The + * time should be passed into the play() or + * start() method to ensure precision. + * @param {Array} sequence Array of values to pass into the callback + * at each step of the phrase. + * @example + *
    + * let mySound, myPhrase, myPart; + * let pattern = [1,0,0,2,0,2,0,0]; + * + * function preload() { + * mySound = loadSound('assets/beatbox.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playMyPart); + * background(220); + * text('tap to play', width/2, height/2); + * textAlign(CENTER, CENTER); + * + * myPhrase = new p5.Phrase('bbox', onEachStep, pattern); + * myPart = new p5.Part(); + * myPart.addPhrase(myPhrase); + * myPart.setBPM(60); + * } + * + * function onEachStep(time, playbackRate) { + * mySound.rate(playbackRate); + * mySound.play(time); + * } + * + * function playMyPart() { + * userStartAudio(); + * myPart.start(); + * } + *
    + */ + + +var Phrase = function Phrase(name, callback, sequence) { + looper_classCallCheck(this, Phrase); + + this.phraseStep = 0; + this.name = name; + this.callback = callback; + /** + * Array of values to pass into the callback + * at each step of the phrase. Depending on the callback + * function's requirements, these values may be numbers, + * strings, or an object with multiple parameters. + * Zero (0) indicates a rest. + * + * @property {Array} sequence + */ + + this.sequence = sequence; +}; +/** + *

    A p5.Part plays back one or more p5.Phrases. Instantiate a part + * with steps and tatums. By default, each step represents a 1/16th note.

    + * + *

    See p5.Phrase for more about musical timing.

    + * + * @class p5.Part + * @constructor + * @param {Number} [steps] Steps in the part + * @param {Number} [tatums] Divisions of a beat, e.g. use 1/4, or 0.25 for a quater note (default is 1/16, a sixteenth note) + * @example + *
    + * let box, drum, myPart; + * let boxPat = [1,0,0,2,0,2,0,0]; + * let drumPat = [0,1,1,0,2,0,1,0]; + * + * function preload() { + * box = loadSound('assets/beatbox.mp3'); + * drum = loadSound('assets/drum.mp3'); + * } + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playMyPart); + * background(220); + * textAlign(CENTER, CENTER); + * text('tap to play', width/2, height/2); + * + * let boxPhrase = new p5.Phrase('box', playBox, boxPat); + * let drumPhrase = new p5.Phrase('drum', playDrum, drumPat); + * myPart = new p5.Part(); + * myPart.addPhrase(boxPhrase); + * myPart.addPhrase(drumPhrase); + * myPart.setBPM(60); + * } + * + * function playBox(time, playbackRate) { + * box.rate(playbackRate); + * box.play(time); + * } + * + * function playDrum(time, playbackRate) { + * drum.rate(playbackRate); + * drum.play(time); + * } + * + * function playMyPart() { + * userStartAudio(); + * + * myPart.start(); + * } + *
    + */ + + +var looper_Part = +function () { + function Part(steps, bLength) { + looper_classCallCheck(this, Part); + + this.length = steps || 0; + + this.partStep = 0; + this.phrases = []; + this.isPlaying = false; + this.noLoop(); + this.tatums = bLength || 0.0625; + + this.metro = new metro(); + + this.metro._init(); + + this.metro.beatLength(this.tatums); + this.metro.setBPM(BPM); + master.parts.push(this); + + this.callback = function () {}; + } + /** + * Set the tempo of this part, in Beats Per Minute. + * + * @method setBPM + * @for p5.Part + * @param {Number} BPM Beats Per Minute + * @param {Number} [rampTime] Seconds from now + */ + + + looper_createClass(Part, [{ + key: "setBPM", + value: function setBPM(tempo, rampTime) { + this.metro.setBPM(tempo, rampTime); + } + /** + * Returns the tempo, in Beats Per Minute, of this part. + * + * @method getBPM + * @for p5.Part + * @return {Number} + */ + + }, { + key: "getBPM", + value: function getBPM() { + return this.metro.getBPM(); + } + /** + * Start playback of this part. It will play + * through all of its phrases at a speed + * determined by setBPM. + * + * @method start + * @for p5.Part + * @param {Number} [time] seconds from now + */ + + }, { + key: "start", + value: function start(time) { + if (!this.isPlaying) { + this.isPlaying = true; + this.metro.resetSync(this); + var t = time || 0; + this.metro.start(t); + } + } + /** + * Loop playback of this part. It will begin + * looping through all of its phrases at a speed + * determined by setBPM. + * + * @method loop + * @for p5.Part + * @param {Number} [time] seconds from now + */ + + }, { + key: "loop", + value: function loop(time) { + this.looping = true; + + this.onended = function () { + this.partStep = 0; + }; + + var t = time || 0; + this.start(t); + } + /** + * Tell the part to stop looping. + * + * @method noLoop + * @for p5.Part + */ + + }, { + key: "noLoop", + value: function noLoop() { + this.looping = false; + + this.onended = function () { + this.stop(); + }; + } + /** + * Stop the part and cue it to step 0. Playback will resume from the begining of the Part when it is played again. + * + * @method stop + * @for p5.Part + * @param {Number} [time] seconds from now + */ + + }, { + key: "stop", + value: function stop(time) { + this.partStep = 0; + this.pause(time); + } + /** + * Pause the part. Playback will resume + * from the current step. + * + * @method pause + * @for p5.Part + * @param {Number} time seconds from now + */ + + }, { + key: "pause", + value: function pause(time) { + this.isPlaying = false; + var t = time || 0; + this.metro.stop(t); + } + /** + * Add a p5.Phrase to this Part. + * + * @method addPhrase + * @for p5.Part + * @param {p5.Phrase} phrase reference to a p5.Phrase + */ + + }, { + key: "addPhrase", + value: function addPhrase(name, callback, array) { + var p; + + if (arguments.length === 3) { + p = new Phrase(name, callback, array); + } else if (arguments[0] instanceof Phrase) { + p = arguments[0]; + } else { + throw 'invalid input. addPhrase accepts name, callback, array or a p5.Phrase'; + } + + this.phrases.push(p); + + if (p.sequence.length > this.length) { + this.length = p.sequence.length; + } + } + /** + * Remove a phrase from this part, based on the name it was + * given when it was created. + * + * @method removePhrase + * @for p5.Part + * @param {String} phraseName + */ + + }, { + key: "removePhrase", + value: function removePhrase(name) { + for (var i in this.phrases) { + if (this.phrases[i].name === name) { + this.phrases.splice(i, 1); + } + } + } + /** + * Get a phrase from this part, based on the name it was + * given when it was created. Now you can modify its array. + * + * @method getPhrase + * @for p5.Part + * @param {String} phraseName + */ + + }, { + key: "getPhrase", + value: function getPhrase(name) { + for (var i in this.phrases) { + if (this.phrases[i].name === name) { + return this.phrases[i]; + } + } + } + /** + * Find all sequences with the specified name, and replace their patterns with the specified array. + * + * @method replaceSequence + * @for p5.Part + * @param {String} phraseName + * @param {Array} sequence Array of values to pass into the callback + * at each step of the phrase. + */ + + }, { + key: "replaceSequence", + value: function replaceSequence(name, array) { + for (var i in this.phrases) { + if (this.phrases[i].name === name) { + this.phrases[i].sequence = array; + } + } + } + }, { + key: "incrementStep", + value: function incrementStep(time) { + if (this.partStep < this.length - 1) { + this.callback(time); + this.partStep += 1; + } else { + if (!this.looping && this.partStep === this.length - 1) { + this.onended(); + } + } + } + /** + * Set the function that will be called at every step. This will clear the previous function. + * + * @method onStep + * @for p5.Part + * @param {Function} callback The name of the callback + * you want to fire + * on every beat/tatum. + */ + + }, { + key: "onStep", + value: function onStep(callback) { + this.callback = callback; + } + }]); + + return Part; +}(); + +/** + * A Score consists of a series of Parts. The parts will + * be played back in order. For example, you could have an + * A part, a B part, and a C part, and play them back in this order + * new p5.Score(a, a, b, a, c) + * + * @class p5.Score + * @constructor + * @param {p5.Part} [...parts] One or multiple parts, to be played in sequence. + */ + + +var Score = +function () { + function Score() { + looper_classCallCheck(this, Score); + + this.parts = []; + this.currentPart = 0; + var thisScore = this; + + for (var i in arguments) { + if (arguments[i] && this.parts[i]) { + this.parts[i] = arguments[i]; + this.parts[i].nextPart = this.parts[i + 1]; + + this.parts[i].onended = function () { + thisScore.resetPart(i); + playNextPart(thisScore); + }; + } + } + + this.looping = false; + } + + looper_createClass(Score, [{ + key: "onended", + value: function onended() { + if (this.looping) { + this.parts[0].start(); + } else { + this.parts[this.parts.length - 1].onended = function () { + this.stop(); + this.resetParts(); + }; + } + + this.currentPart = 0; + } + /** + * Start playback of the score. + * + * @method start + * @for p5.Score + */ + + }, { + key: "start", + value: function start() { + this.parts[this.currentPart].start(); + this.scoreStep = 0; + } + /** + * Stop playback of the score. + * + * @method stop + * @for p5.Score + */ + + }, { + key: "stop", + value: function stop() { + this.parts[this.currentPart].stop(); + this.currentPart = 0; + this.scoreStep = 0; + } + /** + * Pause playback of the score. + * + * @method pause + * @for p5.Score + */ + + }, { + key: "pause", + value: function pause() { + this.parts[this.currentPart].stop(); + } + /** + * Loop playback of the score. + * + * @method loop + * @for p5.Score + */ + + }, { + key: "loop", + value: function loop() { + this.looping = true; + this.start(); + } + /** + * Stop looping playback of the score. If it + * is currently playing, this will go into effect + * after the current round of playback completes. + * + * @method noLoop + * @for p5.Score + */ + + }, { + key: "noLoop", + value: function noLoop() { + this.looping = false; + } + }, { + key: "resetParts", + value: function resetParts() { + var self = this; + this.parts.forEach(function (part) { + self.resetParts[part]; + }); + } + }, { + key: "resetPart", + value: function resetPart(i) { + this.parts[i].stop(); + this.parts[i].partStep = 0; + + for (var p in this.parts[i].phrases) { + if (this.parts[i]) { + this.parts[i].phrases[p].phraseStep = 0; + } + } + } + /** + * Set the tempo for all parts in the score + * + * @method setBPM + * @for p5.Score + * @param {Number} BPM Beats Per Minute + * @param {Number} rampTime Seconds from now + */ + + }, { + key: "setBPM", + value: function setBPM(bpm, rampTime) { + for (var i in this.parts) { + if (this.parts[i]) { + this.parts[i].setBPM(bpm, rampTime); + } + } + } + }]); + + return Score; +}(); + +function playNextPart(aScore) { + aScore.currentPart++; + + if (aScore.currentPart >= aScore.parts.length) { + aScore.scoreStep = 0; + aScore.onended(); + } else { + aScore.scoreStep = 0; + aScore.parts[aScore.currentPart - 1].stop(); + aScore.parts[aScore.currentPart].start(); + } +} + + +function soundLoop_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function soundLoop_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function soundLoop_createClass(Constructor, protoProps, staticProps) { if (protoProps) soundLoop_defineProperties(Constructor.prototype, protoProps); if (staticProps) soundLoop_defineProperties(Constructor, staticProps); return Constructor; } + + + +/** + * SoundLoop + * + * @class p5.SoundLoop + * @constructor + * + * @param {Function} callback this function will be called on each iteration of theloop + * @param {Number|String} [interval] amount of time (if a number) or beats (if a string, following Tone.Time convention) for each iteration of the loop. Defaults to 1 second. + * + * @example + *
    + * let synth, soundLoop; + * let notePattern = [60, 62, 64, 67, 69, 72]; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * colorMode(HSB); + * background(0, 0, 86); + * text('tap to start/stop', 10, 20); + * + * //the looper's callback is passed the timeFromNow + * //this value should be used as a reference point from + * //which to schedule sounds + * let intervalInSeconds = 0.2; + * soundLoop = new p5.SoundLoop(onSoundLoop, intervalInSeconds); + * + * synth = new p5.MonoSynth(); + * } + * + * function canvasPressed() { + * // ensure audio is enabled + * userStartAudio(); + * + * if (soundLoop.isPlaying) { + * soundLoop.stop(); + * } else { + * // start the loop + * soundLoop.start(); + * } + * } + * + * function onSoundLoop(timeFromNow) { + * let noteIndex = (soundLoop.iterations - 1) % notePattern.length; + * let note = midiToFreq(notePattern[noteIndex]); + * synth.play(note, 0.5, timeFromNow); + * background(noteIndex * 360 / notePattern.length, 50, 100); + * } + *
    + */ + +var soundLoop_SoundLoop = +function () { + function SoundLoop(callback, interval) { + soundLoop_classCallCheck(this, SoundLoop); + + /** + * Getters and Setters, setting any paramter will result in a change in the clock's + * frequency, that will be reflected after the next callback + * beats per minute (defaults to 60) + * @property {Number} bpm + * @for p5.SoundLoop + */ + Object.defineProperty(this, 'bpm', { + get: function get() { + return this._bpm; + }, + set: function set(bpm) { + if (!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 = bpm; + + this._update(); + } + }); + /** + * number of quarter notes in a measure (defaults to 4) + * @property {Number} timeSignature + * @for p5.SoundLoop + */ + + Object.defineProperty(this, 'timeSignature', { + get: function get() { + return this._timeSignature; + }, + set: function set(timeSig) { + if (!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 = timeSig; + + this._update(); + } + }); + /** + * length of the loops interval + * @property {Number|String} interval + * @for p5.SoundLoop + */ + + Object.defineProperty(this, 'interval', { + get: function get() { + return this._interval; + }, + set: function set(interval) { + this.musicalTimeMode = typeof interval === 'number' ? false : true; + this._interval = interval; + + this._update(); + } + }); + /** + * how many times the callback has been called so far + * @property {Number} iterations + * @for p5.SoundLoop + * @readonly + */ + + Object.defineProperty(this, 'iterations', { + get: function get() { + return this.clock.ticks; + } + }); + this.callback = callback; + /** + * musicalTimeMode uses Tone.Time convention + * true if string, false if number + * @property {Boolean} musicalTimeMode + */ + + this.musicalTimeMode = typeof this._interval === 'number' ? false : true; + this._interval = interval || 1; + /** + * musicalTimeMode variables + * modify these only when the interval is specified in musicalTime format as a string + */ + + this._timeSignature = 4; + this._bpm = 60; + this.isPlaying = false; + /** + * Set a limit to the number of loops to play. defaults to Infinity + * @property {Number} maxIterations + */ + + this.maxIterations = Infinity; + var self = this; + this.clock = new Clock_default.a({ + callback: function callback(time) { + var timeFromNow = time - master.audiocontext.currentTime; + /** + * Do not initiate the callback if timeFromNow is < 0 + * This ususually occurs for a few milliseconds when the page + * is not fully loaded + * + * The callback should only be called until maxIterations is reached + */ + + if (timeFromNow > 0 && self.iterations <= self.maxIterations) { + self.callback(timeFromNow); + } + }, + frequency: this._calcFreq() + }); + } + /** + * Start the loop + * @method start + * @for p5.SoundLoop + * @param {Number} [timeFromNow] schedule a starting time + */ + + + soundLoop_createClass(SoundLoop, [{ + key: "start", + value: function start(timeFromNow) { + var t = timeFromNow || 0; + var now = master.audiocontext.currentTime; + + if (!this.isPlaying) { + this.clock.start(now + t); + this.isPlaying = true; + } + } + /** + * Stop the loop + * @method stop + * @for p5.SoundLoop + * @param {Number} [timeFromNow] schedule a stopping time + */ + + }, { + key: "stop", + value: function stop(timeFromNow) { + var t = timeFromNow || 0; + var now = master.audiocontext.currentTime; + + if (this.isPlaying) { + this.clock.stop(now + t); + this.isPlaying = false; + } + } + /** + * Pause the loop + * @method pause + * @for p5.SoundLoop + * @param {Number} [timeFromNow] schedule a pausing time + */ + + }, { + key: "pause", + value: function pause(timeFromNow) { + var t = timeFromNow || 0; + var now = master.audiocontext.currentTime; + + if (this.isPlaying) { + this.clock.pause(now + t); + this.isPlaying = false; + } + } + /** + * Synchronize loops. Use this method to start two or more loops in synchronization + * or to start a loop in synchronization with a loop that is already playing + * This method will schedule the implicit loop in sync with the explicit master loop + * i.e. loopToStart.syncedStart(loopToSyncWith) + * + * @method syncedStart + * @for p5.SoundLoop + * @param {Object} otherLoop a p5.SoundLoop to sync with + * @param {Number} [timeFromNow] Start the loops in sync after timeFromNow seconds + */ + + }, { + key: "syncedStart", + value: function syncedStart(otherLoop, timeFromNow) { + var t = timeFromNow || 0; + var now = master.audiocontext.currentTime; + + if (!otherLoop.isPlaying) { + otherLoop.clock.start(now + t); + otherLoop.isPlaying = true; + this.clock.start(now + t); + this.isPlaying = true; + } else if (otherLoop.isPlaying) { + var time = otherLoop.clock._nextTick - master.audiocontext.currentTime; + this.clock.start(now + time); + this.isPlaying = true; + } + } + /** + * Updates frequency value, reflected in next callback + * @private + * @for p5.SoundLoop + * @method _update + */ + + }, { + key: "_update", + value: function _update() { + this.clock.frequency.value = this._calcFreq(); + } + /** + * Calculate the frequency of the clock's callback based on bpm, interval, and timesignature + * @private + * @for p5.SoundLoop + * @method _calcFreq + * @return {Number} new clock frequency value + */ + + }, { + key: "_calcFreq", + value: function _calcFreq() { + if (typeof this._interval === 'number') { + this.musicalTimeMode = false; + return 1 / this._interval; + } + else if (typeof this._interval === 'string') { + this.musicalTimeMode = true; + return this._bpm / 60 / this._convertNotation(this._interval) * (this._timeSignature / 4); + } + } + /** + * Convert notation from musical time format to seconds + * Uses Tone.Time convention + * @private + * @for p5.SoundLoop + * @method _convertNotation + * @param {String} value value to be converted + * @return {Number} converted value in seconds + */ + + }, { + key: "_convertNotation", + value: function _convertNotation(value) { + var type = value.slice(-1); + value = Number(value.slice(0, -1)); + + switch (type) { + case 'm': + return this._measure(value); + + case 'n': + return this._note(value); + + 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'); + } + } + /** + * Helper conversion methods of measure and note + * @private + * @for p5.SoundLoop + * @method _measure + */ + + }, { + key: "_measure", + value: function _measure(value) { + return value * this._timeSignature; + } + /** + * @private + * @method _note + * @for p5.SoundLoop + */ + + }, { + key: "_note", + value: function _note(value) { + return this._timeSignature / value; + } + }]); + + return SoundLoop; +}(); + + var soundLoop = (soundLoop_SoundLoop); +function compressor_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { compressor_typeof = function _typeof(obj) { return typeof obj; }; } else { compressor_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return compressor_typeof(obj); } + +function compressor_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function compressor_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function compressor_createClass(Constructor, protoProps, staticProps) { if (protoProps) compressor_defineProperties(Constructor.prototype, protoProps); if (staticProps) compressor_defineProperties(Constructor, staticProps); return Constructor; } + +function compressor_possibleConstructorReturn(self, call) { if (call && (compressor_typeof(call) === "object" || typeof call === "function")) { return call; } return compressor_assertThisInitialized(self); } + +function compressor_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function compressor_get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { compressor_get = Reflect.get; } else { compressor_get = function _get(target, property, receiver) { var base = compressor_superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return compressor_get(target, property, receiver || target); } + +function compressor_superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = compressor_getPrototypeOf(object); if (object === null) break; } return object; } + +function compressor_getPrototypeOf(o) { compressor_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return compressor_getPrototypeOf(o); } + +function compressor_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) compressor_setPrototypeOf(subClass, superClass); } + +function compressor_setPrototypeOf(o, p) { compressor_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return compressor_setPrototypeOf(o, p); } + + +/** + * Compressor is an audio effect class that performs dynamics compression + * on an audio input source. This is a very commonly used technique in music + * and sound production. Compression creates an overall louder, richer, + * and fuller sound by lowering the volume of louds and raising that of softs. + * Compression can be used to avoid clipping (sound distortion due to + * peaks in volume) and is especially useful when many sounds are played + * at once. Compression can be used on indivudal sound sources in addition + * to the master output. + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.Compressor + * @constructor + * @extends p5.Effect + * + * + */ + +var Compressor = +function (_Effect) { + compressor_inherits(Compressor, _Effect); + + function Compressor() { + var _this; + + compressor_classCallCheck(this, Compressor); + + _this = compressor_possibleConstructorReturn(this, compressor_getPrototypeOf(Compressor).call(this)); + /** + * + * The p5.Compressor is built with a Web Audio Dynamics Compressor Node + * + * @property {AudioNode} compressor + */ + + _this.compressor = _this.ac.createDynamicsCompressor(); + + _this.input.connect(_this.compressor); + + _this.compressor.connect(_this.wet); + + return _this; + } + /** + * Performs the same function as .connect, but also accepts + * optional parameters to set compressor's audioParams + * @method process + * @for p5.Compressor + * + * @param {Object} src Sound source to be connected + * + * @param {Number} [attack] The amount of time (in seconds) to reduce the gain by 10dB, + * default = .003, range 0 - 1 + * @param {Number} [knee] A decibel value representing the range above the + * threshold where the curve smoothly transitions to the "ratio" portion. + * default = 30, range 0 - 40 + * @param {Number} [ratio] The amount of dB change in input for a 1 dB change in output + * default = 12, range 1 - 20 + * @param {Number} [threshold] The decibel value above which the compression will start taking effect + * default = -24, range -100 - 0 + * @param {Number} [release] The amount of time (in seconds) to increase the gain by 10dB + * default = .25, range 0 - 1 + */ + + + compressor_createClass(Compressor, [{ + key: "process", + value: function process(src, attack, knee, ratio, threshold, release) { + src.connect(this.input); + this.set(attack, knee, ratio, threshold, release); + } + /** + * Set the paramters of a compressor. + * @method set + * @for p5.Compressor + * @param {Number} attack The amount of time (in seconds) to reduce the gain by 10dB, + * default = .003, range 0 - 1 + * @param {Number} knee A decibel value representing the range above the + * threshold where the curve smoothly transitions to the "ratio" portion. + * default = 30, range 0 - 40 + * @param {Number} ratio The amount of dB change in input for a 1 dB change in output + * default = 12, range 1 - 20 + * @param {Number} threshold The decibel value above which the compression will start taking effect + * default = -24, range -100 - 0 + * @param {Number} release The amount of time (in seconds) to increase the gain by 10dB + * default = .25, range 0 - 1 + */ + + }, { + key: "set", + value: function set(attack, knee, ratio, threshold, release) { + if (typeof attack !== 'undefined') { + this.attack(attack); + } + + if (typeof knee !== 'undefined') { + this.knee(knee); + } + + if (typeof ratio !== 'undefined') { + this.ratio(ratio); + } + + if (typeof threshold !== 'undefined') { + this.threshold(threshold); + } + + if (typeof release !== 'undefined') { + this.release(release); + } + } + /** + * Get current attack or set value w/ time ramp + * + * + * @method attack + * @for p5.Compressor + * @param {Number} [attack] Attack is the amount of time (in seconds) to reduce the gain by 10dB, + * default = .003, range 0 - 1 + * @param {Number} [time] Assign time value to schedule the change in value + */ + + }, { + key: "attack", + value: function attack(_attack, time) { + var t = time || 0; + + if (typeof _attack === 'number') { + this.compressor.attack.value = _attack; + this.compressor.attack.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.attack.linearRampToValueAtTime(_attack, this.ac.currentTime + 0.02 + t); + } else if (typeof _attack !== 'undefined') { + _attack.connect(this.compressor.attack); + } + + return this.compressor.attack.value; + } + /** + * Get current knee or set value w/ time ramp + * + * @method knee + * @for p5.Compressor + * @param {Number} [knee] A decibel value representing the range above the + * threshold where the curve smoothly transitions to the "ratio" portion. + * default = 30, range 0 - 40 + * @param {Number} [time] Assign time value to schedule the change in value + */ + + }, { + key: "knee", + value: function knee(_knee, time) { + var t = time || 0; + + if (typeof _knee === 'number') { + this.compressor.knee.value = _knee; + this.compressor.knee.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.knee.linearRampToValueAtTime(_knee, this.ac.currentTime + 0.02 + t); + } else if (typeof _knee !== 'undefined') { + _knee.connect(this.compressor.knee); + } + + return this.compressor.knee.value; + } + /** + * Get current ratio or set value w/ time ramp + * @method ratio + * @for p5.Compressor + * @param {Number} [ratio] The amount of dB change in input for a 1 dB change in output + * default = 12, range 1 - 20 + * @param {Number} [time] Assign time value to schedule the change in value + */ + + }, { + key: "ratio", + value: function ratio(_ratio, time) { + var t = time || 0; + + if (typeof _ratio === 'number') { + this.compressor.ratio.value = _ratio; + this.compressor.ratio.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.ratio.linearRampToValueAtTime(_ratio, this.ac.currentTime + 0.02 + t); + } else if (typeof _ratio !== 'undefined') { + _ratio.connect(this.compressor.ratio); + } + + return this.compressor.ratio.value; + } + /** + * Get current threshold or set value w/ time ramp + * @method threshold + * @for p5.Compressor + * @param {Number} threshold The decibel value above which the compression will start taking effect + * default = -24, range -100 - 0 + * @param {Number} [time] Assign time value to schedule the change in value + */ + + }, { + key: "threshold", + value: function threshold(_threshold, time) { + var t = time || 0; + + if (typeof _threshold === 'number') { + this.compressor.threshold.value = _threshold; + this.compressor.threshold.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.threshold.linearRampToValueAtTime(_threshold, this.ac.currentTime + 0.02 + t); + } else if (typeof _threshold !== 'undefined') { + _threshold.connect(this.compressor.threshold); + } + + return this.compressor.threshold.value; + } + /** + * Get current release or set value w/ time ramp + * @method release + * @for p5.Compressor + * @param {Number} release The amount of time (in seconds) to increase the gain by 10dB + * default = .25, range 0 - 1 + * + * @param {Number} [time] Assign time value to schedule the change in value + */ + + }, { + key: "release", + value: function release(_release, time) { + var t = time || 0; + + if (typeof _release === 'number') { + this.compressor.release.value = _release; + this.compressor.release.cancelScheduledValues(this.ac.currentTime + 0.01 + t); + this.compressor.release.linearRampToValueAtTime(_release, this.ac.currentTime + 0.02 + t); + } else if (typeof number !== 'undefined') { + _release.connect(this.compressor.release); + } + + return this.compressor.release.value; + } + /** + * Return the current reduction value + * + * @method reduction + * @for p5.Compressor + * @return {Number} Value of the amount of gain reduction that is applied to the signal + */ + + }, { + key: "reduction", + value: function reduction() { + return this.compressor.reduction.value; + } + }, { + key: "dispose", + value: function dispose() { + compressor_get(compressor_getPrototypeOf(Compressor.prototype), "dispose", this).call(this); + + if (this.compressor) { + this.compressor.disconnect(); + delete this.compressor; + } + } + }]); + + return Compressor; +}(effect); + + var compressor = (Compressor); +function peakDetect_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function peakDetect_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function peakDetect_createClass(Constructor, protoProps, staticProps) { if (protoProps) peakDetect_defineProperties(Constructor.prototype, protoProps); if (staticProps) peakDetect_defineProperties(Constructor, staticProps); return Constructor; } + +/** + *

    PeakDetect works in conjunction with p5.FFT to + * look for onsets in some or all of the frequency spectrum. + *

    + *

    + * To use p5.PeakDetect, call update in the draw loop + * and pass in a p5.FFT object. + *

    + *

    + * You can listen for a specific part of the frequency spectrum by + * setting the range between freq1 and freq2. + *

    + * + *

    threshold is the threshold for detecting a peak, + * scaled between 0 and 1. It is logarithmic, so 0.1 is half as loud + * as 1.0.

    + * + *

    + * The update method is meant to be run in the draw loop, and + * frames determines how many loops must pass before + * another peak can be detected. + * For example, if the frameRate() = 60, you could detect the beat of a + * 120 beat-per-minute song with this equation: + * framesPerPeak = 60 / (estimatedBPM / 60 ); + *

    + * + *

    + * Based on example contribtued by @b2renger, and a simple beat detection + * explanation by Felix Turner. + *

    + * + * @class p5.PeakDetect + * @constructor + * @param {Number} [freq1] lowFrequency - defaults to 20Hz + * @param {Number} [freq2] highFrequency - defaults to 20000 Hz + * @param {Number} [threshold] Threshold for detecting a beat between 0 and 1 + * scaled logarithmically where 0.1 is 1/2 the loudness + * of 1.0. Defaults to 0.35. + * @param {Number} [framesPerPeak] Defaults to 20. + * @example + *
    + * + * var cnv, soundFile, fft, peakDetect; + * var ellipseWidth = 10; + * + * function preload() { + * soundFile = loadSound('assets/beat.mp3'); + * } + * + * function setup() { + * background(0); + * noStroke(); + * fill(255); + * textAlign(CENTER); + * + * // p5.PeakDetect requires a p5.FFT + * fft = new p5.FFT(); + * peakDetect = new p5.PeakDetect(); + * } + * + * function draw() { + * background(0); + * text('click to play/pause', width/2, height/2); + * + * // peakDetect accepts an fft post-analysis + * fft.analyze(); + * peakDetect.update(fft); + * + * if ( peakDetect.isDetected ) { + * ellipseWidth = 50; + * } else { + * ellipseWidth *= 0.95; + * } + * + * ellipse(width/2, height/2, ellipseWidth, ellipseWidth); + * } + * + * // toggle play/stop when canvas is clicked + * function mouseClicked() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * if (soundFile.isPlaying() ) { + * soundFile.stop(); + * } else { + * soundFile.play(); + * } + * } + * } + *
    + */ +var PeakDetect = +function () { + function PeakDetect(freq1, freq2, threshold, _framesPerPeak) { + peakDetect_classCallCheck(this, PeakDetect); + + this.framesPerPeak = _framesPerPeak || 20; + this.framesSinceLastPeak = 0; + this.decayRate = 0.95; + this.threshold = threshold || 0.35; + this.cutoff = 0; + + this.cutoffMult = 1.5; + this.energy = 0; + this.penergy = 0; + + this.currentValue = 0; + /** + * isDetected is set to true when a peak is detected. + * + * @attribute isDetected {Boolean} + * @default false + */ + + this.isDetected = false; + this.f1 = freq1 || 40; + this.f2 = freq2 || 20000; + + this._onPeak = function () {}; + } + /** + * The update method is run in the draw loop. + * + * Accepts an FFT object. You must call .analyze() + * on the FFT object prior to updating the peakDetect + * because it relies on a completed FFT analysis. + * + * @method update + * @param {p5.FFT} fftObject A p5.FFT object + */ + + + peakDetect_createClass(PeakDetect, [{ + key: "update", + value: function update(fftObject) { + var nrg = this.energy = fftObject.getEnergy(this.f1, this.f2) / 255; + + if (nrg > this.cutoff && nrg > this.threshold && nrg - this.penergy > 0) { + this._onPeak(); + + this.isDetected = true; + + this.cutoff = nrg * this.cutoffMult; + this.framesSinceLastPeak = 0; + } else { + this.isDetected = false; + + if (this.framesSinceLastPeak <= this.framesPerPeak) { + this.framesSinceLastPeak++; + } else { + this.cutoff *= this.decayRate; + this.cutoff = Math.max(this.cutoff, this.threshold); + } + } + + this.currentValue = nrg; + this.penergy = nrg; + } + /** + * onPeak accepts two arguments: a function to call when + * a peak is detected. The value of the peak, + * between 0.0 and 1.0, is passed to the callback. + * + * @method onPeak + * @param {Function} callback Name of a function that will + * be called when a peak is + * detected. + * @param {Object} [val] Optional value to pass + * into the function when + * a peak is detected. + * @example + *
    + * var cnv, soundFile, fft, peakDetect; + * var ellipseWidth = 0; + * + * function preload() { + * soundFile = loadSound('assets/beat.mp3'); + * } + * + * function setup() { + * cnv = createCanvas(100,100); + * textAlign(CENTER); + * + * fft = new p5.FFT(); + * peakDetect = new p5.PeakDetect(); + * + * setupSound(); + * + * // when a beat is detected, call triggerBeat() + * peakDetect.onPeak(triggerBeat); + * } + * + * function draw() { + * background(0); + * fill(255); + * text('click to play', width/2, height/2); + * + * fft.analyze(); + * peakDetect.update(fft); + * + * ellipseWidth *= 0.95; + * ellipse(width/2, height/2, ellipseWidth, ellipseWidth); + * } + * + * // this function is called by peakDetect.onPeak + * function triggerBeat() { + * ellipseWidth = 50; + * } + * + * // mouseclick starts/stops sound + * function setupSound() { + * cnv.mouseClicked( function() { + * if (soundFile.isPlaying() ) { + * soundFile.stop(); + * } else { + * soundFile.play(); + * } + * }); + * } + *
    + */ + + }, { + key: "onPeak", + value: function onPeak(callback, val) { + var self = this; + + self._onPeak = function () { + callback(self.energy, val); + }; + } + }]); + + return PeakDetect; +}(); + + var peakDetect = (PeakDetect); +function soundRecorder_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function soundRecorder_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function soundRecorder_createClass(Constructor, protoProps, staticProps) { if (protoProps) soundRecorder_defineProperties(Constructor.prototype, protoProps); if (staticProps) soundRecorder_defineProperties(Constructor, staticProps); return Constructor; } + + + + +var soundRecorder_ac = master.audiocontext; +/** + *

    Record sounds for playback and/or to save as a .wav file. + * The p5.SoundRecorder records all sound output from your sketch, + * or can be assigned a specific source with setInput().

    + *

    The record() method accepts a p5.SoundFile as a parameter. + * When playback is stopped (either after the given amount of time, + * or with the stop() method), the p5.SoundRecorder will send its + * recording to that p5.SoundFile for playback.

    + * + * @class p5.SoundRecorder + * @constructor + * @example + *
    + * let mic, recorder, soundFile; + * let state = 0; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(canvasPressed); + * background(220); + * textAlign(CENTER, CENTER); + * + * // create an audio in + * mic = new p5.AudioIn(); + * + * // prompts user to enable their browser mic + * mic.start(); + * + * // create a sound recorder + * recorder = new p5.SoundRecorder(); + * + * // connect the mic to the recorder + * recorder.setInput(mic); + * + * // this sound file will be used to + * // playback & save the recording + * soundFile = new p5.SoundFile(); + * + * text('tap to record', width/2, height/2); + * } + * + * function canvasPressed() { + * // ensure audio is enabled + * userStartAudio(); + * + * // make sure user enabled the mic + * if (state === 0 && mic.enabled) { + * + * // record to our p5.SoundFile + * recorder.record(soundFile); + * + * background(255,0,0); + * text('Recording!', width/2, height/2); + * state++; + * } + * else if (state === 1) { + * background(0,255,0); + * + * // stop recorder and + * // send result to soundFile + * recorder.stop(); + * + * text('Done! Tap to play and download', width/2, height/2, width - 20); + * state++; + * } + * + * else if (state === 2) { + * soundFile.play(); // play the result! + * save(soundFile, 'mySound.wav'); + * state++; + * } + * } + *
    + */ + +var soundRecorder_SoundRecorder = +function () { + function SoundRecorder() { + soundRecorder_classCallCheck(this, SoundRecorder); + + this.input = soundRecorder_ac.createGain(); + this.output = soundRecorder_ac.createGain(); + this._inputChannels = 2; + this._outputChannels = 2; + + var workletBufferSize = safeBufferSize(1024); + this._workletNode = new AudioWorkletNode(soundRecorder_ac, processorNames_default.a.recorderProcessor, { + outputChannelCount: [this._outputChannels], + processorOptions: { + numInputChannels: this._inputChannels, + bufferSize: workletBufferSize + } + }); + + this._workletNode.port.onmessage = function (event) { + if (event.data.name === 'buffers') { + var buffers = [new Float32Array(event.data.leftBuffer), new Float32Array(event.data.rightBuffer)]; + + this._callback(buffers); + } + }.bind(this); + /** + * callback invoked when the recording is over + * @private + * @type Function(Float32Array) + */ + + + this._callback = function () {}; + + + this._workletNode.connect(p5.soundOut._silentNode); + + this.setInput(); + + master.soundArray.push(this); + } + /** + * Connect a specific device to the p5.SoundRecorder. + * If no parameter is given, p5.SoundRecorer will record + * all audible p5.sound from your sketch. + * + * @method setInput + * @for p5.SoundRecorder + * @param {Object} [unit] p5.sound object or a web audio unit + * that outputs sound + */ + + + soundRecorder_createClass(SoundRecorder, [{ + key: "setInput", + value: function setInput(unit) { + this.input.disconnect(); + this.input = null; + this.input = soundRecorder_ac.createGain(); + this.input.connect(this._workletNode); + this.input.connect(this.output); + + if (unit) { + unit.connect(this.input); + } else { + p5.soundOut.output.connect(this.input); + } + } + /** + * Start recording. To access the recording, provide + * a p5.SoundFile as the first parameter. The p5.SoundRecorder + * will send its recording to that p5.SoundFile for playback once + * recording is complete. Optional parameters include duration + * (in seconds) of the recording, and a callback function that + * will be called once the complete recording has been + * transfered to the p5.SoundFile. + * + * @method record + * @for p5.SoundRecorder + * @param {p5.SoundFile} soundFile p5.SoundFile + * @param {Number} [duration] Time (in seconds) + * @param {Function} [callback] The name of a function that will be + * called once the recording completes + */ + + }, { + key: "record", + value: function record(sFile, duration, callback) { + this._workletNode.port.postMessage({ + name: 'start', + duration: duration + }); + + if (sFile && callback) { + this._callback = function (buffer) { + sFile.setBuffer(buffer); + callback(); + }; + } else if (sFile) { + this._callback = function (buffer) { + sFile.setBuffer(buffer); + }; + } + } + /** + * Stop the recording. Once the recording is stopped, + * the results will be sent to the p5.SoundFile that + * was given on .record(), and if a callback function + * was provided on record, that function will be called. + * + * @method stop + * @for p5.SoundRecorder + */ + + }, { + key: "stop", + value: function stop() { + this._workletNode.port.postMessage({ + name: 'stop' + }); + } + }, { + key: "dispose", + value: function dispose() { + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + + this._callback = function () {}; + + if (this.input) { + this.input.disconnect(); + } + + this.input = null; + this._workletNode = null; + } + }]); + + return SoundRecorder; +}(); + + var soundRecorder = (soundRecorder_SoundRecorder); +function distortion_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { distortion_typeof = function _typeof(obj) { return typeof obj; }; } else { distortion_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return distortion_typeof(obj); } + +function distortion_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function distortion_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function distortion_createClass(Constructor, protoProps, staticProps) { if (protoProps) distortion_defineProperties(Constructor.prototype, protoProps); if (staticProps) distortion_defineProperties(Constructor, staticProps); return Constructor; } + +function distortion_possibleConstructorReturn(self, call) { if (call && (distortion_typeof(call) === "object" || typeof call === "function")) { return call; } return distortion_assertThisInitialized(self); } + +function distortion_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function distortion_get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { distortion_get = Reflect.get; } else { distortion_get = function _get(target, property, receiver) { var base = distortion_superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return distortion_get(target, property, receiver || target); } + +function distortion_superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = distortion_getPrototypeOf(object); if (object === null) break; } return object; } + +function distortion_getPrototypeOf(o) { distortion_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return distortion_getPrototypeOf(o); } + +function distortion_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) distortion_setPrototypeOf(subClass, superClass); } + +function distortion_setPrototypeOf(o, p) { distortion_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return distortion_setPrototypeOf(o, p); } + + + +function makeDistortionCurve(amount) { + var k = typeof amount === 'number' ? amount : 50; + var numSamples = 44100; + var curve = new Float32Array(numSamples); + var deg = Math.PI / 180; + var i = 0; + var x; + + for (; i < numSamples; ++i) { + x = i * 2 / numSamples - 1; + curve[i] = (3 + k) * x * 20 * deg / (Math.PI + k * Math.abs(x)); + } + + return curve; +} +/** + * A Distortion effect created with a Waveshaper Node, + * with an approach adapted from + * [Kevin Ennis](http://stackoverflow.com/questions/22312841/waveshaper-node-in-webaudio-how-to-emulate-distortion) + * + * This class extends p5.Effect. + * Methods amp(), chain(), + * drywet(), connect(), and + * disconnect() are available. + * + * @class p5.Distortion + * @extends p5.Effect + * @constructor + * @param {Number} [amount=0.25] Unbounded distortion amount. + * Normal values range from 0-1. + * @param {String} [oversample='none'] 'none', '2x', or '4x'. + * + */ + + +var Distortion = +function (_Effect) { + distortion_inherits(Distortion, _Effect); + + function Distortion(amount, oversample) { + var _this; + + distortion_classCallCheck(this, Distortion); + + _this = distortion_possibleConstructorReturn(this, distortion_getPrototypeOf(Distortion).call(this)); + + if (typeof amount === 'undefined') { + amount = 0.25; + } + + if (typeof amount !== 'number') { + throw new Error('amount must be a number'); + } + + if (typeof oversample === 'undefined') { + oversample = '2x'; + } + + if (typeof oversample !== 'string') { + throw new Error('oversample must be a String'); + } + + var curveAmount = p5.prototype.map(amount, 0.0, 1.0, 0, 2000); + /** + * The p5.Distortion is built with a + * + * Web Audio WaveShaper Node. + * + * @property {AudioNode} WaveShaperNode + */ + + _this.waveShaperNode = _this.ac.createWaveShaper(); + _this.amount = curveAmount; + _this.waveShaperNode.curve = makeDistortionCurve(curveAmount); + _this.waveShaperNode.oversample = oversample; + + _this.input.connect(_this.waveShaperNode); + + _this.waveShaperNode.connect(_this.wet); + + return _this; + } + /** + * Process a sound source, optionally specify amount and oversample values. + * + * @method process + * @for p5.Distortion + * @param {Number} [amount=0.25] Unbounded distortion amount. + * Normal values range from 0-1. + * @param {String} [oversample='none'] 'none', '2x', or '4x'. + */ + + + distortion_createClass(Distortion, [{ + key: "process", + value: function process(src, amount, oversample) { + src.connect(this.input); + this.set(amount, oversample); + } + /** + * Set the amount and oversample of the waveshaper distortion. + * + * @method set + * @for p5.Distortion + * @param {Number} [amount=0.25] Unbounded distortion amount. + * Normal values range from 0-1. + * @param {String} [oversample='none'] 'none', '2x', or '4x'. + */ + + }, { + key: "set", + value: function set(amount, oversample) { + if (amount) { + var curveAmount = p5.prototype.map(amount, 0.0, 1.0, 0, 2000); + this.amount = curveAmount; + this.waveShaperNode.curve = makeDistortionCurve(curveAmount); + } + + if (oversample) { + this.waveShaperNode.oversample = oversample; + } + } + /** + * Return the distortion amount, typically between 0-1. + * + * @method getAmount + * @for p5.Distortion + * @return {Number} Unbounded distortion amount. + * Normal values range from 0-1. + */ + + }, { + key: "getAmount", + value: function getAmount() { + return this.amount; + } + /** + * Return the oversampling. + * + * @method getOversample + * @for p5.Distortion + * @return {String} Oversample can either be 'none', '2x', or '4x'. + */ + + }, { + key: "getOversample", + value: function getOversample() { + return this.waveShaperNode.oversample; + } + }, { + key: "dispose", + value: function dispose() { + distortion_get(distortion_getPrototypeOf(Distortion.prototype), "dispose", this).call(this); + + if (this.waveShaperNode) { + this.waveShaperNode.disconnect(); + this.waveShaperNode = null; + } + } + }]); + + return Distortion; +}(effect); + + var distortion = (Distortion); +function gain_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function gain_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function gain_createClass(Constructor, protoProps, staticProps) { if (protoProps) gain_defineProperties(Constructor.prototype, protoProps); if (staticProps) gain_defineProperties(Constructor, staticProps); return Constructor; } + + +/** + * A gain node is usefull to set the relative volume of sound. + * It's typically used to build mixers. + * + * @class p5.Gain + * @constructor + * @example + *
    + * + * // load two soundfile and crossfade beetween them + * let sound1,sound2; + * let sound1Gain, sound2Gain, masterGain; + * function preload(){ + * soundFormats('ogg', 'mp3'); + * sound1 = loadSound('assets/Damscray_-_Dancing_Tiger_01'); + * sound2 = loadSound('assets/beat'); + * } + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(startSound); + * // create a 'master' gain to which we will connect both soundfiles + * masterGain = new p5.Gain(); + * masterGain.connect(); + * sound1.disconnect(); // diconnect from p5 output + * sound1Gain = new p5.Gain(); // setup a gain node + * sound1Gain.setInput(sound1); // connect the first sound to its input + * sound1Gain.connect(masterGain); // connect its output to the 'master' + * sound2.disconnect(); + * sound2Gain = new p5.Gain(); + * sound2Gain.setInput(sound2); + * sound2Gain.connect(masterGain); + * } + * function startSound() { + * sound1.loop(); + * sound2.loop(); + * loop(); + * } + * function mouseReleased() { + * sound1.stop(); + * sound2.stop(); + * } + * function draw(){ + * background(220); + * textAlign(CENTER); + * textSize(11); + * fill(0); + * if (!sound1.isPlaying()) { + * text('tap and drag to play', width/2, height/2); + * return; + * } + * // map the horizontal position of the mouse to values useable for volume * control of sound1 + * var sound1Volume = constrain(map(mouseX,width,0,0,1), 0, 1); + * var sound2Volume = 1-sound1Volume; + * sound1Gain.amp(sound1Volume); + * sound2Gain.amp(sound2Volume); + * // map the vertical position of the mouse to values useable for 'master * volume control' + * var masterVolume = constrain(map(mouseY,height,0,0,1), 0, 1); + * masterGain.amp(masterVolume); + * text('master', width/2, height - masterVolume * height * 0.9) + * fill(255, 0, 255); + * textAlign(LEFT); + * text('sound1', 5, height - sound1Volume * height * 0.9); + * textAlign(RIGHT); + * text('sound2', width - 5, height - sound2Volume * height * 0.9); + * } + *
    + */ + +var gain_Gain = +function () { + function Gain() { + gain_classCallCheck(this, Gain); + + this.ac = master.audiocontext; + this.input = this.ac.createGain(); + this.output = this.ac.createGain(); + + this.input.gain.value = 0.5; + this.input.connect(this.output); + + master.soundArray.push(this); + } + /** + * Connect a source to the gain node. + * + * @method setInput + * @for p5.Gain + * @param {Object} src p5.sound / Web Audio object with a sound + * output. + */ + + + gain_createClass(Gain, [{ + key: "setInput", + value: function setInput(src) { + src.connect(this.input); + } + /** + * Send output to a p5.sound or web audio object + * + * @method connect + * @for p5.Gain + * @param {Object} unit + */ + + }, { + key: "connect", + value: function connect(unit) { + var u = unit || p5.soundOut.input; + this.output.connect(u.input ? u.input : u); + } + /** + * Disconnect all output. + * + * @method disconnect + * @for p5.Gain + */ + + }, { + key: "disconnect", + value: function disconnect() { + if (this.output) { + this.output.disconnect(); + } + } + /** + * Set the output level of the gain node. + * + * @method amp + * @for p5.Gain + * @param {Number} volume amplitude between 0 and 1.0 + * @param {Number} [rampTime] create a fade that lasts rampTime + * @param {Number} [timeFromNow] schedule this event to happen + * seconds from now + */ + + }, { + key: "amp", + value: function amp(vol) { + var rampTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var tFromNow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var now = master.audiocontext.currentTime; + var currentVol = this.output.gain.value; + this.output.gain.cancelScheduledValues(now); + this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow); + this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime); + } + }, { + key: "dispose", + value: function dispose() { + var index = master.soundArray.indexOf(this); + master.soundArray.splice(index, 1); + + if (this.output) { + this.output.disconnect(); + delete this.output; + } + + if (this.input) { + this.input.disconnect(); + delete this.input; + } + } + }]); + + return Gain; +}(); + + var gain = (gain_Gain); +function audioVoice_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function audioVoice_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function audioVoice_createClass(Constructor, protoProps, staticProps) { if (protoProps) audioVoice_defineProperties(Constructor.prototype, protoProps); if (staticProps) audioVoice_defineProperties(Constructor, staticProps); return Constructor; } + + +/** + * Base class for monophonic synthesizers. Any extensions of this class + * should follow the API and implement the methods below in order to + * remain compatible with p5.PolySynth(); + * + * @class p5.AudioVoice + * @constructor + */ + +var audioVoice_AudioVoice = +function () { + function AudioVoice() { + audioVoice_classCallCheck(this, AudioVoice); + + this.ac = master.audiocontext; + this.output = this.ac.createGain(); + this.connect(); + master.soundArray.push(this); + } + + audioVoice_createClass(AudioVoice, [{ + key: "play", + value: function play(note, velocity, secondsFromNow, sustime) {} + }, { + key: "triggerAttack", + value: function triggerAttack(note, velocity, secondsFromNow) {} + }, { + key: "triggerRelease", + value: function triggerRelease(secondsFromNow) {} + }, { + key: "amp", + value: function amp(vol, rampTime) {} + /** + * Connect to p5 objects or Web Audio Nodes + * @method connect + * @for p5.AudioVoice + * @param {Object} unit + */ + + }, { + key: "connect", + value: function connect(unit) { + var u = unit || master.input; + this.output.connect(u.input ? u.input : u); + } + /** + * Disconnect from soundOut + * @method disconnect + * @for p5.AudioVoice + */ + + }, { + key: "disconnect", + value: function disconnect() { + this.output.disconnect(); + } + }, { + key: "dispose", + value: function dispose() { + if (this.output) { + this.output.disconnect(); + delete this.output; + } + } + }]); + + return AudioVoice; +}(); + + var audioVoice_0 = (audioVoice_AudioVoice); +function monosynth_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { monosynth_typeof = function _typeof(obj) { return typeof obj; }; } else { monosynth_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return monosynth_typeof(obj); } + +function monosynth_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function monosynth_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function monosynth_createClass(Constructor, protoProps, staticProps) { if (protoProps) monosynth_defineProperties(Constructor.prototype, protoProps); if (staticProps) monosynth_defineProperties(Constructor, staticProps); return Constructor; } + +function monosynth_possibleConstructorReturn(self, call) { if (call && (monosynth_typeof(call) === "object" || typeof call === "function")) { return call; } return monosynth_assertThisInitialized(self); } + +function monosynth_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function monosynth_get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { monosynth_get = Reflect.get; } else { monosynth_get = function _get(target, property, receiver) { var base = monosynth_superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return monosynth_get(target, property, receiver || target); } + +function monosynth_superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = monosynth_getPrototypeOf(object); if (object === null) break; } return object; } + +function monosynth_getPrototypeOf(o) { monosynth_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return monosynth_getPrototypeOf(o); } + +function monosynth_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) monosynth_setPrototypeOf(subClass, superClass); } + +function monosynth_setPrototypeOf(o, p) { monosynth_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return monosynth_setPrototypeOf(o, p); } + + + + + + +var DEFAULT_SUSTAIN = 0.15; +/** + * A MonoSynth is used as a single voice for sound synthesis. + * This is a class to be used in conjunction with the PolySynth + * class. Custom synthetisers should be built inheriting from + * this class. + * + * @class p5.MonoSynth + * @constructor + * @example + *
    + * let monoSynth; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playSynth); + * background(220); + * textAlign(CENTER); + * text('tap to play', width/2, height/2); + * + * monoSynth = new p5.MonoSynth(); + * } + * + * function playSynth() { + * userStartAudio(); + * + * let note = random(['Fb4', 'G4']); + * // note velocity (volume, from 0 to 1) + * let velocity = random(); + * // time from now (in seconds) + * let time = 0; + * // note duration (in seconds) + * let dur = 1/6; + * + * monoSynth.play(note, velocity, time, dur); + * } + *
    + **/ + +var monosynth_MonoSynth = +function (_AudioVoice) { + monosynth_inherits(MonoSynth, _AudioVoice); + + function MonoSynth() { + var _this; + + monosynth_classCallCheck(this, MonoSynth); + + _this = monosynth_possibleConstructorReturn(this, monosynth_getPrototypeOf(MonoSynth).call(this)); + _this.oscillator = new oscillator(); + _this.env = new envelope(); + + _this.env.setRange(1, 0); + + _this.env.setExp(true); + + + _this.setADSR(0.02, 0.25, 0.05, 0.35); + + + _this.oscillator.disconnect(); + + _this.oscillator.connect(_this.output); + + _this.env.disconnect(); + + _this.env.setInput(_this.output.gain); + + + _this.oscillator.output.gain.value = 1.0; + + _this.oscillator.start(); + + _this.connect(); + + master.soundArray.push(monosynth_assertThisInitialized(_this)); + /** + * Getters and Setters + * @property {Number} attack + * @for p5.MonoSynth + */ + + /** + * @property {Number} decay + * @for p5.MonoSynth + */ + + /** + * @property {Number} sustain + * @for p5.MonoSynth + */ + + /** + * @property {Number} release + * @for p5.MonoSynth + */ + + Object.defineProperties(monosynth_assertThisInitialized(_this), { + attack: { + get: function get() { + return this.env.aTime; + }, + set: function set(attack) { + this.env.setADSR(attack, this.env.dTime, this.env.sPercent, this.env.rTime); + } + }, + decay: { + get: function get() { + return this.env.dTime; + }, + set: function set(decay) { + this.env.setADSR(this.env.aTime, decay, this.env.sPercent, this.env.rTime); + } + }, + sustain: { + get: function get() { + return this.env.sPercent; + }, + set: function set(sustain) { + this.env.setADSR(this.env.aTime, this.env.dTime, sustain, this.env.rTime); + } + }, + release: { + get: function get() { + return this.env.rTime; + }, + set: function set(release) { + this.env.setADSR(this.env.aTime, this.env.dTime, this.env.sPercent, release); + } + } + }); + return _this; + } + /** + * Play tells the MonoSynth to start playing a note. This method schedules + * the calling of .triggerAttack and .triggerRelease. + * + * @method play + * @for p5.MonoSynth + * @param {String | Number} note the note you want to play, specified as a + * frequency in Hertz (Number) or as a midi + * value in Note/Octave format ("C4", "Eb3"...etc") + * See + * Tone. Defaults to 440 hz. + * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1) + * @param {Number} [secondsFromNow] time from now (in seconds) at which to play + * @param {Number} [sustainTime] time to sustain before releasing the envelope. Defaults to 0.15 seconds. + * @example + *
    + * let monoSynth; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playSynth); + * background(220); + * textAlign(CENTER); + * text('tap to play', width/2, height/2); + * + * monoSynth = new p5.MonoSynth(); + * } + * + * function playSynth() { + * userStartAudio(); + * + * let note = random(['Fb4', 'G4']); + * // note velocity (volume, from 0 to 1) + * let velocity = random(); + * // time from now (in seconds) + * let time = 0; + * // note duration (in seconds) + * let dur = 1/6; + * + * monoSynth.play(note, velocity, time, dur); + * } + *
    + * + */ + + + monosynth_createClass(MonoSynth, [{ + key: "play", + value: function play(note, velocity, secondsFromNow, susTime) { + this.triggerAttack(note, velocity, ~~secondsFromNow); + this.triggerRelease(~~secondsFromNow + (susTime || DEFAULT_SUSTAIN)); + } + /** + * Trigger the Attack, and Decay portion of the Envelope. + * Similar to holding down a key on a piano, but it will + * hold the sustain level until you let go. + * + * @param {String | Number} note the note you want to play, specified as a + * frequency in Hertz (Number) or as a midi + * value in Note/Octave format ("C4", "Eb3"...etc") + * See + * Tone. Defaults to 440 hz + * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1) + * @param {Number} [secondsFromNow] time from now (in seconds) at which to play + * @method triggerAttack + * @for p5.MonoSynth + * @example + *
    + * let monoSynth; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(triggerAttack); + * background(220); + * text('tap here for attack, let go to release', 5, 20, width - 20); + * monoSynth = new p5.MonoSynth(); + * } + * + * function triggerAttack() { + * userStartAudio(); + * + * monoSynth.triggerAttack("E3"); + * } + * + * function mouseReleased() { + * monoSynth.triggerRelease(); + * } + *
    + */ + + }, { + key: "triggerAttack", + value: function triggerAttack(note, velocity) { + var secondsFromNow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var freq = noteToFreq(note); + var vel = velocity || 0.1; + this.oscillator.freq(freq, 0, secondsFromNow); + this.env.ramp(this.output.gain, secondsFromNow, vel); + } + /** + * Trigger the release of the Envelope. This is similar to releasing + * the key on a piano and letting the sound fade according to the + * release level and release time. + * + * @param {Number} secondsFromNow time to trigger the release + * @method triggerRelease + * @for p5.MonoSynth + * @example + *
    + * let monoSynth; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(triggerAttack); + * background(220); + * text('tap here for attack, let go to release', 5, 20, width - 20); + * monoSynth = new p5.MonoSynth(); + * } + * + * function triggerAttack() { + * userStartAudio(); + * + * monoSynth.triggerAttack("E3"); + * } + * + * function mouseReleased() { + * monoSynth.triggerRelease(); + * } + *
    + */ + + }, { + key: "triggerRelease", + value: function triggerRelease() { + var secondsFromNow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + this.env.ramp(this.output.gain, secondsFromNow, 0); + } + /** + * Set values like a traditional + * + * ADSR envelope + * . + * + * @method setADSR + * @for p5.MonoSynth + * @param {Number} attackTime Time (in seconds before envelope + * reaches Attack Level + * @param {Number} [decayTime] Time (in seconds) before envelope + * reaches Decay/Sustain Level + * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, + * where 1.0 = attackLevel, 0.0 = releaseLevel. + * The susRatio determines the decayLevel and the level at which the + * sustain portion of the envelope will sustain. + * For example, if attackLevel is 0.4, releaseLevel is 0, + * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is + * increased to 1.0 (using setRange), + * then decayLevel would increase proportionally, to become 0.5. + * @param {Number} [releaseTime] Time in seconds from now (defaults to 0) + */ + + }, { + key: "setADSR", + value: function setADSR(attack, decay, sustain, release) { + this.env.setADSR(attack, decay, sustain, release); + } + /** + * MonoSynth amp + * @method amp + * @for p5.MonoSynth + * @param {Number} vol desired volume + * @param {Number} [rampTime] Time to reach new volume + * @return {Number} new volume value + */ + + }, { + key: "amp", + value: function amp(vol, rampTime) { + var t = rampTime || 0; + + if (typeof vol !== 'undefined') { + this.oscillator.amp(vol, t); + } + + return this.oscillator.amp().value; + } + /** + * Connect to a p5.sound / Web Audio object. + * + * @method connect + * @for p5.MonoSynth + * @param {Object} unit A p5.sound or Web Audio object + */ + + }, { + key: "connect", + value: function connect(unit) { + var u = unit || master.input; + this.output.connect(u.input ? u.input : u); + } + /** + * Disconnect all outputs + * + * @method disconnect + * @for p5.MonoSynth + */ + + }, { + key: "disconnect", + value: function disconnect() { + if (this.output) { + this.output.disconnect(); + } + } + /** + * Get rid of the MonoSynth and free up its resources / memory. + * + * @method dispose + * @for p5.MonoSynth + */ + + }, { + key: "dispose", + value: function dispose() { + monosynth_get(monosynth_getPrototypeOf(MonoSynth.prototype), "dispose", this).call(this); + + if (this.env) { + this.env.dispose(); + } + + if (this.oscillator) { + this.oscillator.dispose(); + } + } + }]); + + return MonoSynth; +}(audioVoice_0); + + var monosynth = (monosynth_MonoSynth); +function onsetDetect_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function onsetDetect_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function onsetDetect_createClass(Constructor, protoProps, staticProps) { if (protoProps) onsetDetect_defineProperties(Constructor.prototype, protoProps); if (staticProps) onsetDetect_defineProperties(Constructor, staticProps); return Constructor; } + +/** + * Listen for onsets (a sharp increase in volume) within a given + * frequency range. + * + * @class p5.OnsetDetect + * @constructor + * @param {Number} freqLow Low frequency + * @param {Number} freqHigh High frequency + * @param {Number} threshold Amplitude threshold between 0 (no energy) and 1 (maximum) + * @param {Function} callback Function to call when an onset is detected + */ +var OnsetDetect = +function () { + function OnsetDetect(freqLow, freqHigh, threshold, callback) { + onsetDetect_classCallCheck(this, OnsetDetect); + + this.isDetected = false; + this.freqLow = freqLow; + this.freqHigh = freqHigh; + this.treshold = threshold; + this.energy = 0; + this.penergy = 0; + + this.sensitivity = 500; + this.callback = callback; + } + + + onsetDetect_createClass(OnsetDetect, [{ + key: "update", + value: function update(fftObject, callback) { + this.energy = fftObject.getEnergy(this.freqLow, this.freqHigh) / 255; + + if (this.isDetected === false) { + if (this.energy - this.penergy > this.treshold) { + this.isDetected = true; + + if (this.callback) { + this.callback(this.energy); + } else if (callback) { + callback(this.energy); + } + + var self = this; + setTimeout(function () { + self.isDetected = false; + }, this.sensitivity); + } + } + + this.penergy = this.energy; + } + }]); + + return OnsetDetect; +}(); + + var onsetDetect = (OnsetDetect); +function polysynth_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function polysynth_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function polysynth_createClass(Constructor, protoProps, staticProps) { if (protoProps) polysynth_defineProperties(Constructor.prototype, protoProps); if (staticProps) polysynth_defineProperties(Constructor, staticProps); return Constructor; } + + + + +/** + * An AudioVoice is used as a single voice for sound synthesis. + * The PolySynth class holds an array of AudioVoice, and deals + * with voices allocations, with setting notes to be played, and + * parameters to be set. + * + * @class p5.PolySynth + * @constructor + * + * @param {Number} [synthVoice] A monophonic synth voice inheriting + * the AudioVoice class. Defaults to p5.MonoSynth + * @param {Number} [maxVoices] Number of voices, defaults to 8; + * @example + *
    + * let polySynth; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playSynth); + * background(220); + * text('click to play', 20, 20); + * + * polySynth = new p5.PolySynth(); + * } + * + * function playSynth() { + * userStartAudio(); + * + * // note duration (in seconds) + * let dur = 1.5; + * + * // time from now (in seconds) + * let time = 0; + * + * // velocity (volume, from 0 to 1) + * let vel = 0.1; + * + * // notes can overlap with each other + * polySynth.play('G2', vel, 0, dur); + * polySynth.play('C3', vel, time += 1/3, dur); + * polySynth.play('G3', vel, time += 1/3, dur); + * } + *
    + **/ + +var polysynth_PolySynth = +function () { + function PolySynth(audioVoice, maxVoices) { + polysynth_classCallCheck(this, PolySynth); + + this.audiovoices = []; + /** + * An object that holds information about which notes have been played and + * which notes are currently being played. New notes are added as keys + * on the fly. While a note has been attacked, but not released, the value of the + * key is the audiovoice which is generating that note. When notes are released, + * the value of the key becomes undefined. + * @property notes + */ + + this.notes = {}; + + this._newest = 0; + this._oldest = 0; + /** + * A PolySynth must have at least 1 voice, defaults to 8 + * @property polyvalue + */ + + this.maxVoices = maxVoices || 8; + /** + * Monosynth that generates the sound for each note that is triggered. The + * p5.PolySynth defaults to using the p5.MonoSynth as its voice. + * @property AudioVoice + */ + + this.AudioVoice = audioVoice === undefined ? p5.MonoSynth : audioVoice; + /** + * This value must only change as a note is attacked or released. Due to delay + * and sustain times, Tone.TimelineSignal is required to schedule the change in value. + * @private + * @property {Tone.TimelineSignal} _voicesInUse + */ + + this._voicesInUse = new TimelineSignal_default.a(0); + this.output = master.audiocontext.createGain(); + this.connect(); + + this._allocateVoices(); + + master.soundArray.push(this); + } + /** + * Construct the appropriate number of audiovoices + * @private + * @for p5.PolySynth + * @method _allocateVoices + */ + + + polysynth_createClass(PolySynth, [{ + key: "_allocateVoices", + value: function _allocateVoices() { + for (var i = 0; i < this.maxVoices; i++) { + this.audiovoices.push(new this.AudioVoice()); + this.audiovoices[i].disconnect(); + this.audiovoices[i].connect(this.output); + } + } + /** + * Play a note by triggering noteAttack and noteRelease with sustain time + * + * @method play + * @for p5.PolySynth + * @param {Number} [note] midi note to play (ranging from 0 to 127 - 60 being a middle C) + * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1) + * @param {Number} [secondsFromNow] time from now (in seconds) at which to play + * @param {Number} [sustainTime] time to sustain before releasing the envelope + * @example + *
    + * let polySynth; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playSynth); + * background(220); + * text('click to play', 20, 20); + * + * polySynth = new p5.PolySynth(); + * } + * + * function playSynth() { + * userStartAudio(); + * + * // note duration (in seconds) + * let dur = 1.5; + * + * // time from now (in seconds) + * let time = 0; + * + * // velocity (volume, from 0 to 1) + * let vel = 0.1; + * + * // notes can overlap with each other + * polySynth.play('G2', vel, 0, dur); + * polySynth.play('C3', vel, time += 1/3, dur); + * polySynth.play('G3', vel, time += 1/3, dur); + * } + *
    + */ + + }, { + key: "play", + value: function play(note, velocity, secondsFromNow) { + var susTime = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + this.noteAttack(note, velocity, secondsFromNow); + this.noteRelease(note, secondsFromNow + susTime); + } + /** + * noteADSR sets the envelope for a specific note that has just been triggered. + * Using this method modifies the envelope of whichever audiovoice is being used + * to play the desired note. The envelope should be reset before noteRelease is called + * in order to prevent the modified envelope from being used on other notes. + * + * @method noteADSR + * @for p5.PolySynth + * @param {Number} [note] Midi note on which ADSR should be set. + * @param {Number} [attackTime] Time (in seconds before envelope + * reaches Attack Level + * @param {Number} [decayTime] Time (in seconds) before envelope + * reaches Decay/Sustain Level + * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, + * where 1.0 = attackLevel, 0.0 = releaseLevel. + * The susRatio determines the decayLevel and the level at which the + * sustain portion of the envelope will sustain. + * For example, if attackLevel is 0.4, releaseLevel is 0, + * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is + * increased to 1.0 (using setRange), + * then decayLevel would increase proportionally, to become 0.5. + * @param {Number} [releaseTime] Time in seconds from now (defaults to 0) + **/ + + }, { + key: "noteADSR", + value: function noteADSR(note, a, d, s, r) { + var timeFromNow = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var now = master.audiocontext.currentTime; + var t = now + timeFromNow; + this.audiovoices[this.notes[note].getValueAtTime(t)].setADSR(a, d, s, r); + } + /** + * Set the PolySynths global envelope. This method modifies the envelopes of each + * monosynth so that all notes are played with this envelope. + * + * @method setADSR + * @for p5.PolySynth + * @param {Number} [attackTime] Time (in seconds before envelope + * reaches Attack Level + * @param {Number} [decayTime] Time (in seconds) before envelope + * reaches Decay/Sustain Level + * @param {Number} [susRatio] Ratio between attackLevel and releaseLevel, on a scale from 0 to 1, + * where 1.0 = attackLevel, 0.0 = releaseLevel. + * The susRatio determines the decayLevel and the level at which the + * sustain portion of the envelope will sustain. + * For example, if attackLevel is 0.4, releaseLevel is 0, + * and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is + * increased to 1.0 (using setRange), + * then decayLevel would increase proportionally, to become 0.5. + * @param {Number} [releaseTime] Time in seconds from now (defaults to 0) + **/ + + }, { + key: "setADSR", + value: function setADSR(a, d, s, r) { + this.audiovoices.forEach(function (voice) { + voice.setADSR(a, d, s, r); + }); + } + /** + * Trigger the Attack, and Decay portion of a MonoSynth. + * Similar to holding down a key on a piano, but it will + * hold the sustain level until you let go. + * + * @method noteAttack + * @for p5.PolySynth + * @param {Number} [note] midi note on which attack should be triggered. + * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1)/ + * @param {Number} [secondsFromNow] time from now (in seconds) + * @example + *
    + * let polySynth = new p5.PolySynth(); + * let pitches = ['G', 'D', 'G', 'C']; + * let octaves = [2, 3, 4]; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playChord); + * background(220); + * text('tap to play', 20, 20); + * } + * + * function playChord() { + * userStartAudio(); + * + * // play a chord: multiple notes at the same time + * for (let i = 0; i < 4; i++) { + * let note = random(pitches) + random(octaves); + * polySynth.noteAttack(note, 0.1); + * } + * } + * + * function mouseReleased() { + * // release all voices + * polySynth.noteRelease(); + * } + *
    + */ + + }, { + key: "noteAttack", + value: function noteAttack(_note, _velocity) { + var secondsFromNow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var acTime = master.audiocontext.currentTime + secondsFromNow; + + var note = noteToFreq(_note); + var velocity = _velocity || 0.1; + var currentVoice; + + if (this.notes[note] && this.notes[note].getValueAtTime(acTime) !== null) { + this.noteRelease(note, 0); + } + + + if (this._voicesInUse.getValueAtTime(acTime) < this.maxVoices) { + currentVoice = Math.max(~~this._voicesInUse.getValueAtTime(acTime), 0); + } + else { + currentVoice = this._oldest; + oldestNote = freqToMidi(this.audiovoices[this._oldest].oscillator.freq().value); + this.noteRelease(oldestNote); + this._oldest = (this._oldest + 1) % (this.maxVoices - 1); + } + + + this.notes[note] = new TimelineSignal_default.a(); + this.notes[note].setValueAtTime(currentVoice, acTime); + + var previousVal = this._voicesInUse._searchBefore(acTime) === null ? 0 : this._voicesInUse._searchBefore(acTime).value; + + this._voicesInUse.setValueAtTime(previousVal + 1, acTime); + + + this._updateAfter(acTime, 1); + + this._newest = currentVoice; + + if (typeof velocity === 'number') { + var maxRange = 1 / this._voicesInUse.getValueAtTime(acTime) * 2; + velocity = velocity > maxRange ? maxRange : velocity; + } + + + this.audiovoices[currentVoice].triggerAttack(note, velocity, secondsFromNow); + } + /** + * Private method to ensure accurate values of this._voicesInUse + * Any time a new value is scheduled, it is necessary to increment all subsequent + * scheduledValues after attack, and decrement all subsequent + * scheduledValues after release + * + * @private + * @for p5.PolySynth + * @param {[type]} time [description] + * @param {[type]} value [description] + * @return {[type]} [description] + */ + + }, { + key: "_updateAfter", + value: function _updateAfter(time, value) { + if (this._voicesInUse._searchAfter(time) === null) { + return; + } else { + this._voicesInUse._searchAfter(time).value += value; + + var nextTime = this._voicesInUse._searchAfter(time).time; + + this._updateAfter(nextTime, value); + } + } + /** + * Trigger the Release of an AudioVoice note. This is similar to releasing + * the key on a piano and letting the sound fade according to the + * release level and release time. + * + * @method noteRelease + * @for p5.PolySynth + * @param {Number} [note] midi note on which attack should be triggered. + * If no value is provided, all notes will be released. + * @param {Number} [secondsFromNow] time to trigger the release + * @example + *
    + * let polySynth = new p5.PolySynth(); + * let pitches = ['G', 'D', 'G', 'C']; + * let octaves = [2, 3, 4]; + * + * function setup() { + * let cnv = createCanvas(100, 100); + * cnv.mousePressed(playChord); + * background(220); + * text('tap to play', 20, 20); + * } + * + * function playChord() { + * userStartAudio(); + * + * // play a chord: multiple notes at the same time + * for (let i = 0; i < 4; i++) { + * let note = random(pitches) + random(octaves); + * polySynth.noteAttack(note, 0.1); + * } + * } + * + * function mouseReleased() { + * // release all voices + * polySynth.noteRelease(); + * } + *
    + * + */ + + }, { + key: "noteRelease", + value: function noteRelease(_note, secondsFromNow) { + var now = master.audiocontext.currentTime; + var tFromNow = secondsFromNow || 0; + var t = now + tFromNow; + + if (!_note) { + this.audiovoices.forEach(function (voice) { + voice.triggerRelease(tFromNow); + }); + + this._voicesInUse.setValueAtTime(0, t); + + for (var n in this.notes) { + this.notes[n].dispose(); + delete this.notes[n]; + } + + return; + } + + + var note = noteToFreq(_note); + + if (!this.notes[note] || this.notes[note].getValueAtTime(t) === null) { + console.warn('Cannot release a note that is not already playing'); + } else { + var previousVal = Math.max(~~this._voicesInUse.getValueAtTime(t).value, 1); + + this._voicesInUse.setValueAtTime(previousVal - 1, t); + + + if (previousVal > 0) { + this._updateAfter(t, -1); + } + + this.audiovoices[this.notes[note].getValueAtTime(t)].triggerRelease(tFromNow); + this.notes[note].dispose(); + delete this.notes[note]; + this._newest = this._newest === 0 ? 0 : (this._newest - 1) % (this.maxVoices - 1); + } + } + /** + * Connect to a p5.sound / Web Audio object. + * + * @method connect + * @for p5.PolySynth + * @param {Object} unit A p5.sound or Web Audio object + */ + + }, { + key: "connect", + value: function connect(unit) { + var u = unit || master.input; + this.output.connect(u.input ? u.input : u); + } + /** + * Disconnect all outputs + * + * @method disconnect + * @for p5.PolySynth + */ + + }, { + key: "disconnect", + value: function disconnect() { + if (this.output) { + this.output.disconnect(); + } + } + /** + * Get rid of the MonoSynth and free up its resources / memory. + * + * @method dispose + * @for p5.PolySynth + */ + + }, { + key: "dispose", + value: function dispose() { + this.audiovoices.forEach(function (voice) { + voice.dispose(); + }); + + if (this.output) { + this.output.disconnect(); + delete this.output; + } + } + }]); + + return PolySynth; +}(); + + var polysynth = (polysynth_PolySynth); +function Signal_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Signal_Signal = function Signal() { + Signal_classCallCheck(this, Signal); + + console.warn('p5.Signal is deprecated , Use Tone.js Signal instead '); +}; + + var deprecations_Signal = (Signal_Signal); + + + +p5.prototype.getAudioContext = audiocontext["b" ]; +p5.prototype.userStartAudio = audiocontext["c" ]; + + +p5.prototype.sampleRate = sampleRate; +p5.prototype.freqToMidi = freqToMidi; +p5.prototype.midiToFreq = midiToFreq; +p5.prototype.noteToFreq = noteToFreq; +p5.prototype.soundFormats = soundFormats; +p5.prototype.disposeSound = disposeSound; +p5.prototype._checkFileFormats = _checkFileFormats; +p5.prototype._mathChain = _mathChain; +p5.prototype.convertToWav = convertToWav; +p5.prototype.interleave = interleave; +p5.prototype.writeUTFBytes = writeUTFBytes; +p5.prototype.safeBufferSize = safeBufferSize; +p5.prototype.saveSound = saveSound; + +p5.prototype.registerMethod('remove', p5.prototype.disposeSound); + + + +p5.Panner = panner_0; + +p5.SoundFile = soundfile; +p5.prototype.loadSound = loadSound; + +p5.prototype.registerPreloadMethod('loadSound', p5.prototype); + +p5.Amplitude = amplitude; + +p5.FFT = fft; + +p5.Oscillator = oscillator; +p5.SinOsc = SinOsc; +p5.TriOsc = TriOsc; +p5.SawOsc = SawOsc; +p5.SqrOsc = SqrOsc; + + +p5.Noise = noise; + +p5.Pulse = pulse; + +p5.AudioIn = audioin; + +p5.Effect = effect; + +p5.Filter = filter; +p5.LowPass = LowPass; +p5.HighPass = HighPass; +p5.BandPass = BandPass; + +p5.EQ = eq; + +p5.listener3D = listener3d; + +p5.Panner3D = panner3d; + +p5.Delay = delay; + +p5.Reverb = Reverb; +p5.Convolver = reverb_Convolver; +p5.prototype.createConvolver = createConvolver; +p5.prototype.registerPreloadMethod('createConvolver', p5.prototype); + +p5.Metro = metro; + +p5.Phrase = Phrase; +p5.Part = looper_Part; +p5.Score = Score; + +p5.SoundLoop = soundLoop; + +p5.Compressor = compressor; + +p5.peakDetect = peakDetect; + +p5.SoundRecorder = soundRecorder; + +p5.Distortion = distortion; + +p5.Gain = gain; + +p5.AudioVoice = audioVoice_0; + +p5.MonoSynth = monosynth; + +p5.OnsetDetect = onsetDetect; + +p5.PolySynth = polysynth; + + +p5.Signal = deprecations_Signal; + + }) + ]); diff --git a/sounds/PNF_01.mp3 b/sounds/PNF_01.mp3 new file mode 100644 index 0000000..783d6fb Binary files /dev/null and b/sounds/PNF_01.mp3 differ diff --git a/sounds/walking.mp3 b/sounds/walking.mp3 new file mode 100644 index 0000000..ebd07b9 Binary files /dev/null and b/sounds/walking.mp3 differ diff --git a/style-mb.css b/style-mb.css new file mode 100644 index 0000000..cc5c2b2 --- /dev/null +++ b/style-mb.css @@ -0,0 +1,12 @@ +#textcontainer{ + display: none; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: auto; + background-color: pink; + font-size: 72px; + text-align: center; + color: red; +} \ No newline at end of file diff --git a/style.css b/style.css new file mode 100644 index 0000000..4cbf44b --- /dev/null +++ b/style.css @@ -0,0 +1,369 @@ + + +img { opacity: 1; + z-index: 0; + display: block; + position: fixed; +} + +a span.unclickable { text-decoration: none; +} + a span.unclickable:hover { cursor: default; +} + +/*----------------- CANVAS FROM P5.JS--------------------*/ + +canvas{ + z-index: 20; +} + +#GIF { + visibility: visible; + position: absolute; + height: 50%; + top: 48%; + text-align: center; + left: 50%; + transform: translate(-50%,-50%); +} + +/*----------------- CONTAINING ALL CONTENTS--------------------*/ + + + +/*----------------- WHAT IS THIS? THE MODAL BOX MAYBE--------------------*/ + + +@keyframes disparition { + 0% {opacity:1; z-index: 15000;} + 10%, 90% { opacity: 0; z-index: -100;} + 100% {opacity : 0; z-index: -100;} +} + + + +/*----------------- HELP POP UP WINDOW--------------------*/ + +#openModal { + display:none; + font-family: 'ApfelGrotezk-Regular'; + color: #000; + z-index: 99999; +} + +.modalDialog { + position: absolute; + font-family: 'ApfelGrotezk-Regular'; + color: #FFFF; + top: 0; + right: 0; + bottom: 0; + left: 0; + background: rgba(0, 0, 0, 1); + z-index: 99999; + cursor: url(symboles/CURSEUR.png), pointer; +} + + +.modalDialog:target { + opacity: 1; + pointer-events: auto; + cursor: url(symboles/CURSEUR.png), pointer; + +} +.modalDialog > div { + font-family: 'ApfelGrotezk-Regular'; + + url('ApfelGrotezk-Regular.woff') format('woff'); + width: 100%; + color: white; + position: fixed; + margin: 1% auto; + padding: 1% 1% 1% 1%; + background: #000; + cursor: url(symboles/CURSEUR.png), pointer; +} + +/*----------------- CLOSE POP UP --------------------*/ + +*{ +/* Prevent any object from being highlighted upon touch event*/ + tap-highlight-color: transparent; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + -moz-tap-highlight-color: rgba(0, 0, 0, 0); + outline: none; +} + +@font-face { + font-family: "ApfelGrotezk-Regular"; + src: url("../ApfelGrotezk-Regular.ttf"); +} + + +.display-none { + display:none; +} +.display-flex { + display:flex; +} +.display-block{ + display:block; +} + +body{ + font-size: 1.5em; + background-color: black; + color: white; + font-family: "ApfelGrotezk-Regular"; +} + +.overlay{ + z-index: 2; + position: fixed; +} + +#code-input{ + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; + color: white; + font-family: "ApfelGrotezk-Regular"; + font-size: 0.8em; +} + +#code-input:hover{ + color: white; + cursor: pointer; + +} + +#input{ + visibility: hidden; + border: 0; + outline: 0; + background: transparent; + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; + color: white; + font-family: "ApfelGrotezk-Regular"; + font-size: 5vw; + +} + +#fname{ + border: 0; + outline: 0; + background: transparent; + left: 1em; + bottom: 1em; + border: none; + position: fixed; + background: transparent; + color: white; + font-family: "ApfelGrotezk-Regular"; + font-size: 5vw; + +} + +.close { + font-family: 'ApfelGrotezk-Regular'; + color: #FFF; + font-size: 200%; + position: fixed; + right: -0.7%; + bottom: 1.5%; + width:40px; + text-decoration: none; + cursor: url(symboles/CURSEUR.png), pointer; + +} +.close:hover { + color: #FFF; + cursor: url(symboles/CURSEUR.png), pointer; +} + +/*----------------- FONTS --------------------*/ + +@font-face { + font-family: 'ApfelGrotezk-Regular'; + + + font-weight: normal; + font-style: normal; +} + +/*----------------- CURSOR --------------------*/ + +html { +cursor: url(symboles/NOcursor.png), pointer; min-height: 100%; + background: black; +} + + +/*----------------- AUDIO --------------------*/ + + +#audio { + display: none; +} + + +#BOX4 img{ + width:60px; + height: 60px; + position:absolute; + bottom:0; + left: 0; + cursor: url(symboles/CURSEUR.png), pointer; +} + +#BOX4{ + opacity:0; + transition: opacity .1s ease-out; + -moz-transition: opacity .1s ease-out; + -webkit-transition: opacity .1s ease-out; + -o-transition: opacity .1s ease-out; + animation: all 2s; + cursor: url(symboles/CURSEUR.png), pointer; +} + +#BOX4:hover { + opacity:1; + transition: opacity .1s ease-out; + -moz-transition: opacity .1s ease-out; + -webkit-transition: opacity .1s ease-out; + -o-transition: opacity .1s ease-out; + animation: all 2s; + cursor: url(symboles/CURSEUR.png), pointer; +} + +/*-----------------HELP/ABOUT BUTTON---------------------------------*/ + + #BOX3 img{ + display: block; + width:40px; + height: 50px; + position: absolute; + bottom:0; + right: 0; + cursor: url(symboles/CURSEUR.png), pointer; + z-index: 9999; +} + +#BOX3{ + opacity:0.5; + transition: opacity .1s ease-out; + -moz-transition: opacity .1s ease-out; + -webkit-transition: opacity .1s ease-out; + -o-transition: opacity .1s ease-out; + animation: all 2s; + cursor: url(symboles/CURSEUR.png), pointer; + +} + +#BOX3:hover { + opacity:1; + transition: opacity .1s ease-out; + -moz-transition: opacity .1s ease-out; + -webkit-transition: opacity .1s ease-out; + -o-transition: opacity .1s ease-out; + animation: all 2s; + cursor: url(symboles/CURSEUR.png), pointer; +} + +@media screen and (max-width: 768px) { + +#textcontainer{ + display: none; + position: absolute; + top: 0; + left: 0; + right:0; + width: auto; + height: auto; + font-size: 4.5vw; + text-align: center; + color: black; + margin-top: 70px; + padding: 5%; +} +#container2{ + font-family: 'ApfelGrotezk-Regular'; + width:100%; + z-index: 15000; + position: relative; + color: white; + display: block; + flex-direction: column; + justify-content: center; + align-items:center; + animation: disparition 1s ease-in forwards; + animation-delay: 10s; +} + + p2 { + text-align: center; + font-size: 3vw; + line-height: 110%; + padding-left:10%; + padding-right:10%; + +} } + +@media screen and (min-width: 768px) { + #textcontainer{ + width: calc(100% - 4em); + display: none; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: auto; + font-size: 3vw; + text-align: center; + color: black; + margin-top: 70px; +} +#container2{ + font-family: 'ApfelGrotezk-Regular'; + width:100%; + z-index: 15000; + position: relative; + color: white; + display: block; + flex-direction: column; + justify-content: center; + align-items:center; + animation: disparition 1s ease-in forwards; + animation-delay: 10s; +} + + p2 { + text-align: center; + font-size: 3vw; + line-height: 110%; + padding-left:10%; + padding-right:10%; + +} } + + + + + + + + + + + + + + + + diff --git a/symboles/CURSEUR.png b/symboles/CURSEUR.png new file mode 100644 index 0000000..cc81cae Binary files /dev/null and b/symboles/CURSEUR.png differ diff --git a/symboles/HELP.png b/symboles/HELP.png new file mode 100644 index 0000000..2b93090 Binary files /dev/null and b/symboles/HELP.png differ diff --git a/symboles/NOcursor.png b/symboles/NOcursor.png new file mode 100644 index 0000000..dd12d24 Binary files /dev/null and b/symboles/NOcursor.png differ diff --git a/symboles/index.html b/symboles/index.html new file mode 100644 index 0000000..42d57bc --- /dev/null +++ b/symboles/index.html @@ -0,0 +1,58 @@ + + + + + + + + + + +
    CURSEUR.png
    +
    HELP.png
    +
    PRINT.png
    +
    REFRESH.png
    +../ + + + diff --git a/test.md b/test.md deleted file mode 100644 index e69de29..0000000 diff --git a/test.txt b/test.txt deleted file mode 100644 index e69de29..0000000 diff --git a/typefaces/TINY5x3-100.ttf b/typefaces/TINY5x3-100.ttf new file mode 100644 index 0000000..c071247 Binary files /dev/null and b/typefaces/TINY5x3-100.ttf differ diff --git a/typefaces/TINY5x3-100.woff b/typefaces/TINY5x3-100.woff new file mode 100644 index 0000000..362498e Binary files /dev/null and b/typefaces/TINY5x3-100.woff differ diff --git a/typefaces/TINY5x3-100.woff2 b/typefaces/TINY5x3-100.woff2 new file mode 100644 index 0000000..a0154ca Binary files /dev/null and b/typefaces/TINY5x3-100.woff2 differ diff --git a/typefaces/TINY5x3-120.ttf b/typefaces/TINY5x3-120.ttf new file mode 100644 index 0000000..f79f937 Binary files /dev/null and b/typefaces/TINY5x3-120.ttf differ diff --git a/typefaces/TINY5x3-120.woff b/typefaces/TINY5x3-120.woff new file mode 100644 index 0000000..08a991e Binary files /dev/null and b/typefaces/TINY5x3-120.woff differ diff --git a/typefaces/TINY5x3-120.woff2 b/typefaces/TINY5x3-120.woff2 new file mode 100644 index 0000000..3a88e6c Binary files /dev/null and b/typefaces/TINY5x3-120.woff2 differ diff --git a/typefaces/TINY5x3-140.ttf b/typefaces/TINY5x3-140.ttf new file mode 100644 index 0000000..8827f75 Binary files /dev/null and b/typefaces/TINY5x3-140.ttf differ diff --git a/typefaces/TINY5x3-140.woff b/typefaces/TINY5x3-140.woff new file mode 100644 index 0000000..d6c29d4 Binary files /dev/null and b/typefaces/TINY5x3-140.woff differ diff --git a/typefaces/TINY5x3-140.woff2 b/typefaces/TINY5x3-140.woff2 new file mode 100644 index 0000000..896b1bf Binary files /dev/null and b/typefaces/TINY5x3-140.woff2 differ diff --git a/typefaces/TINY5x3-160.ttf b/typefaces/TINY5x3-160.ttf new file mode 100644 index 0000000..8fa216c Binary files /dev/null and b/typefaces/TINY5x3-160.ttf differ diff --git a/typefaces/TINY5x3-160.woff b/typefaces/TINY5x3-160.woff new file mode 100644 index 0000000..83e9cf1 Binary files /dev/null and b/typefaces/TINY5x3-160.woff differ diff --git a/typefaces/TINY5x3-160.woff2 b/typefaces/TINY5x3-160.woff2 new file mode 100644 index 0000000..4d18761 Binary files /dev/null and b/typefaces/TINY5x3-160.woff2 differ diff --git a/typefaces/TINY5x3-180.ttf b/typefaces/TINY5x3-180.ttf new file mode 100644 index 0000000..9373eff Binary files /dev/null and b/typefaces/TINY5x3-180.ttf differ diff --git a/typefaces/TINY5x3-180.woff b/typefaces/TINY5x3-180.woff new file mode 100644 index 0000000..5ecf7c4 Binary files /dev/null and b/typefaces/TINY5x3-180.woff differ diff --git a/typefaces/TINY5x3-180.woff2 b/typefaces/TINY5x3-180.woff2 new file mode 100644 index 0000000..c98346e Binary files /dev/null and b/typefaces/TINY5x3-180.woff2 differ diff --git a/typefaces/TINY5x3-20.woff b/typefaces/TINY5x3-20.woff new file mode 100644 index 0000000..861a1be Binary files /dev/null and b/typefaces/TINY5x3-20.woff differ diff --git a/typefaces/TINY5x3-20.woff2 b/typefaces/TINY5x3-20.woff2 new file mode 100644 index 0000000..0c597c0 Binary files /dev/null and b/typefaces/TINY5x3-20.woff2 differ diff --git a/typefaces/TINY5x3-200.ttf b/typefaces/TINY5x3-200.ttf new file mode 100644 index 0000000..71e077e Binary files /dev/null and b/typefaces/TINY5x3-200.ttf differ diff --git a/typefaces/TINY5x3-200.woff b/typefaces/TINY5x3-200.woff new file mode 100644 index 0000000..705d4c5 Binary files /dev/null and b/typefaces/TINY5x3-200.woff differ diff --git a/typefaces/TINY5x3-200.woff2 b/typefaces/TINY5x3-200.woff2 new file mode 100644 index 0000000..ab20c16 Binary files /dev/null and b/typefaces/TINY5x3-200.woff2 differ diff --git a/typefaces/TINY5x3-220.ttf b/typefaces/TINY5x3-220.ttf new file mode 100644 index 0000000..7b88684 Binary files /dev/null and b/typefaces/TINY5x3-220.ttf differ diff --git a/typefaces/TINY5x3-220.woff b/typefaces/TINY5x3-220.woff new file mode 100644 index 0000000..1733b0c Binary files /dev/null and b/typefaces/TINY5x3-220.woff differ diff --git a/typefaces/TINY5x3-220.woff2 b/typefaces/TINY5x3-220.woff2 new file mode 100644 index 0000000..1b71010 Binary files /dev/null and b/typefaces/TINY5x3-220.woff2 differ diff --git a/typefaces/TINY5x3-240.ttf b/typefaces/TINY5x3-240.ttf new file mode 100644 index 0000000..b8ad3ac Binary files /dev/null and b/typefaces/TINY5x3-240.ttf differ diff --git a/typefaces/TINY5x3-240.woff b/typefaces/TINY5x3-240.woff new file mode 100644 index 0000000..15930c8 Binary files /dev/null and b/typefaces/TINY5x3-240.woff differ diff --git a/typefaces/TINY5x3-240.woff2 b/typefaces/TINY5x3-240.woff2 new file mode 100644 index 0000000..d006085 Binary files /dev/null and b/typefaces/TINY5x3-240.woff2 differ diff --git a/typefaces/TINY5x3-260.ttf b/typefaces/TINY5x3-260.ttf new file mode 100644 index 0000000..c58eca4 Binary files /dev/null and b/typefaces/TINY5x3-260.ttf differ diff --git a/typefaces/TINY5x3-260.woff b/typefaces/TINY5x3-260.woff new file mode 100644 index 0000000..156f466 Binary files /dev/null and b/typefaces/TINY5x3-260.woff differ diff --git a/typefaces/TINY5x3-260.woff2 b/typefaces/TINY5x3-260.woff2 new file mode 100644 index 0000000..bc30393 Binary files /dev/null and b/typefaces/TINY5x3-260.woff2 differ diff --git a/typefaces/TINY5x3-280.ttf b/typefaces/TINY5x3-280.ttf new file mode 100644 index 0000000..3ea1dd4 Binary files /dev/null and b/typefaces/TINY5x3-280.ttf differ diff --git a/typefaces/TINY5x3-280.woff b/typefaces/TINY5x3-280.woff new file mode 100644 index 0000000..05ae089 Binary files /dev/null and b/typefaces/TINY5x3-280.woff differ diff --git a/typefaces/TINY5x3-280.woff2 b/typefaces/TINY5x3-280.woff2 new file mode 100644 index 0000000..d637e8f Binary files /dev/null and b/typefaces/TINY5x3-280.woff2 differ diff --git a/typefaces/TINY5x3-300.ttf b/typefaces/TINY5x3-300.ttf new file mode 100644 index 0000000..adb8b7a Binary files /dev/null and b/typefaces/TINY5x3-300.ttf differ diff --git a/typefaces/TINY5x3-300.woff b/typefaces/TINY5x3-300.woff new file mode 100644 index 0000000..aca298e Binary files /dev/null and b/typefaces/TINY5x3-300.woff differ diff --git a/typefaces/TINY5x3-300.woff2 b/typefaces/TINY5x3-300.woff2 new file mode 100644 index 0000000..66e9857 Binary files /dev/null and b/typefaces/TINY5x3-300.woff2 differ diff --git a/typefaces/TINY5x3-40.ttf b/typefaces/TINY5x3-40.ttf new file mode 100644 index 0000000..3ebc42b Binary files /dev/null and b/typefaces/TINY5x3-40.ttf differ diff --git a/typefaces/TINY5x3-40.woff b/typefaces/TINY5x3-40.woff new file mode 100644 index 0000000..c20db42 Binary files /dev/null and b/typefaces/TINY5x3-40.woff differ diff --git a/typefaces/TINY5x3-40.woff2 b/typefaces/TINY5x3-40.woff2 new file mode 100644 index 0000000..24be68f Binary files /dev/null and b/typefaces/TINY5x3-40.woff2 differ diff --git a/typefaces/TINY5x3-60.ttf b/typefaces/TINY5x3-60.ttf new file mode 100644 index 0000000..def6ae5 Binary files /dev/null and b/typefaces/TINY5x3-60.ttf differ diff --git a/typefaces/TINY5x3-60.woff b/typefaces/TINY5x3-60.woff new file mode 100644 index 0000000..3060b2e Binary files /dev/null and b/typefaces/TINY5x3-60.woff differ diff --git a/typefaces/TINY5x3-60.woff2 b/typefaces/TINY5x3-60.woff2 new file mode 100644 index 0000000..20e6af3 Binary files /dev/null and b/typefaces/TINY5x3-60.woff2 differ diff --git a/typefaces/TINY5x3-80.ttf b/typefaces/TINY5x3-80.ttf new file mode 100644 index 0000000..6207482 Binary files /dev/null and b/typefaces/TINY5x3-80.ttf differ diff --git a/typefaces/TINY5x3-80.woff b/typefaces/TINY5x3-80.woff new file mode 100644 index 0000000..77fc2b5 Binary files /dev/null and b/typefaces/TINY5x3-80.woff differ diff --git a/typefaces/TINY5x3-80.woff2 b/typefaces/TINY5x3-80.woff2 new file mode 100644 index 0000000..313f638 Binary files /dev/null and b/typefaces/TINY5x3-80.woff2 differ