diff --git a/estudiantes/09-SofiaEct/clase-15/README.md b/estudiantes/09-SofiaEct/clase-15/README.md index 58e82138..d4cf4a62 100644 --- a/estudiantes/09-SofiaEct/clase-15/README.md +++ b/estudiantes/09-SofiaEct/clase-15/README.md @@ -1,29 +1,244 @@ # clase-15 -## planes examen +## planes exámen - personalmente quiero hacer algo personal jaja, sobre lo conversado en la clase, quiero hacer algo mucho mas significativo para mí, en formato juego en p5.js, creo que será un proceso MUY duro, pero pienso en este proyecto como algo que quedará para siempre en mí (si es que funciona, claro). - pincipalmente este trabajo está inspirado en [chino kim](https://chino.kim/) y en su trabajo [...and](http://chjno.github.io/...and/) - [oregon trail](https://es.wikipedia.org/wiki/Oregon_Trail_(videojuego)) no olvidar! -- quiero ver bien mis referentes antes de mepezar a hacer algo -- INCREIBLE, me pse a ver lo juegos hecho en p5.js en [p5play](https://p5play.org/lang/es/index.html) y de tdos los increibles trabajo el que mas se acercaba a lo que queria hacer fue ["into the mines"](https://tezumie.github.io/into-the-mines/?_gl=1*7im9tm*_ga*MjA0Nzk4MDQ2Ni4xNzE4NjQ5OTgw*_ga_EHXNCTSYLK*MTcxODY0OTk3OS4xLjEuMTcxODY1MDEzMy4wLjAuMA..) de @Tezumies +- quiero ver bien mis referentes antes de empezar a hacer algo. +- INCREIBLE, me pase a ver lo juegos hecho en p5.js en [p5play](https://p5play.org/lang/es/index.html) y de todos los increíbles trabajo el que más se acercaba a lo que quería hacer fue ["into the mines"](https://tezumie.github.io/into-the-mines/?_gl=1*7im9tm*_ga*MjA0Nzk4MDQ2Ni4xNzE4NjQ5OTgw*_ga_EHXNCTSYLK*MTcxODY0OTk3OS4xLjEuMTcxODY1MDEzMy4wLjAuMA..) de @Tezumies https://github.com/SofiaEct/dis9034-2024-1/assets/163043878/73048c95-e438-4c27-9b1a-ccbbd788b074 -- combinandolo con animacion hecha tambien en p5play, referenciando a [forrest live](https://quinton-ashley.github.io/Squirrel/Code/index.html) de @Axiom +- combinándolo con animación hecha también en p5play, referenciando a [forrest live](https://quinton-ashley.github.io/Squirrel/Code/index.html) de @Axiom https://github.com/SofiaEct/dis9034-2024-1/assets/163043878/2583edcc-482a-4fad-b948-b275159f24b4 -## examen +## exámen -(ya no son planes, esto lo hago si o si) +(ya no son planes, esto lo hago sí o sí) -como mencione en el punteo de los planes para este examen, quiero hacer algo mas personal, asi que hare una pequeña sinopsis del juego: "Sofìa una niña de 14 años recorre un largo camino para encontrarse con su gato 'simio' que es lo que mas quiere en este vidapara estar con su amigo felino` +como mencione en el punteo de los planes para este examen, quiero hacer algo más personal, así que haré una pequeña sinopsis del juego: "Sofía, una niña de 14 años, recorre un largo camino para encontrarse con su gato 'simio' que es lo que más quiere en esta vida para estar con su amigo felino". -primero estoy viendo lo que es el personaje pero debo de hacer cada paso dibujandolo por lo que lo dejare para despues (ya que los necesito pa poder usar el cofdigo), me basare en el diseño de personaje de @Tezumines para hacerlo, y demas cosas de su github [Tezumine Github](https://github.com/Tezumie/into-the-mines) +primero estoy viendo lo que es el personaje, pero debo de hacer cada paso dibujándolo por lo que lo dejaré para después (ya que los necesito para poder usar el código), me basaré en el diseño de personaje de @Tezumines para hacerlo, y demás cosas de su github [Tezumine Github](https://github.com/Tezumie/into-the-mines) ![playerSprite](https://github.com/SofiaEct/dis9034-2024-1/assets/163043878/8ffc2fd0-c2f1-4041-90c5-bcbffa4c85c2) -ya en p5.js estuve probando usar las capas con las imagenes que hice previamente e intentar animar mi sprite con la referencia de @p5play en su apartado de [aprender](https://p5play.org/lang/es/learn/) estan los codigos para animar nuestro personaje [p5play: Animation](https://p5play.org/lang/es/learn/animation.html?page=4) +ya en p5.js estuve probando usar las capas con las imágenes que hice previamente e intentar animar mi sprite con la referencia de @p5play en su apartado de [aprender](https://p5play.org/lang/es/learn/) están los códigos para animar nuestro personaje [p5play: Animation](https://p5play.org/lang/es/learn/animation.html?page=4) -https://editor.p5js.org/SofiaEct/sketches/sxnDCwZsC +al final solo tuve errores que estaban fuera de mi entendimiento, así que decidí buscar tutoriales que animaran directamente en p5.js y me encontré con el video [Beginner's Guide: Make things move with keyboard input in P5js](https://youtu.be/MA_aFQV9vss?feature=shared) del canal @Barney Codes, donde enseñaba a aplicar un código de movimiento para mi personaje. + +```js + +let player; + +let pressedKeys = {}; + +function setup() { + createCanvas(600, 600); + player = new Player(width/2, height/2); +} + +function draw() { + background(220); + player.update(); + player.draw(); +} + +function keyPressed() { + pressedKeys[key] = true; +} + +function keyReleased() { + delete pressedKeys[key]; +} + +class Player { + constructor(x, y) { + this.x = x; + this.y = y; + + this.speed = 4; + } + + update() { + let mvmt = createVector(0, 0); + + if(pressedKeys.a) { + mvmt.x -= 1; + } + if(pressedKeys.d) { + mvmt.x += 1; + } + if(pressedKeys.w) { + mvmt.y -= 1; + } + if(pressedKeys.s) { + mvmt.y += 1; + } + + mvmt.setMag(this.speed); + + this.x += mvmt.x; + this.y += mvmt.y; + } + + draw() { + fill(255, 0, 0); + circle(this.x, this.y, 30); + } +} + +``` + +continué descifrando como poder cambiar de escenarios con el paso del personaje, esto fue bastante difícil, pero gracias a la ayuda se pudo lograr, más que nada es usando la condicional if y else if. +```js + if (player.x > 1.0 * width && fotitoActual == 0) { + // y aqui se indica el fondo + fotitoActual = 1; + player.x = 0; + } + // pasar de 1 a 2. + else if (player.x > 1.0 * width && fotitoActual == 1) { + // y aqui se indica el fondo. + fotitoActual = 2; + player.x = 0; + } + // pasar de 1 a 0. + else if (player.x < 0.0 * width && fotitoActual == 1) { + // y aqui se indica el fondo. + fotitoActual = 0; + player.x = width; + } + // pasar de 2 a 1. + else if (player.x < 0.0 * width && fotitoActual == 2) { + // y aqui se indica el fondo. + fotitoActual = 1; + player.x = width; + } +} +``` +y bueno, más allá del código, los fondos fueron hechos a mano por mí en estilo pixel, contemplando que quería hacer algo más interactivo, pero por tiempo y técnica no pude concretar TT. + +![fondo_3](https://github.com/SofiaEct/dis9034-2024-1/assets/163043878/1984b1dd-43f1-48f0-b89a-dfee95ebcd01) + +![fondo_2](https://github.com/SofiaEct/dis9034-2024-1/assets/163043878/cc58f98b-fcc9-4967-a68d-2e29e873ae3a) + +![fondo_1](https://github.com/SofiaEct/dis9034-2024-1/assets/163043878/2b5834ff-3285-455e-9297-ecc6ab76815d) + +y finlmente el resultado final. + +https://github.com/SofiaEct/dis9034-2024-1/assets/163043878/4a6c25d9-64c4-4af3-9a27-f7a0a0a157f2 + + y ya por último dejar documentado el código. + ```js +// inspirado en el trabajo de @Tezumine en p5play y siguiendo los pasos de @Barney Codes en youtube + +let player; +// aplicar []; es un arreglo que permite poner/subir más archivos dentro del mismo let. +let fotitos = []; +// variable para usar las teclas +let pressedKeys = {}; +// parte del arreglo []; que permite hacer el cambio de escenarios. +let fotitoActual = 0; + +function preload() { + // fotito.push es donde ya está aplicado el arreglo de la variable. + fotitos.push(loadImage("fondo_3.jpg")); + fotitos.push(loadImage("fondo_2.jpg")); + fotitos.push(loadImage("fondo_1.png")); +} + +function setup() { + createCanvas(1434, 860); + // definir el jugador y disponerlo en el lienzo (ubicación). + player = new Player(width / 12, height / 2); +} + +function draw() { + // aquí van los fondos. + background(0); + image(fotitos[fotitoActual], 0, 0); + + player.update(); + player.draw(); + // condicional if para poder cambiar los escenarios cuando el personaje pase los límites del lienzo en forma horizontal. + // pasar de 0 a 1. + // https://p5js.org/es/reference/#/p5/if + if (player.x > 1.0 * width && fotitoActual == 0) { + // y aqui se indica el fondo + fotitoActual = 1; + player.x = 0; + } + // pasar de 1 a 2. + else if (player.x > 1.0 * width && fotitoActual == 1) { + // y aqui se indica el fondo. + fotitoActual = 2; + player.x = 0; + } + // pasar de 1 a 0. + else if (player.x < 0.0 * width && fotitoActual == 1) { + // y aqui se indica el fondo. + fotitoActual = 0; + player.x = width; + } + // pasar de 2 a 1. + else if (player.x < 0.0 * width && fotitoActual == 2) { + // y aqui se indica el fondo. + fotitoActual = 1; + player.x = width; + } +} + +function keyPressed() { + // definiendo si se presiona una tecla esta hará una acción. + pressedKeys[key] = true; +} + +function keyReleased() { + // y esto detiene la acción de la tecla, así que la hace momentánea. + delete pressedKeys[key]; +} + +class Player { + constructor(x, y) { + this.x = x; + this.y = y; + + this.speed = 8; + } + + update() { + // movimiento del personaje. + let mvmt = createVector(0, 0); + //condicional if, si se presiona 'a' el movimiento será en la línea x (horizontal). https://p5js.org/es/reference/#/p5/if + if (pressedKeys.a) { + mvmt.x -= 1; + } + if (pressedKeys.d) { + mvmt.x += 1; + } + if (pressedKeys.w) { + mvmt.y -= 1; + } + if (pressedKeys.s) { + mvmt.y += 1; + } + + mvmt.setMag(this.speed); + + this.x += mvmt.x; + this.y += mvmt.y; + } + + draw() { + // acá definí al personaje que es el cuadrado de color rosa. + fill(234, 134, 157); + square(this.x, this.y, 60); + noStroke(); + } +} +``` +https://editor.p5js.org/SofiaEct/sketches/r1vAbchV9 + +seré sincera, de todos los proyectos que he hecho es el que menos me ha gustado, creo que desde el principio había tenido demasiadas expectativas, sin considerar el tiempo y la poca experiencia que he tenido con el código, pero me motiva a seguir aprendiendo y cuando pueda poder retomar este proyecto. diff --git a/estudiantes/09-SofiaEct/clase-15/fondo_1.png b/estudiantes/09-SofiaEct/clase-15/fondo_1.png new file mode 100644 index 00000000..e3e995c1 Binary files /dev/null and b/estudiantes/09-SofiaEct/clase-15/fondo_1.png differ diff --git a/estudiantes/09-SofiaEct/clase-15/fondo_2.jpg b/estudiantes/09-SofiaEct/clase-15/fondo_2.jpg new file mode 100644 index 00000000..08990d9c Binary files /dev/null and b/estudiantes/09-SofiaEct/clase-15/fondo_2.jpg differ diff --git a/estudiantes/09-SofiaEct/clase-15/fondo_3.jpg b/estudiantes/09-SofiaEct/clase-15/fondo_3.jpg new file mode 100644 index 00000000..f438a71e Binary files /dev/null and b/estudiantes/09-SofiaEct/clase-15/fondo_3.jpg differ diff --git a/estudiantes/09-SofiaEct/clase-15/index.html b/estudiantes/09-SofiaEct/clase-15/index.html new file mode 100644 index 00000000..1a7dea4c --- /dev/null +++ b/estudiantes/09-SofiaEct/clase-15/index.html @@ -0,0 +1,15 @@ + + + + + + + + + + +
+
+ + + diff --git a/estudiantes/09-SofiaEct/clase-15/p5.js b/estudiantes/09-SofiaEct/clase-15/p5.js new file mode 100644 index 00000000..222ac5d4 --- /dev/null +++ b/estudiantes/09-SofiaEct/clase-15/p5.js @@ -0,0 +1,144657 @@ +/*! p5.js v1.9.4 May 21, 2024 */ +(function (f) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + module.exports = f() + } else if (typeof define === 'function' && define.amd) { + define([], f) + } else { + var g; + if (typeof window !== 'undefined') { + g = window + } else if (typeof global !== 'undefined') { + g = global + } else if (typeof self !== 'undefined') { + g = self + } else { + g = this + } + g.p5 = f() + } +}) (function () { + var define, + module, + exports; + return (function () { + function r(e, n, t) { + function o(i, f) { + if (!n[i]) { + if (!e[i]) { + var c = 'function' == typeof require && require; + if (!f && c) return c(i, !0); + if (u) return u(i, !0); + var a = new Error('Cannot find module \'' + i + '\''); + throw a.code = 'MODULE_NOT_FOUND', + a + } + var p = n[i] = { + exports: { + } + }; + e[i][0].call(p.exports, function (r) { + var n = e[i][1][r]; + return o(n || r) + }, p, p.exports, r, e, n, t) + } + return n[i].exports + } + for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++) o(t[i]); + return o + } + return r + }) () ({ + 1: [ + function (_dereq_, module, exports) { + module.exports = { + 'p5': { + 'describe': { + 'name': 'describe', + 'params': [ + { + 'name': 'text', + 'description': '

description of the canvas.

\n', + 'type': 'String' + }, + { + 'name': 'display', + 'description': '

either LABEL or FALLBACK.

\n', + 'type': 'Constant', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Environment' + }, + 'describeElement': { + 'name': 'describeElement', + 'params': [ + { + 'name': 'name', + 'description': '

name of the element.

\n', + 'type': 'String' + }, + { + 'name': 'text', + 'description': '

description of the element.

\n', + 'type': 'String' + }, + { + 'name': 'display', + 'description': '

either LABEL or FALLBACK.

\n', + 'type': 'Constant', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Environment' + }, + 'textOutput': { + 'name': 'textOutput', + 'params': [ + { + 'name': 'display', + 'description': '

either FALLBACK or LABEL.

\n', + 'type': 'Constant', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Environment' + }, + 'gridOutput': { + 'name': 'gridOutput', + 'params': [ + { + 'name': 'display', + 'description': '

either FALLBACK or LABEL.

\n', + 'type': 'Constant', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Environment' + }, + 'alpha': { + 'name': 'alpha', + 'params': [ + { + 'name': 'color', + 'description': '

p5.Color object, array of\n color components, or CSS color string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'blue': { + 'name': 'blue', + 'params': [ + { + 'name': 'color', + 'description': '

p5.Color object, array of\n color components, or CSS color string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'brightness': { + 'name': 'brightness', + 'params': [ + { + 'name': 'color', + 'description': '

p5.Color object, array of\n color components, or CSS color string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'color': { + 'name': 'color', + 'class': 'p5', + 'module': 'Color', + 'overloads': [ + { + 'params': [ + { + 'name': 'gray', + 'description': '

number specifying value between white and black.

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '

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

\n', + 'type': 'Number', + 'optional': true + } + ] + }, + { + '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': true + } + ] + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

a color string.

\n', + 'type': 'String' + } + ] + }, + { + 'params': [ + { + 'name': 'values', + 'description': '

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

\n', + 'type': 'Number[]' + } + ] + }, + { + 'params': [ + { + 'name': 'color', + 'description': '', + 'type': 'p5.Color' + } + ] + } + ] + }, + 'green': { + 'name': 'green', + 'params': [ + { + 'name': 'color', + 'description': '

p5.Color object, array of\n color components, or CSS color string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'hue': { + 'name': 'hue', + 'params': [ + { + 'name': 'color', + 'description': '

p5.Color object, array of\n color components, or CSS color string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'lerpColor': { + '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' + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'lightness': { + 'name': 'lightness', + 'params': [ + { + 'name': 'color', + 'description': '

p5.Color object, array of\n color components, or CSS color string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'red': { + 'name': 'red', + 'params': [ + { + 'name': 'color', + 'description': '

p5.Color object, array of\n color components, or CSS color string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'saturation': { + 'name': 'saturation', + 'params': [ + { + 'name': 'color', + 'description': '

p5.Color object, array of\n color components, or CSS color string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'beginClip': { + 'name': 'beginClip', + 'params': [ + { + 'name': 'options', + 'description': '

an object containing clip settings.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'endClip': { + 'name': 'endClip', + 'class': 'p5', + 'module': 'Color' + }, + 'clip': { + 'name': 'clip', + 'params': [ + { + 'name': 'callback', + 'description': '

a function that draws the mask shape.

\n', + 'type': 'Function' + }, + { + 'name': 'options', + 'description': '

an object containing clip settings.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'background': { + 'name': 'background', + 'class': 'p5', + 'module': 'Color', + 'overloads': [ + { + 'params': [ + { + 'name': 'color', + 'description': '

any value created by the color() function

\n', + 'type': 'p5.Color' + } + ], + 'chainable': 1 + }, + { + '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': '

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

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'gray', + 'description': '

specifies a value between white and black.

\n', + 'type': 'Number' + }, + { + 'name': 'a', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '

red value if color mode is RGB, or hue value if color mode is HSB.

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green value if color mode is RGB, or saturation value if color mode is HSB.

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue value if color mode is RGB, or brightness value if color mode is HSB.

\n', + 'type': 'Number' + }, + { + 'name': 'a', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'values', + 'description': '

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

\n', + 'type': 'Number[]' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'image', + 'description': '

image created with loadImage()\n 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': true + } + ], + 'chainable': 1 + } + ] + }, + 'clear': { + 'name': 'clear', + 'params': [ + { + 'name': 'r', + 'description': '

normalized red value.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'g', + 'description': '

normalized green value.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'b', + 'description': '

normalized blue value.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'a', + 'description': '

normalized alpha value.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'colorMode': { + 'name': 'colorMode', + 'class': 'p5', + 'module': 'Color', + 'overloads': [ + { + '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': true + } + ], + 'chainable': 1 + }, + { + '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/lightness\n depending on the current color mode.

\n', + 'type': 'Number' + }, + { + 'name': 'maxA', + 'description': '

range for the alpha.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'fill': { + 'name': 'fill', + 'class': 'p5', + 'module': 'Color', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red value if color mode is RGB or hue value if color mode is HSB.

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green value if color mode is RGB or saturation value if color mode is HSB.

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue value if color mode is RGB or brightness value if color mode is HSB.

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

a color string.

\n', + 'type': 'String' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'gray', + 'description': '

a grayscale value.

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'values', + 'description': '

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

\n', + 'type': 'Number[]' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

the fill color.

\n', + 'type': 'p5.Color' + } + ], + 'chainable': 1 + } + ] + }, + 'noFill': { + 'name': 'noFill', + 'class': 'p5', + 'module': 'Color' + }, + 'noStroke': { + 'name': 'noStroke', + 'class': 'p5', + 'module': 'Color' + }, + 'stroke': { + 'name': 'stroke', + 'class': 'p5', + 'module': 'Color', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red value if color mode is RGB or hue value if color mode is HSB.

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green value if color mode is RGB or saturation value if color mode is HSB.

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue value if color mode is RGB or brightness value if color mode is HSB.

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

a color string.

\n', + 'type': 'String' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'gray', + 'description': '

a grayscale value.

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'values', + 'description': '

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

\n', + 'type': 'Number[]' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

the stroke color.

\n', + 'type': 'p5.Color' + } + ], + 'chainable': 1 + } + ] + }, + 'erase': { + 'name': 'erase', + 'params': [ + { + 'name': 'strengthFill', + 'description': '

a number (0-255) for the strength of erasing under a shape\'s interior.\n Defaults to 255, which is full strength.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'strengthStroke', + 'description': '

a number (0-255) for the strength of erasing under a shape\'s edge.\n Defaults to 255, which is full strength.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Color' + }, + 'noErase': { + 'name': 'noErase', + 'class': 'p5', + 'module': 'Color' + }, + 'arc': { + 'name': 'arc', + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the arc\'s ellipse.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the arc\'s ellipse.

\n', + 'type': 'Number' + }, + { + 'name': 'w', + 'description': '

width of the arc\'s ellipse by default.

\n', + 'type': 'Number' + }, + { + 'name': 'h', + '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, PIE, or OPEN.

\n', + 'type': 'Constant', + 'optional': true + }, + { + 'name': 'detail', + 'description': '

optional parameter for WebGL mode only. This is to\n specify the number of vertices that makes up the\n perimeter of the arc. Default value is 25. Won\'t\n draw a stroke for a detail of more than 50.

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'ellipse': { + 'name': 'ellipse', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the center of the ellipse.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the center 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': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'w', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'h', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'detail', + 'description': '

optional parameter for WebGL mode only. This is to\n specify the number of vertices that makes up the\n perimeter of the ellipse. Default value is 25. Won\'t\n draw a stroke for a detail of more than 50.

\n', + 'type': 'Integer', + 'optional': true + } + ] + } + ] + }, + 'circle': { + 'name': 'circle', + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the center of the circle.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the center of the circle.

\n', + 'type': 'Number' + }, + { + 'name': 'd', + 'description': '

diameter of the circle.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'line': { + 'name': 'line', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + '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 + }, + { + 'params': [ + { + 'name': 'x1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z1', + 'description': '

the z-coordinate of the first point.

\n', + 'type': 'Number' + }, + { + 'name': 'x2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z2', + 'description': '

the z-coordinate of the second point.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + } + ] + }, + 'point': { + 'name': 'point', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

the x-coordinate.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

the y-coordinate.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

the z-coordinate (for WebGL mode).

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'coordinateVector', + 'description': '

the coordinate vector.

\n', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + } + ] + }, + 'quad': { + 'name': 'quad', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + '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' + }, + { + 'name': 'detailX', + 'description': '

number of segments in the x-direction.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '

number of segments in the y-direction.

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z1', + 'description': '

the z-coordinate of the first point.

\n', + 'type': 'Number' + }, + { + 'name': 'x2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z2', + 'description': '

the z-coordinate of the second point.

\n', + 'type': 'Number' + }, + { + 'name': 'x3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z3', + 'description': '

the z-coordinate of the third point.

\n', + 'type': 'Number' + }, + { + 'name': 'x4', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y4', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z4', + 'description': '

the z-coordinate of the fourth point.

\n', + 'type': 'Number' + }, + { + 'name': 'detailX', + 'description': '', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '', + 'type': 'Integer', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'rect': { + 'name': 'rect', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + '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', + 'optional': true + }, + { + 'name': 'tl', + 'description': '

optional radius of top-left corner.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'tr', + 'description': '

optional radius of top-right corner.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'br', + 'description': '

optional radius of bottom-right corner.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'bl', + 'description': '

optional radius of bottom-left corner.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'w', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'h', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'detailX', + 'description': '

number of segments in the x-direction (for WebGL mode).

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '

number of segments in the y-direction (for WebGL mode).

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'square': { + 'name': 'square', + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the square.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the square.

\n', + 'type': 'Number' + }, + { + 'name': 's', + 'description': '

side size of the square.

\n', + 'type': 'Number' + }, + { + 'name': 'tl', + 'description': '

optional radius of top-left corner.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'tr', + 'description': '

optional radius of top-right corner.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'br', + 'description': '

optional radius of bottom-right corner.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'bl', + 'description': '

optional radius of bottom-left corner.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'triangle': { + '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' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'ellipseMode': { + 'name': 'ellipseMode', + 'params': [ + { + 'name': 'mode', + 'description': '

either CENTER, RADIUS, CORNER, or CORNERS

\n', + 'type': 'Constant' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'noSmooth': { + 'name': 'noSmooth', + 'class': 'p5', + 'module': 'Shape' + }, + 'rectMode': { + 'name': 'rectMode', + 'params': [ + { + 'name': 'mode', + 'description': '

either CORNER, CORNERS, CENTER, or RADIUS

\n', + 'type': 'Constant' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'smooth': { + 'name': 'smooth', + 'class': 'p5', + 'module': 'Shape' + }, + 'strokeCap': { + 'name': 'strokeCap', + 'params': [ + { + 'name': 'cap', + 'description': '

either ROUND, SQUARE, or PROJECT

\n', + 'type': 'Constant' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'strokeJoin': { + 'name': 'strokeJoin', + 'params': [ + { + 'name': 'join', + 'description': '

either MITER, BEVEL, or ROUND

\n', + 'type': 'Constant' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'strokeWeight': { + 'name': 'strokeWeight', + 'params': [ + { + 'name': 'weight', + 'description': '

the weight of the stroke (in pixels).

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'bezier': { + 'name': 'bezier', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + 'params': [ + { + 'name': 'x1', + 'description': '

x-coordinate of the first anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'y1', + 'description': '

y-coordinate of the first anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'x2', + 'description': '

x-coordinate of the first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'y2', + 'description': '

y-coordinate of the first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x3', + 'description': '

x-coordinate of the second control point.

\n', + 'type': 'Number' + }, + { + 'name': 'y3', + 'description': '

y-coordinate of the second control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x4', + 'description': '

x-coordinate of the second anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'y4', + 'description': '

y-coordinate of the second anchor point.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z1', + 'description': '

z-coordinate of the first anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'x2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z2', + 'description': '

z-coordinate of the first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z3', + 'description': '

z-coordinate of the second control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x4', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y4', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z4', + 'description': '

z-coordinate of the second anchor point.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + } + ] + }, + 'bezierDetail': { + 'name': 'bezierDetail', + 'params': [ + { + 'name': 'detail', + 'description': '

number of segments to use. Defaults to 20.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'bezierPoint': { + 'name': 'bezierPoint', + 'params': [ + { + 'name': 'a', + 'description': '

coordinate of first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'b', + 'description': '

coordinate of first anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'c', + 'description': '

coordinate of second anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'd', + 'description': '

coordinate of second control point.

\n', + 'type': 'Number' + }, + { + 'name': 't', + 'description': '

amount to interpolate between 0 and 1.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'bezierTangent': { + 'name': 'bezierTangent', + 'params': [ + { + 'name': 'a', + 'description': '

coordinate of first anchor point.

\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 anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 't', + 'description': '

amount to interpolate between 0 and 1.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'curve': { + 'name': 'curve', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + 'params': [ + { + 'name': 'x1', + 'description': '

x-coordinate of the first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'y1', + 'description': '

y-coordinate of the first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x2', + 'description': '

x-coordinate of the first anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'y2', + 'description': '

y-coordinate of the first anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'x3', + 'description': '

x-coordinate of the second anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'y3', + 'description': '

y-coordinate of the second anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'x4', + 'description': '

x-coordinate of the second control point.

\n', + 'type': 'Number' + }, + { + 'name': 'y4', + 'description': '

y-coordinate of the second control point.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z1', + 'description': '

z-coordinate of the first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z2', + 'description': '

z-coordinate of the first anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'x3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z3', + 'description': '

z-coordinate of the second anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'x4', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y4', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z4', + 'description': '

z-coordinate of the second control point.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + } + ] + }, + 'curveDetail': { + 'name': 'curveDetail', + 'params': [ + { + 'name': 'resolution', + 'description': '

number of segments to use. Defaults to 20.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'curveTightness': { + 'name': 'curveTightness', + 'params': [ + { + 'name': 'amount', + 'description': '

amount of tightness.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'curvePoint': { + 'name': 'curvePoint', + 'params': [ + { + 'name': 'a', + 'description': '

coordinate of first anchor point.

\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 anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 't', + 'description': '

amount to interpolate between 0 and 1.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'curveTangent': { + 'name': 'curveTangent', + 'params': [ + { + 'name': 'a', + 'description': '

coordinate of first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'b', + 'description': '

coordinate of first anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'c', + 'description': '

coordinate of second anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'd', + 'description': '

coordinate of second control point.

\n', + 'type': 'Number' + }, + { + 'name': 't', + 'description': '

amount to interpolate between 0 and 1.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'beginContour': { + 'name': 'beginContour', + 'class': 'p5', + 'module': 'Shape' + }, + 'beginShape': { + 'name': 'beginShape', + 'params': [ + { + 'name': 'kind', + 'description': '

either POINTS, LINES, TRIANGLES, TRIANGLE_FAN\n TRIANGLE_STRIP, QUADS, QUAD_STRIP or TESS.

\n', + 'type': 'Constant', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'bezierVertex': { + 'name': 'bezierVertex', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + 'params': [ + { + 'name': 'x2', + 'description': '

x-coordinate of the first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'y2', + 'description': '

y-coordinate of the first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x3', + 'description': '

x-coordinate of the second control point.

\n', + 'type': 'Number' + }, + { + 'name': 'y3', + 'description': '

y-coordinate of the second control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x4', + 'description': '

x-coordinate of the anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'y4', + 'description': '

y-coordinate of the anchor point.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z2', + 'description': '

z-coordinate of the first control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z3', + 'description': '

z-coordinate of the second control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x4', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y4', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z4', + 'description': '

z-coordinate of the anchor point.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + } + ] + }, + 'curveVertex': { + 'name': 'curveVertex', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + '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 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z-coordinate of the vertex.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'endContour': { + 'name': 'endContour', + 'class': 'p5', + 'module': 'Shape' + }, + 'endShape': { + 'name': 'endShape', + 'params': [ + { + 'name': 'mode', + 'description': '

use CLOSE to close the shape

\n', + 'type': 'Constant', + 'optional': true + }, + { + 'name': 'count', + 'description': '

number of times you want to draw/instance the shape (for WebGL mode).

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'quadraticVertex': { + 'name': 'quadraticVertex', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + 'params': [ + { + 'name': 'cx', + 'description': '

x-coordinate of the control point.

\n', + 'type': 'Number' + }, + { + 'name': 'cy', + 'description': '

y-coordinate of the control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x3', + 'description': '

x-coordinate of the anchor point.

\n', + 'type': 'Number' + }, + { + 'name': 'y3', + 'description': '

y-coordinate of the anchor point.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'cx', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'cy', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'cz', + 'description': '

z-coordinate of the control point.

\n', + 'type': 'Number' + }, + { + 'name': 'x3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z3', + 'description': '

z-coordinate of the anchor point.

\n', + 'type': 'Number' + } + ] + } + ] + }, + 'vertex': { + 'name': 'vertex', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + '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 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z-coordinate of the vertex. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'u', + 'description': '

u-coordinate of the vertex\'s texture. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'v', + 'description': '

v-coordinate of the vertex\'s texture. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'normal': { + 'name': 'normal', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + 'params': [ + { + 'name': 'vector', + 'description': '

vertex normal as a p5.Vector object.

\n', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '

x-component of the vertex normal.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-component of the vertex normal.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z-component of the vertex normal.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + } + ] + }, + 'VERSION': { + 'name': 'VERSION', + 'class': 'p5', + 'module': 'Constants' + }, + 'P2D': { + 'name': 'P2D', + 'class': 'p5', + 'module': 'Constants' + }, + 'WEBGL': { + 'name': 'WEBGL', + 'class': 'p5', + 'module': 'Constants' + }, + 'WEBGL2': { + 'name': 'WEBGL2', + 'class': 'p5', + 'module': 'Constants' + }, + 'ARROW': { + 'name': 'ARROW', + 'class': 'p5', + 'module': 'Constants' + }, + 'CROSS': { + 'name': 'CROSS', + 'class': 'p5', + 'module': 'Constants' + }, + 'HAND': { + 'name': 'HAND', + 'class': 'p5', + 'module': 'Constants' + }, + 'MOVE': { + 'name': 'MOVE', + 'class': 'p5', + 'module': 'Constants' + }, + 'TEXT': { + 'name': 'TEXT', + 'class': 'p5', + 'module': 'Constants' + }, + 'WAIT': { + 'name': 'WAIT', + 'class': 'p5', + 'module': 'Constants' + }, + 'HALF_PI': { + 'name': 'HALF_PI', + 'class': 'p5', + 'module': 'Constants' + }, + 'PI': { + 'name': 'PI', + 'class': 'p5', + 'module': 'Constants' + }, + 'QUARTER_PI': { + 'name': 'QUARTER_PI', + 'class': 'p5', + 'module': 'Constants' + }, + 'TAU': { + 'name': 'TAU', + 'class': 'p5', + 'module': 'Constants' + }, + 'TWO_PI': { + 'name': 'TWO_PI', + 'class': 'p5', + 'module': 'Constants' + }, + 'DEGREES': { + 'name': 'DEGREES', + 'class': 'p5', + 'module': 'Constants' + }, + 'RADIANS': { + 'name': 'RADIANS', + 'class': 'p5', + 'module': 'Constants' + }, + 'CORNER': { + 'name': 'CORNER', + 'class': 'p5', + 'module': 'Constants' + }, + 'CORNERS': { + 'name': 'CORNERS', + 'class': 'p5', + 'module': 'Constants' + }, + 'RADIUS': { + 'name': 'RADIUS', + 'class': 'p5', + 'module': 'Constants' + }, + 'RIGHT': { + 'name': 'RIGHT', + 'class': 'p5', + 'module': 'Constants' + }, + 'LEFT': { + 'name': 'LEFT', + 'class': 'p5', + 'module': 'Constants' + }, + 'CENTER': { + 'name': 'CENTER', + 'class': 'p5', + 'module': 'Constants' + }, + 'TOP': { + 'name': 'TOP', + 'class': 'p5', + 'module': 'Constants' + }, + 'BOTTOM': { + 'name': 'BOTTOM', + 'class': 'p5', + 'module': 'Constants' + }, + 'BASELINE': { + 'name': 'BASELINE', + 'class': 'p5', + 'module': 'Constants' + }, + 'POINTS': { + 'name': 'POINTS', + 'class': 'p5', + 'module': 'Constants' + }, + 'LINES': { + 'name': 'LINES', + 'class': 'p5', + 'module': 'Constants' + }, + 'LINE_STRIP': { + 'name': 'LINE_STRIP', + 'class': 'p5', + 'module': 'Constants' + }, + 'LINE_LOOP': { + 'name': 'LINE_LOOP', + 'class': 'p5', + 'module': 'Constants' + }, + 'TRIANGLES': { + 'name': 'TRIANGLES', + 'class': 'p5', + 'module': 'Constants' + }, + 'TRIANGLE_FAN': { + 'name': 'TRIANGLE_FAN', + 'class': 'p5', + 'module': 'Constants' + }, + 'TRIANGLE_STRIP': { + 'name': 'TRIANGLE_STRIP', + 'class': 'p5', + 'module': 'Constants' + }, + 'QUADS': { + 'name': 'QUADS', + 'class': 'p5', + 'module': 'Constants' + }, + 'QUAD_STRIP': { + 'name': 'QUAD_STRIP', + 'class': 'p5', + 'module': 'Constants' + }, + 'TESS': { + 'name': 'TESS', + 'class': 'p5', + 'module': 'Constants' + }, + 'CLOSE': { + 'name': 'CLOSE', + 'class': 'p5', + 'module': 'Constants' + }, + 'OPEN': { + 'name': 'OPEN', + 'class': 'p5', + 'module': 'Constants' + }, + 'CHORD': { + 'name': 'CHORD', + 'class': 'p5', + 'module': 'Constants' + }, + 'PIE': { + 'name': 'PIE', + 'class': 'p5', + 'module': 'Constants' + }, + 'PROJECT': { + 'name': 'PROJECT', + 'class': 'p5', + 'module': 'Constants' + }, + 'SQUARE': { + 'name': 'SQUARE', + 'class': 'p5', + 'module': 'Constants' + }, + 'ROUND': { + 'name': 'ROUND', + 'class': 'p5', + 'module': 'Constants' + }, + 'BEVEL': { + 'name': 'BEVEL', + 'class': 'p5', + 'module': 'Constants' + }, + 'MITER': { + 'name': 'MITER', + 'class': 'p5', + 'module': 'Constants' + }, + 'RGB': { + 'name': 'RGB', + 'class': 'p5', + 'module': 'Constants' + }, + 'HSB': { + 'name': 'HSB', + 'class': 'p5', + 'module': 'Constants' + }, + 'HSL': { + 'name': 'HSL', + 'class': 'p5', + 'module': 'Constants' + }, + 'AUTO': { + 'name': 'AUTO', + 'class': 'p5', + 'module': 'Constants' + }, + 'ALT': { + 'name': 'ALT', + 'class': 'p5', + 'module': 'Constants' + }, + 'BACKSPACE': { + 'name': 'BACKSPACE', + 'class': 'p5', + 'module': 'Constants' + }, + 'CONTROL': { + 'name': 'CONTROL', + 'class': 'p5', + 'module': 'Constants' + }, + 'DELETE': { + 'name': 'DELETE', + 'class': 'p5', + 'module': 'Constants' + }, + 'DOWN_ARROW': { + 'name': 'DOWN_ARROW', + 'class': 'p5', + 'module': 'Constants' + }, + 'ENTER': { + 'name': 'ENTER', + 'class': 'p5', + 'module': 'Constants' + }, + 'ESCAPE': { + 'name': 'ESCAPE', + 'class': 'p5', + 'module': 'Constants' + }, + 'LEFT_ARROW': { + 'name': 'LEFT_ARROW', + 'class': 'p5', + 'module': 'Constants' + }, + 'OPTION': { + 'name': 'OPTION', + 'class': 'p5', + 'module': 'Constants' + }, + 'RETURN': { + 'name': 'RETURN', + 'class': 'p5', + 'module': 'Constants' + }, + 'RIGHT_ARROW': { + 'name': 'RIGHT_ARROW', + 'class': 'p5', + 'module': 'Constants' + }, + 'SHIFT': { + 'name': 'SHIFT', + 'class': 'p5', + 'module': 'Constants' + }, + 'TAB': { + 'name': 'TAB', + 'class': 'p5', + 'module': 'Constants' + }, + 'UP_ARROW': { + 'name': 'UP_ARROW', + 'class': 'p5', + 'module': 'Constants' + }, + 'BLEND': { + 'name': 'BLEND', + 'class': 'p5', + 'module': 'Constants' + }, + 'REMOVE': { + 'name': 'REMOVE', + 'class': 'p5', + 'module': 'Constants' + }, + 'ADD': { + 'name': 'ADD', + 'class': 'p5', + 'module': 'Constants' + }, + 'DARKEST': { + 'name': 'DARKEST', + 'class': 'p5', + 'module': 'Constants' + }, + 'LIGHTEST': { + 'name': 'LIGHTEST', + 'class': 'p5', + 'module': 'Constants' + }, + 'DIFFERENCE': { + 'name': 'DIFFERENCE', + 'class': 'p5', + 'module': 'Constants' + }, + 'SUBTRACT': { + 'name': 'SUBTRACT', + 'class': 'p5', + 'module': 'Constants' + }, + 'EXCLUSION': { + 'name': 'EXCLUSION', + 'class': 'p5', + 'module': 'Constants' + }, + 'MULTIPLY': { + 'name': 'MULTIPLY', + 'class': 'p5', + 'module': 'Constants' + }, + 'SCREEN': { + 'name': 'SCREEN', + 'class': 'p5', + 'module': 'Constants' + }, + 'REPLACE': { + 'name': 'REPLACE', + 'class': 'p5', + 'module': 'Constants' + }, + 'OVERLAY': { + 'name': 'OVERLAY', + 'class': 'p5', + 'module': 'Constants' + }, + 'HARD_LIGHT': { + 'name': 'HARD_LIGHT', + 'class': 'p5', + 'module': 'Constants' + }, + 'SOFT_LIGHT': { + 'name': 'SOFT_LIGHT', + 'class': 'p5', + 'module': 'Constants' + }, + 'DODGE': { + 'name': 'DODGE', + 'class': 'p5', + 'module': 'Constants' + }, + 'BURN': { + 'name': 'BURN', + 'class': 'p5', + 'module': 'Constants' + }, + 'THRESHOLD': { + 'name': 'THRESHOLD', + 'class': 'p5', + 'module': 'Constants' + }, + 'GRAY': { + 'name': 'GRAY', + 'class': 'p5', + 'module': 'Constants' + }, + 'OPAQUE': { + 'name': 'OPAQUE', + 'class': 'p5', + 'module': 'Constants' + }, + 'INVERT': { + 'name': 'INVERT', + 'class': 'p5', + 'module': 'Constants' + }, + 'POSTERIZE': { + 'name': 'POSTERIZE', + 'class': 'p5', + 'module': 'Constants' + }, + 'DILATE': { + 'name': 'DILATE', + 'class': 'p5', + 'module': 'Constants' + }, + 'ERODE': { + 'name': 'ERODE', + 'class': 'p5', + 'module': 'Constants' + }, + 'BLUR': { + 'name': 'BLUR', + 'class': 'p5', + 'module': 'Constants' + }, + 'NORMAL': { + 'name': 'NORMAL', + 'class': 'p5', + 'module': 'Constants' + }, + 'ITALIC': { + 'name': 'ITALIC', + 'class': 'p5', + 'module': 'Constants' + }, + 'BOLD': { + 'name': 'BOLD', + 'class': 'p5', + 'module': 'Constants' + }, + 'BOLDITALIC': { + 'name': 'BOLDITALIC', + 'class': 'p5', + 'module': 'Constants' + }, + 'CHAR': { + 'name': 'CHAR', + 'class': 'p5', + 'module': 'Constants' + }, + 'WORD': { + 'name': 'WORD', + 'class': 'p5', + 'module': 'Constants' + }, + 'LINEAR': { + 'name': 'LINEAR', + 'class': 'p5', + 'module': 'Constants' + }, + 'QUADRATIC': { + 'name': 'QUADRATIC', + 'class': 'p5', + 'module': 'Constants' + }, + 'BEZIER': { + 'name': 'BEZIER', + 'class': 'p5', + 'module': 'Constants' + }, + 'CURVE': { + 'name': 'CURVE', + 'class': 'p5', + 'module': 'Constants' + }, + 'STROKE': { + 'name': 'STROKE', + 'class': 'p5', + 'module': 'Constants' + }, + 'FILL': { + 'name': 'FILL', + 'class': 'p5', + 'module': 'Constants' + }, + 'TEXTURE': { + 'name': 'TEXTURE', + 'class': 'p5', + 'module': 'Constants' + }, + 'IMMEDIATE': { + 'name': 'IMMEDIATE', + 'class': 'p5', + 'module': 'Constants' + }, + 'IMAGE': { + 'name': 'IMAGE', + 'class': 'p5', + 'module': 'Constants' + }, + 'NEAREST': { + 'name': 'NEAREST', + 'class': 'p5', + 'module': 'Constants' + }, + 'REPEAT': { + 'name': 'REPEAT', + 'class': 'p5', + 'module': 'Constants' + }, + 'CLAMP': { + 'name': 'CLAMP', + 'class': 'p5', + 'module': 'Constants' + }, + 'MIRROR': { + 'name': 'MIRROR', + 'class': 'p5', + 'module': 'Constants' + }, + 'FLAT': { + 'name': 'FLAT', + 'class': 'p5', + 'module': 'Constants' + }, + 'SMOOTH': { + 'name': 'SMOOTH', + 'class': 'p5', + 'module': 'Constants' + }, + 'LANDSCAPE': { + 'name': 'LANDSCAPE', + 'class': 'p5', + 'module': 'Constants' + }, + 'PORTRAIT': { + 'name': 'PORTRAIT', + 'class': 'p5', + 'module': 'Constants' + }, + 'GRID': { + 'name': 'GRID', + 'class': 'p5', + 'module': 'Constants' + }, + 'AXES': { + 'name': 'AXES', + 'class': 'p5', + 'module': 'Constants' + }, + 'LABEL': { + 'name': 'LABEL', + 'class': 'p5', + 'module': 'Constants' + }, + 'FALLBACK': { + 'name': 'FALLBACK', + 'class': 'p5', + 'module': 'Constants' + }, + 'CONTAIN': { + 'name': 'CONTAIN', + 'class': 'p5', + 'module': 'Constants' + }, + 'COVER': { + 'name': 'COVER', + 'class': 'p5', + 'module': 'Constants' + }, + 'UNSIGNED_BYTE': { + 'name': 'UNSIGNED_BYTE', + 'class': 'p5', + 'module': 'Constants' + }, + 'UNSIGNED_INT': { + 'name': 'UNSIGNED_INT', + 'class': 'p5', + 'module': 'Constants' + }, + 'FLOAT': { + 'name': 'FLOAT', + 'class': 'p5', + 'module': 'Constants' + }, + 'HALF_FLOAT': { + 'name': 'HALF_FLOAT', + 'class': 'p5', + 'module': 'Constants' + }, + 'RGBA': { + 'name': 'RGBA', + 'class': 'p5', + 'module': 'Constants' + }, + 'print': { + 'name': 'print', + 'params': [ + { + 'name': 'contents', + 'description': '

content to print to the console.

\n', + 'type': 'Any' + } + ], + 'class': 'p5', + 'module': 'Environment' + }, + 'frameCount': { + 'name': 'frameCount', + 'class': 'p5', + 'module': 'Environment' + }, + 'deltaTime': { + 'name': 'deltaTime', + 'class': 'p5', + 'module': 'Environment' + }, + 'focused': { + 'name': 'focused', + 'class': 'p5', + 'module': 'Environment' + }, + 'cursor': { + 'name': 'cursor', + 'params': [ + { + 'name': 'type', + 'description': '

Built-in: either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT.\n Native CSS properties: \'grab\', \'progress\', and so on.\n Path to cursor image.

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

horizontal active spot of the cursor.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'y', + 'description': '

vertical active spot of the cursor.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Environment' + }, + 'frameRate': { + 'name': 'frameRate', + 'class': 'p5', + 'module': 'Environment', + 'overloads': [ + { + 'params': [ + { + 'name': 'fps', + 'description': '

number of frames to draw per second.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + ] + } + ] + }, + 'getTargetFrameRate': { + 'name': 'getTargetFrameRate', + 'class': 'p5', + 'module': 'Environment' + }, + 'noCursor': { + 'name': 'noCursor', + 'class': 'p5', + 'module': 'Environment' + }, + 'webglVersion': { + 'name': 'webglVersion', + 'class': 'p5', + 'module': 'Environment' + }, + 'displayWidth': { + 'name': 'displayWidth', + 'class': 'p5', + 'module': 'Environment' + }, + 'displayHeight': { + 'name': 'displayHeight', + 'class': 'p5', + 'module': 'Environment' + }, + 'windowWidth': { + 'name': 'windowWidth', + 'class': 'p5', + 'module': 'Environment' + }, + 'windowHeight': { + 'name': 'windowHeight', + 'class': 'p5', + 'module': 'Environment' + }, + 'windowResized': { + 'name': 'windowResized', + 'params': [ + { + 'name': 'event', + 'description': '

optional resize Event.

\n', + 'type': 'UIEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Environment' + }, + 'width': { + 'name': 'width', + 'class': 'p5', + 'module': 'Environment' + }, + 'height': { + 'name': 'height', + 'class': 'p5', + 'module': 'Environment' + }, + 'fullscreen': { + 'name': 'fullscreen', + 'params': [ + { + 'name': 'val', + 'description': '

whether the sketch should be in fullscreen mode.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Environment' + }, + 'pixelDensity': { + 'name': 'pixelDensity', + 'class': 'p5', + 'module': 'Environment', + 'overloads': [ + { + 'params': [ + { + 'name': 'val', + 'description': '

desired pixel density.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + ] + } + ] + }, + 'displayDensity': { + 'name': 'displayDensity', + 'class': 'p5', + 'module': 'Environment' + }, + 'getURL': { + 'name': 'getURL', + 'class': 'p5', + 'module': 'Environment' + }, + 'getURLPath': { + 'name': 'getURLPath', + 'class': 'p5', + 'module': 'Environment' + }, + 'getURLParams': { + 'name': 'getURLParams', + 'class': 'p5', + 'module': 'Environment' + }, + 'preload': { + 'name': 'preload', + 'class': 'p5', + 'module': 'Structure' + }, + 'setup': { + 'name': 'setup', + 'class': 'p5', + 'module': 'Structure' + }, + 'draw': { + 'name': 'draw', + 'class': 'p5', + 'module': 'Structure' + }, + 'remove': { + 'name': 'remove', + 'class': 'p5', + 'module': 'Structure' + }, + 'disableFriendlyErrors': { + 'name': 'disableFriendlyErrors', + 'class': 'p5', + 'module': 'Structure' + }, + 'let': { + 'name': 'let', + 'class': 'p5', + 'module': 'Foundation' + }, + 'if': { + 'name': 'if', + 'class': 'p5', + 'module': 'Foundation' + }, + 'function': { + 'name': 'function', + 'class': 'p5', + 'module': 'Foundation' + }, + 'Boolean': { + 'name': 'Boolean', + 'class': 'p5', + 'module': 'Foundation' + }, + 'String': { + 'name': 'String', + 'class': 'p5', + 'module': 'Foundation' + }, + 'Number': { + 'name': 'Number', + 'class': 'p5', + 'module': 'Foundation' + }, + 'Object': { + 'name': 'Object', + 'class': 'p5', + 'module': 'Foundation' + }, + 'Array': { + 'name': 'Array', + 'class': 'p5', + 'module': 'Foundation' + }, + 'class': { + 'name': 'class', + 'class': 'p5', + 'module': 'Foundation' + }, + 'for': { + 'name': 'for', + 'class': 'p5', + 'module': 'Foundation' + }, + 'while': { + 'name': 'while', + 'class': 'p5', + 'module': 'Foundation' + }, + 'console': { + 'name': 'console', + 'class': 'p5', + 'module': 'Foundation' + }, + 'createCanvas': { + 'name': 'createCanvas', + 'class': 'p5', + 'module': 'Rendering', + 'overloads': [ + { + 'params': [ + { + 'name': 'width', + 'description': '

width of the canvas. Defaults to 100.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'height', + 'description': '

width of the canvas. Defaults to 100.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'renderer', + 'description': '

either P2D or WEBGL. Defaults to P2D.

\n', + 'type': 'Constant', + 'optional': true + }, + { + 'name': 'canvas', + 'description': '

existing canvas element that should be used for the sketch.

\n', + 'type': 'HTMLCanvasElement', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'width', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'height', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'canvas', + 'description': '', + 'type': 'HTMLCanvasElement', + 'optional': true + } + ] + } + ] + }, + 'resizeCanvas': { + 'name': 'resizeCanvas', + 'params': [ + { + 'name': 'width', + 'description': '

width of the canvas.

\n', + 'type': 'Number' + }, + { + 'name': 'height', + 'description': '

height of the canvas.

\n', + 'type': 'Number' + }, + { + 'name': 'noRedraw', + 'description': '

whether to delay calling\n redraw(). Defaults\n to false.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Rendering' + }, + 'noCanvas': { + 'name': 'noCanvas', + 'class': 'p5', + 'module': 'Rendering' + }, + 'createGraphics': { + 'name': 'createGraphics', + 'class': 'p5', + 'module': 'Rendering', + 'overloads': [ + { + 'params': [ + { + 'name': 'width', + 'description': '

width of the graphics buffer.

\n', + 'type': 'Number' + }, + { + 'name': 'height', + 'description': '

height of the graphics buffer.

\n', + 'type': 'Number' + }, + { + 'name': 'renderer', + 'description': '

either P2D or WEBGL. Defaults to P2D.

\n', + 'type': 'Constant', + 'optional': true + }, + { + 'name': 'canvas', + 'description': '

existing canvas element that should be\n used for the graphics buffer..

\n', + 'type': 'HTMLCanvasElement', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'width', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'height', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'canvas', + 'description': '', + 'type': 'HTMLCanvasElement', + 'optional': true + } + ] + } + ] + }, + 'createFramebuffer': { + 'name': 'createFramebuffer', + 'params': [ + { + 'name': 'options', + 'description': '

configuration options.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Rendering' + }, + 'clearDepth': { + 'name': 'clearDepth', + 'params': [ + { + 'name': 'depth', + 'description': '

amount of the depth buffer to clear between 0\n (none) and 1 (far clipping plane). Defaults to 1.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Rendering' + }, + 'blendMode': { + 'name': 'blendMode', + 'params': [ + { + 'name': 'mode', + 'description': '

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

\n', + 'type': 'Constant' + } + ], + 'class': 'p5', + 'module': 'Rendering' + }, + 'drawingContext': { + 'name': 'drawingContext', + 'class': 'p5', + 'module': 'Rendering' + }, + 'noLoop': { + 'name': 'noLoop', + 'class': 'p5', + 'module': 'Structure' + }, + 'loop': { + 'name': 'loop', + 'class': 'p5', + 'module': 'Structure' + }, + 'isLooping': { + 'name': 'isLooping', + 'class': 'p5', + 'module': 'Structure' + }, + 'push': { + 'name': 'push', + 'class': 'p5', + 'module': 'Structure' + }, + 'pop': { + 'name': 'pop', + 'class': 'p5', + 'module': 'Structure' + }, + 'redraw': { + 'name': 'redraw', + 'params': [ + { + 'name': 'n', + 'description': '

number of times to run draw(). Defaults to 1.

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Structure' + }, + 'p5': { + 'name': 'p5', + 'params': [ + { + 'name': 'sketch', + 'description': '

function containing the sketch.

\n', + 'type': 'Object' + }, + { + 'name': 'node', + 'description': '

ID or reference to the HTML element that will contain the sketch.

\n', + 'type': 'String|HTMLElement' + } + ], + 'class': 'p5', + 'module': 'Structure' + }, + 'applyMatrix': { + 'name': 'applyMatrix', + 'class': 'p5', + 'module': 'Transform', + 'overloads': [ + { + 'params': [ + { + 'name': 'arr', + 'description': '

an array containing the elements of the transformation matrix. Its length should be either 6 (2D) or 16 (3D).

\n', + 'type': 'Array' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'a', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'b', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'c', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'd', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'e', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'f', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'a', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'b', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'c', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'd', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'e', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'f', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'g', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'h', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'i', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'j', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'k', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'l', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'm', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'n', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'o', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + }, + { + 'name': 'p', + 'description': '

an element of the transformation matrix.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + } + ] + }, + 'resetMatrix': { + 'name': 'resetMatrix', + 'class': 'p5', + 'module': 'Transform' + }, + 'rotate': { + 'name': 'rotate', + 'params': [ + { + 'name': 'angle', + 'description': '

angle of rotation in the current angleMode().

\n', + 'type': 'Number' + }, + { + 'name': 'axis', + 'description': '

axis to rotate about in 3D.

\n', + 'type': 'p5.Vector|Number[]', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Transform' + }, + 'rotateX': { + 'name': 'rotateX', + 'params': [ + { + 'name': 'angle', + 'description': '

angle of rotation in the current angleMode().

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Transform' + }, + 'rotateY': { + 'name': 'rotateY', + 'params': [ + { + 'name': 'angle', + 'description': '

angle of rotation in the current angleMode().

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Transform' + }, + 'rotateZ': { + 'name': 'rotateZ', + 'params': [ + { + 'name': 'angle', + 'description': '

angle of rotation in the current angleMode().

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Transform' + }, + 'scale': { + 'name': 'scale', + 'class': 'p5', + 'module': 'Transform', + 'overloads': [ + { + 'params': [ + { + 'name': 's', + 'description': '

amount to scale along the positive x-axis.

\n', + 'type': 'Number|p5.Vector|Number[]' + }, + { + 'name': 'y', + 'description': '

amount to scale along the positive y-axis. Defaults to s.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'z', + 'description': '

amount to scale along the positive z-axis. Defaults to y.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'scales', + 'description': '

vector whose components should be used to scale.

\n', + 'type': 'p5.Vector|Number[]' + } + ], + 'chainable': 1 + } + ] + }, + 'shearX': { + 'name': 'shearX', + 'params': [ + { + 'name': 'angle', + 'description': '

angle to shear by in the current angleMode().

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Transform' + }, + 'shearY': { + 'name': 'shearY', + 'params': [ + { + 'name': 'angle', + 'description': '

angle to shear by in the current angleMode().

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Transform' + }, + 'translate': { + 'name': 'translate', + 'class': 'p5', + 'module': 'Transform', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

amount to translate along the positive x-axis.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

amount to translate along the positive y-axis.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

amount to translate along the positive z-axis.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'vector', + 'description': '

vector by which to translate.

\n', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + } + ] + }, + 'storeItem': { + 'name': 'storeItem', + 'params': [ + { + 'name': 'key', + 'description': '

name of the value.

\n', + 'type': 'String' + }, + { + 'name': 'value', + 'description': '

value to be stored.

\n', + 'type': 'String|Number|Boolean|Object|Array' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'getItem': { + 'name': 'getItem', + 'params': [ + { + 'name': 'key', + 'description': '

name of the value.

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'clearStorage': { + 'name': 'clearStorage', + 'class': 'p5', + 'module': 'Data' + }, + 'removeItem': { + 'name': 'removeItem', + 'params': [ + { + 'name': 'key', + 'description': '

name of the value to remove.

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'createStringDict': { + 'name': 'createStringDict', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'key', + 'description': '', + 'type': 'String' + }, + { + 'name': 'value', + 'description': '', + 'type': 'String' + } + ] + }, + { + 'params': [ + { + 'name': 'object', + 'description': '

object

\n', + 'type': 'Object' + } + ] + } + ] + }, + 'createNumberDict': { + 'name': 'createNumberDict', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'key', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'value', + 'description': '', + 'type': 'Number' + } + ] + }, + { + 'params': [ + { + 'name': 'object', + 'description': '

object

\n', + 'type': 'Object' + } + ] + } + ] + }, + 'select': { + 'name': 'select', + 'params': [ + { + 'name': 'selectors', + 'description': '

CSS selector string of element to search for.

\n', + 'type': 'String' + }, + { + 'name': 'container', + 'description': '

CSS selector string, p5.Element, or\n HTMLElement to search within.

\n', + 'type': 'String|p5.Element|HTMLElement', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'selectAll': { + 'name': 'selectAll', + 'params': [ + { + 'name': 'selectors', + 'description': '

CSS selector string of element to search for.

\n', + 'type': 'String' + }, + { + 'name': 'container', + 'description': '

CSS selector string, p5.Element, or\n HTMLElement to search within.

\n', + 'type': 'String|p5.Element|HTMLElement', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'removeElements': { + 'name': 'removeElements', + 'class': 'p5', + 'module': 'DOM' + }, + 'changed': { + 'name': 'changed', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the element changes.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'input': { + 'name': 'input', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when input is detected within\n the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createDiv': { + 'name': 'createDiv', + 'params': [ + { + 'name': 'html', + 'description': '

inner HTML for the new <div></div> element.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createP': { + 'name': 'createP', + 'params': [ + { + 'name': 'html', + 'description': '

inner HTML for the new <p></p> element.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createSpan': { + 'name': 'createSpan', + 'params': [ + { + 'name': 'html', + 'description': '

inner HTML for the new <span></span> element.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createImg': { + 'name': 'createImg', + 'class': 'p5', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + { + 'name': 'src', + 'description': '

relative path or URL for the image.

\n', + 'type': 'String' + }, + { + 'name': 'alt', + 'description': '

alternate text for the image.

\n', + 'type': 'String' + } + ] + }, + { + 'params': [ + { + 'name': 'src', + 'description': '', + 'type': 'String' + }, + { + 'name': 'alt', + 'description': '', + 'type': 'String' + }, + { + 'name': 'crossOrigin', + 'description': '

crossOrigin property to use when fetching the image.

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'successCallback', + 'description': '

function to call once the image loads. The new image will be passed\n to the function as a p5.Element object.

\n', + 'type': 'Function', + 'optional': true + } + ] + } + ] + }, + 'createA': { + 'name': 'createA', + 'params': [ + { + 'name': 'href', + 'description': '

URL of linked page.

\n', + 'type': 'String' + }, + { + 'name': 'html', + 'description': '

inner HTML of link element to display.

\n', + 'type': 'String' + }, + { + 'name': 'target', + 'description': '

target where the new link should open,\n either \'_blank\', \'_self\', \'_parent\', or \'_top\'.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createSlider': { + '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': true + }, + { + 'name': 'step', + 'description': '

size for each step in the slider\'s range.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createButton': { + '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': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createCheckbox': { + 'name': 'createCheckbox', + 'params': [ + { + 'name': 'label', + 'description': '

label displayed after the checkbox.

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'value', + 'description': '

value of the checkbox. Checked is true and unchecked is false.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createSelect': { + 'name': 'createSelect', + 'class': 'p5', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + { + 'name': 'multiple', + 'description': '

support multiple selections.

\n', + 'type': 'Boolean', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'existing', + 'description': '

select element to wrap, either as a p5.Element or\n a HTMLSelectElement.

\n', + 'type': 'Object' + } + ] + } + ] + }, + 'createRadio': { + 'name': 'createRadio', + 'class': 'p5', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + { + 'name': 'containerElement', + 'description': '

container HTML Element, either a <div></div>\nor <span></span>.

\n', + 'type': 'Object', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'name', + 'description': '

name parameter assigned to each option\'s <input></input> element.

\n', + 'type': 'String', + 'optional': true + } + ] + }, + { + 'params': [ + ] + } + ] + }, + 'createColorPicker': { + 'name': 'createColorPicker', + 'params': [ + { + 'name': 'value', + 'description': '

default color as a CSS color string.

\n', + 'type': 'String|p5.Color', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createInput': { + 'name': 'createInput', + 'class': 'p5', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + { + 'name': 'value', + 'description': '

default value of the input box. Defaults to an empty string \'\'.

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'type', + 'description': '

type of input. Defaults to \'text\'.

\n', + 'type': 'String', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'value', + 'description': '', + 'type': 'String', + 'optional': true + } + ] + } + ] + }, + 'createFileInput': { + 'name': 'createFileInput', + 'params': [ + { + 'name': 'callback', + 'description': '

function to call once the file loads.

\n', + 'type': 'Function' + }, + { + 'name': 'multiple', + 'description': '

allow multiple files to be selected.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createVideo': { + 'name': 'createVideo', + 'params': [ + { + 'name': 'src', + 'description': '

path to a video file, or an array of paths for\n supporting different browsers.

\n', + 'type': 'String|String[]' + }, + { + 'name': 'callback', + 'description': '

function to call once the video is ready to play.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createAudio': { + 'name': 'createAudio', + 'params': [ + { + 'name': 'src', + 'description': '

path to an audio file, or an array of paths\n for supporting different browsers.

\n', + 'type': 'String|String[]', + 'optional': true + }, + { + 'name': 'callback', + 'description': '

function to call once the audio is ready to play.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createCapture': { + 'name': 'createCapture', + 'params': [ + { + 'name': 'type', + 'description': '

type of capture, either AUDIO or VIDEO,\n or a constraints object. Both video and audio\n audio streams are captured by default.

\n', + 'type': 'String|Constant|Object', + 'optional': true + }, + { + 'name': 'flipped', + 'description': '

flip the capturing video and mirror the output with {flipped:true}. By\n default it is false.

\n', + 'type': 'Object', + 'optional': true + }, + { + 'name': 'callback', + 'description': '

function to call once the stream\n has loaded.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'createElement': { + 'name': 'createElement', + 'params': [ + { + 'name': 'tag', + 'description': '

tag for the new element.

\n', + 'type': 'String' + }, + { + 'name': 'content', + 'description': '

HTML content to insert into the element.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'DOM' + }, + 'deviceOrientation': { + 'name': 'deviceOrientation', + 'class': 'p5', + 'module': 'Events' + }, + 'accelerationX': { + 'name': 'accelerationX', + 'class': 'p5', + 'module': 'Events' + }, + 'accelerationY': { + 'name': 'accelerationY', + 'class': 'p5', + 'module': 'Events' + }, + 'accelerationZ': { + 'name': 'accelerationZ', + 'class': 'p5', + 'module': 'Events' + }, + 'pAccelerationX': { + 'name': 'pAccelerationX', + 'class': 'p5', + 'module': 'Events' + }, + 'pAccelerationY': { + 'name': 'pAccelerationY', + 'class': 'p5', + 'module': 'Events' + }, + 'pAccelerationZ': { + 'name': 'pAccelerationZ', + 'class': 'p5', + 'module': 'Events' + }, + 'rotationX': { + 'name': 'rotationX', + 'class': 'p5', + 'module': 'Events' + }, + 'rotationY': { + 'name': 'rotationY', + 'class': 'p5', + 'module': 'Events' + }, + 'rotationZ': { + 'name': 'rotationZ', + 'class': 'p5', + 'module': 'Events' + }, + 'pRotationX': { + 'name': 'pRotationX', + 'class': 'p5', + 'module': 'Events' + }, + 'pRotationY': { + 'name': 'pRotationY', + 'class': 'p5', + 'module': 'Events' + }, + 'pRotationZ': { + 'name': 'pRotationZ', + 'class': 'p5', + 'module': 'Events' + }, + 'turnAxis': { + 'name': 'turnAxis', + 'class': 'p5', + 'module': 'Events' + }, + 'setMoveThreshold': { + 'name': 'setMoveThreshold', + 'params': [ + { + 'name': 'value', + 'description': '

The threshold value

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'setShakeThreshold': { + 'name': 'setShakeThreshold', + 'params': [ + { + 'name': 'value', + 'description': '

The threshold value

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'deviceMoved': { + 'name': 'deviceMoved', + 'class': 'p5', + 'module': 'Events' + }, + 'deviceTurned': { + 'name': 'deviceTurned', + 'class': 'p5', + 'module': 'Events' + }, + 'deviceShaken': { + 'name': 'deviceShaken', + 'class': 'p5', + 'module': 'Events' + }, + 'keyIsPressed': { + 'name': 'keyIsPressed', + 'class': 'p5', + 'module': 'Events' + }, + 'key': { + 'name': 'key', + 'class': 'p5', + 'module': 'Events' + }, + 'keyCode': { + 'name': 'keyCode', + 'class': 'p5', + 'module': 'Events' + }, + 'keyPressed': { + 'name': 'keyPressed', + 'params': [ + { + 'name': 'event', + 'description': '

optional KeyboardEvent callback argument.

\n', + 'type': 'KeyboardEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'keyReleased': { + 'name': 'keyReleased', + 'params': [ + { + 'name': 'event', + 'description': '

optional KeyboardEvent callback argument.

\n', + 'type': 'KeyboardEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'keyTyped': { + 'name': 'keyTyped', + 'params': [ + { + 'name': 'event', + 'description': '

optional KeyboardEvent callback argument.

\n', + 'type': 'KeyboardEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'keyIsDown': { + 'name': 'keyIsDown', + 'params': [ + { + 'name': 'code', + 'description': '

key to check.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'movedX': { + 'name': 'movedX', + 'class': 'p5', + 'module': 'Events' + }, + 'movedY': { + 'name': 'movedY', + 'class': 'p5', + 'module': 'Events' + }, + 'mouseX': { + 'name': 'mouseX', + 'class': 'p5', + 'module': 'Events' + }, + 'mouseY': { + 'name': 'mouseY', + 'class': 'p5', + 'module': 'Events' + }, + 'pmouseX': { + 'name': 'pmouseX', + 'class': 'p5', + 'module': 'Events' + }, + 'pmouseY': { + 'name': 'pmouseY', + 'class': 'p5', + 'module': 'Events' + }, + 'winMouseX': { + 'name': 'winMouseX', + 'class': 'p5', + 'module': 'Events' + }, + 'winMouseY': { + 'name': 'winMouseY', + 'class': 'p5', + 'module': 'Events' + }, + 'pwinMouseX': { + 'name': 'pwinMouseX', + 'class': 'p5', + 'module': 'Events' + }, + 'pwinMouseY': { + 'name': 'pwinMouseY', + 'class': 'p5', + 'module': 'Events' + }, + 'mouseButton': { + 'name': 'mouseButton', + 'class': 'p5', + 'module': 'Events' + }, + 'mouseIsPressed': { + 'name': 'mouseIsPressed', + 'class': 'p5', + 'module': 'Events' + }, + 'mouseMoved': { + 'name': 'mouseMoved', + 'params': [ + { + 'name': 'event', + 'description': '

optional MouseEvent argument.

\n', + 'type': 'MouseEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'mouseDragged': { + 'name': 'mouseDragged', + 'params': [ + { + 'name': 'event', + 'description': '

optional MouseEvent argument.

\n', + 'type': 'MouseEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'mousePressed': { + 'name': 'mousePressed', + 'params': [ + { + 'name': 'event', + 'description': '

optional MouseEvent argument.

\n', + 'type': 'MouseEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'mouseReleased': { + 'name': 'mouseReleased', + 'params': [ + { + 'name': 'event', + 'description': '

optional MouseEvent argument.

\n', + 'type': 'MouseEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'mouseClicked': { + 'name': 'mouseClicked', + 'params': [ + { + 'name': 'event', + 'description': '

optional MouseEvent argument.

\n', + 'type': 'MouseEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'doubleClicked': { + 'name': 'doubleClicked', + 'params': [ + { + 'name': 'event', + 'description': '

optional MouseEvent argument.

\n', + 'type': 'MouseEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'mouseWheel': { + 'name': 'mouseWheel', + 'params': [ + { + 'name': 'event', + 'description': '

optional WheelEvent argument.

\n', + 'type': 'WheelEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'requestPointerLock': { + 'name': 'requestPointerLock', + 'class': 'p5', + 'module': 'Events' + }, + 'exitPointerLock': { + 'name': 'exitPointerLock', + 'class': 'p5', + 'module': 'Events' + }, + 'touches': { + 'name': 'touches', + 'class': 'p5', + 'module': 'Events' + }, + 'touchStarted': { + 'name': 'touchStarted', + 'params': [ + { + 'name': 'event', + 'description': '

optional TouchEvent argument.

\n', + 'type': 'TouchEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'touchMoved': { + 'name': 'touchMoved', + 'params': [ + { + 'name': 'event', + 'description': '

optional TouchEvent argument.

\n', + 'type': 'TouchEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'touchEnded': { + 'name': 'touchEnded', + 'params': [ + { + 'name': 'event', + 'description': '

optional TouchEvent argument.

\n', + 'type': 'TouchEvent', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Events' + }, + 'createImage': { + 'name': 'createImage', + 'params': [ + { + 'name': 'width', + 'description': '

width in pixels.

\n', + 'type': 'Integer' + }, + { + 'name': 'height', + 'description': '

height in pixels.

\n', + 'type': 'Integer' + } + ], + 'class': 'p5', + 'module': 'Image' + }, + 'saveCanvas': { + 'name': 'saveCanvas', + 'class': 'p5', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'selectedCanvas', + 'description': '

reference to a\n specific HTML5 canvas element.

\n', + 'type': 'p5.Framebuffer|p5.Element|HTMLCanvasElement' + }, + { + 'name': 'filename', + 'description': '

file name. Defaults to \'untitled\'.

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'extension', + 'description': '

file extension, either \'jpg\' or \'png\'. Defaults to \'png\'.

\n', + 'type': 'String', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'filename', + 'description': '', + 'type': 'String', + 'optional': true + }, + { + 'name': 'extension', + 'description': '', + 'type': 'String', + 'optional': true + } + ] + } + ] + }, + 'saveFrames': { + 'name': 'saveFrames', + 'params': [ + { + 'name': 'filename', + 'description': '

prefix of file name.

\n', + 'type': 'String' + }, + { + 'name': 'extension', + 'description': '

file extension, either \'jpg\' or \'png\'.

\n', + 'type': 'String' + }, + { + 'name': 'duration', + 'description': '

duration in seconds to record. This parameter will be constrained to be less or equal to 15.

\n', + 'type': 'Number' + }, + { + 'name': 'framerate', + 'description': '

number of frames to save per second. This parameter will be constrained to be less or equal to 22.

\n', + 'type': 'Number' + }, + { + 'name': 'callback', + 'description': '

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, filename, and extension.

\n', + 'type': 'Function(Array)', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Image' + }, + 'loadImage': { + 'name': 'loadImage', + 'params': [ + { + 'name': 'path', + 'description': '

path of the image to be loaded or base64 encoded image.

\n', + 'type': 'String' + }, + { + 'name': 'successCallback', + 'description': '

function called with\n p5.Image once it\n loads.

\n', + 'type': 'function(p5.Image)', + 'optional': true + }, + { + 'name': 'failureCallback', + 'description': '

function called with event\n error if the image fails to load.

\n', + 'type': 'Function(Event)', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Image' + }, + 'saveGif': { + 'name': 'saveGif', + 'params': [ + { + 'name': 'filename', + 'description': '

file name of gif.

\n', + 'type': 'String' + }, + { + 'name': 'duration', + 'description': '

duration in seconds to capture from the sketch.

\n', + 'type': 'Number' + }, + { + 'name': 'options', + 'description': '

an object that can contain five more properties:\n delay, a Number specifying how much time to wait before recording;\n units, a String that can be either \'seconds\' or \'frames\'. By default it\'s \'seconds’;\n silent, a Boolean that defines presence of progress notifications. By default it’s false;\n notificationDuration, a Number that defines how long in seconds the final notification\n will live. By default it\'s 0, meaning the notification will never be removed;\n notificationID, a String that specifies the id of the notification\'s DOM element. By default it’s \'progressBar’.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Image' + }, + 'image': { + 'name': 'image', + 'class': 'p5', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'img', + 'description': '

image to display.

\n', + 'type': 'p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture' + }, + { + 'name': 'x', + 'description': '

x-coordinate of the top-left corner of the image.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the top-left corner of the image.

\n', + 'type': 'Number' + }, + { + 'name': 'width', + 'description': '

width to draw the image.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'height', + 'description': '

height to draw the image.

\n', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'img', + 'description': '', + 'type': 'p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture' + }, + { + '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': true + }, + { + 'name': 'sHeight', + 'description': '

the height of the subsection of the\n source image to draw into the destination rectangle

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'fit', + 'description': '

either CONTAIN or COVER

\n', + 'type': 'Constant', + 'optional': true + }, + { + 'name': 'xAlign', + 'description': '

either LEFT, RIGHT or CENTER default is CENTER

\n', + 'type': 'Constant', + 'optional': true + }, + { + 'name': 'yAlign', + 'description': '

either TOP, BOTTOM or CENTER default is CENTER

\n', + 'type': 'Constant', + 'optional': true + } + ] + } + ] + }, + 'tint': { + 'name': 'tint', + 'class': 'p5', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red or hue value.

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green or saturation value.

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue or brightness.

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

CSS color string.

\n', + 'type': 'String' + } + ] + }, + { + 'params': [ + { + 'name': 'gray', + 'description': '

grayscale value.

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'values', + 'description': '

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

\n', + 'type': 'Number[]' + } + ] + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

the tint color

\n', + 'type': 'p5.Color' + } + ] + } + ] + }, + 'noTint': { + 'name': 'noTint', + 'class': 'p5', + 'module': 'Image' + }, + 'imageMode': { + 'name': 'imageMode', + 'params': [ + { + 'name': 'mode', + 'description': '

either CORNER, CORNERS, or CENTER.

\n', + 'type': 'Constant' + } + ], + 'class': 'p5', + 'module': 'Image' + }, + 'pixels': { + 'name': 'pixels', + 'class': 'p5', + 'module': 'Image' + }, + 'blend': { + 'name': 'blend', + 'class': 'p5', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'srcImage', + 'description': '

source image.

\n', + 'type': 'p5.Image' + }, + { + '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. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.

\n', + 'type': 'Constant' + } + ] + }, + { + 'params': [ + { + 'name': 'sx', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sy', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sw', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sh', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dx', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dy', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dw', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dh', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'blendMode', + 'description': '', + 'type': 'Constant' + } + ] + } + ] + }, + 'copy': { + 'name': 'copy', + 'class': 'p5', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'srcImage', + 'description': '

source image.

\n', + 'type': 'p5.Image|p5.Element' + }, + { + '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' + } + ] + }, + { + 'params': [ + { + 'name': 'sx', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sy', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sw', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sh', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dx', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dy', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dw', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dh', + 'description': '', + 'type': 'Integer' + } + ] + } + ] + }, + 'filter': { + 'name': 'filter', + 'class': 'p5', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'filterType', + 'description': '

either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.

\n', + 'type': 'Constant' + }, + { + 'name': 'filterParam', + 'description': '

parameter unique to each filter.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'useWebGL', + 'description': '

flag to control whether to use fast\n WebGL filters (GPU) or original image\n filters (CPU); defaults to true.

\n', + 'type': 'Boolean', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'filterType', + 'description': '', + 'type': 'Constant' + }, + { + 'name': 'useWebGL', + 'description': '', + 'type': 'Boolean', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'shaderFilter', + 'description': '

shader that\'s been loaded, with the\n frag shader using a tex0 uniform.

\n', + 'type': 'p5.Shader' + } + ] + } + ] + }, + 'get': { + 'name': 'get', + 'class': 'p5', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the pixel.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the pixel.

\n', + 'type': 'Number' + }, + { + 'name': 'w', + 'description': '

width of the subsection to be returned.

\n', + 'type': 'Number' + }, + { + 'name': 'h', + 'description': '

height of the subsection to be returned.

\n', + 'type': 'Number' + } + ] + }, + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + } + ] + } + ] + }, + 'loadPixels': { + 'name': 'loadPixels', + 'class': 'p5', + 'module': 'Image' + }, + 'set': { + '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': '

grayscale value | pixel array |\n p5.Color object | p5.Image to copy.

\n', + 'type': 'Number|Number[]|Object' + } + ], + 'class': 'p5', + 'module': 'Image' + }, + 'updatePixels': { + 'name': 'updatePixels', + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the upper-left corner of region\n to update.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'y', + 'description': '

y-coordinate of the upper-left corner of region\n to update.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'w', + 'description': '

width of region to update.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'h', + 'description': '

height of region to update.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Image' + }, + 'loadJSON': { + 'name': 'loadJSON', + 'params': [ + { + 'name': 'path', + 'description': '

path of the JSON file to be loaded.

\n', + 'type': 'String' + }, + { + 'name': 'successCallback', + 'description': '

function to call once the data is loaded. Will be passed the object.

\n', + 'type': 'Function', + 'optional': true + }, + { + 'name': 'errorCallback', + 'description': '

function to call if the data fails to load. Will be passed an Error event object.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'loadStrings': { + 'name': 'loadStrings', + 'params': [ + { + 'name': 'path', + 'description': '

path of the text file to be loaded.

\n', + 'type': 'String' + }, + { + 'name': 'successCallback', + 'description': '

function to call once the data is\n loaded. Will be passed the array.

\n', + 'type': 'Function', + 'optional': true + }, + { + 'name': 'errorCallback', + 'description': '

function to call if the data fails to\n load. Will be passed an Error event\n object.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'loadTable': { + 'name': 'loadTable', + 'params': [ + { + 'name': 'filename', + 'description': '

name of the file or URL to load

\n', + 'type': 'String' + }, + { + 'name': 'extension', + 'description': '

parse the table by comma-separated values "csv", semicolon-separated\n values "ssv", or tab-separated values "tsv"

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'header', + 'description': '

"header" to indicate table has header row

\n', + 'type': 'String', + 'optional': true + }, + { + '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': true + }, + { + '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': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'loadXML': { + 'name': 'loadXML', + 'params': [ + { + 'name': 'path', + 'description': '

path of the XML file to be loaded.

\n', + 'type': 'String' + }, + { + 'name': 'successCallback', + 'description': '

function to call once the data is\n loaded. Will be passed the\n p5.XML object.

\n', + 'type': 'Function', + 'optional': true + }, + { + 'name': 'errorCallback', + 'description': '

function to call if the data fails to\n load. Will be passed an Error event\n object.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'loadBytes': { + 'name': 'loadBytes', + 'params': [ + { + 'name': 'file', + 'description': '

name of the file or URL to load

\n', + 'type': 'String' + }, + { + 'name': 'callback', + 'description': '

function to be executed after loadBytes()\n completes

\n', + 'type': 'Function', + 'optional': true + }, + { + 'name': 'errorCallback', + 'description': '

function to be executed if there\n is an error

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'httpGet': { + 'name': 'httpGet', + 'class': 'p5', + 'module': 'IO', + 'overloads': [ + { + 'params': [ + { + 'name': 'path', + 'description': '

name of the file or url to load

\n', + 'type': 'String' + }, + { + 'name': 'datatype', + 'description': '

"json", "jsonp", "binary", "arrayBuffer",\n "xml", or "text"

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'data', + 'description': '

param data passed sent with request

\n', + 'type': 'Object|Boolean', + 'optional': true + }, + { + 'name': 'callback', + 'description': '

function to be executed after\n httpGet() completes, data is passed in\n as first argument

\n', + 'type': 'Function', + 'optional': true + }, + { + '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': true + } + ] + }, + { + 'params': [ + { + 'name': 'path', + 'description': '', + 'type': 'String' + }, + { + 'name': 'data', + 'description': '', + 'type': 'Object|Boolean' + }, + { + 'name': 'callback', + 'description': '', + 'type': 'Function', + 'optional': true + }, + { + 'name': 'errorCallback', + 'description': '', + 'type': 'Function', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'path', + 'description': '', + 'type': 'String' + }, + { + 'name': 'callback', + 'description': '', + 'type': 'Function' + }, + { + 'name': 'errorCallback', + 'description': '', + 'type': 'Function', + 'optional': true + } + ] + } + ] + }, + 'httpPost': { + 'name': 'httpPost', + 'class': 'p5', + 'module': 'IO', + 'overloads': [ + { + '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': true + }, + { + 'name': 'data', + 'description': '

param data passed sent with request

\n', + 'type': 'Object|Boolean', + 'optional': true + }, + { + 'name': 'callback', + 'description': '

function to be executed after\n httpPost() completes, data is passed in\n as first argument

\n', + 'type': 'Function', + 'optional': true + }, + { + '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': true + } + ] + }, + { + 'params': [ + { + 'name': 'path', + 'description': '', + 'type': 'String' + }, + { + 'name': 'data', + 'description': '', + 'type': 'Object|Boolean' + }, + { + 'name': 'callback', + 'description': '', + 'type': 'Function', + 'optional': true + }, + { + 'name': 'errorCallback', + 'description': '', + 'type': 'Function', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'path', + 'description': '', + 'type': 'String' + }, + { + 'name': 'callback', + 'description': '', + 'type': 'Function' + }, + { + 'name': 'errorCallback', + 'description': '', + 'type': 'Function', + 'optional': true + } + ] + } + ] + }, + 'httpDo': { + 'name': 'httpDo', + 'class': 'p5', + 'module': 'IO', + 'overloads': [ + { + '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': true + }, + { + 'name': 'datatype', + 'description': '

"json", "jsonp", "xml", or "text"

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'data', + 'description': '

param data passed sent with request

\n', + 'type': 'Object', + 'optional': true + }, + { + 'name': 'callback', + 'description': '

function to be executed after\n httpGet() completes, data is passed in\n as first argument

\n', + 'type': 'Function', + 'optional': true + }, + { + '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': true + } + ] + }, + { + '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': true + }, + { + 'name': 'errorCallback', + 'description': '', + 'type': 'Function', + 'optional': true + } + ] + } + ] + }, + 'createWriter': { + 'name': 'createWriter', + 'params': [ + { + 'name': 'name', + 'description': '

name of the file to create.

\n', + 'type': 'String' + }, + { + 'name': 'extension', + 'description': '

format to use for the file.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'save': { + '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': true + }, + { + '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': true + }, + { + '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': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'saveJSON': { + 'name': 'saveJSON', + 'params': [ + { + 'name': 'json', + 'description': '

data to save.

\n', + 'type': 'Array|Object' + }, + { + 'name': 'filename', + 'description': '

name of the file to be saved.

\n', + 'type': 'String' + }, + { + 'name': 'optimize', + 'description': '

whether to trim unneeded whitespace. Defaults\n to true.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'saveStrings': { + 'name': 'saveStrings', + 'params': [ + { + 'name': 'list', + 'description': '

data to save.

\n', + 'type': 'String[]' + }, + { + 'name': 'filename', + 'description': '

name of file to be saved.

\n', + 'type': 'String' + }, + { + 'name': 'extension', + 'description': '

format to use for the file.

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'isCRLF', + 'description': '

whether to add \\r\\n to the end of each\n string. Defaults to false.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'saveTable': { + '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': true + } + ], + 'class': 'p5', + 'module': 'IO' + }, + 'abs': { + 'name': 'abs', + 'params': [ + { + 'name': 'n', + 'description': '

number to compute.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'ceil': { + 'name': 'ceil', + 'params': [ + { + 'name': 'n', + 'description': '

number to round up.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'constrain': { + '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' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'dist': { + 'name': 'dist', + 'class': 'p5', + 'module': 'Math', + 'overloads': [ + { + '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' + } + ] + }, + { + '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' + } + ] + } + ] + }, + 'exp': { + 'name': 'exp', + 'params': [ + { + 'name': 'n', + 'description': '

exponent to raise.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'floor': { + 'name': 'floor', + 'params': [ + { + 'name': 'n', + 'description': '

number to round down.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'lerp': { + 'name': 'lerp', + 'params': [ + { + 'name': 'start', + 'description': '

first value.

\n', + 'type': 'Number' + }, + { + 'name': 'stop', + 'description': '

second value.

\n', + 'type': 'Number' + }, + { + 'name': 'amt', + 'description': '

number.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'log': { + 'name': 'log', + 'params': [ + { + 'name': 'n', + 'description': '

number greater than 0.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'mag': { + 'name': 'mag', + 'params': [ + { + 'name': 'x', + 'description': '

first component.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

second component.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'map': { + 'name': 'map', + 'params': [ + { + 'name': 'value', + 'description': '

the value to be remapped.

\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': true + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'max': { + 'name': 'max', + 'class': 'p5', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'n0', + 'description': '

first number to compare.

\n', + 'type': 'Number' + }, + { + 'name': 'n1', + 'description': '

second number to compare.

\n', + 'type': 'Number' + } + ] + }, + { + 'params': [ + { + 'name': 'nums', + 'description': '

numbers to compare.

\n', + 'type': 'Number[]' + } + ] + } + ] + }, + 'min': { + 'name': 'min', + 'class': 'p5', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'n0', + 'description': '

first number to compare.

\n', + 'type': 'Number' + }, + { + 'name': 'n1', + 'description': '

second number to compare.

\n', + 'type': 'Number' + } + ] + }, + { + 'params': [ + { + 'name': 'nums', + 'description': '

numbers to compare.

\n', + 'type': 'Number[]' + } + ] + } + ] + }, + 'norm': { + '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' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'pow': { + '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' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'round': { + 'name': 'round', + 'params': [ + { + 'name': 'n', + 'description': '

number to round.

\n', + 'type': 'Number' + }, + { + 'name': 'decimals', + 'description': '

number of decimal places to round to, default is 0.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'sq': { + 'name': 'sq', + 'params': [ + { + 'name': 'n', + 'description': '

number to square.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'sqrt': { + 'name': 'sqrt', + 'params': [ + { + 'name': 'n', + 'description': '

non-negative number to square root.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'fract': { + 'name': 'fract', + 'params': [ + { + 'name': 'n', + 'description': '

number whose fractional part will be found.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'createVector': { + 'name': 'createVector', + 'params': [ + { + 'name': 'x', + 'description': '

x component of the vector.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'y', + 'description': '

y component of the vector.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'z', + 'description': '

z component of the vector.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'noise': { + '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': true + }, + { + 'name': 'z', + 'description': '

z-coordinate in noise space.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'noiseDetail': { + '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' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'noiseSeed': { + 'name': 'noiseSeed', + 'params': [ + { + 'name': 'seed', + 'description': '

seed value.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'randomSeed': { + 'name': 'randomSeed', + 'params': [ + { + 'name': 'seed', + 'description': '

seed value.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'random': { + 'name': 'random', + 'class': 'p5', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'min', + 'description': '

lower bound (inclusive).

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'max', + 'description': '

upper bound (exclusive).

\n', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'choices', + 'description': '

array to choose from.

\n', + 'type': 'Array' + } + ] + } + ] + }, + 'randomGaussian': { + 'name': 'randomGaussian', + 'params': [ + { + 'name': 'mean', + 'description': '

mean.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'sd', + 'description': '

standard deviation.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'acos': { + 'name': 'acos', + 'params': [ + { + 'name': 'value', + 'description': '

value whose arc cosine is to be returned.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'asin': { + 'name': 'asin', + 'params': [ + { + 'name': 'value', + 'description': '

value whose arc sine is to be returned.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'atan': { + 'name': 'atan', + 'params': [ + { + 'name': 'value', + 'description': '

value whose arc tangent is to be returned.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'atan2': { + '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' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'cos': { + 'name': 'cos', + 'params': [ + { + 'name': 'angle', + 'description': '

the angle.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'sin': { + 'name': 'sin', + 'params': [ + { + 'name': 'angle', + 'description': '

the angle.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'tan': { + 'name': 'tan', + 'params': [ + { + 'name': 'angle', + 'description': '

the angle.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'degrees': { + 'name': 'degrees', + 'params': [ + { + 'name': 'radians', + 'description': '

radians value to convert to degrees.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'radians': { + 'name': 'radians', + 'params': [ + { + 'name': 'degrees', + 'description': '

degree value to convert to radians.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'Math' + }, + 'angleMode': { + 'name': 'angleMode', + 'class': 'p5', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'mode', + 'description': '

either RADIANS or DEGREES.

\n', + 'type': 'Constant' + } + ] + }, + { + 'params': [ + ] + } + ] + }, + 'textAlign': { + 'name': 'textAlign', + 'class': 'p5', + 'module': 'Typography', + 'overloads': [ + { + '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': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + ] + } + ] + }, + 'textLeading': { + 'name': 'textLeading', + 'class': 'p5', + 'module': 'Typography', + 'overloads': [ + { + 'params': [ + { + 'name': 'leading', + 'description': '

spacing between lines of text in units of pixels.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + ] + } + ] + }, + 'textSize': { + 'name': 'textSize', + 'class': 'p5', + 'module': 'Typography', + 'overloads': [ + { + 'params': [ + { + 'name': 'size', + 'description': '

size of the letters in units of pixels.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + ] + } + ] + }, + 'textStyle': { + 'name': 'textStyle', + 'class': 'p5', + 'module': 'Typography', + 'overloads': [ + { + 'params': [ + { + 'name': 'style', + 'description': '

styling for text, either NORMAL,\n ITALIC, BOLD or BOLDITALIC.

\n', + 'type': 'Constant' + } + ], + 'chainable': 1 + }, + { + 'params': [ + ] + } + ] + }, + 'textWidth': { + 'name': 'textWidth', + 'params': [ + { + 'name': 'str', + 'description': '

string of text to measure.

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': 'Typography' + }, + 'textAscent': { + 'name': 'textAscent', + 'class': 'p5', + 'module': 'Typography' + }, + 'textDescent': { + 'name': 'textDescent', + 'class': 'p5', + 'module': 'Typography' + }, + 'textWrap': { + 'name': 'textWrap', + 'params': [ + { + 'name': 'style', + 'description': '

text wrapping style, either WORD or CHAR.

\n', + 'type': 'Constant' + } + ], + 'class': 'p5', + 'module': 'Typography' + }, + 'loadFont': { + 'name': 'loadFont', + 'params': [ + { + 'name': 'path', + 'description': '

path of the font to be loaded.

\n', + 'type': 'String' + }, + { + 'name': 'successCallback', + 'description': '

function called with the\n p5.Font object after it\n loads.

\n', + 'type': 'Function', + 'optional': true + }, + { + 'name': 'failureCallback', + 'description': '

function called with the error\n Event\n object if the font fails to load.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Typography' + }, + 'text': { + 'name': 'text', + 'params': [ + { + 'name': 'str', + 'description': '

text to be displayed.

\n', + 'type': 'String|Object|Array|Number|Boolean' + }, + { + 'name': 'x', + 'description': '

x-coordinate of the text box.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the text box.

\n', + 'type': 'Number' + }, + { + 'name': 'maxWidth', + 'description': '

maximum width of the text box. See\n rectMode() for\n other options.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'maxHeight', + 'description': '

maximum height of the text box. See\n rectMode() for\n other options.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Typography' + }, + 'textFont': { + 'name': 'textFont', + 'class': 'p5', + 'module': 'Typography', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'font', + 'description': '

font as a p5.Font object or a string.

\n', + 'type': 'Object|String' + }, + { + 'name': 'size', + 'description': '

font size in pixels.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'append': { + 'name': 'append', + 'params': [ + { + 'name': 'array', + 'description': '

Array to append

\n', + 'type': 'Array' + }, + { + 'name': 'value', + 'description': '

to be added to the Array

\n', + 'type': 'Any' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'arrayCopy': { + 'name': 'arrayCopy', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'src', + 'description': '

the source Array

\n', + 'type': 'Array' + }, + { + 'name': 'srcPosition', + 'description': '

starting position in the source Array

\n', + 'type': 'Integer' + }, + { + 'name': 'dst', + 'description': '

the destination Array

\n', + 'type': 'Array' + }, + { + 'name': 'dstPosition', + 'description': '

starting position in the destination Array

\n', + 'type': 'Integer' + }, + { + 'name': 'length', + 'description': '

number of Array elements to be copied

\n', + 'type': 'Integer' + } + ] + }, + { + 'params': [ + { + 'name': 'src', + 'description': '', + 'type': 'Array' + }, + { + 'name': 'dst', + 'description': '', + 'type': 'Array' + }, + { + 'name': 'length', + 'description': '', + 'type': 'Integer', + 'optional': true + } + ] + } + ] + }, + 'concat': { + 'name': 'concat', + 'params': [ + { + 'name': 'a', + 'description': '

first Array to concatenate

\n', + 'type': 'Array' + }, + { + 'name': 'b', + 'description': '

second Array to concatenate

\n', + 'type': 'Array' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'reverse': { + 'name': 'reverse', + 'params': [ + { + 'name': 'list', + 'description': '

Array to reverse

\n', + 'type': 'Array' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'shorten': { + 'name': 'shorten', + 'params': [ + { + 'name': 'list', + 'description': '

Array to shorten

\n', + 'type': 'Array' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'shuffle': { + 'name': 'shuffle', + 'params': [ + { + 'name': 'array', + 'description': '

array to shuffle.

\n', + 'type': 'Array' + }, + { + 'name': 'bool', + 'description': '

if true, shuffle the original array in place. Defaults to false.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'sort': { + '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': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'splice': { + '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': 'Integer' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'subset': { + 'name': 'subset', + 'params': [ + { + 'name': 'list', + 'description': '

Array to extract from

\n', + 'type': 'Array' + }, + { + 'name': 'start', + 'description': '

position to begin

\n', + 'type': 'Integer' + }, + { + 'name': 'count', + 'description': '

number of values to extract

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'float': { + 'name': 'float', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'str', + 'description': '

string to convert.

\n', + 'type': 'String' + } + ] + }, + { + 'params': [ + { + 'name': 'ns', + 'description': '

array of strings to convert.

\n', + 'type': 'String[]' + } + ] + } + ] + }, + 'int': { + 'name': 'int', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'n', + 'description': '

value to convert.

\n', + 'type': 'String|Boolean|Number' + } + ] + }, + { + 'params': [ + { + 'name': 'ns', + 'description': '

values to convert.

\n', + 'type': 'Array' + } + ] + } + ] + }, + 'str': { + 'name': 'str', + 'params': [ + { + 'name': 'n', + 'description': '

value to convert.

\n', + 'type': 'String|Boolean|Number' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'boolean': { + 'name': 'boolean', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'n', + 'description': '

value to convert.

\n', + 'type': 'String|Boolean|Number' + } + ] + }, + { + 'params': [ + { + 'name': 'ns', + 'description': '

values to convert.

\n', + 'type': 'Array' + } + ] + } + ] + }, + 'byte': { + 'name': 'byte', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'n', + 'description': '

value to convert.

\n', + 'type': 'String|Boolean|Number' + } + ] + }, + { + 'params': [ + { + 'name': 'ns', + 'description': '

values to convert.

\n', + 'type': 'Array' + } + ] + } + ] + }, + 'char': { + 'name': 'char', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'n', + 'description': '

value to convert.

\n', + 'type': 'String|Number' + } + ] + }, + { + 'params': [ + { + 'name': 'ns', + 'description': '

values to convert.

\n', + 'type': 'Array' + } + ] + } + ] + }, + 'unchar': { + 'name': 'unchar', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'n', + 'description': '

value to convert.

\n', + 'type': 'String' + } + ] + }, + { + 'params': [ + { + 'name': 'ns', + 'description': '

values to convert.

\n', + 'type': 'String[]' + } + ] + } + ] + }, + 'hex': { + 'name': 'hex', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'n', + 'description': '

value to convert.

\n', + 'type': 'Number' + }, + { + 'name': 'digits', + 'description': '

number of digits to include.

\n', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'ns', + 'description': '

values to convert.

\n', + 'type': 'Number[]' + }, + { + 'name': 'digits', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + } + ] + }, + 'unhex': { + 'name': 'unhex', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'n', + 'description': '

value to convert.

\n', + 'type': 'String' + } + ] + }, + { + 'params': [ + { + 'name': 'ns', + 'description': '

values to convert.

\n', + 'type': 'String[]' + } + ] + } + ] + }, + 'join': { + 'name': 'join', + 'params': [ + { + 'name': 'list', + 'description': '

array of strings to combine.

\n', + 'type': 'Array' + }, + { + 'name': 'separator', + 'description': '

character(s) to place between strings when they\'re combined.

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'match': { + 'name': 'match', + 'params': [ + { + 'name': 'str', + 'description': '

string to search.

\n', + 'type': 'String' + }, + { + 'name': 'regexp', + 'description': '

regular expression to match.

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'matchAll': { + 'name': 'matchAll', + 'params': [ + { + 'name': 'str', + 'description': '

string to search.

\n', + 'type': 'String' + }, + { + 'name': 'regexp', + 'description': '

regular expression to match.

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'nf': { + 'name': 'nf', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'num', + 'description': '

number to format.

\n', + 'type': 'Number|String' + }, + { + 'name': 'left', + 'description': '

number of digits to include to the left of\n the decimal point.

\n', + 'type': 'Integer|String', + 'optional': true + }, + { + 'name': 'right', + 'description': '

number of digits to include to the right\n of the decimal point.

\n', + 'type': 'Integer|String', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'nums', + 'description': '

numbers to format.

\n', + 'type': 'Number[]' + }, + { + 'name': 'left', + 'description': '', + 'type': 'Integer|String', + 'optional': true + }, + { + 'name': 'right', + 'description': '', + 'type': 'Integer|String', + 'optional': true + } + ] + } + ] + }, + 'nfc': { + 'name': 'nfc', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'num', + 'description': '

number to format.

\n', + 'type': 'Number|String' + }, + { + 'name': 'right', + 'description': '

number of digits to include to the right\n of the decimal point.

\n', + 'type': 'Integer|String', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'nums', + 'description': '

numbers to format.

\n', + 'type': 'Number[]' + }, + { + 'name': 'right', + 'description': '', + 'type': 'Integer|String', + 'optional': true + } + ] + } + ] + }, + 'nfp': { + 'name': 'nfp', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'num', + 'description': '

number to format.

\n', + 'type': 'Number' + }, + { + 'name': 'left', + 'description': '

number of digits to include to the left of the\n decimal point.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'right', + 'description': '

number of digits to include to the right of the\n decimal point.

\n', + 'type': 'Integer', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'nums', + 'description': '

numbers to format.

\n', + 'type': 'Number[]' + }, + { + 'name': 'left', + 'description': '', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'right', + 'description': '', + 'type': 'Integer', + 'optional': true + } + ] + } + ] + }, + 'nfs': { + 'name': 'nfs', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'num', + 'description': '

number to format.

\n', + 'type': 'Number' + }, + { + 'name': 'left', + 'description': '

number of digits to include to the left of the\n decimal point.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'right', + 'description': '

number of digits to include to the right of the\n decimal point.

\n', + 'type': 'Integer', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'nums', + 'description': '

numbers to format.

\n', + 'type': 'Array' + }, + { + 'name': 'left', + 'description': '', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'right', + 'description': '', + 'type': 'Integer', + 'optional': true + } + ] + } + ] + }, + 'split': { + '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' + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'splitTokens': { + 'name': 'splitTokens', + 'params': [ + { + 'name': 'value', + 'description': '

string to split.

\n', + 'type': 'String' + }, + { + 'name': 'delim', + 'description': '

character(s) to use for splitting the string.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Data' + }, + 'trim': { + 'name': 'trim', + 'class': 'p5', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'str', + 'description': '

string to trim.

\n', + 'type': 'String' + } + ] + }, + { + 'params': [ + { + 'name': 'strs', + 'description': '

strings to trim.

\n', + 'type': 'String[]' + } + ] + } + ] + }, + 'day': { + 'name': 'day', + 'class': 'p5', + 'module': 'IO' + }, + 'hour': { + 'name': 'hour', + 'class': 'p5', + 'module': 'IO' + }, + 'minute': { + 'name': 'minute', + 'class': 'p5', + 'module': 'IO' + }, + 'millis': { + 'name': 'millis', + 'class': 'p5', + 'module': 'IO' + }, + 'month': { + 'name': 'month', + 'class': 'p5', + 'module': 'IO' + }, + 'second': { + 'name': 'second', + 'class': 'p5', + 'module': 'IO' + }, + 'year': { + 'name': 'year', + 'class': 'p5', + 'module': 'IO' + }, + 'beginGeometry': { + 'name': 'beginGeometry', + 'class': 'p5', + 'module': 'Shape' + }, + 'endGeometry': { + 'name': 'endGeometry', + 'class': 'p5', + 'module': 'Shape' + }, + 'buildGeometry': { + 'name': 'buildGeometry', + 'params': [ + { + 'name': 'callback', + 'description': '

function that draws the shape.

\n', + 'type': 'Function' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'freeGeometry': { + 'name': 'freeGeometry', + 'params': [ + { + 'name': 'geometry', + 'description': '

3D shape whose resources should be freed.

\n', + 'type': 'p5.Geometry' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'plane': { + 'name': 'plane', + 'params': [ + { + 'name': 'width', + 'description': '

width of the plane.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'height', + 'description': '

height of the plane.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'detailX', + 'description': '

number of triangle subdivisions along the x-axis.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '

number of triangle subdivisions along the y-axis.

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'box': { + 'name': 'box', + 'params': [ + { + 'name': 'width', + 'description': '

width of the box.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'height', + 'description': '

height of the box.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'depth', + 'description': '

depth of the box.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'detailX', + 'description': '

number of triangle subdivisions along the x-axis.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '

number of triangle subdivisions along the y-axis.

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'sphere': { + 'name': 'sphere', + 'params': [ + { + 'name': 'radius', + 'description': '

radius of the sphere. Defaults to 50.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'detailX', + 'description': '

number of triangle subdivisions along the x-axis. Defaults to 24.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '

number of triangle subdivisions along the y-axis. Defaults to 16.

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'cylinder': { + 'name': 'cylinder', + 'params': [ + { + 'name': 'radius', + 'description': '

radius of the cylinder. Defaults to 50.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'height', + 'description': '

height of the cylinder. Defaults to the value of radius.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'detailX', + 'description': '

number of edges along the top and bottom. Defaults to 24.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '

number of triangle subdivisions along the y-axis. Defaults to 1.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'bottomCap', + 'description': '

whether to draw the cylinder\'s bottom. Defaults to true.

\n', + 'type': 'Boolean', + 'optional': true + }, + { + 'name': 'topCap', + 'description': '

whether to draw the cylinder\'s top. Defaults to true.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'cone': { + 'name': 'cone', + 'params': [ + { + 'name': 'radius', + 'description': '

radius of the cone\'s base. Defaults to 50.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'height', + 'description': '

height of the cone. Defaults to the value of radius.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'detailX', + 'description': '

number of edges used to draw the base. Defaults to 24.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '

number of triangle subdivisions along the y-axis. Defaults to 1.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'cap', + 'description': '

whether to draw the cone\'s base. Defaults to true.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'ellipsoid': { + 'name': 'ellipsoid', + 'params': [ + { + 'name': 'radiusX', + 'description': '

radius of the ellipsoid along the x-axis. Defaults to 50.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'radiusY', + 'description': '

radius of the ellipsoid along the y-axis. Defaults to radiusX.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'radiusZ', + 'description': '

radius of the ellipsoid along the z-axis. Defaults to radiusY.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'detailX', + 'description': '

number of triangle subdivisions along the x-axis. Defaults to 24.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '

number of triangle subdivisions along the y-axis. Defaults to 16.

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'torus': { + 'name': 'torus', + 'params': [ + { + 'name': 'radius', + 'description': '

radius of the torus. Defaults to 50.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'tubeRadius', + 'description': '

radius of the tube. Defaults to 10.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'detailX', + 'description': '

number of edges that form the hole. Defaults to 24.

\n', + 'type': 'Integer', + 'optional': true + }, + { + 'name': 'detailY', + 'description': '

number of triangle subdivisions along the y-axis. Defaults to 16.

\n', + 'type': 'Integer', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'orbitControl': { + 'name': 'orbitControl', + 'params': [ + { + 'name': 'sensitivityX', + 'description': '

sensitivity to movement along the x-axis. Defaults to 1.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'sensitivityY', + 'description': '

sensitivity to movement along the y-axis. Defaults to 1.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'sensitivityZ', + 'description': '

sensitivity to movement along the z-axis. Defaults to 1.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'options', + 'description': '

object with two optional properties, disableTouchActions\n and freeRotation. Both are Booleans. disableTouchActions\n defaults to true and freeRotation defaults to false.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'debugMode': { + 'name': 'debugMode', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'mode', + 'description': '

either GRID or AXES

\n', + 'type': 'Constant' + } + ] + }, + { + 'params': [ + { + 'name': 'mode', + 'description': '', + 'type': 'Constant' + }, + { + 'name': 'gridSize', + 'description': '

side length of the grid.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'gridDivisions', + 'description': '

number of divisions in the grid.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'xOff', + 'description': '

offset from origin along the x-axis.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'yOff', + 'description': '

offset from origin along the y-axis.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'zOff', + 'description': '

offset from origin along the z-axis.

\n', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'mode', + 'description': '', + 'type': 'Constant' + }, + { + 'name': 'axesSize', + 'description': '

length of axes icon markers.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'xOff', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'yOff', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'zOff', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'gridSize', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'gridDivisions', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'gridXOff', + 'description': '

grid offset from the origin along the x-axis.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'gridYOff', + 'description': '

grid offset from the origin along the y-axis.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'gridZOff', + 'description': '

grid offset from the origin along the z-axis.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'axesSize', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'axesXOff', + 'description': '

axes icon offset from the origin along the x-axis.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'axesYOff', + 'description': '

axes icon offset from the origin along the y-axis.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'axesZOff', + 'description': '

axes icon offset from the origin along the z-axis.

\n', + 'type': 'Number', + 'optional': true + } + ] + } + ] + }, + 'noDebugMode': { + 'name': 'noDebugMode', + 'class': 'p5', + 'module': '3D' + }, + 'ambientLight': { + 'name': 'ambientLight', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red or hue value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green or saturation value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue, brightness, or lightness value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '

alpha (transparency) value in the current\n colorMode().

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'gray', + 'description': '

grayscale value between 0 and 255.

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

color as a CSS string.

\n', + 'type': 'String' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'values', + 'description': '

color as an array of RGBA, HSBA, or HSLA\n values.

\n', + 'type': 'Number[]' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

color as a p5.Color object.

\n', + 'type': 'p5.Color' + } + ], + 'chainable': 1 + } + ] + }, + 'specularColor': { + 'name': 'specularColor', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red or hue value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green or saturation value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue, brightness, or lightness value in the current\n colorMode().

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'gray', + 'description': '

grayscale value between 0 and 255.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

color as a CSS string.

\n', + 'type': 'String' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'values', + 'description': '

color as an array of RGBA, HSBA, or HSLA\n values.

\n', + 'type': 'Number[]' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

color as a p5.Color object.

\n', + 'type': 'p5.Color' + } + ], + 'chainable': 1 + } + ] + }, + 'directionalLight': { + 'name': 'directionalLight', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red or hue value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green or saturation value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue, brightness, or lightness value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'x', + 'description': '

x-component of the light\'s direction between -1 and 1.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-component of the light\'s direction between -1 and 1.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z-component of the light\'s direction between -1 and 1.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'direction', + 'description': '

direction of the light as a\n p5.Vector object.

\n', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

color as a p5.Color object,\n an array of color values, or as a CSS string.

\n', + 'type': 'p5.Color|Number[]|String' + }, + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '', + 'type': 'p5.Color|Number[]|String' + }, + { + 'name': 'direction', + 'description': '', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + } + ] + }, + 'pointLight': { + 'name': 'pointLight', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red or hue value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green or saturation value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue, brightness, or lightness value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'x', + 'description': '

x-coordinate of the light.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the light.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z-coordinate of the light.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'position', + 'description': '

position of the light as a\n p5.Vector object.

\n', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

color as a p5.Color object,\n an array of color values, or a CSS string.

\n', + 'type': 'p5.Color|Number[]|String' + }, + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '', + 'type': 'p5.Color|Number[]|String' + }, + { + 'name': 'position', + 'description': '', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + } + ] + }, + 'imageLight': { + 'name': 'imageLight', + 'params': [ + { + 'name': 'img', + 'description': '

image to use as the light source.

\n', + 'type': 'p5.image' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'panorama': { + 'name': 'panorama', + 'params': [ + { + 'name': 'img', + 'description': '

360˚ image to use as the background.

\n', + 'type': 'p5.Image' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'lights': { + 'name': 'lights', + 'class': 'p5', + 'module': '3D' + }, + 'lightFalloff': { + 'name': 'lightFalloff', + 'params': [ + { + 'name': 'constant', + 'description': '

constant value for calculating falloff.

\n', + 'type': 'Number' + }, + { + 'name': 'linear', + 'description': '

linear value for calculating falloff.

\n', + 'type': 'Number' + }, + { + 'name': 'quadratic', + 'description': '

quadratic value for calculating falloff.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'spotLight': { + 'name': 'spotLight', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red or hue value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green or saturation value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue, brightness, or lightness value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'x', + 'description': '

x-coordinate of the light.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the light.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z-coordinate of the light.

\n', + 'type': 'Number' + }, + { + 'name': 'rx', + 'description': '

x-component of light direction between -1 and 1.

\n', + 'type': 'Number' + }, + { + 'name': 'ry', + 'description': '

y-component of light direction between -1 and 1.

\n', + 'type': 'Number' + }, + { + 'name': 'rz', + 'description': '

z-component of light direction between -1 and 1.

\n', + 'type': 'Number' + }, + { + 'name': 'angle', + 'description': '

angle of the light cone. Defaults to PI / 3.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'concentration', + 'description': '

concentration of the light. Defaults to 100.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

color as a p5.Color object,\n an array of color values, or a CSS string.

\n', + 'type': 'p5.Color|Number[]|String' + }, + { + 'name': 'position', + 'description': '

position of the light as a p5.Vector object.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'direction', + 'description': '

direction of light as a p5.Vector object.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'angle', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'concentration', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'position', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'direction', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'angle', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'concentration', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'color', + 'description': '', + 'type': 'p5.Color|Number[]|String' + }, + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'direction', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'angle', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'concentration', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'color', + 'description': '', + 'type': 'p5.Color|Number[]|String' + }, + { + 'name': 'position', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'rx', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'ry', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'rz', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'angle', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'concentration', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'direction', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'angle', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'concentration', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'position', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'rx', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'ry', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'rz', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'angle', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'concentration', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'color', + 'description': '', + 'type': 'p5.Color|Number[]|String' + }, + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'rx', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'ry', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'rz', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'angle', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'concentration', + 'description': '', + 'type': 'Number', + 'optional': true + } + ] + } + ] + }, + 'noLights': { + 'name': 'noLights', + 'class': 'p5', + 'module': '3D' + }, + 'loadModel': { + 'name': 'loadModel', + 'class': 'p5', + 'module': 'Shape', + 'overloads': [ + { + 'params': [ + { + 'name': 'path', + 'description': '

path of the model to be loaded.

\n', + 'type': 'String' + }, + { + 'name': 'normalize', + 'description': '

if true, scale the model to fit the canvas.

\n', + 'type': 'Boolean' + }, + { + 'name': 'successCallback', + 'description': '

function to call once the model is loaded. Will be passed\n the p5.Geometry object.

\n', + 'type': 'function(p5.Geometry)', + 'optional': true + }, + { + 'name': 'failureCallback', + 'description': '

function to call if the model fails to load. Will be passed an Error event object.

\n', + 'type': 'Function(Event)', + 'optional': true + }, + { + 'name': 'fileType', + 'description': '

model’s file extension. Either \'.obj\' or \'.stl\'.

\n', + 'type': 'String', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'path', + 'description': '', + 'type': 'String' + }, + { + 'name': 'successCallback', + 'description': '', + 'type': 'function(p5.Geometry)', + 'optional': true + }, + { + 'name': 'failureCallback', + 'description': '', + 'type': 'Function(Event)', + 'optional': true + }, + { + 'name': 'fileType', + 'description': '', + 'type': 'String', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'path', + 'description': '', + 'type': 'String' + }, + { + 'name': 'options', + 'description': '

loading options.

\n', + 'type': 'Object', + 'optional': true, + 'props': [ + { + 'name': 'successCallback', + 'description': '', + 'type': 'function(p5.Geometry)', + 'optional': true + }, + { + 'name': 'failureCallback', + 'description': '', + 'type': 'Function(Event)', + 'optional': true + }, + { + 'name': 'fileType', + 'description': '', + 'type': 'String', + 'optional': true + }, + { + 'name': 'normalize', + 'description': '', + 'type': 'Boolean', + 'optional': true + }, + { + 'name': 'flipU', + 'description': '', + 'type': 'Boolean', + 'optional': true + }, + { + 'name': 'flipV', + 'description': '', + 'type': 'Boolean', + 'optional': true + } + ] + } + ] + } + ] + }, + 'model': { + 'name': 'model', + 'params': [ + { + 'name': 'model', + 'description': '

3D shape to be drawn.

\n', + 'type': 'p5.Geometry' + } + ], + 'class': 'p5', + 'module': 'Shape' + }, + 'loadShader': { + 'name': 'loadShader', + 'params': [ + { + 'name': 'vertFilename', + 'description': '

path of the vertex shader to be loaded.

\n', + 'type': 'String' + }, + { + 'name': 'fragFilename', + 'description': '

path of the fragment shader to be loaded.

\n', + 'type': 'String' + }, + { + 'name': 'successCallback', + 'description': '

function to call once the shader is loaded. Can be passed the\n p5.Shader object.

\n', + 'type': 'Function', + 'optional': true + }, + { + 'name': 'failureCallback', + 'description': '

function to call if the shader fails to load. Can be passed an\n Error event object.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'createShader': { + 'name': 'createShader', + 'params': [ + { + 'name': 'vertSrc', + 'description': '

source code for the vertex shader.

\n', + 'type': 'String' + }, + { + 'name': 'fragSrc', + 'description': '

source code for the fragment shader.

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'createFilterShader': { + 'name': 'createFilterShader', + 'params': [ + { + 'name': 'fragSrc', + 'description': '

source code for the fragment shader.

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'shader': { + 'name': 'shader', + 'params': [ + { + 'name': 's', + 'description': '

p5.Shader object\n to apply.

\n', + 'type': 'p5.Shader' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'resetShader': { + 'name': 'resetShader', + 'class': 'p5', + 'module': '3D' + }, + 'texture': { + 'name': 'texture', + 'params': [ + { + 'name': 'tex', + 'description': '

media to use as the texture.

\n', + 'type': 'p5.Image|p5.MediaElement|p5.Graphics|p5.Texture|p5.Framebuffer|p5.FramebufferTexture' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'textureMode': { + 'name': 'textureMode', + 'params': [ + { + 'name': 'mode', + 'description': '

either IMAGE or NORMAL.

\n', + 'type': 'Constant' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'textureWrap': { + 'name': 'textureWrap', + 'params': [ + { + 'name': 'wrapX', + 'description': '

either CLAMP, REPEAT, or MIRROR

\n', + 'type': 'Constant' + }, + { + 'name': 'wrapY', + 'description': '

either CLAMP, REPEAT, or MIRROR

\n', + 'type': 'Constant', + 'optional': true + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'normalMaterial': { + 'name': 'normalMaterial', + 'class': 'p5', + 'module': '3D' + }, + 'ambientMaterial': { + 'name': 'ambientMaterial', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red or hue value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green or saturation value in the\n current colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue, brightness, or lightness value in the\n current colorMode().

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'gray', + 'description': '

grayscale value between 0 (black) and 255 (white).

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

color as a p5.Color object,\n an array of color values, or a CSS string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'chainable': 1 + } + ] + }, + 'emissiveMaterial': { + 'name': 'emissiveMaterial', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + { + 'name': 'v1', + 'description': '

red or hue value in the current\n colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green or saturation value in the\n current colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue, brightness, or lightness value in the\n current colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '

alpha value in the current\n colorMode().

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'gray', + 'description': '

grayscale value between 0 (black) and 255 (white).

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

color as a p5.Color object,\n an array of color values, or a CSS string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'chainable': 1 + } + ] + }, + 'specularMaterial': { + 'name': 'specularMaterial', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + { + 'name': 'gray', + 'description': '

grayscale value between 0 (black) and 255 (white).

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '

alpha value in the current current\n colorMode().

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '

red or hue value in\n the current colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v2', + 'description': '

green or saturation value\n in the current colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'v3', + 'description': '

blue, brightness, or lightness value\n in the current colorMode().

\n', + 'type': 'Number' + }, + { + 'name': 'alpha', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'color', + 'description': '

color as a p5.Color object,\n an array of color values, or a CSS string.

\n', + 'type': 'p5.Color|Number[]|String' + } + ], + 'chainable': 1 + } + ] + }, + 'shininess': { + 'name': 'shininess', + 'params': [ + { + 'name': 'shine', + 'description': '

amount of shine.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'metalness': { + 'name': 'metalness', + 'params': [ + { + 'name': 'metallic', + 'description': '

amount of metalness.

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'camera': { + 'name': 'camera', + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the camera. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'y', + 'description': '

y-coordinate of the camera. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'z', + 'description': '

z-coordinate of the camera. Defaults to 800.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'centerX', + 'description': '

x-coordinate of the point the camera faces. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'centerY', + 'description': '

y-coordinate of the point the camera faces. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'centerZ', + 'description': '

z-coordinate of the point the camera faces. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'upX', + 'description': '

x-component of the camera’s "up" vector. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'upY', + 'description': '

y-component of the camera’s "up" vector. Defaults to 1.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'upZ', + 'description': '

z-component of the camera’s "up" vector. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'perspective': { + 'name': 'perspective', + 'params': [ + { + 'name': 'fovy', + 'description': '

camera frustum vertical field of view. Defaults to\n 2 * atan(height / 2 / 800).

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'aspect', + 'description': '

camera frustum aspect ratio. Defaults to\n width / height.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'near', + 'description': '

distance from the camera to the near clipping plane.\n Defaults to 0.1 * 800.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'far', + 'description': '

distance from the camera to the far clipping plane.\n Defaults to 10 * 800.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'linePerspective': { + 'name': 'linePerspective', + 'class': 'p5', + 'module': '3D', + 'overloads': [ + { + 'params': [ + { + 'name': 'enable', + 'description': '

whether to enable line perspective.

\n', + 'type': 'Boolean' + } + ] + }, + { + 'params': [ + ] + } + ] + }, + 'ortho': { + 'name': 'ortho', + 'params': [ + { + 'name': 'left', + 'description': '

x-coordinate of the frustum’s left plane. Defaults to -width / 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'right', + 'description': '

x-coordinate of the frustum’s right plane. Defaults to width / 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'bottom', + 'description': '

y-coordinate of the frustum’s bottom plane. Defaults to height / 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'top', + 'description': '

y-coordinate of the frustum’s top plane. Defaults to -height / 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'near', + 'description': '

z-coordinate of the frustum’s near plane. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'far', + 'description': '

z-coordinate of the frustum’s far plane. Defaults to max(width, height) + 800.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'frustum': { + 'name': 'frustum', + 'params': [ + { + 'name': 'left', + 'description': '

x-coordinate of the frustum’s left plane. Defaults to -width / 20.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'right', + 'description': '

x-coordinate of the frustum’s right plane. Defaults to width / 20.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'bottom', + 'description': '

y-coordinate of the frustum’s bottom plane. Defaults to height / 20.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'top', + 'description': '

y-coordinate of the frustum’s top plane. Defaults to -height / 20.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'near', + 'description': '

z-coordinate of the frustum’s near plane. Defaults to 0.1 * 800.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'far', + 'description': '

z-coordinate of the frustum’s far plane. Defaults to 10 * 800.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'createCamera': { + 'name': 'createCamera', + 'class': 'p5', + 'module': '3D' + }, + 'setCamera': { + 'name': 'setCamera', + 'params': [ + { + 'name': 'cam', + 'description': '

camera that should be made active.

\n', + 'type': 'p5.Camera' + } + ], + 'class': 'p5', + 'module': '3D' + }, + 'setAttributes': { + 'name': 'setAttributes', + 'class': 'p5', + 'module': 'Rendering', + 'overloads': [ + { + 'params': [ + { + 'name': 'key', + 'description': '

Name of attribute

\n', + 'type': 'String' + }, + { + 'name': 'value', + 'description': '

New value of named attribute

\n', + 'type': 'Boolean' + } + ] + }, + { + 'params': [ + { + 'name': 'obj', + 'description': '

object with key-value pairs

\n', + 'type': 'Object' + } + ] + } + ] + }, + 'getAudioContext': { + 'name': 'getAudioContext', + 'class': 'p5', + 'module': 'p5.sound' + }, + 'userStartAudio': { + 'params': [ + { + 'name': 'elements', + 'description': '

This argument can be an Element,\n Selector String, NodeList, p5.Element,\n jQuery Element, or an Array of any of those.

\n', + 'type': 'Element|Array', + 'optional': true + }, + { + 'name': 'callback', + 'description': '

Callback to invoke when the AudioContext\n has started

\n', + 'type': 'Function', + 'optional': true + } + ], + 'name': 'userStartAudio', + 'class': 'p5', + 'module': 'p5.sound' + }, + 'getOutputVolume': { + 'name': 'getOutputVolume', + 'class': 'p5', + 'module': 'p5.sound' + }, + 'outputVolume': { + 'name': 'outputVolume', + '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': true + }, + { + 'name': 'timeFromNow', + 'description': '

Schedule this event to happen at\n t seconds in the future

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5', + 'module': 'p5.sound' + }, + 'soundOut': { + 'name': 'soundOut', + 'class': 'p5', + 'module': 'p5.sound' + }, + 'sampleRate': { + 'name': 'sampleRate', + 'class': 'p5', + 'module': 'p5.sound' + }, + 'freqToMidi': { + 'name': 'freqToMidi', + 'params': [ + { + 'name': 'frequency', + 'description': '

A freqeuncy, for example, the "A"\n above Middle C is 440Hz

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'p5.sound' + }, + 'midiToFreq': { + 'name': 'midiToFreq', + 'params': [ + { + 'name': 'midiNote', + 'description': '

The number of a MIDI note

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'p5.sound' + }, + 'soundFormats': { + 'name': 'soundFormats', + 'params': [ + { + 'name': 'formats', + 'description': '

i.e. \'mp3\', \'wav\', \'ogg\'

\n', + 'type': 'String', + 'optional': true, + 'multiple': true + } + ], + 'class': 'p5', + 'module': 'p5.sound' + }, + 'saveSound': { + 'name': 'saveSound', + 'params': [ + { + 'name': 'soundFile', + 'description': '

p5.SoundFile that you wish to save

\n', + 'type': 'p5.SoundFile' + }, + { + 'name': 'fileName', + 'description': '

name of the resulting .wav file.

\n', + 'type': 'String' + } + ], + 'class': 'p5', + 'module': 'p5.sound' + }, + 'loadSound': { + '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': true + }, + { + 'name': 'errorCallback', + 'description': '

Name of a function to call if there is\n an error loading the file.

\n', + 'type': 'Function', + 'optional': true + }, + { + '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': true + } + ], + 'class': 'p5', + 'module': 'p5.sound' + }, + 'createConvolver': { + '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': true + }, + { + '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': true + } + ], + 'class': 'p5', + 'module': 'p5.sound' + }, + 'setBPM': { + 'name': 'setBPM', + 'params': [ + { + 'name': 'BPM', + 'description': '

Beats Per Minute

\n', + 'type': 'Number' + }, + { + 'name': 'rampTime', + 'description': '

Seconds from now

\n', + 'type': 'Number' + } + ], + 'class': 'p5', + 'module': 'p5.sound' + } + }, + 'p5.Color': { + 'toString': { + 'name': 'toString', + 'params': [ + { + 'name': 'format', + 'description': '

how the color string will be formatted.\nLeaving this empty formats the string as rgba(r, g, b, a).\n\'#rgb\' \'#rgba\' \'#rrggbb\' and \'#rrggbbaa\' format as hexadecimal color codes.\n\'rgb\' \'hsb\' and \'hsl\' return the color formatted in the specified color mode.\n\'rgba\' \'hsba\' and \'hsla\' are the same as above but with alpha channels.\n\'rgb%\' \'hsb%\' \'hsl%\' \'rgba%\' \'hsba%\' and \'hsla%\' format as percentages.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5.Color', + 'module': 'Color' + }, + 'setRed': { + 'name': 'setRed', + 'params': [ + { + 'name': 'red', + 'description': '

the new red value.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Color', + 'module': 'Color' + }, + 'setGreen': { + 'name': 'setGreen', + 'params': [ + { + 'name': 'green', + 'description': '

the new green value.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Color', + 'module': 'Color' + }, + 'setBlue': { + 'name': 'setBlue', + 'params': [ + { + 'name': 'blue', + 'description': '

the new blue value.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Color', + 'module': 'Color' + }, + 'setAlpha': { + 'name': 'setAlpha', + 'params': [ + { + 'name': 'alpha', + 'description': '

the new alpha value.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Color', + 'module': 'Color' + } + }, + 'p5.Element': { + 'elt': { + 'name': 'elt', + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'width': { + 'name': 'width', + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'height': { + 'name': 'height', + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'parent': { + 'name': 'parent', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + { + 'name': 'parent', + 'description': '

ID, p5.Element,\n or HTMLElement of desired parent element.

\n', + 'type': 'String|p5.Element|Object' + } + ], + 'chainable': 1 + }, + { + 'params': [ + ] + } + ] + }, + 'id': { + 'name': 'id', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + { + 'name': 'id', + 'description': '

ID of the element.

\n', + 'type': 'String' + } + ], + 'chainable': 1 + }, + { + 'params': [ + ] + } + ] + }, + 'class': { + 'name': 'class', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + { + 'name': 'class', + 'description': '

class to add.

\n', + 'type': 'String' + } + ], + 'chainable': 1 + }, + { + 'params': [ + ] + } + ] + }, + 'mousePressed': { + 'name': 'mousePressed', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the mouse is\n pressed over the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'doubleClicked': { + 'name': 'doubleClicked', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the mouse is\n double clicked over the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'mouseWheel': { + 'name': 'mouseWheel', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the mouse wheel is\n scrolled over the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'mouseReleased': { + 'name': 'mouseReleased', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the mouse is\n pressed over the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'mouseClicked': { + 'name': 'mouseClicked', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the mouse is\n pressed and released over the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'mouseMoved': { + 'name': 'mouseMoved', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the mouse\n moves over the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'mouseOver': { + 'name': 'mouseOver', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the mouse\n moves onto the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'mouseOut': { + 'name': 'mouseOut', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the mouse\n moves off the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'touchStarted': { + 'name': 'touchStarted', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the touch\n starts.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'touchMoved': { + 'name': 'touchMoved', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the touch\n moves over the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'touchEnded': { + 'name': 'touchEnded', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the touch\n ends.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'dragOver': { + 'name': 'dragOver', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the file is\n dragged over the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'dragLeave': { + 'name': 'dragLeave', + 'params': [ + { + 'name': 'fxn', + 'description': '

function to call when the file is\n dragged off the element.\n false disables the function.

\n', + 'type': 'Function|Boolean' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'addClass': { + 'name': 'addClass', + 'params': [ + { + 'name': 'class', + 'description': '

name of class to add.

\n', + 'type': 'String' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'removeClass': { + 'name': 'removeClass', + 'params': [ + { + 'name': 'class', + 'description': '

name of class to remove.

\n', + 'type': 'String' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'hasClass': { + 'name': 'hasClass', + 'params': [ + { + 'name': 'c', + 'description': '

name of class to check.

\n', + 'type': 'String' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'toggleClass': { + 'name': 'toggleClass', + 'params': [ + { + 'name': 'c', + 'description': '

class name to toggle.

\n', + 'type': 'String' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'child': { + 'name': 'child', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'child', + 'description': '

the ID, DOM node, or p5.Element\n to add to the current element

\n', + 'type': 'String|p5.Element', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'center': { + 'name': 'center', + 'params': [ + { + 'name': 'align', + 'description': '

passing \'vertical\', \'horizontal\' aligns element accordingly

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'html': { + 'name': 'html', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'html', + 'description': '

the HTML to be placed inside the element

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'append', + 'description': '

whether to append HTML to existing

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'position': { + 'name': 'position', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'x', + 'description': '

x-position relative to top-left of window (optional)

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'y', + 'description': '

y-position relative to top-left of window (optional)

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'positionType', + 'description': '

it can be static, fixed, relative, sticky, initial or inherit (optional)

\n', + 'type': 'String', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'style': { + 'name': 'style', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + { + 'name': 'property', + 'description': '

style property to set.

\n', + 'type': 'String' + } + ] + }, + { + 'params': [ + { + 'name': 'property', + 'description': '', + 'type': 'String' + }, + { + 'name': 'value', + 'description': '

value to assign to the property.

\n', + 'type': 'String|p5.Color' + } + ], + 'chainable': 1 + } + ] + }, + 'attribute': { + 'name': 'attribute', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'attr', + 'description': '

attribute to set.

\n', + 'type': 'String' + }, + { + 'name': 'value', + 'description': '

value to assign to the attribute.

\n', + 'type': 'String' + } + ], + 'chainable': 1 + } + ] + }, + 'removeAttribute': { + 'name': 'removeAttribute', + 'params': [ + { + 'name': 'attr', + 'description': '

attribute to remove.

\n', + 'type': 'String' + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'value': { + 'name': 'value', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'value', + 'description': '', + 'type': 'String|Number' + } + ], + 'chainable': 1 + } + ] + }, + 'show': { + 'name': 'show', + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'hide': { + 'name': 'hide', + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'size': { + 'name': 'size', + 'class': 'p5.Element', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'w', + 'description': '

width of the element, either AUTO, or a number.

\n', + 'type': 'Number|Constant', + 'optional': true + }, + { + 'name': 'h', + 'description': '

height of the element, either AUTO, or a number.

\n', + 'type': 'Number|Constant', + 'optional': true + } + ], + 'chainable': 1 + } + ] + }, + 'remove': { + 'name': 'remove', + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'drop': { + 'name': 'drop', + 'params': [ + { + 'name': 'callback', + 'description': '

called when a file loads. Called once for each file dropped.

\n', + 'type': 'Function' + }, + { + 'name': 'fxn', + 'description': '

called once when any files are dropped.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + }, + 'draggable': { + 'name': 'draggable', + 'params': [ + { + 'name': 'elmnt', + 'description': '

another p5.Element.

\n', + 'type': 'p5.Element', + 'optional': true + } + ], + 'class': 'p5.Element', + 'module': 'DOM' + } + }, + 'p5.Graphics': { + 'reset': { + 'name': 'reset', + 'class': 'p5.Graphics', + 'module': 'Rendering' + }, + 'remove': { + 'name': 'remove', + 'class': 'p5.Graphics', + 'module': 'Rendering' + }, + 'createFramebuffer': { + 'name': 'createFramebuffer', + 'params': [ + { + 'name': 'options', + 'description': '

configuration options.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5.Graphics', + 'module': 'Rendering' + } + }, + 'p5.TypedDict': { + 'size': { + 'name': 'size', + 'class': 'p5.TypedDict', + 'module': 'Data' + }, + 'hasKey': { + 'name': 'hasKey', + 'params': [ + { + 'name': 'key', + 'description': '

that you want to look up

\n', + 'type': 'Number|String' + } + ], + 'class': 'p5.TypedDict', + 'module': 'Data' + }, + 'get': { + 'name': 'get', + 'params': [ + { + 'name': 'the', + 'description': '

key you want to access

\n', + 'type': 'Number|String' + } + ], + 'class': 'p5.TypedDict', + 'module': 'Data' + }, + 'set': { + 'name': 'set', + 'params': [ + { + 'name': 'key', + 'description': '', + 'type': 'Number|String' + }, + { + 'name': 'value', + 'description': '', + 'type': 'Number|String' + } + ], + 'class': 'p5.TypedDict', + 'module': 'Data' + }, + 'create': { + 'name': 'create', + 'class': 'p5.TypedDict', + 'module': 'Data', + 'overloads': [ + { + 'params': [ + { + 'name': 'key', + 'description': '', + 'type': 'Number|String' + }, + { + 'name': 'value', + 'description': '', + 'type': 'Number|String' + } + ] + }, + { + 'params': [ + { + 'name': 'obj', + 'description': '

key/value pair

\n', + 'type': 'Object' + } + ] + } + ] + }, + 'clear': { + 'name': 'clear', + 'class': 'p5.TypedDict', + 'module': 'Data' + }, + 'remove': { + 'name': 'remove', + 'params': [ + { + 'name': 'key', + 'description': '

for the pair to remove

\n', + 'type': 'Number|String' + } + ], + 'class': 'p5.TypedDict', + 'module': 'Data' + }, + 'print': { + 'name': 'print', + 'class': 'p5.TypedDict', + 'module': 'Data' + }, + 'saveTable': { + 'name': 'saveTable', + 'class': 'p5.TypedDict', + 'module': 'Data' + }, + 'saveJSON': { + 'name': 'saveJSON', + 'class': 'p5.TypedDict', + 'module': 'Data' + } + }, + 'p5.NumberDict': { + 'add': { + 'name': 'add', + 'params': [ + { + 'name': 'Key', + 'description': '

for the value you wish to add to

\n', + 'type': 'Number' + }, + { + 'name': 'Number', + 'description': '

to add to the value

\n', + 'type': 'Number' + } + ], + 'class': 'p5.NumberDict', + 'module': 'Data' + }, + 'sub': { + 'name': 'sub', + 'params': [ + { + 'name': 'Key', + 'description': '

for the value you wish to subtract from

\n', + 'type': 'Number' + }, + { + 'name': 'Number', + 'description': '

to subtract from the value

\n', + 'type': 'Number' + } + ], + 'class': 'p5.NumberDict', + 'module': 'Data' + }, + 'mult': { + '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' + } + ], + 'class': 'p5.NumberDict', + 'module': 'Data' + }, + 'div': { + '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' + } + ], + 'class': 'p5.NumberDict', + 'module': 'Data' + }, + 'minValue': { + 'name': 'minValue', + 'class': 'p5.NumberDict', + 'module': 'Data' + }, + 'maxValue': { + 'name': 'maxValue', + 'class': 'p5.NumberDict', + 'module': 'Data' + }, + 'minKey': { + 'name': 'minKey', + 'class': 'p5.NumberDict', + 'module': 'Data' + }, + 'maxKey': { + 'name': 'maxKey', + 'class': 'p5.NumberDict', + 'module': 'Data' + } + }, + 'p5.MediaElement': { + 'src': { + 'name': 'src', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'play': { + 'name': 'play', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'stop': { + 'name': 'stop', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'pause': { + 'name': 'pause', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'loop': { + 'name': 'loop', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'noLoop': { + 'name': 'noLoop', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'autoplay': { + 'name': 'autoplay', + 'params': [ + { + 'name': 'shouldAutoplay', + 'description': '

whether the element should autoplay.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'volume': { + 'name': 'volume', + 'class': 'p5.MediaElement', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'val', + 'description': '

volume between 0.0 and 1.0.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + } + ] + }, + 'speed': { + 'name': 'speed', + 'class': 'p5.MediaElement', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'speed', + 'description': '

speed multiplier for playback.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + } + ] + }, + 'time': { + 'name': 'time', + 'class': 'p5.MediaElement', + 'module': 'DOM', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'time', + 'description': '

time to jump to (in seconds).

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + } + ] + }, + 'duration': { + 'name': 'duration', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'onended': { + 'name': 'onended', + 'params': [ + { + 'name': 'callback', + 'description': '

function to call when playback ends.\n The p5.MediaElement is passed as\n the argument.

\n', + 'type': 'Function' + } + ], + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'connect': { + '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': 'DOM' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'showControls': { + 'name': 'showControls', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'hideControls': { + 'name': 'hideControls', + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'addCue': { + 'name': 'addCue', + 'params': [ + { + 'name': 'time', + 'description': '

cue time to run the callback function.

\n', + 'type': 'Number' + }, + { + 'name': 'callback', + 'description': '

function to call at the cue time.

\n', + 'type': 'Function' + }, + { + 'name': 'value', + 'description': '

object to pass as the argument to\n callback.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'removeCue': { + 'name': 'removeCue', + 'params': [ + { + 'name': 'id', + 'description': '

ID of the cue, created by media.addCue().

\n', + 'type': 'Number' + } + ], + 'class': 'p5.MediaElement', + 'module': 'DOM' + }, + 'clearCues': { + 'name': 'clearCues', + 'class': 'p5.MediaElement', + 'module': 'DOM' + } + }, + 'p5.File': { + 'file': { + 'name': 'file', + 'class': 'p5.File', + 'module': 'DOM' + }, + 'type': { + 'name': 'type', + 'class': 'p5.File', + 'module': 'DOM' + }, + 'subtype': { + 'name': 'subtype', + 'class': 'p5.File', + 'module': 'DOM' + }, + 'name': { + 'name': 'name', + 'class': 'p5.File', + 'module': 'DOM' + }, + 'size': { + 'name': 'size', + 'class': 'p5.File', + 'module': 'DOM' + }, + 'data': { + 'name': 'data', + 'class': 'p5.File', + 'module': 'DOM' + } + }, + 'p5.Image': { + 'width': { + 'name': 'width', + 'class': 'p5.Image', + 'module': 'Image' + }, + 'height': { + 'name': 'height', + 'class': 'p5.Image', + 'module': 'Image' + }, + 'pixels': { + 'name': 'pixels', + 'class': 'p5.Image', + 'module': 'Image' + }, + 'pixelDensity': { + 'name': 'pixelDensity', + 'params': [ + { + 'name': 'density', + 'description': '

A scaling factor for the number of pixels per\nside

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Image', + 'module': 'Image' + }, + 'loadPixels': { + 'name': 'loadPixels', + 'class': 'p5.Image', + 'module': 'Image' + }, + 'updatePixels': { + 'name': 'updatePixels', + 'class': 'p5.Image', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the upper-left corner\n of the subsection to update.

\n', + 'type': 'Integer' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the upper-left corner\n of the subsection to update.

\n', + 'type': 'Integer' + }, + { + 'name': 'w', + 'description': '

width of the subsection to update.

\n', + 'type': 'Integer' + }, + { + 'name': 'h', + 'description': '

height of the subsection to update.

\n', + 'type': 'Integer' + } + ] + }, + { + 'params': [ + ] + } + ] + }, + 'get': { + 'name': 'get', + 'class': 'p5.Image', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the pixel.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the pixel.

\n', + 'type': 'Number' + }, + { + 'name': 'w', + 'description': '

width of the subsection to be returned.

\n', + 'type': 'Number' + }, + { + 'name': 'h', + 'description': '

height of the subsection to be returned.

\n', + 'type': 'Number' + } + ] + }, + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + } + ] + } + ] + }, + 'set': { + '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 p5.Color object |\n p5.Image to copy.

\n', + 'type': 'Number|Number[]|Object' + } + ], + 'class': 'p5.Image', + 'module': 'Image' + }, + 'resize': { + 'name': 'resize', + 'params': [ + { + 'name': 'width', + 'description': '

resized image width.

\n', + 'type': 'Number' + }, + { + 'name': 'height', + 'description': '

resized image height.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Image', + 'module': 'Image' + }, + 'copy': { + 'name': 'copy', + 'class': 'p5.Image', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'srcImage', + 'description': '

source image.

\n', + 'type': 'p5.Image|p5.Element' + }, + { + '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' + } + ] + }, + { + 'params': [ + { + 'name': 'sx', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sy', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sw', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sh', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dx', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dy', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dw', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dh', + 'description': '', + 'type': 'Integer' + } + ] + } + ] + }, + 'mask': { + 'name': 'mask', + 'params': [ + { + 'name': 'srcImage', + 'description': '

source image.

\n', + 'type': 'p5.Image' + } + ], + 'class': 'p5.Image', + 'module': 'Image' + }, + 'filter': { + 'name': 'filter', + 'params': [ + { + 'name': 'filterType', + 'description': '

either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, ERODE, DILATE or BLUR.

\n', + 'type': 'Constant' + }, + { + 'name': 'filterParam', + 'description': '

parameter unique to each filter.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Image', + 'module': 'Image' + }, + 'blend': { + 'name': 'blend', + 'class': 'p5.Image', + 'module': 'Image', + 'overloads': [ + { + 'params': [ + { + 'name': 'srcImage', + 'description': '

source image

\n', + 'type': 'p5.Image' + }, + { + '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. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.

\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': 'Constant' + } + ] + }, + { + 'params': [ + { + 'name': 'sx', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sy', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sw', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'sh', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dx', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dy', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dw', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'dh', + 'description': '', + 'type': 'Integer' + }, + { + 'name': 'blendMode', + 'description': '', + 'type': 'Constant' + } + ] + } + ] + }, + 'save': { + 'name': 'save', + 'params': [ + { + 'name': 'filename', + 'description': '

filename. Defaults to \'untitled\'.

\n', + 'type': 'String' + }, + { + 'name': 'extension', + 'description': '

file extension, either \'png\' or \'jpg\'.\n Defaults to \'png\'.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5.Image', + 'module': 'Image' + }, + 'reset': { + 'name': 'reset', + 'class': 'p5.Image', + 'module': 'Image' + }, + 'getCurrentFrame': { + 'name': 'getCurrentFrame', + 'class': 'p5.Image', + 'module': 'Image' + }, + 'setFrame': { + 'name': 'setFrame', + 'params': [ + { + 'name': 'index', + 'description': '

index of the frame to display.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Image', + 'module': 'Image' + }, + 'numFrames': { + 'name': 'numFrames', + 'class': 'p5.Image', + 'module': 'Image' + }, + 'play': { + 'name': 'play', + 'class': 'p5.Image', + 'module': 'Image' + }, + 'pause': { + 'name': 'pause', + 'class': 'p5.Image', + 'module': 'Image' + }, + 'delay': { + 'name': 'delay', + 'params': [ + { + 'name': 'd', + 'description': '

delay in milliseconds between switching frames.

\n', + 'type': 'Number' + }, + { + 'name': 'index', + 'description': '

index of the frame that will have its delay modified.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Image', + 'module': 'Image' + } + }, + 'p5.PrintWriter': { + 'write': { + 'name': 'write', + 'params': [ + { + 'name': 'data', + 'description': '

data to be written as a string, number,\n or array of strings and numbers.

\n', + 'type': 'String|Number|Array' + } + ], + 'class': 'p5.PrintWriter', + 'module': 'IO' + }, + 'print': { + 'name': 'print', + 'params': [ + { + 'name': 'data', + 'description': '

data to be written as a string, number,\n or array of strings and numbers.

\n', + 'type': 'String|Number|Array' + } + ], + 'class': 'p5.PrintWriter', + 'module': 'IO' + }, + 'clear': { + 'name': 'clear', + 'class': 'p5.PrintWriter', + 'module': 'IO' + }, + 'close': { + 'name': 'close', + 'class': 'p5.PrintWriter', + 'module': 'IO' + } + }, + 'p5.Table': { + 'columns': { + 'name': 'columns', + 'class': 'p5.Table', + 'module': 'IO' + }, + 'rows': { + 'name': 'rows', + 'class': 'p5.Table', + 'module': 'IO' + }, + 'addRow': { + 'name': 'addRow', + 'params': [ + { + 'name': 'row', + 'description': '

row to be added to the table

\n', + 'type': 'p5.TableRow', + 'optional': true + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'removeRow': { + 'name': 'removeRow', + 'params': [ + { + 'name': 'id', + 'description': '

ID number of the row to remove

\n', + 'type': 'Integer' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'getRow': { + 'name': 'getRow', + 'params': [ + { + 'name': 'rowID', + 'description': '

ID number of the row to get

\n', + 'type': 'Integer' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'getRows': { + 'name': 'getRows', + 'class': 'p5.Table', + 'module': 'IO' + }, + 'findRow': { + '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': 'Integer|String' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'findRows': { + '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': 'Integer|String' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'matchRow': { + 'name': 'matchRow', + 'params': [ + { + 'name': 'regexp', + 'description': '

The regular expression to match

\n', + 'type': 'String|RegExp' + }, + { + 'name': 'column', + 'description': '

The column ID (number) or\n title (string)

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'matchRows': { + '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|Integer', + 'optional': true + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'getColumn': { + 'name': 'getColumn', + 'params': [ + { + 'name': 'column', + 'description': '

String or Number of the column to return

\n', + 'type': 'String|Number' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'clearRows': { + 'name': 'clearRows', + 'class': 'p5.Table', + 'module': 'IO' + }, + 'addColumn': { + 'name': 'addColumn', + 'params': [ + { + 'name': 'title', + 'description': '

title of the given column

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'getColumnCount': { + 'name': 'getColumnCount', + 'class': 'p5.Table', + 'module': 'IO' + }, + 'getRowCount': { + 'name': 'getRowCount', + 'class': 'p5.Table', + 'module': 'IO' + }, + 'removeTokens': { + '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|Integer', + 'optional': true + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'trim': { + 'name': 'trim', + 'params': [ + { + 'name': 'column', + 'description': '

Column ID (number)\n or name (string)

\n', + 'type': 'String|Integer', + 'optional': true + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'removeColumn': { + 'name': 'removeColumn', + 'params': [ + { + 'name': 'column', + 'description': '

columnName (string) or ID (number)

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'set': { + 'name': 'set', + 'params': [ + { + 'name': 'row', + 'description': '

row ID

\n', + 'type': 'Integer' + }, + { + 'name': 'column', + 'description': '

column ID (Number)\n or title (String)

\n', + 'type': 'String|Integer' + }, + { + 'name': 'value', + 'description': '

value to assign

\n', + 'type': 'String|Number' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'setNum': { + 'name': 'setNum', + 'params': [ + { + 'name': 'row', + 'description': '

row ID

\n', + 'type': 'Integer' + }, + { + 'name': 'column', + 'description': '

column ID (Number)\n or title (String)

\n', + 'type': 'String|Integer' + }, + { + 'name': 'value', + 'description': '

value to assign

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'setString': { + 'name': 'setString', + 'params': [ + { + 'name': 'row', + 'description': '

row ID

\n', + 'type': 'Integer' + }, + { + 'name': 'column', + 'description': '

column ID (Number)\n or title (String)

\n', + 'type': 'String|Integer' + }, + { + 'name': 'value', + 'description': '

value to assign

\n', + 'type': 'String' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'get': { + 'name': 'get', + 'params': [ + { + 'name': 'row', + 'description': '

row ID

\n', + 'type': 'Integer' + }, + { + 'name': 'column', + 'description': '

columnName (string) or\n ID (number)

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'getNum': { + 'name': 'getNum', + 'params': [ + { + 'name': 'row', + 'description': '

row ID

\n', + 'type': 'Integer' + }, + { + 'name': 'column', + 'description': '

columnName (string) or\n ID (number)

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'getString': { + 'name': 'getString', + 'params': [ + { + 'name': 'row', + 'description': '

row ID

\n', + 'type': 'Integer' + }, + { + 'name': 'column', + 'description': '

columnName (string) or\n ID (number)

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'getObject': { + 'name': 'getObject', + 'params': [ + { + 'name': 'headerColumn', + 'description': '

Name of the column which should be used to\n title each row object (optional)

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5.Table', + 'module': 'IO' + }, + 'getArray': { + 'name': 'getArray', + 'class': 'p5.Table', + 'module': 'IO' + } + }, + 'p5.TableRow': { + 'set': { + 'name': 'set', + 'params': [ + { + 'name': 'column', + 'description': '

Column ID (Number)\n or Title (String)

\n', + 'type': 'String|Integer' + }, + { + 'name': 'value', + 'description': '

The value to be stored

\n', + 'type': 'String|Number' + } + ], + 'class': 'p5.TableRow', + 'module': 'IO' + }, + 'setNum': { + 'name': 'setNum', + 'params': [ + { + 'name': 'column', + 'description': '

Column ID (Number)\n or Title (String)

\n', + 'type': 'String|Integer' + }, + { + 'name': 'value', + 'description': '

The value to be stored\n as a Float

\n', + 'type': 'Number|String' + } + ], + 'class': 'p5.TableRow', + 'module': 'IO' + }, + 'setString': { + 'name': 'setString', + 'params': [ + { + 'name': 'column', + 'description': '

Column ID (Number)\n or Title (String)

\n', + 'type': 'String|Integer' + }, + { + 'name': 'value', + 'description': '

The value to be stored\n as a String

\n', + 'type': 'String|Number|Boolean|Object' + } + ], + 'class': 'p5.TableRow', + 'module': 'IO' + }, + 'get': { + 'name': 'get', + 'params': [ + { + 'name': 'column', + 'description': '

columnName (string) or\n ID (number)

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.TableRow', + 'module': 'IO' + }, + 'getNum': { + 'name': 'getNum', + 'params': [ + { + 'name': 'column', + 'description': '

columnName (string) or\n ID (number)

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.TableRow', + 'module': 'IO' + }, + 'getString': { + 'name': 'getString', + 'params': [ + { + 'name': 'column', + 'description': '

columnName (string) or\n ID (number)

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.TableRow', + 'module': 'IO' + } + }, + 'p5.XML': { + 'getParent': { + 'name': 'getParent', + 'class': 'p5.XML', + 'module': 'IO' + }, + 'getName': { + 'name': 'getName', + 'class': 'p5.XML', + 'module': 'IO' + }, + 'setName': { + 'name': 'setName', + 'params': [ + { + 'name': 'name', + 'description': '

new tag name of the element.

\n', + 'type': 'String' + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'hasChildren': { + 'name': 'hasChildren', + 'class': 'p5.XML', + 'module': 'IO' + }, + 'listChildren': { + 'name': 'listChildren', + 'class': 'p5.XML', + 'module': 'IO' + }, + 'getChildren': { + 'name': 'getChildren', + 'params': [ + { + 'name': 'name', + 'description': '

name of the elements to return.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'getChild': { + 'name': 'getChild', + 'params': [ + { + 'name': 'name', + 'description': '

element name or index.

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'addChild': { + 'name': 'addChild', + 'params': [ + { + 'name': 'child', + 'description': '

child element to add.

\n', + 'type': 'p5.XML' + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'removeChild': { + 'name': 'removeChild', + 'params': [ + { + 'name': 'name', + 'description': '

name or index of the child element to remove.

\n', + 'type': 'String|Integer' + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'getAttributeCount': { + 'name': 'getAttributeCount', + 'class': 'p5.XML', + 'module': 'IO' + }, + 'listAttributes': { + 'name': 'listAttributes', + 'class': 'p5.XML', + 'module': 'IO' + }, + 'hasAttribute': { + 'name': 'hasAttribute', + 'params': [ + { + 'name': 'name', + 'description': '

name of the attribute to be checked.

\n', + 'type': 'String' + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'getNum': { + 'name': 'getNum', + 'params': [ + { + 'name': 'name', + 'description': '

name of the attribute to be checked.

\n', + 'type': 'String' + }, + { + 'name': 'defaultValue', + 'description': '

value to return if the attribute doesn\'t exist.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'getString': { + 'name': 'getString', + 'params': [ + { + 'name': 'name', + 'description': '

name of the attribute to be checked.

\n', + 'type': 'String' + }, + { + 'name': 'defaultValue', + 'description': '

value to return if the attribute doesn\'t exist.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'setAttribute': { + 'name': 'setAttribute', + 'params': [ + { + 'name': 'name', + 'description': '

name of the attribute to be set.

\n', + 'type': 'String' + }, + { + 'name': 'value', + 'description': '

attribute\'s new value.

\n', + 'type': 'Number|String|Boolean' + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'getContent': { + 'name': 'getContent', + 'params': [ + { + 'name': 'defaultValue', + 'description': '

value to return if the element has no\n content.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'setContent': { + 'name': 'setContent', + 'params': [ + { + 'name': 'content', + 'description': '

new content for the element.

\n', + 'type': 'String' + } + ], + 'class': 'p5.XML', + 'module': 'IO' + }, + 'serialize': { + 'name': 'serialize', + 'class': 'p5.XML', + 'module': 'IO' + } + }, + 'p5.Vector': { + 'x': { + 'name': 'x', + 'class': 'p5.Vector', + 'module': 'Math' + }, + 'y': { + 'name': 'y', + 'class': 'p5.Vector', + 'module': 'Math' + }, + 'z': { + 'name': 'z', + 'class': 'p5.Vector', + 'module': 'Math' + }, + 'toString': { + 'name': 'toString', + 'class': 'p5.Vector', + 'module': 'Math' + }, + 'set': { + 'name': 'set', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x component of the vector.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'y', + 'description': '

y component of the vector.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'z', + 'description': '

z component of the vector.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

vector to set.

\n', + 'type': 'p5.Vector|Number[]' + } + ], + 'chainable': 1 + } + ] + }, + 'copy': { + 'name': 'copy', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

the p5.Vector to create a copy of

\n', + 'type': 'p5.Vector' + } + ], + 'static': 1 + } + ] + }, + 'add': { + 'name': 'add', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x component of the vector to be added.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y component of the vector to be added.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'z', + 'description': '

z component of the vector to be added.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

The vector to add

\n', + 'type': 'p5.Vector|Number[]' + } + ], + 'chainable': 1 + }, + { + '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': '

vector to receive the result.

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'rem': { + 'name': 'rem', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x component of divisor vector.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y component of divisor vector.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z component of divisor vector.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

divisor vector.

\n', + 'type': 'p5.Vector | Number[]' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '

The dividend p5.Vector

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'v2', + 'description': '

The divisor p5.Vector

\n', + 'type': 'p5.Vector' + } + ], + 'static': 1 + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'v2', + 'description': '', + 'type': 'p5.Vector' + } + ], + 'static': 1 + } + ] + }, + 'sub': { + 'name': 'sub', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x component of the vector to subtract.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y component of the vector to subtract.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'z', + 'description': '

z component of the vector to subtract.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

the vector to subtract

\n', + 'type': 'p5.Vector|Number[]' + } + ], + 'chainable': 1 + }, + { + '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': '

vector to receive the result.

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'mult': { + 'name': 'mult', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'n', + 'description': '

The number to multiply with the vector

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '

number to multiply with the x component of the vector.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

number to multiply with the y component of the vector.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

number to multiply with the z component of the vector.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'arr', + 'description': '

array to multiply with the components of the vector.

\n', + 'type': 'Number[]' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

vector to multiply with the components of the original vector.

\n', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'static': 1 + }, + { + 'params': [ + { + 'name': 'v', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'n', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'target', + 'description': '

vector to receive the result.

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + }, + { + 'params': [ + { + 'name': 'v0', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'v1', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'target', + 'description': '', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + }, + { + 'params': [ + { + 'name': 'v0', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'arr', + 'description': '', + 'type': 'Number[]' + }, + { + 'name': 'target', + 'description': '', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'div': { + 'name': 'div', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'n', + 'description': '

The number to divide the vector by

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '

number to divide with the x component of the vector.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

number to divide with the y component of the vector.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

number to divide with the z component of the vector.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'arr', + 'description': '

array to divide the components of the vector by.

\n', + 'type': 'Number[]' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

vector to divide the components of the original vector by.

\n', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'static': 1 + }, + { + 'params': [ + { + 'name': 'v', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'n', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'target', + 'description': '

The vector to receive the result

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + }, + { + 'params': [ + { + 'name': 'v0', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'v1', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'target', + 'description': '', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + }, + { + 'params': [ + { + 'name': 'v0', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'arr', + 'description': '', + 'type': 'Number[]' + }, + { + 'name': 'target', + 'description': '', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'mag': { + 'name': 'mag', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'vecT', + 'description': '

The vector to return the magnitude of

\n', + 'type': 'p5.Vector' + } + ], + 'static': 1 + } + ] + }, + 'magSq': { + 'name': 'magSq', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'vecT', + 'description': '

the vector to return the squared magnitude of

\n', + 'type': 'p5.Vector' + } + ], + 'static': 1 + } + ] + }, + 'dot': { + 'name': 'dot', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x component of the vector.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y component of the vector.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'z', + 'description': '

z component of the vector.

\n', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

p5.Vector to be dotted.

\n', + 'type': 'p5.Vector' + } + ] + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '

first p5.Vector.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'v2', + 'description': '

second p5.Vector.

\n', + 'type': 'p5.Vector' + } + ], + 'static': 1 + } + ] + }, + 'cross': { + 'name': 'cross', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'v', + 'description': '

p5.Vector to be crossed.

\n', + 'type': 'p5.Vector' + } + ] + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '

first p5.Vector.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'v2', + 'description': '

second p5.Vector.

\n', + 'type': 'p5.Vector' + } + ], + 'static': 1 + } + ] + }, + 'dist': { + 'name': 'dist', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'v', + 'description': '

x, y, and z coordinates of a p5.Vector.

\n', + 'type': 'p5.Vector' + } + ] + }, + { + '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 + } + ] + }, + 'normalize': { + 'name': 'normalize', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

The vector to normalize

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'target', + 'description': '

The vector to receive the result

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'limit': { + 'name': 'limit', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'max', + 'description': '

maximum magnitude for the vector.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

the vector to limit

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'max', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'target', + 'description': '

the vector to receive the result (Optional)

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'setMag': { + 'name': 'setMag', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'len', + 'description': '

new length for this vector.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

the vector to set the magnitude of

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'len', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'target', + 'description': '

the vector to receive the result (Optional)

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'heading': { + 'name': 'heading', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

the vector to find the angle of

\n', + 'type': 'p5.Vector' + } + ], + 'static': 1 + } + ] + }, + 'setHeading': { + 'name': 'setHeading', + 'params': [ + { + 'name': 'angle', + 'description': '

angle of rotation.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Vector', + 'module': 'Math' + }, + 'rotate': { + 'name': 'rotate', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'angle', + 'description': '

angle of rotation.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'angle', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'target', + 'description': '

The vector to receive the result

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'angleBetween': { + 'name': 'angleBetween', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'value', + 'description': '

x, y, and z components of a p5.Vector.

\n', + 'type': 'p5.Vector' + } + ] + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '

the first vector.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'v2', + 'description': '

the second vector.

\n', + 'type': 'p5.Vector' + } + ], + 'static': 1 + } + ] + }, + 'lerp': { + 'name': 'lerp', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x component.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y component.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z component.

\n', + 'type': 'Number' + }, + { + 'name': 'amt', + 'description': '

amount of interpolation between 0.0 (old vector)\n and 1.0 (new vector). 0.5 is halfway between.

\n', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

p5.Vector to lerp toward.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'amt', + 'description': '', + 'type': 'Number' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'v2', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'amt', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'target', + 'description': '

The vector to receive the result

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'slerp': { + 'name': 'slerp', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'v', + 'description': '

p5.Vector to slerp toward.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'amt', + 'description': '

amount of interpolation between 0.0 (old vector)\n and 1.0 (new vector). 0.5 is halfway between.

\n', + 'type': 'Number' + } + ] + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '

old vector.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'v2', + 'description': '

new vector.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'amt', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'target', + 'description': '

vector to receive the result.

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'reflect': { + 'name': 'reflect', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'surfaceNormal', + 'description': '

p5.Vector\n to reflect about.

\n', + 'type': 'p5.Vector' + } + ], + 'chainable': 1 + }, + { + 'params': [ + { + 'name': 'incidentVector', + 'description': '

vector to be reflected.

\n', + 'type': 'p5.Vector' + }, + { + 'name': 'surfaceNormal', + 'description': '', + 'type': 'p5.Vector' + }, + { + 'name': 'target', + 'description': '

vector to receive the result.

\n', + 'type': 'p5.Vector', + 'optional': true + } + ], + 'static': 1 + } + ] + }, + 'array': { + 'name': 'array', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'v', + 'description': '

the vector to convert to an array

\n', + 'type': 'p5.Vector' + } + ], + 'static': 1 + } + ] + }, + 'equals': { + 'name': 'equals', + 'class': 'p5.Vector', + 'module': 'Math', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x component of the vector.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'y', + 'description': '

y component of the vector.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'z', + 'description': '

z component of the vector.

\n', + 'type': 'Number', + 'optional': true + } + ] + }, + { + 'params': [ + { + 'name': 'value', + 'description': '

vector to compare.

\n', + 'type': 'p5.Vector|Array' + } + ] + }, + { + 'params': [ + { + 'name': 'v1', + 'description': '

the first vector to compare

\n', + 'type': 'p5.Vector|Array' + }, + { + 'name': 'v2', + 'description': '

the second vector to compare

\n', + 'type': 'p5.Vector|Array' + } + ], + 'static': 1 + } + ] + }, + 'fromAngle': { + 'name': 'fromAngle', + 'params': [ + { + 'name': 'angle', + 'description': '

desired angle, in radians. Unaffected by angleMode().

\n', + 'type': 'Number' + }, + { + 'name': 'length', + 'description': '

length of the new vector (defaults to 1).

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Vector', + 'module': 'Math' + }, + 'fromAngles': { + 'name': 'fromAngles', + 'params': [ + { + 'name': 'theta', + 'description': '

polar angle in radians (zero is up).

\n', + 'type': 'Number' + }, + { + 'name': 'phi', + 'description': '

azimuthal angle in radians\n (zero is out of the screen).

\n', + 'type': 'Number' + }, + { + 'name': 'length', + 'description': '

length of the new vector (defaults to 1).

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Vector', + 'module': 'Math' + }, + 'random2D': { + 'name': 'random2D', + 'class': 'p5.Vector', + 'module': 'Math' + }, + 'random3D': { + 'name': 'random3D', + 'class': 'p5.Vector', + 'module': 'Math' + } + }, + 'p5.Font': { + 'font': { + 'name': 'font', + 'class': 'p5.Font', + 'module': 'Typography' + }, + 'textBounds': { + 'name': 'textBounds', + 'params': [ + { + 'name': 'str', + 'description': '

string of text.

\n', + 'type': 'String' + }, + { + 'name': 'x', + 'description': '

x-coordinate of the text.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the text.

\n', + 'type': 'Number' + }, + { + 'name': 'fontSize', + 'description': '

font size. Defaults to the current\n textSize().

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Font', + 'module': 'Typography' + }, + 'textToPoints': { + 'name': 'textToPoints', + 'params': [ + { + 'name': 'str', + 'description': '

string of text.

\n', + 'type': 'String' + }, + { + 'name': 'x', + 'description': '

x-coordinate of the text.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the text.

\n', + 'type': 'Number' + }, + { + 'name': 'fontSize', + 'description': '

font size. Defaults to the current\n textSize().

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'options', + 'description': '

object with sampleFactor and simplifyThreshold\n properties.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5.Font', + 'module': 'Typography' + } + }, + 'p5.Camera': { + 'eyeX': { + 'name': 'eyeX', + 'class': 'p5.Camera', + 'module': '3D' + }, + 'eyeY': { + 'name': 'eyeY', + 'class': 'p5.Camera', + 'module': '3D' + }, + 'eyeZ': { + 'name': 'eyeZ', + 'class': 'p5.Camera', + 'module': '3D' + }, + 'centerX': { + 'name': 'centerX', + 'class': 'p5.Camera', + 'module': '3D' + }, + 'centerY': { + 'name': 'centerY', + 'class': 'p5.Camera', + 'module': '3D' + }, + 'centerZ': { + 'name': 'centerZ', + 'class': 'p5.Camera', + 'module': '3D' + }, + 'upX': { + 'name': 'upX', + 'class': 'p5.Camera', + 'module': '3D' + }, + 'upY': { + 'name': 'upY', + 'class': 'p5.Camera', + 'module': '3D' + }, + 'upZ': { + 'name': 'upZ', + 'class': 'p5.Camera', + 'module': '3D' + }, + 'perspective': { + 'name': 'perspective', + 'params': [ + { + 'name': 'fovy', + 'description': '

camera frustum vertical field of view. Defaults to\n 2 * atan(height / 2 / 800).

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'aspect', + 'description': '

camera frustum aspect ratio. Defaults to\n width / height.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'near', + 'description': '

distance from the camera to the near clipping plane.\n Defaults to 0.1 * 800.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'far', + 'description': '

distance from the camera to the far clipping plane.\n Defaults to 10 * 800.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'ortho': { + 'name': 'ortho', + 'params': [ + { + 'name': 'left', + 'description': '

x-coordinate of the frustum’s left plane. Defaults to -width / 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'right', + 'description': '

x-coordinate of the frustum’s right plane. Defaults to width / 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'bottom', + 'description': '

y-coordinate of the frustum’s bottom plane. Defaults to height / 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'top', + 'description': '

y-coordinate of the frustum’s top plane. Defaults to -height / 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'near', + 'description': '

z-coordinate of the frustum’s near plane. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'far', + 'description': '

z-coordinate of the frustum’s far plane. Defaults to max(width, height) + 800.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'frustum': { + 'name': 'frustum', + 'params': [ + { + 'name': 'left', + 'description': '

x-coordinate of the frustum’s left plane. Defaults to -width / 20.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'right', + 'description': '

x-coordinate of the frustum’s right plane. Defaults to width / 20.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'bottom', + 'description': '

y-coordinate of the frustum’s bottom plane. Defaults to height / 20.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'top', + 'description': '

y-coordinate of the frustum’s top plane. Defaults to -height / 20.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'near', + 'description': '

z-coordinate of the frustum’s near plane. Defaults to 0.1 * 800.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'far', + 'description': '

z-coordinate of the frustum’s far plane. Defaults to 10 * 800.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'pan': { + 'name': 'pan', + 'params': [ + { + 'name': 'angle', + 'description': '

amount to rotate in the current\n angleMode().

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'tilt': { + 'name': 'tilt', + 'params': [ + { + 'name': 'angle', + 'description': '

amount to rotate in the current\n angleMode().

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'lookAt': { + 'name': 'lookAt', + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the position where the camera should look in "world" space.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the position where the camera should look in "world" space.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z-coordinate of the position where the camera should look in "world" space.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'camera': { + 'name': 'camera', + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the camera. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'y', + 'description': '

y-coordinate of the camera. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'z', + 'description': '

z-coordinate of the camera. Defaults to 800.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'centerX', + 'description': '

x-coordinate of the point the camera faces. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'centerY', + 'description': '

y-coordinate of the point the camera faces. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'centerZ', + 'description': '

z-coordinate of the point the camera faces. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'upX', + 'description': '

x-component of the camera’s "up" vector. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'upY', + 'description': '

x-component of the camera’s "up" vector. Defaults to 1.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'upZ', + 'description': '

z-component of the camera’s "up" vector. Defaults to 0.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'move': { + 'name': 'move', + 'params': [ + { + 'name': 'x', + 'description': '

distance to move along the camera’s "local" x-axis.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

distance to move along the camera’s "local" y-axis.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

distance to move along the camera’s "local" z-axis.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'setPosition': { + 'name': 'setPosition', + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate in "world" space.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate in "world" space.

\n', + 'type': 'Number' + }, + { + 'name': 'z', + 'description': '

z-coordinate in "world" space.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'set': { + 'name': 'set', + 'params': [ + { + 'name': 'cam', + 'description': '

camera to copy.

\n', + 'type': 'p5.Camera' + } + ], + 'class': 'p5.Camera', + 'module': '3D' + }, + 'slerp': { + 'name': 'slerp', + 'params': [ + { + 'name': 'cam0', + 'description': '

first camera.

\n', + 'type': 'p5.Camera' + }, + { + 'name': 'cam1', + 'description': '

second camera.

\n', + 'type': 'p5.Camera' + }, + { + 'name': 'amt', + 'description': '

amount of interpolation between 0.0 (cam0) and 1.0 (cam1).

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Camera', + 'module': '3D' + } + }, + 'p5.Framebuffer': { + 'pixels': { + 'name': 'pixels', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'resize': { + 'name': 'resize', + 'params': [ + { + 'name': 'width', + 'description': '

width of the framebuffer.

\n', + 'type': 'Number' + }, + { + 'name': 'height', + 'description': '

height of the framebuffer.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'pixelDensity': { + 'name': 'pixelDensity', + 'params': [ + { + 'name': 'density', + 'description': '

pixel density to set.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'autoSized': { + 'name': 'autoSized', + 'params': [ + { + 'name': 'autoSized', + 'description': '

whether to automatically resize the framebuffer to match the canvas.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'createCamera': { + 'name': 'createCamera', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'remove': { + 'name': 'remove', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'begin': { + 'name': 'begin', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'end': { + 'name': 'end', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'draw': { + 'name': 'draw', + 'params': [ + { + 'name': 'callback', + 'description': '

function that draws to the framebuffer.

\n', + 'type': 'Function' + } + ], + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'loadPixels': { + 'name': 'loadPixels', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'get': { + 'name': 'get', + 'class': 'p5.Framebuffer', + 'module': 'Rendering', + 'overloads': [ + { + 'params': [ + { + 'name': 'x', + 'description': '

x-coordinate of the pixel. Defaults to 0.

\n', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '

y-coordinate of the pixel. Defaults to 0.

\n', + 'type': 'Number' + }, + { + 'name': 'w', + 'description': '

width of the subsection to be returned.

\n', + 'type': 'Number' + }, + { + 'name': 'h', + 'description': '

height of the subsection to be returned.

\n', + 'type': 'Number' + } + ] + }, + { + 'params': [ + ] + }, + { + 'params': [ + { + 'name': 'x', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'y', + 'description': '', + 'type': 'Number' + } + ] + } + ] + }, + 'updatePixels': { + 'name': 'updatePixels', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'color': { + 'name': 'color', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + }, + 'depth': { + 'name': 'depth', + 'class': 'p5.Framebuffer', + 'module': 'Rendering' + } + }, + 'p5.Geometry': { + 'vertices': { + 'name': 'vertices', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'vertexNormals': { + 'name': 'vertexNormals', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'faces': { + 'name': 'faces', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'uvs': { + 'name': 'uvs', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'calculateBoundingBox': { + 'name': 'calculateBoundingBox', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'clearColors': { + 'name': 'clearColors', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'flipU': { + 'name': 'flipU', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'flipV': { + 'name': 'flipV', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'computeFaces': { + 'name': 'computeFaces', + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'computeNormals': { + 'name': 'computeNormals', + 'params': [ + { + 'name': 'shadingType', + 'description': '

shading type. either FLAT or SMOOTH. Defaults to FLAT.

\n', + 'type': 'String', + 'optional': true + }, + { + 'name': 'options', + 'description': '

shading options.

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5.Geometry', + 'module': 'Shape' + }, + 'normalize': { + 'name': 'normalize', + 'class': 'p5.Geometry', + 'module': 'Shape' + } + }, + 'p5.Shader': { + 'copyToContext': { + 'name': 'copyToContext', + 'params': [ + { + 'name': 'context', + 'description': '

WebGL context for the copied shader.

\n', + 'type': 'p5|p5.Graphics' + } + ], + 'class': 'p5.Shader', + 'module': '3D' + }, + 'setUniform': { + 'name': 'setUniform', + 'params': [ + { + 'name': 'uniformName', + 'description': '

name of the uniform. Must match the name\n used in the vertex and fragment shaders.

\n', + 'type': 'String' + }, + { + 'name': 'data', + 'description': '

value to assign to the uniform. Must match the uniform’s data type.

\n', + 'type': 'Boolean|Number|Number[]|p5.Image|p5.Graphics|p5.MediaElement|p5.Texture' + } + ], + 'class': 'p5.Shader', + 'module': '3D' + } + }, + 'p5.SoundFile': { + 'isLoaded': { + 'name': 'isLoaded', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'play': { + 'name': 'play', + 'params': [ + { + 'name': 'startTime', + 'description': '

(optional) schedule playback to start (in seconds from now).

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'rate', + 'description': '

(optional) playback rate

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'amp', + 'description': '

(optional) amplitude (volume)\n of playback

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'cueStart', + 'description': '

(optional) cue start time in seconds

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'duration', + 'description': '

(optional) duration of playback in seconds

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'playMode': { + 'name': 'playMode', + 'params': [ + { + 'name': 'str', + 'description': '

\'restart\' or \'sustain\' or \'untilDone\'

\n', + 'type': 'String' + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'pause': { + 'name': 'pause', + 'params': [ + { + 'name': 'startTime', + 'description': '

(optional) schedule event to occur\n seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'loop': { + 'name': 'loop', + 'params': [ + { + 'name': 'startTime', + 'description': '

(optional) schedule event to occur\n seconds from now

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'rate', + 'description': '

(optional) playback rate

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'amp', + 'description': '

(optional) playback volume

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'cueLoopStart', + 'description': '

(optional) startTime in seconds

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'duration', + 'description': '

(optional) loop duration in seconds

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'setLoop': { + 'name': 'setLoop', + 'params': [ + { + 'name': 'Boolean', + 'description': '

set looping to true or false

\n', + 'type': 'Boolean' + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'isLooping': { + 'name': 'isLooping', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'isPlaying': { + 'name': 'isPlaying', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'isPaused': { + 'name': 'isPaused', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'stop': { + 'name': 'stop', + 'params': [ + { + 'name': 'startTime', + 'description': '

(optional) schedule event to occur\n in seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'pan': { + 'name': 'pan', + 'params': [ + { + 'name': 'panValue', + 'description': '

Set the stereo panner

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'timeFromNow', + 'description': '

schedule this event to happen\n seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'getPan': { + 'name': 'getPan', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'rate': { + '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': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'setVolume': { + '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': true + }, + { + 'name': 'timeFromNow', + 'description': '

Schedule this event to happen at\n t seconds in the future

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'duration': { + 'name': 'duration', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'currentTime': { + 'name': 'currentTime', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'jump': { + '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' + }, + 'channels': { + 'name': 'channels', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'sampleRate': { + 'name': 'sampleRate', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'frames': { + 'name': 'frames', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'getPeaks': { + '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': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'reverseBuffer': { + 'name': 'reverseBuffer', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'onended': { + 'name': 'onended', + 'params': [ + { + 'name': 'callback', + 'description': '

function to call when the\n soundfile has ended.

\n', + 'type': 'Function' + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'object', + 'description': '

Audio object that accepts an input

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'setPath': { + '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' + }, + 'setBuffer': { + 'name': 'setBuffer', + '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' + }, + 'addCue': { + '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': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'removeCue': { + 'name': 'removeCue', + 'params': [ + { + 'name': 'id', + 'description': '

ID of the cue, as returned by addCue

\n', + 'type': 'Number' + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'clearCues': { + 'name': 'clearCues', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'save': { + 'name': 'save', + 'params': [ + { + 'name': 'fileName', + 'description': '

name of the resulting .wav file.

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + }, + 'getBlob': { + 'name': 'getBlob', + 'class': 'p5.SoundFile', + 'module': 'p5.sound' + } + }, + 'p5.Amplitude': { + 'setInput': { + 'name': 'setInput', + 'params': [ + { + 'name': 'snd', + 'description': '

set the sound source\n (optional, defaults to\n main output)

\n', + 'type': 'SoundObject|undefined', + 'optional': true + }, + { + 'name': 'smoothing', + 'description': '

a range between 0.0 and 1.0\n to smooth amplitude readings

\n', + 'type': 'Number|undefined', + 'optional': true + } + ], + 'class': 'p5.Amplitude', + 'module': 'p5.sound' + }, + 'getLevel': { + 'name': 'getLevel', + 'params': [ + { + 'name': 'channel', + 'description': '

Optionally return only channel 0 (left) or 1 (right)

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Amplitude', + 'module': 'p5.sound' + }, + 'toggleNormalize': { + 'name': 'toggleNormalize', + 'params': [ + { + 'name': 'boolean', + 'description': '

set normalize to true (1) or false (0)

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5.Amplitude', + 'module': 'p5.sound' + }, + 'smooth': { + 'name': 'smooth', + 'params': [ + { + 'name': 'set', + 'description': '

smoothing from 0.0 <= 1

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Amplitude', + 'module': 'p5.sound' + } + }, + 'p5.FFT': { + 'setInput': { + 'name': 'setInput', + 'params': [ + { + 'name': 'source', + 'description': '

p5.sound object (or web audio API source node)

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5.FFT', + 'module': 'p5.sound' + }, + 'waveform': { + 'name': 'waveform', + 'params': [ + { + 'name': 'bins', + 'description': '

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

\n', + 'type': 'Number', + 'optional': true + }, + { + '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': true + } + ], + 'class': 'p5.FFT', + 'module': 'p5.sound' + }, + 'analyze': { + 'name': 'analyze', + 'params': [ + { + 'name': 'bins', + 'description': '

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

\n', + 'type': 'Number', + 'optional': true + }, + { + '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': true + } + ], + 'class': 'p5.FFT', + 'module': 'p5.sound' + }, + 'getEnergy': { + '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': true + } + ], + 'class': 'p5.FFT', + 'module': 'p5.sound' + }, + 'getCentroid': { + 'name': 'getCentroid', + 'class': 'p5.FFT', + 'module': 'p5.sound' + }, + 'smooth': { + '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' + }, + 'linAverages': { + 'name': 'linAverages', + 'params': [ + { + 'name': 'N', + 'description': '

Number of returned frequency groups

\n', + 'type': 'Number' + } + ], + 'class': 'p5.FFT', + 'module': 'p5.sound' + }, + 'logAverages': { + 'name': 'logAverages', + 'params': [ + { + 'name': 'octaveBands', + 'description': '

Array of Octave Bands objects for grouping

\n', + 'type': 'Array' + } + ], + 'class': 'p5.FFT', + 'module': 'p5.sound' + }, + 'getOctaveBands': { + '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' + } + ], + 'class': 'p5.FFT', + 'module': 'p5.sound' + } + }, + 'p5.Oscillator': { + 'start': { + 'name': 'start', + 'params': [ + { + 'name': 'time', + 'description': '

startTime in seconds from now.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'frequency', + 'description': '

frequency in Hz.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'stop': { + 'name': 'stop', + 'params': [ + { + 'name': 'secondsFromNow', + 'description': '

Time, in seconds from now.

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'amp': { + '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': true + }, + { + 'name': 'timeFromNow', + 'description': '

schedule this event to happen\n seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'getAmp': { + 'name': 'getAmp', + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'freq': { + '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': true + }, + { + 'name': 'timeFromNow', + 'description': '

Schedule this event to happen\n at x seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'getFreq': { + 'name': 'getFreq', + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'setType': { + 'name': 'setType', + 'params': [ + { + 'name': 'type', + 'description': '

\'sine\', \'triangle\', \'sawtooth\' or \'square\'.

\n', + 'type': 'String' + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'getType': { + 'name': 'getType', + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'unit', + 'description': '

A p5.sound or Web Audio object

\n', + 'type': 'Object' + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'pan': { + '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' + }, + 'getPan': { + 'name': 'getPan', + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'phase': { + 'name': 'phase', + 'params': [ + { + 'name': 'phase', + 'description': '

float between 0.0 and 1.0

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'add': { + 'name': 'add', + 'params': [ + { + 'name': 'number', + 'description': '

Constant number to add

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'mult': { + 'name': 'mult', + 'params': [ + { + 'name': 'number', + 'description': '

Constant number to multiply

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + }, + 'scale': { + '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' + } + ], + 'class': 'p5.Oscillator', + 'module': 'p5.sound' + } + }, + 'p5.Envelope': { + 'attackTime': { + 'name': 'attackTime', + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'attackLevel': { + 'name': 'attackLevel', + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'decayTime': { + 'name': 'decayTime', + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'decayLevel': { + 'name': 'decayLevel', + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'releaseTime': { + 'name': 'releaseTime', + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'releaseLevel': { + 'name': 'releaseLevel', + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'set': { + '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' + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'setADSR': { + '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': true + }, + { + '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': true + }, + { + 'name': 'releaseTime', + 'description': '

Time in seconds from now (defaults to 0)

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'setRange': { + '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' + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'setInput': { + 'name': 'setInput', + 'params': [ + { + 'name': 'inputs', + 'description': '

A p5.sound object or\n Web Audio Param.

\n', + 'type': 'Object', + 'optional': true, + 'multiple': true + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'setExp': { + 'name': 'setExp', + 'params': [ + { + 'name': 'isExp', + 'description': '

true is exponential, false is linear

\n', + 'type': 'Boolean' + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'play': { + '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': true + }, + { + 'name': 'sustainTime', + 'description': '

time to sustain before releasing the envelope

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'triggerAttack': { + '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' + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'triggerRelease': { + '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' + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'ramp': { + '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

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'add': { + 'name': 'add', + 'params': [ + { + 'name': 'number', + 'description': '

Constant number to add

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'mult': { + 'name': 'mult', + 'params': [ + { + 'name': 'number', + 'description': '

Constant number to multiply

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + }, + 'scale': { + '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' + } + ], + 'class': 'p5.Envelope', + 'module': 'p5.sound' + } + }, + 'p5.Noise': { + 'setType': { + 'name': 'setType', + 'params': [ + { + 'name': 'type', + 'description': '

\'white\', \'pink\' or \'brown\'

\n', + 'type': 'String', + 'optional': true + } + ], + 'class': 'p5.Noise', + 'module': 'p5.sound' + } + }, + 'p5.Pulse': { + 'width': { + 'name': 'width', + 'params': [ + { + 'name': 'width', + 'description': '

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

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Pulse', + 'module': 'p5.sound' + } + }, + 'p5.AudioIn': { + 'input': { + 'name': 'input', + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'output': { + 'name': 'output', + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'stream': { + 'name': 'stream', + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'mediaStream': { + 'name': 'mediaStream', + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'currentSource': { + 'name': 'currentSource', + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'enabled': { + 'name': 'enabled', + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'amplitude': { + 'name': 'amplitude', + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'start': { + 'name': 'start', + 'params': [ + { + 'name': 'successCallback', + 'description': '

Name of a function to call on\n success.

\n', + 'type': 'Function', + 'optional': true + }, + { + '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': true + } + ], + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'stop': { + 'name': 'stop', + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'unit', + 'description': '

An object that accepts audio input,\n such as an FFT

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'getLevel': { + 'name': 'getLevel', + 'params': [ + { + 'name': 'smoothing', + 'description': '

Smoothing is 0.0 by default.\n Smooths values based on previous values.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'amp': { + 'name': 'amp', + 'params': [ + { + 'name': 'vol', + 'description': '

between 0 and 1.0

\n', + 'type': 'Number' + }, + { + 'name': 'time', + 'description': '

ramp time (optional)

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'getSources': { + 'name': 'getSources', + 'params': [ + { + 'name': 'successCallback', + 'description': '

This callback function handles the sources when they\n have been enumerated. The callback function\n receives the deviceList array as its only argument

\n', + 'type': 'Function', + 'optional': true + }, + { + 'name': 'errorCallback', + 'description': '

This optional callback receives the error\n message as its argument.

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + }, + 'setSource': { + 'name': 'setSource', + 'params': [ + { + 'name': 'num', + 'description': '

position of input source in the array

\n', + 'type': 'Number' + } + ], + 'class': 'p5.AudioIn', + 'module': 'p5.sound' + } + }, + 'p5.Effect': { + 'amp': { + 'name': 'amp', + 'params': [ + { + 'name': 'vol', + 'description': '

amplitude between 0 and 1.0

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'rampTime', + 'description': '

create a fade that lasts until rampTime

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'tFromNow', + 'description': '

schedule this event to happen in tFromNow seconds

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Effect', + 'module': 'p5.sound' + }, + 'chain': { + 'name': 'chain', + 'params': [ + { + 'name': 'arguments', + 'description': '

Chain together multiple sound objects

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5.Effect', + 'module': 'p5.sound' + }, + 'drywet': { + 'name': 'drywet', + 'params': [ + { + 'name': 'fade', + 'description': '

The desired drywet value (0 - 1.0)

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Effect', + 'module': 'p5.sound' + }, + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'unit', + 'description': '', + 'type': 'Object' + } + ], + 'class': 'p5.Effect', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.Effect', + 'module': 'p5.sound' + } + }, + 'p5.Filter': { + 'biquadFilter': { + 'name': 'biquadFilter', + 'class': 'p5.Filter', + 'module': 'p5.sound' + }, + 'process': { + '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': true + }, + { + 'name': 'res', + 'description': '

Resonance/Width of the filter frequency\n from 0.001 to 1000

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Filter', + 'module': 'p5.sound' + }, + 'set': { + 'name': 'set', + 'params': [ + { + 'name': 'freq', + 'description': '

Frequency in Hz, from 10 to 22050

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'res', + 'description': '

Resonance (Q) from 0.001 to 1000

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'timeFromNow', + 'description': '

schedule this event to happen\n seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Filter', + 'module': 'p5.sound' + }, + 'freq': { + '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': true + } + ], + 'class': 'p5.Filter', + 'module': 'p5.sound' + }, + 'res': { + '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': true + } + ], + 'class': 'p5.Filter', + 'module': 'p5.sound' + }, + 'gain': { + 'name': 'gain', + 'params': [ + { + 'name': 'gain', + 'description': '', + 'type': 'Number' + } + ], + 'class': 'p5.Filter', + 'module': 'p5.sound' + }, + 'toggle': { + 'name': 'toggle', + 'class': 'p5.Filter', + 'module': 'p5.sound' + }, + 'setType': { + 'name': 'setType', + 'params': [ + { + 'name': 't', + 'description': '', + 'type': 'String' + } + ], + 'class': 'p5.Filter', + 'module': 'p5.sound' + } + }, + 'p5.EQ': { + 'bands': { + 'name': 'bands', + 'class': 'p5.EQ', + 'module': 'p5.sound' + }, + 'process': { + 'name': 'process', + 'params': [ + { + 'name': 'src', + 'description': '

Audio source

\n', + 'type': 'Object' + } + ], + 'class': 'p5.EQ', + 'module': 'p5.sound' + } + }, + 'p5.Panner3D': { + 'panner': { + 'name': 'panner', + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'process': { + 'name': 'process', + 'params': [ + { + 'name': 'src', + 'description': '

Input source

\n', + 'type': 'Object' + } + ], + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'set': { + 'name': 'set', + 'params': [ + { + 'name': 'xVal', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'yVal', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'zVal', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'time', + 'description': '', + 'type': 'Number' + } + ], + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'positionX': { + 'name': 'positionX', + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'positionY': { + 'name': 'positionY', + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'positionZ': { + 'name': 'positionZ', + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'orient': { + 'name': 'orient', + 'params': [ + { + 'name': 'xVal', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'yVal', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'zVal', + 'description': '', + 'type': 'Number' + }, + { + 'name': 'time', + 'description': '', + 'type': 'Number' + } + ], + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'orientX': { + 'name': 'orientX', + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'orientY': { + 'name': 'orientY', + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'orientZ': { + 'name': 'orientZ', + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'setFalloff': { + 'name': 'setFalloff', + 'params': [ + { + 'name': 'maxDistance', + 'description': '', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'rolloffFactor', + 'description': '', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'maxDist': { + 'name': 'maxDist', + 'params': [ + { + 'name': 'maxDistance', + 'description': '', + 'type': 'Number' + } + ], + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + }, + 'rollof': { + 'name': 'rollof', + 'params': [ + { + 'name': 'rolloffFactor', + 'description': '', + 'type': 'Number' + } + ], + 'class': 'p5.Panner3D', + 'module': 'p5.sound' + } + }, + 'p5.Delay': { + 'leftDelay': { + 'name': 'leftDelay', + 'class': 'p5.Delay', + 'module': 'p5.sound' + }, + 'rightDelay': { + 'name': 'rightDelay', + 'class': 'p5.Delay', + 'module': 'p5.sound' + }, + 'process': { + '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': true + }, + { + 'name': 'feedback', + 'description': '

sends the delay back through itself\n in a loop that decreases in volume\n each time.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'lowPass', + 'description': '

Cutoff frequency. Only frequencies\n below the lowPass will be part of the\n delay.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Delay', + 'module': 'p5.sound' + }, + 'delayTime': { + 'name': 'delayTime', + 'params': [ + { + 'name': 'delayTime', + 'description': '

Time (in seconds) of the delay

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Delay', + 'module': 'p5.sound' + }, + 'feedback': { + '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' + } + ], + 'class': 'p5.Delay', + 'module': 'p5.sound' + }, + 'filter': { + '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' + }, + 'setType': { + 'name': 'setType', + 'params': [ + { + 'name': 'type', + 'description': '

\'pingPong\' (1) or \'default\' (0)

\n', + 'type': 'String|Number' + } + ], + 'class': 'p5.Delay', + 'module': 'p5.sound' + }, + 'amp': { + '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': true + }, + { + 'name': 'timeFromNow', + 'description': '

schedule this event to happen\n seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Delay', + 'module': 'p5.sound' + }, + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'unit', + 'description': '', + 'type': 'Object' + } + ], + 'class': 'p5.Delay', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.Delay', + 'module': 'p5.sound' + } + }, + 'p5.Reverb': { + 'process': { + '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': true + }, + { + 'name': 'decayRate', + 'description': '

Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'reverse', + 'description': '

Play the reverb backwards or forwards.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5.Reverb', + 'module': 'p5.sound' + }, + 'set': { + 'name': 'set', + 'params': [ + { + 'name': 'seconds', + 'description': '

Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'decayRate', + 'description': '

Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'reverse', + 'description': '

Play the reverb backwards or forwards.

\n', + 'type': 'Boolean', + 'optional': true + } + ], + 'class': 'p5.Reverb', + 'module': 'p5.sound' + }, + 'amp': { + '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': true + }, + { + 'name': 'timeFromNow', + 'description': '

schedule this event to happen\n seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Reverb', + 'module': 'p5.sound' + }, + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'unit', + 'description': '', + 'type': 'Object' + } + ], + 'class': 'p5.Reverb', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.Reverb', + 'module': 'p5.sound' + } + }, + 'p5.Convolver': { + 'convolverNode': { + 'name': 'convolverNode', + 'class': 'p5.Convolver', + 'module': 'p5.sound' + }, + 'impulses': { + 'name': 'impulses', + 'class': 'p5.Convolver', + 'module': 'p5.sound' + }, + 'process': { + 'name': 'process', + 'params': [ + { + 'name': 'src', + 'description': '

p5.sound / Web Audio object with a sound\n output.

\n', + 'type': 'Object' + } + ], + 'class': 'p5.Convolver', + 'module': 'p5.sound' + }, + 'addImpulse': { + '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' + }, + 'resetImpulse': { + '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' + }, + 'toggleImpulse': { + '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' + } + }, + 'p5.Phrase': { + 'sequence': { + 'name': 'sequence', + 'class': 'p5.Phrase', + 'module': 'p5.sound' + } + }, + 'p5.Part': { + 'setBPM': { + 'name': 'setBPM', + 'params': [ + { + 'name': 'BPM', + 'description': '

Beats Per Minute

\n', + 'type': 'Number' + }, + { + 'name': 'rampTime', + 'description': '

Seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'getBPM': { + 'name': 'getBPM', + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'start': { + 'name': 'start', + 'params': [ + { + 'name': 'time', + 'description': '

seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'loop': { + 'name': 'loop', + 'params': [ + { + 'name': 'time', + 'description': '

seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'noLoop': { + 'name': 'noLoop', + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'stop': { + 'name': 'stop', + 'params': [ + { + 'name': 'time', + 'description': '

seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'pause': { + 'name': 'pause', + 'params': [ + { + 'name': 'time', + 'description': '

seconds from now

\n', + 'type': 'Number' + } + ], + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'addPhrase': { + 'name': 'addPhrase', + 'params': [ + { + 'name': 'phrase', + 'description': '

reference to a p5.Phrase

\n', + 'type': 'p5.Phrase' + } + ], + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'removePhrase': { + 'name': 'removePhrase', + 'params': [ + { + 'name': 'phraseName', + 'description': '', + 'type': 'String' + } + ], + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'getPhrase': { + 'name': 'getPhrase', + 'params': [ + { + 'name': 'phraseName', + 'description': '', + 'type': 'String' + } + ], + 'class': 'p5.Part', + 'module': 'p5.sound' + }, + 'replaceSequence': { + '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' + }, + 'onStep': { + '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' + } + }, + 'p5.Score': { + 'start': { + 'name': 'start', + 'class': 'p5.Score', + 'module': 'p5.sound' + }, + 'stop': { + 'name': 'stop', + 'class': 'p5.Score', + 'module': 'p5.sound' + }, + 'pause': { + 'name': 'pause', + 'class': 'p5.Score', + 'module': 'p5.sound' + }, + 'loop': { + 'name': 'loop', + 'class': 'p5.Score', + 'module': 'p5.sound' + }, + 'noLoop': { + 'name': 'noLoop', + 'class': 'p5.Score', + 'module': 'p5.sound' + }, + 'setBPM': { + 'name': 'setBPM', + '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' + } + }, + 'p5.SoundLoop': { + 'bpm': { + 'name': 'bpm', + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + }, + 'timeSignature': { + 'name': 'timeSignature', + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + }, + 'interval': { + 'name': 'interval', + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + }, + 'iterations': { + 'name': 'iterations', + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + }, + 'musicalTimeMode': { + 'name': 'musicalTimeMode', + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + }, + 'maxIterations': { + 'name': 'maxIterations', + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + }, + 'start': { + 'name': 'start', + 'params': [ + { + 'name': 'timeFromNow', + 'description': '

schedule a starting time

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + }, + 'stop': { + 'name': 'stop', + 'params': [ + { + 'name': 'timeFromNow', + 'description': '

schedule a stopping time

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + }, + 'pause': { + 'name': 'pause', + 'params': [ + { + 'name': 'timeFromNow', + 'description': '

schedule a pausing time

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + }, + 'syncedStart': { + 'name': 'syncedStart', + 'params': [ + { + 'name': 'otherLoop', + 'description': '

a p5.SoundLoop to sync with

\n', + 'type': 'Object' + }, + { + 'name': 'timeFromNow', + 'description': '

Start the loops in sync after timeFromNow seconds

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.SoundLoop', + 'module': 'p5.sound' + } + }, + 'p5.Compressor': { + 'compressor': { + 'name': 'compressor', + 'class': 'p5.Compressor', + 'module': 'p5.sound' + }, + 'process': { + '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': true + }, + { + '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': true + }, + { + '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': true + }, + { + 'name': 'threshold', + 'description': '

The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0

\n', + 'type': 'Number', + 'optional': true + }, + { + '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': true + } + ], + 'class': 'p5.Compressor', + 'module': 'p5.sound' + }, + 'set': { + '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' + }, + 'attack': { + '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': true + }, + { + 'name': 'time', + 'description': '

Assign time value to schedule the change in value

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Compressor', + 'module': 'p5.sound' + }, + 'knee': { + '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': true + }, + { + 'name': 'time', + 'description': '

Assign time value to schedule the change in value

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Compressor', + 'module': 'p5.sound' + }, + 'ratio': { + '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': true + }, + { + 'name': 'time', + 'description': '

Assign time value to schedule the change in value

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Compressor', + 'module': 'p5.sound' + }, + 'threshold': { + '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': true + } + ], + 'class': 'p5.Compressor', + 'module': 'p5.sound' + }, + 'release': { + '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': true + } + ], + 'class': 'p5.Compressor', + 'module': 'p5.sound' + }, + 'reduction': { + 'name': 'reduction', + 'class': 'p5.Compressor', + 'module': 'p5.sound' + } + }, + 'p5.PeakDetect': { + 'isDetected': { + 'name': 'isDetected', + 'class': 'p5.PeakDetect', + 'module': 'p5.sound' + }, + 'update': { + 'name': 'update', + 'params': [ + { + 'name': 'fftObject', + 'description': '

A p5.FFT object

\n', + 'type': 'p5.FFT' + } + ], + 'class': 'p5.PeakDetect', + 'module': 'p5.sound' + }, + 'onPeak': { + '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': true + } + ], + 'class': 'p5.PeakDetect', + 'module': 'p5.sound' + } + }, + 'p5.SoundRecorder': { + 'setInput': { + 'name': 'setInput', + 'params': [ + { + 'name': 'unit', + 'description': '

p5.sound object or a web audio unit\n that outputs sound

\n', + 'type': 'Object', + 'optional': true + } + ], + 'class': 'p5.SoundRecorder', + 'module': 'p5.sound' + }, + 'record': { + 'name': 'record', + 'params': [ + { + 'name': 'soundFile', + 'description': '

p5.SoundFile

\n', + 'type': 'p5.SoundFile' + }, + { + 'name': 'duration', + 'description': '

Time (in seconds)

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'callback', + 'description': '

The name of a function that will be\n called once the recording completes

\n', + 'type': 'Function', + 'optional': true + } + ], + 'class': 'p5.SoundRecorder', + 'module': 'p5.sound' + }, + 'stop': { + 'name': 'stop', + 'class': 'p5.SoundRecorder', + 'module': 'p5.sound' + } + }, + 'p5.Distortion': { + 'WaveShaperNode': { + 'name': 'WaveShaperNode', + 'class': 'p5.Distortion', + 'module': 'p5.sound' + }, + 'process': { + 'name': 'process', + 'params': [ + { + 'name': 'amount', + 'description': '

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

\n', + 'type': 'Number', + 'optional': true, + 'optdefault': '0.25' + }, + { + 'name': 'oversample', + 'description': '

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

\n', + 'type': 'String', + 'optional': true, + 'optdefault': '\'none\'' + } + ], + 'class': 'p5.Distortion', + 'module': 'p5.sound' + }, + 'set': { + 'name': 'set', + 'params': [ + { + 'name': 'amount', + 'description': '

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

\n', + 'type': 'Number', + 'optional': true, + 'optdefault': '0.25' + }, + { + 'name': 'oversample', + 'description': '

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

\n', + 'type': 'String', + 'optional': true, + 'optdefault': '\'none\'' + } + ], + 'class': 'p5.Distortion', + 'module': 'p5.sound' + }, + 'getAmount': { + 'name': 'getAmount', + 'class': 'p5.Distortion', + 'module': 'p5.sound' + }, + 'getOversample': { + 'name': 'getOversample', + 'class': 'p5.Distortion', + 'module': 'p5.sound' + } + }, + 'p5.Gain': { + 'setInput': { + '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' + }, + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'unit', + 'description': '', + 'type': 'Object' + } + ], + 'class': 'p5.Gain', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.Gain', + 'module': 'p5.sound' + }, + 'amp': { + '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': true + }, + { + 'name': 'timeFromNow', + 'description': '

schedule this event to happen\n seconds from now

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.Gain', + 'module': 'p5.sound' + } + }, + 'p5.AudioVoice': { + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'unit', + 'description': '', + 'type': 'Object' + } + ], + 'class': 'p5.AudioVoice', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.AudioVoice', + 'module': 'p5.sound' + } + }, + 'p5.MonoSynth': { + 'attack': { + 'name': 'attack', + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'decay': { + 'name': 'decay', + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'sustain': { + 'name': 'sustain', + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'release': { + 'name': 'release', + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'play': { + 'name': 'play', + 'params': [ + { + 'name': 'note', + 'description': '

the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format ("C4", "Eb3"...etc")\n See \n Tone. Defaults to 440 hz.

\n', + 'type': 'String | Number' + }, + { + 'name': 'velocity', + 'description': '

velocity of the note to play (ranging from 0 to 1)

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'secondsFromNow', + 'description': '

time from now (in seconds) at which to play

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'sustainTime', + 'description': '

time to sustain before releasing the envelope. Defaults to 0.15 seconds.

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'triggerAttack': { + 'params': [ + { + 'name': 'note', + 'description': '

the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format ("C4", "Eb3"...etc")\n See \n Tone. Defaults to 440 hz

\n', + 'type': 'String | Number' + }, + { + 'name': 'velocity', + 'description': '

velocity of the note to play (ranging from 0 to 1)

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'secondsFromNow', + 'description': '

time from now (in seconds) at which to play

\n', + 'type': 'Number', + 'optional': true + } + ], + 'name': 'triggerAttack', + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'triggerRelease': { + 'params': [ + { + 'name': 'secondsFromNow', + 'description': '

time to trigger the release

\n', + 'type': 'Number' + } + ], + 'name': 'triggerRelease', + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'setADSR': { + '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': true + }, + { + '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': true + }, + { + 'name': 'releaseTime', + 'description': '

Time in seconds from now (defaults to 0)

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'amp': { + 'name': 'amp', + 'params': [ + { + 'name': 'vol', + 'description': '

desired volume

\n', + 'type': 'Number' + }, + { + 'name': 'rampTime', + 'description': '

Time to reach new volume

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'unit', + 'description': '

A p5.sound or Web Audio object

\n', + 'type': 'Object' + } + ], + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + }, + 'dispose': { + 'name': 'dispose', + 'class': 'p5.MonoSynth', + 'module': 'p5.sound' + } + }, + 'p5.PolySynth': { + 'notes': { + 'name': 'notes', + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'polyvalue': { + 'name': 'polyvalue', + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'AudioVoice': { + 'name': 'AudioVoice', + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'play': { + 'name': 'play', + 'params': [ + { + 'name': 'note', + 'description': '

midi note to play (ranging from 0 to 127 - 60 being a middle C)

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'velocity', + 'description': '

velocity of the note to play (ranging from 0 to 1)

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'secondsFromNow', + 'description': '

time from now (in seconds) at which to play

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'sustainTime', + 'description': '

time to sustain before releasing the envelope

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'noteADSR': { + 'name': 'noteADSR', + 'params': [ + { + 'name': 'note', + 'description': '

Midi note on which ADSR should be set.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'attackTime', + 'description': '

Time (in seconds before envelope\n reaches Attack Level

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'decayTime', + 'description': '

Time (in seconds) before envelope\n reaches Decay/Sustain Level

\n', + 'type': 'Number', + 'optional': true + }, + { + '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': true + }, + { + 'name': 'releaseTime', + 'description': '

Time in seconds from now (defaults to 0)

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'setADSR': { + 'name': 'setADSR', + 'params': [ + { + 'name': 'attackTime', + 'description': '

Time (in seconds before envelope\n reaches Attack Level

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'decayTime', + 'description': '

Time (in seconds) before envelope\n reaches Decay/Sustain Level

\n', + 'type': 'Number', + 'optional': true + }, + { + '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': true + }, + { + 'name': 'releaseTime', + 'description': '

Time in seconds from now (defaults to 0)

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'noteAttack': { + 'name': 'noteAttack', + 'params': [ + { + 'name': 'note', + 'description': '

midi note on which attack should be triggered.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'velocity', + 'description': '

velocity of the note to play (ranging from 0 to 1)/

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'secondsFromNow', + 'description': '

time from now (in seconds)

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'noteRelease': { + 'name': 'noteRelease', + 'params': [ + { + 'name': 'note', + 'description': '

midi note on which attack should be triggered.\n If no value is provided, all notes will be released.

\n', + 'type': 'Number', + 'optional': true + }, + { + 'name': 'secondsFromNow', + 'description': '

time to trigger the release

\n', + 'type': 'Number', + 'optional': true + } + ], + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'connect': { + 'name': 'connect', + 'params': [ + { + 'name': 'unit', + 'description': '

A p5.sound or Web Audio object

\n', + 'type': 'Object' + } + ], + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'disconnect': { + 'name': 'disconnect', + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + }, + 'dispose': { + 'name': 'dispose', + 'class': 'p5.PolySynth', + 'module': 'p5.sound' + } + } + } + }, + { + } + ], + 2: [ + function (_dereq_, module, exports) { + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + module.exports = _arrayWithHoles; + }, + { + } + ], + 3: [ + function (_dereq_, module, exports) { + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } + module.exports = _arrayWithoutHoles; + }, + { + } + ], + 4: [ + function (_dereq_, module, exports) { + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return self; + } + module.exports = _assertThisInitialized; + }, + { + } + ], + 5: [ + function (_dereq_, module, exports) { + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + module.exports = _classCallCheck; + }, + { + } + ], + 6: [ + function (_dereq_, module, exports) { + 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; + } + module.exports = _createClass; + }, + { + } + ], + 7: [ + function (_dereq_, module, exports) { + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } + module.exports = _defineProperty; + }, + { + } + ], + 8: [ + function (_dereq_, module, exports) { + function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } + module.exports = _getPrototypeOf; + }, + { + } + ], + 9: [ + function (_dereq_, module, exports) { + var setPrototypeOf = _dereq_('./setPrototypeOf'); + 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); + } + module.exports = _inherits; + }, + { + './setPrototypeOf': 16 + } + ], + 10: [ + function (_dereq_, module, exports) { + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + module.exports = _iterableToArray; + }, + { + } + ], + 11: [ + function (_dereq_, module, exports) { + function _iterableToArrayLimit(arr, i) { + var _arr = [ + ]; + var _n = true; + var _d = false; + var _e = undefined; + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i['return'] != null) _i['return'](); + } finally { + if (_d) throw _e; + } + } + return _arr; + } + module.exports = _iterableToArrayLimit; + }, + { + } + ], + 12: [ + function (_dereq_, module, exports) { + function _nonIterableRest() { + throw new TypeError('Invalid attempt to destructure non-iterable instance'); + } + module.exports = _nonIterableRest; + }, + { + } + ], + 13: [ + function (_dereq_, module, exports) { + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + module.exports = _nonIterableSpread; + }, + { + } + ], + 14: [ + function (_dereq_, module, exports) { + var defineProperty = _dereq_('./defineProperty'); + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : { + }; + var ownKeys = Object.keys(source); + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); + } + ownKeys.forEach(function (key) { + defineProperty(target, key, source[key]); + }); + } + return target; + } + module.exports = _objectSpread; + }, + { + './defineProperty': 7 + } + ], + 15: [ + function (_dereq_, module, exports) { + var _typeof = _dereq_('../helpers/typeof'); + var assertThisInitialized = _dereq_('./assertThisInitialized'); + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === 'object' || typeof call === 'function')) { + return call; + } + return assertThisInitialized(self); + } + module.exports = _possibleConstructorReturn; + }, + { + '../helpers/typeof': 19, + './assertThisInitialized': 4 + } + ], + 16: [ + function (_dereq_, module, exports) { + function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + module.exports = _setPrototypeOf; + }, + { + } + ], + 17: [ + function (_dereq_, module, exports) { + var arrayWithHoles = _dereq_('./arrayWithHoles'); + var iterableToArrayLimit = _dereq_('./iterableToArrayLimit'); + var nonIterableRest = _dereq_('./nonIterableRest'); + function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest(); + } + module.exports = _slicedToArray; + }, + { + './arrayWithHoles': 2, + './iterableToArrayLimit': 11, + './nonIterableRest': 12 + } + ], + 18: [ + function (_dereq_, module, exports) { + var arrayWithoutHoles = _dereq_('./arrayWithoutHoles'); + var iterableToArray = _dereq_('./iterableToArray'); + var nonIterableSpread = _dereq_('./nonIterableSpread'); + function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread(); + } + module.exports = _toConsumableArray; + }, + { + './arrayWithoutHoles': 3, + './iterableToArray': 10, + './nonIterableSpread': 13 + } + ], + 19: [ + function (_dereq_, module, exports) { + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + module.exports = _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + module.exports = _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + module.exports = _typeof; + }, + { + } + ], + 20: [ + function (_dereq_, module, exports) { + 'use strict'; + exports.byteLength = byteLength; + exports.toByteArray = toByteArray; + exports.fromByteArray = fromByteArray; + var lookup = [ + ]; + var revLookup = [ + ]; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } // Support decoding URL-safe base64 strings, as Node.js does. + // See: https://en.wikipedia.org/wiki/Base64#URL_applications + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + function getLens(b64) { + var len = b64.length; + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4'); + } // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + + var validLen = b64.indexOf('='); + if (validLen === - 1) validLen = len; + var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; + return [validLen, + placeHoldersLen]; + } // base64 is 4/3 + up to two characters of the original data + + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i; + for (i = 0; i < len; i += 4) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + return arr; + } + function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; + } + function encodeChunk(uint8, start, end) { + var tmp; + var output = [ + ]; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(''); + } + function fromByteArray(uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var parts = [ + ]; + var maxChunkLength = 16383; // must be multiple of 3 + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } // pad the end with zeros, but make sure to not forget the extra bytes + + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + '=='); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + '='); + } + return parts.join(''); + } + }, + { + } + ], + 21: [ + function (_dereq_, module, exports) { + }, + { + } + ], + 22: [ + function (_dereq_, module, exports) { + (function (Buffer) { + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + 'use strict'; + var base64 = _dereq_('base64-js'); + var ieee754 = _dereq_('ieee754'); + var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : null; + exports.Buffer = Buffer; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 2147483647; + exports.kMaxLength = K_MAX_LENGTH; + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ + Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { + console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'); + } + function typedArraySupport() { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1); + var proto = { + foo: function () { + return 42; + } + }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e) { + return false; + } + } + Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined; + return this.buffer; + } + }); + Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined; + return this.byteOffset; + } + }); + function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"'); + } // Return an augmented `Uint8Array` instance + + var buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; + } /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer(arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError('The "string" argument must be of type string. Received type number'); + } + return allocUnsafe(arg); + } + return from(arg, encodingOrOffset, length); + } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + + if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }); + } + Buffer.poolSize = 8192; // not used by this implementation + function from(value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset); + } + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value); + } + if (value == null) { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + typeof value); + } + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type number'); + } + var valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length); + } + var b = fromObject(value); + if (b) return b; + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length); + } + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + typeof value); + } /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + + Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length); + }; + // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: + // https://github.com/feross/buffer/pull/148 + Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer, Uint8Array); + function assertSize(size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + return createBuffer(size); + } /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding); + }; + function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + + Buffer.allocUnsafe = function (size) { + return allocUnsafe(size); + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size); + }; + function fromString(string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); + var actual = buf.write(string, encoding); + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual); + } + return buf; + } + function fromArrayLike(array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length); + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf; + } + function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + var buf; + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array); + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } // Return an augmented `Uint8Array` instance + + Object.setPrototypeOf(buf, Buffer.prototype); + return buf; + } + function fromObject(obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + function checked(length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes'); + } + return length | 0; + } + function SlowBuffer(length) { + if ( + length != length) { + // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc( + length); + } + Buffer.isBuffer = function isBuffer(b) { + return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false + }; + Buffer.compare = function compare(a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); + } + if (a === b) return 0; + var x = a.length; + var y = b.length; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) return - 1; + if (y < x) return 1; + return 0; + }; + Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true; + default: + return false; + } + }; + Buffer.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list.length === 0) { + return Buffer.alloc(0); + } + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf); + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer; + }; + function byteLength(string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length; + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength; + } + if (typeof string !== 'string') { + throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string); + } + var len = string.length; + var mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) return 0; + // Use a for loop to avoid recursion + var loweredCase = false; + for (; ; ) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len; + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2; + case 'hex': + return len >>> 1; + case 'base64': + return base64ToBytes(string).length; + default: + if (loweredCase) { + return mustMatch ? - 1 : utf8ToBytes(string).length; // assume utf8 + } + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + function slowToString(encoding, start, end) { + var loweredCase = false; + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + + if (start > this.length) { + return ''; + } + if (end === undefined || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ''; + } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ''; + } + if (!encoding) encoding = 'utf8'; + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end); + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end); + case 'ascii': + return asciiSlice(this, start, end); + case 'latin1': + case 'binary': + return latin1Slice(this, start, end); + case 'base64': + return base64Slice(this, start, end); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end); + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) + // to detect a Buffer instance. It's not possible to use `instanceof Buffer` + // reliably in a browserify context because there could be multiple different + // copies of the 'buffer' package in use. This method works even for Buffer + // instances that were created from another copy of the `buffer` package. + // See: https://github.com/feross/buffer/issues/154 + + Buffer.prototype._isBuffer = true; + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + Buffer.prototype.swap16 = function swap16() { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits'); + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; + }; + Buffer.prototype.swap32 = function swap32() { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits'); + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; + }; + Buffer.prototype.swap64 = function swap64() { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits'); + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; + }; + Buffer.prototype.toString = function toString() { + var length = this.length; + if (length === 0) return ''; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + Buffer.prototype.toLocaleString = Buffer.prototype.toString; + Buffer.prototype.equals = function equals(b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); + if (this === b) return true; + return Buffer.compare(this, b) === 0; + }; + Buffer.prototype.inspect = function inspect() { + var str = ''; + var max = exports.INSPECT_MAX_BYTES; + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); + if (this.length > max) str += ' ... '; + return ''; + }; + if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; + } + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength); + } + if (!Buffer.isBuffer(target)) { + throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + typeof target); + } + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index'); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return - 1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + if (x < y) return - 1; + if (y < x) return 1; + return 0; + }; + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return - 1; + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < - 2147483648) { + byteOffset = - 2147483648; + } + byteOffset = + byteOffset; // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } // Normalize byteOffset: negative offsets start from the end of the buffer + + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return - 1; + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return - 1; + } // Normalize val + + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } // Finally, search either indexOf (if dir is true) or lastIndexOf + + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return - 1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === 'number') { + val = val & 255; // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + return arrayIndexOf(buffer, [ + val + ], byteOffset, encoding, dir); + } + throw new TypeError('val must be string, number or Buffer'); + } + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return - 1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } + var i; + if (dir) { + var foundIndex = - 1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === - 1 ? 0 : i - foundIndex)) { + if (foundIndex === - 1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== - 1) i -= i - foundIndex; + foundIndex = - 1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + if (found) return i; + } + } + return - 1; + } + Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== - 1; + }; + Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + var strLen = string.length; + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i; + buf[offset + i] = parsed; + } + return i; + } + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + } + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } + function latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length); + } + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); + } + Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length)) { + length = length >>> 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + } else { + throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); + } + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds'); + } + if (!encoding) encoding = 'utf8'; + var loweredCase = false; + for (; ; ) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length); + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length); + case 'ascii': + return asciiWrite(this, string, offset, length); + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length); + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length); + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + Buffer.prototype.toJSON = function toJSON() { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf); + } else { + return base64.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = [ + ]; + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i + bytesPerSequence <= end) { + var secondByte, + thirdByte, + fourthByte, + tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + // encode to utf16 (surrogate pair dance) + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i += bytesPerSequence; + } + return decodeCodePointsArray(res); + } // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + + var MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } // Decode in chunks to avoid "call stack size exceeded". + + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); + } + return res; + } + function asciiSlice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 127); + } + return ret; + } + function latin1Slice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; + } + function hexSlice(buf, start, end) { + var len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + var out = ''; + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out; + } + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; + } + Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + if (end < start) end = start; + var newBuf = this.subarray(start, end); + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype); + return newBuf; + }; + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); + } + Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 256)) { + val += this[offset + i] * mul; + } + return val; + }; + Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 256)) { + val += this[offset + --byteLength] * mul; + } + return val; + }; + Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }; + Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; + }; + Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 256)) { + val += this[offset + i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 256)) { + val += this[offset + --i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; + }; + Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 128)) return this[offset]; + return (255 - this[offset] + 1) * - 1; + }; + Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | this[offset + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | this[offset] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + } + Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = + value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + var mul = 1; + var i = 0; + this[offset] = value & 255; + while (++i < byteLength && (mul *= 256)) { + this[offset + i] = value / mul & 255; + } + return offset + byteLength; + }; + Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = + value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + this[offset + i] = value / mul & 255; + } + return offset + byteLength; + }; + Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 255, 0); + this[offset] = value & 255; + return offset + 1; + }; + Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 255; + return offset + 4; + }; + Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, - limit); + } + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 255; + while (++i < byteLength && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength; + }; + Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, - limit); + } + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength; + }; + Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 127, - 128); + if (value < 0) value = 255 + value + 1; + this[offset] = value & 255; + return offset + 1; + }; + Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 32767, - 32768); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 32767, - 32768); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 2147483647, - 2147483648); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 2147483647, - 2147483648); + if (value < 0) value = 4294967295 + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + if (offset < 0) throw new RangeError('Index out of range'); + } + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, - 3.4028234663852886e+38); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = + value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157e+308, - 1.7976931348623157e+308); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer'); + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + // Copy 0 bytes; we're done + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds'); + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); + if (end < 0) throw new RangeError('sourceEnd out of bounds'); + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + var len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end); + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); + } + return len; + }; + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string'); + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (encoding === 'utf8' && code < 128 || encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code; + } + } + } else if (typeof val === 'number') { + val = val & 255; + } else if (typeof val === 'boolean') { + val = Number(val); + } // Invalid ranges are not set to a default, so can range check early. + + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index'); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + if (!val) val = 0; + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); + var len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + return this; + }; + // HELPER FUNCTIONS + // ================ + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=') [0]; + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return ''; + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str; + } + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = [ + ]; + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + // is surrogate component + if (codePoint > 55295 && codePoint < 57344) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 56319) { + // unexpected trail + if ((units -= 3) > - 1) bytes.push(239, 191, 189); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > - 1) bytes.push(239, 191, 189); + continue; + } // valid lead + + leadSurrogate = codePoint; + continue; + } // 2 leads in a row + + if (codePoint < 56320) { + if ((units -= 3) > - 1) bytes.push(239, 191, 189); + leadSurrogate = codePoint; + continue; + } // valid surrogate pair + + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > - 1) bytes.push(239, 191, 189); + } + leadSurrogate = null; + // encode utf8 + if (codePoint < 128) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) break; + bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) break; + bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) break; + bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); + } else { + throw new Error('Invalid code point'); + } + } + return bytes; + } + function asciiToBytes(str) { + var byteArray = [ + ]; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 255); + } + return byteArray; + } + function utf16leToBytes(str, units) { + var c, + hi, + lo; + var byteArray = [ + ]; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + return byteArray; + } + function base64ToBytes(str) { + return base64.toByteArray(base64clean(str)); + } + function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + return i; + } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass + // the `instanceof` check but they should be treated as of that type. + // See: https://github.com/feross/buffer/issues/166 + + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + function numberIsNaN(obj) { + // For IE11 support + return obj !== obj; // eslint-disable-line no-self-compare + } // Create lookup table for `toString('hex')` + // See: https://github.com/feross/buffer/issues/219 + + var hexSliceLookupTable = function () { + var alphabet = '0123456789abcdef'; + var table = new Array(256); + for (var i = 0; i < 16; ++i) { + var i16 = i * 16; + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + return table; + }(); + }).call(this, _dereq_('buffer').Buffer) + }, + { + 'base64-js': 20, + 'buffer': 22, + 'ieee754': 273 + } + ], + 23: [ + function (_dereq_, module, exports) { + module.exports = function (it) { + if (typeof it != 'function') { + throw TypeError(String(it) + ' is not a function'); + } + return it; + }; + }, + { + } + ], + 24: [ + function (_dereq_, module, exports) { + var isObject = _dereq_('../internals/is-object'); + module.exports = function (it) { + if (!isObject(it) && it !== null) { + throw TypeError('Can\'t set ' + String(it) + ' as a prototype'); + } + return it; + }; + }, + { + '../internals/is-object': 93 + } + ], + 25: [ + function (_dereq_, module, exports) { + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var create = _dereq_('../internals/object-create'); + var definePropertyModule = _dereq_('../internals/object-define-property'); + var UNSCOPABLES = wellKnownSymbol('unscopables'); + var ArrayPrototype = Array.prototype; + // Array.prototype[@@unscopables] + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + if (ArrayPrototype[UNSCOPABLES] == undefined) { + definePropertyModule.f(ArrayPrototype, UNSCOPABLES, { + configurable: true, + value: create(null) + }); + } // add a key to Array.prototype[@@unscopables] + + module.exports = function (key) { + ArrayPrototype[UNSCOPABLES][key] = true; + }; + }, + { + '../internals/object-create': 109, + '../internals/object-define-property': 111, + '../internals/well-known-symbol': 167 + } + ], + 26: [ + function (_dereq_, module, exports) { + 'use strict'; + var charAt = _dereq_('../internals/string-multibyte').charAt; + // `AdvanceStringIndex` abstract operation + // https://tc39.github.io/ecma262/#sec-advancestringindex + module.exports = function (S, index, unicode) { + return index + (unicode ? charAt(S, index).length : 1); + }; + }, + { + '../internals/string-multibyte': 142 + } + ], + 27: [ + function (_dereq_, module, exports) { + module.exports = function (it, Constructor, name) { + if (!(it instanceof Constructor)) { + throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation'); + } + return it; + }; + }, + { + } + ], + 28: [ + function (_dereq_, module, exports) { + var isObject = _dereq_('../internals/is-object'); + module.exports = function (it) { + if (!isObject(it)) { + throw TypeError(String(it) + ' is not an object'); + } + return it; + }; + }, + { + '../internals/is-object': 93 + } + ], + 29: [ + function (_dereq_, module, exports) { + module.exports = typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined'; + }, + { + } + ], + 30: [ + function (_dereq_, module, exports) { + 'use strict'; + var NATIVE_ARRAY_BUFFER = _dereq_('../internals/array-buffer-native'); + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var global = _dereq_('../internals/global'); + var isObject = _dereq_('../internals/is-object'); + var has = _dereq_('../internals/has'); + var classof = _dereq_('../internals/classof'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var redefine = _dereq_('../internals/redefine'); + var defineProperty = _dereq_('../internals/object-define-property').f; + var getPrototypeOf = _dereq_('../internals/object-get-prototype-of'); + var setPrototypeOf = _dereq_('../internals/object-set-prototype-of'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var uid = _dereq_('../internals/uid'); + var Int8Array = global.Int8Array; + var Int8ArrayPrototype = Int8Array && Int8Array.prototype; + var Uint8ClampedArray = global.Uint8ClampedArray; + var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; + var TypedArray = Int8Array && getPrototypeOf(Int8Array); + var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype); + var ObjectPrototype = Object.prototype; + var isPrototypeOf = ObjectPrototype.isPrototypeOf; + var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); + // Fixing native typed arrays in Opera Presto crashes the browser, see #595 + var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera'; + var TYPED_ARRAY_TAG_REQIRED = false; + var NAME; + var TypedArrayConstructorsList = { + Int8Array: 1, + Uint8Array: 1, + Uint8ClampedArray: 1, + Int16Array: 2, + Uint16Array: 2, + Int32Array: 4, + Uint32Array: 4, + Float32Array: 4, + Float64Array: 8 + }; + var isView = function isView(it) { + var klass = classof(it); + return klass === 'DataView' || has(TypedArrayConstructorsList, klass); + }; + var isTypedArray = function (it) { + return isObject(it) && has(TypedArrayConstructorsList, classof(it)); + }; + var aTypedArray = function (it) { + if (isTypedArray(it)) return it; + throw TypeError('Target is not a typed array'); + }; + var aTypedArrayConstructor = function (C) { + if (setPrototypeOf) { + if (isPrototypeOf.call(TypedArray, C)) return C; + } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) { + var TypedArrayConstructor = global[ARRAY]; + if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) { + return C; + } + } + throw TypeError('Target is not a typed array constructor'); + }; + var exportTypedArrayMethod = function (KEY, property, forced) { + if (!DESCRIPTORS) return; + if (forced) for (var ARRAY in TypedArrayConstructorsList) { + var TypedArrayConstructor = global[ARRAY]; + if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) { + delete TypedArrayConstructor.prototype[KEY]; + } + } + if (!TypedArrayPrototype[KEY] || forced) { + redefine(TypedArrayPrototype, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property); + } + }; + var exportTypedArrayStaticMethod = function (KEY, property, forced) { + var ARRAY, + TypedArrayConstructor; + if (!DESCRIPTORS) return; + if (setPrototypeOf) { + if (forced) for (ARRAY in TypedArrayConstructorsList) { + TypedArrayConstructor = global[ARRAY]; + if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) { + delete TypedArrayConstructor[KEY]; + } + } + if (!TypedArray[KEY] || forced) { + // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable + try { + return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property); + } catch (error) { /* empty */ + } + } else return; + } + for (ARRAY in TypedArrayConstructorsList) { + TypedArrayConstructor = global[ARRAY]; + if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { + redefine(TypedArrayConstructor, KEY, property); + } + } + }; + for (NAME in TypedArrayConstructorsList) { + if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false; + } // WebKit bug - typed arrays constructors prototype is Object.prototype + + if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) { + // eslint-disable-next-line no-shadow + TypedArray = function TypedArray() { + throw TypeError('Incorrect invocation'); + }; + if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { + if (global[NAME]) setPrototypeOf(global[NAME], TypedArray); + } + } + if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) { + TypedArrayPrototype = TypedArray.prototype; + if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { + if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype); + } + } // WebKit bug - one more object in Uint8ClampedArray prototype chain + + if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { + setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); + } + if (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) { + TYPED_ARRAY_TAG_REQIRED = true; + defineProperty(TypedArrayPrototype, TO_STRING_TAG, { + get: function () { + return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; + } + }); + for (NAME in TypedArrayConstructorsList) if (global[NAME]) { + createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME); + } + } + module.exports = { + NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, + TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG, + aTypedArray: aTypedArray, + aTypedArrayConstructor: aTypedArrayConstructor, + exportTypedArrayMethod: exportTypedArrayMethod, + exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, + isView: isView, + isTypedArray: isTypedArray, + TypedArray: TypedArray, + TypedArrayPrototype: TypedArrayPrototype + }; + }, + { + '../internals/array-buffer-native': 29, + '../internals/classof': 47, + '../internals/create-non-enumerable-property': 56, + '../internals/descriptors': 61, + '../internals/global': 78, + '../internals/has': 79, + '../internals/is-object': 93, + '../internals/object-define-property': 111, + '../internals/object-get-prototype-of': 116, + '../internals/object-set-prototype-of': 120, + '../internals/redefine': 127, + '../internals/uid': 164, + '../internals/well-known-symbol': 167 + } + ], + 31: [ + function (_dereq_, module, exports) { + 'use strict'; + var global = _dereq_('../internals/global'); + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var NATIVE_ARRAY_BUFFER = _dereq_('../internals/array-buffer-native'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var redefineAll = _dereq_('../internals/redefine-all'); + var fails = _dereq_('../internals/fails'); + var anInstance = _dereq_('../internals/an-instance'); + var toInteger = _dereq_('../internals/to-integer'); + var toLength = _dereq_('../internals/to-length'); + var toIndex = _dereq_('../internals/to-index'); + var IEEE754 = _dereq_('../internals/ieee754'); + var getPrototypeOf = _dereq_('../internals/object-get-prototype-of'); + var setPrototypeOf = _dereq_('../internals/object-set-prototype-of'); + var getOwnPropertyNames = _dereq_('../internals/object-get-own-property-names').f; + var defineProperty = _dereq_('../internals/object-define-property').f; + var arrayFill = _dereq_('../internals/array-fill'); + var setToStringTag = _dereq_('../internals/set-to-string-tag'); + var InternalStateModule = _dereq_('../internals/internal-state'); + var getInternalState = InternalStateModule.get; + var setInternalState = InternalStateModule.set; + var ARRAY_BUFFER = 'ArrayBuffer'; + var DATA_VIEW = 'DataView'; + var PROTOTYPE = 'prototype'; + var WRONG_LENGTH = 'Wrong length'; + var WRONG_INDEX = 'Wrong index'; + var NativeArrayBuffer = global[ARRAY_BUFFER]; + var $ArrayBuffer = NativeArrayBuffer; + var $DataView = global[DATA_VIEW]; + var $DataViewPrototype = $DataView && $DataView[PROTOTYPE]; + var ObjectPrototype = Object.prototype; + var RangeError = global.RangeError; + var packIEEE754 = IEEE754.pack; + var unpackIEEE754 = IEEE754.unpack; + var packInt8 = function (number) { + return [number & 255]; + }; + var packInt16 = function (number) { + return [number & 255, + number >> 8 & 255]; + }; + var packInt32 = function (number) { + return [number & 255, + number >> 8 & 255, + number >> 16 & 255, + number >> 24 & 255]; + }; + var unpackInt32 = function (buffer) { + return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0]; + }; + var packFloat32 = function (number) { + return packIEEE754(number, 23, 4); + }; + var packFloat64 = function (number) { + return packIEEE754(number, 52, 8); + }; + var addGetter = function (Constructor, key) { + defineProperty(Constructor[PROTOTYPE], key, { + get: function () { + return getInternalState(this) [key]; + } + }); + }; + var get = function (view, count, index, isLittleEndian) { + var intIndex = toIndex(index); + var store = getInternalState(view); + if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX); + var bytes = getInternalState(store.buffer).bytes; + var start = intIndex + store.byteOffset; + var pack = bytes.slice(start, start + count); + return isLittleEndian ? pack : pack.reverse(); + }; + var set = function (view, count, index, conversion, value, isLittleEndian) { + var intIndex = toIndex(index); + var store = getInternalState(view); + if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX); + var bytes = getInternalState(store.buffer).bytes; + var start = intIndex + store.byteOffset; + var pack = conversion( + value); + for (var i = 0; i < count; i++) bytes[start + i] = pack[isLittleEndian ? i : count - i - 1]; + }; + if (!NATIVE_ARRAY_BUFFER) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer, ARRAY_BUFFER); + var byteLength = toIndex(length); + setInternalState(this, { + bytes: arrayFill.call(new Array(byteLength), 0), + byteLength: byteLength + }); + if (!DESCRIPTORS) this.byteLength = byteLength; + }; + $DataView = function DataView(buffer, byteOffset, byteLength) { + anInstance(this, $DataView, DATA_VIEW); + anInstance(buffer, $ArrayBuffer, DATA_VIEW); + var bufferLength = getInternalState(buffer).byteLength; + var offset = toInteger(byteOffset); + if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset'); + byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); + if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); + setInternalState(this, { + buffer: buffer, + byteLength: byteLength, + byteOffset: offset + }); + if (!DESCRIPTORS) { + this.buffer = buffer; + this.byteLength = byteLength; + this.byteOffset = offset; + } + }; + if (DESCRIPTORS) { + addGetter($ArrayBuffer, 'byteLength'); + addGetter($DataView, 'buffer'); + addGetter($DataView, 'byteLength'); + addGetter($DataView, 'byteOffset'); + } + redefineAll($DataView[PROTOTYPE], { + getInt8: function getInt8(byteOffset) { + return get(this, 1, byteOffset) [0] << 24 >> 24; + }, + getUint8: function getUint8(byteOffset) { + return get(this, 1, byteOffset) [0]; + }, + getInt16: function getInt16(byteOffset /* , littleEndian */ ) { + var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); + return (bytes[1] << 8 | bytes[0]) << 16 >> 16; + }, + getUint16: function getUint16(byteOffset /* , littleEndian */ ) { + var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); + return bytes[1] << 8 | bytes[0]; + }, + getInt32: function getInt32(byteOffset /* , littleEndian */ ) { + return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)); + }, + getUint32: function getUint32(byteOffset /* , littleEndian */ ) { + return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0; + }, + getFloat32: function getFloat32(byteOffset /* , littleEndian */ ) { + return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23); + }, + getFloat64: function getFloat64(byteOffset /* , littleEndian */ ) { + return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52); + }, + setInt8: function setInt8(byteOffset, value) { + set(this, 1, byteOffset, packInt8, value); + }, + setUint8: function setUint8(byteOffset, value) { + set(this, 1, byteOffset, packInt8, value); + }, + setInt16: function setInt16(byteOffset, value /* , littleEndian */ ) { + set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setUint16: function setUint16(byteOffset, value /* , littleEndian */ ) { + set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setInt32: function setInt32(byteOffset, value /* , littleEndian */ ) { + set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setUint32: function setUint32(byteOffset, value /* , littleEndian */ ) { + set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setFloat32: function setFloat32(byteOffset, value /* , littleEndian */ ) { + set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setFloat64: function setFloat64(byteOffset, value /* , littleEndian */ ) { + set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined); + } + }); + } else { + if (!fails(function () { + NativeArrayBuffer(1); + }) || !fails(function () { + new NativeArrayBuffer( - 1); // eslint-disable-line no-new + }) || fails(function () { + new NativeArrayBuffer(); // eslint-disable-line no-new + new NativeArrayBuffer(1.5); // eslint-disable-line no-new + new NativeArrayBuffer(NaN); // eslint-disable-line no-new + return NativeArrayBuffer.name != ARRAY_BUFFER; + })) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer); + return new NativeArrayBuffer(toIndex(length)); + }; + var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE] = NativeArrayBuffer[PROTOTYPE]; + for (var keys = getOwnPropertyNames(NativeArrayBuffer), j = 0, key; keys.length > j; ) { + if (!((key = keys[j++]) in $ArrayBuffer)) { + createNonEnumerableProperty($ArrayBuffer, key, NativeArrayBuffer[key]); + } + } + ArrayBufferPrototype.constructor = $ArrayBuffer; + } // WebKit bug - the same parent prototype for typed arrays and data view + + if (setPrototypeOf && getPrototypeOf($DataViewPrototype) !== ObjectPrototype) { + setPrototypeOf($DataViewPrototype, ObjectPrototype); + } // iOS Safari 7.x bug + + var testView = new $DataView(new $ArrayBuffer(2)); + var nativeSetInt8 = $DataViewPrototype.setInt8; + testView.setInt8(0, 2147483648); + testView.setInt8(1, 2147483649); + if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll($DataViewPrototype, { + setInt8: function setInt8(byteOffset, value) { + nativeSetInt8.call(this, byteOffset, value << 24 >> 24); + }, + setUint8: function setUint8(byteOffset, value) { + nativeSetInt8.call(this, byteOffset, value << 24 >> 24); + } + }, { + unsafe: true + }); + } + setToStringTag($ArrayBuffer, ARRAY_BUFFER); + setToStringTag($DataView, DATA_VIEW); + module.exports = { + ArrayBuffer: $ArrayBuffer, + DataView: $DataView + }; + }, + { + '../internals/an-instance': 27, + '../internals/array-buffer-native': 29, + '../internals/array-fill': 33, + '../internals/create-non-enumerable-property': 56, + '../internals/descriptors': 61, + '../internals/fails': 69, + '../internals/global': 78, + '../internals/ieee754': 84, + '../internals/internal-state': 89, + '../internals/object-define-property': 111, + '../internals/object-get-own-property-names': 114, + '../internals/object-get-prototype-of': 116, + '../internals/object-set-prototype-of': 120, + '../internals/redefine-all': 126, + '../internals/set-to-string-tag': 136, + '../internals/to-index': 152, + '../internals/to-integer': 154, + '../internals/to-length': 155 + } + ], + 32: [ + function (_dereq_, module, exports) { + 'use strict'; + var toObject = _dereq_('../internals/to-object'); + var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); + var toLength = _dereq_('../internals/to-length'); + var min = Math.min; + // `Array.prototype.copyWithin` method implementation + // https://tc39.github.io/ecma262/#sec-array.prototype.copywithin + module.exports = [ + ].copyWithin || function copyWithin(target /* = 0 */ , start /* = 0, end = @length */ ) { + var O = toObject(this); + var len = toLength(O.length); + var to = toAbsoluteIndex(target, len); + var from = toAbsoluteIndex(start, len); + var end = arguments.length > 2 ? arguments[2] : undefined; + var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); + var inc = 1; + if (from < to && to < from + count) { + inc = - 1; + from += count - 1; + to += count - 1; + } + while (count-- > 0) { + if (from in O) O[to] = O[from]; + else delete O[to]; + to += inc; + from += inc; + } + return O; + }; + }, + { + '../internals/to-absolute-index': 151, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 33: [ + function (_dereq_, module, exports) { + 'use strict'; + var toObject = _dereq_('../internals/to-object'); + var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); + var toLength = _dereq_('../internals/to-length'); + // `Array.prototype.fill` method implementation + // https://tc39.github.io/ecma262/#sec-array.prototype.fill + module.exports = function fill(value /* , start = 0, end = @length */ ) { + var O = toObject(this); + var length = toLength(O.length); + var argumentsLength = arguments.length; + var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length); + var end = argumentsLength > 2 ? arguments[2] : undefined; + var endPos = end === undefined ? length : toAbsoluteIndex(end, length); + while (endPos > index) O[index++] = value; + return O; + }; + }, + { + '../internals/to-absolute-index': 151, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 34: [ + function (_dereq_, module, exports) { + 'use strict'; + var $forEach = _dereq_('../internals/array-iteration').forEach; + var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var STRICT_METHOD = arrayMethodIsStrict('forEach'); + var USES_TO_LENGTH = arrayMethodUsesToLength('forEach'); + // `Array.prototype.forEach` method implementation + // https://tc39.github.io/ecma262/#sec-array.prototype.foreach + module.exports = !STRICT_METHOD || !USES_TO_LENGTH ? function forEach(callbackfn /* , thisArg */ ) { + return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + : [ + ].forEach; + }, + { + '../internals/array-iteration': 37, + '../internals/array-method-is-strict': 40, + '../internals/array-method-uses-to-length': 41 + } + ], + 35: [ + function (_dereq_, module, exports) { + 'use strict'; + var bind = _dereq_('../internals/function-bind-context'); + var toObject = _dereq_('../internals/to-object'); + var callWithSafeIterationClosing = _dereq_('../internals/call-with-safe-iteration-closing'); + var isArrayIteratorMethod = _dereq_('../internals/is-array-iterator-method'); + var toLength = _dereq_('../internals/to-length'); + var createProperty = _dereq_('../internals/create-property'); + var getIteratorMethod = _dereq_('../internals/get-iterator-method'); + // `Array.from` method implementation + // https://tc39.github.io/ecma262/#sec-array.from + module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */ ) { + var O = toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var argumentsLength = arguments.length; + var mapfn = argumentsLength > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var iteratorMethod = getIteratorMethod(O); + var index = 0; + var length, + result, + step, + iterator, + next, + value; + if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); + // if the target is not iterable or it's an array with the default iterator - use a simple case + if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) { + iterator = iteratorMethod.call(O); + next = iterator.next; + result = new C(); + for (; !(step = next.call(iterator)).done; index++) { + value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [ + step.value, + index + ], true) : step.value; + createProperty(result, index, value); + } + } else { + length = toLength(O.length); + result = new C(length); + for (; length > index; index++) { + value = mapping ? mapfn(O[index], index) : O[index]; + createProperty(result, index, value); + } + } + result.length = index; + return result; + }; + }, + { + '../internals/call-with-safe-iteration-closing': 44, + '../internals/create-property': 58, + '../internals/function-bind-context': 73, + '../internals/get-iterator-method': 76, + '../internals/is-array-iterator-method': 90, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 36: [ + function (_dereq_, module, exports) { + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var toLength = _dereq_('../internals/to-length'); + var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); + // `Array.prototype.{ indexOf, includes }` methods implementation + var createMethod = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIndexedObject($this); + var length = toLength(O.length); + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (; length > index; index++) { + if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; + } + return !IS_INCLUDES && - 1; + }; + }; + module.exports = { + // `Array.prototype.includes` method + // https://tc39.github.io/ecma262/#sec-array.prototype.includes + includes: createMethod(true), + // `Array.prototype.indexOf` method + // https://tc39.github.io/ecma262/#sec-array.prototype.indexof + indexOf: createMethod(false) + }; + }, + { + '../internals/to-absolute-index': 151, + '../internals/to-indexed-object': 153, + '../internals/to-length': 155 + } + ], + 37: [ + function (_dereq_, module, exports) { + var bind = _dereq_('../internals/function-bind-context'); + var IndexedObject = _dereq_('../internals/indexed-object'); + var toObject = _dereq_('../internals/to-object'); + var toLength = _dereq_('../internals/to-length'); + var arraySpeciesCreate = _dereq_('../internals/array-species-create'); + var push = [ + ].push; + // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation + var createMethod = function (TYPE) { + var IS_MAP = TYPE == 1; + var IS_FILTER = TYPE == 2; + var IS_SOME = TYPE == 3; + var IS_EVERY = TYPE == 4; + var IS_FIND_INDEX = TYPE == 6; + var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; + return function ($this, callbackfn, that, specificCreate) { + var O = toObject($this); + var self = IndexedObject(O); + var boundFunction = bind(callbackfn, that, 3); + var length = toLength(self.length); + var index = 0; + var create = specificCreate || arraySpeciesCreate; + var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; + var value, + result; + for (; length > index; index++) if (NO_HOLES || index in self) { + value = self[index]; + result = boundFunction(value, index, O); + if (TYPE) { + if (IS_MAP) target[index] = result; // map + else if (result) switch (TYPE) { + case 3: + return true; + // some + case 5: + return value; + // find + case 6: + return index; + // findIndex + case 2: + push.call(target, value); + // filter + } else if (IS_EVERY) return false; // every + } + } + return IS_FIND_INDEX ? - 1 : IS_SOME || IS_EVERY ? IS_EVERY : target; + }; + }; + module.exports = { + // `Array.prototype.forEach` method + // https://tc39.github.io/ecma262/#sec-array.prototype.foreach + forEach: createMethod(0), + // `Array.prototype.map` method + // https://tc39.github.io/ecma262/#sec-array.prototype.map + map: createMethod(1), + // `Array.prototype.filter` method + // https://tc39.github.io/ecma262/#sec-array.prototype.filter + filter: createMethod(2), + // `Array.prototype.some` method + // https://tc39.github.io/ecma262/#sec-array.prototype.some + some: createMethod(3), + // `Array.prototype.every` method + // https://tc39.github.io/ecma262/#sec-array.prototype.every + every: createMethod(4), + // `Array.prototype.find` method + // https://tc39.github.io/ecma262/#sec-array.prototype.find + find: createMethod(5), + // `Array.prototype.findIndex` method + // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex + findIndex: createMethod(6) + }; + }, + { + '../internals/array-species-create': 43, + '../internals/function-bind-context': 73, + '../internals/indexed-object': 85, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 38: [ + function (_dereq_, module, exports) { + 'use strict'; + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var toInteger = _dereq_('../internals/to-integer'); + var toLength = _dereq_('../internals/to-length'); + var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var min = Math.min; + var nativeLastIndexOf = [ + ].lastIndexOf; + var NEGATIVE_ZERO = !!nativeLastIndexOf && 1 / [ + 1 + ].lastIndexOf(1, - 0) < 0; + var STRICT_METHOD = arrayMethodIsStrict('lastIndexOf'); + // For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method + var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { + ACCESSORS: true, + 1: 0 + }); + var FORCED = NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH; + // `Array.prototype.lastIndexOf` method implementation + // https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof + module.exports = FORCED ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */ ) { + // convert -0 to +0 + if (NEGATIVE_ZERO) return nativeLastIndexOf.apply(this, arguments) || 0; + var O = toIndexedObject(this); + var length = toLength(O.length); + var index = length - 1; + if (arguments.length > 1) index = min(index, toInteger(arguments[1])); + if (index < 0) index = length + index; + for (; index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0; + return - 1; + } + : nativeLastIndexOf; + }, + { + '../internals/array-method-is-strict': 40, + '../internals/array-method-uses-to-length': 41, + '../internals/to-indexed-object': 153, + '../internals/to-integer': 154, + '../internals/to-length': 155 + } + ], + 39: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var V8_VERSION = _dereq_('../internals/engine-v8-version'); + var SPECIES = wellKnownSymbol('species'); + module.exports = function (METHOD_NAME) { + // We can't use this feature detection in V8 since it causes + // deoptimization and serious performance degradation + // https://github.com/zloirock/core-js/issues/677 + return V8_VERSION >= 51 || !fails(function () { + var array = [ + ]; + var constructor = array.constructor = { + }; + constructor[SPECIES] = function () { + return { + foo: 1 + }; + }; + return array[METHOD_NAME](Boolean).foo !== 1; + }); + }; + }, + { + '../internals/engine-v8-version': 66, + '../internals/fails': 69, + '../internals/well-known-symbol': 167 + } + ], + 40: [ + function (_dereq_, module, exports) { + 'use strict'; + var fails = _dereq_('../internals/fails'); + module.exports = function (METHOD_NAME, argument) { + var method = [ + ][METHOD_NAME]; + return !!method && fails(function () { + // eslint-disable-next-line no-useless-call,no-throw-literal + method.call(null, argument || function () { + throw 1; + }, 1); + }); + }; + }, + { + '../internals/fails': 69 + } + ], + 41: [ + function (_dereq_, module, exports) { + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var fails = _dereq_('../internals/fails'); + var has = _dereq_('../internals/has'); + var defineProperty = Object.defineProperty; + var cache = { + }; + var thrower = function (it) { + throw it; + }; + module.exports = function (METHOD_NAME, options) { + if (has(cache, METHOD_NAME)) return cache[METHOD_NAME]; + if (!options) options = { + }; + var method = [ + ][METHOD_NAME]; + var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false; + var argument0 = has(options, 0) ? options[0] : thrower; + var argument1 = has(options, 1) ? options[1] : undefined; + return cache[METHOD_NAME] = !!method && !fails(function () { + if (ACCESSORS && !DESCRIPTORS) return true; + var O = { + length: - 1 + }; + if (ACCESSORS) defineProperty(O, 1, { + enumerable: true, + get: thrower + }); + else O[1] = 1; + method.call(O, argument0, argument1); + }); + }; + }, + { + '../internals/descriptors': 61, + '../internals/fails': 69, + '../internals/has': 79 + } + ], + 42: [ + function (_dereq_, module, exports) { + var aFunction = _dereq_('../internals/a-function'); + var toObject = _dereq_('../internals/to-object'); + var IndexedObject = _dereq_('../internals/indexed-object'); + var toLength = _dereq_('../internals/to-length'); + // `Array.prototype.{ reduce, reduceRight }` methods implementation + var createMethod = function (IS_RIGHT) { + return function (that, callbackfn, argumentsLength, memo) { + aFunction(callbackfn); + var O = toObject(that); + var self = IndexedObject(O); + var length = toLength(O.length); + var index = IS_RIGHT ? length - 1 : 0; + var i = IS_RIGHT ? - 1 : 1; + if (argumentsLength < 2) while (true) { + if (index in self) { + memo = self[index]; + index += i; + break; + } + index += i; + if (IS_RIGHT ? index < 0 : length <= index) { + throw TypeError('Reduce of empty array with no initial value'); + } + } + for (; IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) { + memo = callbackfn(memo, self[index], index, O); + } + return memo; + }; + }; + module.exports = { + // `Array.prototype.reduce` method + // https://tc39.github.io/ecma262/#sec-array.prototype.reduce + left: createMethod(false), + // `Array.prototype.reduceRight` method + // https://tc39.github.io/ecma262/#sec-array.prototype.reduceright + right: createMethod(true) + }; + }, + { + '../internals/a-function': 23, + '../internals/indexed-object': 85, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 43: [ + function (_dereq_, module, exports) { + var isObject = _dereq_('../internals/is-object'); + var isArray = _dereq_('../internals/is-array'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var SPECIES = wellKnownSymbol('species'); + // `ArraySpeciesCreate` abstract operation + // https://tc39.github.io/ecma262/#sec-arrayspeciescreate + module.exports = function (originalArray, length) { + var C; + if (isArray(originalArray)) { + C = originalArray.constructor; + // cross-realm fallback + if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; + else if (isObject(C)) { + C = C[SPECIES]; + if (C === null) C = undefined; + } + } + return new (C === undefined ? Array : C) (length === 0 ? 0 : length); + }; + }, + { + '../internals/is-array': 91, + '../internals/is-object': 93, + '../internals/well-known-symbol': 167 + } + ], + 44: [ + function (_dereq_, module, exports) { + var anObject = _dereq_('../internals/an-object'); + // call something on iterator step with safe closing on error + module.exports = function (iterator, fn, value, ENTRIES) { + try { + return ENTRIES ? fn(anObject(value) [0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch (error) { + var returnMethod = iterator['return']; + if (returnMethod !== undefined) anObject(returnMethod.call(iterator)); + throw error; + } + }; + }, + { + '../internals/an-object': 28 + } + ], + 45: [ + function (_dereq_, module, exports) { + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var ITERATOR = wellKnownSymbol('iterator'); + var SAFE_CLOSING = false; + try { + var called = 0; + var iteratorWithReturn = { + next: function () { + return { + done: !!called++ + }; + }, + 'return': function () { + SAFE_CLOSING = true; + } + }; + iteratorWithReturn[ITERATOR] = function () { + return this; + }; + // eslint-disable-next-line no-throw-literal + Array.from(iteratorWithReturn, function () { + throw 2; + }); + } catch (error) { /* empty */ + } + module.exports = function (exec, SKIP_CLOSING) { + if (!SKIP_CLOSING && !SAFE_CLOSING) return false; + var ITERATION_SUPPORT = false; + try { + var object = { + }; + object[ITERATOR] = function () { + return { + next: function () { + return { + done: ITERATION_SUPPORT = true + }; + } + }; + }; + exec(object); + } catch (error) { /* empty */ + } + return ITERATION_SUPPORT; + }; + }, + { + '../internals/well-known-symbol': 167 + } + ], + 46: [ + function (_dereq_, module, exports) { + var toString = { + }.toString; + module.exports = function (it) { + return toString.call(it).slice(8, - 1); + }; + }, + { + } + ], + 47: [ + function (_dereq_, module, exports) { + var TO_STRING_TAG_SUPPORT = _dereq_('../internals/to-string-tag-support'); + var classofRaw = _dereq_('../internals/classof-raw'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + // ES3 wrong here + var CORRECT_ARGUMENTS = classofRaw(function () { + return arguments; + }()) == 'Arguments'; + // fallback for IE11 Script Access Denied error + var tryGet = function (it, key) { + try { + return it[key]; + } catch (error) { /* empty */ + } + }; + // getting tag from ES6+ `Object.prototype.toString` + module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) { + var O, + tag, + result; + return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case + : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag // builtinTag case + : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback + : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result; + }; + }, + { + '../internals/classof-raw': 46, + '../internals/to-string-tag-support': 160, + '../internals/well-known-symbol': 167 + } + ], + 48: [ + function (_dereq_, module, exports) { + 'use strict'; + var defineProperty = _dereq_('../internals/object-define-property').f; + var create = _dereq_('../internals/object-create'); + var redefineAll = _dereq_('../internals/redefine-all'); + var bind = _dereq_('../internals/function-bind-context'); + var anInstance = _dereq_('../internals/an-instance'); + var iterate = _dereq_('../internals/iterate'); + var defineIterator = _dereq_('../internals/define-iterator'); + var setSpecies = _dereq_('../internals/set-species'); + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var fastKey = _dereq_('../internals/internal-metadata').fastKey; + var InternalStateModule = _dereq_('../internals/internal-state'); + var setInternalState = InternalStateModule.set; + var internalStateGetterFor = InternalStateModule.getterFor; + module.exports = { + getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, CONSTRUCTOR_NAME); + setInternalState(that, { + type: CONSTRUCTOR_NAME, + index: create(null), + first: undefined, + last: undefined, + size: 0 + }); + if (!DESCRIPTORS) that.size = 0; + if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP); + }); + var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); + var define = function (that, key, value) { + var state = getInternalState(that); + var entry = getEntry(that, key); + var previous, + index; + // change existing entry + if (entry) { + entry.value = value; + // create new entry + } else { + state.last = entry = { + index: index = fastKey(key, true), + key: key, + value: value, + previous: previous = state.last, + next: undefined, + removed: false + }; + if (!state.first) state.first = entry; + if (previous) previous.next = entry; + if (DESCRIPTORS) state.size++; + else that.size++; + // add to index + if (index !== 'F') state.index[index] = entry; + } + return that; + }; + var getEntry = function (that, key) { + var state = getInternalState(that); + // fast case + var index = fastKey(key); + var entry; + if (index !== 'F') return state.index[index]; + // frozen object case + for (entry = state.first; entry; entry = entry.next) { + if (entry.key == key) return entry; + } + }; + redefineAll(C.prototype, { + // 23.1.3.1 Map.prototype.clear() + // 23.2.3.2 Set.prototype.clear() + clear: function clear() { + var that = this; + var state = getInternalState(that); + var data = state.index; + var entry = state.first; + while (entry) { + entry.removed = true; + if (entry.previous) entry.previous = entry.previous.next = undefined; + delete data[entry.index]; + entry = entry.next; + } + state.first = state.last = undefined; + if (DESCRIPTORS) state.size = 0; + else that.size = 0; + }, + // 23.1.3.3 Map.prototype.delete(key) + // 23.2.3.4 Set.prototype.delete(value) + 'delete': function (key) { + var that = this; + var state = getInternalState(that); + var entry = getEntry(that, key); + if (entry) { + var next = entry.next; + var prev = entry.previous; + delete state.index[entry.index]; + entry.removed = true; + if (prev) prev.next = next; + if (next) next.previous = prev; + if (state.first == entry) state.first = next; + if (state.last == entry) state.last = prev; + if (DESCRIPTORS) state.size--; + else that.size--; + } + return !!entry; + }, + // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) + // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) + forEach: function forEach(callbackfn /* , that = undefined */ ) { + var state = getInternalState(this); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var entry; + while (entry = entry ? entry.next : state.first) { + boundFunction(entry.value, entry.key, this); + // revert to the last existing entry + while (entry && entry.removed) entry = entry.previous; + } + }, + // 23.1.3.7 Map.prototype.has(key) + // 23.2.3.7 Set.prototype.has(value) + has: function has(key) { + return !!getEntry(this, key); + } + }); + redefineAll(C.prototype, IS_MAP ? { + // 23.1.3.6 Map.prototype.get(key) + get: function get(key) { + var entry = getEntry(this, key); + return entry && entry.value; + }, + // 23.1.3.9 Map.prototype.set(key, value) + set: function set(key, value) { + return define(this, key === 0 ? 0 : key, value); + } + } + : { + // 23.2.3.1 Set.prototype.add(value) + add: function add(value) { + return define(this, value = value === 0 ? 0 : value, value); + } + }); + if (DESCRIPTORS) defineProperty(C.prototype, 'size', { + get: function () { + return getInternalState(this).size; + } + }); + return C; + }, + setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) { + var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator'; + var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME); + var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); + // add .keys, .values, .entries, [@@iterator] + // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 + defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) { + setInternalState(this, { + type: ITERATOR_NAME, + target: iterated, + state: getInternalCollectionState(iterated), + kind: kind, + last: undefined + }); + }, function () { + var state = getInternalIteratorState(this); + var kind = state.kind; + var entry = state.last; + // revert to the last existing entry + while (entry && entry.removed) entry = entry.previous; + // get next entry + if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) { + // or finish the iteration + state.target = undefined; + return { + value: undefined, + done: true + }; + } // return step by kind + + if (kind == 'keys') return { + value: entry.key, + done: false + }; + if (kind == 'values') return { + value: entry.value, + done: false + }; + return { + value: [ + entry.key, + entry.value + ], + done: false + }; + }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); + // add [@@species], 23.1.2.2, 23.2.2.2 + setSpecies(CONSTRUCTOR_NAME); + } + }; + }, + { + '../internals/an-instance': 27, + '../internals/define-iterator': 59, + '../internals/descriptors': 61, + '../internals/function-bind-context': 73, + '../internals/internal-metadata': 88, + '../internals/internal-state': 89, + '../internals/iterate': 96, + '../internals/object-create': 109, + '../internals/object-define-property': 111, + '../internals/redefine-all': 126, + '../internals/set-species': 135 + } + ], + 49: [ + function (_dereq_, module, exports) { + 'use strict'; + var redefineAll = _dereq_('../internals/redefine-all'); + var getWeakData = _dereq_('../internals/internal-metadata').getWeakData; + var anObject = _dereq_('../internals/an-object'); + var isObject = _dereq_('../internals/is-object'); + var anInstance = _dereq_('../internals/an-instance'); + var iterate = _dereq_('../internals/iterate'); + var ArrayIterationModule = _dereq_('../internals/array-iteration'); + var $has = _dereq_('../internals/has'); + var InternalStateModule = _dereq_('../internals/internal-state'); + var setInternalState = InternalStateModule.set; + var internalStateGetterFor = InternalStateModule.getterFor; + var find = ArrayIterationModule.find; + var findIndex = ArrayIterationModule.findIndex; + var id = 0; + // fallback for uncaught frozen keys + var uncaughtFrozenStore = function (store) { + return store.frozen || (store.frozen = new UncaughtFrozenStore()); + }; + var UncaughtFrozenStore = function () { + this.entries = [ + ]; + }; + var findUncaughtFrozen = function (store, key) { + return find(store.entries, function (it) { + return it[0] === key; + }); + }; + UncaughtFrozenStore.prototype = { + get: function (key) { + var entry = findUncaughtFrozen(this, key); + if (entry) return entry[1]; + }, + has: function (key) { + return !!findUncaughtFrozen(this, key); + }, + set: function (key, value) { + var entry = findUncaughtFrozen(this, key); + if (entry) entry[1] = value; + else this.entries.push([key, + value]); + }, + 'delete': function (key) { + var index = findIndex(this.entries, function (it) { + return it[0] === key; + }); + if (~index) this.entries.splice(index, 1); + return !!~index; + } + }; + module.exports = { + getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, CONSTRUCTOR_NAME); + setInternalState(that, { + type: CONSTRUCTOR_NAME, + id: id++, + frozen: undefined + }); + if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP); + }); + var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); + var define = function (that, key, value) { + var state = getInternalState(that); + var data = getWeakData(anObject(key), true); + if (data === true) uncaughtFrozenStore(state).set(key, value); + else data[state.id] = value; + return that; + }; + redefineAll(C.prototype, { + // 23.3.3.2 WeakMap.prototype.delete(key) + // 23.4.3.3 WeakSet.prototype.delete(value) + 'delete': function (key) { + var state = getInternalState(this); + if (!isObject(key)) return false; + var data = getWeakData(key); + if (data === true) return uncaughtFrozenStore(state) ['delete'](key); + return data && $has(data, state.id) && delete data[state.id]; + }, + // 23.3.3.4 WeakMap.prototype.has(key) + // 23.4.3.4 WeakSet.prototype.has(value) + has: function has(key) { + var state = getInternalState(this); + if (!isObject(key)) return false; + var data = getWeakData(key); + if (data === true) return uncaughtFrozenStore(state).has(key); + return data && $has(data, state.id); + } + }); + redefineAll(C.prototype, IS_MAP ? { + // 23.3.3.3 WeakMap.prototype.get(key) + get: function get(key) { + var state = getInternalState(this); + if (isObject(key)) { + var data = getWeakData(key); + if (data === true) return uncaughtFrozenStore(state).get(key); + return data ? data[state.id] : undefined; + } + }, + // 23.3.3.5 WeakMap.prototype.set(key, value) + set: function set(key, value) { + return define(this, key, value); + } + } + : { + // 23.4.3.1 WeakSet.prototype.add(value) + add: function add(value) { + return define(this, value, true); + } + }); + return C; + } + }; + }, + { + '../internals/an-instance': 27, + '../internals/an-object': 28, + '../internals/array-iteration': 37, + '../internals/has': 79, + '../internals/internal-metadata': 88, + '../internals/internal-state': 89, + '../internals/is-object': 93, + '../internals/iterate': 96, + '../internals/redefine-all': 126 + } + ], + 50: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var global = _dereq_('../internals/global'); + var isForced = _dereq_('../internals/is-forced'); + var redefine = _dereq_('../internals/redefine'); + var InternalMetadataModule = _dereq_('../internals/internal-metadata'); + var iterate = _dereq_('../internals/iterate'); + var anInstance = _dereq_('../internals/an-instance'); + var isObject = _dereq_('../internals/is-object'); + var fails = _dereq_('../internals/fails'); + var checkCorrectnessOfIteration = _dereq_('../internals/check-correctness-of-iteration'); + var setToStringTag = _dereq_('../internals/set-to-string-tag'); + var inheritIfRequired = _dereq_('../internals/inherit-if-required'); + module.exports = function (CONSTRUCTOR_NAME, wrapper, common) { + var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== - 1; + var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== - 1; + var ADDER = IS_MAP ? 'set' : 'add'; + var NativeConstructor = global[CONSTRUCTOR_NAME]; + var NativePrototype = NativeConstructor && NativeConstructor.prototype; + var Constructor = NativeConstructor; + var exported = { + }; + var fixMethod = function (KEY) { + var nativeMethod = NativePrototype[KEY]; + redefine(NativePrototype, KEY, KEY == 'add' ? function add(value) { + nativeMethod.call(this, value === 0 ? 0 : value); + return this; + } + : KEY == 'delete' ? function (key) { + return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); + } + : KEY == 'get' ? function get(key) { + return IS_WEAK && !isObject(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key); + } + : KEY == 'has' ? function has(key) { + return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); + } + : function set(key, value) { + nativeMethod.call(this, key === 0 ? 0 : key, value); + return this; + }); + }; + // eslint-disable-next-line max-len + if (isForced(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () { + new NativeConstructor().entries().next(); + })))) { + // create collection constructor + Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER); + InternalMetadataModule.REQUIRED = true; + } else if (isForced(CONSTRUCTOR_NAME, true)) { + var instance = new Constructor(); + // early implementations not supports chaining + var HASNT_CHAINING = instance[ADDER](IS_WEAK ? { + } + : - 0, 1) != instance; + // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false + var THROWS_ON_PRIMITIVES = fails(function () { + instance.has(1); + }); + // most early implementations doesn't supports iterables, most modern - not close it correctly + // eslint-disable-next-line no-new + var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { + new NativeConstructor(iterable); + }); + // for early implementations -0 and +0 not the same + var BUGGY_ZERO = !IS_WEAK && fails(function () { + // V8 ~ Chromium 42- fails only with 5+ elements + var $instance = new NativeConstructor(); + var index = 5; + while (index--) $instance[ADDER](index, index); + return !$instance.has( - 0); + }); + if (!ACCEPT_ITERABLES) { + Constructor = wrapper(function (dummy, iterable) { + anInstance(dummy, Constructor, CONSTRUCTOR_NAME); + var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor); + if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP); + return that; + }); + Constructor.prototype = NativePrototype; + NativePrototype.constructor = Constructor; + } + if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { + fixMethod('delete'); + fixMethod('has'); + IS_MAP && fixMethod('get'); + } + if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); + // weak collections should not contains .clear method + if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear; + } + exported[CONSTRUCTOR_NAME] = Constructor; + $({ + global: true, + forced: Constructor != NativeConstructor + }, exported); + setToStringTag(Constructor, CONSTRUCTOR_NAME); + if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP); + return Constructor; + }; + }, + { + '../internals/an-instance': 27, + '../internals/check-correctness-of-iteration': 45, + '../internals/export': 68, + '../internals/fails': 69, + '../internals/global': 78, + '../internals/inherit-if-required': 86, + '../internals/internal-metadata': 88, + '../internals/is-forced': 92, + '../internals/is-object': 93, + '../internals/iterate': 96, + '../internals/redefine': 127, + '../internals/set-to-string-tag': 136 + } + ], + 51: [ + function (_dereq_, module, exports) { + var has = _dereq_('../internals/has'); + var ownKeys = _dereq_('../internals/own-keys'); + var getOwnPropertyDescriptorModule = _dereq_('../internals/object-get-own-property-descriptor'); + var definePropertyModule = _dereq_('../internals/object-define-property'); + module.exports = function (target, source) { + var keys = ownKeys(source); + var defineProperty = definePropertyModule.f; + var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); + } + }; + }, + { + '../internals/has': 79, + '../internals/object-define-property': 111, + '../internals/object-get-own-property-descriptor': 112, + '../internals/own-keys': 122 + } + ], + 52: [ + function (_dereq_, module, exports) { + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var MATCH = wellKnownSymbol('match'); + module.exports = function (METHOD_NAME) { + var regexp = /./; + try { + '/./'[METHOD_NAME](regexp); + } catch (e) { + try { + regexp[MATCH] = false; + return '/./'[METHOD_NAME](regexp); + } catch (f) { /* empty */ + } + } + return false; + }; + }, + { + '../internals/well-known-symbol': 167 + } + ], + 53: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + module.exports = !fails(function () { + function F() { /* empty */ + } + F.prototype.constructor = null; + return Object.getPrototypeOf(new F()) !== F.prototype; + }); + }, + { + '../internals/fails': 69 + } + ], + 54: [ + function (_dereq_, module, exports) { + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var quot = /"/g; + // B.2.3.2.1 CreateHTML(string, tag, attribute, value) + // https://tc39.github.io/ecma262/#sec-createhtml + module.exports = function (string, tag, attribute, value) { + var S = String(requireObjectCoercible(string)); + var p1 = '<' + tag; + if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; + return p1 + '>' + S + ''; + }; + }, + { + '../internals/require-object-coercible': 132 + } + ], + 55: [ + function (_dereq_, module, exports) { + 'use strict'; + var IteratorPrototype = _dereq_('../internals/iterators-core').IteratorPrototype; + var create = _dereq_('../internals/object-create'); + var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor'); + var setToStringTag = _dereq_('../internals/set-to-string-tag'); + var Iterators = _dereq_('../internals/iterators'); + var returnThis = function () { + return this; + }; + module.exports = function (IteratorConstructor, NAME, next) { + var TO_STRING_TAG = NAME + ' Iterator'; + IteratorConstructor.prototype = create(IteratorPrototype, { + next: createPropertyDescriptor(1, next) + }); + setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true); + Iterators[TO_STRING_TAG] = returnThis; + return IteratorConstructor; + }; + }, + { + '../internals/create-property-descriptor': 57, + '../internals/iterators': 98, + '../internals/iterators-core': 97, + '../internals/object-create': 109, + '../internals/set-to-string-tag': 136 + } + ], + 56: [ + function (_dereq_, module, exports) { + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var definePropertyModule = _dereq_('../internals/object-define-property'); + var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor'); + module.exports = DESCRIPTORS ? function (object, key, value) { + return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); + } + : function (object, key, value) { + object[key] = value; + return object; + }; + }, + { + '../internals/create-property-descriptor': 57, + '../internals/descriptors': 61, + '../internals/object-define-property': 111 + } + ], + 57: [ + function (_dereq_, module, exports) { + module.exports = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; + }; + }, + { + } + ], + 58: [ + function (_dereq_, module, exports) { + 'use strict'; + var toPrimitive = _dereq_('../internals/to-primitive'); + var definePropertyModule = _dereq_('../internals/object-define-property'); + var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor'); + module.exports = function (object, key, value) { + var propertyKey = toPrimitive(key); + if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value)); + else object[propertyKey] = value; + }; + }, + { + '../internals/create-property-descriptor': 57, + '../internals/object-define-property': 111, + '../internals/to-primitive': 159 + } + ], + 59: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var createIteratorConstructor = _dereq_('../internals/create-iterator-constructor'); + var getPrototypeOf = _dereq_('../internals/object-get-prototype-of'); + var setPrototypeOf = _dereq_('../internals/object-set-prototype-of'); + var setToStringTag = _dereq_('../internals/set-to-string-tag'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var redefine = _dereq_('../internals/redefine'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var IS_PURE = _dereq_('../internals/is-pure'); + var Iterators = _dereq_('../internals/iterators'); + var IteratorsCore = _dereq_('../internals/iterators-core'); + var IteratorPrototype = IteratorsCore.IteratorPrototype; + var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS; + var ITERATOR = wellKnownSymbol('iterator'); + var KEYS = 'keys'; + var VALUES = 'values'; + var ENTRIES = 'entries'; + var returnThis = function () { + return this; + }; + module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { + createIteratorConstructor(IteratorConstructor, NAME, next); + var getIterationMethod = function (KIND) { + if (KIND === DEFAULT && defaultIterator) return defaultIterator; + if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND]; + switch (KIND) { + case KEYS: + return function keys() { + return new IteratorConstructor(this, KIND); + }; + case VALUES: + return function values() { + return new IteratorConstructor(this, KIND); + }; + case ENTRIES: + return function entries() { + return new IteratorConstructor(this, KIND); + }; + } + return function () { + return new IteratorConstructor(this); + }; + }; + var TO_STRING_TAG = NAME + ' Iterator'; + var INCORRECT_VALUES_NAME = false; + var IterablePrototype = Iterable.prototype; + var nativeIterator = IterablePrototype[ITERATOR] || IterablePrototype['@@iterator'] || DEFAULT && IterablePrototype[DEFAULT]; + var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT); + var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; + var CurrentIteratorPrototype, + methods, + KEY; + // fix native + if (anyNativeIterator) { + CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable())); + if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) { + if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) { + if (setPrototypeOf) { + setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype); + } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') { + createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis); + } + } // Set @@toStringTag to native iterators + + setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true); + if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis; + } + } // fix Array#{values, @@iterator}.name in V8 / FF + + if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) { + INCORRECT_VALUES_NAME = true; + defaultIterator = function values() { + return nativeIterator.call(this); + }; + } // define iterator + + if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) { + createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator); + } + Iterators[NAME] = defaultIterator; + // export additional methods + if (DEFAULT) { + methods = { + values: getIterationMethod(VALUES), + keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), + entries: getIterationMethod(ENTRIES) + }; + if (FORCED) for (KEY in methods) { + if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { + redefine(IterablePrototype, KEY, methods[KEY]); + } + } else $({ + target: NAME, + proto: true, + forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME + }, methods); + } + return methods; + }; + }, + { + '../internals/create-iterator-constructor': 55, + '../internals/create-non-enumerable-property': 56, + '../internals/export': 68, + '../internals/is-pure': 94, + '../internals/iterators': 98, + '../internals/iterators-core': 97, + '../internals/object-get-prototype-of': 116, + '../internals/object-set-prototype-of': 120, + '../internals/redefine': 127, + '../internals/set-to-string-tag': 136, + '../internals/well-known-symbol': 167 + } + ], + 60: [ + function (_dereq_, module, exports) { + var path = _dereq_('../internals/path'); + var has = _dereq_('../internals/has'); + var wrappedWellKnownSymbolModule = _dereq_('../internals/well-known-symbol-wrapped'); + var defineProperty = _dereq_('../internals/object-define-property').f; + module.exports = function (NAME) { + var Symbol = path.Symbol || (path.Symbol = { + }); + if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, { + value: wrappedWellKnownSymbolModule.f(NAME) + }); + }; + }, + { + '../internals/has': 79, + '../internals/object-define-property': 111, + '../internals/path': 123, + '../internals/well-known-symbol-wrapped': 166 + } + ], + 61: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + // Thank's IE8 for his funny defineProperty + module.exports = !fails(function () { + return Object.defineProperty({ + }, 1, { + get: function () { + return 7; + } + }) [1] != 7; + }); + }, + { + '../internals/fails': 69 + } + ], + 62: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var isObject = _dereq_('../internals/is-object'); + var document = global.document; + // typeof document.createElement is 'object' in old IE + var EXISTS = isObject(document) && isObject(document.createElement); + module.exports = function (it) { + return EXISTS ? document.createElement(it) : { + }; + }; + }, + { + '../internals/global': 78, + '../internals/is-object': 93 + } + ], + 63: [ + function (_dereq_, module, exports) { + // iterable DOM collections + // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods + module.exports = { + CSSRuleList: 0, + CSSStyleDeclaration: 0, + CSSValueList: 0, + ClientRectList: 0, + DOMRectList: 0, + DOMStringList: 0, + DOMTokenList: 1, + DataTransferItemList: 0, + FileList: 0, + HTMLAllCollection: 0, + HTMLCollection: 0, + HTMLFormElement: 0, + HTMLSelectElement: 0, + MediaList: 0, + MimeTypeArray: 0, + NamedNodeMap: 0, + NodeList: 1, + PaintRequestList: 0, + Plugin: 0, + PluginArray: 0, + SVGLengthList: 0, + SVGNumberList: 0, + SVGPathSegList: 0, + SVGPointList: 0, + SVGStringList: 0, + SVGTransformList: 0, + SourceBufferList: 0, + StyleSheetList: 0, + TextTrackCueList: 0, + TextTrackList: 0, + TouchList: 0 + }; + }, + { + } + ], + 64: [ + function (_dereq_, module, exports) { + var userAgent = _dereq_('../internals/engine-user-agent'); + module.exports = /(iphone|ipod|ipad).*applewebkit/i.test(userAgent); + }, + { + '../internals/engine-user-agent': 65 + } + ], + 65: [ + function (_dereq_, module, exports) { + var getBuiltIn = _dereq_('../internals/get-built-in'); + module.exports = getBuiltIn('navigator', 'userAgent') || ''; + }, + { + '../internals/get-built-in': 75 + } + ], + 66: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var userAgent = _dereq_('../internals/engine-user-agent'); + var process = global.process; + var versions = process && process.versions; + var v8 = versions && versions.v8; + var match, + version; + if (v8) { + match = v8.split('.'); + version = match[0] + match[1]; + } else if (userAgent) { + match = userAgent.match(/Edge\/(\d+)/); + if (!match || match[1] >= 74) { + match = userAgent.match(/Chrome\/(\d+)/); + if (match) version = match[1]; + } + } + module.exports = version && + version; + }, + { + '../internals/engine-user-agent': 65, + '../internals/global': 78 + } + ], + 67: [ + function (_dereq_, module, exports) { + // IE8- don't enum bug keys + module.exports = [ + 'constructor', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'toLocaleString', + 'toString', + 'valueOf' + ]; + }, + { + } + ], + 68: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var getOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f; + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var redefine = _dereq_('../internals/redefine'); + var setGlobal = _dereq_('../internals/set-global'); + var copyConstructorProperties = _dereq_('../internals/copy-constructor-properties'); + var isForced = _dereq_('../internals/is-forced'); + /* + options.target - name of the target object + options.global - target is the global object + options.stat - export as static methods of target + options.proto - export as prototype methods of target + options.real - real prototype method for the `pure` version + options.forced - export even if the native feature is available + options.bind - bind methods to the target, required for the `pure` version + options.wrap - wrap constructors to preventing global pollution, required for the `pure` version + options.unsafe - use the simple assignment of property instead of delete + defineProperty + options.sham - add a flag to not completely full polyfills + options.enumerable - export as enumerable property + options.noTargetGet - prevent calling a getter on target +*/ + module.exports = function (options, source) { + var TARGET = options.target; + var GLOBAL = options.global; + var STATIC = options.stat; + var FORCED, + target, + key, + targetProperty, + sourceProperty, + descriptor; + if (GLOBAL) { + target = global; + } else if (STATIC) { + target = global[TARGET] || setGlobal(TARGET, { + }); + } else { + target = (global[TARGET] || { + }).prototype; + } + if (target) for (key in source) { + sourceProperty = source[key]; + if (options.noTargetGet) { + descriptor = getOwnPropertyDescriptor(target, key); + targetProperty = descriptor && descriptor.value; + } else targetProperty = target[key]; + FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); + // contained in target + if (!FORCED && targetProperty !== undefined) { + if (typeof sourceProperty === typeof targetProperty) continue; + copyConstructorProperties(sourceProperty, targetProperty); + } // add a flag to not completely full polyfills + + if (options.sham || targetProperty && targetProperty.sham) { + createNonEnumerableProperty(sourceProperty, 'sham', true); + } // extend global + + redefine(target, key, sourceProperty, options); + } + }; + }, + { + '../internals/copy-constructor-properties': 51, + '../internals/create-non-enumerable-property': 56, + '../internals/global': 78, + '../internals/is-forced': 92, + '../internals/object-get-own-property-descriptor': 112, + '../internals/redefine': 127, + '../internals/set-global': 134 + } + ], + 69: [ + function (_dereq_, module, exports) { + module.exports = function (exec) { + try { + return !!exec(); + } catch (error) { + return true; + } + }; + }, + { + } + ], + 70: [ + function (_dereq_, module, exports) { + 'use strict'; + // TODO: Remove from `core-js@4` since it's moved to entry points + _dereq_('../modules/es.regexp.exec'); + var redefine = _dereq_('../internals/redefine'); + var fails = _dereq_('../internals/fails'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var regexpExec = _dereq_('../internals/regexp-exec'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var SPECIES = wellKnownSymbol('species'); + var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () { + // #replace needs built-in support for named groups. + // #match works fine because it just return the exec results, even if it has + // a "grops" property. + var re = /./; + re.exec = function () { + var result = [ + ]; + result.groups = { + a: '7' + }; + return result; + }; + return ''.replace(re, '$') !== '7'; + }); + // IE <= 11 replaces $0 with the whole match, as if it was $& + // https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0 + var REPLACE_KEEPS_$0 = function () { + return 'a'.replace(/./, '$0') === '$0'; + }(); + var REPLACE = wellKnownSymbol('replace'); + // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string + var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = function () { + if (/./[REPLACE]) { + return /./[REPLACE]('a', '$0') === ''; + } + return false; + }(); + // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec + // Weex JS has frozen built-in prototypes, so use try / catch wrapper + var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () { + var re = /(?:)/; + var originalExec = re.exec; + re.exec = function () { + return originalExec.apply(this, arguments); + }; + var result = 'ab'.split(re); + return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b'; + }); + module.exports = function (KEY, length, exec, sham) { + var SYMBOL = wellKnownSymbol(KEY); + var DELEGATES_TO_SYMBOL = !fails(function () { + // String methods call symbol-named RegEp methods + var O = { + }; + O[SYMBOL] = function () { + return 7; + }; + return ''[KEY](O) != 7; + }); + var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () { + // Symbol-named RegExp methods call .exec + var execCalled = false; + var re = /a/; + if (KEY === 'split') { + // We can't use real regex here since it causes deoptimization + // and serious performance degradation in V8 + // https://github.com/zloirock/core-js/issues/306 + re = { + }; + // RegExp[@@split] doesn't call the regex's exec method, but first creates + // a new one. We need to return the patched regex when creating the new one. + re.constructor = { + }; + re.constructor[SPECIES] = function () { + return re; + }; + re.flags = ''; + re[SYMBOL] = /./[SYMBOL]; + } + re.exec = function () { + execCalled = true; + return null; + }; + re[SYMBOL](''); + return !execCalled; + }); + if (!DELEGATES_TO_SYMBOL || !DELEGATES_TO_EXEC || KEY === 'replace' && !(REPLACE_SUPPORTS_NAMED_GROUPS && REPLACE_KEEPS_$0 && !REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE) || KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC) { + var nativeRegExpMethod = /./[SYMBOL]; + var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) { + if (regexp.exec === regexpExec) { + if (DELEGATES_TO_SYMBOL && !forceStringMethod) { + // The native String method already delegates to @@method (this + // polyfilled function), leasing to infinite recursion. + // We avoid it by directly calling the native @@method method. + return { + done: true, + value: nativeRegExpMethod.call(regexp, str, arg2) + }; + } + return { + done: true, + value: nativeMethod.call(str, regexp, arg2) + }; + } + return { + done: false + }; + }, { + REPLACE_KEEPS_$0: REPLACE_KEEPS_$0, + REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE: REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE + }); + var stringMethod = methods[0]; + var regexMethod = methods[1]; + redefine(String.prototype, KEY, stringMethod); + redefine(RegExp.prototype, SYMBOL, length == 2 // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) + // 21.2.5.11 RegExp.prototype[@@split](string, limit) + ? function (string, arg) { + return regexMethod.call(string, this, arg); + } // 21.2.5.6 RegExp.prototype[@@match](string) + // 21.2.5.9 RegExp.prototype[@@search](string) + + : function (string) { + return regexMethod.call(string, this); + }); + } + if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true); + }; + }, + { + '../internals/create-non-enumerable-property': 56, + '../internals/fails': 69, + '../internals/redefine': 127, + '../internals/regexp-exec': 129, + '../internals/well-known-symbol': 167, + '../modules/es.regexp.exec': 210 + } + ], + 71: [ + function (_dereq_, module, exports) { + 'use strict'; + var isArray = _dereq_('../internals/is-array'); + var toLength = _dereq_('../internals/to-length'); + var bind = _dereq_('../internals/function-bind-context'); + // `FlattenIntoArray` abstract operation + // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray + var flattenIntoArray = function (target, original, source, sourceLen, start, depth, mapper, thisArg) { + var targetIndex = start; + var sourceIndex = 0; + var mapFn = mapper ? bind(mapper, thisArg, 3) : false; + var element; + while (sourceIndex < sourceLen) { + if (sourceIndex in source) { + element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; + if (depth > 0 && isArray(element)) { + targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; + } else { + if (targetIndex >= 9007199254740991) throw TypeError('Exceed the acceptable array length'); + target[targetIndex] = element; + } + targetIndex++; + } + sourceIndex++; + } + return targetIndex; + }; + module.exports = flattenIntoArray; + }, + { + '../internals/function-bind-context': 73, + '../internals/is-array': 91, + '../internals/to-length': 155 + } + ], + 72: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + module.exports = !fails(function () { + return Object.isExtensible(Object.preventExtensions({ + })); + }); + }, + { + '../internals/fails': 69 + } + ], + 73: [ + function (_dereq_, module, exports) { + var aFunction = _dereq_('../internals/a-function'); + // optional / simple context binding + module.exports = function (fn, that, length) { + aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 0: + return function () { + return fn.call(that); + }; + case 1: + return function (a) { + return fn.call(that, a); + }; + case 2: + return function (a, b) { + return fn.call(that, a, b); + }; + case 3: + return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function /* ...args */ + () { + return fn.apply(that, arguments); + }; + }; + }, + { + '../internals/a-function': 23 + } + ], + 74: [ + function (_dereq_, module, exports) { + 'use strict'; + var aFunction = _dereq_('../internals/a-function'); + var isObject = _dereq_('../internals/is-object'); + var slice = [ + ].slice; + var factories = { + }; + var construct = function (C, argsLength, args) { + if (!(argsLength in factories)) { + for (var list = [ + ], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']'; + // eslint-disable-next-line no-new-func + factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')'); + } + return factories[argsLength](C, args); + }; + // `Function.prototype.bind` method implementation + // https://tc39.github.io/ecma262/#sec-function.prototype.bind + module.exports = Function.bind || function bind(that /* , ...args */ ) { + var fn = aFunction(this); + var partArgs = slice.call(arguments, 1); + var boundFunction = function bound( /* args... */ + ) { + var args = partArgs.concat(slice.call(arguments)); + return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args); + }; + if (isObject(fn.prototype)) boundFunction.prototype = fn.prototype; + return boundFunction; + }; + }, + { + '../internals/a-function': 23, + '../internals/is-object': 93 + } + ], + 75: [ + function (_dereq_, module, exports) { + var path = _dereq_('../internals/path'); + var global = _dereq_('../internals/global'); + var aFunction = function (variable) { + return typeof variable == 'function' ? variable : undefined; + }; + module.exports = function (namespace, method) { + return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace]) : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method]; + }; + }, + { + '../internals/global': 78, + '../internals/path': 123 + } + ], + 76: [ + function (_dereq_, module, exports) { + var classof = _dereq_('../internals/classof'); + var Iterators = _dereq_('../internals/iterators'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var ITERATOR = wellKnownSymbol('iterator'); + module.exports = function (it) { + if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; + }; + }, + { + '../internals/classof': 47, + '../internals/iterators': 98, + '../internals/well-known-symbol': 167 + } + ], + 77: [ + function (_dereq_, module, exports) { + var anObject = _dereq_('../internals/an-object'); + var getIteratorMethod = _dereq_('../internals/get-iterator-method'); + module.exports = function (it) { + var iteratorMethod = getIteratorMethod(it); + if (typeof iteratorMethod != 'function') { + throw TypeError(String(it) + ' is not iterable'); + } + return anObject(iteratorMethod.call(it)); + }; + }, + { + '../internals/an-object': 28, + '../internals/get-iterator-method': 76 + } + ], + 78: [ + function (_dereq_, module, exports) { + (function (global) { + var check = function (it) { + return it && it.Math == Math && it; + }; + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + module.exports = // eslint-disable-next-line no-undef + check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || check(typeof self == 'object' && self) || check(typeof global == 'object' && global) || // eslint-disable-next-line no-new-func + Function('return this') (); + }).call(this, typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : { + }) + }, + { + } + ], + 79: [ + function (_dereq_, module, exports) { + var hasOwnProperty = { + }.hasOwnProperty; + module.exports = function (it, key) { + return hasOwnProperty.call(it, key); + }; + }, + { + } + ], + 80: [ + function (_dereq_, module, exports) { + module.exports = { + }; + }, + { + } + ], + 81: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + module.exports = function (a, b) { + var console = global.console; + if (console && console.error) { + arguments.length === 1 ? console.error(a) : console.error(a, b); + } + }; + }, + { + '../internals/global': 78 + } + ], + 82: [ + function (_dereq_, module, exports) { + var getBuiltIn = _dereq_('../internals/get-built-in'); + module.exports = getBuiltIn('document', 'documentElement'); + }, + { + '../internals/get-built-in': 75 + } + ], + 83: [ + function (_dereq_, module, exports) { + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var fails = _dereq_('../internals/fails'); + var createElement = _dereq_('../internals/document-create-element'); + // Thank's IE8 for his funny defineProperty + module.exports = !DESCRIPTORS && !fails(function () { + return Object.defineProperty(createElement('div'), 'a', { + get: function () { + return 7; + } + }).a != 7; + }); + }, + { + '../internals/descriptors': 61, + '../internals/document-create-element': 62, + '../internals/fails': 69 + } + ], + 84: [ + function (_dereq_, module, exports) { + // IEEE754 conversions based on https://github.com/feross/ieee754 + // eslint-disable-next-line no-shadow-restricted-names + var Infinity = 1 / 0; + var abs = Math.abs; + var pow = Math.pow; + var floor = Math.floor; + var log = Math.log; + var LN2 = Math.LN2; + var pack = function (number, mantissaLength, bytes) { + var buffer = new Array(bytes); + var exponentLength = bytes * 8 - mantissaLength - 1; + var eMax = (1 << exponentLength) - 1; + var eBias = eMax >> 1; + var rt = mantissaLength === 23 ? pow(2, - 24) - pow(2, - 77) : 0; + var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0; + var index = 0; + var exponent, + mantissa, + c; + number = abs(number); + // eslint-disable-next-line no-self-compare + if (number != number || number === Infinity) { + // eslint-disable-next-line no-self-compare + mantissa = number != number ? 1 : 0; + exponent = eMax; + } else { + exponent = floor(log(number) / LN2); + if (number * (c = pow(2, - exponent)) < 1) { + exponent--; + c *= 2; + } + if (exponent + eBias >= 1) { + number += rt / c; + } else { + number += rt * pow(2, 1 - eBias); + } + if (number * c >= 2) { + exponent++; + c /= 2; + } + if (exponent + eBias >= eMax) { + mantissa = 0; + exponent = eMax; + } else if (exponent + eBias >= 1) { + mantissa = (number * c - 1) * pow(2, mantissaLength); + exponent = exponent + eBias; + } else { + mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength); + exponent = 0; + } + } + for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8); + exponent = exponent << mantissaLength | mantissa; + exponentLength += mantissaLength; + for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8); + buffer[--index] |= sign * 128; + return buffer; + }; + var unpack = function (buffer, mantissaLength) { + var bytes = buffer.length; + var exponentLength = bytes * 8 - mantissaLength - 1; + var eMax = (1 << exponentLength) - 1; + var eBias = eMax >> 1; + var nBits = exponentLength - 7; + var index = bytes - 1; + var sign = buffer[index--]; + var exponent = sign & 127; + var mantissa; + sign >>= 7; + for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8); + mantissa = exponent & (1 << - nBits) - 1; + exponent >>= - nBits; + nBits += mantissaLength; + for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8); + if (exponent === 0) { + exponent = 1 - eBias; + } else if (exponent === eMax) { + return mantissa ? NaN : sign ? - Infinity : Infinity; + } else { + mantissa = mantissa + pow(2, mantissaLength); + exponent = exponent - eBias; + } + return (sign ? - 1 : 1) * mantissa * pow(2, exponent - mantissaLength); + }; + module.exports = { + pack: pack, + unpack: unpack + }; + }, + { + } + ], + 85: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + var classof = _dereq_('../internals/classof-raw'); + var split = ''.split; + // fallback for non-array-like ES3 and non-enumerable old V8 strings + module.exports = fails(function () { + // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 + // eslint-disable-next-line no-prototype-builtins + return !Object('z').propertyIsEnumerable(0); + }) ? function (it) { + return classof(it) == 'String' ? split.call(it, '') : Object(it); + } + : Object; + }, + { + '../internals/classof-raw': 46, + '../internals/fails': 69 + } + ], + 86: [ + function (_dereq_, module, exports) { + var isObject = _dereq_('../internals/is-object'); + var setPrototypeOf = _dereq_('../internals/object-set-prototype-of'); + // makes subclassing work correct for wrapped built-ins + module.exports = function ($this, dummy, Wrapper) { + var NewTarget, + NewTargetPrototype; + if ( // it can work only with native `setPrototypeOf` + setPrototypeOf && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this + typeof (NewTarget = dummy.constructor) == 'function' && NewTarget !== Wrapper && isObject(NewTargetPrototype = NewTarget.prototype) && NewTargetPrototype !== Wrapper.prototype) setPrototypeOf($this, NewTargetPrototype); + return $this; + }; + }, + { + '../internals/is-object': 93, + '../internals/object-set-prototype-of': 120 + } + ], + 87: [ + function (_dereq_, module, exports) { + var store = _dereq_('../internals/shared-store'); + var functionToString = Function.toString; + // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper + if (typeof store.inspectSource != 'function') { + store.inspectSource = function (it) { + return functionToString.call(it); + }; + } + module.exports = store.inspectSource; + }, + { + '../internals/shared-store': 138 + } + ], + 88: [ + function (_dereq_, module, exports) { + var hiddenKeys = _dereq_('../internals/hidden-keys'); + var isObject = _dereq_('../internals/is-object'); + var has = _dereq_('../internals/has'); + var defineProperty = _dereq_('../internals/object-define-property').f; + var uid = _dereq_('../internals/uid'); + var FREEZING = _dereq_('../internals/freezing'); + var METADATA = uid('meta'); + var id = 0; + var isExtensible = Object.isExtensible || function () { + return true; + }; + var setMetadata = function (it) { + defineProperty(it, METADATA, { + value: { + objectID: 'O' + ++id, + // object ID + weakData: { + } // weak collections IDs + + } + }); + }; + var fastKey = function (it, create) { + // return a primitive with prefix + if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!has(it, METADATA)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMetadata(it); + // return object ID + } + return it[METADATA].objectID; + }; + var getWeakData = function (it, create) { + if (!has(it, METADATA)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMetadata(it); + // return the store of weak collections IDs + } + return it[METADATA].weakData; + }; + // add metadata on freeze-family methods calling + var onFreeze = function (it) { + if (FREEZING && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it); + return it; + }; + var meta = module.exports = { + REQUIRED: false, + fastKey: fastKey, + getWeakData: getWeakData, + onFreeze: onFreeze + }; + hiddenKeys[METADATA] = true; + }, + { + '../internals/freezing': 72, + '../internals/has': 79, + '../internals/hidden-keys': 80, + '../internals/is-object': 93, + '../internals/object-define-property': 111, + '../internals/uid': 164 + } + ], + 89: [ + function (_dereq_, module, exports) { + var NATIVE_WEAK_MAP = _dereq_('../internals/native-weak-map'); + var global = _dereq_('../internals/global'); + var isObject = _dereq_('../internals/is-object'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var objectHas = _dereq_('../internals/has'); + var sharedKey = _dereq_('../internals/shared-key'); + var hiddenKeys = _dereq_('../internals/hidden-keys'); + var WeakMap = global.WeakMap; + var set, + get, + has; + var enforce = function (it) { + return has(it) ? get(it) : set(it, { + }); + }; + var getterFor = function (TYPE) { + return function (it) { + var state; + if (!isObject(it) || (state = get(it)).type !== TYPE) { + throw TypeError('Incompatible receiver, ' + TYPE + ' required'); + } + return state; + }; + }; + if (NATIVE_WEAK_MAP) { + var store = new WeakMap(); + var wmget = store.get; + var wmhas = store.has; + var wmset = store.set; + set = function (it, metadata) { + wmset.call(store, it, metadata); + return metadata; + }; + get = function (it) { + return wmget.call(store, it) || { + }; + }; + has = function (it) { + return wmhas.call(store, it); + }; + } else { + var STATE = sharedKey('state'); + hiddenKeys[STATE] = true; + set = function (it, metadata) { + createNonEnumerableProperty(it, STATE, metadata); + return metadata; + }; + get = function (it) { + return objectHas(it, STATE) ? it[STATE] : { + }; + }; + has = function (it) { + return objectHas(it, STATE); + }; + } + module.exports = { + set: set, + get: get, + has: has, + enforce: enforce, + getterFor: getterFor + }; + }, + { + '../internals/create-non-enumerable-property': 56, + '../internals/global': 78, + '../internals/has': 79, + '../internals/hidden-keys': 80, + '../internals/is-object': 93, + '../internals/native-weak-map': 104, + '../internals/shared-key': 137 + } + ], + 90: [ + function (_dereq_, module, exports) { + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var Iterators = _dereq_('../internals/iterators'); + var ITERATOR = wellKnownSymbol('iterator'); + var ArrayPrototype = Array.prototype; + // check on default Array iterator + module.exports = function (it) { + return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); + }; + }, + { + '../internals/iterators': 98, + '../internals/well-known-symbol': 167 + } + ], + 91: [ + function (_dereq_, module, exports) { + var classof = _dereq_('../internals/classof-raw'); + // `IsArray` abstract operation + // https://tc39.github.io/ecma262/#sec-isarray + module.exports = Array.isArray || function isArray(arg) { + return classof(arg) == 'Array'; + }; + }, + { + '../internals/classof-raw': 46 + } + ], + 92: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + var replacement = /#|\.prototype\./; + var isForced = function (feature, detection) { + var value = data[normalize(feature)]; + return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails(detection) : !!detection; + }; + var normalize = isForced.normalize = function (string) { + return String(string).replace(replacement, '.').toLowerCase(); + }; + var data = isForced.data = { + }; + var NATIVE = isForced.NATIVE = 'N'; + var POLYFILL = isForced.POLYFILL = 'P'; + module.exports = isForced; + }, + { + '../internals/fails': 69 + } + ], + 93: [ + function (_dereq_, module, exports) { + module.exports = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; + }; + }, + { + } + ], + 94: [ + function (_dereq_, module, exports) { + module.exports = false; + }, + { + } + ], + 95: [ + function (_dereq_, module, exports) { + var isObject = _dereq_('../internals/is-object'); + var classof = _dereq_('../internals/classof-raw'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var MATCH = wellKnownSymbol('match'); + // `IsRegExp` abstract operation + // https://tc39.github.io/ecma262/#sec-isregexp + module.exports = function (it) { + var isRegExp; + return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) == 'RegExp'); + }; + }, + { + '../internals/classof-raw': 46, + '../internals/is-object': 93, + '../internals/well-known-symbol': 167 + } + ], + 96: [ + function (_dereq_, module, exports) { + var anObject = _dereq_('../internals/an-object'); + var isArrayIteratorMethod = _dereq_('../internals/is-array-iterator-method'); + var toLength = _dereq_('../internals/to-length'); + var bind = _dereq_('../internals/function-bind-context'); + var getIteratorMethod = _dereq_('../internals/get-iterator-method'); + var callWithSafeIterationClosing = _dereq_('../internals/call-with-safe-iteration-closing'); + var Result = function (stopped, result) { + this.stopped = stopped; + this.result = result; + }; + var iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) { + var boundFunction = bind(fn, that, AS_ENTRIES ? 2 : 1); + var iterator, + iterFn, + index, + length, + result, + next, + step; + if (IS_ITERATOR) { + iterator = iterable; + } else { + iterFn = getIteratorMethod(iterable); + if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); + // optimisation for array iterators + if (isArrayIteratorMethod(iterFn)) { + for (index = 0, length = toLength(iterable.length); length > index; index++) { + result = AS_ENTRIES ? boundFunction(anObject(step = iterable[index]) [0], step[1]) : boundFunction(iterable[index]); + if (result && result instanceof Result) return result; + } + return new Result(false); + } + iterator = iterFn.call(iterable); + } + next = iterator.next; + while (!(step = next.call(iterator)).done) { + result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES); + if (typeof result == 'object' && result && result instanceof Result) return result; + } + return new Result(false); + }; + iterate.stop = function (result) { + return new Result(true, result); + }; + }, + { + '../internals/an-object': 28, + '../internals/call-with-safe-iteration-closing': 44, + '../internals/function-bind-context': 73, + '../internals/get-iterator-method': 76, + '../internals/is-array-iterator-method': 90, + '../internals/to-length': 155 + } + ], + 97: [ + function (_dereq_, module, exports) { + 'use strict'; + var getPrototypeOf = _dereq_('../internals/object-get-prototype-of'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var has = _dereq_('../internals/has'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var IS_PURE = _dereq_('../internals/is-pure'); + var ITERATOR = wellKnownSymbol('iterator'); + var BUGGY_SAFARI_ITERATORS = false; + var returnThis = function () { + return this; + }; + // `%IteratorPrototype%` object + // https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object + var IteratorPrototype, + PrototypeOfArrayIteratorPrototype, + arrayIterator; + if ([].keys) { + arrayIterator = [ + ].keys(); + // Safari 8 has buggy iterators w/o `next` + if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true; + else { + PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator)); + if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype; + } + } + if (IteratorPrototype == undefined) IteratorPrototype = { + }; + // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() + if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) { + createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis); + } + module.exports = { + IteratorPrototype: IteratorPrototype, + BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS + }; + }, + { + '../internals/create-non-enumerable-property': 56, + '../internals/has': 79, + '../internals/is-pure': 94, + '../internals/object-get-prototype-of': 116, + '../internals/well-known-symbol': 167 + } + ], + 98: [ + function (_dereq_, module, exports) { + module.exports = { + }; + }, + { + } + ], + 99: [ + function (_dereq_, module, exports) { + // `Math.sign` method implementation + // https://tc39.github.io/ecma262/#sec-math.sign + module.exports = Math.sign || function sign(x) { + // eslint-disable-next-line no-self-compare + return (x = + x) == 0 || x != x ? x : x < 0 ? - 1 : 1; + }; + }, + { + } + ], + 100: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var getOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f; + var classof = _dereq_('../internals/classof-raw'); + var macrotask = _dereq_('../internals/task').set; + var IS_IOS = _dereq_('../internals/engine-is-ios'); + var MutationObserver = global.MutationObserver || global.WebKitMutationObserver; + var process = global.process; + var Promise = global.Promise; + var IS_NODE = classof(process) == 'process'; + // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask` + var queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask'); + var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value; + var flush, + head, + last, + notify, + toggle, + node, + promise, + then; + // modern engines have queueMicrotask method + if (!queueMicrotask) { + flush = function () { + var parent, + fn; + if (IS_NODE && (parent = process.domain)) parent.exit(); + while (head) { + fn = head.fn; + head = head.next; + try { + fn(); + } catch (error) { + if (head) notify(); + else last = undefined; + throw error; + } + } + last = undefined; + if (parent) parent.enter(); + }; + // Node.js + if (IS_NODE) { + notify = function () { + process.nextTick(flush); + }; + // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 + } else if (MutationObserver && !IS_IOS) { + toggle = true; + node = document.createTextNode(''); + new MutationObserver(flush).observe(node, { + characterData: true + }); + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (Promise && Promise.resolve) { + // Promise.resolve without an argument throws an error in LG WebOS 2 + promise = Promise.resolve(undefined); + then = promise.then; + notify = function () { + then.call(promise, flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function () { + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; + } + } + module.exports = queueMicrotask || function (fn) { + var task = { + fn: fn, + next: undefined + }; + if (last) last.next = task; + if (!head) { + head = task; + notify(); + } + last = task; + }; + }, + { + '../internals/classof-raw': 46, + '../internals/engine-is-ios': 64, + '../internals/global': 78, + '../internals/object-get-own-property-descriptor': 112, + '../internals/task': 149 + } + ], + 101: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + module.exports = global.Promise; + }, + { + '../internals/global': 78 + } + ], + 102: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + module.exports = !!Object.getOwnPropertySymbols && !fails(function () { + // Chrome 38 Symbol has incorrect toString conversion + // eslint-disable-next-line no-undef + return !String(Symbol()); + }); + }, + { + '../internals/fails': 69 + } + ], + 103: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var IS_PURE = _dereq_('../internals/is-pure'); + var ITERATOR = wellKnownSymbol('iterator'); + module.exports = !fails(function () { + var url = new URL('b?a=1&b=2&c=3', 'http://a'); + var searchParams = url.searchParams; + var result = ''; + url.pathname = 'c%20d'; + searchParams.forEach(function (value, key) { + searchParams['delete']('b'); + result += key + value; + }); + return IS_PURE && !url.toJSON || !searchParams.sort || url.href !== 'http://a/c%20d?a=1&c=3' || searchParams.get('c') !== '3' || String(new URLSearchParams('?a=1')) !== 'a=1' || !searchParams[ITERATOR] // throws in Edge + || new URL('https://a@b').username !== 'a' || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' // not punycoded in Edge + || new URL('http://тест').host !== 'xn--e1aybc' // not escaped in Chrome 62- + || new URL('http://a#б').hash !== '#%D0%B1' // fails in Chrome 66- + || result !== 'a1c3' // throws in Safari + || new URL('http://x', undefined).host !== 'x'; + }); + }, + { + '../internals/fails': 69, + '../internals/is-pure': 94, + '../internals/well-known-symbol': 167 + } + ], + 104: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var inspectSource = _dereq_('../internals/inspect-source'); + var WeakMap = global.WeakMap; + module.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap)); + }, + { + '../internals/global': 78, + '../internals/inspect-source': 87 + } + ], + 105: [ + function (_dereq_, module, exports) { + 'use strict'; + var aFunction = _dereq_('../internals/a-function'); + var PromiseCapability = function (C) { + var resolve, + reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve); + this.reject = aFunction(reject); + }; + // 25.4.1.5 NewPromiseCapability(C) + module.exports.f = function (C) { + return new PromiseCapability(C); + }; + }, + { + '../internals/a-function': 23 + } + ], + 106: [ + function (_dereq_, module, exports) { + var isRegExp = _dereq_('../internals/is-regexp'); + module.exports = function (it) { + if (isRegExp(it)) { + throw TypeError('The method doesn\'t accept regular expressions'); + } + return it; + }; + }, + { + '../internals/is-regexp': 95 + } + ], + 107: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var globalIsFinite = global.isFinite; + // `Number.isFinite` method + // https://tc39.github.io/ecma262/#sec-number.isfinite + module.exports = Number.isFinite || function isFinite(it) { + return typeof it == 'number' && globalIsFinite(it); + }; + }, + { + '../internals/global': 78 + } + ], + 108: [ + function (_dereq_, module, exports) { + 'use strict'; + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var fails = _dereq_('../internals/fails'); + var objectKeys = _dereq_('../internals/object-keys'); + var getOwnPropertySymbolsModule = _dereq_('../internals/object-get-own-property-symbols'); + var propertyIsEnumerableModule = _dereq_('../internals/object-property-is-enumerable'); + var toObject = _dereq_('../internals/to-object'); + var IndexedObject = _dereq_('../internals/indexed-object'); + var nativeAssign = Object.assign; + var defineProperty = Object.defineProperty; + // `Object.assign` method + // https://tc39.github.io/ecma262/#sec-object.assign + module.exports = !nativeAssign || fails(function () { + // should have correct order of operations (Edge bug) + if (DESCRIPTORS && nativeAssign({ + b: 1 + }, nativeAssign(defineProperty({ + }, 'a', { + enumerable: true, + get: function () { + defineProperty(this, 'b', { + value: 3, + enumerable: false + }); + } + }), { + b: 2 + })).b !== 1) return true; + // should work with symbols and should have deterministic property order (V8 bug) + var A = { + }; + var B = { + }; + // eslint-disable-next-line no-undef + var symbol = Symbol(); + var alphabet = 'abcdefghijklmnopqrst'; + A[symbol] = 7; + alphabet.split('').forEach(function (chr) { + B[chr] = chr; + }); + return nativeAssign({ + }, A) [symbol] != 7 || objectKeys(nativeAssign({ + }, B)).join('') != alphabet; + }) ? function assign(target, source) { + // eslint-disable-line no-unused-vars + var T = toObject(target); + var argumentsLength = arguments.length; + var index = 1; + var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; + var propertyIsEnumerable = propertyIsEnumerableModule.f; + while (argumentsLength > index) { + var S = IndexedObject(arguments[index++]); + var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) { + key = keys[j++]; + if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key]; + } + } + return T; + } + : nativeAssign; + }, + { + '../internals/descriptors': 61, + '../internals/fails': 69, + '../internals/indexed-object': 85, + '../internals/object-get-own-property-symbols': 115, + '../internals/object-keys': 118, + '../internals/object-property-is-enumerable': 119, + '../internals/to-object': 156 + } + ], + 109: [ + function (_dereq_, module, exports) { + var anObject = _dereq_('../internals/an-object'); + var defineProperties = _dereq_('../internals/object-define-properties'); + var enumBugKeys = _dereq_('../internals/enum-bug-keys'); + var hiddenKeys = _dereq_('../internals/hidden-keys'); + var html = _dereq_('../internals/html'); + var documentCreateElement = _dereq_('../internals/document-create-element'); + var sharedKey = _dereq_('../internals/shared-key'); + var GT = '>'; + var LT = '<'; + var PROTOTYPE = 'prototype'; + var SCRIPT = 'script'; + var IE_PROTO = sharedKey('IE_PROTO'); + var EmptyConstructor = function () { /* empty */ + }; + var scriptTag = function (content) { + return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; + }; + // Create object with fake `null` prototype: use ActiveX Object with cleared prototype + var NullProtoObjectViaActiveX = function (activeXDocument) { + activeXDocument.write(scriptTag('')); + activeXDocument.close(); + var temp = activeXDocument.parentWindow.Object; + activeXDocument = null; // avoid memory leak + return temp; + }; + // Create object with fake `null` prototype: use iframe Object with cleared prototype + var NullProtoObjectViaIFrame = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = documentCreateElement('iframe'); + var JS = 'java' + SCRIPT + ':'; + var iframeDocument; + iframe.style.display = 'none'; + html.appendChild(iframe); + // https://github.com/zloirock/core-js/issues/475 + iframe.src = String(JS); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(scriptTag('document.F=Object')); + iframeDocument.close(); + return iframeDocument.F; + }; + // Check for document.domain and active x support + // No need to use active x approach when document.domain is not set + // see https://github.com/es-shims/es5-shim/issues/150 + // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 + // avoid IE GC bug + var activeXDocument; + var NullProtoObject = function () { + try { + /* global ActiveXObject */ + activeXDocument = document.domain && new ActiveXObject('htmlfile'); + } catch (error) { /* ignore */ + } + NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame(); + var length = enumBugKeys.length; + while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; + return NullProtoObject(); + }; + hiddenKeys[IE_PROTO] = true; + // `Object.create` method + // https://tc39.github.io/ecma262/#sec-object.create + module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + EmptyConstructor[PROTOTYPE] = anObject(O); + result = new EmptyConstructor(); + EmptyConstructor[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = NullProtoObject(); + return Properties === undefined ? result : defineProperties(result, Properties); + }; + }, + { + '../internals/an-object': 28, + '../internals/document-create-element': 62, + '../internals/enum-bug-keys': 67, + '../internals/hidden-keys': 80, + '../internals/html': 82, + '../internals/object-define-properties': 110, + '../internals/shared-key': 137 + } + ], + 110: [ + function (_dereq_, module, exports) { + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var definePropertyModule = _dereq_('../internals/object-define-property'); + var anObject = _dereq_('../internals/an-object'); + var objectKeys = _dereq_('../internals/object-keys'); + // `Object.defineProperties` method + // https://tc39.github.io/ecma262/#sec-object.defineproperties + module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = objectKeys(Properties); + var length = keys.length; + var index = 0; + var key; + while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]); + return O; + }; + }, + { + '../internals/an-object': 28, + '../internals/descriptors': 61, + '../internals/object-define-property': 111, + '../internals/object-keys': 118 + } + ], + 111: [ + function (_dereq_, module, exports) { + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var IE8_DOM_DEFINE = _dereq_('../internals/ie8-dom-define'); + var anObject = _dereq_('../internals/an-object'); + var toPrimitive = _dereq_('../internals/to-primitive'); + var nativeDefineProperty = Object.defineProperty; + // `Object.defineProperty` method + // https://tc39.github.io/ecma262/#sec-object.defineproperty + exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return nativeDefineProperty(O, P, Attributes); + } catch (error) { /* empty */ + } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; + }; + }, + { + '../internals/an-object': 28, + '../internals/descriptors': 61, + '../internals/ie8-dom-define': 83, + '../internals/to-primitive': 159 + } + ], + 112: [ + function (_dereq_, module, exports) { + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var propertyIsEnumerableModule = _dereq_('../internals/object-property-is-enumerable'); + var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor'); + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var toPrimitive = _dereq_('../internals/to-primitive'); + var has = _dereq_('../internals/has'); + var IE8_DOM_DEFINE = _dereq_('../internals/ie8-dom-define'); + var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + // `Object.getOwnPropertyDescriptor` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor + exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { + O = toIndexedObject(O); + P = toPrimitive(P, true); + if (IE8_DOM_DEFINE) try { + return nativeGetOwnPropertyDescriptor(O, P); + } catch (error) { /* empty */ + } + if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]); + }; + }, + { + '../internals/create-property-descriptor': 57, + '../internals/descriptors': 61, + '../internals/has': 79, + '../internals/ie8-dom-define': 83, + '../internals/object-property-is-enumerable': 119, + '../internals/to-indexed-object': 153, + '../internals/to-primitive': 159 + } + ], + 113: [ + function (_dereq_, module, exports) { + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var nativeGetOwnPropertyNames = _dereq_('../internals/object-get-own-property-names').f; + var toString = { + }.toString; + var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : [ + ]; + var getWindowNames = function (it) { + try { + return nativeGetOwnPropertyNames(it); + } catch (error) { + return windowNames.slice(); + } + }; + // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + module.exports.f = function getOwnPropertyNames(it) { + return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : nativeGetOwnPropertyNames(toIndexedObject(it)); + }; + }, + { + '../internals/object-get-own-property-names': 114, + '../internals/to-indexed-object': 153 + } + ], + 114: [ + function (_dereq_, module, exports) { + var internalObjectKeys = _dereq_('../internals/object-keys-internal'); + var enumBugKeys = _dereq_('../internals/enum-bug-keys'); + var hiddenKeys = enumBugKeys.concat('length', 'prototype'); + // `Object.getOwnPropertyNames` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertynames + exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return internalObjectKeys(O, hiddenKeys); + }; + }, + { + '../internals/enum-bug-keys': 67, + '../internals/object-keys-internal': 117 + } + ], + 115: [ + function (_dereq_, module, exports) { + exports.f = Object.getOwnPropertySymbols; + }, + { + } + ], + 116: [ + function (_dereq_, module, exports) { + var has = _dereq_('../internals/has'); + var toObject = _dereq_('../internals/to-object'); + var sharedKey = _dereq_('../internals/shared-key'); + var CORRECT_PROTOTYPE_GETTER = _dereq_('../internals/correct-prototype-getter'); + var IE_PROTO = sharedKey('IE_PROTO'); + var ObjectPrototype = Object.prototype; + // `Object.getPrototypeOf` method + // https://tc39.github.io/ecma262/#sec-object.getprototypeof + module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) { + O = toObject(O); + if (has(O, IE_PROTO)) return O[IE_PROTO]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } + return O instanceof Object ? ObjectPrototype : null; + }; + }, + { + '../internals/correct-prototype-getter': 53, + '../internals/has': 79, + '../internals/shared-key': 137, + '../internals/to-object': 156 + } + ], + 117: [ + function (_dereq_, module, exports) { + var has = _dereq_('../internals/has'); + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var indexOf = _dereq_('../internals/array-includes').indexOf; + var hiddenKeys = _dereq_('../internals/hidden-keys'); + module.exports = function (object, names) { + var O = toIndexedObject(object); + var i = 0; + var result = [ + ]; + var key; + for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while (names.length > i) if (has(O, key = names[i++])) { + ~indexOf(result, key) || result.push(key); + } + return result; + }; + }, + { + '../internals/array-includes': 36, + '../internals/has': 79, + '../internals/hidden-keys': 80, + '../internals/to-indexed-object': 153 + } + ], + 118: [ + function (_dereq_, module, exports) { + var internalObjectKeys = _dereq_('../internals/object-keys-internal'); + var enumBugKeys = _dereq_('../internals/enum-bug-keys'); + // `Object.keys` method + // https://tc39.github.io/ecma262/#sec-object.keys + module.exports = Object.keys || function keys(O) { + return internalObjectKeys(O, enumBugKeys); + }; + }, + { + '../internals/enum-bug-keys': 67, + '../internals/object-keys-internal': 117 + } + ], + 119: [ + function (_dereq_, module, exports) { + 'use strict'; + var nativePropertyIsEnumerable = { + }.propertyIsEnumerable; + var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + // Nashorn ~ JDK8 bug + var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ + 1: 2 + }, 1); + // `Object.prototype.propertyIsEnumerable` method implementation + // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable + exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { + var descriptor = getOwnPropertyDescriptor(this, V); + return !!descriptor && descriptor.enumerable; + } + : nativePropertyIsEnumerable; + }, + { + } + ], + 120: [ + function (_dereq_, module, exports) { + var anObject = _dereq_('../internals/an-object'); + var aPossiblePrototype = _dereq_('../internals/a-possible-prototype'); + // `Object.setPrototypeOf` method + // https://tc39.github.io/ecma262/#sec-object.setprototypeof + // Works with __proto__ only. Old v8 can't work with null proto objects. + /* eslint-disable no-proto */ + module.exports = Object.setPrototypeOf || ('__proto__' in { + } + ? function () { + var CORRECT_SETTER = false; + var test = { + }; + var setter; + try { + setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set; + setter.call(test, [ + ]); + CORRECT_SETTER = test instanceof Array; + } catch (error) { /* empty */ + } + return function setPrototypeOf(O, proto) { + anObject(O); + aPossiblePrototype(proto); + if (CORRECT_SETTER) setter.call(O, proto); + else O.__proto__ = proto; + return O; + }; + }() : undefined); + }, + { + '../internals/a-possible-prototype': 24, + '../internals/an-object': 28 + } + ], + 121: [ + function (_dereq_, module, exports) { + 'use strict'; + var TO_STRING_TAG_SUPPORT = _dereq_('../internals/to-string-tag-support'); + var classof = _dereq_('../internals/classof'); + // `Object.prototype.toString` method implementation + // https://tc39.github.io/ecma262/#sec-object.prototype.tostring + module.exports = TO_STRING_TAG_SUPPORT ? { + }.toString : function toString() { + return '[object ' + classof(this) + ']'; + }; + }, + { + '../internals/classof': 47, + '../internals/to-string-tag-support': 160 + } + ], + 122: [ + function (_dereq_, module, exports) { + var getBuiltIn = _dereq_('../internals/get-built-in'); + var getOwnPropertyNamesModule = _dereq_('../internals/object-get-own-property-names'); + var getOwnPropertySymbolsModule = _dereq_('../internals/object-get-own-property-symbols'); + var anObject = _dereq_('../internals/an-object'); + // all object keys, includes non-enumerable and symbols + module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { + var keys = getOwnPropertyNamesModule.f(anObject(it)); + var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; + return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; + }; + }, + { + '../internals/an-object': 28, + '../internals/get-built-in': 75, + '../internals/object-get-own-property-names': 114, + '../internals/object-get-own-property-symbols': 115 + } + ], + 123: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + module.exports = global; + }, + { + '../internals/global': 78 + } + ], + 124: [ + function (_dereq_, module, exports) { + module.exports = function (exec) { + try { + return { + error: false, + value: exec() + }; + } catch (error) { + return { + error: true, + value: error + }; + } + }; + }, + { + } + ], + 125: [ + function (_dereq_, module, exports) { + var anObject = _dereq_('../internals/an-object'); + var isObject = _dereq_('../internals/is-object'); + var newPromiseCapability = _dereq_('../internals/new-promise-capability'); + module.exports = function (C, x) { + anObject(C); + if (isObject(x) && x.constructor === C) return x; + var promiseCapability = newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; + }; + }, + { + '../internals/an-object': 28, + '../internals/is-object': 93, + '../internals/new-promise-capability': 105 + } + ], + 126: [ + function (_dereq_, module, exports) { + var redefine = _dereq_('../internals/redefine'); + module.exports = function (target, src, options) { + for (var key in src) redefine(target, key, src[key], options); + return target; + }; + }, + { + '../internals/redefine': 127 + } + ], + 127: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var has = _dereq_('../internals/has'); + var setGlobal = _dereq_('../internals/set-global'); + var inspectSource = _dereq_('../internals/inspect-source'); + var InternalStateModule = _dereq_('../internals/internal-state'); + var getInternalState = InternalStateModule.get; + var enforceInternalState = InternalStateModule.enforce; + var TEMPLATE = String(String).split('String'); + (module.exports = function (O, key, value, options) { + var unsafe = options ? !!options.unsafe : false; + var simple = options ? !!options.enumerable : false; + var noTargetGet = options ? !!options.noTargetGet : false; + if (typeof value == 'function') { + if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key); + enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : ''); + } + if (O === global) { + if (simple) O[key] = value; + else setGlobal(key, value); + return; + } else if (!unsafe) { + delete O[key]; + } else if (!noTargetGet && O[key]) { + simple = true; + } + if (simple) O[key] = value; + else createNonEnumerableProperty(O, key, value); + // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative + }) (Function.prototype, 'toString', function toString() { + return typeof this == 'function' && getInternalState(this).source || inspectSource(this); + }); + }, + { + '../internals/create-non-enumerable-property': 56, + '../internals/global': 78, + '../internals/has': 79, + '../internals/inspect-source': 87, + '../internals/internal-state': 89, + '../internals/set-global': 134 + } + ], + 128: [ + function (_dereq_, module, exports) { + var classof = _dereq_('./classof-raw'); + var regexpExec = _dereq_('./regexp-exec'); + // `RegExpExec` abstract operation + // https://tc39.github.io/ecma262/#sec-regexpexec + module.exports = function (R, S) { + var exec = R.exec; + if (typeof exec === 'function') { + var result = exec.call(R, S); + if (typeof result !== 'object') { + throw TypeError('RegExp exec method returned something other than an Object or null'); + } + return result; + } + if (classof(R) !== 'RegExp') { + throw TypeError('RegExp#exec called on incompatible receiver'); + } + return regexpExec.call(R, S); + }; + }, + { + './classof-raw': 46, + './regexp-exec': 129 + } + ], + 129: [ + function (_dereq_, module, exports) { + 'use strict'; + var regexpFlags = _dereq_('./regexp-flags'); + var stickyHelpers = _dereq_('./regexp-sticky-helpers'); + var nativeExec = RegExp.prototype.exec; + // This always refers to the native implementation, because the + // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js, + // which loads this file before patching the method. + var nativeReplace = String.prototype.replace; + var patchedExec = nativeExec; + var UPDATES_LAST_INDEX_WRONG = function () { + var re1 = /a/; + var re2 = /b*/g; + nativeExec.call(re1, 'a'); + nativeExec.call(re2, 'a'); + return re1.lastIndex !== 0 || re2.lastIndex !== 0; + }(); + var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y || stickyHelpers.BROKEN_CARET; + // nonparticipating capturing group, copied from es5-shim's String#split patch. + var NPCG_INCLUDED = /()??/.exec('') [1] !== undefined; + var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y; + if (PATCH) { + patchedExec = function exec(str) { + var re = this; + var lastIndex, + reCopy, + match, + i; + var sticky = UNSUPPORTED_Y && re.sticky; + var flags = regexpFlags.call(re); + var source = re.source; + var charsAdded = 0; + var strCopy = str; + if (sticky) { + flags = flags.replace('y', ''); + if (flags.indexOf('g') === - 1) { + flags += 'g'; + } + strCopy = String(str).slice(re.lastIndex); + // Support anchored sticky behavior. + if (re.lastIndex > 0 && (!re.multiline || re.multiline && str[re.lastIndex - 1] !== '\n')) { + source = '(?: ' + source + ')'; + strCopy = ' ' + strCopy; + charsAdded++; + } // ^(? + rx + ) is needed, in combination with some str slicing, to + // simulate the 'y' flag. + + reCopy = new RegExp('^(?:' + source + ')', flags); + } + if (NPCG_INCLUDED) { + reCopy = new RegExp('^' + source + '$(?!\\s)', flags); + } + if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex; + match = nativeExec.call(sticky ? reCopy : re, strCopy); + if (sticky) { + if (match) { + match.input = match.input.slice(charsAdded); + match[0] = match[0].slice(charsAdded); + match.index = re.lastIndex; + re.lastIndex += match[0].length; + } else re.lastIndex = 0; + } else if (UPDATES_LAST_INDEX_WRONG && match) { + re.lastIndex = re.global ? match.index + match[0].length : lastIndex; + } + if (NPCG_INCLUDED && match && match.length > 1) { + // Fix browsers whose `exec` methods don't consistently return `undefined` + // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/ + nativeReplace.call(match[0], reCopy, function () { + for (i = 1; i < arguments.length - 2; i++) { + if (arguments[i] === undefined) match[i] = undefined; + } + }); + } + return match; + }; + } + module.exports = patchedExec; + }, + { + './regexp-flags': 130, + './regexp-sticky-helpers': 131 + } + ], + 130: [ + function (_dereq_, module, exports) { + 'use strict'; + var anObject = _dereq_('../internals/an-object'); + // `RegExp.prototype.flags` getter implementation + // https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags + module.exports = function () { + var that = anObject(this); + var result = ''; + if (that.global) result += 'g'; + if (that.ignoreCase) result += 'i'; + if (that.multiline) result += 'm'; + if (that.dotAll) result += 's'; + if (that.unicode) result += 'u'; + if (that.sticky) result += 'y'; + return result; + }; + }, + { + '../internals/an-object': 28 + } + ], + 131: [ + function (_dereq_, module, exports) { + 'use strict'; + var fails = _dereq_('./fails'); + // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError, + // so we use an intermediate function. + function RE(s, f) { + return RegExp(s, f); + } + exports.UNSUPPORTED_Y = fails(function () { + // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError + var re = RE('a', 'y'); + re.lastIndex = 2; + return re.exec('abcd') != null; + }); + exports.BROKEN_CARET = fails(function () { + // https://bugzilla.mozilla.org/show_bug.cgi?id=773687 + var re = RE('^r', 'gy'); + re.lastIndex = 2; + return re.exec('str') != null; + }); + }, + { + './fails': 69 + } + ], + 132: [ + function (_dereq_, module, exports) { + // `RequireObjectCoercible` abstract operation + // https://tc39.github.io/ecma262/#sec-requireobjectcoercible + module.exports = function (it) { + if (it == undefined) throw TypeError('Can\'t call method on ' + it); + return it; + }; + }, + { + } + ], + 133: [ + function (_dereq_, module, exports) { + // `SameValue` abstract operation + // https://tc39.github.io/ecma262/#sec-samevalue + module.exports = Object.is || function is(x, y) { + // eslint-disable-next-line no-self-compare + return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; + }; + }, + { + } + ], + 134: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + module.exports = function (key, value) { + try { + createNonEnumerableProperty(global, key, value); + } catch (error) { + global[key] = value; + } + return value; + }; + }, + { + '../internals/create-non-enumerable-property': 56, + '../internals/global': 78 + } + ], + 135: [ + function (_dereq_, module, exports) { + 'use strict'; + var getBuiltIn = _dereq_('../internals/get-built-in'); + var definePropertyModule = _dereq_('../internals/object-define-property'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var SPECIES = wellKnownSymbol('species'); + module.exports = function (CONSTRUCTOR_NAME) { + var Constructor = getBuiltIn(CONSTRUCTOR_NAME); + var defineProperty = definePropertyModule.f; + if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) { + defineProperty(Constructor, SPECIES, { + configurable: true, + get: function () { + return this; + } + }); + } + }; + }, + { + '../internals/descriptors': 61, + '../internals/get-built-in': 75, + '../internals/object-define-property': 111, + '../internals/well-known-symbol': 167 + } + ], + 136: [ + function (_dereq_, module, exports) { + var defineProperty = _dereq_('../internals/object-define-property').f; + var has = _dereq_('../internals/has'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + module.exports = function (it, TAG, STATIC) { + if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) { + defineProperty(it, TO_STRING_TAG, { + configurable: true, + value: TAG + }); + } + }; + }, + { + '../internals/has': 79, + '../internals/object-define-property': 111, + '../internals/well-known-symbol': 167 + } + ], + 137: [ + function (_dereq_, module, exports) { + var shared = _dereq_('../internals/shared'); + var uid = _dereq_('../internals/uid'); + var keys = shared('keys'); + module.exports = function (key) { + return keys[key] || (keys[key] = uid(key)); + }; + }, + { + '../internals/shared': 139, + '../internals/uid': 164 + } + ], + 138: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var setGlobal = _dereq_('../internals/set-global'); + var SHARED = '__core-js_shared__'; + var store = global[SHARED] || setGlobal(SHARED, { + }); + module.exports = store; + }, + { + '../internals/global': 78, + '../internals/set-global': 134 + } + ], + 139: [ + function (_dereq_, module, exports) { + var IS_PURE = _dereq_('../internals/is-pure'); + var store = _dereq_('../internals/shared-store'); + (module.exports = function (key, value) { + return store[key] || (store[key] = value !== undefined ? value : { + }); + }) ('versions', [ + ]).push({ + version: '3.6.5', + mode: IS_PURE ? 'pure' : 'global', + copyright: '© 2020 Denis Pushkarev (zloirock.ru)' + }); + }, + { + '../internals/is-pure': 94, + '../internals/shared-store': 138 + } + ], + 140: [ + function (_dereq_, module, exports) { + var anObject = _dereq_('../internals/an-object'); + var aFunction = _dereq_('../internals/a-function'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var SPECIES = wellKnownSymbol('species'); + // `SpeciesConstructor` abstract operation + // https://tc39.github.io/ecma262/#sec-speciesconstructor + module.exports = function (O, defaultConstructor) { + var C = anObject(O).constructor; + var S; + return C === undefined || (S = anObject(C) [SPECIES]) == undefined ? defaultConstructor : aFunction(S); + }; + }, + { + '../internals/a-function': 23, + '../internals/an-object': 28, + '../internals/well-known-symbol': 167 + } + ], + 141: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + // check the existence of a method, lowercase + // of a tag and escaping quotes in arguments + module.exports = function (METHOD_NAME) { + return fails(function () { + var test = ''[METHOD_NAME]('"'); + return test !== test.toLowerCase() || test.split('"').length > 3; + }); + }; + }, + { + '../internals/fails': 69 + } + ], + 142: [ + function (_dereq_, module, exports) { + var toInteger = _dereq_('../internals/to-integer'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + // `String.prototype.{ codePointAt, at }` methods implementation + var createMethod = function (CONVERT_TO_STRING) { + return function ($this, pos) { + var S = String(requireObjectCoercible($this)); + var position = toInteger(pos); + var size = S.length; + var first, + second; + if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; + first = S.charCodeAt(position); + return first < 55296 || first > 56319 || position + 1 === size || (second = S.charCodeAt(position + 1)) < 56320 || second > 57343 ? CONVERT_TO_STRING ? S.charAt(position) : first : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 55296 << 10) + (second - 56320) + 65536; + }; + }; + module.exports = { + // `String.prototype.codePointAt` method + // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat + codeAt: createMethod(false), + // `String.prototype.at` method + // https://github.com/mathiasbynens/String.prototype.at + charAt: createMethod(true) + }; + }, + { + '../internals/require-object-coercible': 132, + '../internals/to-integer': 154 + } + ], + 143: [ + function (_dereq_, module, exports) { + // https://github.com/zloirock/core-js/issues/280 + var userAgent = _dereq_('../internals/engine-user-agent'); + // eslint-disable-next-line unicorn/no-unsafe-regex + module.exports = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent); + }, + { + '../internals/engine-user-agent': 65 + } + ], + 144: [ + function (_dereq_, module, exports) { + // https://github.com/tc39/proposal-string-pad-start-end + var toLength = _dereq_('../internals/to-length'); + var repeat = _dereq_('../internals/string-repeat'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var ceil = Math.ceil; + // `String.prototype.{ padStart, padEnd }` methods implementation + var createMethod = function (IS_END) { + return function ($this, maxLength, fillString) { + var S = String(requireObjectCoercible($this)); + var stringLength = S.length; + var fillStr = fillString === undefined ? ' ' : String(fillString); + var intMaxLength = toLength(maxLength); + var fillLen, + stringFiller; + if (intMaxLength <= stringLength || fillStr == '') return S; + fillLen = intMaxLength - stringLength; + stringFiller = repeat.call(fillStr, ceil(fillLen / fillStr.length)); + if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); + return IS_END ? S + stringFiller : stringFiller + S; + }; + }; + module.exports = { + // `String.prototype.padStart` method + // https://tc39.github.io/ecma262/#sec-string.prototype.padstart + start: createMethod(false), + // `String.prototype.padEnd` method + // https://tc39.github.io/ecma262/#sec-string.prototype.padend + end: createMethod(true) + }; + }, + { + '../internals/require-object-coercible': 132, + '../internals/string-repeat': 146, + '../internals/to-length': 155 + } + ], + 145: [ + function (_dereq_, module, exports) { + 'use strict'; + // based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js + var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + var base = 36; + var tMin = 1; + var tMax = 26; + var skew = 38; + var damp = 700; + var initialBias = 72; + var initialN = 128; // 0x80 + var delimiter = '-'; // '\x2D' + var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars + var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process'; + var baseMinusTMin = base - tMin; + var floor = Math.floor; + var stringFromCharCode = String.fromCharCode; + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + */ + var ucs2decode = function (string) { + var output = [ + ]; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 55296 && value <= 56319 && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 64512) == 56320) { + // Low surrogate. + output.push(((value & 1023) << 10) + (extra & 1023) + 65536); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + }; + /** + * Converts a digit/integer into a basic code point. + */ + var digitToBasic = function (digit) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26); + }; + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + */ + var adapt = function (delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + }; + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + */ + // eslint-disable-next-line max-statements + var encode = function (input) { + var output = [ + ]; + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + // Cache the length. + var inputLength = input.length; + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + var i, + currentValue; + // Handle the basic code points. + for (i = 0; i < input.length; i++) { + currentValue = input[i]; + if (currentValue < 128) { + output.push(stringFromCharCode(currentValue)); + } + } + var basicLength = output.length; // number of basic code points. + var handledCPCount = basicLength; // number of code points that have been handled; + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } // Main encoding loop: + + while (handledCPCount < inputLength) { + // All non-basic code points < n have been handled already. Find the next larger one: + var m = maxInt; + for (i = 0; i < input.length; i++) { + currentValue = input[i]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } // Increase `delta` enough to advance the decoder's state to , but guard against overflow. + + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + throw RangeError(OVERFLOW_ERROR); + } + delta += (m - n) * handledCPCountPlusOne; + n = m; + for (i = 0; i < input.length; i++) { + currentValue = input[i]; + if (currentValue < n && ++delta > maxInt) { + throw RangeError(OVERFLOW_ERROR); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for /* no condition */ + (var k = base; ; k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) break; + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT))); + q = floor(qMinusT / baseMinusT); + } + output.push(stringFromCharCode(digitToBasic(q))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + ++delta; + ++n; + } + return output.join(''); + }; + module.exports = function (input) { + var encoded = [ + ]; + var labels = input.toLowerCase().replace(regexSeparators, '.').split('.'); + var i, + label; + for (i = 0; i < labels.length; i++) { + label = labels[i]; + encoded.push(regexNonASCII.test(label) ? 'xn--' + encode(label) : label); + } + return encoded.join('.'); + }; + }, + { + } + ], + 146: [ + function (_dereq_, module, exports) { + 'use strict'; + var toInteger = _dereq_('../internals/to-integer'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + // `String.prototype.repeat` method implementation + // https://tc39.github.io/ecma262/#sec-string.prototype.repeat + module.exports = ''.repeat || function repeat(count) { + var str = String(requireObjectCoercible(this)); + var result = ''; + var n = toInteger(count); + if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions'); + for (; n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str; + return result; + }; + }, + { + '../internals/require-object-coercible': 132, + '../internals/to-integer': 154 + } + ], + 147: [ + function (_dereq_, module, exports) { + var fails = _dereq_('../internals/fails'); + var whitespaces = _dereq_('../internals/whitespaces'); + var non = '​…᠎'; + // check that a method works with the correct list + // of whitespaces and has a correct name + module.exports = function (METHOD_NAME) { + return fails(function () { + return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME; + }); + }; + }, + { + '../internals/fails': 69, + '../internals/whitespaces': 168 + } + ], + 148: [ + function (_dereq_, module, exports) { + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var whitespaces = _dereq_('../internals/whitespaces'); + var whitespace = '[' + whitespaces + ']'; + var ltrim = RegExp('^' + whitespace + whitespace + '*'); + var rtrim = RegExp(whitespace + whitespace + '*$'); + // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation + var createMethod = function (TYPE) { + return function ($this) { + var string = String(requireObjectCoercible($this)); + if (TYPE & 1) string = string.replace(ltrim, ''); + if (TYPE & 2) string = string.replace(rtrim, ''); + return string; + }; + }; + module.exports = { + // `String.prototype.{ trimLeft, trimStart }` methods + // https://tc39.github.io/ecma262/#sec-string.prototype.trimstart + start: createMethod(1), + // `String.prototype.{ trimRight, trimEnd }` methods + // https://tc39.github.io/ecma262/#sec-string.prototype.trimend + end: createMethod(2), + // `String.prototype.trim` method + // https://tc39.github.io/ecma262/#sec-string.prototype.trim + trim: createMethod(3) + }; + }, + { + '../internals/require-object-coercible': 132, + '../internals/whitespaces': 168 + } + ], + 149: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var fails = _dereq_('../internals/fails'); + var classof = _dereq_('../internals/classof-raw'); + var bind = _dereq_('../internals/function-bind-context'); + var html = _dereq_('../internals/html'); + var createElement = _dereq_('../internals/document-create-element'); + var IS_IOS = _dereq_('../internals/engine-is-ios'); + var location = global.location; + var set = global.setImmediate; + var clear = global.clearImmediate; + var process = global.process; + var MessageChannel = global.MessageChannel; + var Dispatch = global.Dispatch; + var counter = 0; + var queue = { + }; + var ONREADYSTATECHANGE = 'onreadystatechange'; + var defer, + channel, + port; + var run = function (id) { + // eslint-disable-next-line no-prototype-builtins + if (queue.hasOwnProperty(id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } + }; + var runner = function (id) { + return function () { + run(id); + }; + }; + var listener = function (event) { + run(event.data); + }; + var post = function (id) { + // old engines have not location.origin + global.postMessage(id + '', location.protocol + '//' + location.host); + }; + // Node.js 0.9+ & IE10+ has setImmediate, otherwise: + if (!set || !clear) { + set = function setImmediate(fn) { + var args = [ + ]; + var i = 1; + while (arguments.length > i) args.push(arguments[i++]); + queue[++counter] = function () { + // eslint-disable-next-line no-new-func + (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args); + }; + defer(counter); + return counter; + }; + clear = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (classof(process) == 'process') { + defer = function (id) { + process.nextTick(runner(id)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(runner(id)); + }; + // Browsers with MessageChannel, includes WebWorkers + // except iOS - https://github.com/zloirock/core-js/issues/624 + } else if (MessageChannel && !IS_IOS) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = listener; + defer = bind(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts && !fails(post) && location.protocol !== 'file:') { + defer = post; + global.addEventListener('message', listener, false); + // IE8- + } else if (ONREADYSTATECHANGE in createElement('script')) { + defer = function (id) { + html.appendChild(createElement('script')) [ONREADYSTATECHANGE] = function () { + html.removeChild(this); + run(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(runner(id), 0); + }; + } + } + module.exports = { + set: set, + clear: clear + }; + }, + { + '../internals/classof-raw': 46, + '../internals/document-create-element': 62, + '../internals/engine-is-ios': 64, + '../internals/fails': 69, + '../internals/function-bind-context': 73, + '../internals/global': 78, + '../internals/html': 82 + } + ], + 150: [ + function (_dereq_, module, exports) { + var classof = _dereq_('../internals/classof-raw'); + // `thisNumberValue` abstract operation + // https://tc39.github.io/ecma262/#sec-thisnumbervalue + module.exports = function (value) { + if (typeof value != 'number' && classof(value) != 'Number') { + throw TypeError('Incorrect invocation'); + } + return + value; + }; + }, + { + '../internals/classof-raw': 46 + } + ], + 151: [ + function (_dereq_, module, exports) { + var toInteger = _dereq_('../internals/to-integer'); + var max = Math.max; + var min = Math.min; + // Helper for a popular repeating case of the spec: + // Let integer be ? ToInteger(index). + // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). + module.exports = function (index, length) { + var integer = toInteger(index); + return integer < 0 ? max(integer + length, 0) : min(integer, length); + }; + }, + { + '../internals/to-integer': 154 + } + ], + 152: [ + function (_dereq_, module, exports) { + var toInteger = _dereq_('../internals/to-integer'); + var toLength = _dereq_('../internals/to-length'); + // `ToIndex` abstract operation + // https://tc39.github.io/ecma262/#sec-toindex + module.exports = function (it) { + if (it === undefined) return 0; + var number = toInteger(it); + var length = toLength(number); + if (number !== length) throw RangeError('Wrong length or index'); + return length; + }; + }, + { + '../internals/to-integer': 154, + '../internals/to-length': 155 + } + ], + 153: [ + function (_dereq_, module, exports) { + // toObject with fallback for non-array-like ES3 strings + var IndexedObject = _dereq_('../internals/indexed-object'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + module.exports = function (it) { + return IndexedObject(requireObjectCoercible(it)); + }; + }, + { + '../internals/indexed-object': 85, + '../internals/require-object-coercible': 132 + } + ], + 154: [ + function (_dereq_, module, exports) { + var ceil = Math.ceil; + var floor = Math.floor; + // `ToInteger` abstract operation + // https://tc39.github.io/ecma262/#sec-tointeger + module.exports = function (argument) { + return isNaN(argument = + argument) ? 0 : (argument > 0 ? floor : ceil) (argument); + }; + }, + { + } + ], + 155: [ + function (_dereq_, module, exports) { + var toInteger = _dereq_('../internals/to-integer'); + var min = Math.min; + // `ToLength` abstract operation + // https://tc39.github.io/ecma262/#sec-tolength + module.exports = function (argument) { + return argument > 0 ? min(toInteger(argument), 9007199254740991) : 0; // 2 ** 53 - 1 == 9007199254740991 + }; + }, + { + '../internals/to-integer': 154 + } + ], + 156: [ + function (_dereq_, module, exports) { + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + // `ToObject` abstract operation + // https://tc39.github.io/ecma262/#sec-toobject + module.exports = function (argument) { + return Object(requireObjectCoercible(argument)); + }; + }, + { + '../internals/require-object-coercible': 132 + } + ], + 157: [ + function (_dereq_, module, exports) { + var toPositiveInteger = _dereq_('../internals/to-positive-integer'); + module.exports = function (it, BYTES) { + var offset = toPositiveInteger(it); + if (offset % BYTES) throw RangeError('Wrong offset'); + return offset; + }; + }, + { + '../internals/to-positive-integer': 158 + } + ], + 158: [ + function (_dereq_, module, exports) { + var toInteger = _dereq_('../internals/to-integer'); + module.exports = function (it) { + var result = toInteger(it); + if (result < 0) throw RangeError('The argument can\'t be less than 0'); + return result; + }; + }, + { + '../internals/to-integer': 154 + } + ], + 159: [ + function (_dereq_, module, exports) { + var isObject = _dereq_('../internals/is-object'); + // `ToPrimitive` abstract operation + // https://tc39.github.io/ecma262/#sec-toprimitive + // instead of the ES6 spec version, we didn't implement @@toPrimitive case + // and the second argument - flag - preferred type is a string + module.exports = function (input, PREFERRED_STRING) { + if (!isObject(input)) return input; + var fn, + val; + if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; + if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val; + if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; + throw TypeError('Can\'t convert object to primitive value'); + }; + }, + { + '../internals/is-object': 93 + } + ], + 160: [ + function (_dereq_, module, exports) { + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + var test = { + }; + test[TO_STRING_TAG] = 'z'; + module.exports = String(test) === '[object z]'; + }, + { + '../internals/well-known-symbol': 167 + } + ], + 161: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var global = _dereq_('../internals/global'); + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = _dereq_('../internals/typed-array-constructors-require-wrappers'); + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var ArrayBufferModule = _dereq_('../internals/array-buffer'); + var anInstance = _dereq_('../internals/an-instance'); + var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var toLength = _dereq_('../internals/to-length'); + var toIndex = _dereq_('../internals/to-index'); + var toOffset = _dereq_('../internals/to-offset'); + var toPrimitive = _dereq_('../internals/to-primitive'); + var has = _dereq_('../internals/has'); + var classof = _dereq_('../internals/classof'); + var isObject = _dereq_('../internals/is-object'); + var create = _dereq_('../internals/object-create'); + var setPrototypeOf = _dereq_('../internals/object-set-prototype-of'); + var getOwnPropertyNames = _dereq_('../internals/object-get-own-property-names').f; + var typedArrayFrom = _dereq_('../internals/typed-array-from'); + var forEach = _dereq_('../internals/array-iteration').forEach; + var setSpecies = _dereq_('../internals/set-species'); + var definePropertyModule = _dereq_('../internals/object-define-property'); + var getOwnPropertyDescriptorModule = _dereq_('../internals/object-get-own-property-descriptor'); + var InternalStateModule = _dereq_('../internals/internal-state'); + var inheritIfRequired = _dereq_('../internals/inherit-if-required'); + var getInternalState = InternalStateModule.get; + var setInternalState = InternalStateModule.set; + var nativeDefineProperty = definePropertyModule.f; + var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; + var round = Math.round; + var RangeError = global.RangeError; + var ArrayBuffer = ArrayBufferModule.ArrayBuffer; + var DataView = ArrayBufferModule.DataView; + var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; + var TYPED_ARRAY_TAG = ArrayBufferViewCore.TYPED_ARRAY_TAG; + var TypedArray = ArrayBufferViewCore.TypedArray; + var TypedArrayPrototype = ArrayBufferViewCore.TypedArrayPrototype; + var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; + var isTypedArray = ArrayBufferViewCore.isTypedArray; + var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; + var WRONG_LENGTH = 'Wrong length'; + var fromList = function (C, list) { + var index = 0; + var length = list.length; + var result = new (aTypedArrayConstructor(C)) (length); + while (length > index) result[index] = list[index++]; + return result; + }; + var addGetter = function (it, key) { + nativeDefineProperty(it, key, { + get: function () { + return getInternalState(this) [key]; + } + }); + }; + var isArrayBuffer = function (it) { + var klass; + return it instanceof ArrayBuffer || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer'; + }; + var isTypedArrayIndex = function (target, key) { + return isTypedArray(target) && typeof key != 'symbol' && key in target && String( + key) == String(key); + }; + var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) { + return isTypedArrayIndex(target, key = toPrimitive(key, true)) ? createPropertyDescriptor(2, target[key]) : nativeGetOwnPropertyDescriptor(target, key); + }; + var wrappedDefineProperty = function defineProperty(target, key, descriptor) { + if (isTypedArrayIndex(target, key = toPrimitive(key, true)) && isObject(descriptor) && has(descriptor, 'value') && !has(descriptor, 'get') && !has(descriptor, 'set') // TODO: add validation descriptor w/o calling accessors + && !descriptor.configurable && (!has(descriptor, 'writable') || descriptor.writable) && (!has(descriptor, 'enumerable') || descriptor.enumerable)) { + target[key] = descriptor.value; + return target; + } + return nativeDefineProperty(target, key, descriptor); + }; + if (DESCRIPTORS) { + if (!NATIVE_ARRAY_BUFFER_VIEWS) { + getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor; + definePropertyModule.f = wrappedDefineProperty; + addGetter(TypedArrayPrototype, 'buffer'); + addGetter(TypedArrayPrototype, 'byteOffset'); + addGetter(TypedArrayPrototype, 'byteLength'); + addGetter(TypedArrayPrototype, 'length'); + } + $({ + target: 'Object', + stat: true, + forced: !NATIVE_ARRAY_BUFFER_VIEWS + }, { + getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor, + defineProperty: wrappedDefineProperty + }); + module.exports = function (TYPE, wrapper, CLAMPED) { + var BYTES = TYPE.match(/\d+$/) [0] / 8; + var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array'; + var GETTER = 'get' + TYPE; + var SETTER = 'set' + TYPE; + var NativeTypedArrayConstructor = global[CONSTRUCTOR_NAME]; + var TypedArrayConstructor = NativeTypedArrayConstructor; + var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype; + var exported = { + }; + var getter = function (that, index) { + var data = getInternalState(that); + return data.view[GETTER](index * BYTES + data.byteOffset, true); + }; + var setter = function (that, index, value) { + var data = getInternalState(that); + if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 255 ? 255 : value & 255; + data.view[SETTER](index * BYTES + data.byteOffset, value, true); + }; + var addElement = function (that, index) { + nativeDefineProperty(that, index, { + get: function () { + return getter(this, index); + }, + set: function (value) { + return setter(this, index, value); + }, + enumerable: true + }); + }; + if (!NATIVE_ARRAY_BUFFER_VIEWS) { + TypedArrayConstructor = wrapper(function (that, data, offset, $length) { + anInstance(that, TypedArrayConstructor, CONSTRUCTOR_NAME); + var index = 0; + var byteOffset = 0; + var buffer, + byteLength, + length; + if (!isObject(data)) { + length = toIndex(data); + byteLength = length * BYTES; + buffer = new ArrayBuffer(byteLength); + } else if (isArrayBuffer(data)) { + buffer = data; + byteOffset = toOffset(offset, BYTES); + var $len = data.byteLength; + if ($length === undefined) { + if ($len % BYTES) throw RangeError(WRONG_LENGTH); + byteLength = $len - byteOffset; + if (byteLength < 0) throw RangeError(WRONG_LENGTH); + } else { + byteLength = toLength($length) * BYTES; + if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH); + } + length = byteLength / BYTES; + } else if (isTypedArray(data)) { + return fromList(TypedArrayConstructor, data); + } else { + return typedArrayFrom.call(TypedArrayConstructor, data); + } + setInternalState(that, { + buffer: buffer, + byteOffset: byteOffset, + byteLength: byteLength, + length: length, + view: new DataView(buffer) + }); + while (index < length) addElement(that, index++); + }); + if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); + TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create(TypedArrayPrototype); + } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) { + TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) { + anInstance(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME); + return inheritIfRequired(function () { + if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data)); + if (isArrayBuffer(data)) return $length !== undefined ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length) : typedArrayOffset !== undefined ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES)) : new NativeTypedArrayConstructor(data); + if (isTypedArray(data)) return fromList(TypedArrayConstructor, data); + return typedArrayFrom.call(TypedArrayConstructor, data); + }(), dummy, TypedArrayConstructor); + }); + if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); + forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) { + if (!(key in TypedArrayConstructor)) { + createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]); + } + }); + TypedArrayConstructor.prototype = TypedArrayConstructorPrototype; + } + if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) { + createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor); + } + if (TYPED_ARRAY_TAG) { + createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME); + } + exported[CONSTRUCTOR_NAME] = TypedArrayConstructor; + $({ + global: true, + forced: TypedArrayConstructor != NativeTypedArrayConstructor, + sham: !NATIVE_ARRAY_BUFFER_VIEWS + }, exported); + if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) { + createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES); + } + if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) { + createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES); + } + setSpecies(CONSTRUCTOR_NAME); + }; + } else module.exports = function () { /* empty */ + }; + }, + { + '../internals/an-instance': 27, + '../internals/array-buffer': 31, + '../internals/array-buffer-view-core': 30, + '../internals/array-iteration': 37, + '../internals/classof': 47, + '../internals/create-non-enumerable-property': 56, + '../internals/create-property-descriptor': 57, + '../internals/descriptors': 61, + '../internals/export': 68, + '../internals/global': 78, + '../internals/has': 79, + '../internals/inherit-if-required': 86, + '../internals/internal-state': 89, + '../internals/is-object': 93, + '../internals/object-create': 109, + '../internals/object-define-property': 111, + '../internals/object-get-own-property-descriptor': 112, + '../internals/object-get-own-property-names': 114, + '../internals/object-set-prototype-of': 120, + '../internals/set-species': 135, + '../internals/to-index': 152, + '../internals/to-length': 155, + '../internals/to-offset': 157, + '../internals/to-primitive': 159, + '../internals/typed-array-constructors-require-wrappers': 162, + '../internals/typed-array-from': 163 + } + ], + 162: [ + function (_dereq_, module, exports) { + /* eslint-disable no-new */ + var global = _dereq_('../internals/global'); + var fails = _dereq_('../internals/fails'); + var checkCorrectnessOfIteration = _dereq_('../internals/check-correctness-of-iteration'); + var NATIVE_ARRAY_BUFFER_VIEWS = _dereq_('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER_VIEWS; + var ArrayBuffer = global.ArrayBuffer; + var Int8Array = global.Int8Array; + module.exports = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () { + Int8Array(1); + }) || !fails(function () { + new Int8Array( - 1); + }) || !checkCorrectnessOfIteration(function (iterable) { + new Int8Array(); + new Int8Array(null); + new Int8Array(1.5); + new Int8Array(iterable); + }, true) || fails(function () { + // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill + return new Int8Array(new ArrayBuffer(2), 1, undefined).length !== 1; + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/check-correctness-of-iteration': 45, + '../internals/fails': 69, + '../internals/global': 78 + } + ], + 163: [ + function (_dereq_, module, exports) { + var toObject = _dereq_('../internals/to-object'); + var toLength = _dereq_('../internals/to-length'); + var getIteratorMethod = _dereq_('../internals/get-iterator-method'); + var isArrayIteratorMethod = _dereq_('../internals/is-array-iterator-method'); + var bind = _dereq_('../internals/function-bind-context'); + var aTypedArrayConstructor = _dereq_('../internals/array-buffer-view-core').aTypedArrayConstructor; + module.exports = function from(source /* , mapfn, thisArg */ ) { + var O = toObject(source); + var argumentsLength = arguments.length; + var mapfn = argumentsLength > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var iteratorMethod = getIteratorMethod(O); + var i, + length, + result, + step, + iterator, + next; + if (iteratorMethod != undefined && !isArrayIteratorMethod(iteratorMethod)) { + iterator = iteratorMethod.call(O); + next = iterator.next; + O = [ + ]; + while (!(step = next.call(iterator)).done) { + O.push(step.value); + } + } + if (mapping && argumentsLength > 2) { + mapfn = bind(mapfn, arguments[2], 2); + } + length = toLength(O.length); + result = new (aTypedArrayConstructor(this)) (length); + for (i = 0; length > i; i++) { + result[i] = mapping ? mapfn(O[i], i) : O[i]; + } + return result; + }; + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/function-bind-context': 73, + '../internals/get-iterator-method': 76, + '../internals/is-array-iterator-method': 90, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 164: [ + function (_dereq_, module, exports) { + var id = 0; + var postfix = Math.random(); + module.exports = function (key) { + return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36); + }; + }, + { + } + ], + 165: [ + function (_dereq_, module, exports) { + var NATIVE_SYMBOL = _dereq_('../internals/native-symbol'); + module.exports = NATIVE_SYMBOL // eslint-disable-next-line no-undef + && !Symbol.sham // eslint-disable-next-line no-undef + && typeof Symbol.iterator == 'symbol'; + }, + { + '../internals/native-symbol': 102 + } + ], + 166: [ + function (_dereq_, module, exports) { + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + exports.f = wellKnownSymbol; + }, + { + '../internals/well-known-symbol': 167 + } + ], + 167: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var shared = _dereq_('../internals/shared'); + var has = _dereq_('../internals/has'); + var uid = _dereq_('../internals/uid'); + var NATIVE_SYMBOL = _dereq_('../internals/native-symbol'); + var USE_SYMBOL_AS_UID = _dereq_('../internals/use-symbol-as-uid'); + var WellKnownSymbolsStore = shared('wks'); + var Symbol = global.Symbol; + var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid; + module.exports = function (name) { + if (!has(WellKnownSymbolsStore, name)) { + if (NATIVE_SYMBOL && has(Symbol, name)) WellKnownSymbolsStore[name] = Symbol[name]; + else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name); + } + return WellKnownSymbolsStore[name]; + }; + }, + { + '../internals/global': 78, + '../internals/has': 79, + '../internals/native-symbol': 102, + '../internals/shared': 139, + '../internals/uid': 164, + '../internals/use-symbol-as-uid': 165 + } + ], + 168: [ + function (_dereq_, module, exports) { + // a string of all valid unicode whitespaces + // eslint-disable-next-line max-len + module.exports = '\t\n\v\f\r                 \u2028\u2029'; + }, + { + } + ], + 169: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var global = _dereq_('../internals/global'); + var arrayBufferModule = _dereq_('../internals/array-buffer'); + var setSpecies = _dereq_('../internals/set-species'); + var ARRAY_BUFFER = 'ArrayBuffer'; + var ArrayBuffer = arrayBufferModule[ARRAY_BUFFER]; + var NativeArrayBuffer = global[ARRAY_BUFFER]; + // `ArrayBuffer` constructor + // https://tc39.github.io/ecma262/#sec-arraybuffer-constructor + $({ + global: true, + forced: NativeArrayBuffer !== ArrayBuffer + }, { + ArrayBuffer: ArrayBuffer + }); + setSpecies(ARRAY_BUFFER); + }, + { + '../internals/array-buffer': 31, + '../internals/export': 68, + '../internals/global': 78, + '../internals/set-species': 135 + } + ], + 170: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var fails = _dereq_('../internals/fails'); + var isArray = _dereq_('../internals/is-array'); + var isObject = _dereq_('../internals/is-object'); + var toObject = _dereq_('../internals/to-object'); + var toLength = _dereq_('../internals/to-length'); + var createProperty = _dereq_('../internals/create-property'); + var arraySpeciesCreate = _dereq_('../internals/array-species-create'); + var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var V8_VERSION = _dereq_('../internals/engine-v8-version'); + var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); + var MAX_SAFE_INTEGER = 9007199254740991; + var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; + // We can't use this feature detection in V8 since it causes + // deoptimization and serious performance degradation + // https://github.com/zloirock/core-js/issues/679 + var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () { + var array = [ + ]; + array[IS_CONCAT_SPREADABLE] = false; + return array.concat() [0] !== array; + }); + var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); + var isConcatSpreadable = function (O) { + if (!isObject(O)) return false; + var spreadable = O[IS_CONCAT_SPREADABLE]; + return spreadable !== undefined ? !!spreadable : isArray(O); + }; + var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; + // `Array.prototype.concat` method + // https://tc39.github.io/ecma262/#sec-array.prototype.concat + // with adding support of @@isConcatSpreadable and @@species + $({ + target: 'Array', + proto: true, + forced: FORCED + }, { + concat: function concat(arg) { + // eslint-disable-line no-unused-vars + var O = toObject(this); + var A = arraySpeciesCreate(O, 0); + var n = 0; + var i, + k, + length, + len, + E; + for (i = - 1, length = arguments.length; i < length; i++) { + E = i === - 1 ? O : arguments[i]; + if (isConcatSpreadable(E)) { + len = toLength(E.length); + if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); + for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]); + } else { + if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); + createProperty(A, n++, E); + } + } + A.length = n; + return A; + } + }); + }, + { + '../internals/array-method-has-species-support': 39, + '../internals/array-species-create': 43, + '../internals/create-property': 58, + '../internals/engine-v8-version': 66, + '../internals/export': 68, + '../internals/fails': 69, + '../internals/is-array': 91, + '../internals/is-object': 93, + '../internals/to-length': 155, + '../internals/to-object': 156, + '../internals/well-known-symbol': 167 + } + ], + 171: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var copyWithin = _dereq_('../internals/array-copy-within'); + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + // `Array.prototype.copyWithin` method + // https://tc39.github.io/ecma262/#sec-array.prototype.copywithin + $({ + target: 'Array', + proto: true + }, { + copyWithin: copyWithin + }); + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + addToUnscopables('copyWithin'); + }, + { + '../internals/add-to-unscopables': 25, + '../internals/array-copy-within': 32, + '../internals/export': 68 + } + ], + 172: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var $every = _dereq_('../internals/array-iteration').every; + var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var STRICT_METHOD = arrayMethodIsStrict('every'); + var USES_TO_LENGTH = arrayMethodUsesToLength('every'); + // `Array.prototype.every` method + // https://tc39.github.io/ecma262/#sec-array.prototype.every + $({ + target: 'Array', + proto: true, + forced: !STRICT_METHOD || !USES_TO_LENGTH + }, { + every: function every(callbackfn /* , thisArg */ ) { + return $every(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + }, + { + '../internals/array-iteration': 37, + '../internals/array-method-is-strict': 40, + '../internals/array-method-uses-to-length': 41, + '../internals/export': 68 + } + ], + 173: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var fill = _dereq_('../internals/array-fill'); + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + // `Array.prototype.fill` method + // https://tc39.github.io/ecma262/#sec-array.prototype.fill + $({ + target: 'Array', + proto: true + }, { + fill: fill + }); + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + addToUnscopables('fill'); + }, + { + '../internals/add-to-unscopables': 25, + '../internals/array-fill': 33, + '../internals/export': 68 + } + ], + 174: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var $filter = _dereq_('../internals/array-iteration').filter; + var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter'); + // Edge 14- issue + var USES_TO_LENGTH = arrayMethodUsesToLength('filter'); + // `Array.prototype.filter` method + // https://tc39.github.io/ecma262/#sec-array.prototype.filter + // with adding support of @@species + $({ + target: 'Array', + proto: true, + forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH + }, { + filter: function filter(callbackfn /* , thisArg */ ) { + return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + }, + { + '../internals/array-iteration': 37, + '../internals/array-method-has-species-support': 39, + '../internals/array-method-uses-to-length': 41, + '../internals/export': 68 + } + ], + 175: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var $findIndex = _dereq_('../internals/array-iteration').findIndex; + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var FIND_INDEX = 'findIndex'; + var SKIPS_HOLES = true; + var USES_TO_LENGTH = arrayMethodUsesToLength(FIND_INDEX); + // Shouldn't skip holes + if (FIND_INDEX in [ + ]) Array(1) [FIND_INDEX](function () { + SKIPS_HOLES = false; + }); + // `Array.prototype.findIndex` method + // https://tc39.github.io/ecma262/#sec-array.prototype.findindex + $({ + target: 'Array', + proto: true, + forced: SKIPS_HOLES || !USES_TO_LENGTH + }, { + findIndex: function findIndex(callbackfn /* , that = undefined */ ) { + return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + addToUnscopables(FIND_INDEX); + }, + { + '../internals/add-to-unscopables': 25, + '../internals/array-iteration': 37, + '../internals/array-method-uses-to-length': 41, + '../internals/export': 68 + } + ], + 176: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var flattenIntoArray = _dereq_('../internals/flatten-into-array'); + var toObject = _dereq_('../internals/to-object'); + var toLength = _dereq_('../internals/to-length'); + var aFunction = _dereq_('../internals/a-function'); + var arraySpeciesCreate = _dereq_('../internals/array-species-create'); + // `Array.prototype.flatMap` method + // https://github.com/tc39/proposal-flatMap + $({ + target: 'Array', + proto: true + }, { + flatMap: function flatMap(callbackfn /* , thisArg */ ) { + var O = toObject(this); + var sourceLen = toLength(O.length); + var A; + aFunction(callbackfn); + A = arraySpeciesCreate(O, 0); + A.length = flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + return A; + } + }); + }, + { + '../internals/a-function': 23, + '../internals/array-species-create': 43, + '../internals/export': 68, + '../internals/flatten-into-array': 71, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 177: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var flattenIntoArray = _dereq_('../internals/flatten-into-array'); + var toObject = _dereq_('../internals/to-object'); + var toLength = _dereq_('../internals/to-length'); + var toInteger = _dereq_('../internals/to-integer'); + var arraySpeciesCreate = _dereq_('../internals/array-species-create'); + // `Array.prototype.flat` method + // https://github.com/tc39/proposal-flatMap + $({ + target: 'Array', + proto: true + }, { + flat: function flat( /* depthArg = 1 */ + ) { + var depthArg = arguments.length ? arguments[0] : undefined; + var O = toObject(this); + var sourceLen = toLength(O.length); + var A = arraySpeciesCreate(O, 0); + A.length = flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); + return A; + } + }); + }, + { + '../internals/array-species-create': 43, + '../internals/export': 68, + '../internals/flatten-into-array': 71, + '../internals/to-integer': 154, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 178: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var forEach = _dereq_('../internals/array-for-each'); + // `Array.prototype.forEach` method + // https://tc39.github.io/ecma262/#sec-array.prototype.foreach + $({ + target: 'Array', + proto: true, + forced: [ + ].forEach != forEach + }, { + forEach: forEach + }); + }, + { + '../internals/array-for-each': 34, + '../internals/export': 68 + } + ], + 179: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var from = _dereq_('../internals/array-from'); + var checkCorrectnessOfIteration = _dereq_('../internals/check-correctness-of-iteration'); + var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) { + Array.from(iterable); + }); + // `Array.from` method + // https://tc39.github.io/ecma262/#sec-array.from + $({ + target: 'Array', + stat: true, + forced: INCORRECT_ITERATION + }, { + from: from + }); + }, + { + '../internals/array-from': 35, + '../internals/check-correctness-of-iteration': 45, + '../internals/export': 68 + } + ], + 180: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var $includes = _dereq_('../internals/array-includes').includes; + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { + ACCESSORS: true, + 1: 0 + }); + // `Array.prototype.includes` method + // https://tc39.github.io/ecma262/#sec-array.prototype.includes + $({ + target: 'Array', + proto: true, + forced: !USES_TO_LENGTH + }, { + includes: function includes(el /* , fromIndex = 0 */ ) { + return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); + } + }); + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + addToUnscopables('includes'); + }, + { + '../internals/add-to-unscopables': 25, + '../internals/array-includes': 36, + '../internals/array-method-uses-to-length': 41, + '../internals/export': 68 + } + ], + 181: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var $indexOf = _dereq_('../internals/array-includes').indexOf; + var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var nativeIndexOf = [ + ].indexOf; + var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [ + 1 + ].indexOf(1, - 0) < 0; + var STRICT_METHOD = arrayMethodIsStrict('indexOf'); + var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { + ACCESSORS: true, + 1: 0 + }); + // `Array.prototype.indexOf` method + // https://tc39.github.io/ecma262/#sec-array.prototype.indexof + $({ + target: 'Array', + proto: true, + forced: NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH + }, { + indexOf: function indexOf(searchElement /* , fromIndex = 0 */ ) { + return NEGATIVE_ZERO // convert -0 to +0 + ? nativeIndexOf.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined); + } + }); + }, + { + '../internals/array-includes': 36, + '../internals/array-method-is-strict': 40, + '../internals/array-method-uses-to-length': 41, + '../internals/export': 68 + } + ], + 182: [ + function (_dereq_, module, exports) { + 'use strict'; + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + var Iterators = _dereq_('../internals/iterators'); + var InternalStateModule = _dereq_('../internals/internal-state'); + var defineIterator = _dereq_('../internals/define-iterator'); + var ARRAY_ITERATOR = 'Array Iterator'; + var setInternalState = InternalStateModule.set; + var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR); + // `Array.prototype.entries` method + // https://tc39.github.io/ecma262/#sec-array.prototype.entries + // `Array.prototype.keys` method + // https://tc39.github.io/ecma262/#sec-array.prototype.keys + // `Array.prototype.values` method + // https://tc39.github.io/ecma262/#sec-array.prototype.values + // `Array.prototype[@@iterator]` method + // https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator + // `CreateArrayIterator` internal method + // https://tc39.github.io/ecma262/#sec-createarrayiterator + module.exports = defineIterator(Array, 'Array', function (iterated, kind) { + setInternalState(this, { + type: ARRAY_ITERATOR, + target: toIndexedObject(iterated), + // target + index: 0, + // next index + kind: kind // kind + }); + // `%ArrayIteratorPrototype%.next` method + // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next + }, function () { + var state = getInternalState(this); + var target = state.target; + var kind = state.kind; + var index = state.index++; + if (!target || index >= target.length) { + state.target = undefined; + return { + value: undefined, + done: true + }; + } + if (kind == 'keys') return { + value: index, + done: false + }; + if (kind == 'values') return { + value: target[index], + done: false + }; + return { + value: [ + index, + target[index] + ], + done: false + }; + }, 'values'); + // argumentsList[@@iterator] is %ArrayProto_values% + // https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject + // https://tc39.github.io/ecma262/#sec-createmappedargumentsobject + Iterators.Arguments = Iterators.Array; + // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables + addToUnscopables('keys'); + addToUnscopables('values'); + addToUnscopables('entries'); + }, + { + '../internals/add-to-unscopables': 25, + '../internals/define-iterator': 59, + '../internals/internal-state': 89, + '../internals/iterators': 98, + '../internals/to-indexed-object': 153 + } + ], + 183: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var IndexedObject = _dereq_('../internals/indexed-object'); + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict'); + var nativeJoin = [ + ].join; + var ES3_STRINGS = IndexedObject != Object; + var STRICT_METHOD = arrayMethodIsStrict('join', ','); + // `Array.prototype.join` method + // https://tc39.github.io/ecma262/#sec-array.prototype.join + $({ + target: 'Array', + proto: true, + forced: ES3_STRINGS || !STRICT_METHOD + }, { + join: function join(separator) { + return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator); + } + }); + }, + { + '../internals/array-method-is-strict': 40, + '../internals/export': 68, + '../internals/indexed-object': 85, + '../internals/to-indexed-object': 153 + } + ], + 184: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var lastIndexOf = _dereq_('../internals/array-last-index-of'); + // `Array.prototype.lastIndexOf` method + // https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof + $({ + target: 'Array', + proto: true, + forced: lastIndexOf !== [].lastIndexOf + }, { + lastIndexOf: lastIndexOf + }); + }, + { + '../internals/array-last-index-of': 38, + '../internals/export': 68 + } + ], + 185: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var $map = _dereq_('../internals/array-iteration').map; + var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map'); + // FF49- issue + var USES_TO_LENGTH = arrayMethodUsesToLength('map'); + // `Array.prototype.map` method + // https://tc39.github.io/ecma262/#sec-array.prototype.map + // with adding support of @@species + $({ + target: 'Array', + proto: true, + forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH + }, { + map: function map(callbackfn /* , thisArg */ ) { + return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + }, + { + '../internals/array-iteration': 37, + '../internals/array-method-has-species-support': 39, + '../internals/array-method-uses-to-length': 41, + '../internals/export': 68 + } + ], + 186: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var isObject = _dereq_('../internals/is-object'); + var isArray = _dereq_('../internals/is-array'); + var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); + var toLength = _dereq_('../internals/to-length'); + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var createProperty = _dereq_('../internals/create-property'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice'); + var USES_TO_LENGTH = arrayMethodUsesToLength('slice', { + ACCESSORS: true, + 0: 0, + 1: 2 + }); + var SPECIES = wellKnownSymbol('species'); + var nativeSlice = [ + ].slice; + var max = Math.max; + // `Array.prototype.slice` method + // https://tc39.github.io/ecma262/#sec-array.prototype.slice + // fallback for not array-like ES3 strings and DOM objects + $({ + target: 'Array', + proto: true, + forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH + }, { + slice: function slice(start, end) { + var O = toIndexedObject(this); + var length = toLength(O.length); + var k = toAbsoluteIndex(start, length); + var fin = toAbsoluteIndex(end === undefined ? length : end, length); + // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible + var Constructor, + result, + n; + if (isArray(O)) { + Constructor = O.constructor; + // cross-realm fallback + if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) { + Constructor = undefined; + } else if (isObject(Constructor)) { + Constructor = Constructor[SPECIES]; + if (Constructor === null) Constructor = undefined; + } + if (Constructor === Array || Constructor === undefined) { + return nativeSlice.call(O, k, fin); + } + } + result = new (Constructor === undefined ? Array : Constructor) (max(fin - k, 0)); + for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]); + result.length = n; + return result; + } + }); + }, + { + '../internals/array-method-has-species-support': 39, + '../internals/array-method-uses-to-length': 41, + '../internals/create-property': 58, + '../internals/export': 68, + '../internals/is-array': 91, + '../internals/is-object': 93, + '../internals/to-absolute-index': 151, + '../internals/to-indexed-object': 153, + '../internals/to-length': 155, + '../internals/well-known-symbol': 167 + } + ], + 187: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var $some = _dereq_('../internals/array-iteration').some; + var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var STRICT_METHOD = arrayMethodIsStrict('some'); + var USES_TO_LENGTH = arrayMethodUsesToLength('some'); + // `Array.prototype.some` method + // https://tc39.github.io/ecma262/#sec-array.prototype.some + $({ + target: 'Array', + proto: true, + forced: !STRICT_METHOD || !USES_TO_LENGTH + }, { + some: function some(callbackfn /* , thisArg */ ) { + return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + }, + { + '../internals/array-iteration': 37, + '../internals/array-method-is-strict': 40, + '../internals/array-method-uses-to-length': 41, + '../internals/export': 68 + } + ], + 188: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); + var toInteger = _dereq_('../internals/to-integer'); + var toLength = _dereq_('../internals/to-length'); + var toObject = _dereq_('../internals/to-object'); + var arraySpeciesCreate = _dereq_('../internals/array-species-create'); + var createProperty = _dereq_('../internals/create-property'); + var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support'); + var arrayMethodUsesToLength = _dereq_('../internals/array-method-uses-to-length'); + var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('splice'); + var USES_TO_LENGTH = arrayMethodUsesToLength('splice', { + ACCESSORS: true, + 0: 0, + 1: 2 + }); + var max = Math.max; + var min = Math.min; + var MAX_SAFE_INTEGER = 9007199254740991; + var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; + // `Array.prototype.splice` method + // https://tc39.github.io/ecma262/#sec-array.prototype.splice + // with adding support of @@species + $({ + target: 'Array', + proto: true, + forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH + }, { + splice: function splice(start, deleteCount /* , ...items */ ) { + var O = toObject(this); + var len = toLength(O.length); + var actualStart = toAbsoluteIndex(start, len); + var argumentsLength = arguments.length; + var insertCount, + actualDeleteCount, + A, + k, + from, + to; + if (argumentsLength === 0) { + insertCount = actualDeleteCount = 0; + } else if (argumentsLength === 1) { + insertCount = 0; + actualDeleteCount = len - actualStart; + } else { + insertCount = argumentsLength - 2; + actualDeleteCount = min(max(toInteger(deleteCount), 0), len - actualStart); + } + if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER) { + throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED); + } + A = arraySpeciesCreate(O, actualDeleteCount); + for (k = 0; k < actualDeleteCount; k++) { + from = actualStart + k; + if (from in O) createProperty(A, k, O[from]); + } + A.length = actualDeleteCount; + if (insertCount < actualDeleteCount) { + for (k = actualStart; k < len - actualDeleteCount; k++) { + from = k + actualDeleteCount; + to = k + insertCount; + if (from in O) O[to] = O[from]; + else delete O[to]; + } + for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1]; + } else if (insertCount > actualDeleteCount) { + for (k = len - actualDeleteCount; k > actualStart; k--) { + from = k + actualDeleteCount - 1; + to = k + insertCount - 1; + if (from in O) O[to] = O[from]; + else delete O[to]; + } + } + for (k = 0; k < insertCount; k++) { + O[k + actualStart] = arguments[k + 2]; + } + O.length = len - actualDeleteCount + insertCount; + return A; + } + }); + }, + { + '../internals/array-method-has-species-support': 39, + '../internals/array-method-uses-to-length': 41, + '../internals/array-species-create': 43, + '../internals/create-property': 58, + '../internals/export': 68, + '../internals/to-absolute-index': 151, + '../internals/to-integer': 154, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 189: [ + function (_dereq_, module, exports) { + // this method was added to unscopables after implementation + // in popular engines, so it's moved to a separate module + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + addToUnscopables('flatMap'); + }, + { + '../internals/add-to-unscopables': 25 + } + ], + 190: [ + function (_dereq_, module, exports) { + // this method was added to unscopables after implementation + // in popular engines, so it's moved to a separate module + var addToUnscopables = _dereq_('../internals/add-to-unscopables'); + addToUnscopables('flat'); + }, + { + '../internals/add-to-unscopables': 25 + } + ], + 191: [ + function (_dereq_, module, exports) { + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var defineProperty = _dereq_('../internals/object-define-property').f; + var FunctionPrototype = Function.prototype; + var FunctionPrototypeToString = FunctionPrototype.toString; + var nameRE = /^\s*function ([^ (]*)/; + var NAME = 'name'; + // Function instances `.name` property + // https://tc39.github.io/ecma262/#sec-function-instances-name + if (DESCRIPTORS && !(NAME in FunctionPrototype)) { + defineProperty(FunctionPrototype, NAME, { + configurable: true, + get: function () { + try { + return FunctionPrototypeToString.call(this).match(nameRE) [1]; + } catch (error) { + return ''; + } + } + }); + } + }, + { + '../internals/descriptors': 61, + '../internals/object-define-property': 111 + } + ], + 192: [ + function (_dereq_, module, exports) { + 'use strict'; + var collection = _dereq_('../internals/collection'); + var collectionStrong = _dereq_('../internals/collection-strong'); + // `Map` constructor + // https://tc39.github.io/ecma262/#sec-map-objects + module.exports = collection('Map', function (init) { + return function Map() { + return init(this, arguments.length ? arguments[0] : undefined); + }; + }, collectionStrong); + }, + { + '../internals/collection': 50, + '../internals/collection-strong': 48 + } + ], + 193: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var $hypot = Math.hypot; + var abs = Math.abs; + var sqrt = Math.sqrt; + // Chrome 77 bug + // https://bugs.chromium.org/p/v8/issues/detail?id=9546 + var BUGGY = !!$hypot && $hypot(Infinity, NaN) !== Infinity; + // `Math.hypot` method + // https://tc39.github.io/ecma262/#sec-math.hypot + $({ + target: 'Math', + stat: true, + forced: BUGGY + }, { + hypot: function hypot(value1, value2) { + // eslint-disable-line no-unused-vars + var sum = 0; + var i = 0; + var aLen = arguments.length; + var larg = 0; + var arg, + div; + while (i < aLen) { + arg = abs(arguments[i++]); + if (larg < arg) { + div = larg / arg; + sum = sum * div * div + 1; + larg = arg; + } else if (arg > 0) { + div = arg / larg; + sum += div * div; + } else sum += arg; + } + return larg === Infinity ? Infinity : larg * sqrt(sum); + } + }); + }, + { + '../internals/export': 68 + } + ], + 194: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var log = Math.log; + var LN2 = Math.LN2; + // `Math.log2` method + // https://tc39.github.io/ecma262/#sec-math.log2 + $({ + target: 'Math', + stat: true + }, { + log2: function log2(x) { + return log(x) / LN2; + } + }); + }, + { + '../internals/export': 68 + } + ], + 195: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var sign = _dereq_('../internals/math-sign'); + // `Math.sign` method + // https://tc39.github.io/ecma262/#sec-math.sign + $({ + target: 'Math', + stat: true + }, { + sign: sign + }); + }, + { + '../internals/export': 68, + '../internals/math-sign': 99 + } + ], + 196: [ + function (_dereq_, module, exports) { + 'use strict'; + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var global = _dereq_('../internals/global'); + var isForced = _dereq_('../internals/is-forced'); + var redefine = _dereq_('../internals/redefine'); + var has = _dereq_('../internals/has'); + var classof = _dereq_('../internals/classof-raw'); + var inheritIfRequired = _dereq_('../internals/inherit-if-required'); + var toPrimitive = _dereq_('../internals/to-primitive'); + var fails = _dereq_('../internals/fails'); + var create = _dereq_('../internals/object-create'); + var getOwnPropertyNames = _dereq_('../internals/object-get-own-property-names').f; + var getOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f; + var defineProperty = _dereq_('../internals/object-define-property').f; + var trim = _dereq_('../internals/string-trim').trim; + var NUMBER = 'Number'; + var NativeNumber = global[NUMBER]; + var NumberPrototype = NativeNumber.prototype; + // Opera ~12 has broken Object#toString + var BROKEN_CLASSOF = classof(create(NumberPrototype)) == NUMBER; + // `ToNumber` abstract operation + // https://tc39.github.io/ecma262/#sec-tonumber + var toNumber = function (argument) { + var it = toPrimitive(argument, false); + var first, + third, + radix, + maxCode, + digits, + length, + index, + code; + if (typeof it == 'string' && it.length > 2) { + it = trim(it); + first = it.charCodeAt(0); + if (first === 43 || first === 45) { + third = it.charCodeAt(2); + if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix + } else if (first === 48) { + switch (it.charCodeAt(1)) { + case 66: + case 98: + radix = 2; + maxCode = 49; + break; + // fast equal of /^0b[01]+$/i + case 79: + case 111: + radix = 8; + maxCode = 55; + break; + // fast equal of /^0o[0-7]+$/i + default: + return + it; + } + digits = it.slice(2); + length = digits.length; + for (index = 0; index < length; index++) { + code = digits.charCodeAt(index); + // parseInt parses a string to a first unavailable symbol + // but ToNumber should return NaN if a string contains unavailable symbols + if (code < 48 || code > maxCode) return NaN; + } + return parseInt(digits, radix); + } + } + return + it; + }; + // `Number` constructor + // https://tc39.github.io/ecma262/#sec-number-constructor + if (isForced(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) { + var NumberWrapper = function Number(value) { + var it = arguments.length < 1 ? 0 : value; + var dummy = this; + return dummy instanceof NumberWrapper // check on 1..constructor(foo) case + && (BROKEN_CLASSOF ? fails(function () { + NumberPrototype.valueOf.call(dummy); + }) : classof(dummy) != NUMBER) ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it); + }; + for (var keys = DESCRIPTORS ? getOwnPropertyNames(NativeNumber) : ( // ES3: + 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES2015 (in case, if modules with ES2015 Number statics required before): + 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger').split(','), j = 0, key; keys.length > j; j++) { + if (has(NativeNumber, key = keys[j]) && !has(NumberWrapper, key)) { + defineProperty(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key)); + } + } + NumberWrapper.prototype = NumberPrototype; + NumberPrototype.constructor = NumberWrapper; + redefine(global, NUMBER, NumberWrapper); + } + }, + { + '../internals/classof-raw': 46, + '../internals/descriptors': 61, + '../internals/fails': 69, + '../internals/global': 78, + '../internals/has': 79, + '../internals/inherit-if-required': 86, + '../internals/is-forced': 92, + '../internals/object-create': 109, + '../internals/object-define-property': 111, + '../internals/object-get-own-property-descriptor': 112, + '../internals/object-get-own-property-names': 114, + '../internals/redefine': 127, + '../internals/string-trim': 148, + '../internals/to-primitive': 159 + } + ], + 197: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var numberIsFinite = _dereq_('../internals/number-is-finite'); + // `Number.isFinite` method + // https://tc39.github.io/ecma262/#sec-number.isfinite + $({ + target: 'Number', + stat: true + }, { + isFinite: numberIsFinite + }); + }, + { + '../internals/export': 68, + '../internals/number-is-finite': 107 + } + ], + 198: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var toInteger = _dereq_('../internals/to-integer'); + var thisNumberValue = _dereq_('../internals/this-number-value'); + var repeat = _dereq_('../internals/string-repeat'); + var fails = _dereq_('../internals/fails'); + var nativeToFixed = 1 .toFixed; + var floor = Math.floor; + var pow = function (x, n, acc) { + return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); + }; + var log = function (x) { + var n = 0; + var x2 = x; + while (x2 >= 4096) { + n += 12; + x2 /= 4096; + } + while (x2 >= 2) { + n += 1; + x2 /= 2; + } + return n; + }; + var FORCED = nativeToFixed && (0.00008 .toFixed(3) !== '0.000' || 0.9 .toFixed(0) !== '1' || 1.255 .toFixed(2) !== '1.25' || 1000000000000000100 .toFixed(0) !== '1000000000000000128') || !fails(function () { + // V8 ~ Android 4.3- + nativeToFixed.call({ + }); + }); + // `Number.prototype.toFixed` method + // https://tc39.github.io/ecma262/#sec-number.prototype.tofixed + $({ + target: 'Number', + proto: true, + forced: FORCED + }, { + // eslint-disable-next-line max-statements + toFixed: function toFixed(fractionDigits) { + var number = thisNumberValue(this); + var fractDigits = toInteger(fractionDigits); + var data = [ + 0, + 0, + 0, + 0, + 0, + 0 + ]; + var sign = ''; + var result = '0'; + var e, + z, + j, + k; + var multiply = function (n, c) { + var index = - 1; + var c2 = c; + while (++index < 6) { + c2 += n * data[index]; + data[index] = c2 % 10000000; + c2 = floor(c2 / 10000000); + } + }; + var divide = function (n) { + var index = 6; + var c = 0; + while (--index >= 0) { + c += data[index]; + data[index] = floor(c / n); + c = c % n * 10000000; + } + }; + var dataToString = function () { + var index = 6; + var s = ''; + while (--index >= 0) { + if (s !== '' || index === 0 || data[index] !== 0) { + var t = String(data[index]); + s = s === '' ? t : s + repeat.call('0', 7 - t.length) + t; + } + } + return s; + }; + if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits'); + // eslint-disable-next-line no-self-compare + if (number != number) return 'NaN'; + if (number <= - 1e+21 || number >= 1e+21) return String(number); + if (number < 0) { + sign = '-'; + number = - number; + } + if (number > 1e-21) { + e = log(number * pow(2, 69, 1)) - 69; + z = e < 0 ? number * pow(2, - e, 1) : number / pow(2, e, 1); + z *= 4503599627370496; + e = 52 - e; + if (e > 0) { + multiply(0, z); + j = fractDigits; + while (j >= 7) { + multiply(10000000, 0); + j -= 7; + } + multiply(pow(10, j, 1), 0); + j = e - 1; + while (j >= 23) { + divide(1 << 23); + j -= 23; + } + divide(1 << j); + multiply(1, 1); + divide(2); + result = dataToString(); + } else { + multiply(0, z); + multiply(1 << - e, 0); + result = dataToString() + repeat.call('0', fractDigits); + } + } + if (fractDigits > 0) { + k = result.length; + result = sign + (k <= fractDigits ? '0.' + repeat.call('0', fractDigits - k) + result : result.slice(0, k - fractDigits) + '.' + result.slice(k - fractDigits)); + } else { + result = sign + result; + } + return result; + } + }); + }, + { + '../internals/export': 68, + '../internals/fails': 69, + '../internals/string-repeat': 146, + '../internals/this-number-value': 150, + '../internals/to-integer': 154 + } + ], + 199: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var assign = _dereq_('../internals/object-assign'); + // `Object.assign` method + // https://tc39.github.io/ecma262/#sec-object.assign + $({ + target: 'Object', + stat: true, + forced: Object.assign !== assign + }, { + assign: assign + }); + }, + { + '../internals/export': 68, + '../internals/object-assign': 108 + } + ], + 200: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var iterate = _dereq_('../internals/iterate'); + var createProperty = _dereq_('../internals/create-property'); + // `Object.fromEntries` method + // https://github.com/tc39/proposal-object-from-entries + $({ + target: 'Object', + stat: true + }, { + fromEntries: function fromEntries(iterable) { + var obj = { + }; + iterate(iterable, function (k, v) { + createProperty(obj, k, v); + }, undefined, true); + return obj; + } + }); + }, + { + '../internals/create-property': 58, + '../internals/export': 68, + '../internals/iterate': 96 + } + ], + 201: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var fails = _dereq_('../internals/fails'); + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var nativeGetOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f; + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var FAILS_ON_PRIMITIVES = fails(function () { + nativeGetOwnPropertyDescriptor(1); + }); + var FORCED = !DESCRIPTORS || FAILS_ON_PRIMITIVES; + // `Object.getOwnPropertyDescriptor` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor + $({ + target: 'Object', + stat: true, + forced: FORCED, + sham: !DESCRIPTORS + }, { + getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) { + return nativeGetOwnPropertyDescriptor(toIndexedObject(it), key); + } + }); + }, + { + '../internals/descriptors': 61, + '../internals/export': 68, + '../internals/fails': 69, + '../internals/object-get-own-property-descriptor': 112, + '../internals/to-indexed-object': 153 + } + ], + 202: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var fails = _dereq_('../internals/fails'); + var nativeGetOwnPropertyNames = _dereq_('../internals/object-get-own-property-names-external').f; + var FAILS_ON_PRIMITIVES = fails(function () { + return !Object.getOwnPropertyNames(1); + }); + // `Object.getOwnPropertyNames` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertynames + $({ + target: 'Object', + stat: true, + forced: FAILS_ON_PRIMITIVES + }, { + getOwnPropertyNames: nativeGetOwnPropertyNames + }); + }, + { + '../internals/export': 68, + '../internals/fails': 69, + '../internals/object-get-own-property-names-external': 113 + } + ], + 203: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var fails = _dereq_('../internals/fails'); + var toObject = _dereq_('../internals/to-object'); + var nativeGetPrototypeOf = _dereq_('../internals/object-get-prototype-of'); + var CORRECT_PROTOTYPE_GETTER = _dereq_('../internals/correct-prototype-getter'); + var FAILS_ON_PRIMITIVES = fails(function () { + nativeGetPrototypeOf(1); + }); + // `Object.getPrototypeOf` method + // https://tc39.github.io/ecma262/#sec-object.getprototypeof + $({ + target: 'Object', + stat: true, + forced: FAILS_ON_PRIMITIVES, + sham: !CORRECT_PROTOTYPE_GETTER + }, { + getPrototypeOf: function getPrototypeOf(it) { + return nativeGetPrototypeOf(toObject(it)); + } + }); + }, + { + '../internals/correct-prototype-getter': 53, + '../internals/export': 68, + '../internals/fails': 69, + '../internals/object-get-prototype-of': 116, + '../internals/to-object': 156 + } + ], + 204: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var toObject = _dereq_('../internals/to-object'); + var nativeKeys = _dereq_('../internals/object-keys'); + var fails = _dereq_('../internals/fails'); + var FAILS_ON_PRIMITIVES = fails(function () { + nativeKeys(1); + }); + // `Object.keys` method + // https://tc39.github.io/ecma262/#sec-object.keys + $({ + target: 'Object', + stat: true, + forced: FAILS_ON_PRIMITIVES + }, { + keys: function keys(it) { + return nativeKeys(toObject(it)); + } + }); + }, + { + '../internals/export': 68, + '../internals/fails': 69, + '../internals/object-keys': 118, + '../internals/to-object': 156 + } + ], + 205: [ + function (_dereq_, module, exports) { + var TO_STRING_TAG_SUPPORT = _dereq_('../internals/to-string-tag-support'); + var redefine = _dereq_('../internals/redefine'); + var toString = _dereq_('../internals/object-to-string'); + // `Object.prototype.toString` method + // https://tc39.github.io/ecma262/#sec-object.prototype.tostring + if (!TO_STRING_TAG_SUPPORT) { + redefine(Object.prototype, 'toString', toString, { + unsafe: true + }); + } + }, + { + '../internals/object-to-string': 121, + '../internals/redefine': 127, + '../internals/to-string-tag-support': 160 + } + ], + 206: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var IS_PURE = _dereq_('../internals/is-pure'); + var global = _dereq_('../internals/global'); + var getBuiltIn = _dereq_('../internals/get-built-in'); + var NativePromise = _dereq_('../internals/native-promise-constructor'); + var redefine = _dereq_('../internals/redefine'); + var redefineAll = _dereq_('../internals/redefine-all'); + var setToStringTag = _dereq_('../internals/set-to-string-tag'); + var setSpecies = _dereq_('../internals/set-species'); + var isObject = _dereq_('../internals/is-object'); + var aFunction = _dereq_('../internals/a-function'); + var anInstance = _dereq_('../internals/an-instance'); + var classof = _dereq_('../internals/classof-raw'); + var inspectSource = _dereq_('../internals/inspect-source'); + var iterate = _dereq_('../internals/iterate'); + var checkCorrectnessOfIteration = _dereq_('../internals/check-correctness-of-iteration'); + var speciesConstructor = _dereq_('../internals/species-constructor'); + var task = _dereq_('../internals/task').set; + var microtask = _dereq_('../internals/microtask'); + var promiseResolve = _dereq_('../internals/promise-resolve'); + var hostReportErrors = _dereq_('../internals/host-report-errors'); + var newPromiseCapabilityModule = _dereq_('../internals/new-promise-capability'); + var perform = _dereq_('../internals/perform'); + var InternalStateModule = _dereq_('../internals/internal-state'); + var isForced = _dereq_('../internals/is-forced'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var V8_VERSION = _dereq_('../internals/engine-v8-version'); + var SPECIES = wellKnownSymbol('species'); + var PROMISE = 'Promise'; + var getInternalState = InternalStateModule.get; + var setInternalState = InternalStateModule.set; + var getInternalPromiseState = InternalStateModule.getterFor(PROMISE); + var PromiseConstructor = NativePromise; + var TypeError = global.TypeError; + var document = global.document; + var process = global.process; + var $fetch = getBuiltIn('fetch'); + var newPromiseCapability = newPromiseCapabilityModule.f; + var newGenericPromiseCapability = newPromiseCapability; + var IS_NODE = classof(process) == 'process'; + var DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent); + var UNHANDLED_REJECTION = 'unhandledrejection'; + var REJECTION_HANDLED = 'rejectionhandled'; + var PENDING = 0; + var FULFILLED = 1; + var REJECTED = 2; + var HANDLED = 1; + var UNHANDLED = 2; + var Internal, + OwnPromiseCapability, + PromiseWrapper, + nativeThen; + var FORCED = isForced(PROMISE, function () { + var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor); + if (!GLOBAL_CORE_JS_PROMISE) { + // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables + // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 + // We can't detect it synchronously, so just check versions + if (V8_VERSION === 66) return true; + // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test + if (!IS_NODE && typeof PromiseRejectionEvent != 'function') return true; + } // We need Promise#finally in the pure version for preventing prototype pollution + + if (IS_PURE && !PromiseConstructor.prototype['finally']) return true; + // We can't use @@species feature detection in V8 since it causes + // deoptimization and performance degradation + // https://github.com/zloirock/core-js/issues/679 + if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false; + // Detect correctness of subclassing with @@species support + var promise = PromiseConstructor.resolve(1); + var FakePromise = function (exec) { + exec(function () { /* empty */ + }, function () { /* empty */ + }); + }; + var constructor = promise.constructor = { + }; + constructor[SPECIES] = FakePromise; + return !(promise.then(function () { /* empty */ + }) instanceof FakePromise); + }); + var INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) { + PromiseConstructor.all(iterable) ['catch'](function () { /* empty */ + }); + }); + // helpers + var isThenable = function (it) { + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; + }; + var notify = function (promise, state, isReject) { + if (state.notified) return; + state.notified = true; + var chain = state.reactions; + microtask(function () { + var value = state.value; + var ok = state.state == FULFILLED; + var index = 0; + // variable length - can't use forEach + while (chain.length > index) { + var reaction = chain[index++]; + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, + then, + exited; + try { + if (handler) { + if (!ok) { + if (state.rejection === UNHANDLED) onHandleUnhandled(promise, state); + state.rejection = HANDLED; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); // can throw + if (domain) { + domain.exit(); + exited = true; + } + } + if (result === reaction.promise) { + reject(TypeError('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (error) { + if (domain && !exited) domain.exit(); + reject(error); + } + } + state.reactions = [ + ]; + state.notified = false; + if (isReject && !state.rejection) onUnhandled(promise, state); + }); + }; + var dispatchEvent = function (name, promise, reason) { + var event, + handler; + if (DISPATCH_EVENT) { + event = document.createEvent('Event'); + event.promise = promise; + event.reason = reason; + event.initEvent(name, false, true); + global.dispatchEvent(event); + } else event = { + promise: promise, + reason: reason + }; + if (handler = global['on' + name]) handler(event); + else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason); + }; + var onUnhandled = function (promise, state) { + task.call(global, function () { + var value = state.value; + var IS_UNHANDLED = isUnhandled(state); + var result; + if (IS_UNHANDLED) { + result = perform(function () { + if (IS_NODE) { + process.emit('unhandledRejection', value, promise); + } else dispatchEvent(UNHANDLED_REJECTION, promise, value); + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED; + if (result.error) throw result.value; + } + }); + }; + var isUnhandled = function (state) { + return state.rejection !== HANDLED && !state.parent; + }; + var onHandleUnhandled = function (promise, state) { + task.call(global, function () { + if (IS_NODE) { + process.emit('rejectionHandled', promise); + } else dispatchEvent(REJECTION_HANDLED, promise, state.value); + }); + }; + var bind = function (fn, promise, state, unwrap) { + return function (value) { + fn(promise, state, value, unwrap); + }; + }; + var internalReject = function (promise, state, value, unwrap) { + if (state.done) return; + state.done = true; + if (unwrap) state = unwrap; + state.value = value; + state.state = REJECTED; + notify(promise, state, true); + }; + var internalResolve = function (promise, state, value, unwrap) { + if (state.done) return; + state.done = true; + if (unwrap) state = unwrap; + try { + if (promise === value) throw TypeError('Promise can\'t be resolved itself'); + var then = isThenable(value); + if (then) { + microtask(function () { + var wrapper = { + done: false + }; + try { + then.call(value, bind(internalResolve, promise, wrapper, state), bind(internalReject, promise, wrapper, state)); + } catch (error) { + internalReject(promise, wrapper, error, state); + } + }); + } else { + state.value = value; + state.state = FULFILLED; + notify(promise, state, false); + } + } catch (error) { + internalReject(promise, { + done: false + }, error, state); + } + }; + // constructor polyfill + if (FORCED) { + // 25.4.3.1 Promise(executor) + PromiseConstructor = function Promise(executor) { + anInstance(this, PromiseConstructor, PROMISE); + aFunction(executor); + Internal.call(this); + var state = getInternalState(this); + try { + executor(bind(internalResolve, this, state), bind(internalReject, this, state)); + } catch (error) { + internalReject(this, state, error); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + setInternalState(this, { + type: PROMISE, + done: false, + notified: false, + parent: false, + reactions: [ + ], + rejection: false, + state: PENDING, + value: undefined + }); + }; + Internal.prototype = redefineAll(PromiseConstructor.prototype, { + // `Promise.prototype.then` method + // https://tc39.github.io/ecma262/#sec-promise.prototype.then + then: function then(onFulfilled, onRejected) { + var state = getInternalPromiseState(this); + var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = IS_NODE ? process.domain : undefined; + state.parent = true; + state.reactions.push(reaction); + if (state.state != PENDING) notify(this, state, false); + return reaction.promise; + }, + // `Promise.prototype.catch` method + // https://tc39.github.io/ecma262/#sec-promise.prototype.catch + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + var state = getInternalState(promise); + this.promise = promise; + this.resolve = bind(internalResolve, promise, state); + this.reject = bind(internalReject, promise, state); + }; + newPromiseCapabilityModule.f = newPromiseCapability = function (C) { + return C === PromiseConstructor || C === PromiseWrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); + }; + if (!IS_PURE && typeof NativePromise == 'function') { + nativeThen = NativePromise.prototype.then; + // wrap native Promise#then for native async functions + redefine(NativePromise.prototype, 'then', function then(onFulfilled, onRejected) { + var that = this; + return new PromiseConstructor(function (resolve, reject) { + nativeThen.call(that, resolve, reject); + }).then(onFulfilled, onRejected); + // https://github.com/zloirock/core-js/issues/640 + }, { + unsafe: true + }); + // wrap fetch result + if (typeof $fetch == 'function') $({ + global: true, + enumerable: true, + forced: true + }, { + // eslint-disable-next-line no-unused-vars + fetch: function fetch(input /* , init */ ) { + return promiseResolve(PromiseConstructor, $fetch.apply(global, arguments)); + } + }); + } + } + $({ + global: true, + wrap: true, + forced: FORCED + }, { + Promise: PromiseConstructor + }); + setToStringTag(PromiseConstructor, PROMISE, false, true); + setSpecies(PROMISE); + PromiseWrapper = getBuiltIn(PROMISE); + // statics + $({ + target: PROMISE, + stat: true, + forced: FORCED + }, { + // `Promise.reject` method + // https://tc39.github.io/ecma262/#sec-promise.reject + reject: function reject(r) { + var capability = newPromiseCapability(this); + capability.reject.call(undefined, r); + return capability.promise; + } + }); + $({ + target: PROMISE, + stat: true, + forced: IS_PURE || FORCED + }, { + // `Promise.resolve` method + // https://tc39.github.io/ecma262/#sec-promise.resolve + resolve: function resolve(x) { + return promiseResolve(IS_PURE && this === PromiseWrapper ? PromiseConstructor : this, x); + } + }); + $({ + target: PROMISE, + stat: true, + forced: INCORRECT_ITERATION + }, { + // `Promise.all` method + // https://tc39.github.io/ecma262/#sec-promise.all + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var $promiseResolve = aFunction(C.resolve); + var values = [ + ]; + var counter = 0; + var remaining = 1; + iterate(iterable, function (promise) { + var index = counter++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + $promiseResolve.call(C, promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.error) reject(result.value); + return capability.promise; + }, + // `Promise.race` method + // https://tc39.github.io/ecma262/#sec-promise.race + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = perform(function () { + var $promiseResolve = aFunction(C.resolve); + iterate(iterable, function (promise) { + $promiseResolve.call(C, promise).then(capability.resolve, reject); + }); + }); + if (result.error) reject(result.value); + return capability.promise; + } + }); + }, + { + '../internals/a-function': 23, + '../internals/an-instance': 27, + '../internals/check-correctness-of-iteration': 45, + '../internals/classof-raw': 46, + '../internals/engine-v8-version': 66, + '../internals/export': 68, + '../internals/get-built-in': 75, + '../internals/global': 78, + '../internals/host-report-errors': 81, + '../internals/inspect-source': 87, + '../internals/internal-state': 89, + '../internals/is-forced': 92, + '../internals/is-object': 93, + '../internals/is-pure': 94, + '../internals/iterate': 96, + '../internals/microtask': 100, + '../internals/native-promise-constructor': 101, + '../internals/new-promise-capability': 105, + '../internals/perform': 124, + '../internals/promise-resolve': 125, + '../internals/redefine': 127, + '../internals/redefine-all': 126, + '../internals/set-species': 135, + '../internals/set-to-string-tag': 136, + '../internals/species-constructor': 140, + '../internals/task': 149, + '../internals/well-known-symbol': 167 + } + ], + 207: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var getBuiltIn = _dereq_('../internals/get-built-in'); + var aFunction = _dereq_('../internals/a-function'); + var anObject = _dereq_('../internals/an-object'); + var isObject = _dereq_('../internals/is-object'); + var create = _dereq_('../internals/object-create'); + var bind = _dereq_('../internals/function-bind'); + var fails = _dereq_('../internals/fails'); + var nativeConstruct = getBuiltIn('Reflect', 'construct'); + // `Reflect.construct` method + // https://tc39.github.io/ecma262/#sec-reflect.construct + // MS Edge supports only 2 arguments and argumentsList argument is optional + // FF Nightly sets third argument as `new.target`, but does not create `this` from it + var NEW_TARGET_BUG = fails(function () { + function F() { /* empty */ + } + return !(nativeConstruct(function () { /* empty */ + }, [ + ], F) instanceof F); + }); + var ARGS_BUG = !fails(function () { + nativeConstruct(function () { /* empty */ + }); + }); + var FORCED = NEW_TARGET_BUG || ARGS_BUG; + $({ + target: 'Reflect', + stat: true, + forced: FORCED, + sham: FORCED + }, { + construct: function construct(Target, args /* , newTarget */ ) { + aFunction(Target); + anObject(args); + var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); + if (ARGS_BUG && !NEW_TARGET_BUG) return nativeConstruct(Target, args, newTarget); + if (Target == newTarget) { + // w/o altered newTarget, optimization for 0-4 arguments + switch (args.length) { + case 0: + return new Target(); + case 1: + return new Target(args[0]); + case 2: + return new Target(args[0], args[1]); + case 3: + return new Target(args[0], args[1], args[2]); + case 4: + return new Target(args[0], args[1], args[2], args[3]); + } // w/o altered newTarget, lot of arguments case + + var $args = [ + null + ]; + $args.push.apply($args, args); + return new (bind.apply(Target, $args)) (); + } // with altered newTarget, not support built-in constructors + + var proto = newTarget.prototype; + var instance = create(isObject(proto) ? proto : Object.prototype); + var result = Function.apply.call(Target, instance, args); + return isObject(result) ? result : instance; + } + }); + }, + { + '../internals/a-function': 23, + '../internals/an-object': 28, + '../internals/export': 68, + '../internals/fails': 69, + '../internals/function-bind': 74, + '../internals/get-built-in': 75, + '../internals/is-object': 93, + '../internals/object-create': 109 + } + ], + 208: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var isObject = _dereq_('../internals/is-object'); + var anObject = _dereq_('../internals/an-object'); + var has = _dereq_('../internals/has'); + var getOwnPropertyDescriptorModule = _dereq_('../internals/object-get-own-property-descriptor'); + var getPrototypeOf = _dereq_('../internals/object-get-prototype-of'); + // `Reflect.get` method + // https://tc39.github.io/ecma262/#sec-reflect.get + function get(target, propertyKey /* , receiver */ ) { + var receiver = arguments.length < 3 ? target : arguments[2]; + var descriptor, + prototype; + if (anObject(target) === receiver) return target[propertyKey]; + if (descriptor = getOwnPropertyDescriptorModule.f(target, propertyKey)) return has(descriptor, 'value') ? descriptor.value : descriptor.get === undefined ? undefined : descriptor.get.call(receiver); + if (isObject(prototype = getPrototypeOf(target))) return get(prototype, propertyKey, receiver); + } + $({ + target: 'Reflect', + stat: true + }, { + get: get + }); + }, + { + '../internals/an-object': 28, + '../internals/export': 68, + '../internals/has': 79, + '../internals/is-object': 93, + '../internals/object-get-own-property-descriptor': 112, + '../internals/object-get-prototype-of': 116 + } + ], + 209: [ + function (_dereq_, module, exports) { + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var global = _dereq_('../internals/global'); + var isForced = _dereq_('../internals/is-forced'); + var inheritIfRequired = _dereq_('../internals/inherit-if-required'); + var defineProperty = _dereq_('../internals/object-define-property').f; + var getOwnPropertyNames = _dereq_('../internals/object-get-own-property-names').f; + var isRegExp = _dereq_('../internals/is-regexp'); + var getFlags = _dereq_('../internals/regexp-flags'); + var stickyHelpers = _dereq_('../internals/regexp-sticky-helpers'); + var redefine = _dereq_('../internals/redefine'); + var fails = _dereq_('../internals/fails'); + var setInternalState = _dereq_('../internals/internal-state').set; + var setSpecies = _dereq_('../internals/set-species'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var MATCH = wellKnownSymbol('match'); + var NativeRegExp = global.RegExp; + var RegExpPrototype = NativeRegExp.prototype; + var re1 = /a/g; + var re2 = /a/g; + // "new" should create a new object, old webkit bug + var CORRECT_NEW = new NativeRegExp(re1) !== re1; + var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y; + var FORCED = DESCRIPTORS && isForced('RegExp', !CORRECT_NEW || UNSUPPORTED_Y || fails(function () { + re2[MATCH] = false; + // RegExp constructor can alter flags and IsRegExp works correct with @@match + return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i'; + })); + // `RegExp` constructor + // https://tc39.github.io/ecma262/#sec-regexp-constructor + if (FORCED) { + var RegExpWrapper = function RegExp(pattern, flags) { + var thisIsRegExp = this instanceof RegExpWrapper; + var patternIsRegExp = isRegExp(pattern); + var flagsAreUndefined = flags === undefined; + var sticky; + if (!thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined) { + return pattern; + } + if (CORRECT_NEW) { + if (patternIsRegExp && !flagsAreUndefined) pattern = pattern.source; + } else if (pattern instanceof RegExpWrapper) { + if (flagsAreUndefined) flags = getFlags.call(pattern); + pattern = pattern.source; + } + if (UNSUPPORTED_Y) { + sticky = !!flags && flags.indexOf('y') > - 1; + if (sticky) flags = flags.replace(/y/g, ''); + } + var result = inheritIfRequired(CORRECT_NEW ? new NativeRegExp(pattern, flags) : NativeRegExp(pattern, flags), thisIsRegExp ? this : RegExpPrototype, RegExpWrapper); + if (UNSUPPORTED_Y && sticky) setInternalState(result, { + sticky: sticky + }); + return result; + }; + var proxy = function (key) { + key in RegExpWrapper || defineProperty(RegExpWrapper, key, { + configurable: true, + get: function () { + return NativeRegExp[key]; + }, + set: function (it) { + NativeRegExp[key] = it; + } + }); + }; + var keys = getOwnPropertyNames(NativeRegExp); + var index = 0; + while (keys.length > index) proxy(keys[index++]); + RegExpPrototype.constructor = RegExpWrapper; + RegExpWrapper.prototype = RegExpPrototype; + redefine(global, 'RegExp', RegExpWrapper); + } // https://tc39.github.io/ecma262/#sec-get-regexp-@@species + + setSpecies('RegExp'); + }, + { + '../internals/descriptors': 61, + '../internals/fails': 69, + '../internals/global': 78, + '../internals/inherit-if-required': 86, + '../internals/internal-state': 89, + '../internals/is-forced': 92, + '../internals/is-regexp': 95, + '../internals/object-define-property': 111, + '../internals/object-get-own-property-names': 114, + '../internals/redefine': 127, + '../internals/regexp-flags': 130, + '../internals/regexp-sticky-helpers': 131, + '../internals/set-species': 135, + '../internals/well-known-symbol': 167 + } + ], + 210: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var exec = _dereq_('../internals/regexp-exec'); + $({ + target: 'RegExp', + proto: true, + forced: /./.exec !== exec + }, { + exec: exec + }); + }, + { + '../internals/export': 68, + '../internals/regexp-exec': 129 + } + ], + 211: [ + function (_dereq_, module, exports) { + 'use strict'; + var redefine = _dereq_('../internals/redefine'); + var anObject = _dereq_('../internals/an-object'); + var fails = _dereq_('../internals/fails'); + var flags = _dereq_('../internals/regexp-flags'); + var TO_STRING = 'toString'; + var RegExpPrototype = RegExp.prototype; + var nativeToString = RegExpPrototype[TO_STRING]; + var NOT_GENERIC = fails(function () { + return nativeToString.call({ + source: 'a', + flags: 'b' + }) != '/a/b'; + }); + // FF44- RegExp#toString has a wrong name + var INCORRECT_NAME = nativeToString.name != TO_STRING; + // `RegExp.prototype.toString` method + // https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring + if (NOT_GENERIC || INCORRECT_NAME) { + redefine(RegExp.prototype, TO_STRING, function toString() { + var R = anObject(this); + var p = String(R.source); + var rf = R.flags; + var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? flags.call(R) : rf); + return '/' + p + '/' + f; + }, { + unsafe: true + }); + } + }, + { + '../internals/an-object': 28, + '../internals/fails': 69, + '../internals/redefine': 127, + '../internals/regexp-flags': 130 + } + ], + 212: [ + function (_dereq_, module, exports) { + 'use strict'; + var collection = _dereq_('../internals/collection'); + var collectionStrong = _dereq_('../internals/collection-strong'); + // `Set` constructor + // https://tc39.github.io/ecma262/#sec-set-objects + module.exports = collection('Set', function (init) { + return function Set() { + return init(this, arguments.length ? arguments[0] : undefined); + }; + }, collectionStrong); + }, + { + '../internals/collection': 50, + '../internals/collection-strong': 48 + } + ], + 213: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var getOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f; + var toLength = _dereq_('../internals/to-length'); + var notARegExp = _dereq_('../internals/not-a-regexp'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var correctIsRegExpLogic = _dereq_('../internals/correct-is-regexp-logic'); + var IS_PURE = _dereq_('../internals/is-pure'); + var nativeEndsWith = ''.endsWith; + var min = Math.min; + var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('endsWith'); + // https://github.com/zloirock/core-js/pull/702 + var MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () { + var descriptor = getOwnPropertyDescriptor(String.prototype, 'endsWith'); + return descriptor && !descriptor.writable; + }(); + // `String.prototype.endsWith` method + // https://tc39.github.io/ecma262/#sec-string.prototype.endswith + $({ + target: 'String', + proto: true, + forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC + }, { + endsWith: function endsWith(searchString /* , endPosition = @length */ ) { + var that = String(requireObjectCoercible(this)); + notARegExp(searchString); + var endPosition = arguments.length > 1 ? arguments[1] : undefined; + var len = toLength(that.length); + var end = endPosition === undefined ? len : min(toLength(endPosition), len); + var search = String(searchString); + return nativeEndsWith ? nativeEndsWith.call(that, search, end) : that.slice(end - search.length, end) === search; + } + }); + }, + { + '../internals/correct-is-regexp-logic': 52, + '../internals/export': 68, + '../internals/is-pure': 94, + '../internals/not-a-regexp': 106, + '../internals/object-get-own-property-descriptor': 112, + '../internals/require-object-coercible': 132, + '../internals/to-length': 155 + } + ], + 214: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var notARegExp = _dereq_('../internals/not-a-regexp'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var correctIsRegExpLogic = _dereq_('../internals/correct-is-regexp-logic'); + // `String.prototype.includes` method + // https://tc39.github.io/ecma262/#sec-string.prototype.includes + $({ + target: 'String', + proto: true, + forced: !correctIsRegExpLogic('includes') + }, { + includes: function includes(searchString /* , position = 0 */ ) { + return !!~String(requireObjectCoercible(this)).indexOf(notARegExp(searchString), arguments.length > 1 ? arguments[1] : undefined); + } + }); + }, + { + '../internals/correct-is-regexp-logic': 52, + '../internals/export': 68, + '../internals/not-a-regexp': 106, + '../internals/require-object-coercible': 132 + } + ], + 215: [ + function (_dereq_, module, exports) { + 'use strict'; + var charAt = _dereq_('../internals/string-multibyte').charAt; + var InternalStateModule = _dereq_('../internals/internal-state'); + var defineIterator = _dereq_('../internals/define-iterator'); + var STRING_ITERATOR = 'String Iterator'; + var setInternalState = InternalStateModule.set; + var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); + // `String.prototype[@@iterator]` method + // https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator + defineIterator(String, 'String', function (iterated) { + setInternalState(this, { + type: STRING_ITERATOR, + string: String(iterated), + index: 0 + }); + // `%StringIteratorPrototype%.next` method + // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next + }, function next() { + var state = getInternalState(this); + var string = state.string; + var index = state.index; + var point; + if (index >= string.length) return { + value: undefined, + done: true + }; + point = charAt(string, index); + state.index += point.length; + return { + value: point, + done: false + }; + }); + }, + { + '../internals/define-iterator': 59, + '../internals/internal-state': 89, + '../internals/string-multibyte': 142 + } + ], + 216: [ + function (_dereq_, module, exports) { + 'use strict'; + var fixRegExpWellKnownSymbolLogic = _dereq_('../internals/fix-regexp-well-known-symbol-logic'); + var anObject = _dereq_('../internals/an-object'); + var toLength = _dereq_('../internals/to-length'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var advanceStringIndex = _dereq_('../internals/advance-string-index'); + var regExpExec = _dereq_('../internals/regexp-exec-abstract'); + // @@match logic + fixRegExpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) { + return [ // `String.prototype.match` method + // https://tc39.github.io/ecma262/#sec-string.prototype.match + function match(regexp) { + var O = requireObjectCoercible(this); + var matcher = regexp == undefined ? undefined : regexp[MATCH]; + return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp) [MATCH](String(O)); + }, + // `RegExp.prototype[@@match]` method + // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match + function (regexp) { + var res = maybeCallNative(nativeMatch, regexp, this); + if (res.done) return res.value; + var rx = anObject(regexp); + var S = String(this); + if (!rx.global) return regExpExec(rx, S); + var fullUnicode = rx.unicode; + rx.lastIndex = 0; + var A = [ + ]; + var n = 0; + var result; + while ((result = regExpExec(rx, S)) !== null) { + var matchStr = String(result[0]); + A[n] = matchStr; + if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); + n++; + } + return n === 0 ? null : A; + } + ]; + }); + }, + { + '../internals/advance-string-index': 26, + '../internals/an-object': 28, + '../internals/fix-regexp-well-known-symbol-logic': 70, + '../internals/regexp-exec-abstract': 128, + '../internals/require-object-coercible': 132, + '../internals/to-length': 155 + } + ], + 217: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var $padStart = _dereq_('../internals/string-pad').start; + var WEBKIT_BUG = _dereq_('../internals/string-pad-webkit-bug'); + // `String.prototype.padStart` method + // https://tc39.github.io/ecma262/#sec-string.prototype.padstart + $({ + target: 'String', + proto: true, + forced: WEBKIT_BUG + }, { + padStart: function padStart(maxLength /* , fillString = ' ' */ ) { + return $padStart(this, maxLength, arguments.length > 1 ? arguments[1] : undefined); + } + }); + }, + { + '../internals/export': 68, + '../internals/string-pad': 144, + '../internals/string-pad-webkit-bug': 143 + } + ], + 218: [ + function (_dereq_, module, exports) { + var $ = _dereq_('../internals/export'); + var repeat = _dereq_('../internals/string-repeat'); + // `String.prototype.repeat` method + // https://tc39.github.io/ecma262/#sec-string.prototype.repeat + $({ + target: 'String', + proto: true + }, { + repeat: repeat + }); + }, + { + '../internals/export': 68, + '../internals/string-repeat': 146 + } + ], + 219: [ + function (_dereq_, module, exports) { + 'use strict'; + var fixRegExpWellKnownSymbolLogic = _dereq_('../internals/fix-regexp-well-known-symbol-logic'); + var anObject = _dereq_('../internals/an-object'); + var toObject = _dereq_('../internals/to-object'); + var toLength = _dereq_('../internals/to-length'); + var toInteger = _dereq_('../internals/to-integer'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var advanceStringIndex = _dereq_('../internals/advance-string-index'); + var regExpExec = _dereq_('../internals/regexp-exec-abstract'); + var max = Math.max; + var min = Math.min; + var floor = Math.floor; + var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g; + var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g; + var maybeToString = function (it) { + return it === undefined ? it : String(it); + }; + // @@replace logic + fixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) { + var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE; + var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0; + var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0'; + return [ // `String.prototype.replace` method + // https://tc39.github.io/ecma262/#sec-string.prototype.replace + function replace(searchValue, replaceValue) { + var O = requireObjectCoercible(this); + var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; + return replacer !== undefined ? replacer.call(searchValue, O, replaceValue) : nativeReplace.call(String(O), searchValue, replaceValue); + }, + // `RegExp.prototype[@@replace]` method + // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace + function (regexp, replaceValue) { + if (!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0 || typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === - 1) { + var res = maybeCallNative(nativeReplace, regexp, this, replaceValue); + if (res.done) return res.value; + } + var rx = anObject(regexp); + var S = String(this); + var functionalReplace = typeof replaceValue === 'function'; + if (!functionalReplace) replaceValue = String(replaceValue); + var global = rx.global; + if (global) { + var fullUnicode = rx.unicode; + rx.lastIndex = 0; + } + var results = [ + ]; + while (true) { + var result = regExpExec(rx, S); + if (result === null) break; + results.push(result); + if (!global) break; + var matchStr = String(result[0]); + if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); + } + var accumulatedResult = ''; + var nextSourcePosition = 0; + for (var i = 0; i < results.length; i++) { + result = results[i]; + var matched = String(result[0]); + var position = max(min(toInteger(result.index), S.length), 0); + var captures = [ + ]; + // NOTE: This is equivalent to + // captures = result.slice(1).map(maybeToString) + // but for some reason `nativeSlice.call(result, 1, result.length)` (called in + // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and + // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. + for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); + var namedCaptures = result.groups; + if (functionalReplace) { + var replacerArgs = [ + matched + ].concat(captures, position, S); + if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); + var replacement = String(replaceValue.apply(undefined, replacerArgs)); + } else { + replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); + } + if (position >= nextSourcePosition) { + accumulatedResult += S.slice(nextSourcePosition, position) + replacement; + nextSourcePosition = position + matched.length; + } + } + return accumulatedResult + S.slice(nextSourcePosition); + } + ]; + // https://tc39.github.io/ecma262/#sec-getsubstitution + function getSubstitution(matched, str, position, captures, namedCaptures, replacement) { + var tailPos = position + matched.length; + var m = captures.length; + var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; + if (namedCaptures !== undefined) { + namedCaptures = toObject(namedCaptures); + symbols = SUBSTITUTION_SYMBOLS; + } + return nativeReplace.call(replacement, symbols, function (match, ch) { + var capture; + switch (ch.charAt(0)) { + case '$': + return '$'; + case '&': + return matched; + case '`': + return str.slice(0, position); + case '\'': + return str.slice(tailPos); + case '<': + capture = namedCaptures[ch.slice(1, - 1)]; + break; + default: + // \d\d? + var n = + ch; + if (n === 0) return match; + if (n > m) { + var f = floor(n / 10); + if (f === 0) return match; + if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); + return match; + } + capture = captures[n - 1]; + } + return capture === undefined ? '' : capture; + }); + } + }); + }, + { + '../internals/advance-string-index': 26, + '../internals/an-object': 28, + '../internals/fix-regexp-well-known-symbol-logic': 70, + '../internals/regexp-exec-abstract': 128, + '../internals/require-object-coercible': 132, + '../internals/to-integer': 154, + '../internals/to-length': 155, + '../internals/to-object': 156 + } + ], + 220: [ + function (_dereq_, module, exports) { + 'use strict'; + var fixRegExpWellKnownSymbolLogic = _dereq_('../internals/fix-regexp-well-known-symbol-logic'); + var anObject = _dereq_('../internals/an-object'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var sameValue = _dereq_('../internals/same-value'); + var regExpExec = _dereq_('../internals/regexp-exec-abstract'); + // @@search logic + fixRegExpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) { + return [ // `String.prototype.search` method + // https://tc39.github.io/ecma262/#sec-string.prototype.search + function search(regexp) { + var O = requireObjectCoercible(this); + var searcher = regexp == undefined ? undefined : regexp[SEARCH]; + return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp) [SEARCH](String(O)); + }, + // `RegExp.prototype[@@search]` method + // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search + function (regexp) { + var res = maybeCallNative(nativeSearch, regexp, this); + if (res.done) return res.value; + var rx = anObject(regexp); + var S = String(this); + var previousLastIndex = rx.lastIndex; + if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0; + var result = regExpExec(rx, S); + if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex; + return result === null ? - 1 : result.index; + } + ]; + }); + }, + { + '../internals/an-object': 28, + '../internals/fix-regexp-well-known-symbol-logic': 70, + '../internals/regexp-exec-abstract': 128, + '../internals/require-object-coercible': 132, + '../internals/same-value': 133 + } + ], + 221: [ + function (_dereq_, module, exports) { + 'use strict'; + var fixRegExpWellKnownSymbolLogic = _dereq_('../internals/fix-regexp-well-known-symbol-logic'); + var isRegExp = _dereq_('../internals/is-regexp'); + var anObject = _dereq_('../internals/an-object'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var speciesConstructor = _dereq_('../internals/species-constructor'); + var advanceStringIndex = _dereq_('../internals/advance-string-index'); + var toLength = _dereq_('../internals/to-length'); + var callRegExpExec = _dereq_('../internals/regexp-exec-abstract'); + var regexpExec = _dereq_('../internals/regexp-exec'); + var fails = _dereq_('../internals/fails'); + var arrayPush = [ + ].push; + var min = Math.min; + var MAX_UINT32 = 4294967295; + // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError + var SUPPORTS_Y = !fails(function () { + return !RegExp(MAX_UINT32, 'y'); + }); + // @@split logic + fixRegExpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) { + var internalSplit; + if ('abbc'.split(/(b)*/) [1] == 'c' || 'test'.split(/(?:)/, - 1).length != 4 || 'ab'.split(/(?:ab)*/).length != 2 || '.'.split(/(.?)(.?)/).length != 4 || '.'.split(/()()/).length > 1 || ''.split(/.?/).length) { + // based on es5-shim implementation, need to rework it + internalSplit = function (separator, limit) { + var string = String(requireObjectCoercible(this)); + var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; + if (lim === 0) return []; + if (separator === undefined) return [string]; + // If `separator` is not a regex, use native split + if (!isRegExp(separator)) { + return nativeSplit.call(string, separator, lim); + } + var output = [ + ]; + var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : ''); + var lastLastIndex = 0; + // Make `global` and avoid `lastIndex` issues by working with a copy + var separatorCopy = new RegExp(separator.source, flags + 'g'); + var match, + lastIndex, + lastLength; + while (match = regexpExec.call(separatorCopy, string)) { + lastIndex = separatorCopy.lastIndex; + if (lastIndex > lastLastIndex) { + output.push(string.slice(lastLastIndex, match.index)); + if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1)); + lastLength = match[0].length; + lastLastIndex = lastIndex; + if (output.length >= lim) break; + } + if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop + } + if (lastLastIndex === string.length) { + if (lastLength || !separatorCopy.test('')) output.push(''); + } else output.push(string.slice(lastLastIndex)); + return output.length > lim ? output.slice(0, lim) : output; + }; + // Chakra, V8 + } else if ('0'.split(undefined, 0).length) { + internalSplit = function (separator, limit) { + return separator === undefined && limit === 0 ? [ + ] : nativeSplit.call(this, separator, limit); + }; + } else internalSplit = nativeSplit; + return [ // `String.prototype.split` method + // https://tc39.github.io/ecma262/#sec-string.prototype.split + function split(separator, limit) { + var O = requireObjectCoercible(this); + var splitter = separator == undefined ? undefined : separator[SPLIT]; + return splitter !== undefined ? splitter.call(separator, O, limit) : internalSplit.call(String(O), separator, limit); + }, + // `RegExp.prototype[@@split]` method + // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split + // + // NOTE: This cannot be properly polyfilled in engines that don't support + // the 'y' flag. + function (regexp, limit) { + var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit); + if (res.done) return res.value; + var rx = anObject(regexp); + var S = String(this); + var C = speciesConstructor(rx, RegExp); + var unicodeMatching = rx.unicode; + var flags = (rx.ignoreCase ? 'i' : '') + (rx.multiline ? 'm' : '') + (rx.unicode ? 'u' : '') + (SUPPORTS_Y ? 'y' : 'g'); + // ^(? + rx + ) is needed, in combination with some S slicing, to + // simulate the 'y' flag. + var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags); + var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; + if (lim === 0) return []; + if (S.length === 0) return callRegExpExec(splitter, S) === null ? [ + S + ] : [ + ]; + var p = 0; + var q = 0; + var A = [ + ]; + while (q < S.length) { + splitter.lastIndex = SUPPORTS_Y ? q : 0; + var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q)); + var e; + if (z === null || (e = min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p) { + q = advanceStringIndex(S, q, unicodeMatching); + } else { + A.push(S.slice(p, q)); + if (A.length === lim) return A; + for (var i = 1; i <= z.length - 1; i++) { + A.push(z[i]); + if (A.length === lim) return A; + } + q = p = e; + } + } + A.push(S.slice(p)); + return A; + } + ]; + }, !SUPPORTS_Y); + }, + { + '../internals/advance-string-index': 26, + '../internals/an-object': 28, + '../internals/fails': 69, + '../internals/fix-regexp-well-known-symbol-logic': 70, + '../internals/is-regexp': 95, + '../internals/regexp-exec': 129, + '../internals/regexp-exec-abstract': 128, + '../internals/require-object-coercible': 132, + '../internals/species-constructor': 140, + '../internals/to-length': 155 + } + ], + 222: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var getOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f; + var toLength = _dereq_('../internals/to-length'); + var notARegExp = _dereq_('../internals/not-a-regexp'); + var requireObjectCoercible = _dereq_('../internals/require-object-coercible'); + var correctIsRegExpLogic = _dereq_('../internals/correct-is-regexp-logic'); + var IS_PURE = _dereq_('../internals/is-pure'); + var nativeStartsWith = ''.startsWith; + var min = Math.min; + var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('startsWith'); + // https://github.com/zloirock/core-js/pull/702 + var MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () { + var descriptor = getOwnPropertyDescriptor(String.prototype, 'startsWith'); + return descriptor && !descriptor.writable; + }(); + // `String.prototype.startsWith` method + // https://tc39.github.io/ecma262/#sec-string.prototype.startswith + $({ + target: 'String', + proto: true, + forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC + }, { + startsWith: function startsWith(searchString /* , position = 0 */ ) { + var that = String(requireObjectCoercible(this)); + notARegExp(searchString); + var index = toLength(min(arguments.length > 1 ? arguments[1] : undefined, that.length)); + var search = String(searchString); + return nativeStartsWith ? nativeStartsWith.call(that, search, index) : that.slice(index, index + search.length) === search; + } + }); + }, + { + '../internals/correct-is-regexp-logic': 52, + '../internals/export': 68, + '../internals/is-pure': 94, + '../internals/not-a-regexp': 106, + '../internals/object-get-own-property-descriptor': 112, + '../internals/require-object-coercible': 132, + '../internals/to-length': 155 + } + ], + 223: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var createHTML = _dereq_('../internals/create-html'); + var forcedStringHTMLMethod = _dereq_('../internals/string-html-forced'); + // `String.prototype.sub` method + // https://tc39.github.io/ecma262/#sec-string.prototype.sub + $({ + target: 'String', + proto: true, + forced: forcedStringHTMLMethod('sub') + }, { + sub: function sub() { + return createHTML(this, 'sub', '', ''); + } + }); + }, + { + '../internals/create-html': 54, + '../internals/export': 68, + '../internals/string-html-forced': 141 + } + ], + 224: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var $trim = _dereq_('../internals/string-trim').trim; + var forcedStringTrimMethod = _dereq_('../internals/string-trim-forced'); + // `String.prototype.trim` method + // https://tc39.github.io/ecma262/#sec-string.prototype.trim + $({ + target: 'String', + proto: true, + forced: forcedStringTrimMethod('trim') + }, { + trim: function trim() { + return $trim(this); + } + }); + }, + { + '../internals/export': 68, + '../internals/string-trim': 148, + '../internals/string-trim-forced': 147 + } + ], + 225: [ + function (_dereq_, module, exports) { + // `Symbol.prototype.description` getter + // https://tc39.github.io/ecma262/#sec-symbol.prototype.description + 'use strict'; + var $ = _dereq_('../internals/export'); + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var global = _dereq_('../internals/global'); + var has = _dereq_('../internals/has'); + var isObject = _dereq_('../internals/is-object'); + var defineProperty = _dereq_('../internals/object-define-property').f; + var copyConstructorProperties = _dereq_('../internals/copy-constructor-properties'); + var NativeSymbol = global.Symbol; + if (DESCRIPTORS && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) || // Safari 12 bug + NativeSymbol().description !== undefined)) { + var EmptyStringDescriptionStore = { + }; + // wrap Symbol constructor for correct work with undefined description + var SymbolWrapper = function Symbol() { + var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]); + var result = this instanceof SymbolWrapper ? new NativeSymbol(description) // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)' + : description === undefined ? NativeSymbol() : NativeSymbol(description); + if (description === '') EmptyStringDescriptionStore[result] = true; + return result; + }; + copyConstructorProperties(SymbolWrapper, NativeSymbol); + var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype; + symbolPrototype.constructor = SymbolWrapper; + var symbolToString = symbolPrototype.toString; + var native = String(NativeSymbol('test')) == 'Symbol(test)'; + var regexp = /^Symbol\((.*)\)[^)]+$/; + defineProperty(symbolPrototype, 'description', { + configurable: true, + get: function description() { + var symbol = isObject(this) ? this.valueOf() : this; + var string = symbolToString.call(symbol); + if (has(EmptyStringDescriptionStore, symbol)) return ''; + var desc = native ? string.slice(7, - 1) : string.replace(regexp, '$1'); + return desc === '' ? undefined : desc; + } + }); + $({ + global: true, + forced: true + }, { + Symbol: SymbolWrapper + }); + } + }, + { + '../internals/copy-constructor-properties': 51, + '../internals/descriptors': 61, + '../internals/export': 68, + '../internals/global': 78, + '../internals/has': 79, + '../internals/is-object': 93, + '../internals/object-define-property': 111 + } + ], + 226: [ + function (_dereq_, module, exports) { + var defineWellKnownSymbol = _dereq_('../internals/define-well-known-symbol'); + // `Symbol.iterator` well-known symbol + // https://tc39.github.io/ecma262/#sec-symbol.iterator + defineWellKnownSymbol('iterator'); + }, + { + '../internals/define-well-known-symbol': 60 + } + ], + 227: [ + function (_dereq_, module, exports) { + 'use strict'; + var $ = _dereq_('../internals/export'); + var global = _dereq_('../internals/global'); + var getBuiltIn = _dereq_('../internals/get-built-in'); + var IS_PURE = _dereq_('../internals/is-pure'); + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var NATIVE_SYMBOL = _dereq_('../internals/native-symbol'); + var USE_SYMBOL_AS_UID = _dereq_('../internals/use-symbol-as-uid'); + var fails = _dereq_('../internals/fails'); + var has = _dereq_('../internals/has'); + var isArray = _dereq_('../internals/is-array'); + var isObject = _dereq_('../internals/is-object'); + var anObject = _dereq_('../internals/an-object'); + var toObject = _dereq_('../internals/to-object'); + var toIndexedObject = _dereq_('../internals/to-indexed-object'); + var toPrimitive = _dereq_('../internals/to-primitive'); + var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor'); + var nativeObjectCreate = _dereq_('../internals/object-create'); + var objectKeys = _dereq_('../internals/object-keys'); + var getOwnPropertyNamesModule = _dereq_('../internals/object-get-own-property-names'); + var getOwnPropertyNamesExternal = _dereq_('../internals/object-get-own-property-names-external'); + var getOwnPropertySymbolsModule = _dereq_('../internals/object-get-own-property-symbols'); + var getOwnPropertyDescriptorModule = _dereq_('../internals/object-get-own-property-descriptor'); + var definePropertyModule = _dereq_('../internals/object-define-property'); + var propertyIsEnumerableModule = _dereq_('../internals/object-property-is-enumerable'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var redefine = _dereq_('../internals/redefine'); + var shared = _dereq_('../internals/shared'); + var sharedKey = _dereq_('../internals/shared-key'); + var hiddenKeys = _dereq_('../internals/hidden-keys'); + var uid = _dereq_('../internals/uid'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var wrappedWellKnownSymbolModule = _dereq_('../internals/well-known-symbol-wrapped'); + var defineWellKnownSymbol = _dereq_('../internals/define-well-known-symbol'); + var setToStringTag = _dereq_('../internals/set-to-string-tag'); + var InternalStateModule = _dereq_('../internals/internal-state'); + var $forEach = _dereq_('../internals/array-iteration').forEach; + var HIDDEN = sharedKey('hidden'); + var SYMBOL = 'Symbol'; + var PROTOTYPE = 'prototype'; + var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); + var setInternalState = InternalStateModule.set; + var getInternalState = InternalStateModule.getterFor(SYMBOL); + var ObjectPrototype = Object[PROTOTYPE]; + var $Symbol = global.Symbol; + var $stringify = getBuiltIn('JSON', 'stringify'); + var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; + var nativeDefineProperty = definePropertyModule.f; + var nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f; + var nativePropertyIsEnumerable = propertyIsEnumerableModule.f; + var AllSymbols = shared('symbols'); + var ObjectPrototypeSymbols = shared('op-symbols'); + var StringToSymbolRegistry = shared('string-to-symbol-registry'); + var SymbolToStringRegistry = shared('symbol-to-string-registry'); + var WellKnownSymbolsStore = shared('wks'); + var QObject = global.QObject; + // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 + var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 + var setSymbolDescriptor = DESCRIPTORS && fails(function () { + return nativeObjectCreate(nativeDefineProperty({ + }, 'a', { + get: function () { + return nativeDefineProperty(this, 'a', { + value: 7 + }).a; + } + })).a != 7; + }) ? function (O, P, Attributes) { + var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P); + if (ObjectPrototypeDescriptor) delete ObjectPrototype[P]; + nativeDefineProperty(O, P, Attributes); + if (ObjectPrototypeDescriptor && O !== ObjectPrototype) { + nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor); + } + } + : nativeDefineProperty; + var wrap = function (tag, description) { + var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol[PROTOTYPE]); + setInternalState(symbol, { + type: SYMBOL, + tag: tag, + description: description + }); + if (!DESCRIPTORS) symbol.description = description; + return symbol; + }; + var isSymbol = USE_SYMBOL_AS_UID ? function (it) { + return typeof it == 'symbol'; + } + : function (it) { + return Object(it) instanceof $Symbol; + }; + var $defineProperty = function defineProperty(O, P, Attributes) { + if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes); + anObject(O); + var key = toPrimitive(P, true); + anObject(Attributes); + if (has(AllSymbols, key)) { + if (!Attributes.enumerable) { + if (!has(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, { + })); + O[HIDDEN][key] = true; + } else { + if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false; + Attributes = nativeObjectCreate(Attributes, { + enumerable: createPropertyDescriptor(0, false) + }); + } + return setSymbolDescriptor(O, key, Attributes); + } + return nativeDefineProperty(O, key, Attributes); + }; + var $defineProperties = function defineProperties(O, Properties) { + anObject(O); + var properties = toIndexedObject(Properties); + var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties)); + $forEach(keys, function (key) { + if (!DESCRIPTORS || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]); + }); + return O; + }; + var $create = function create(O, Properties) { + return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties); + }; + var $propertyIsEnumerable = function propertyIsEnumerable(V) { + var P = toPrimitive(V, true); + var enumerable = nativePropertyIsEnumerable.call(this, P); + if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false; + return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true; + }; + var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) { + var it = toIndexedObject(O); + var key = toPrimitive(P, true); + if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return; + var descriptor = nativeGetOwnPropertyDescriptor(it, key); + if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) { + descriptor.enumerable = true; + } + return descriptor; + }; + var $getOwnPropertyNames = function getOwnPropertyNames(O) { + var names = nativeGetOwnPropertyNames(toIndexedObject(O)); + var result = [ + ]; + $forEach(names, function (key) { + if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key); + }); + return result; + }; + var $getOwnPropertySymbols = function getOwnPropertySymbols(O) { + var IS_OBJECT_PROTOTYPE = O === ObjectPrototype; + var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O)); + var result = [ + ]; + $forEach(names, function (key) { + if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) { + result.push(AllSymbols[key]); + } + }); + return result; + }; + // `Symbol` constructor + // https://tc39.github.io/ecma262/#sec-symbol-constructor + if (!NATIVE_SYMBOL) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor'); + var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]); + var tag = uid(description); + var setter = function (value) { + if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value); + if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value)); + }; + if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { + configurable: true, + set: setter + }); + return wrap(tag, description); + }; + redefine($Symbol[PROTOTYPE], 'toString', function toString() { + return getInternalState(this).tag; + }); + redefine($Symbol, 'withoutSetter', function (description) { + return wrap(uid(description), description); + }); + propertyIsEnumerableModule.f = $propertyIsEnumerable; + definePropertyModule.f = $defineProperty; + getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor; + getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames; + getOwnPropertySymbolsModule.f = $getOwnPropertySymbols; + wrappedWellKnownSymbolModule.f = function (name) { + return wrap(wellKnownSymbol(name), name); + }; + if (DESCRIPTORS) { + // https://github.com/tc39/proposal-Symbol-description + nativeDefineProperty($Symbol[PROTOTYPE], 'description', { + configurable: true, + get: function description() { + return getInternalState(this).description; + } + }); + if (!IS_PURE) { + redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { + unsafe: true + }); + } + } + } + $({ + global: true, + wrap: true, + forced: !NATIVE_SYMBOL, + sham: !NATIVE_SYMBOL + }, { + Symbol: $Symbol + }); + $forEach(objectKeys(WellKnownSymbolsStore), function (name) { + defineWellKnownSymbol(name); + }); + $({ + target: SYMBOL, + stat: true, + forced: !NATIVE_SYMBOL + }, { + // `Symbol.for` method + // https://tc39.github.io/ecma262/#sec-symbol.for + 'for': function (key) { + var string = String(key); + if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string]; + var symbol = $Symbol(string); + StringToSymbolRegistry[string] = symbol; + SymbolToStringRegistry[symbol] = string; + return symbol; + }, + // `Symbol.keyFor` method + // https://tc39.github.io/ecma262/#sec-symbol.keyfor + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol'); + if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym]; + }, + useSetter: function () { + USE_SETTER = true; + }, + useSimple: function () { + USE_SETTER = false; + } + }); + $({ + target: 'Object', + stat: true, + forced: !NATIVE_SYMBOL, + sham: !DESCRIPTORS + }, { + // `Object.create` method + // https://tc39.github.io/ecma262/#sec-object.create + create: $create, + // `Object.defineProperty` method + // https://tc39.github.io/ecma262/#sec-object.defineproperty + defineProperty: $defineProperty, + // `Object.defineProperties` method + // https://tc39.github.io/ecma262/#sec-object.defineproperties + defineProperties: $defineProperties, + // `Object.getOwnPropertyDescriptor` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors + getOwnPropertyDescriptor: $getOwnPropertyDescriptor + }); + $({ + target: 'Object', + stat: true, + forced: !NATIVE_SYMBOL + }, { + // `Object.getOwnPropertyNames` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertynames + getOwnPropertyNames: $getOwnPropertyNames, + // `Object.getOwnPropertySymbols` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols + getOwnPropertySymbols: $getOwnPropertySymbols + }); + // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives + // https://bugs.chromium.org/p/v8/issues/detail?id=3443 + $({ + target: 'Object', + stat: true, + forced: fails(function () { + getOwnPropertySymbolsModule.f(1); + }) + }, { + getOwnPropertySymbols: function getOwnPropertySymbols(it) { + return getOwnPropertySymbolsModule.f(toObject(it)); + } + }); + // `JSON.stringify` method behavior with symbols + // https://tc39.github.io/ecma262/#sec-json.stringify + if ($stringify) { + var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails(function () { + var symbol = $Symbol(); + // MS Edge converts symbol values to JSON as {} + return $stringify([symbol]) != '[null]' // WebKit converts symbol values to JSON as null + || $stringify({ + a: symbol + }) != '{}' // V8 throws on boxed symbols + || $stringify(Object(symbol)) != '{}'; + }); + $({ + target: 'JSON', + stat: true, + forced: FORCED_JSON_STRINGIFY + }, { + // eslint-disable-next-line no-unused-vars + stringify: function stringify(it, replacer, space) { + var args = [ + it + ]; + var index = 1; + var $replacer; + while (arguments.length > index) args.push(arguments[index++]); + $replacer = replacer; + if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + if (!isArray(replacer)) replacer = function (key, value) { + if (typeof $replacer == 'function') value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return $stringify.apply(null, args); + } + }); + } // `Symbol.prototype[@@toPrimitive]` method + // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive + + if (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) { + createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); + } // `Symbol.prototype[@@toStringTag]` property + // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag + + setToStringTag($Symbol, SYMBOL); + hiddenKeys[HIDDEN] = true; + }, + { + '../internals/an-object': 28, + '../internals/array-iteration': 37, + '../internals/create-non-enumerable-property': 56, + '../internals/create-property-descriptor': 57, + '../internals/define-well-known-symbol': 60, + '../internals/descriptors': 61, + '../internals/export': 68, + '../internals/fails': 69, + '../internals/get-built-in': 75, + '../internals/global': 78, + '../internals/has': 79, + '../internals/hidden-keys': 80, + '../internals/internal-state': 89, + '../internals/is-array': 91, + '../internals/is-object': 93, + '../internals/is-pure': 94, + '../internals/native-symbol': 102, + '../internals/object-create': 109, + '../internals/object-define-property': 111, + '../internals/object-get-own-property-descriptor': 112, + '../internals/object-get-own-property-names': 114, + '../internals/object-get-own-property-names-external': 113, + '../internals/object-get-own-property-symbols': 115, + '../internals/object-keys': 118, + '../internals/object-property-is-enumerable': 119, + '../internals/redefine': 127, + '../internals/set-to-string-tag': 136, + '../internals/shared': 139, + '../internals/shared-key': 137, + '../internals/to-indexed-object': 153, + '../internals/to-object': 156, + '../internals/to-primitive': 159, + '../internals/uid': 164, + '../internals/use-symbol-as-uid': 165, + '../internals/well-known-symbol': 167, + '../internals/well-known-symbol-wrapped': 166 + } + ], + 228: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $copyWithin = _dereq_('../internals/array-copy-within'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.copyWithin` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.copywithin + exportTypedArrayMethod('copyWithin', function copyWithin(target, start /* , end */ ) { + return $copyWithin.call(aTypedArray(this), target, start, arguments.length > 2 ? arguments[2] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-copy-within': 32 + } + ], + 229: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $every = _dereq_('../internals/array-iteration').every; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.every` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.every + exportTypedArrayMethod('every', function every(callbackfn /* , thisArg */ ) { + return $every(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-iteration': 37 + } + ], + 230: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $fill = _dereq_('../internals/array-fill'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.fill` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill + // eslint-disable-next-line no-unused-vars + exportTypedArrayMethod('fill', function fill(value /* , start, end */ ) { + return $fill.apply(aTypedArray(this), arguments); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-fill': 33 + } + ], + 231: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $filter = _dereq_('../internals/array-iteration').filter; + var speciesConstructor = _dereq_('../internals/species-constructor'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.filter` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.filter + exportTypedArrayMethod('filter', function filter(callbackfn /* , thisArg */ ) { + var list = $filter(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + var C = speciesConstructor(this, this.constructor); + var index = 0; + var length = list.length; + var result = new (aTypedArrayConstructor(C)) (length); + while (length > index) result[index] = list[index++]; + return result; + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-iteration': 37, + '../internals/species-constructor': 140 + } + ], + 232: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $findIndex = _dereq_('../internals/array-iteration').findIndex; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.findIndex` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.findindex + exportTypedArrayMethod('findIndex', function findIndex(predicate /* , thisArg */ ) { + return $findIndex(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-iteration': 37 + } + ], + 233: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $find = _dereq_('../internals/array-iteration').find; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.find` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.find + exportTypedArrayMethod('find', function find(predicate /* , thisArg */ ) { + return $find(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-iteration': 37 + } + ], + 234: [ + function (_dereq_, module, exports) { + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Float32Array` constructor + // https://tc39.github.io/ecma262/#sec-typedarray-objects + createTypedArrayConstructor('Float32', function (init) { + return function Float32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + }, + { + '../internals/typed-array-constructor': 161 + } + ], + 235: [ + function (_dereq_, module, exports) { + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Float64Array` constructor + // https://tc39.github.io/ecma262/#sec-typedarray-objects + createTypedArrayConstructor('Float64', function (init) { + return function Float64Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + }, + { + '../internals/typed-array-constructor': 161 + } + ], + 236: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $forEach = _dereq_('../internals/array-iteration').forEach; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.forEach` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.foreach + exportTypedArrayMethod('forEach', function forEach(callbackfn /* , thisArg */ ) { + $forEach(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-iteration': 37 + } + ], + 237: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $includes = _dereq_('../internals/array-includes').includes; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.includes` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.includes + exportTypedArrayMethod('includes', function includes(searchElement /* , fromIndex */ ) { + return $includes(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-includes': 36 + } + ], + 238: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $indexOf = _dereq_('../internals/array-includes').indexOf; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.indexOf` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.indexof + exportTypedArrayMethod('indexOf', function indexOf(searchElement /* , fromIndex */ ) { + return $indexOf(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-includes': 36 + } + ], + 239: [ + function (_dereq_, module, exports) { + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Int16Array` constructor + // https://tc39.github.io/ecma262/#sec-typedarray-objects + createTypedArrayConstructor('Int16', function (init) { + return function Int16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + }, + { + '../internals/typed-array-constructor': 161 + } + ], + 240: [ + function (_dereq_, module, exports) { + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Int32Array` constructor + // https://tc39.github.io/ecma262/#sec-typedarray-objects + createTypedArrayConstructor('Int32', function (init) { + return function Int32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + }, + { + '../internals/typed-array-constructor': 161 + } + ], + 241: [ + function (_dereq_, module, exports) { + 'use strict'; + var global = _dereq_('../internals/global'); + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var ArrayIterators = _dereq_('../modules/es.array.iterator'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var ITERATOR = wellKnownSymbol('iterator'); + var Uint8Array = global.Uint8Array; + var arrayValues = ArrayIterators.values; + var arrayKeys = ArrayIterators.keys; + var arrayEntries = ArrayIterators.entries; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + var nativeTypedArrayIterator = Uint8Array && Uint8Array.prototype[ITERATOR]; + var CORRECT_ITER_NAME = !!nativeTypedArrayIterator && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined); + var typedArrayValues = function values() { + return arrayValues.call(aTypedArray(this)); + }; + // `%TypedArray%.prototype.entries` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.entries + exportTypedArrayMethod('entries', function entries() { + return arrayEntries.call(aTypedArray(this)); + }); + // `%TypedArray%.prototype.keys` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.keys + exportTypedArrayMethod('keys', function keys() { + return arrayKeys.call(aTypedArray(this)); + }); + // `%TypedArray%.prototype.values` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.values + exportTypedArrayMethod('values', typedArrayValues, !CORRECT_ITER_NAME); + // `%TypedArray%.prototype[@@iterator]` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype-@@iterator + exportTypedArrayMethod(ITERATOR, typedArrayValues, !CORRECT_ITER_NAME); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/global': 78, + '../internals/well-known-symbol': 167, + '../modules/es.array.iterator': 182 + } + ], + 242: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + var $join = [ + ].join; + // `%TypedArray%.prototype.join` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join + // eslint-disable-next-line no-unused-vars + exportTypedArrayMethod('join', function join(separator) { + return $join.apply(aTypedArray(this), arguments); + }); + }, + { + '../internals/array-buffer-view-core': 30 + } + ], + 243: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $lastIndexOf = _dereq_('../internals/array-last-index-of'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.lastIndexOf` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.lastindexof + // eslint-disable-next-line no-unused-vars + exportTypedArrayMethod('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */ ) { + return $lastIndexOf.apply(aTypedArray(this), arguments); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-last-index-of': 38 + } + ], + 244: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $map = _dereq_('../internals/array-iteration').map; + var speciesConstructor = _dereq_('../internals/species-constructor'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.map` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.map + exportTypedArrayMethod('map', function map(mapfn /* , thisArg */ ) { + return $map(aTypedArray(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) { + return new (aTypedArrayConstructor(speciesConstructor(O, O.constructor))) (length); + }); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-iteration': 37, + '../internals/species-constructor': 140 + } + ], + 245: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $reduceRight = _dereq_('../internals/array-reduce').right; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.reduceRicht` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduceright + exportTypedArrayMethod('reduceRight', function reduceRight(callbackfn /* , initialValue */ ) { + return $reduceRight(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-reduce': 42 + } + ], + 246: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $reduce = _dereq_('../internals/array-reduce').left; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.reduce` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduce + exportTypedArrayMethod('reduce', function reduce(callbackfn /* , initialValue */ ) { + return $reduce(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-reduce': 42 + } + ], + 247: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + var floor = Math.floor; + // `%TypedArray%.prototype.reverse` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reverse + exportTypedArrayMethod('reverse', function reverse() { + var that = this; + var length = aTypedArray(that).length; + var middle = floor(length / 2); + var index = 0; + var value; + while (index < middle) { + value = that[index]; + that[index++] = that[--length]; + that[length] = value; + } + return that; + }); + }, + { + '../internals/array-buffer-view-core': 30 + } + ], + 248: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var toLength = _dereq_('../internals/to-length'); + var toOffset = _dereq_('../internals/to-offset'); + var toObject = _dereq_('../internals/to-object'); + var fails = _dereq_('../internals/fails'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + var FORCED = fails(function () { + // eslint-disable-next-line no-undef + new Int8Array(1).set({ + }); + }); + // `%TypedArray%.prototype.set` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.set + exportTypedArrayMethod('set', function set(arrayLike /* , offset */ ) { + aTypedArray(this); + var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1); + var length = this.length; + var src = toObject(arrayLike); + var len = toLength(src.length); + var index = 0; + if (len + offset > length) throw RangeError('Wrong length'); + while (index < len) this[offset + index] = src[index++]; + }, FORCED); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/fails': 69, + '../internals/to-length': 155, + '../internals/to-object': 156, + '../internals/to-offset': 157 + } + ], + 249: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var speciesConstructor = _dereq_('../internals/species-constructor'); + var fails = _dereq_('../internals/fails'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + var $slice = [ + ].slice; + var FORCED = fails(function () { + // eslint-disable-next-line no-undef + new Int8Array(1).slice(); + }); + // `%TypedArray%.prototype.slice` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.slice + exportTypedArrayMethod('slice', function slice(start, end) { + var list = $slice.call(aTypedArray(this), start, end); + var C = speciesConstructor(this, this.constructor); + var index = 0; + var length = list.length; + var result = new (aTypedArrayConstructor(C)) (length); + while (length > index) result[index] = list[index++]; + return result; + }, FORCED); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/fails': 69, + '../internals/species-constructor': 140 + } + ], + 250: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var $some = _dereq_('../internals/array-iteration').some; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.some` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some + exportTypedArrayMethod('some', function some(callbackfn /* , thisArg */ ) { + return $some(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/array-iteration': 37 + } + ], + 251: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + var $sort = [ + ].sort; + // `%TypedArray%.prototype.sort` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.sort + exportTypedArrayMethod('sort', function sort(comparefn) { + return $sort.call(aTypedArray(this), comparefn); + }); + }, + { + '../internals/array-buffer-view-core': 30 + } + ], + 252: [ + function (_dereq_, module, exports) { + 'use strict'; + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var toLength = _dereq_('../internals/to-length'); + var toAbsoluteIndex = _dereq_('../internals/to-absolute-index'); + var speciesConstructor = _dereq_('../internals/species-constructor'); + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + // `%TypedArray%.prototype.subarray` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.subarray + exportTypedArrayMethod('subarray', function subarray(begin, end) { + var O = aTypedArray(this); + var length = O.length; + var beginIndex = toAbsoluteIndex(begin, length); + return new (speciesConstructor(O, O.constructor)) (O.buffer, O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT, toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - beginIndex)); + }); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/species-constructor': 140, + '../internals/to-absolute-index': 151, + '../internals/to-length': 155 + } + ], + 253: [ + function (_dereq_, module, exports) { + 'use strict'; + var global = _dereq_('../internals/global'); + var ArrayBufferViewCore = _dereq_('../internals/array-buffer-view-core'); + var fails = _dereq_('../internals/fails'); + var Int8Array = global.Int8Array; + var aTypedArray = ArrayBufferViewCore.aTypedArray; + var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; + var $toLocaleString = [ + ].toLocaleString; + var $slice = [ + ].slice; + // iOS Safari 6.x fails here + var TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () { + $toLocaleString.call(new Int8Array(1)); + }); + var FORCED = fails(function () { + return [1, + 2].toLocaleString() != new Int8Array([1, + 2]).toLocaleString(); + }) || !fails(function () { + Int8Array.prototype.toLocaleString.call([1, + 2]); + }); + // `%TypedArray%.prototype.toLocaleString` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tolocalestring + exportTypedArrayMethod('toLocaleString', function toLocaleString() { + return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments); + }, FORCED); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/fails': 69, + '../internals/global': 78 + } + ], + 254: [ + function (_dereq_, module, exports) { + 'use strict'; + var exportTypedArrayMethod = _dereq_('../internals/array-buffer-view-core').exportTypedArrayMethod; + var fails = _dereq_('../internals/fails'); + var global = _dereq_('../internals/global'); + var Uint8Array = global.Uint8Array; + var Uint8ArrayPrototype = Uint8Array && Uint8Array.prototype || { + }; + var arrayToString = [ + ].toString; + var arrayJoin = [ + ].join; + if (fails(function () { + arrayToString.call({ + }); + })) { + arrayToString = function toString() { + return arrayJoin.call(this); + }; + } + var IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString; + // `%TypedArray%.prototype.toString` method + // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tostring + exportTypedArrayMethod('toString', arrayToString, IS_NOT_ARRAY_METHOD); + }, + { + '../internals/array-buffer-view-core': 30, + '../internals/fails': 69, + '../internals/global': 78 + } + ], + 255: [ + function (_dereq_, module, exports) { + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Uint16Array` constructor + // https://tc39.github.io/ecma262/#sec-typedarray-objects + createTypedArrayConstructor('Uint16', function (init) { + return function Uint16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + }, + { + '../internals/typed-array-constructor': 161 + } + ], + 256: [ + function (_dereq_, module, exports) { + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Uint32Array` constructor + // https://tc39.github.io/ecma262/#sec-typedarray-objects + createTypedArrayConstructor('Uint32', function (init) { + return function Uint32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + }, + { + '../internals/typed-array-constructor': 161 + } + ], + 257: [ + function (_dereq_, module, exports) { + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Uint8Array` constructor + // https://tc39.github.io/ecma262/#sec-typedarray-objects + createTypedArrayConstructor('Uint8', function (init) { + return function Uint8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + }, + { + '../internals/typed-array-constructor': 161 + } + ], + 258: [ + function (_dereq_, module, exports) { + var createTypedArrayConstructor = _dereq_('../internals/typed-array-constructor'); + // `Uint8ClampedArray` constructor + // https://tc39.github.io/ecma262/#sec-typedarray-objects + createTypedArrayConstructor('Uint8', function (init) { + return function Uint8ClampedArray(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }, true); + }, + { + '../internals/typed-array-constructor': 161 + } + ], + 259: [ + function (_dereq_, module, exports) { + 'use strict'; + var global = _dereq_('../internals/global'); + var redefineAll = _dereq_('../internals/redefine-all'); + var InternalMetadataModule = _dereq_('../internals/internal-metadata'); + var collection = _dereq_('../internals/collection'); + var collectionWeak = _dereq_('../internals/collection-weak'); + var isObject = _dereq_('../internals/is-object'); + var enforceIternalState = _dereq_('../internals/internal-state').enforce; + var NATIVE_WEAK_MAP = _dereq_('../internals/native-weak-map'); + var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global; + var isExtensible = Object.isExtensible; + var InternalWeakMap; + var wrapper = function (init) { + return function WeakMap() { + return init(this, arguments.length ? arguments[0] : undefined); + }; + }; + // `WeakMap` constructor + // https://tc39.github.io/ecma262/#sec-weakmap-constructor + var $WeakMap = module.exports = collection('WeakMap', wrapper, collectionWeak); + // IE11 WeakMap frozen keys fix + // We can't use feature detection because it crash some old IE builds + // https://github.com/zloirock/core-js/issues/485 + if (NATIVE_WEAK_MAP && IS_IE11) { + InternalWeakMap = collectionWeak.getConstructor(wrapper, 'WeakMap', true); + InternalMetadataModule.REQUIRED = true; + var WeakMapPrototype = $WeakMap.prototype; + var nativeDelete = WeakMapPrototype['delete']; + var nativeHas = WeakMapPrototype.has; + var nativeGet = WeakMapPrototype.get; + var nativeSet = WeakMapPrototype.set; + redefineAll(WeakMapPrototype, { + 'delete': function (key) { + if (isObject(key) && !isExtensible(key)) { + var state = enforceIternalState(this); + if (!state.frozen) state.frozen = new InternalWeakMap(); + return nativeDelete.call(this, key) || state.frozen['delete'](key); + } + return nativeDelete.call(this, key); + }, + has: function has(key) { + if (isObject(key) && !isExtensible(key)) { + var state = enforceIternalState(this); + if (!state.frozen) state.frozen = new InternalWeakMap(); + return nativeHas.call(this, key) || state.frozen.has(key); + } + return nativeHas.call(this, key); + }, + get: function get(key) { + if (isObject(key) && !isExtensible(key)) { + var state = enforceIternalState(this); + if (!state.frozen) state.frozen = new InternalWeakMap(); + return nativeHas.call(this, key) ? nativeGet.call(this, key) : state.frozen.get(key); + } + return nativeGet.call(this, key); + }, + set: function set(key, value) { + if (isObject(key) && !isExtensible(key)) { + var state = enforceIternalState(this); + if (!state.frozen) state.frozen = new InternalWeakMap(); + nativeHas.call(this, key) ? nativeSet.call(this, key, value) : state.frozen.set(key, value); + } else nativeSet.call(this, key, value); + return this; + } + }); + } + }, + { + '../internals/collection': 50, + '../internals/collection-weak': 49, + '../internals/global': 78, + '../internals/internal-metadata': 88, + '../internals/internal-state': 89, + '../internals/is-object': 93, + '../internals/native-weak-map': 104, + '../internals/redefine-all': 126 + } + ], + 260: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var DOMIterables = _dereq_('../internals/dom-iterables'); + var forEach = _dereq_('../internals/array-for-each'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + for (var COLLECTION_NAME in DOMIterables) { + var Collection = global[COLLECTION_NAME]; + var CollectionPrototype = Collection && Collection.prototype; + // some Chrome versions have non-configurable methods on DOMTokenList + if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try { + createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach); + } catch (error) { + CollectionPrototype.forEach = forEach; + } + } + }, + { + '../internals/array-for-each': 34, + '../internals/create-non-enumerable-property': 56, + '../internals/dom-iterables': 63, + '../internals/global': 78 + } + ], + 261: [ + function (_dereq_, module, exports) { + var global = _dereq_('../internals/global'); + var DOMIterables = _dereq_('../internals/dom-iterables'); + var ArrayIteratorMethods = _dereq_('../modules/es.array.iterator'); + var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var ITERATOR = wellKnownSymbol('iterator'); + var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + var ArrayValues = ArrayIteratorMethods.values; + for (var COLLECTION_NAME in DOMIterables) { + var Collection = global[COLLECTION_NAME]; + var CollectionPrototype = Collection && Collection.prototype; + if (CollectionPrototype) { + // some Chrome versions have non-configurable methods on DOMTokenList + if (CollectionPrototype[ITERATOR] !== ArrayValues) try { + createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues); + } catch (error) { + CollectionPrototype[ITERATOR] = ArrayValues; + } + if (!CollectionPrototype[TO_STRING_TAG]) { + createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME); + } + if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) { + // some Chrome versions have non-configurable methods on DOMTokenList + if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try { + createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]); + } catch (error) { + CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME]; + } + } + } + } + }, + { + '../internals/create-non-enumerable-property': 56, + '../internals/dom-iterables': 63, + '../internals/global': 78, + '../internals/well-known-symbol': 167, + '../modules/es.array.iterator': 182 + } + ], + 262: [ + function (_dereq_, module, exports) { + 'use strict'; + // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` + _dereq_('../modules/es.array.iterator'); + var $ = _dereq_('../internals/export'); + var getBuiltIn = _dereq_('../internals/get-built-in'); + var USE_NATIVE_URL = _dereq_('../internals/native-url'); + var redefine = _dereq_('../internals/redefine'); + var redefineAll = _dereq_('../internals/redefine-all'); + var setToStringTag = _dereq_('../internals/set-to-string-tag'); + var createIteratorConstructor = _dereq_('../internals/create-iterator-constructor'); + var InternalStateModule = _dereq_('../internals/internal-state'); + var anInstance = _dereq_('../internals/an-instance'); + var hasOwn = _dereq_('../internals/has'); + var bind = _dereq_('../internals/function-bind-context'); + var classof = _dereq_('../internals/classof'); + var anObject = _dereq_('../internals/an-object'); + var isObject = _dereq_('../internals/is-object'); + var create = _dereq_('../internals/object-create'); + var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor'); + var getIterator = _dereq_('../internals/get-iterator'); + var getIteratorMethod = _dereq_('../internals/get-iterator-method'); + var wellKnownSymbol = _dereq_('../internals/well-known-symbol'); + var $fetch = getBuiltIn('fetch'); + var Headers = getBuiltIn('Headers'); + var ITERATOR = wellKnownSymbol('iterator'); + var URL_SEARCH_PARAMS = 'URLSearchParams'; + var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator'; + var setInternalState = InternalStateModule.set; + var getInternalParamsState = InternalStateModule.getterFor(URL_SEARCH_PARAMS); + var getInternalIteratorState = InternalStateModule.getterFor(URL_SEARCH_PARAMS_ITERATOR); + var plus = /\+/g; + var sequences = Array(4); + var percentSequence = function (bytes) { + return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp('((?:%[\\da-f]{2}){' + bytes + '})', 'gi')); + }; + var percentDecode = function (sequence) { + try { + return decodeURIComponent(sequence); + } catch (error) { + return sequence; + } + }; + var deserialize = function (it) { + var result = it.replace(plus, ' '); + var bytes = 4; + try { + return decodeURIComponent(result); + } catch (error) { + while (bytes) { + result = result.replace(percentSequence(bytes--), percentDecode); + } + return result; + } + }; + var find = /[!'()~]|%20/g; + var replace = { + '!': '%21', + '\'': '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+' + }; + var replacer = function (match) { + return replace[match]; + }; + var serialize = function (it) { + return encodeURIComponent(it).replace(find, replacer); + }; + var parseSearchParams = function (result, query) { + if (query) { + var attributes = query.split('&'); + var index = 0; + var attribute, + entry; + while (index < attributes.length) { + attribute = attributes[index++]; + if (attribute.length) { + entry = attribute.split('='); + result.push({ + key: deserialize(entry.shift()), + value: deserialize(entry.join('=')) + }); + } + } + } + }; + var updateSearchParams = function (query) { + this.entries.length = 0; + parseSearchParams(this.entries, query); + }; + var validateArgumentsLength = function (passed, required) { + if (passed < required) throw TypeError('Not enough arguments'); + }; + var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) { + setInternalState(this, { + type: URL_SEARCH_PARAMS_ITERATOR, + iterator: getIterator(getInternalParamsState(params).entries), + kind: kind + }); + }, 'Iterator', function next() { + var state = getInternalIteratorState(this); + var kind = state.kind; + var step = state.iterator.next(); + var entry = step.value; + if (!step.done) { + step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [ + entry.key, + entry.value + ]; + } + return step; + }); + // `URLSearchParams` constructor + // https://url.spec.whatwg.org/#interface-urlsearchparams + var URLSearchParamsConstructor = function URLSearchParams( /* init */ + ) { + anInstance(this, URLSearchParamsConstructor, URL_SEARCH_PARAMS); + var init = arguments.length > 0 ? arguments[0] : undefined; + var that = this; + var entries = [ + ]; + var iteratorMethod, + iterator, + next, + step, + entryIterator, + entryNext, + first, + second, + key; + setInternalState(that, { + type: URL_SEARCH_PARAMS, + entries: entries, + updateURL: function () { /* empty */ + }, + updateSearchParams: updateSearchParams + }); + if (init !== undefined) { + if (isObject(init)) { + iteratorMethod = getIteratorMethod(init); + if (typeof iteratorMethod === 'function') { + iterator = iteratorMethod.call(init); + next = iterator.next; + while (!(step = next.call(iterator)).done) { + entryIterator = getIterator(anObject(step.value)); + entryNext = entryIterator.next; + if ((first = entryNext.call(entryIterator)).done || (second = entryNext.call(entryIterator)).done || !entryNext.call(entryIterator).done) throw TypeError('Expected sequence with length 2'); + entries.push({ + key: first.value + '', + value: second.value + '' + }); + } + } else for (key in init) if (hasOwn(init, key)) entries.push({ + key: key, + value: init[key] + '' + }); + } else { + parseSearchParams(entries, typeof init === 'string' ? init.charAt(0) === '?' ? init.slice(1) : init : init + ''); + } + } + }; + var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype; + redefineAll(URLSearchParamsPrototype, { + // `URLSearchParams.prototype.appent` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-append + append: function append(name, value) { + validateArgumentsLength(arguments.length, 2); + var state = getInternalParamsState(this); + state.entries.push({ + key: name + '', + value: value + '' + }); + state.updateURL(); + }, + // `URLSearchParams.prototype.delete` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-delete + 'delete': function (name) { + validateArgumentsLength(arguments.length, 1); + var state = getInternalParamsState(this); + var entries = state.entries; + var key = name + ''; + var index = 0; + while (index < entries.length) { + if (entries[index].key === key) entries.splice(index, 1); + else index++; + } + state.updateURL(); + }, + // `URLSearchParams.prototype.get` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-get + get: function get(name) { + validateArgumentsLength(arguments.length, 1); + var entries = getInternalParamsState(this).entries; + var key = name + ''; + var index = 0; + for (; index < entries.length; index++) { + if (entries[index].key === key) return entries[index].value; + } + return null; + }, + // `URLSearchParams.prototype.getAll` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-getall + getAll: function getAll(name) { + validateArgumentsLength(arguments.length, 1); + var entries = getInternalParamsState(this).entries; + var key = name + ''; + var result = [ + ]; + var index = 0; + for (; index < entries.length; index++) { + if (entries[index].key === key) result.push(entries[index].value); + } + return result; + }, + // `URLSearchParams.prototype.has` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-has + has: function has(name) { + validateArgumentsLength(arguments.length, 1); + var entries = getInternalParamsState(this).entries; + var key = name + ''; + var index = 0; + while (index < entries.length) { + if (entries[index++].key === key) return true; + } + return false; + }, + // `URLSearchParams.prototype.set` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-set + set: function set(name, value) { + validateArgumentsLength(arguments.length, 1); + var state = getInternalParamsState(this); + var entries = state.entries; + var found = false; + var key = name + ''; + var val = value + ''; + var index = 0; + var entry; + for (; index < entries.length; index++) { + entry = entries[index]; + if (entry.key === key) { + if (found) entries.splice(index--, 1); + else { + found = true; + entry.value = val; + } + } + } + if (!found) entries.push({ + key: key, + value: val + }); + state.updateURL(); + }, + // `URLSearchParams.prototype.sort` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-sort + sort: function sort() { + var state = getInternalParamsState(this); + var entries = state.entries; + // Array#sort is not stable in some engines + var slice = entries.slice(); + var entry, + entriesIndex, + sliceIndex; + entries.length = 0; + for (sliceIndex = 0; sliceIndex < slice.length; sliceIndex++) { + entry = slice[sliceIndex]; + for (entriesIndex = 0; entriesIndex < sliceIndex; entriesIndex++) { + if (entries[entriesIndex].key > entry.key) { + entries.splice(entriesIndex, 0, entry); + break; + } + } + if (entriesIndex === sliceIndex) entries.push(entry); + } + state.updateURL(); + }, + // `URLSearchParams.prototype.forEach` method + forEach: function forEach(callback /* , thisArg */ ) { + var entries = getInternalParamsState(this).entries; + var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3); + var index = 0; + var entry; + while (index < entries.length) { + entry = entries[index++]; + boundFunction(entry.value, entry.key, this); + } + }, + // `URLSearchParams.prototype.keys` method + keys: function keys() { + return new URLSearchParamsIterator(this, 'keys'); + }, + // `URLSearchParams.prototype.values` method + values: function values() { + return new URLSearchParamsIterator(this, 'values'); + }, + // `URLSearchParams.prototype.entries` method + entries: function entries() { + return new URLSearchParamsIterator(this, 'entries'); + } + }, { + enumerable: true + }); + // `URLSearchParams.prototype[@@iterator]` method + redefine(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries); + // `URLSearchParams.prototype.toString` method + // https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior + redefine(URLSearchParamsPrototype, 'toString', function toString() { + var entries = getInternalParamsState(this).entries; + var result = [ + ]; + var index = 0; + var entry; + while (index < entries.length) { + entry = entries[index++]; + result.push(serialize(entry.key) + '=' + serialize(entry.value)); + } + return result.join('&'); + }, { + enumerable: true + }); + setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS); + $({ + global: true, + forced: !USE_NATIVE_URL + }, { + URLSearchParams: URLSearchParamsConstructor + }); + // Wrap `fetch` for correct work with polyfilled `URLSearchParams` + // https://github.com/zloirock/core-js/issues/674 + if (!USE_NATIVE_URL && typeof $fetch == 'function' && typeof Headers == 'function') { + $({ + global: true, + enumerable: true, + forced: true + }, { + fetch: function fetch(input /* , init */ ) { + var args = [ + input + ]; + var init, + body, + headers; + if (arguments.length > 1) { + init = arguments[1]; + if (isObject(init)) { + body = init.body; + if (classof(body) === URL_SEARCH_PARAMS) { + headers = init.headers ? new Headers(init.headers) : new Headers(); + if (!headers.has('content-type')) { + headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + init = create(init, { + body: createPropertyDescriptor(0, String(body)), + headers: createPropertyDescriptor(0, headers) + }); + } + } + args.push(init); + } + return $fetch.apply(this, args); + } + }); + } + module.exports = { + URLSearchParams: URLSearchParamsConstructor, + getState: getInternalParamsState + }; + }, + { + '../internals/an-instance': 27, + '../internals/an-object': 28, + '../internals/classof': 47, + '../internals/create-iterator-constructor': 55, + '../internals/create-property-descriptor': 57, + '../internals/export': 68, + '../internals/function-bind-context': 73, + '../internals/get-built-in': 75, + '../internals/get-iterator': 77, + '../internals/get-iterator-method': 76, + '../internals/has': 79, + '../internals/internal-state': 89, + '../internals/is-object': 93, + '../internals/native-url': 103, + '../internals/object-create': 109, + '../internals/redefine': 127, + '../internals/redefine-all': 126, + '../internals/set-to-string-tag': 136, + '../internals/well-known-symbol': 167, + '../modules/es.array.iterator': 182 + } + ], + 263: [ + function (_dereq_, module, exports) { + 'use strict'; + // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` + _dereq_('../modules/es.string.iterator'); + var $ = _dereq_('../internals/export'); + var DESCRIPTORS = _dereq_('../internals/descriptors'); + var USE_NATIVE_URL = _dereq_('../internals/native-url'); + var global = _dereq_('../internals/global'); + var defineProperties = _dereq_('../internals/object-define-properties'); + var redefine = _dereq_('../internals/redefine'); + var anInstance = _dereq_('../internals/an-instance'); + var has = _dereq_('../internals/has'); + var assign = _dereq_('../internals/object-assign'); + var arrayFrom = _dereq_('../internals/array-from'); + var codeAt = _dereq_('../internals/string-multibyte').codeAt; + var toASCII = _dereq_('../internals/string-punycode-to-ascii'); + var setToStringTag = _dereq_('../internals/set-to-string-tag'); + var URLSearchParamsModule = _dereq_('../modules/web.url-search-params'); + var InternalStateModule = _dereq_('../internals/internal-state'); + var NativeURL = global.URL; + var URLSearchParams = URLSearchParamsModule.URLSearchParams; + var getInternalSearchParamsState = URLSearchParamsModule.getState; + var setInternalState = InternalStateModule.set; + var getInternalURLState = InternalStateModule.getterFor('URL'); + var floor = Math.floor; + var pow = Math.pow; + var INVALID_AUTHORITY = 'Invalid authority'; + var INVALID_SCHEME = 'Invalid scheme'; + var INVALID_HOST = 'Invalid host'; + var INVALID_PORT = 'Invalid port'; + var ALPHA = /[A-Za-z]/; + var ALPHANUMERIC = /[\d+-.A-Za-z]/; + var DIGIT = /\d/; + var HEX_START = /^(0x|0X)/; + var OCT = /^[0-7]+$/; + var DEC = /^\d+$/; + var HEX = /^[\dA-Fa-f]+$/; + // eslint-disable-next-line no-control-regex + var FORBIDDEN_HOST_CODE_POINT = /[\u0000\u0009\u000A\u000D #%/:?@[\\]]/; + // eslint-disable-next-line no-control-regex + var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\u0000\u0009\u000A\u000D #/:?@[\\]]/; + // eslint-disable-next-line no-control-regex + var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g; + // eslint-disable-next-line no-control-regex + var TAB_AND_NEW_LINE = /[\u0009\u000A\u000D]/g; + var EOF; + var parseHost = function (url, input) { + var result, + codePoints, + index; + if (input.charAt(0) == '[') { + if (input.charAt(input.length - 1) != ']') return INVALID_HOST; + result = parseIPv6(input.slice(1, - 1)); + if (!result) return INVALID_HOST; + url.host = result; + // opaque host + } else if (!isSpecial(url)) { + if (FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT.test(input)) return INVALID_HOST; + result = ''; + codePoints = arrayFrom(input); + for (index = 0; index < codePoints.length; index++) { + result += percentEncode(codePoints[index], C0ControlPercentEncodeSet); + } + url.host = result; + } else { + input = toASCII(input); + if (FORBIDDEN_HOST_CODE_POINT.test(input)) return INVALID_HOST; + result = parseIPv4(input); + if (result === null) return INVALID_HOST; + url.host = result; + } + }; + var parseIPv4 = function (input) { + var parts = input.split('.'); + var partsLength, + numbers, + index, + part, + radix, + number, + ipv4; + if (parts.length && parts[parts.length - 1] == '') { + parts.pop(); + } + partsLength = parts.length; + if (partsLength > 4) return input; + numbers = [ + ]; + for (index = 0; index < partsLength; index++) { + part = parts[index]; + if (part == '') return input; + radix = 10; + if (part.length > 1 && part.charAt(0) == '0') { + radix = HEX_START.test(part) ? 16 : 8; + part = part.slice(radix == 8 ? 1 : 2); + } + if (part === '') { + number = 0; + } else { + if (!(radix == 10 ? DEC : radix == 8 ? OCT : HEX).test(part)) return input; + number = parseInt(part, radix); + } + numbers.push(number); + } + for (index = 0; index < partsLength; index++) { + number = numbers[index]; + if (index == partsLength - 1) { + if (number >= pow(256, 5 - partsLength)) return null; + } else if (number > 255) return null; + } + ipv4 = numbers.pop(); + for (index = 0; index < numbers.length; index++) { + ipv4 += numbers[index] * pow(256, 3 - index); + } + return ipv4; + }; + // eslint-disable-next-line max-statements + var parseIPv6 = function (input) { + var address = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]; + var pieceIndex = 0; + var compress = null; + var pointer = 0; + var value, + length, + numbersSeen, + ipv4Piece, + number, + swaps, + swap; + var char = function () { + return input.charAt(pointer); + }; + if (char() == ':') { + if (input.charAt(1) != ':') return; + pointer += 2; + pieceIndex++; + compress = pieceIndex; + } + while (char()) { + if (pieceIndex == 8) return; + if (char() == ':') { + if (compress !== null) return; + pointer++; + pieceIndex++; + compress = pieceIndex; + continue; + } + value = length = 0; + while (length < 4 && HEX.test(char())) { + value = value * 16 + parseInt(char(), 16); + pointer++; + length++; + } + if (char() == '.') { + if (length == 0) return; + pointer -= length; + if (pieceIndex > 6) return; + numbersSeen = 0; + while (char()) { + ipv4Piece = null; + if (numbersSeen > 0) { + if (char() == '.' && numbersSeen < 4) pointer++; + else return; + } + if (!DIGIT.test(char())) return; + while (DIGIT.test(char())) { + number = parseInt(char(), 10); + if (ipv4Piece === null) ipv4Piece = number; + else if (ipv4Piece == 0) return; + else ipv4Piece = ipv4Piece * 10 + number; + if (ipv4Piece > 255) return; + pointer++; + } + address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece; + numbersSeen++; + if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++; + } + if (numbersSeen != 4) return; + break; + } else if (char() == ':') { + pointer++; + if (!char()) return; + } else if (char()) return; + address[pieceIndex++] = value; + } + if (compress !== null) { + swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex != 0 && swaps > 0) { + swap = address[pieceIndex]; + address[pieceIndex--] = address[compress + swaps - 1]; + address[compress + --swaps] = swap; + } + } else if (pieceIndex != 8) return; + return address; + }; + var findLongestZeroSequence = function (ipv6) { + var maxIndex = null; + var maxLength = 1; + var currStart = null; + var currLength = 0; + var index = 0; + for (; index < 8; index++) { + if (ipv6[index] !== 0) { + if (currLength > maxLength) { + maxIndex = currStart; + maxLength = currLength; + } + currStart = null; + currLength = 0; + } else { + if (currStart === null) currStart = index; + ++currLength; + } + } + if (currLength > maxLength) { + maxIndex = currStart; + maxLength = currLength; + } + return maxIndex; + }; + var serializeHost = function (host) { + var result, + index, + compress, + ignore0; + // ipv4 + if (typeof host == 'number') { + result = [ + ]; + for (index = 0; index < 4; index++) { + result.unshift(host % 256); + host = floor(host / 256); + } + return result.join('.'); + // ipv6 + } else if (typeof host == 'object') { + result = ''; + compress = findLongestZeroSequence(host); + for (index = 0; index < 8; index++) { + if (ignore0 && host[index] === 0) continue; + if (ignore0) ignore0 = false; + if (compress === index) { + result += index ? ':' : '::'; + ignore0 = true; + } else { + result += host[index].toString(16); + if (index < 7) result += ':'; + } + } + return '[' + result + ']'; + } + return host; + }; + var C0ControlPercentEncodeSet = { + }; + var fragmentPercentEncodeSet = assign({ + }, C0ControlPercentEncodeSet, { + ' ': 1, + '"': 1, + '<': 1, + '>': 1, + '`': 1 + }); + var pathPercentEncodeSet = assign({ + }, fragmentPercentEncodeSet, { + '#': 1, + '?': 1, + '{': 1, + '}': 1 + }); + var userinfoPercentEncodeSet = assign({ + }, pathPercentEncodeSet, { + '/': 1, + ':': 1, + ';': 1, + '=': 1, + '@': 1, + '[': 1, + '\\': 1, + ']': 1, + '^': 1, + '|': 1 + }); + var percentEncode = function (char, set) { + var code = codeAt(char, 0); + return code > 32 && code < 127 && !has(set, char) ? char : encodeURIComponent(char); + }; + var specialSchemes = { + ftp: 21, + file: null, + http: 80, + https: 443, + ws: 80, + wss: 443 + }; + var isSpecial = function (url) { + return has(specialSchemes, url.scheme); + }; + var includesCredentials = function (url) { + return url.username != '' || url.password != ''; + }; + var cannotHaveUsernamePasswordPort = function (url) { + return !url.host || url.cannotBeABaseURL || url.scheme == 'file'; + }; + var isWindowsDriveLetter = function (string, normalized) { + var second; + return string.length == 2 && ALPHA.test(string.charAt(0)) && ((second = string.charAt(1)) == ':' || !normalized && second == '|'); + }; + var startsWithWindowsDriveLetter = function (string) { + var third; + return string.length > 1 && isWindowsDriveLetter(string.slice(0, 2)) && (string.length == 2 || (third = string.charAt(2)) === '/' || third === '\\' || third === '?' || third === '#'); + }; + var shortenURLsPath = function (url) { + var path = url.path; + var pathSize = path.length; + if (pathSize && (url.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) { + path.pop(); + } + }; + var isSingleDot = function (segment) { + return segment === '.' || segment.toLowerCase() === '%2e'; + }; + var isDoubleDot = function (segment) { + segment = segment.toLowerCase(); + return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e'; + }; + // States: + var SCHEME_START = { + }; + var SCHEME = { + }; + var NO_SCHEME = { + }; + var SPECIAL_RELATIVE_OR_AUTHORITY = { + }; + var PATH_OR_AUTHORITY = { + }; + var RELATIVE = { + }; + var RELATIVE_SLASH = { + }; + var SPECIAL_AUTHORITY_SLASHES = { + }; + var SPECIAL_AUTHORITY_IGNORE_SLASHES = { + }; + var AUTHORITY = { + }; + var HOST = { + }; + var HOSTNAME = { + }; + var PORT = { + }; + var FILE = { + }; + var FILE_SLASH = { + }; + var FILE_HOST = { + }; + var PATH_START = { + }; + var PATH = { + }; + var CANNOT_BE_A_BASE_URL_PATH = { + }; + var QUERY = { + }; + var FRAGMENT = { + }; + // eslint-disable-next-line max-statements + var parseURL = function (url, input, stateOverride, base) { + var state = stateOverride || SCHEME_START; + var pointer = 0; + var buffer = ''; + var seenAt = false; + var seenBracket = false; + var seenPasswordToken = false; + var codePoints, + char, + bufferCodePoints, + failure; + if (!stateOverride) { + url.scheme = ''; + url.username = ''; + url.password = ''; + url.host = null; + url.port = null; + url.path = [ + ]; + url.query = null; + url.fragment = null; + url.cannotBeABaseURL = false; + input = input.replace(LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, ''); + } + input = input.replace(TAB_AND_NEW_LINE, ''); + codePoints = arrayFrom(input); + while (pointer <= codePoints.length) { + char = codePoints[pointer]; + switch (state) { + case SCHEME_START: + if (char && ALPHA.test(char)) { + buffer += char.toLowerCase(); + state = SCHEME; + } else if (!stateOverride) { + state = NO_SCHEME; + continue; + } else return INVALID_SCHEME; + break; + case SCHEME: + if (char && (ALPHANUMERIC.test(char) || char == '+' || char == '-' || char == '.')) { + buffer += char.toLowerCase(); + } else if (char == ':') { + if (stateOverride && (isSpecial(url) != has(specialSchemes, buffer) || buffer == 'file' && (includesCredentials(url) || url.port !== null) || url.scheme == 'file' && !url.host)) return; + url.scheme = buffer; + if (stateOverride) { + if (isSpecial(url) && specialSchemes[url.scheme] == url.port) url.port = null; + return; + } + buffer = ''; + if (url.scheme == 'file') { + state = FILE; + } else if (isSpecial(url) && base && base.scheme == url.scheme) { + state = SPECIAL_RELATIVE_OR_AUTHORITY; + } else if (isSpecial(url)) { + state = SPECIAL_AUTHORITY_SLASHES; + } else if (codePoints[pointer + 1] == '/') { + state = PATH_OR_AUTHORITY; + pointer++; + } else { + url.cannotBeABaseURL = true; + url.path.push(''); + state = CANNOT_BE_A_BASE_URL_PATH; + } + } else if (!stateOverride) { + buffer = ''; + state = NO_SCHEME; + pointer = 0; + continue; + } else return INVALID_SCHEME; + break; + case NO_SCHEME: + if (!base || base.cannotBeABaseURL && char != '#') return INVALID_SCHEME; + if (base.cannotBeABaseURL && char == '#') { + url.scheme = base.scheme; + url.path = base.path.slice(); + url.query = base.query; + url.fragment = ''; + url.cannotBeABaseURL = true; + state = FRAGMENT; + break; + } + state = base.scheme == 'file' ? FILE : RELATIVE; + continue; + case SPECIAL_RELATIVE_OR_AUTHORITY: + if (char == '/' && codePoints[pointer + 1] == '/') { + state = SPECIAL_AUTHORITY_IGNORE_SLASHES; + pointer++; + } else { + state = RELATIVE; + continue; + } + break; + case PATH_OR_AUTHORITY: + if (char == '/') { + state = AUTHORITY; + break; + } else { + state = PATH; + continue; + } + case RELATIVE: + url.scheme = base.scheme; + if (char == EOF) { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + url.path = base.path.slice(); + url.query = base.query; + } else if (char == '/' || char == '\\' && isSpecial(url)) { + state = RELATIVE_SLASH; + } else if (char == '?') { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + url.path = base.path.slice(); + url.query = ''; + state = QUERY; + } else if (char == '#') { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + url.path = base.path.slice(); + url.query = base.query; + url.fragment = ''; + state = FRAGMENT; + } else { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + url.path = base.path.slice(); + url.path.pop(); + state = PATH; + continue; + } + break; + case RELATIVE_SLASH: + if (isSpecial(url) && (char == '/' || char == '\\')) { + state = SPECIAL_AUTHORITY_IGNORE_SLASHES; + } else if (char == '/') { + state = AUTHORITY; + } else { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + state = PATH; + continue; + } + break; + case SPECIAL_AUTHORITY_SLASHES: + state = SPECIAL_AUTHORITY_IGNORE_SLASHES; + if (char != '/' || buffer.charAt(pointer + 1) != '/') continue; + pointer++; + break; + case SPECIAL_AUTHORITY_IGNORE_SLASHES: + if (char != '/' && char != '\\') { + state = AUTHORITY; + continue; + } + break; + case AUTHORITY: + if (char == '@') { + if (seenAt) buffer = '%40' + buffer; + seenAt = true; + bufferCodePoints = arrayFrom(buffer); + for (var i = 0; i < bufferCodePoints.length; i++) { + var codePoint = bufferCodePoints[i]; + if (codePoint == ':' && !seenPasswordToken) { + seenPasswordToken = true; + continue; + } + var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet); + if (seenPasswordToken) url.password += encodedCodePoints; + else url.username += encodedCodePoints; + } + buffer = ''; + } else if (char == EOF || char == '/' || char == '?' || char == '#' || char == '\\' && isSpecial(url)) { + if (seenAt && buffer == '') return INVALID_AUTHORITY; + pointer -= arrayFrom(buffer).length + 1; + buffer = ''; + state = HOST; + } else buffer += char; + break; + case HOST: + case HOSTNAME: + if (stateOverride && url.scheme == 'file') { + state = FILE_HOST; + continue; + } else if (char == ':' && !seenBracket) { + if (buffer == '') return INVALID_HOST; + failure = parseHost(url, buffer); + if (failure) return failure; + buffer = ''; + state = PORT; + if (stateOverride == HOSTNAME) return; + } else if (char == EOF || char == '/' || char == '?' || char == '#' || char == '\\' && isSpecial(url)) { + if (isSpecial(url) && buffer == '') return INVALID_HOST; + if (stateOverride && buffer == '' && (includesCredentials(url) || url.port !== null)) return; + failure = parseHost(url, buffer); + if (failure) return failure; + buffer = ''; + state = PATH_START; + if (stateOverride) return; + continue; + } else { + if (char == '[') seenBracket = true; + else if (char == ']') seenBracket = false; + buffer += char; + } + break; + case PORT: + if (DIGIT.test(char)) { + buffer += char; + } else if (char == EOF || char == '/' || char == '?' || char == '#' || char == '\\' && isSpecial(url) || stateOverride) { + if (buffer != '') { + var port = parseInt(buffer, 10); + if (port > 65535) return INVALID_PORT; + url.port = isSpecial(url) && port === specialSchemes[url.scheme] ? null : port; + buffer = ''; + } + if (stateOverride) return; + state = PATH_START; + continue; + } else return INVALID_PORT; + break; + case FILE: + url.scheme = 'file'; + if (char == '/' || char == '\\') state = FILE_SLASH; + else if (base && base.scheme == 'file') { + if (char == EOF) { + url.host = base.host; + url.path = base.path.slice(); + url.query = base.query; + } else if (char == '?') { + url.host = base.host; + url.path = base.path.slice(); + url.query = ''; + state = QUERY; + } else if (char == '#') { + url.host = base.host; + url.path = base.path.slice(); + url.query = base.query; + url.fragment = ''; + state = FRAGMENT; + } else { + if (!startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { + url.host = base.host; + url.path = base.path.slice(); + shortenURLsPath(url); + } + state = PATH; + continue; + } + } else { + state = PATH; + continue; + } + break; + case FILE_SLASH: + if (char == '/' || char == '\\') { + state = FILE_HOST; + break; + } + if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { + if (isWindowsDriveLetter(base.path[0], true)) url.path.push(base.path[0]); + else url.host = base.host; + } + state = PATH; + continue; + case FILE_HOST: + if (char == EOF || char == '/' || char == '\\' || char == '?' || char == '#') { + if (!stateOverride && isWindowsDriveLetter(buffer)) { + state = PATH; + } else if (buffer == '') { + url.host = ''; + if (stateOverride) return; + state = PATH_START; + } else { + failure = parseHost(url, buffer); + if (failure) return failure; + if (url.host == 'localhost') url.host = ''; + if (stateOverride) return; + buffer = ''; + state = PATH_START; + } + continue; + } else buffer += char; + break; + case PATH_START: + if (isSpecial(url)) { + state = PATH; + if (char != '/' && char != '\\') continue; + } else if (!stateOverride && char == '?') { + url.query = ''; + state = QUERY; + } else if (!stateOverride && char == '#') { + url.fragment = ''; + state = FRAGMENT; + } else if (char != EOF) { + state = PATH; + if (char != '/') continue; + } + break; + case PATH: + if (char == EOF || char == '/' || char == '\\' && isSpecial(url) || !stateOverride && (char == '?' || char == '#')) { + if (isDoubleDot(buffer)) { + shortenURLsPath(url); + if (char != '/' && !(char == '\\' && isSpecial(url))) { + url.path.push(''); + } + } else if (isSingleDot(buffer)) { + if (char != '/' && !(char == '\\' && isSpecial(url))) { + url.path.push(''); + } + } else { + if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) { + if (url.host) url.host = ''; + buffer = buffer.charAt(0) + ':'; // normalize windows drive letter + } + url.path.push(buffer); + } + buffer = ''; + if (url.scheme == 'file' && (char == EOF || char == '?' || char == '#')) { + while (url.path.length > 1 && url.path[0] === '') { + url.path.shift(); + } + } + if (char == '?') { + url.query = ''; + state = QUERY; + } else if (char == '#') { + url.fragment = ''; + state = FRAGMENT; + } + } else { + buffer += percentEncode(char, pathPercentEncodeSet); + } + break; + case CANNOT_BE_A_BASE_URL_PATH: + if (char == '?') { + url.query = ''; + state = QUERY; + } else if (char == '#') { + url.fragment = ''; + state = FRAGMENT; + } else if (char != EOF) { + url.path[0] += percentEncode(char, C0ControlPercentEncodeSet); + } + break; + case QUERY: + if (!stateOverride && char == '#') { + url.fragment = ''; + state = FRAGMENT; + } else if (char != EOF) { + if (char == '\'' && isSpecial(url)) url.query += '%27'; + else if (char == '#') url.query += '%23'; + else url.query += percentEncode(char, C0ControlPercentEncodeSet); + } + break; + case FRAGMENT: + if (char != EOF) url.fragment += percentEncode(char, fragmentPercentEncodeSet); + break; + } + pointer++; + } + }; + // `URL` constructor + // https://url.spec.whatwg.org/#url-class + var URLConstructor = function URL(url /* , base */ ) { + var that = anInstance(this, URLConstructor, 'URL'); + var base = arguments.length > 1 ? arguments[1] : undefined; + var urlString = String(url); + var state = setInternalState(that, { + type: 'URL' + }); + var baseState, + failure; + if (base !== undefined) { + if (base instanceof URLConstructor) baseState = getInternalURLState(base); + else { + failure = parseURL(baseState = { + }, String(base)); + if (failure) throw TypeError(failure); + } + } + failure = parseURL(state, urlString, null, baseState); + if (failure) throw TypeError(failure); + var searchParams = state.searchParams = new URLSearchParams(); + var searchParamsState = getInternalSearchParamsState(searchParams); + searchParamsState.updateSearchParams(state.query); + searchParamsState.updateURL = function () { + state.query = String(searchParams) || null; + }; + if (!DESCRIPTORS) { + that.href = serializeURL.call(that); + that.origin = getOrigin.call(that); + that.protocol = getProtocol.call(that); + that.username = getUsername.call(that); + that.password = getPassword.call(that); + that.host = getHost.call(that); + that.hostname = getHostname.call(that); + that.port = getPort.call(that); + that.pathname = getPathname.call(that); + that.search = getSearch.call(that); + that.searchParams = getSearchParams.call(that); + that.hash = getHash.call(that); + } + }; + var URLPrototype = URLConstructor.prototype; + var serializeURL = function () { + var url = getInternalURLState(this); + var scheme = url.scheme; + var username = url.username; + var password = url.password; + var host = url.host; + var port = url.port; + var path = url.path; + var query = url.query; + var fragment = url.fragment; + var output = scheme + ':'; + if (host !== null) { + output += '//'; + if (includesCredentials(url)) { + output += username + (password ? ':' + password : '') + '@'; + } + output += serializeHost(host); + if (port !== null) output += ':' + port; + } else if (scheme == 'file') output += '//'; + output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; + if (query !== null) output += '?' + query; + if (fragment !== null) output += '#' + fragment; + return output; + }; + var getOrigin = function () { + var url = getInternalURLState(this); + var scheme = url.scheme; + var port = url.port; + if (scheme == 'blob') try { + return new URL(scheme.path[0]).origin; + } catch (error) { + return 'null'; + } + if (scheme == 'file' || !isSpecial(url)) return 'null'; + return scheme + '://' + serializeHost(url.host) + (port !== null ? ':' + port : ''); + }; + var getProtocol = function () { + return getInternalURLState(this).scheme + ':'; + }; + var getUsername = function () { + return getInternalURLState(this).username; + }; + var getPassword = function () { + return getInternalURLState(this).password; + }; + var getHost = function () { + var url = getInternalURLState(this); + var host = url.host; + var port = url.port; + return host === null ? '' : port === null ? serializeHost(host) : serializeHost(host) + ':' + port; + }; + var getHostname = function () { + var host = getInternalURLState(this).host; + return host === null ? '' : serializeHost(host); + }; + var getPort = function () { + var port = getInternalURLState(this).port; + return port === null ? '' : String(port); + }; + var getPathname = function () { + var url = getInternalURLState(this); + var path = url.path; + return url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; + }; + var getSearch = function () { + var query = getInternalURLState(this).query; + return query ? '?' + query : ''; + }; + var getSearchParams = function () { + return getInternalURLState(this).searchParams; + }; + var getHash = function () { + var fragment = getInternalURLState(this).fragment; + return fragment ? '#' + fragment : ''; + }; + var accessorDescriptor = function (getter, setter) { + return { + get: getter, + set: setter, + configurable: true, + enumerable: true + }; + }; + if (DESCRIPTORS) { + defineProperties(URLPrototype, { + // `URL.prototype.href` accessors pair + // https://url.spec.whatwg.org/#dom-url-href + href: accessorDescriptor(serializeURL, function (href) { + var url = getInternalURLState(this); + var urlString = String(href); + var failure = parseURL(url, urlString); + if (failure) throw TypeError(failure); + getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); + }), + // `URL.prototype.origin` getter + // https://url.spec.whatwg.org/#dom-url-origin + origin: accessorDescriptor(getOrigin), + // `URL.prototype.protocol` accessors pair + // https://url.spec.whatwg.org/#dom-url-protocol + protocol: accessorDescriptor(getProtocol, function (protocol) { + var url = getInternalURLState(this); + parseURL(url, String(protocol) + ':', SCHEME_START); + }), + // `URL.prototype.username` accessors pair + // https://url.spec.whatwg.org/#dom-url-username + username: accessorDescriptor(getUsername, function (username) { + var url = getInternalURLState(this); + var codePoints = arrayFrom(String(username)); + if (cannotHaveUsernamePasswordPort(url)) return; + url.username = ''; + for (var i = 0; i < codePoints.length; i++) { + url.username += percentEncode(codePoints[i], userinfoPercentEncodeSet); + } + }), + // `URL.prototype.password` accessors pair + // https://url.spec.whatwg.org/#dom-url-password + password: accessorDescriptor(getPassword, function (password) { + var url = getInternalURLState(this); + var codePoints = arrayFrom(String(password)); + if (cannotHaveUsernamePasswordPort(url)) return; + url.password = ''; + for (var i = 0; i < codePoints.length; i++) { + url.password += percentEncode(codePoints[i], userinfoPercentEncodeSet); + } + }), + // `URL.prototype.host` accessors pair + // https://url.spec.whatwg.org/#dom-url-host + host: accessorDescriptor(getHost, function (host) { + var url = getInternalURLState(this); + if (url.cannotBeABaseURL) return; + parseURL(url, String(host), HOST); + }), + // `URL.prototype.hostname` accessors pair + // https://url.spec.whatwg.org/#dom-url-hostname + hostname: accessorDescriptor(getHostname, function (hostname) { + var url = getInternalURLState(this); + if (url.cannotBeABaseURL) return; + parseURL(url, String(hostname), HOSTNAME); + }), + // `URL.prototype.port` accessors pair + // https://url.spec.whatwg.org/#dom-url-port + port: accessorDescriptor(getPort, function (port) { + var url = getInternalURLState(this); + if (cannotHaveUsernamePasswordPort(url)) return; + port = String(port); + if (port == '') url.port = null; + else parseURL(url, port, PORT); + }), + // `URL.prototype.pathname` accessors pair + // https://url.spec.whatwg.org/#dom-url-pathname + pathname: accessorDescriptor(getPathname, function (pathname) { + var url = getInternalURLState(this); + if (url.cannotBeABaseURL) return; + url.path = [ + ]; + parseURL(url, pathname + '', PATH_START); + }), + // `URL.prototype.search` accessors pair + // https://url.spec.whatwg.org/#dom-url-search + search: accessorDescriptor(getSearch, function (search) { + var url = getInternalURLState(this); + search = String(search); + if (search == '') { + url.query = null; + } else { + if ('?' == search.charAt(0)) search = search.slice(1); + url.query = ''; + parseURL(url, search, QUERY); + } + getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); + }), + // `URL.prototype.searchParams` getter + // https://url.spec.whatwg.org/#dom-url-searchparams + searchParams: accessorDescriptor(getSearchParams), + // `URL.prototype.hash` accessors pair + // https://url.spec.whatwg.org/#dom-url-hash + hash: accessorDescriptor(getHash, function (hash) { + var url = getInternalURLState(this); + hash = String(hash); + if (hash == '') { + url.fragment = null; + return; + } + if ('#' == hash.charAt(0)) hash = hash.slice(1); + url.fragment = ''; + parseURL(url, hash, FRAGMENT); + }) + }); + } // `URL.prototype.toJSON` method + // https://url.spec.whatwg.org/#dom-url-tojson + + redefine(URLPrototype, 'toJSON', function toJSON() { + return serializeURL.call(this); + }, { + enumerable: true + }); + // `URL.prototype.toString` method + // https://url.spec.whatwg.org/#URL-stringification-behavior + redefine(URLPrototype, 'toString', function toString() { + return serializeURL.call(this); + }, { + enumerable: true + }); + if (NativeURL) { + var nativeCreateObjectURL = NativeURL.createObjectURL; + var nativeRevokeObjectURL = NativeURL.revokeObjectURL; + // `URL.createObjectURL` method + // https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL + // eslint-disable-next-line no-unused-vars + if (nativeCreateObjectURL) redefine(URLConstructor, 'createObjectURL', function createObjectURL(blob) { + return nativeCreateObjectURL.apply(NativeURL, arguments); + }); + // `URL.revokeObjectURL` method + // https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL + // eslint-disable-next-line no-unused-vars + if (nativeRevokeObjectURL) redefine(URLConstructor, 'revokeObjectURL', function revokeObjectURL(url) { + return nativeRevokeObjectURL.apply(NativeURL, arguments); + }); + } + setToStringTag(URLConstructor, 'URL'); + $({ + global: true, + forced: !USE_NATIVE_URL, + sham: !DESCRIPTORS + }, { + URL: URLConstructor + }); + }, + { + '../internals/an-instance': 27, + '../internals/array-from': 35, + '../internals/descriptors': 61, + '../internals/export': 68, + '../internals/global': 78, + '../internals/has': 79, + '../internals/internal-state': 89, + '../internals/native-url': 103, + '../internals/object-assign': 108, + '../internals/object-define-properties': 110, + '../internals/redefine': 127, + '../internals/set-to-string-tag': 136, + '../internals/string-multibyte': 142, + '../internals/string-punycode-to-ascii': 145, + '../modules/es.string.iterator': 215, + '../modules/web.url-search-params': 262 + } + ], + 264: [ + function (_dereq_, module, exports) { + // This file can be required in Browserify and Node.js for automatic polyfill + // To use it: require('es6-promise/auto'); + 'use strict'; + module.exports = _dereq_('./').polyfill(); + }, + { + './': 265 + } + ], + 265: [ + function (_dereq_, module, exports) { + (function (process, global) { + /*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version v4.2.8+1e68dce6 + */ + (function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.ES6Promise = factory(); + }) (this, function () { + 'use strict'; + function objectOrFunction(x) { + var type = typeof x; + return x !== null && (type === 'object' || type === 'function'); + } + function isFunction(x) { + return typeof x === 'function'; + } + var _isArray = void 0; + if (Array.isArray) { + _isArray = Array.isArray; + } else { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } + var isArray = _isArray; + var len = 0; + var vertxNext = void 0; + var customSchedulerFn = void 0; + var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } + }; + function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; + } + function setAsap(asapFn) { + asap = asapFn; + } + var browserWindow = typeof window !== 'undefined' ? window : undefined; + var browserGlobal = browserWindow || { + }; + var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; + var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && { + }.toString.call(process) === '[object process]'; + // test for web worker but not in IE10 + var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + // node + function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function () { + return process.nextTick(flush); + }; + } // vertx + + function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } + return useSetTimeout(); + } + function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { + characterData: true + }); + return function () { + node.data = iterations = ++iterations % 2; + }; + } // web worker + + function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; + } + function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function () { + return globalSetTimeout(flush, 1); + }; + } + var queue = new Array(1000); + function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + callback(arg); + queue[i] = undefined; + queue[i + 1] = undefined; + } + len = 0; + } + function attemptVertx() { + try { + var vertx = Function('return this') ().require('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } + } + var scheduleFlush = void 0; + // Decide what async method to use to triggering processing of queued callbacks: + if (isNode) { + scheduleFlush = useNextTick(); + } else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); + } else if (isWorker) { + scheduleFlush = useMessageChannel(); + } else if (browserWindow === undefined && typeof _dereq_ === 'function') { + scheduleFlush = attemptVertx(); + } else { + scheduleFlush = useSetTimeout(); + } + function then(onFulfillment, onRejection) { + var parent = this; + var child = new this.constructor(noop); + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + var _state = parent._state; + if (_state) { + var callback = arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + return child; + } /** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` + */ + + function resolve$1(object) { + /*jshint validthis:true */ + var Constructor = this; + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + var promise = new Constructor(noop); + resolve(promise, object); + return promise; + } + var PROMISE_ID = Math.random().toString(36).substring(2); + function noop() { + } + var PENDING = void 0; + var FULFILLED = 1; + var REJECTED = 2; + function selfFulfillment() { + return new TypeError('You cannot resolve a promise with itself'); + } + function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { + try { + then$$1.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } + } + function handleForeignThenable(promise, thenable, then$$1) { + asap(function (promise) { + var sealed = false; + var error = tryThen(then$$1, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + if (!sealed && error) { + sealed = true; + reject(promise, error); + } + }, promise); + } + function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + return resolve(promise, value); + }, function (reason) { + return reject(promise, reason); + }); + } + } + function handleMaybeThenable(promise, maybeThenable, then$$1) { + if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$1 === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$1)) { + handleForeignThenable(promise, maybeThenable, then$$1); + } else { + fulfill(promise, maybeThenable); + } + } + } + function resolve(promise, value) { + if (promise === value) { + reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + var then$$1 = void 0; + try { + then$$1 = value.then; + } catch (error) { + reject(promise, error); + return; + } + handleMaybeThenable(promise, value, then$$1); + } else { + fulfill(promise, value); + } + } + function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + publish(promise); + } + function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + promise._result = value; + promise._state = FULFILLED; + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } + } + function reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + asap(publishRejection, promise); + } + function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; + parent._onerror = null; + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + if (length === 0 && parent._state) { + asap(publish, parent); + } + } + function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + if (subscribers.length === 0) { + return; + } + var child = void 0, + callback = void 0, + detail = promise._result; + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + promise._subscribers.length = 0; + } + function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = void 0, + error = void 0, + succeeded = true; + if (hasCallback) { + try { + value = callback(detail); + } catch (e) { + succeeded = false; + error = e; + } + if (promise === value) { + reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + } + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (succeeded === false) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } + } + function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + resolve(promise, value); + }, function rejectPromise(reason) { + reject(promise, reason); + }); + } catch (e) { + reject(promise, e); + } + } + var id = 0; + function nextId() { + return id++; + } + function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = [ + ]; + } + function validationError() { + return new Error('Array Methods must be provided an Array'); + } + var Enumerator = function () { + function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + if (isArray(input)) { + this.length = input.length; + this._remaining = input.length; + this._result = new Array(this.length); + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(input); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + reject(this.promise, validationError()); + } + } + Enumerator.prototype._enumerate = function _enumerate(input) { + for (var i = 0; this._state === PENDING && i < input.length; i++) { + this._eachEntry(input[i], i); + } + }; + Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { + var c = this._instanceConstructor; + var resolve$$1 = c.resolve; + if (resolve$$1 === resolve$1) { + var _then = void 0; + var error = void 0; + var didError = false; + try { + _then = entry.then; + } catch (e) { + didError = true; + error = e; + } + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise$1) { + var promise = new c(noop); + if (didError) { + reject(promise, error); + } else { + handleMaybeThenable(promise, entry, _then); + } + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$1) { + return resolve$$1(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$1(entry), i); + } + }; + Enumerator.prototype._settledAt = function _settledAt(state, i, value) { + var promise = this.promise; + if (promise._state === PENDING) { + this._remaining--; + if (state === REJECTED) { + reject(promise, value); + } else { + this._result[i] = value; + } + } + if (this._remaining === 0) { + fulfill(promise, this._result); + } + }; + Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { + var enumerator = this; + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); + }; + return Enumerator; + }(); + /** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static + */ + function all(entries) { + return new Enumerator(this, entries).promise; + } /** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. + */ + + function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + if (!isArray(entries)) { + return new Constructor(function (_, reject) { + return reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function (resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } + } /** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. + */ + + function reject$1(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + reject(promise, reason); + return promise; + } + function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + function needsNew() { + throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); + } /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {Function} resolver + Useful for tooling. + @constructor + */ + + var Promise$1 = function () { + function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = [ + ]; + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } + } /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + Chaining + -------- + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + Assimilation + ------------ + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + If the assimliated promise rejects, then the downstream promise will also reject. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + Simple Example + -------------- + Synchronous Example + ```javascript + let result; + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + Promise Example; + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + Advanced Example + -------------- + Synchronous Example + ```javascript + let author, books; + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + function foundBooks(books) { + } + function failure(reason) { + } + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + Promise Example; + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + + Promise.prototype.catch = function _catch(onRejection) { + return this.then(null, onRejection); + }; + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + Synchronous example: + + ```js + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); + } + + try { + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuther(); + } finally { + // always runs + // doesn't affect the return value + } + ``` + + Asynchronous example: + + ```js + findAuthor().catch(function(reason){ + return findOtherAuther(); + }).finally(function(){ + // author was either found, or not + }); + ``` + + @method finally + @param {Function} callback + @return {Promise} + */ + Promise.prototype.finally = function _finally(callback) { + var promise = this; + var constructor = promise.constructor; + if (isFunction(callback)) { + return promise.then(function (value) { + return constructor.resolve(callback()).then(function () { + return value; + }); + }, function (reason) { + return constructor.resolve(callback()).then(function () { + throw reason; + }); + }); + } + return promise.then(callback, callback); + }; + return Promise; + }(); + Promise$1.prototype.then = then; + Promise$1.all = all; + Promise$1.race = race; + Promise$1.resolve = resolve$1; + Promise$1.reject = reject$1; + Promise$1._setScheduler = setScheduler; + Promise$1._setAsap = setAsap; + Promise$1._asap = asap; + /*global self*/ + function polyfill() { + var local = void 0; + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this') (); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + var P = local.Promise; + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } + local.Promise = Promise$1; + } // Strange compat.. + + Promise$1.polyfill = polyfill; + Promise$1.Promise = Promise$1; + return Promise$1; + }); + }).call(this, _dereq_('_process'), typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : { + }) + }, + { + '_process': 278 + } + ], + 266: [ + function (_dereq_, module, exports) { + (function (global, factory) { + if (typeof define === 'function' && define.amd) { + define(['exports', + 'module'], factory); + } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') { + factory(exports, module); + } else { + var mod = { + exports: { + } + }; + factory(mod.exports, mod); + global.fetchJsonp = mod.exports; + } + }) (this, function (exports, module) { + 'use strict'; + var defaultOptions = { + timeout: 5000, + jsonpCallback: 'callback', + jsonpCallbackFunction: null + }; + function generateCallbackFunction() { + return 'jsonp_' + Date.now() + '_' + Math.ceil(Math.random() * 100000); + } + function clearFunction(functionName) { + // IE8 throws an exception when you try to delete a property on window + // http://stackoverflow.com/a/1824228/751089 + try { + delete window[functionName]; + } catch (e) { + window[functionName] = undefined; + } + } + function removeScript(scriptId) { + var script = document.getElementById(scriptId); + if (script) { + document.getElementsByTagName('head') [0].removeChild(script); + } + } + function fetchJsonp(_url) { + var options = arguments.length <= 1 || arguments[1] === undefined ? { + } + : arguments[1]; + // to avoid param reassign + var url = _url; + var timeout = options.timeout || defaultOptions.timeout; + var jsonpCallback = options.jsonpCallback || defaultOptions.jsonpCallback; + var timeoutId = undefined; + return new Promise(function (resolve, reject) { + var callbackFunction = options.jsonpCallbackFunction || generateCallbackFunction(); + var scriptId = jsonpCallback + '_' + callbackFunction; + window[callbackFunction] = function (response) { + resolve({ + ok: true, + // keep consistent with fetch API + json: function json() { + return Promise.resolve(response); + } + }); + if (timeoutId) clearTimeout(timeoutId); + removeScript(scriptId); + clearFunction(callbackFunction); + }; + // Check if the user set their own params, and if not add a ? to start a list of params + url += url.indexOf('?') === - 1 ? '?' : '&'; + var jsonpScript = document.createElement('script'); + jsonpScript.setAttribute('src', '' + url + jsonpCallback + '=' + callbackFunction); + if (options.charset) { + jsonpScript.setAttribute('charset', options.charset); + } + jsonpScript.id = scriptId; + document.getElementsByTagName('head') [0].appendChild(jsonpScript); + timeoutId = setTimeout(function () { + reject(new Error('JSONP request to ' + _url + ' timed out')); + clearFunction(callbackFunction); + removeScript(scriptId); + window[callbackFunction] = function () { + clearFunction(callbackFunction); + }; + }, timeout); + // Caught if got 404/500 + jsonpScript.onerror = function () { + reject(new Error('JSONP request to ' + _url + ' failed')); + clearFunction(callbackFunction); + removeScript(scriptId); + if (timeoutId) clearTimeout(timeoutId); + }; + }); + } // export as global function + /* + let local; + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + local.fetchJsonp = fetchJsonp; + */ + + module.exports = fetchJsonp; + }); + }, + { + } + ], + 267: [ + function (_dereq_, module, exports) { + /* FileSaver.js + * A saveAs() FileSaver implementation. + * 1.3.2 + * 2016-06-16 18:25:19 + * + * By Eli Grey, http://eligrey.com + * License: MIT + * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md + */ + /*global self */ + /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ + /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ + var saveAs = saveAs || function (view) { + 'use strict'; + // IE <10 is explicitly unsupported + if (typeof view === 'undefined' || typeof navigator !== 'undefined' && /MSIE [1-9]\./.test(navigator.userAgent)) { + return; + } + var doc = view.document // only get URL when necessary in case Blob.js hasn't overridden it yet + , + get_URL = function () { + return view.URL || view.webkitURL || view; + }, + save_link = doc.createElementNS('http://www.w3.org/1999/xhtml', 'a'), + can_use_save_link = ('download' in save_link), + click = function (node) { + var event = new MouseEvent('click'); + node.dispatchEvent(event); + }, + is_safari = /constructor/i.test(view.HTMLElement) || view.safari, + is_chrome_ios = /CriOS\/[\d]+/.test(navigator.userAgent), + throw_outside = function (ex) { + (view.setImmediate || view.setTimeout) (function () { + throw ex; + }, 0); + }, + force_saveable_type = 'application/octet-stream' // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to + , + arbitrary_revoke_timeout = 1000 * 40 // in ms + , + revoke = function (file) { + var revoker = function () { + if (typeof file === 'string') { + // file is an object URL + get_URL().revokeObjectURL(file); + } else { + // file is a File + file.remove(); + } + }; + setTimeout(revoker, arbitrary_revoke_timeout); + }, + dispatch = function (filesaver, event_types, event) { + event_types = [ + ].concat(event_types); + var i = event_types.length; + while (i--) { + var listener = filesaver['on' + event_types[i]]; + if (typeof listener === 'function') { + try { + listener.call(filesaver, event || filesaver); + } catch (ex) { + throw_outside(ex); + } + } + } + }, + auto_bom = function (blob) { + // prepend BOM for UTF-8 XML and text/* types (including HTML) + // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF + if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { + return new Blob([String.fromCharCode(65279), + blob], { + type: blob.type + }); + } + return blob; + }, + FileSaver = function (blob, name, no_auto_bom) { + if (!no_auto_bom) { + blob = auto_bom(blob); + } // First try a.download, then web filesystem, then object URLs + + var filesaver = this, + type = blob.type, + force = type === force_saveable_type, + object_url, + dispatch_all = function () { + dispatch(filesaver, 'writestart progress write writeend'.split(' ')); + } // on any filesys errors revert to saving with object URLs + , + fs_error = function () { + if ((is_chrome_ios || force && is_safari) && view.FileReader) { + // Safari doesn't allow downloading of blob urls + var reader = new FileReader(); + reader.onloadend = function () { + var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;'); + var popup = view.open(url, '_blank'); + if (!popup) view.location.href = url; + url = undefined; // release reference before dispatching + filesaver.readyState = filesaver.DONE; + dispatch_all(); + }; + reader.readAsDataURL(blob); + filesaver.readyState = filesaver.INIT; + return; + } // don't create more object URLs than needed + + if (!object_url) { + object_url = get_URL().createObjectURL(blob); + } + if (force) { + view.location.href = object_url; + } else { + var opened = view.open(object_url, '_blank'); + if (!opened) { + // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html + view.location.href = object_url; + } + } + filesaver.readyState = filesaver.DONE; + dispatch_all(); + revoke(object_url); + }; + filesaver.readyState = filesaver.INIT; + if (can_use_save_link) { + object_url = get_URL().createObjectURL(blob); + setTimeout(function () { + save_link.href = object_url; + save_link.download = name; + click(save_link); + dispatch_all(); + revoke(object_url); + filesaver.readyState = filesaver.DONE; + }); + return; + } + fs_error(); + }, + FS_proto = FileSaver.prototype, + saveAs = function (blob, name, no_auto_bom) { + return new FileSaver(blob, name || blob.name || 'download', no_auto_bom); + }; + // IE 10+ (native saveAs) + if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) { + return function (blob, name, no_auto_bom) { + name = name || blob.name || 'download'; + if (!no_auto_bom) { + blob = auto_bom(blob); + } + return navigator.msSaveOrOpenBlob(blob, name); + }; + } + FS_proto.abort = function () { + }; + FS_proto.readyState = FS_proto.INIT = 0; + FS_proto.WRITING = 1; + FS_proto.DONE = 2; + FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; + return saveAs; + }(typeof self !== 'undefined' && self || typeof window !== 'undefined' && window || this.content); + // `self` is undefined in Firefox for Android content script context + // while `this` is nsIContentFrameMessageManager + // with an attribute `content` that corresponds to the window + if (typeof module !== 'undefined' && module.exports) { + module.exports.saveAs = saveAs; + } else if (typeof define !== 'undefined' && define !== null && define.amd !== null) { + define('FileSaver.js', function () { + return saveAs; + }); + } + }, + { + } + ], + 268: [ + function (_dereq_, module, exports) { + var __defProp = Object.defineProperty; + var __markAsModule = target=>__defProp(target, '__esModule', { + value: true + }); + var __export = (target, all) =>{ + for (var name in all) __defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + // src/index.js + __markAsModule(exports); + __export(exports, { + GIFEncoder: () =>GIFEncoder, + applyPalette: () =>applyPalette, + default: + () =>src_default, + nearestColor: () =>nearestColor, + nearestColorIndex: () =>nearestColorIndex, + nearestColorIndexWithDistance: () =>nearestColorIndexWithDistance, + prequantize: () =>prequantize, + quantize: () =>quantize, + snapColorsToPalette: () =>snapColorsToPalette + }); + // src/constants.js + var constants_default = { + signature: 'GIF', + version: '89a', + trailer: 59, + extensionIntroducer: 33, + applicationExtensionLabel: 255, + graphicControlExtensionLabel: 249, + imageSeparator: 44, + signatureSize: 3, + versionSize: 3, + globalColorTableFlagMask: 128, + colorResolutionMask: 112, + sortFlagMask: 8, + globalColorTableSizeMask: 7, + applicationIdentifierSize: 8, + applicationAuthCodeSize: 3, + disposalMethodMask: 28, + userInputFlagMask: 2, + transparentColorFlagMask: 1, + localColorTableFlagMask: 128, + interlaceFlagMask: 64, + idSortFlagMask: 32, + localColorTableSizeMask: 7 + }; + // src/stream.js + function createStream(initialCapacity = 256) { + let cursor = 0; + let contents = new Uint8Array(initialCapacity); + return { + get buffer() { + return contents.buffer; + }, + reset() { + cursor = 0; + }, + bytesView() { + return contents.subarray(0, cursor); + }, + bytes() { + return contents.slice(0, cursor); + }, + writeByte(byte) { + expand(cursor + 1); + contents[cursor] = byte; + cursor++; + }, + writeBytes(data, offset = 0, byteLength = data.length) { + expand(cursor + byteLength); + for (let i = 0; i < byteLength; i++) { + contents[cursor++] = data[i + offset]; + } + }, + writeBytesView(data, offset = 0, byteLength = data.byteLength) { + expand(cursor + byteLength); + contents.set(data.subarray(offset, offset + byteLength), cursor); + cursor += byteLength; + } + }; + function expand(newCapacity) { + var prevCapacity = contents.length; + if (prevCapacity >= newCapacity) return; + var CAPACITY_DOUBLING_MAX = 1024 * 1024; + newCapacity = Math.max(newCapacity, prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0); + if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); + const oldContents = contents; + contents = new Uint8Array(newCapacity); + if (cursor > 0) contents.set(oldContents.subarray(0, cursor), 0); + } + } // src/lzwEncode.js + + var BITS = 12; + var DEFAULT_HSIZE = 5003; + var MASKS = [ + 0, + 1, + 3, + 7, + 15, + 31, + 63, + 127, + 255, + 511, + 1023, + 2047, + 4095, + 8191, + 16383, + 32767, + 65535 + ]; + function lzwEncode(width, height, pixels, colorDepth, outStream = createStream(512), accum = new Uint8Array(256), htab = new Int32Array(DEFAULT_HSIZE), codetab = new Int32Array(DEFAULT_HSIZE)) { + const hsize = htab.length; + const initCodeSize = Math.max(2, colorDepth); + accum.fill(0); + codetab.fill(0); + htab.fill( - 1); + let cur_accum = 0; + let cur_bits = 0; + const init_bits = initCodeSize + 1; + const g_init_bits = init_bits; + let clear_flg = false; + let n_bits = g_init_bits; + let maxcode = (1 << n_bits) - 1; + const ClearCode = 1 << init_bits - 1; + const EOFCode = ClearCode + 1; + let free_ent = ClearCode + 2; + let a_count = 0; + let ent = pixels[0]; + let hshift = 0; + for (let fcode = hsize; fcode < 65536; fcode *= 2) { + ++hshift; + } + hshift = 8 - hshift; + outStream.writeByte(initCodeSize); + output(ClearCode); + const length = pixels.length; + for (let idx = 1; idx < length; idx++) { + next_block: { + const c = pixels[idx]; + const fcode = (c << BITS) + ent; + let i = c << hshift ^ ent; + if (htab[i] === fcode) { + ent = codetab[i]; + break next_block; + } + const disp = i === 0 ? 1 : hsize - i; + while (htab[i] >= 0) { + i -= disp; + if (i < 0) i += hsize; + if (htab[i] === fcode) { + ent = codetab[i]; + break next_block; + } + } + output(ent); + ent = c; + if (free_ent < 1 << BITS) { + codetab[i] = free_ent++; + htab[i] = fcode; + } else { + htab.fill( - 1); + free_ent = ClearCode + 2; + clear_flg = true; + output(ClearCode); + } + } + } + output(ent); + output(EOFCode); + outStream.writeByte(0); + return outStream.bytesView(); + function output(code) { + cur_accum &= MASKS[cur_bits]; + if (cur_bits > 0) cur_accum |= code << cur_bits; + else cur_accum = code; + cur_bits += n_bits; + while (cur_bits >= 8) { + accum[a_count++] = cur_accum & 255; + if (a_count >= 254) { + outStream.writeByte(a_count); + outStream.writeBytesView(accum, 0, a_count); + a_count = 0; + } + cur_accum >>= 8; + cur_bits -= 8; + } + if (free_ent > maxcode || clear_flg) { + if (clear_flg) { + n_bits = g_init_bits; + maxcode = (1 << n_bits) - 1; + clear_flg = false; + } else { + ++n_bits; + maxcode = n_bits === BITS ? 1 << n_bits : (1 << n_bits) - 1; + } + } + if (code == EOFCode) { + while (cur_bits > 0) { + accum[a_count++] = cur_accum & 255; + if (a_count >= 254) { + outStream.writeByte(a_count); + outStream.writeBytesView(accum, 0, a_count); + a_count = 0; + } + cur_accum >>= 8; + cur_bits -= 8; + } + if (a_count > 0) { + outStream.writeByte(a_count); + outStream.writeBytesView(accum, 0, a_count); + a_count = 0; + } + } + } + } + var lzwEncode_default = lzwEncode; + // src/rgb-packing.js + function rgb888_to_rgb565(r, g, b) { + return r << 8 & 63488 | g << 2 & 992 | b >> 3; + } + function rgba8888_to_rgba4444(r, g, b, a) { + return r >> 4 | g & 240 | (b & 240) << 4 | (a & 240) << 8; + } + function rgb888_to_rgb444(r, g, b) { + return r >> 4 << 8 | g & 240 | b >> 4; + } // src/pnnquant2.js + + function clamp(value, min, max) { + return value < min ? min : value > max ? max : value; + } + function sqr(value) { + return value * value; + } + function find_nn(bins, idx, hasAlpha) { + var nn = 0; + var err = 1e+100; + const bin1 = bins[idx]; + const n1 = bin1.cnt; + const wa = bin1.ac; + const wr = bin1.rc; + const wg = bin1.gc; + const wb = bin1.bc; + for (var i = bin1.fw; i != 0; i = bins[i].fw) { + const bin = bins[i]; + const n2 = bin.cnt; + const nerr2 = n1 * n2 / (n1 + n2); + if (nerr2 >= err) continue; + var nerr = 0; + if (hasAlpha) { + nerr += nerr2 * sqr(bin.ac - wa); + if (nerr >= err) continue; + } + nerr += nerr2 * sqr(bin.rc - wr); + if (nerr >= err) continue; + nerr += nerr2 * sqr(bin.gc - wg); + if (nerr >= err) continue; + nerr += nerr2 * sqr(bin.bc - wb); + if (nerr >= err) continue; + err = nerr; + nn = i; + } + bin1.err = err; + bin1.nn = nn; + } + function create_bin() { + return { + ac: 0, + rc: 0, + gc: 0, + bc: 0, + cnt: 0, + nn: 0, + fw: 0, + bk: 0, + tm: 0, + mtm: 0, + err: 0 + }; + } + function create_bin_list(data, format) { + const bincount = format === 'rgb444' ? 4096 : 65536; + const bins = new Array(bincount); + const size = data.length; + if (format === 'rgba4444') { + for (let i = 0; i < size; ++i) { + const color = data[i]; + const a = color >> 24 & 255; + const b = color >> 16 & 255; + const g = color >> 8 & 255; + const r = color & 255; + const index = rgba8888_to_rgba4444(r, g, b, a); + let bin = index in bins ? bins[index] : bins[index] = create_bin(); + bin.rc += r; + bin.gc += g; + bin.bc += b; + bin.ac += a; + bin.cnt++; + } + } else if (format === 'rgb444') { + for (let i = 0; i < size; ++i) { + const color = data[i]; + const b = color >> 16 & 255; + const g = color >> 8 & 255; + const r = color & 255; + const index = rgb888_to_rgb444(r, g, b); + let bin = index in bins ? bins[index] : bins[index] = create_bin(); + bin.rc += r; + bin.gc += g; + bin.bc += b; + bin.cnt++; + } + } else { + for (let i = 0; i < size; ++i) { + const color = data[i]; + const b = color >> 16 & 255; + const g = color >> 8 & 255; + const r = color & 255; + const index = rgb888_to_rgb565(r, g, b); + let bin = index in bins ? bins[index] : bins[index] = create_bin(); + bin.rc += r; + bin.gc += g; + bin.bc += b; + bin.cnt++; + } + } + return bins; + } + function quantize(rgba, maxColors, opts = { + }) { + const { + format = 'rgb565', + clearAlpha = true, + clearAlphaColor = 0, + clearAlphaThreshold = 0, + oneBitAlpha = false + } + = opts; + if (!rgba || !rgba.buffer) { + throw new Error('quantize() expected RGBA Uint8Array data'); + } + if (!(rgba instanceof Uint8Array) && !(rgba instanceof Uint8ClampedArray)) { + throw new Error('quantize() expected RGBA Uint8Array data'); + } + const data = new Uint32Array(rgba.buffer); + let useSqrt = opts.useSqrt !== false; + const hasAlpha = format === 'rgba4444'; + const bins = create_bin_list(data, format); + const bincount = bins.length; + const bincountMinusOne = bincount - 1; + const heap = new Uint32Array(bincount + 1); + var maxbins = 0; + for (var i = 0; i < bincount; ++i) { + const bin = bins[i]; + if (bin != null) { + var d = 1 / bin.cnt; + if (hasAlpha) bin.ac *= d; + bin.rc *= d; + bin.gc *= d; + bin.bc *= d; + bins[maxbins++] = bin; + } + } + if (sqr(maxColors) / maxbins < 0.022) { + useSqrt = false; + } + var i = 0; + for (; i < maxbins - 1; ++i) { + bins[i].fw = i + 1; + bins[i + 1].bk = i; + if (useSqrt) bins[i].cnt = Math.sqrt(bins[i].cnt); + } + if (useSqrt) bins[i].cnt = Math.sqrt(bins[i].cnt); + var h, + l, + l2; + for (i = 0; i < maxbins; ++i) { + find_nn(bins, i, false); + var err = bins[i].err; + for (l = ++heap[0]; l > 1; l = l2) { + l2 = l >> 1; + if (bins[h = heap[l2]].err <= err) break; + heap[l] = h; + } + heap[l] = i; + } + var extbins = maxbins - maxColors; + for (i = 0; i < extbins; ) { + var tb; + for (; ; ) { + var b1 = heap[1]; + tb = bins[b1]; + if (tb.tm >= tb.mtm && bins[tb.nn].mtm <= tb.tm) break; + if (tb.mtm == bincountMinusOne) b1 = heap[1] = heap[heap[0]--]; + else { + find_nn(bins, b1, false); + tb.tm = i; + } + var err = bins[b1].err; + for (l = 1; (l2 = l + l) <= heap[0]; l = l2) { + if (l2 < heap[0] && bins[heap[l2]].err > bins[heap[l2 + 1]].err) l2++; + if (err <= bins[h = heap[l2]].err) break; + heap[l] = h; + } + heap[l] = b1; + } + var nb = bins[tb.nn]; + var n1 = tb.cnt; + var n2 = nb.cnt; + var d = 1 / (n1 + n2); + if (hasAlpha) tb.ac = d * (n1 * tb.ac + n2 * nb.ac); + tb.rc = d * (n1 * tb.rc + n2 * nb.rc); + tb.gc = d * (n1 * tb.gc + n2 * nb.gc); + tb.bc = d * (n1 * tb.bc + n2 * nb.bc); + tb.cnt += nb.cnt; + tb.mtm = ++i; + bins[nb.bk].fw = nb.fw; + bins[nb.fw].bk = nb.bk; + nb.mtm = bincountMinusOne; + } + let palette = [ + ]; + var k = 0; + for (i = 0; ; ++k) { + let r = clamp(Math.round(bins[i].rc), 0, 255); + let g = clamp(Math.round(bins[i].gc), 0, 255); + let b = clamp(Math.round(bins[i].bc), 0, 255); + let a = 255; + if (hasAlpha) { + a = clamp(Math.round(bins[i].ac), 0, 255); + if (oneBitAlpha) { + const threshold = typeof oneBitAlpha === 'number' ? oneBitAlpha : 127; + a = a <= threshold ? 0 : 255; + } + if (clearAlpha && a <= clearAlphaThreshold) { + r = g = b = clearAlphaColor; + a = 0; + } + } + const color = hasAlpha ? [ + r, + g, + b, + a + ] : [ + r, + g, + b + ]; + const exists = existsInPalette(palette, color); + if (!exists) palette.push(color); + if ((i = bins[i].fw) == 0) break; + } + return palette; + } + function existsInPalette(palette, color) { + for (let i = 0; i < palette.length; i++) { + const p = palette[i]; + let matchesRGB = p[0] === color[0] && p[1] === color[1] && p[2] === color[2]; + let matchesAlpha = p.length >= 4 && color.length >= 4 ? p[3] === color[3] : true; + if (matchesRGB && matchesAlpha) return true; + } + return false; + } // src/color.js + + function euclideanDistanceSquared(a, b) { + var sum = 0; + var n; + for (n = 0; n < a.length; n++) { + const dx = a[n] - b[n]; + sum += dx * dx; + } + return sum; + } // src/palettize.js + + function roundStep(byte, step) { + return step > 1 ? Math.round(byte / step) * step : byte; + } + function prequantize(rgba, { + roundRGB = 5, + roundAlpha = 10, + oneBitAlpha = null + } + = { + }) { + const data = new Uint32Array(rgba.buffer); + for (let i = 0; i < data.length; i++) { + const color = data[i]; + let a = color >> 24 & 255; + let b = color >> 16 & 255; + let g = color >> 8 & 255; + let r = color & 255; + a = roundStep(a, roundAlpha); + if (oneBitAlpha) { + const threshold = typeof oneBitAlpha === 'number' ? oneBitAlpha : 127; + a = a <= threshold ? 0 : 255; + } + r = roundStep(r, roundRGB); + g = roundStep(g, roundRGB); + b = roundStep(b, roundRGB); + data[i] = a << 24 | b << 16 | g << 8 | r << 0; + } + } + function applyPalette(rgba, palette, format = 'rgb565') { + if (!rgba || !rgba.buffer) { + throw new Error('quantize() expected RGBA Uint8Array data'); + } + if (!(rgba instanceof Uint8Array) && !(rgba instanceof Uint8ClampedArray)) { + throw new Error('quantize() expected RGBA Uint8Array data'); + } + if (palette.length > 256) { + throw new Error('applyPalette() only works with 256 colors or less'); + } + const data = new Uint32Array(rgba.buffer); + const length = data.length; + const bincount = format === 'rgb444' ? 4096 : 65536; + const index = new Uint8Array(length); + const cache = new Array(bincount); + const hasAlpha = format === 'rgba4444'; + if (format === 'rgba4444') { + for (let i = 0; i < length; i++) { + const color = data[i]; + const a = color >> 24 & 255; + const b = color >> 16 & 255; + const g = color >> 8 & 255; + const r = color & 255; + const key = rgba8888_to_rgba4444(r, g, b, a); + const idx = key in cache ? cache[key] : cache[key] = nearestColorIndexRGBA(r, g, b, a, palette); + index[i] = idx; + } + } else { + const rgb888_to_key = format === 'rgb444' ? rgb888_to_rgb444 : rgb888_to_rgb565; + for (let i = 0; i < length; i++) { + const color = data[i]; + const b = color >> 16 & 255; + const g = color >> 8 & 255; + const r = color & 255; + const key = rgb888_to_key(r, g, b); + const idx = key in cache ? cache[key] : cache[key] = nearestColorIndexRGB(r, g, b, palette); + index[i] = idx; + } + } + return index; + } + function nearestColorIndexRGBA(r, g, b, a, palette) { + let k = 0; + let mindist = 1e+100; + for (let i = 0; i < palette.length; i++) { + const px2 = palette[i]; + const a2 = px2[3]; + let curdist = sqr2(a2 - a); + if (curdist > mindist) continue; + const r2 = px2[0]; + curdist += sqr2(r2 - r); + if (curdist > mindist) continue; + const g2 = px2[1]; + curdist += sqr2(g2 - g); + if (curdist > mindist) continue; + const b2 = px2[2]; + curdist += sqr2(b2 - b); + if (curdist > mindist) continue; + mindist = curdist; + k = i; + } + return k; + } + function nearestColorIndexRGB(r, g, b, palette) { + let k = 0; + let mindist = 1e+100; + for (let i = 0; i < palette.length; i++) { + const px2 = palette[i]; + const r2 = px2[0]; + let curdist = sqr2(r2 - r); + if (curdist > mindist) continue; + const g2 = px2[1]; + curdist += sqr2(g2 - g); + if (curdist > mindist) continue; + const b2 = px2[2]; + curdist += sqr2(b2 - b); + if (curdist > mindist) continue; + mindist = curdist; + k = i; + } + return k; + } + function snapColorsToPalette(palette, knownColors, threshold = 5) { + if (!palette.length || !knownColors.length) return; + const paletteRGB = palette.map(p=>p.slice(0, 3)); + const thresholdSq = threshold * threshold; + const dim = palette[0].length; + for (let i = 0; i < knownColors.length; i++) { + let color = knownColors[i]; + if (color.length < dim) { + color = [ + color[0], + color[1], + color[2], + 255 + ]; + } else if (color.length > dim) { + color = color.slice(0, 3); + } else { + color = color.slice(); + } + const r = nearestColorIndexWithDistance(paletteRGB, color.slice(0, 3), euclideanDistanceSquared); + const idx = r[0]; + const distanceSq = r[1]; + if (distanceSq > 0 && distanceSq <= thresholdSq) { + palette[idx] = color; + } + } + } + function sqr2(a) { + return a * a; + } + function nearestColorIndex(colors, pixel, distanceFn = euclideanDistanceSquared) { + let minDist = Infinity; + let minDistIndex = - 1; + for (let j = 0; j < colors.length; j++) { + const paletteColor = colors[j]; + const dist = distanceFn(pixel, paletteColor); + if (dist < minDist) { + minDist = dist; + minDistIndex = j; + } + } + return minDistIndex; + } + function nearestColorIndexWithDistance(colors, pixel, distanceFn = euclideanDistanceSquared) { + let minDist = Infinity; + let minDistIndex = - 1; + for (let j = 0; j < colors.length; j++) { + const paletteColor = colors[j]; + const dist = distanceFn(pixel, paletteColor); + if (dist < minDist) { + minDist = dist; + minDistIndex = j; + } + } + return [minDistIndex, + minDist]; + } + function nearestColor(colors, pixel, distanceFn = euclideanDistanceSquared) { + return colors[nearestColorIndex(colors, pixel, distanceFn)]; + } // src/index.js + + function GIFEncoder(opt = { + }) { + const { + initialCapacity = 4096, + auto = true + } + = opt; + const stream = createStream(initialCapacity); + const HSIZE = 5003; + const accum = new Uint8Array(256); + const htab = new Int32Array(HSIZE); + const codetab = new Int32Array(HSIZE); + let hasInit = false; + return { + reset() { + stream.reset(); + hasInit = false; + }, + finish() { + stream.writeByte(constants_default.trailer); + }, + bytes() { + return stream.bytes(); + }, + bytesView() { + return stream.bytesView(); + }, + get buffer() { + return stream.buffer; + }, + get stream() { + return stream; + }, + writeHeader, + writeFrame(index, width, height, opts = { + }) { + const { + transparent = false, + transparentIndex = 0, + delay = 0, + palette = null, + repeat = 0, + colorDepth = 8, + dispose = - 1 + } + = opts; + let first = false; + if (auto) { + if (!hasInit) { + first = true; + writeHeader(); + hasInit = true; + } + } else { + first = Boolean(opts.first); + } + width = Math.max(0, Math.floor(width)); + height = Math.max(0, Math.floor(height)); + if (first) { + if (!palette) { + throw new Error('First frame must include a { palette } option'); + } + encodeLogicalScreenDescriptor(stream, width, height, palette, colorDepth); + encodeColorTable(stream, palette); + if (repeat >= 0) { + encodeNetscapeExt(stream, repeat); + } + } + const delayTime = Math.round(delay / 10); + encodeGraphicControlExt(stream, dispose, delayTime, transparent, transparentIndex); + const useLocalColorTable = Boolean(palette) && !first; + encodeImageDescriptor(stream, width, height, useLocalColorTable ? palette : null); + if (useLocalColorTable) encodeColorTable(stream, palette); + encodePixels(stream, index, width, height, colorDepth, accum, htab, codetab); + } + }; + function writeHeader() { + writeUTFBytes(stream, 'GIF89a'); + } + } + function encodeGraphicControlExt(stream, dispose, delay, transparent, transparentIndex) { + stream.writeByte(33); + stream.writeByte(249); + stream.writeByte(4); + if (transparentIndex < 0) { + transparentIndex = 0; + transparent = false; + } + var transp, + disp; + if (!transparent) { + transp = 0; + disp = 0; + } else { + transp = 1; + disp = 2; + } + if (dispose >= 0) { + disp = dispose & 7; + } + disp <<= 2; + const userInput = 0; + stream.writeByte(0 | disp | userInput | transp); + writeUInt16(stream, delay); + stream.writeByte(transparentIndex || 0); + stream.writeByte(0); + } + function encodeLogicalScreenDescriptor(stream, width, height, palette, colorDepth = 8) { + const globalColorTableFlag = 1; + const sortFlag = 0; + const globalColorTableSize = colorTableSize(palette.length) - 1; + const fields = globalColorTableFlag << 7 | colorDepth - 1 << 4 | sortFlag << 3 | globalColorTableSize; + const backgroundColorIndex = 0; + const pixelAspectRatio = 0; + writeUInt16(stream, width); + writeUInt16(stream, height); + stream.writeBytes([fields, + backgroundColorIndex, + pixelAspectRatio]); + } + function encodeNetscapeExt(stream, repeat) { + stream.writeByte(33); + stream.writeByte(255); + stream.writeByte(11); + writeUTFBytes(stream, 'NETSCAPE2.0'); + stream.writeByte(3); + stream.writeByte(1); + writeUInt16(stream, repeat); + stream.writeByte(0); + } + function encodeColorTable(stream, palette) { + const colorTableLength = 1 << colorTableSize(palette.length); + for (let i = 0; i < colorTableLength; i++) { + let color = [ + 0, + 0, + 0 + ]; + if (i < palette.length) { + color = palette[i]; + } + stream.writeByte(color[0]); + stream.writeByte(color[1]); + stream.writeByte(color[2]); + } + } + function encodeImageDescriptor(stream, width, height, localPalette) { + stream.writeByte(44); + writeUInt16(stream, 0); + writeUInt16(stream, 0); + writeUInt16(stream, width); + writeUInt16(stream, height); + if (localPalette) { + const interlace = 0; + const sorted = 0; + const palSize = colorTableSize(localPalette.length) - 1; + stream.writeByte(128 | interlace | sorted | 0 | palSize); + } else { + stream.writeByte(0); + } + } + function encodePixels(stream, index, width, height, colorDepth = 8, accum, htab, codetab) { + lzwEncode_default(width, height, index, colorDepth, stream, accum, htab, codetab); + } + function writeUInt16(stream, short) { + stream.writeByte(short & 255); + stream.writeByte(short >> 8 & 255); + } + function writeUTFBytes(stream, text) { + for (var i = 0; i < text.length; i++) { + stream.writeByte(text.charCodeAt(i)); + } + } + function colorTableSize(length) { + return Math.max(Math.ceil(Math.log2(length)), 1); + } + var src_default = GIFEncoder; + }, + { + } + ], + 269: [ + function (_dereq_, module, exports) { + 'use strict'; + function _interopDefault(ex) { + return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex; + } + var _classCallCheck = _interopDefault(_dereq_('@babel/runtime/helpers/classCallCheck')); + var _createClass = _interopDefault(_dereq_('@babel/runtime/helpers/createClass')); + var arr = [ + ]; + var each = arr.forEach; + var slice = arr.slice; + function defaults(obj) { + each.call(slice.call(arguments, 1), function (source) { + if (source) { + for (var prop in source) { + if (obj[prop] === undefined) obj[prop] = source[prop]; + } + } + }); + return obj; + } + var cookie = { + create: function create(name, value, minutes, domain) { + var expires; + if (minutes) { + var date = new Date(); + date.setTime(date.getTime() + minutes * 60 * 1000); + expires = '; expires=' + date.toGMTString(); + } else expires = ''; + domain = domain ? 'domain=' + domain + ';' : ''; + document.cookie = name + '=' + value + expires + ';' + domain + 'path=/'; + }, + read: function read(name) { + var nameEQ = name + '='; + var ca = document.cookie.split(';'); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + while (c.charAt(0) === ' ') { + c = c.substring(1, c.length); + } + if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length); + } + return null; + }, + remove: function remove(name) { + this.create(name, '', - 1); + } + }; + var cookie$1 = { + name: 'cookie', + lookup: function lookup(options) { + var found; + if (options.lookupCookie && typeof document !== 'undefined') { + var c = cookie.read(options.lookupCookie); + if (c) found = c; + } + return found; + }, + cacheUserLanguage: function cacheUserLanguage(lng, options) { + if (options.lookupCookie && typeof document !== 'undefined') { + cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain); + } + } + }; + var querystring = { + name: 'querystring', + lookup: function lookup(options) { + var found; + if (typeof window !== 'undefined') { + var query = window.location.search.substring(1); + var params = query.split('&'); + for (var i = 0; i < params.length; i++) { + var pos = params[i].indexOf('='); + if (pos > 0) { + var key = params[i].substring(0, pos); + if (key === options.lookupQuerystring) { + found = params[i].substring(pos + 1); + } + } + } + } + return found; + } + }; + var hasLocalStorageSupport; + try { + hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null; + var testKey = 'i18next.translate.boo'; + window.localStorage.setItem(testKey, 'foo'); + window.localStorage.removeItem(testKey); + } catch (e) { + hasLocalStorageSupport = false; + } + var localStorage = { + name: 'localStorage', + lookup: function lookup(options) { + var found; + if (options.lookupLocalStorage && hasLocalStorageSupport) { + var lng = window.localStorage.getItem(options.lookupLocalStorage); + if (lng) found = lng; + } + return found; + }, + cacheUserLanguage: function cacheUserLanguage(lng, options) { + if (options.lookupLocalStorage && hasLocalStorageSupport) { + window.localStorage.setItem(options.lookupLocalStorage, lng); + } + } + }; + var navigator$1 = { + name: 'navigator', + lookup: function lookup(options) { + var found = [ + ]; + if (typeof navigator !== 'undefined') { + if (navigator.languages) { + // chrome only; not an array, so can't use .push.apply instead of iterating + for (var i = 0; i < navigator.languages.length; i++) { + found.push(navigator.languages[i]); + } + } + if (navigator.userLanguage) { + found.push(navigator.userLanguage); + } + if (navigator.language) { + found.push(navigator.language); + } + } + return found.length > 0 ? found : undefined; + } + }; + var htmlTag = { + name: 'htmlTag', + lookup: function lookup(options) { + var found; + var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null); + if (htmlTag && typeof htmlTag.getAttribute === 'function') { + found = htmlTag.getAttribute('lang'); + } + return found; + } + }; + var path = { + name: 'path', + lookup: function lookup(options) { + var found; + if (typeof window !== 'undefined') { + var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g); + if (language instanceof Array) { + if (typeof options.lookupFromPathIndex === 'number') { + if (typeof language[options.lookupFromPathIndex] !== 'string') { + return undefined; + } + found = language[options.lookupFromPathIndex].replace('/', ''); + } else { + found = language[0].replace('/', ''); + } + } + } + return found; + } + }; + var subdomain = { + name: 'subdomain', + lookup: function lookup(options) { + var found; + if (typeof window !== 'undefined') { + var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi); + if (language instanceof Array) { + if (typeof options.lookupFromSubdomainIndex === 'number') { + found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', ''); + } else { + found = language[0].replace('http://', '').replace('https://', '').replace('.', ''); + } + } + } + return found; + } + }; + function getDefaults() { + return { + order: [ + 'querystring', + 'cookie', + 'localStorage', + 'navigator', + 'htmlTag' + ], + lookupQuerystring: 'lng', + lookupCookie: 'i18next', + lookupLocalStorage: 'i18nextLng', + // cache user language + caches: [ + 'localStorage' + ], + excludeCacheFor: [ + 'cimode' + ], + //cookieMinutes: 10, + //cookieDomain: 'myDomain' + checkWhitelist: true + }; + } + var Browser = /*#__PURE__*/ + function () { + function Browser(services) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + _classCallCheck(this, Browser); + this.type = 'languageDetector'; + this.detectors = { + }; + this.init(services, options); + } + _createClass(Browser, [ + { + key: 'init', + value: function init(services) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + }; + this.services = services; + this.options = defaults(options, this.options || { + }, getDefaults()); // backwards compatibility + if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex; + this.i18nOptions = i18nOptions; + this.addDetector(cookie$1); + this.addDetector(querystring); + this.addDetector(localStorage); + this.addDetector(navigator$1); + this.addDetector(htmlTag); + this.addDetector(path); + this.addDetector(subdomain); + } + }, + { + key: 'addDetector', + value: function addDetector(detector) { + this.detectors[detector.name] = detector; + } + }, + { + key: 'detect', + value: function detect(detectionOrder) { + var _this = this; + if (!detectionOrder) detectionOrder = this.options.order; + var detected = [ + ]; + detectionOrder.forEach(function (detectorName) { + if (_this.detectors[detectorName]) { + var lookup = _this.detectors[detectorName].lookup(_this.options); + if (lookup && typeof lookup === 'string') lookup = [ + lookup + ]; + if (lookup) detected = detected.concat(lookup); + } + }); + var found; + detected.forEach(function (lng) { + if (found) return; + var cleanedLng = _this.services.languageUtils.formatLanguageCode(lng); + if (!_this.options.checkWhitelist || _this.services.languageUtils.isWhitelisted(cleanedLng)) found = cleanedLng; + }); + if (!found) { + var fallbacks = this.i18nOptions.fallbackLng; + if (typeof fallbacks === 'string') fallbacks = [ + fallbacks + ]; + if (!fallbacks) fallbacks = [ + ]; + if (Object.prototype.toString.apply(fallbacks) === '[object Array]') { + found = fallbacks[0]; + } else { + found = fallbacks[0] || fallbacks['default'] && fallbacks['default'][0]; + } + } + return found; + } + }, + { + key: 'cacheUserLanguage', + value: function cacheUserLanguage(lng, caches) { + var _this2 = this; + if (!caches) caches = this.options.caches; + if (!caches) return; + if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > - 1) return; + caches.forEach(function (cacheName) { + if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options); + }); + } + } + ]); + return Browser; + }(); + Browser.type = 'languageDetector'; + module.exports = Browser; + }, + { + '@babel/runtime/helpers/classCallCheck': 270, + '@babel/runtime/helpers/createClass': 271 + } + ], + 270: [ + function (_dereq_, module, exports) { + arguments[4][5][0].apply(exports, arguments) + }, + { + 'dup': 5 + } + ], + 271: [ + function (_dereq_, module, exports) { + arguments[4][6][0].apply(exports, arguments) + }, + { + 'dup': 6 + } + ], + 272: [ + function (_dereq_, module, exports) { + 'use strict'; + function _interopDefault(ex) { + return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex; + } + var _typeof = _interopDefault(_dereq_('@babel/runtime/helpers/typeof')); + var _objectSpread = _interopDefault(_dereq_('@babel/runtime/helpers/objectSpread')); + var _classCallCheck = _interopDefault(_dereq_('@babel/runtime/helpers/classCallCheck')); + var _createClass = _interopDefault(_dereq_('@babel/runtime/helpers/createClass')); + var _possibleConstructorReturn = _interopDefault(_dereq_('@babel/runtime/helpers/possibleConstructorReturn')); + var _getPrototypeOf = _interopDefault(_dereq_('@babel/runtime/helpers/getPrototypeOf')); + var _assertThisInitialized = _interopDefault(_dereq_('@babel/runtime/helpers/assertThisInitialized')); + var _inherits = _interopDefault(_dereq_('@babel/runtime/helpers/inherits')); + var _toConsumableArray = _interopDefault(_dereq_('@babel/runtime/helpers/toConsumableArray')); + var _slicedToArray = _interopDefault(_dereq_('@babel/runtime/helpers/slicedToArray')); + var consoleLogger = { + type: 'logger', + log: function log(args) { + this.output('log', args); + }, + warn: function warn(args) { + this.output('warn', args); + }, + error: function error(args) { + this.output('error', args); + }, + output: function output(type, args) { + var _console; + /* eslint no-console: 0 */ + if (console && console[type]) (_console = console) [type].apply(_console, _toConsumableArray(args)); + } + }; + var Logger = /*#__PURE__*/ + function () { + function Logger(concreteLogger) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + _classCallCheck(this, Logger); + this.init(concreteLogger, options); + } + _createClass(Logger, [ + { + key: 'init', + value: function init(concreteLogger) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + this.prefix = options.prefix || 'i18next:'; + this.logger = concreteLogger || consoleLogger; + this.options = options; + this.debug = options.debug; + } + }, + { + key: 'setDebug', + value: function setDebug(bool) { + this.debug = bool; + } + }, + { + key: 'log', + value: function log() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return this.forward(args, 'log', '', true); + } + }, + { + key: 'warn', + value: function warn() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + return this.forward(args, 'warn', '', true); + } + }, + { + key: 'error', + value: function error() { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + return this.forward(args, 'error', ''); + } + }, + { + key: 'deprecate', + value: function deprecate() { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true); + } + }, + { + key: 'forward', + value: function forward(args, lvl, prefix, debugOnly) { + if (debugOnly && !this.debug) return null; + if (typeof args[0] === 'string') args[0] = ''.concat(prefix).concat(this.prefix, ' ').concat(args[0]); + return this.logger[lvl](args); + } + }, + { + key: 'create', + value: function create(moduleName) { + return new Logger(this.logger, _objectSpread({ + }, { + prefix: ''.concat(this.prefix, ':').concat(moduleName, ':') + }, this.options)); + } + } + ]); + return Logger; + }(); + var baseLogger = new Logger(); + var EventEmitter = /*#__PURE__*/ + function () { + function EventEmitter() { + _classCallCheck(this, EventEmitter); + this.observers = { + }; + } + _createClass(EventEmitter, [ + { + key: 'on', + value: function on(events, listener) { + var _this = this; + events.split(' ').forEach(function (event) { + _this.observers[event] = _this.observers[event] || [ + ]; + _this.observers[event].push(listener); + }); + return this; + } + }, + { + key: 'off', + value: function off(event, listener) { + if (!this.observers[event]) return; + if (!listener) { + delete this.observers[event]; + return; + } + this.observers[event] = this.observers[event].filter(function (l) { + return l !== listener; + }); + } + }, + { + key: 'emit', + value: function emit(event) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + if (this.observers[event]) { + var cloned = [ + ].concat(this.observers[event]); + cloned.forEach(function (observer) { + observer.apply(void 0, args); + }); + } + if (this.observers['*']) { + var _cloned = [ + ].concat(this.observers['*']); + _cloned.forEach(function (observer) { + observer.apply(observer, [ + event + ].concat(args)); + }); + } + } + } + ]); + return EventEmitter; + }(); + // http://lea.verou.me/2016/12/resolve-promises-externally-with-this-one-weird-trick/ + function defer() { + var res; + var rej; + var promise = new Promise(function (resolve, reject) { + res = resolve; + rej = reject; + }); + promise.resolve = res; + promise.reject = rej; + return promise; + } + function makeString(object) { + if (object == null) return ''; + /* eslint prefer-template: 0 */ + return '' + object; + } + function copy(a, s, t) { + a.forEach(function (m) { + if (s[m]) t[m] = s[m]; + }); + } + function getLastOfPath(object, path, Empty) { + function cleanKey(key) { + return key && key.indexOf('###') > - 1 ? key.replace(/###/g, '.') : key; + } + function canNotTraverseDeeper() { + return !object || typeof object === 'string'; + } + var stack = typeof path !== 'string' ? [ + ].concat(path) : path.split('.'); + while (stack.length > 1) { + if (canNotTraverseDeeper()) return { + }; + var key = cleanKey(stack.shift()); + if (!object[key] && Empty) object[key] = new Empty(); + object = object[key]; + } + if (canNotTraverseDeeper()) return { + }; + return { + obj: object, + k: cleanKey(stack.shift()) + }; + } + function setPath(object, path, newValue) { + var _getLastOfPath = getLastOfPath(object, path, Object), + obj = _getLastOfPath.obj, + k = _getLastOfPath.k; + obj[k] = newValue; + } + function pushPath(object, path, newValue, concat) { + var _getLastOfPath2 = getLastOfPath(object, path, Object), + obj = _getLastOfPath2.obj, + k = _getLastOfPath2.k; + obj[k] = obj[k] || [ + ]; + if (concat) obj[k] = obj[k].concat(newValue); + if (!concat) obj[k].push(newValue); + } + function getPath(object, path) { + var _getLastOfPath3 = getLastOfPath(object, path), + obj = _getLastOfPath3.obj, + k = _getLastOfPath3.k; + if (!obj) return undefined; + return obj[k]; + } + function getPathWithDefaults(data, defaultData, key) { + var value = getPath(data, key); + if (value !== undefined) { + return value; + } // Fallback to default values + + return getPath(defaultData, key); + } + function deepExtend(target, source, overwrite) { + /* eslint no-restricted-syntax: 0 */ + for (var prop in source) { + if (prop in target) { + // If we reached a leaf string in target or source then replace with source or skip depending on the 'overwrite' switch + if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) { + if (overwrite) target[prop] = source[prop]; + } else { + deepExtend(target[prop], source[prop], overwrite); + } + } else { + target[prop] = source[prop]; + } + } + return target; + } + function regexEscape(str) { + /* eslint no-useless-escape: 0 */ + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); + } /* eslint-disable */ + + var _entityMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + '\'': ''', + '/': '/' + }; + /* eslint-enable */ + function escape(data) { + if (typeof data === 'string') { + return data.replace(/[&<>"'\/]/g, function (s) { + return _entityMap[s]; + }); + } + return data; + } + var ResourceStore = /*#__PURE__*/ + function (_EventEmitter) { + _inherits(ResourceStore, _EventEmitter); + function ResourceStore(data) { + var _this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + ns: [ + 'translation' + ], + defaultNS: 'translation' + }; + _classCallCheck(this, ResourceStore); + _this = _possibleConstructorReturn(this, _getPrototypeOf(ResourceStore).call(this)); + EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor) + _this.data = data || { + }; + _this.options = options; + if (_this.options.keySeparator === undefined) { + _this.options.keySeparator = '.'; + } + return _this; + } + _createClass(ResourceStore, [ + { + key: 'addNamespaces', + value: function addNamespaces(ns) { + if (this.options.ns.indexOf(ns) < 0) { + this.options.ns.push(ns); + } + } + }, + { + key: 'removeNamespaces', + value: function removeNamespaces(ns) { + var index = this.options.ns.indexOf(ns); + if (index > - 1) { + this.options.ns.splice(index, 1); + } + } + }, + { + key: 'getResource', + value: function getResource(lng, ns, key) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { + }; + var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; + var path = [ + lng, + ns + ]; + if (key && typeof key !== 'string') path = path.concat(key); + if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key); + if (lng.indexOf('.') > - 1) { + path = lng.split('.'); + } + return getPath(this.data, path); + } + }, + { + key: 'addResource', + value: function addResource(lng, ns, key, value) { + var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : { + silent: false + }; + var keySeparator = this.options.keySeparator; + if (keySeparator === undefined) keySeparator = '.'; + var path = [ + lng, + ns + ]; + if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key); + if (lng.indexOf('.') > - 1) { + path = lng.split('.'); + value = ns; + ns = path[1]; + } + this.addNamespaces(ns); + setPath(this.data, path, value); + if (!options.silent) this.emit('added', lng, ns, key, value); + } + }, + { + key: 'addResources', + value: function addResources(lng, ns, resources) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { + silent: false + }; + /* eslint no-restricted-syntax: 0 */ + for (var m in resources) { + if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], { + silent: true + }); + } + if (!options.silent) this.emit('added', lng, ns, resources); + } + }, + { + key: 'addResourceBundle', + value: function addResourceBundle(lng, ns, resources, deep, overwrite) { + var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : { + silent: false + }; + var path = [ + lng, + ns + ]; + if (lng.indexOf('.') > - 1) { + path = lng.split('.'); + deep = resources; + resources = ns; + ns = path[1]; + } + this.addNamespaces(ns); + var pack = getPath(this.data, path) || { + }; + if (deep) { + deepExtend(pack, resources, overwrite); + } else { + pack = _objectSpread({ + }, pack, resources); + } + setPath(this.data, path, pack); + if (!options.silent) this.emit('added', lng, ns, resources); + } + }, + { + key: 'removeResourceBundle', + value: function removeResourceBundle(lng, ns) { + if (this.hasResourceBundle(lng, ns)) { + delete this.data[lng][ns]; + } + this.removeNamespaces(ns); + this.emit('removed', lng, ns); + } + }, + { + key: 'hasResourceBundle', + value: function hasResourceBundle(lng, ns) { + return this.getResource(lng, ns) !== undefined; + } + }, + { + key: 'getResourceBundle', + value: function getResourceBundle(lng, ns) { + if (!ns) ns = this.options.defaultNS; // COMPATIBILITY: remove extend in v2.1.0 + if (this.options.compatibilityAPI === 'v1') return _objectSpread({ + }, { + }, this.getResource(lng, ns)); + return this.getResource(lng, ns); + } + }, + { + key: 'getDataByLanguage', + value: function getDataByLanguage(lng) { + return this.data[lng]; + } + }, + { + key: 'toJSON', + value: function toJSON() { + return this.data; + } + } + ]); + return ResourceStore; + }(EventEmitter); + var postProcessor = { + processors: { + }, + addPostProcessor: function addPostProcessor(module) { + this.processors[module.name] = module; + }, + handle: function handle(processors, value, key, options, translator) { + var _this = this; + processors.forEach(function (processor) { + if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator); + }); + return value; + } + }; + var checkedLoadedFor = { + }; + var Translator = /*#__PURE__*/ + function (_EventEmitter) { + _inherits(Translator, _EventEmitter); + function Translator(services) { + var _this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + _classCallCheck(this, Translator); + _this = _possibleConstructorReturn(this, _getPrototypeOf(Translator).call(this)); + EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor) + copy(['resourceStore', + 'languageUtils', + 'pluralResolver', + 'interpolator', + 'backendConnector', + 'i18nFormat', + 'utils'], services, _assertThisInitialized(_this)); + _this.options = options; + if (_this.options.keySeparator === undefined) { + _this.options.keySeparator = '.'; + } + _this.logger = baseLogger.create('translator'); + return _this; + } + _createClass(Translator, [ + { + key: 'changeLanguage', + value: function changeLanguage(lng) { + if (lng) this.language = lng; + } + }, + { + key: 'exists', + value: function exists(key) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + interpolation: { + } + }; + var resolved = this.resolve(key, options); + return resolved && resolved.res !== undefined; + } + }, + { + key: 'extractFromKey', + value: function extractFromKey(key, options) { + var nsSeparator = options.nsSeparator || this.options.nsSeparator; + if (nsSeparator === undefined) nsSeparator = ':'; + var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; + var namespaces = options.ns || this.options.defaultNS; + if (nsSeparator && key.indexOf(nsSeparator) > - 1) { + var parts = key.split(nsSeparator); + if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > - 1) namespaces = parts.shift(); + key = parts.join(keySeparator); + } + if (typeof namespaces === 'string') namespaces = [ + namespaces + ]; + return { + key: key, + namespaces: namespaces + }; + } + }, + { + key: 'translate', + value: function translate(keys, options) { + var _this2 = this; + if (_typeof(options) !== 'object' && this.options.overloadTranslationOptionHandler) { + /* eslint prefer-rest-params: 0 */ + options = this.options.overloadTranslationOptionHandler(arguments); + } + if (!options) options = { + }; // non valid keys handling + if (keys === undefined || keys === null /* || keys === ''*/ + ) return ''; + if (!Array.isArray(keys)) keys = [ + String(keys) + ]; // separators + var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; // get namespace(s) + var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options), + key = _this$extractFromKey.key, + namespaces = _this$extractFromKey.namespaces; + var namespace = namespaces[namespaces.length - 1]; // return key on CIMode + var lng = options.lng || this.language; + var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode; + if (lng && lng.toLowerCase() === 'cimode') { + if (appendNamespaceToCIMode) { + var nsSeparator = options.nsSeparator || this.options.nsSeparator; + return namespace + nsSeparator + key; + } + return key; + } // resolve from store + + var resolved = this.resolve(keys, options); + var res = resolved && resolved.res; + var resUsedKey = resolved && resolved.usedKey || key; + var resExactUsedKey = resolved && resolved.exactUsedKey || key; + var resType = Object.prototype.toString.apply(res); + var noObject = [ + '[object Number]', + '[object Function]', + '[object RegExp]' + ]; + var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays; // object + var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject; + var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number'; + if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) { + if (!options.returnObjects && !this.options.returnObjects) { + this.logger.warn('accessing an object - but returnObjects options is not enabled!'); + return this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, options) : 'key \''.concat(key, ' (').concat(this.language, ')\' returned an object instead of string.'); + } // if we got a separator we loop over children - else we just return object as is + // as having it set to false means no hierarchy so no lookup for nested values + + if (keySeparator) { + var resTypeIsArray = resType === '[object Array]'; + var copy$$1 = resTypeIsArray ? [ + ] : { + }; // apply child translation on a copy + /* eslint no-restricted-syntax: 0 */ + var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey; + for (var m in res) { + if (Object.prototype.hasOwnProperty.call(res, m)) { + var deepKey = ''.concat(newKeyToUse).concat(keySeparator).concat(m); + copy$$1[m] = this.translate(deepKey, _objectSpread({ + }, options, { + joinArrays: false, + ns: namespaces + })); + if (copy$$1[m] === deepKey) copy$$1[m] = res[m]; // if nothing found use orginal value as fallback + } + } + res = copy$$1; + } + } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') { + // array special treatment + res = res.join(joinArrays); + if (res) res = this.extendTranslation(res, keys, options); + } else { + // string, empty or null + var usedDefault = false; + var usedKey = false; // fallback value + if (!this.isValidLookup(res) && options.defaultValue !== undefined) { + usedDefault = true; + if (options.count !== undefined) { + var suffix = this.pluralResolver.getSuffix(lng, options.count); + res = options['defaultValue'.concat(suffix)]; + } + if (!res) res = options.defaultValue; + } + if (!this.isValidLookup(res)) { + usedKey = true; + res = key; + } // save missing + + var updateMissing = options.defaultValue && options.defaultValue !== res && this.options.updateMissing; + if (usedKey || usedDefault || updateMissing) { + this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? options.defaultValue : res); + var lngs = [ + ]; + var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language); + if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) { + for (var i = 0; i < fallbackLngs.length; i++) { + lngs.push(fallbackLngs[i]); + } + } else if (this.options.saveMissingTo === 'all') { + lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language); + } else { + lngs.push(options.lng || this.language); + } + var send = function send(l, k) { + if (_this2.options.missingKeyHandler) { + _this2.options.missingKeyHandler(l, namespace, k, updateMissing ? options.defaultValue : res, updateMissing, options); + } else if (_this2.backendConnector && _this2.backendConnector.saveMissing) { + _this2.backendConnector.saveMissing(l, namespace, k, updateMissing ? options.defaultValue : res, updateMissing, options); + } + _this2.emit('missingKey', l, namespace, k, res); + }; + if (this.options.saveMissing) { + var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string'; + if (this.options.saveMissingPlurals && needsPluralHandling) { + lngs.forEach(function (l) { + var plurals = _this2.pluralResolver.getPluralFormsOfKey(l, key); + plurals.forEach(function (p) { + return send([l], p); + }); + }); + } else { + send(lngs, key); + } + } + } // extend + + res = this.extendTranslation(res, keys, options, resolved); // append namespace if still key + if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = ''.concat(namespace, ':').concat(key); // parseMissingKeyHandler + if (usedKey && this.options.parseMissingKeyHandler) res = this.options.parseMissingKeyHandler(res); + } // return + + return res; + } + }, + { + key: 'extendTranslation', + value: function extendTranslation(res, key, options, resolved) { + var _this3 = this; + if (this.i18nFormat && this.i18nFormat.parse) { + res = this.i18nFormat.parse(res, options, resolved.usedLng, resolved.usedNS, resolved.usedKey, { + resolved: resolved + }); + } else if (!options.skipInterpolation) { + // i18next.parsing + if (options.interpolation) this.interpolator.init(_objectSpread({ + }, options, { + interpolation: _objectSpread({ + }, this.options.interpolation, options.interpolation) + })); // interpolate + var data = options.replace && typeof options.replace !== 'string' ? options.replace : options; + if (this.options.interpolation.defaultVariables) data = _objectSpread({ + }, this.options.interpolation.defaultVariables, data); + res = this.interpolator.interpolate(res, data, options.lng || this.language, options); // nesting + if (options.nest !== false) res = this.interpolator.nest(res, function () { + return _this3.translate.apply(_this3, arguments); + }, options); + if (options.interpolation) this.interpolator.reset(); + } // post process + + var postProcess = options.postProcess || this.options.postProcess; + var postProcessorNames = typeof postProcess === 'string' ? [ + postProcess + ] : postProcess; + if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) { + res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread({ + i18nResolved: resolved + }, options) : options, this); + } + return res; + } + }, + { + key: 'resolve', + value: function resolve(keys) { + var _this4 = this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + var found; + var usedKey; // plain key + var exactUsedKey; // key with context / plural + var usedLng; + var usedNS; + if (typeof keys === 'string') keys = [ + keys + ]; // forEach possible key + keys.forEach(function (k) { + if (_this4.isValidLookup(found)) return; + var extracted = _this4.extractFromKey(k, options); + var key = extracted.key; + usedKey = key; + var namespaces = extracted.namespaces; + if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS); + var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string'; + var needsContextHandling = options.context !== undefined && typeof options.context === 'string' && options.context !== ''; + var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng); + namespaces.forEach(function (ns) { + if (_this4.isValidLookup(found)) return; + usedNS = ns; + if (!checkedLoadedFor[''.concat(codes[0], '-').concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) { + checkedLoadedFor[''.concat(codes[0], '-').concat(ns)] = true; + _this4.logger.warn('key "'.concat(usedKey, '" for namespace "').concat(usedNS, '" for languages "').concat(codes.join(', '), '" won\'t get resolved as namespace was not yet loaded'), 'This means something IS WRONG in your application setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!'); + } + codes.forEach(function (code) { + if (_this4.isValidLookup(found)) return; + usedLng = code; + var finalKey = key; + var finalKeys = [ + finalKey + ]; + if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) { + _this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options); + } else { + var pluralSuffix; + if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count); // fallback for plural if context not found + if (needsPluralHandling && needsContextHandling) finalKeys.push(finalKey + pluralSuffix); // get key for context if needed + if (needsContextHandling) finalKeys.push(finalKey += ''.concat(_this4.options.contextSeparator).concat(options.context)); // get key for plural if needed + if (needsPluralHandling) finalKeys.push(finalKey += pluralSuffix); + } // iterate over finalKeys starting with most specific pluralkey (-> contextkey only) -> singularkey only + + var possibleKey; + /* eslint no-cond-assign: 0 */ + while (possibleKey = finalKeys.pop()) { + if (!_this4.isValidLookup(found)) { + exactUsedKey = possibleKey; + found = _this4.getResource(code, ns, possibleKey, options); + } + } + }); + }); + }); + return { + res: found, + usedKey: usedKey, + exactUsedKey: exactUsedKey, + usedLng: usedLng, + usedNS: usedNS + }; + } + }, + { + key: 'isValidLookup', + value: function isValidLookup(res) { + return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === ''); + } + }, + { + key: 'getResource', + value: function getResource(code, ns, key) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { + }; + if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options); + return this.resourceStore.getResource(code, ns, key, options); + } + } + ]); + return Translator; + }(EventEmitter); + function capitalize(string) { + return string.charAt(0).toUpperCase() + string.slice(1); + } + var LanguageUtil = /*#__PURE__*/ + function () { + function LanguageUtil(options) { + _classCallCheck(this, LanguageUtil); + this.options = options; + this.whitelist = this.options.whitelist || false; + this.logger = baseLogger.create('languageUtils'); + } + _createClass(LanguageUtil, [ + { + key: 'getScriptPartFromCode', + value: function getScriptPartFromCode(code) { + if (!code || code.indexOf('-') < 0) return null; + var p = code.split('-'); + if (p.length === 2) return null; + p.pop(); + return this.formatLanguageCode(p.join('-')); + } + }, + { + key: 'getLanguagePartFromCode', + value: function getLanguagePartFromCode(code) { + if (!code || code.indexOf('-') < 0) return code; + var p = code.split('-'); + return this.formatLanguageCode(p[0]); + } + }, + { + key: 'formatLanguageCode', + value: function formatLanguageCode(code) { + // http://www.iana.org/assignments/language-tags/language-tags.xhtml + if (typeof code === 'string' && code.indexOf('-') > - 1) { + var specialCases = [ + 'hans', + 'hant', + 'latn', + 'cyrl', + 'cans', + 'mong', + 'arab' + ]; + var p = code.split('-'); + if (this.options.lowerCaseLng) { + p = p.map(function (part) { + return part.toLowerCase(); + }); + } else if (p.length === 2) { + p[0] = p[0].toLowerCase(); + p[1] = p[1].toUpperCase(); + if (specialCases.indexOf(p[1].toLowerCase()) > - 1) p[1] = capitalize(p[1].toLowerCase()); + } else if (p.length === 3) { + p[0] = p[0].toLowerCase(); // if lenght 2 guess it's a country + if (p[1].length === 2) p[1] = p[1].toUpperCase(); + if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase(); + if (specialCases.indexOf(p[1].toLowerCase()) > - 1) p[1] = capitalize(p[1].toLowerCase()); + if (specialCases.indexOf(p[2].toLowerCase()) > - 1) p[2] = capitalize(p[2].toLowerCase()); + } + return p.join('-'); + } + return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code; + } + }, + { + key: 'isWhitelisted', + value: function isWhitelisted(code) { + if (this.options.load === 'languageOnly' || this.options.nonExplicitWhitelist) { + code = this.getLanguagePartFromCode(code); + } + return !this.whitelist || !this.whitelist.length || this.whitelist.indexOf(code) > - 1; + } + }, + { + key: 'getFallbackCodes', + value: function getFallbackCodes(fallbacks, code) { + if (!fallbacks) return []; + if (typeof fallbacks === 'string') fallbacks = [ + fallbacks + ]; + if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks; + if (!code) return fallbacks['default'] || [ + ]; // asume we have an object defining fallbacks + var found = fallbacks[code]; + if (!found) found = fallbacks[this.getScriptPartFromCode(code)]; + if (!found) found = fallbacks[this.formatLanguageCode(code)]; + if (!found) found = fallbacks['default']; + return found || [ + ]; + } + }, + { + key: 'toResolveHierarchy', + value: function toResolveHierarchy(code, fallbackCode) { + var _this = this; + var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [ + ], code); + var codes = [ + ]; + var addCode = function addCode(c) { + if (!c) return; + if (_this.isWhitelisted(c)) { + codes.push(c); + } else { + _this.logger.warn('rejecting non-whitelisted language code: '.concat(c)); + } + }; + if (typeof code === 'string' && code.indexOf('-') > - 1) { + if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code)); + if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code)); + if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code)); + } else if (typeof code === 'string') { + addCode(this.formatLanguageCode(code)); + } + fallbackCodes.forEach(function (fc) { + if (codes.indexOf(fc) < 0) addCode(_this.formatLanguageCode(fc)); + }); + return codes; + } + } + ]); + return LanguageUtil; + }(); + /* eslint-disable */ + var sets = [ + { + lngs: [ + 'ach', + 'ak', + 'am', + 'arn', + 'br', + 'fil', + 'gun', + 'ln', + 'mfe', + 'mg', + 'mi', + 'oc', + 'pt', + 'pt-BR', + 'tg', + 'ti', + 'tr', + 'uz', + 'wa' + ], + nr: [ + 1, + 2 + ], + fc: 1 + }, + { + lngs: [ + 'af', + 'an', + 'ast', + 'az', + 'bg', + 'bn', + 'ca', + 'da', + 'de', + 'dev', + 'el', + 'en', + 'eo', + 'es', + 'et', + 'eu', + 'fi', + 'fo', + 'fur', + 'fy', + 'gl', + 'gu', + 'ha', + 'hi', + 'hu', + 'hy', + 'ia', + 'it', + 'kn', + 'ku', + 'lb', + 'mai', + 'ml', + 'mn', + 'mr', + 'nah', + 'nap', + 'nb', + 'ne', + 'nl', + 'nn', + 'no', + 'nso', + 'pa', + 'pap', + 'pms', + 'ps', + 'pt-PT', + 'rm', + 'sco', + 'se', + 'si', + 'so', + 'son', + 'sq', + 'sv', + 'sw', + 'ta', + 'te', + 'tk', + 'ur', + 'yo' + ], + nr: [ + 1, + 2 + ], + fc: 2 + }, + { + lngs: [ + 'ay', + 'bo', + 'cgg', + 'fa', + 'id', + 'ja', + 'jbo', + 'ka', + 'kk', + 'km', + 'ko', + 'ky', + 'lo', + 'ms', + 'sah', + 'su', + 'th', + 'tt', + 'ug', + 'vi', + 'wo', + 'zh' + ], + nr: [ + 1 + ], + fc: 3 + }, + { + lngs: [ + 'be', + 'bs', + 'cnr', + 'dz', + 'hr', + 'ru', + 'sr', + 'uk' + ], + nr: [ + 1, + 2, + 5 + ], + fc: 4 + }, + { + lngs: [ + 'ar' + ], + nr: [ + 0, + 1, + 2, + 3, + 11, + 100 + ], + fc: 5 + }, + { + lngs: [ + 'cs', + 'sk' + ], + nr: [ + 1, + 2, + 5 + ], + fc: 6 + }, + { + lngs: [ + 'csb', + 'pl' + ], + nr: [ + 1, + 2, + 5 + ], + fc: 7 + }, + { + lngs: [ + 'cy' + ], + nr: [ + 1, + 2, + 3, + 8 + ], + fc: 8 + }, + { + lngs: [ + 'fr' + ], + nr: [ + 1, + 2 + ], + fc: 9 + }, + { + lngs: [ + 'ga' + ], + nr: [ + 1, + 2, + 3, + 7, + 11 + ], + fc: 10 + }, + { + lngs: [ + 'gd' + ], + nr: [ + 1, + 2, + 3, + 20 + ], + fc: 11 + }, + { + lngs: [ + 'is' + ], + nr: [ + 1, + 2 + ], + fc: 12 + }, + { + lngs: [ + 'jv' + ], + nr: [ + 0, + 1 + ], + fc: 13 + }, + { + lngs: [ + 'kw' + ], + nr: [ + 1, + 2, + 3, + 4 + ], + fc: 14 + }, + { + lngs: [ + 'lt' + ], + nr: [ + 1, + 2, + 10 + ], + fc: 15 + }, + { + lngs: [ + 'lv' + ], + nr: [ + 1, + 2, + 0 + ], + fc: 16 + }, + { + lngs: [ + 'mk' + ], + nr: [ + 1, + 2 + ], + fc: 17 + }, + { + lngs: [ + 'mnk' + ], + nr: [ + 0, + 1, + 2 + ], + fc: 18 + }, + { + lngs: [ + 'mt' + ], + nr: [ + 1, + 2, + 11, + 20 + ], + fc: 19 + }, + { + lngs: [ + 'or' + ], + nr: [ + 2, + 1 + ], + fc: 2 + }, + { + lngs: [ + 'ro' + ], + nr: [ + 1, + 2, + 20 + ], + fc: 20 + }, + { + lngs: [ + 'sl' + ], + nr: [ + 5, + 1, + 2, + 3 + ], + fc: 21 + }, + { + lngs: [ + 'he' + ], + nr: [ + 1, + 2, + 20, + 21 + ], + fc: 22 + } + ]; + var _rulesPluralsTypes = { + 1: function _(n) { + return Number(n > 1); + }, + 2: function _(n) { + return Number(n != 1); + }, + 3: function _(n) { + return 0; + }, + 4: function _(n) { + return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); + }, + 5: function _(n) { + return Number(n === 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5); + }, + 6: function _(n) { + return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2); + }, + 7: function _(n) { + return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); + }, + 8: function _(n) { + return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3); + }, + 9: function _(n) { + return Number(n >= 2); + }, + 10: function _(n) { + return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4); + }, + 11: function _(n) { + return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3); + }, + 12: function _(n) { + return Number(n % 10 != 1 || n % 100 == 11); + }, + 13: function _(n) { + return Number(n !== 0); + }, + 14: function _(n) { + return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3); + }, + 15: function _(n) { + return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); + }, + 16: function _(n) { + return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2); + }, + 17: function _(n) { + return Number(n == 1 || n % 10 == 1 ? 0 : 1); + }, + 18: function _(n) { + return Number(n == 0 ? 0 : n == 1 ? 1 : 2); + }, + 19: function _(n) { + return Number(n == 1 ? 0 : n === 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3); + }, + 20: function _(n) { + return Number(n == 1 ? 0 : n === 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2); + }, + 21: function _(n) { + return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0); + }, + 22: function _(n) { + return Number(n === 1 ? 0 : n === 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3); + } + }; + /* eslint-enable */ + function createRules() { + var rules = { + }; + sets.forEach(function (set) { + set.lngs.forEach(function (l) { + rules[l] = { + numbers: set.nr, + plurals: _rulesPluralsTypes[set.fc] + }; + }); + }); + return rules; + } + var PluralResolver = /*#__PURE__*/ + function () { + function PluralResolver(languageUtils) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + _classCallCheck(this, PluralResolver); + this.languageUtils = languageUtils; + this.options = options; + this.logger = baseLogger.create('pluralResolver'); + this.rules = createRules(); + } + _createClass(PluralResolver, [ + { + key: 'addRule', + value: function addRule(lng, obj) { + this.rules[lng] = obj; + } + }, + { + key: 'getRule', + value: function getRule(code) { + return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)]; + } + }, + { + key: 'needsPlural', + value: function needsPlural(code) { + var rule = this.getRule(code); + return rule && rule.numbers.length > 1; + } + }, + { + key: 'getPluralFormsOfKey', + value: function getPluralFormsOfKey(code, key) { + var _this = this; + var ret = [ + ]; + var rule = this.getRule(code); + if (!rule) return ret; + rule.numbers.forEach(function (n) { + var suffix = _this.getSuffix(code, n); + ret.push(''.concat(key).concat(suffix)); + }); + return ret; + } + }, + { + key: 'getSuffix', + value: function getSuffix(code, count) { + var _this2 = this; + var rule = this.getRule(code); + if (rule) { + // if (rule.numbers.length === 1) return ''; // only singular + var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count)); + var suffix = rule.numbers[idx]; // special treatment for lngs only having singular and plural + if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) { + if (suffix === 2) { + suffix = 'plural'; + } else if (suffix === 1) { + suffix = ''; + } + } + var returnSuffix = function returnSuffix() { + return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString(); + }; // COMPATIBILITY JSON + // v1 + if (this.options.compatibilityJSON === 'v1') { + if (suffix === 1) return ''; + if (typeof suffix === 'number') return '_plural_'.concat(suffix.toString()); + return returnSuffix(); + } else if ( /* v2 */ + this.options.compatibilityJSON === 'v2') { + return returnSuffix(); + } else if ( /* v3 - gettext index */ + this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) { + return returnSuffix(); + } + return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString(); + } + this.logger.warn('no plural rule found for: '.concat(code)); + return ''; + } + } + ]); + return PluralResolver; + }(); + var Interpolator = /*#__PURE__*/ + function () { + function Interpolator() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + _classCallCheck(this, Interpolator); + this.logger = baseLogger.create('interpolator'); + this.options = options; + this.format = options.interpolation && options.interpolation.format || function (value) { + return value; + }; + this.init(options); + } /* eslint no-param-reassign: 0 */ + + _createClass(Interpolator, [ + { + key: 'init', + value: function init() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + if (!options.interpolation) options.interpolation = { + escapeValue: true + }; + var iOpts = options.interpolation; + this.escape = iOpts.escape !== undefined ? iOpts.escape : escape; + this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true; + this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false; + this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{'; + this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}'; + this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ','; + this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-'; + this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || ''; + this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t('); + this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')'); + this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000; // the regexp + this.resetRegExp(); + } + }, + { + key: 'reset', + value: function reset() { + if (this.options) this.init(this.options); + } + }, + { + key: 'resetRegExp', + value: function resetRegExp() { + // the regexp + var regexpStr = ''.concat(this.prefix, '(.+?)').concat(this.suffix); + this.regexp = new RegExp(regexpStr, 'g'); + var regexpUnescapeStr = ''.concat(this.prefix).concat(this.unescapePrefix, '(.+?)').concat(this.unescapeSuffix).concat(this.suffix); + this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g'); + var nestingRegexpStr = ''.concat(this.nestingPrefix, '(.+?)').concat(this.nestingSuffix); + this.nestingRegexp = new RegExp(nestingRegexpStr, 'g'); + } + }, + { + key: 'interpolate', + value: function interpolate(str, data, lng, options) { + var _this = this; + var match; + var value; + var replaces; + var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || { + }; + function regexSafe(val) { + return val.replace(/\$/g, '$$$$'); + } + var handleFormat = function handleFormat(key) { + if (key.indexOf(_this.formatSeparator) < 0) { + return getPathWithDefaults(data, defaultData, key); + } + var p = key.split(_this.formatSeparator); + var k = p.shift().trim(); + var f = p.join(_this.formatSeparator).trim(); + return _this.format(getPathWithDefaults(data, defaultData, k), f, lng); + }; + this.resetRegExp(); + var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler; + replaces = 0; // unescape if has unescapePrefix/Suffix + /* eslint no-cond-assign: 0 */ + while (match = this.regexpUnescape.exec(str)) { + value = handleFormat(match[1].trim()); + if (value === undefined) { + if (typeof missingInterpolationHandler === 'function') { + var temp = missingInterpolationHandler(str, match, options); + value = typeof temp === 'string' ? temp : ''; + } else { + this.logger.warn('missed to pass in variable '.concat(match[1], ' for interpolating ').concat(str)); + value = ''; + } + } else if (typeof value !== 'string' && !this.useRawValueToEscape) { + value = makeString(value); + } + str = str.replace(match[0], regexSafe(value)); + this.regexpUnescape.lastIndex = 0; + replaces++; + if (replaces >= this.maxReplaces) { + break; + } + } + replaces = 0; // regular escape on demand + while (match = this.regexp.exec(str)) { + value = handleFormat(match[1].trim()); + if (value === undefined) { + if (typeof missingInterpolationHandler === 'function') { + var _temp = missingInterpolationHandler(str, match, options); + value = typeof _temp === 'string' ? _temp : ''; + } else { + this.logger.warn('missed to pass in variable '.concat(match[1], ' for interpolating ').concat(str)); + value = ''; + } + } else if (typeof value !== 'string' && !this.useRawValueToEscape) { + value = makeString(value); + } + value = this.escapeValue ? regexSafe(this.escape(value)) : regexSafe(value); + str = str.replace(match[0], value); + this.regexp.lastIndex = 0; + replaces++; + if (replaces >= this.maxReplaces) { + break; + } + } + return str; + } + }, + { + key: 'nest', + value: function nest(str, fc) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + }; + var match; + var value; + var clonedOptions = _objectSpread({ + }, options); + clonedOptions.applyPostProcessor = false; // avoid post processing on nested lookup + delete clonedOptions.defaultValue; // assert we do not get a endless loop on interpolating defaultValue again and again + // if value is something like "myKey": "lorem $(anotherKey, { "count": {{aValueInOptions}} })" + function handleHasOptions(key, inheritedOptions) { + if (key.indexOf(',') < 0) return key; + var p = key.split(','); + key = p.shift(); + var optionsString = p.join(','); + optionsString = this.interpolate(optionsString, clonedOptions); + optionsString = optionsString.replace(/'/g, '"'); + try { + clonedOptions = JSON.parse(optionsString); + if (inheritedOptions) clonedOptions = _objectSpread({ + }, inheritedOptions, clonedOptions); + } catch (e) { + this.logger.error('failed parsing options string in nesting for key '.concat(key), e); + } // assert we do not get a endless loop on interpolating defaultValue again and again + + delete clonedOptions.defaultValue; + return key; + } // regular escape on demand + + while (match = this.nestingRegexp.exec(str)) { + value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions); // is only the nesting key (key1 = '$(key2)') return the value without stringify + if (value && match[0] === str && typeof value !== 'string') return value; // no string to include or empty + if (typeof value !== 'string') value = makeString(value); + if (!value) { + this.logger.warn('missed to resolve '.concat(match[1], ' for nesting ').concat(str)); + value = ''; + } // Nested keys should not be escaped by default #854 + // value = this.escapeValue ? regexSafe(utils.escape(value)) : regexSafe(value); + + str = str.replace(match[0], value); + this.regexp.lastIndex = 0; + } + return str; + } + } + ]); + return Interpolator; + }(); + function remove(arr, what) { + var found = arr.indexOf(what); + while (found !== - 1) { + arr.splice(found, 1); + found = arr.indexOf(what); + } + } + var Connector = /*#__PURE__*/ + function (_EventEmitter) { + _inherits(Connector, _EventEmitter); + function Connector(backend, store, services) { + var _this; + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { + }; + _classCallCheck(this, Connector); + _this = _possibleConstructorReturn(this, _getPrototypeOf(Connector).call(this)); + EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor) + _this.backend = backend; + _this.store = store; + _this.services = services; + _this.languageUtils = services.languageUtils; + _this.options = options; + _this.logger = baseLogger.create('backendConnector'); + _this.state = { + }; + _this.queue = [ + ]; + if (_this.backend && _this.backend.init) { + _this.backend.init(services, options.backend, options); + } + return _this; + } + _createClass(Connector, [ + { + key: 'queueLoad', + value: function queueLoad(languages, namespaces, options, callback) { + var _this2 = this; + // find what needs to be loaded + var toLoad = [ + ]; + var pending = [ + ]; + var toLoadLanguages = [ + ]; + var toLoadNamespaces = [ + ]; + languages.forEach(function (lng) { + var hasAllNamespaces = true; + namespaces.forEach(function (ns) { + var name = ''.concat(lng, '|').concat(ns); + if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) { + _this2.state[name] = 2; // loaded + } else if (_this2.state[name] < 0); + else if (_this2.state[name] === 1) { + if (pending.indexOf(name) < 0) pending.push(name); + } else { + _this2.state[name] = 1; // pending + hasAllNamespaces = false; + if (pending.indexOf(name) < 0) pending.push(name); + if (toLoad.indexOf(name) < 0) toLoad.push(name); + if (toLoadNamespaces.indexOf(ns) < 0) toLoadNamespaces.push(ns); + } + }); + if (!hasAllNamespaces) toLoadLanguages.push(lng); + }); + if (toLoad.length || pending.length) { + this.queue.push({ + pending: pending, + loaded: { + }, + errors: [ + ], + callback: callback + }); + } + return { + toLoad: toLoad, + pending: pending, + toLoadLanguages: toLoadLanguages, + toLoadNamespaces: toLoadNamespaces + }; + } + }, + { + key: 'loaded', + value: function loaded(name, err, data) { + var _name$split = name.split('|'), + _name$split2 = _slicedToArray(_name$split, 2), + lng = _name$split2[0], + ns = _name$split2[1]; + if (err) this.emit('failedLoading', lng, ns, err); + if (data) { + this.store.addResourceBundle(lng, ns, data); + } // set loaded + + this.state[name] = err ? - 1 : 2; // consolidated loading done in this run - only emit once for a loaded namespace + var loaded = { + }; // callback if ready + this.queue.forEach(function (q) { + pushPath(q.loaded, [ + lng + ], ns); + remove(q.pending, name); + if (err) q.errors.push(err); + if (q.pending.length === 0 && !q.done) { + // only do once per loaded -> this.emit('loaded', q.loaded); + Object.keys(q.loaded).forEach(function (l) { + if (!loaded[l]) loaded[l] = [ + ]; + if (q.loaded[l].length) { + q.loaded[l].forEach(function (ns) { + if (loaded[l].indexOf(ns) < 0) loaded[l].push(ns); + }); + } + }); + /* eslint no-param-reassign: 0 */ + q.done = true; + if (q.errors.length) { + q.callback(q.errors); + } else { + q.callback(); + } + } + }); // emit consolidated loaded event + this.emit('loaded', loaded); // remove done load requests + this.queue = this.queue.filter(function (q) { + return !q.done; + }); + } + }, + { + key: 'read', + value: function read(lng, ns, fcName) { + var _this3 = this; + var tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 250; + var callback = arguments.length > 5 ? arguments[5] : undefined; + if (!lng.length) return callback(null, { + }); // noting to load + return this.backend[fcName](lng, ns, function (err, data) { + if (err && data /* = retryFlag */ && tried < 5) { + setTimeout(function () { + _this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback); + }, wait); + return; + } + callback(err, data); + }); + } /* eslint consistent-return: 0 */ + + }, + { + key: 'prepareLoading', + value: function prepareLoading(languages, namespaces) { + var _this4 = this; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + }; + var callback = arguments.length > 3 ? arguments[3] : undefined; + if (!this.backend) { + this.logger.warn('No backend was added via i18next.use. Will not load resources.'); + return callback && callback(); + } + if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages); + if (typeof namespaces === 'string') namespaces = [ + namespaces + ]; + var toLoad = this.queueLoad(languages, namespaces, options, callback); + if (!toLoad.toLoad.length) { + if (!toLoad.pending.length) callback(); // nothing to load and no pendings...callback now + return null; // pendings will trigger callback + } + toLoad.toLoad.forEach(function (name) { + _this4.loadOne(name); + }); + } + }, + { + key: 'load', + value: function load(languages, namespaces, callback) { + this.prepareLoading(languages, namespaces, { + }, callback); + } + }, + { + key: 'reload', + value: function reload(languages, namespaces, callback) { + this.prepareLoading(languages, namespaces, { + reload: true + }, callback); + } + }, + { + key: 'loadOne', + value: function loadOne(name) { + var _this5 = this; + var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + var _name$split3 = name.split('|'), + _name$split4 = _slicedToArray(_name$split3, 2), + lng = _name$split4[0], + ns = _name$split4[1]; + this.read(lng, ns, 'read', null, null, function (err, data) { + if (err) _this5.logger.warn(''.concat(prefix, 'loading namespace ').concat(ns, ' for language ').concat(lng, ' failed'), err); + if (!err && data) _this5.logger.log(''.concat(prefix, 'loaded namespace ').concat(ns, ' for language ').concat(lng), data); + _this5.loaded(name, err, data); + }); + } + }, + { + key: 'saveMissing', + value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) { + var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : { + }; + if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) { + this.logger.warn('did not save key "'.concat(key, '" for namespace "').concat(namespace, '" as the namespace was not yet loaded'), 'This means something IS WRONG in your application setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!'); + return; + } // ignore non valid keys + + if (key === undefined || key === null || key === '') return; + if (this.backend && this.backend.create) { + this.backend.create(languages, namespace, key, fallbackValue, null /* unused callback */ , _objectSpread({ + }, options, { + isUpdate: isUpdate + })); + } // write to store to avoid resending + + if (!languages || !languages[0]) return; + this.store.addResource(languages[0], namespace, key, fallbackValue); + } + } + ]); + return Connector; + }(EventEmitter); + function get() { + return { + debug: false, + initImmediate: true, + ns: [ + 'translation' + ], + defaultNS: [ + 'translation' + ], + fallbackLng: [ + 'dev' + ], + fallbackNS: false, + // string or array of namespaces + whitelist: false, + // array with whitelisted languages + nonExplicitWhitelist: false, + load: 'all', + // | currentOnly | languageOnly + preload: false, + // array with preload languages + simplifyPluralSuffix: true, + keySeparator: '.', + nsSeparator: ':', + pluralSeparator: '_', + contextSeparator: '_', + partialBundledLanguages: false, + // allow bundling certain languages that are not remotely fetched + saveMissing: false, + // enable to send missing values + updateMissing: false, + // enable to update default values if different from translated value (only useful on initial development, or when keeping code as source of truth) + saveMissingTo: 'fallback', + // 'current' || 'all' + saveMissingPlurals: true, + // will save all forms not only singular key + missingKeyHandler: false, + // function(lng, ns, key, fallbackValue) -> override if prefer on handling + missingInterpolationHandler: false, + // function(str, match) + postProcess: false, + // string or array of postProcessor names + postProcessPassResolved: false, + // pass resolved object into 'options.i18nResolved' for postprocessor + returnNull: true, + // allows null value as valid translation + returnEmptyString: true, + // allows empty string value as valid translation + returnObjects: false, + joinArrays: false, + // or string to join array + returnedObjectHandler: false, + // function(key, value, options) triggered if key returns object but returnObjects is set to false + parseMissingKeyHandler: false, + // function(key) parsed a key that was not found in t() before returning + appendNamespaceToMissingKey: false, + appendNamespaceToCIMode: false, + overloadTranslationOptionHandler: function handle(args) { + var ret = { + }; + if (_typeof(args[1]) === 'object') ret = args[1]; + if (typeof args[1] === 'string') ret.defaultValue = args[1]; + if (typeof args[2] === 'string') ret.tDescription = args[2]; + if (_typeof(args[2]) === 'object' || _typeof(args[3]) === 'object') { + var options = args[3] || args[2]; + Object.keys(options).forEach(function (key) { + ret[key] = options[key]; + }); + } + return ret; + }, + interpolation: { + escapeValue: true, + format: function format(value, _format, lng) { + return value; + }, + prefix: '{{', + suffix: '}}', + formatSeparator: ',', + // prefixEscaped: '{{', + // suffixEscaped: '}}', + // unescapeSuffix: '', + unescapePrefix: '-', + nestingPrefix: '$t(', + nestingSuffix: ')', + // nestingPrefixEscaped: '$t(', + // nestingSuffixEscaped: ')', + // defaultVariables: undefined // object that can have values to interpolate on - extends passed in interpolation data + maxReplaces: 1000 // max replaces to prevent endless loop + } + }; + } /* eslint no-param-reassign: 0 */ + + function transformOptions(options) { + // create namespace object if namespace is passed in as string + if (typeof options.ns === 'string') options.ns = [ + options.ns + ]; + if (typeof options.fallbackLng === 'string') options.fallbackLng = [ + options.fallbackLng + ]; + if (typeof options.fallbackNS === 'string') options.fallbackNS = [ + options.fallbackNS + ]; // extend whitelist with cimode + if (options.whitelist && options.whitelist.indexOf('cimode') < 0) { + options.whitelist = options.whitelist.concat(['cimode']); + } + return options; + } + function noop() { + } + var I18n = /*#__PURE__*/ + function (_EventEmitter) { + _inherits(I18n, _EventEmitter); + function I18n() { + var _this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + var callback = arguments.length > 1 ? arguments[1] : undefined; + _classCallCheck(this, I18n); + _this = _possibleConstructorReturn(this, _getPrototypeOf(I18n).call(this)); + EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor) + _this.options = transformOptions(options); + _this.services = { + }; + _this.logger = baseLogger; + _this.modules = { + external: [ + ] + }; + if (callback && !_this.isInitialized && !options.isClone) { + // https://github.com/i18next/i18next/issues/879 + if (!_this.options.initImmediate) { + _this.init(options, callback); + return _possibleConstructorReturn(_this, _assertThisInitialized(_this)); + } + setTimeout(function () { + _this.init(options, callback); + }, 0); + } + return _this; + } + _createClass(I18n, [ + { + key: 'init', + value: function init() { + var _this2 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + var callback = arguments.length > 1 ? arguments[1] : undefined; + if (typeof options === 'function') { + callback = options; + options = { + }; + } + this.options = _objectSpread({ + }, get(), this.options, transformOptions(options)); + this.format = this.options.interpolation.format; + if (!callback) callback = noop; + function createClassOnDemand(ClassOrObject) { + if (!ClassOrObject) return null; + if (typeof ClassOrObject === 'function') return new ClassOrObject(); + return ClassOrObject; + } // init services + + if (!this.options.isClone) { + if (this.modules.logger) { + baseLogger.init(createClassOnDemand(this.modules.logger), this.options); + } else { + baseLogger.init(null, this.options); + } + var lu = new LanguageUtil(this.options); + this.store = new ResourceStore(this.options.resources, this.options); + var s = this.services; + s.logger = baseLogger; + s.resourceStore = this.store; + s.languageUtils = lu; + s.pluralResolver = new PluralResolver(lu, { + prepend: this.options.pluralSeparator, + compatibilityJSON: this.options.compatibilityJSON, + simplifyPluralSuffix: this.options.simplifyPluralSuffix + }); + s.interpolator = new Interpolator(this.options); + s.utils = { + hasLoadedNamespace: this.hasLoadedNamespace.bind(this) + }; + s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options); // pipe events from backendConnector + s.backendConnector.on('*', function (event) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + _this2.emit.apply(_this2, [ + event + ].concat(args)); + }); + if (this.modules.languageDetector) { + s.languageDetector = createClassOnDemand(this.modules.languageDetector); + s.languageDetector.init(s, this.options.detection, this.options); + } + if (this.modules.i18nFormat) { + s.i18nFormat = createClassOnDemand(this.modules.i18nFormat); + if (s.i18nFormat.init) s.i18nFormat.init(this); + } + this.translator = new Translator(this.services, this.options); // pipe events from translator + this.translator.on('*', function (event) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + _this2.emit.apply(_this2, [ + event + ].concat(args)); + }); + this.modules.external.forEach(function (m) { + if (m.init) m.init(_this2); + }); + } // append api + + var storeApi = [ + 'getResource', + 'addResource', + 'addResources', + 'addResourceBundle', + 'removeResourceBundle', + 'hasResourceBundle', + 'getResourceBundle', + 'getDataByLanguage' + ]; + storeApi.forEach(function (fcName) { + _this2[fcName] = function () { + var _this2$store; + return (_this2$store = _this2.store) [fcName].apply(_this2$store, arguments); + }; + }); + var deferred = defer(); + var load = function load() { + _this2.changeLanguage(_this2.options.lng, function (err, t) { + _this2.isInitialized = true; + _this2.logger.log('initialized', _this2.options); + _this2.emit('initialized', _this2.options); + deferred.resolve(t); // not rejecting on err (as err is only a loading translation failed warning) + callback(err, t); + }); + }; + if (this.options.resources || !this.options.initImmediate) { + load(); + } else { + setTimeout(load, 0); + } + return deferred; + } /* eslint consistent-return: 0 */ + + }, + { + key: 'loadResources', + value: function loadResources(language) { + var _this3 = this; + var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop; + var usedCallback = callback; + var usedLng = typeof language === 'string' ? language : this.language; + if (typeof language === 'function') usedCallback = language; + if (!this.options.resources || this.options.partialBundledLanguages) { + if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback(); // avoid loading resources for cimode + var toLoad = [ + ]; + var append = function append(lng) { + if (!lng) return; + var lngs = _this3.services.languageUtils.toResolveHierarchy(lng); + lngs.forEach(function (l) { + if (toLoad.indexOf(l) < 0) toLoad.push(l); + }); + }; + if (!usedLng) { + // at least load fallbacks in this case + var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); + fallbacks.forEach(function (l) { + return append(l); + }); + } else { + append(usedLng); + } + if (this.options.preload) { + this.options.preload.forEach(function (l) { + return append(l); + }); + } + this.services.backendConnector.load(toLoad, this.options.ns, usedCallback); + } else { + usedCallback(null); + } + } + }, + { + key: 'reloadResources', + value: function reloadResources(lngs, ns, callback) { + var deferred = defer(); + if (!lngs) lngs = this.languages; + if (!ns) ns = this.options.ns; + if (!callback) callback = noop; + this.services.backendConnector.reload(lngs, ns, function (err) { + deferred.resolve(); // not rejecting on err (as err is only a loading translation failed warning) + callback(err); + }); + return deferred; + } + }, + { + key: 'use', + value: function use(module) { + if (module.type === 'backend') { + this.modules.backend = module; + } + if (module.type === 'logger' || module.log && module.warn && module.error) { + this.modules.logger = module; + } + if (module.type === 'languageDetector') { + this.modules.languageDetector = module; + } + if (module.type === 'i18nFormat') { + this.modules.i18nFormat = module; + } + if (module.type === 'postProcessor') { + postProcessor.addPostProcessor(module); + } + if (module.type === '3rdParty') { + this.modules.external.push(module); + } + return this; + } + }, + { + key: 'changeLanguage', + value: function changeLanguage(lng, callback) { + var _this4 = this; + this.isLanguageChangingTo = lng; + var deferred = defer(); + this.emit('languageChanging', lng); + var done = function done(err, l) { + if (l) { + _this4.language = l; + _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l); + _this4.translator.changeLanguage(l); + _this4.isLanguageChangingTo = undefined; + _this4.emit('languageChanged', l); + _this4.logger.log('languageChanged', l); + } else { + _this4.isLanguageChangingTo = undefined; + } + deferred.resolve(function () { + return _this4.t.apply(_this4, arguments); + }); + if (callback) callback(err, function () { + return _this4.t.apply(_this4, arguments); + }); + }; + var setLng = function setLng(l) { + if (l) { + if (!_this4.language) { + _this4.language = l; + _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l); + } + if (!_this4.translator.language) _this4.translator.changeLanguage(l); + if (_this4.services.languageDetector) _this4.services.languageDetector.cacheUserLanguage(l); + } + _this4.loadResources(l, function (err) { + done(err, l); + }); + }; + if (!lng && this.services.languageDetector && !this.services.languageDetector.async) { + setLng(this.services.languageDetector.detect()); + } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) { + this.services.languageDetector.detect(setLng); + } else { + setLng(lng); + } + return deferred; + } + }, + { + key: 'getFixedT', + value: function getFixedT(lng, ns) { + var _this5 = this; + var fixedT = function fixedT(key, opts) { + var options; + if (_typeof(opts) !== 'object') { + for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { + rest[_key3 - 2] = arguments[_key3]; + } + options = _this5.options.overloadTranslationOptionHandler([key, + opts].concat(rest)); + } else { + options = _objectSpread({ + }, opts); + } + options.lng = options.lng || fixedT.lng; + options.lngs = options.lngs || fixedT.lngs; + options.ns = options.ns || fixedT.ns; + return _this5.t(key, options); + }; + if (typeof lng === 'string') { + fixedT.lng = lng; + } else { + fixedT.lngs = lng; + } + fixedT.ns = ns; + return fixedT; + } + }, + { + key: 't', + value: function t() { + var _this$translator; + return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments); + } + }, + { + key: 'exists', + value: function exists() { + var _this$translator2; + return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments); + } + }, + { + key: 'setDefaultNamespace', + value: function setDefaultNamespace(ns) { + this.options.defaultNS = ns; + } + }, + { + key: 'hasLoadedNamespace', + value: function hasLoadedNamespace(ns) { + var _this6 = this; + if (!this.isInitialized) { + this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages); + return false; + } + if (!this.languages || !this.languages.length) { + this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages); + return false; + } + var lng = this.languages[0]; + var fallbackLng = this.options ? this.options.fallbackLng : false; + var lastLng = this.languages[this.languages.length - 1]; // we're in cimode so this shall pass + if (lng.toLowerCase() === 'cimode') return true; + var loadNotPending = function loadNotPending(l, n) { + var loadState = _this6.services.backendConnector.state[''.concat(l, '|').concat(n)]; + return loadState === - 1 || loadState === 2; + }; // loaded -> SUCCESS + if (this.hasResourceBundle(lng, ns)) return true; // were not loading at all -> SEMI SUCCESS + if (!this.services.backendConnector.backend) return true; // failed loading ns - but at least fallback is not pending -> SEMI SUCCESS + if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true; + return false; + } + }, + { + key: 'loadNamespaces', + value: function loadNamespaces(ns, callback) { + var _this7 = this; + var deferred = defer(); + if (!this.options.ns) { + callback && callback(); + return Promise.resolve(); + } + if (typeof ns === 'string') ns = [ + ns + ]; + ns.forEach(function (n) { + if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n); + }); + this.loadResources(function (err) { + deferred.resolve(); + if (callback) callback(err); + }); + return deferred; + } + }, + { + key: 'loadLanguages', + value: function loadLanguages(lngs, callback) { + var deferred = defer(); + if (typeof lngs === 'string') lngs = [ + lngs + ]; + var preloaded = this.options.preload || [ + ]; + var newLngs = lngs.filter(function (lng) { + return preloaded.indexOf(lng) < 0; + }); // Exit early if all given languages are already preloaded + if (!newLngs.length) { + if (callback) callback(); + return Promise.resolve(); + } + this.options.preload = preloaded.concat(newLngs); + this.loadResources(function (err) { + deferred.resolve(); + if (callback) callback(err); + }); + return deferred; + } + }, + { + key: 'dir', + value: function dir(lng) { + if (!lng) lng = this.languages && this.languages.length > 0 ? this.languages[0] : this.language; + if (!lng) return 'rtl'; + var rtlLngs = [ + 'ar', + 'shu', + 'sqr', + 'ssh', + 'xaa', + 'yhd', + 'yud', + 'aao', + 'abh', + 'abv', + 'acm', + 'acq', + 'acw', + 'acx', + 'acy', + 'adf', + 'ads', + 'aeb', + 'aec', + 'afb', + 'ajp', + 'apc', + 'apd', + 'arb', + 'arq', + 'ars', + 'ary', + 'arz', + 'auz', + 'avl', + 'ayh', + 'ayl', + 'ayn', + 'ayp', + 'bbz', + 'pga', + 'he', + 'iw', + 'ps', + 'pbt', + 'pbu', + 'pst', + 'prp', + 'prd', + 'ur', + 'ydd', + 'yds', + 'yih', + 'ji', + 'yi', + 'hbo', + 'men', + 'xmn', + 'fa', + 'jpr', + 'peo', + 'pes', + 'prs', + 'dv', + 'sam' + ]; + return rtlLngs.indexOf(this.services.languageUtils.getLanguagePartFromCode(lng)) >= 0 ? 'rtl' : 'ltr'; + } /* eslint class-methods-use-this: 0 */ + + }, + { + key: 'createInstance', + value: function createInstance() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + var callback = arguments.length > 1 ? arguments[1] : undefined; + return new I18n(options, callback); + } + }, + { + key: 'cloneInstance', + value: function cloneInstance() { + var _this8 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop; + var mergedOptions = _objectSpread({ + }, this.options, options, { + isClone: true + }); + var clone = new I18n(mergedOptions); + var membersToCopy = [ + 'store', + 'services', + 'language' + ]; + membersToCopy.forEach(function (m) { + clone[m] = _this8[m]; + }); + clone.translator = new Translator(clone.services, clone.options); + clone.translator.on('*', function (event) { + for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + clone.emit.apply(clone, [ + event + ].concat(args)); + }); + clone.init(mergedOptions, callback); + clone.translator.options = clone.options; // sync options + return clone; + } + } + ]); + return I18n; + }(EventEmitter); + var i18next = new I18n(); + module.exports = i18next; + }, + { + '@babel/runtime/helpers/assertThisInitialized': 4, + '@babel/runtime/helpers/classCallCheck': 5, + '@babel/runtime/helpers/createClass': 6, + '@babel/runtime/helpers/getPrototypeOf': 8, + '@babel/runtime/helpers/inherits': 9, + '@babel/runtime/helpers/objectSpread': 14, + '@babel/runtime/helpers/possibleConstructorReturn': 15, + '@babel/runtime/helpers/slicedToArray': 17, + '@babel/runtime/helpers/toConsumableArray': 18, + '@babel/runtime/helpers/typeof': 19 + } + ], + 273: [ + function (_dereq_, module, exports) { + exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, + m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = - 7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? - 1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << - nBits) - 1; + s >>= - nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) { + } + m = e & (1 << - nBits) - 1; + e >>= - nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) { + } + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? - 1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? - 1 : 1) * m * Math.pow(2, e - mLen); + }; + exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, + m, + c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, - 24) - Math.pow(2, - 77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : - 1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, - e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { + } + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { + } + buffer[offset + i - d] |= s * 128; + }; + }, + { + } + ], + 274: [ + function (_dereq_, module, exports) { + /* + + Copyright 2000, Silicon Graphics, Inc. All Rights Reserved. + Copyright 2015, Google Inc. All Rights Reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice including the dates of first publication and + either this permission notice or a reference to http://oss.sgi.com/projects/FreeB/ + shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + Original Code. The Original Code is: OpenGL Sample Implementation, + Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, + Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. + Copyright in any portions created by third parties is as indicated + elsewhere herein. All Rights Reserved. +*/ + 'use strict'; + var n; + function t(a, b) { + return a.b === b.b && a.a === b.a; + } + function u(a, b) { + return a.b < b.b || a.b === b.b && a.a <= b.a; + } + function v(a, b, c) { + var d = b.b - a.b, + e = c.b - b.b; + return 0 < d + e ? d < e ? b.a - a.a + d / (d + e) * (a.a - c.a) : b.a - c.a + e / (d + e) * (c.a - a.a) : 0; + } + function x(a, b, c) { + var d = b.b - a.b, + e = c.b - b.b; + return 0 < d + e ? (b.a - c.a) * d + (b.a - a.a) * e : 0; + } + function z(a, b) { + return a.a < b.a || a.a === b.a && a.b <= b.b; + } + function aa(a, b, c) { + var d = b.a - a.a, + e = c.a - b.a; + return 0 < d + e ? d < e ? b.b - a.b + d / (d + e) * (a.b - c.b) : b.b - c.b + e / (d + e) * (c.b - a.b) : 0; + } + function ba(a, b, c) { + var d = b.a - a.a, + e = c.a - b.a; + return 0 < d + e ? (b.b - c.b) * d + (b.b - a.b) * e : 0; + } + function ca(a) { + return u(a.b.a, a.a); + } + function da(a) { + return u(a.a, a.b.a); + } + function A(a, b, c, d) { + a = 0 > a ? 0 : a; + c = 0 > c ? 0 : c; + return a <= c ? 0 === c ? (b + d) / 2 : b + a / (a + c) * (d - b) : d + c / (a + c) * (b - d); + } + ; + function ea(a) { + var b = B(a.b); + C(b, a.c); + C(b.b, a.c); + D(b, a.a); + return b; + } + function E(a, b) { + var c = !1, + d = !1; + a !== b && (b.a !== a.a && (d = !0, F(b.a, a.a)), b.d !== a.d && (c = !0, G(b.d, a.d)), H(b, a), d || (C(b, a.a), a.a.c = a), c || (D(b, a.d), a.d.a = a)); + } + function I(a) { + var b = a.b, + c = !1; + a.d !== a.b.d && (c = !0, G(a.d, a.b.d)); + a.c === a ? F(a.a, null) : (a.b.d.a = J(a), a.a.c = a.c, H(a, J(a)), c || D(a, a.d)); + b.c === b ? (F(b.a, null), G(b.d, null)) : (a.d.a = J(b), b.a.c = b.c, H(b, J(b))); + fa(a); + } + function K(a) { + var b = B(a), + c = b.b; + H(b, a.e); + b.a = a.b.a; + C(c, b.a); + b.d = c.d = a.d; + b = b.b; + H(a.b, J(a.b)); + H(a.b, b); + a.b.a = b.a; + b.b.a.c = b.b; + b.b.d = a.b.d; + b.f = a.f; + b.b.f = a.b.f; + return b; + } + function L(a, b) { + var c = !1, + d = B(a), + e = d.b; + b.d !== a.d && (c = !0, G(b.d, a.d)); + H(d, a.e); + H(e, b); + d.a = a.b.a; + e.a = b.a; + d.d = e.d = a.d; + a.d.a = e; + c || D(d, a.d); + return d; + } + function B(a) { + var b = new M(), + c = new M(), + d = a.b.h; + c.h = d; + d.b.h = b; + b.h = a; + a.b.h = c; + b.b = c; + b.c = b; + b.e = c; + c.b = b; + c.c = c; + return c.e = b; + } + function H(a, b) { + var c = a.c, + d = b.c; + c.b.e = b; + d.b.e = a; + a.c = d; + b.c = c; + } + function C(a, b) { + var c = b.f, + d = new N(b, c); + c.e = d; + b.f = d; + c = d.c = a; + do c.a = d, + c = c.c; + while (c !== a); + } + function D(a, b) { + var c = b.d, + d = new ga(b, c); + c.b = d; + b.d = d; + d.a = a; + d.c = b.c; + c = a; + do c.d = d, + c = c.e; + while (c !== a); + } + function fa(a) { + var b = a.h; + a = a.b.h; + b.b.h = a; + a.b.h = b; + } + function F(a, b) { + var c = a.c, + d = c; + do d.a = b, + d = d.c; + while (d !== c); + c = a.f; + d = a.e; + d.f = c; + c.e = d; + } + function G(a, b) { + var c = a.a, + d = c; + do d.d = b, + d = d.e; + while (d !== c); + c = a.d; + d = a.b; + d.d = c; + c.b = d; + } + ; + function ha(a) { + var b = 0; + Math.abs(a[1]) > Math.abs(a[0]) && (b = 1); + Math.abs(a[2]) > Math.abs(a[b]) && (b = 2); + return b; + } + ; + var O = 4 * 1e+150; + function P(a, b) { + a.f += b.f; + a.b.f += b.b.f; + } + function ia(a, b, c) { + a = a.a; + b = b.a; + c = c.a; + if (b.b.a === a) return c.b.a === a ? u(b.a, c.a) ? 0 >= x(c.b.a, b.a, c.a) : 0 <= x(b.b.a, c.a, b.a) : 0 >= x(c.b.a, a, c.a); + if (c.b.a === a) return 0 <= x(b.b.a, a, b.a); + b = v(b.b.a, a, b.a); + a = v(c.b.a, a, c.a); + return b >= a; + } + function Q(a) { + a.a.i = null; + var b = a.e; + b.a.c = b.c; + b.c.a = b.a; + a.e = null; + } + function ja(a, b) { + I(a.a); + a.c = !1; + a.a = b; + b.i = a; + } + function ka(a) { + var b = a.a.a; + do a = R(a); + while (a.a.a === b); + a.c && (b = L(S(a).a.b, a.a.e), ja(a, b), a = R(a)); + return a; + } + function la(a, b, c) { + var d = new ma(); + d.a = c; + d.e = na(a.f, b.e, d); + return c.i = d; + } + function oa(a, b) { + switch (a.s) { + case 100130: + return 0 !== (b & 1); + case 100131: + return 0 !== b; + case 100132: + return 0 < b; + case 100133: + return 0 > b; + case 100134: + return 2 <= b || - 2 >= b; + } + return !1; + } + function pa(a) { + var b = a.a, + c = b.d; + c.c = a.d; + c.a = b; + Q(a); + } + function T(a, b, c) { + a = b; + for (b = b.a; a !== c; ) { + a.c = !1; + var d = S(a), + e = d.a; + if (e.a !== b.a) { + if (!d.c) { + pa(a); + break; + } + e = L(b.c.b, e.b); + ja(d, e); + } + b.c !== e && (E(J(e), e), E(b, e)); + pa(a); + b = d.a; + a = d; + } + return b; + } + function U(a, b, c, d, e, f) { + var g = !0; + do la(a, b, c.b), + c = c.c; + while (c !== d); + for (null === e && (e = S(b).a.b.c); ; ) { + d = S(b); + c = d.a.b; + if (c.a !== e.a) break; + c.c !== e && (E(J(c), c), E(J(e), c)); + d.f = b.f - c.f; + d.d = oa(a, d.f); + b.b = !0; + !g && qa(a, b) && (P(c, e), Q(b), I(e)); + g = !1; + b = d; + e = c; + } + b.b = !0; + f && ra(a, b); + } + function sa(a, b, c, d, e) { + var f = [ + b.g[0], + b.g[1], + b.g[2] + ]; + b.d = null; + b.d = a.o ? a.o(f, c, d, a.c) || null : null; + null === b.d && (e ? a.n || (V(a, 100156), a.n = !0) : b.d = c[0]); + } + function ta(a, b, c) { + var d = [ + null, + null, + null, + null + ]; + d[0] = b.a.d; + d[1] = c.a.d; + sa(a, b.a, d, [ + 0.5, + 0.5, + 0, + 0 + ], !1); + E(b, c); + } + function ua(a, b, c, d, e) { + var f = Math.abs(b.b - a.b) + Math.abs(b.a - a.a), + g = Math.abs(c.b - a.b) + Math.abs(c.a - a.a), + h = e + 1; + d[e] = 0.5 * g / (f + g); + d[h] = 0.5 * f / (f + g); + a.g[0] += d[e] * b.g[0] + d[h] * c.g[0]; + a.g[1] += d[e] * b.g[1] + d[h] * c.g[1]; + a.g[2] += d[e] * b.g[2] + d[h] * c.g[2]; + } + function qa(a, b) { + var c = S(b), + d = b.a, + e = c.a; + if (u(d.a, e.a)) { + if (0 < x(e.b.a, d.a, e.a)) return !1; + if (!t(d.a, e.a)) K(e.b), + E(d, J(e)), + b.b = c.b = !0; + else if (d.a !== e.a) { + var c = a.e, + f = d.a.h; + if (0 <= f) { + var c = c.b, + g = c.d, + h = c.e, + k = c.c, + l = k[f]; + g[l] = g[c.a]; + k[g[l]] = l; + l <= --c.a && (1 >= l ? W(c, l) : u(h[g[l >> 1]], h[g[l]]) ? W(c, l) : va(c, l)); + h[f] = null; + k[f] = c.b; + c.b = f; + } else for (c.c[ - (f + 1)] = null; 0 < c.a && null === c.c[c.d[c.a - 1]]; ) --c.a; + ta(a, J(e), d); + } + } else { + if (0 > x(d.b.a, e.a, d.a)) return !1; + R(b).b = b.b = !0; + K(d.b); + E(J(e), d); + } + return !0; + } + function wa(a, b) { + var c = S(b), + d = b.a, + e = c.a, + f = d.a, + g = e.a, + h = d.b.a, + k = e.b.a, + l = new N(); + x(h, a.a, f); + x(k, a.a, g); + if (f === g || Math.min(f.a, h.a) > Math.max(g.a, k.a)) return !1; + if (u(f, g)) { + if (0 < x(k, f, g)) return !1; + } else if (0 > x(h, g, f)) return !1; + var r = h, + p = f, + q = k, + y = g, + m, + w; + u(r, p) || (m = r, r = p, p = m); + u(q, y) || (m = q, q = y, y = m); + u(r, q) || (m = r, r = q, q = m, m = p, p = y, y = m); + u(q, p) ? u(p, y) ? (m = v(r, q, p), w = v(q, p, y), 0 > m + w && (m = - m, w = - w), l.b = A(m, q.b, w, p.b)) : (m = x(r, q, p), w = - x(r, y, p), 0 > m + w && (m = - m, w = - w), l.b = A(m, q.b, w, y.b)) : l.b = (q.b + p.b) / 2; + z(r, p) || (m = r, r = p, p = m); + z(q, y) || (m = q, q = y, y = m); + z(r, q) || (m = r, r = q, q = m, m = p, p = y, y = m); + z(q, p) ? z(p, y) ? (m = aa(r, q, p), w = aa(q, p, y), 0 > m + w && (m = - m, w = - w), l.a = A(m, q.a, w, p.a)) : (m = ba(r, q, p), w = - ba(r, y, p), 0 > m + w && (m = - m, w = - w), l.a = A(m, q.a, w, y.a)) : l.a = (q.a + p.a) / 2; + u(l, a.a) && (l.b = a.a.b, l.a = a.a.a); + r = u(f, g) ? f : g; + u(r, l) && (l.b = r.b, l.a = r.a); + if (t(l, f) || t(l, g)) return qa(a, b), + !1; + if (!t(h, a.a) && 0 <= x(h, a.a, l) || !t(k, a.a) && 0 >= x(k, a.a, l)) { + if (k === a.a) return K(d.b), + E(e.b, d), + b = ka(b), + d = S(b).a, + T(a, S(b), c), + U(a, b, J(d), d, d, !0), + !0; + if (h === a.a) { + K(e.b); + E(d.e, J(e)); + f = c = b; + g = f.a.b.a; + do f = R(f); + while (f.a.b.a === g); + b = f; + f = S(b).a.b.c; + c.a = J(e); + e = T(a, c, null); + U(a, b, e.c, d.b.c, f, !0); + return !0; + } + 0 <= x(h, a.a, l) && (R(b).b = b.b = !0, K(d.b), d.a.b = a.a.b, d.a.a = a.a.a); + 0 >= x(k, a.a, l) && (b.b = c.b = !0, K(e.b), e.a.b = a.a.b, e.a.a = a.a.a); + return !1; + } + K(d.b); + K(e.b); + E(J(e), d); + d.a.b = l.b; + d.a.a = l.a; + d.a.h = xa(a.e, d.a); + d = d.a; + e = [ + 0, + 0, + 0, + 0 + ]; + l = [ + f.d, + h.d, + g.d, + k.d + ]; + d.g[0] = d.g[1] = d.g[2] = 0; + ua(d, f, h, e, 0); + ua(d, g, k, e, 2); + sa(a, d, l, e, !0); + R(b).b = b.b = c.b = !0; + return !1; + } + function ra(a, b) { + for (var c = S(b); ; ) { + for (; c.b; ) b = c, + c = S(c); + if (!b.b && (c = b, b = R(b), null === b || !b.b)) break; + b.b = !1; + var d = b.a, + e = c.a, + f; + if (f = d.b.a !== e.b.a) a: { + f = b; + var g = S(f), + h = f.a, + k = g.a, + l = void 0; + if (u(h.b.a, k.b.a)) { + if (0 > x(h.b.a, k.b.a, h.a)) { + f = !1; + break a; + } + R(f).b = f.b = !0; + l = K(h); + E(k.b, l); + l.d.c = f.d; + } else { + if (0 < x(k.b.a, h.b.a, k.a)) { + f = !1; + break a; + } + f.b = g.b = !0; + l = K(k); + E(h.e, k.b); + l.b.d.c = f.d; + } + f = !0; + } + f && (c.c ? (Q(c), I(e), c = S(b), e = c.a) : b.c && (Q(b), I(d), b = R(c), d = b.a)); + if (d.a !== e.a) if (d.b.a === e.b.a || b.c || c.c || d.b.a !== a.a && e.b.a !== a.a) qa(a, b); + else if (wa(a, b)) break; + d.a === e.a && d.b.a === e.b.a && (P(e, d), Q(b), I(d), b = R(c)); + } + } + function ya(a, b) { + a.a = b; + for (var c = b.c; null === c.i; ) if (c = c.c, c === b.c) { + var c = a, + d = b, + e = new ma(); + e.a = d.c.b; + var f = c.f, + g = f.a; + do g = g.a; + while (null !== g.b && !f.c(f.b, e, g.b)); + var f = g.b, + h = S(f), + e = f.a, + g = h.a; + if (0 === x(e.b.a, d, e.a)) e = f.a, + t(e.a, d) || t(e.b.a, d) || (K(e.b), f.c && (I(e.c), f.c = !1), E(d.c, e), ya(c, d)); + else { + var k = u(g.b.a, e.b.a) ? f : h, + h = void 0; + f.d || k.c ? (k === f ? h = L(d.c.b, e.e) : h = L(g.b.c.b, d.c).b, k.c ? ja(k, h) : (e = c, f = la(c, f, h), f.f = R(f).f + f.a.f, f.d = oa(e, f.f)), ya(c, d)) : U(c, f, d.c, d.c, null, !0); + } + return; + } + c = ka(c.i); + e = S(c); + f = e.a; + e = T(a, e, null); + if (e.c === f) { + var f = e, + e = f.c, + g = S(c), + h = c.a, + k = g.a, + l = !1; + h.b.a !== k.b.a && wa(a, c); + t(h.a, a.a) && (E(J(e), h), c = ka(c), e = S(c).a, T(a, S(c), g), l = !0); + t(k.a, a.a) && (E(f, J(k)), f = T(a, g, null), l = !0); + l ? U(a, c, f.c, e, e, !0) : (u(k.a, h.a) ? d = J(k) : d = h, d = L(f.c.b, d), U(a, c, d, d.c, d.c, !1), d.b.i.c = !0, ra(a, c)); + } else U(a, c, e.c, f, f, !0); + } + function za(a, b) { + var c = new ma(), + d = ea(a.b); + d.a.b = O; + d.a.a = b; + d.b.a.b = - O; + d.b.a.a = b; + a.a = d.b.a; + c.a = d; + c.f = 0; + c.d = !1; + c.c = !1; + c.h = !0; + c.b = !1; + d = a.f; + d = na(d, d.a, c); + c.e = d; + } + ; + function Aa(a) { + this.a = new Ba(); + this.b = a; + this.c = ia; + } + function na(a, b, c) { + do b = b.c; + while (null !== b.b && !a.c(a.b, b.b, c)); + a = new Ba(c, b.a, b); + b.a.c = a; + return b.a = a; + } + ; + function Ba(a, b, c) { + this.b = a || null; + this.a = b || this; + this.c = c || this; + } + ; + function X() { + this.d = Y; + this.p = this.b = this.q = null; + this.j = [ + 0, + 0, + 0 + ]; + this.s = 100130; + this.n = !1; + this.o = this.a = this.e = this.f = null; + this.m = !1; + this.c = this.r = this.i = this.k = this.l = this.h = null; + } + var Y = 0; + n = X.prototype; + n.x = function () { + Z(this, Y); + }; + n.B = function (a, b) { + switch (a) { + case 100142: + return; + case 100140: + switch (b) { + case 100130: + case 100131: + case 100132: + case 100133: + case 100134: + this.s = b; + return; + } + break; + case 100141: + this.m = !!b; + return; + default: + V(this, 100900); + return; + } + V(this, 100901); + }; + n.y = function (a) { + switch (a) { + case 100142: + return 0; + case 100140: + return this.s; + case 100141: + return this.m; + default: + V(this, 100900); + } + return !1; + }; + n.A = function (a, b, c) { + this.j[0] = a; + this.j[1] = b; + this.j[2] = c; + }; + n.z = function (a, b) { + var c = b ? b : null; + switch (a) { + case 100100: + case 100106: + this.h = c; + break; + case 100104: + case 100110: + this.l = c; + break; + case 100101: + case 100107: + this.k = c; + break; + case 100102: + case 100108: + this.i = c; + break; + case 100103: + case 100109: + this.p = c; + break; + case 100105: + case 100111: + this.o = c; + break; + case 100112: + this.r = c; + break; + default: + V(this, 100900); + } + }; + n.C = function (a, b) { + var c = !1, + d = [ + 0, + 0, + 0 + ]; + Z(this, 2); + for (var e = 0; 3 > e; ++e) { + var f = a[e]; + - 1e+150 > f && (f = - 1e+150, c = !0); + 1e+150 < f && (f = 1e+150, c = !0); + d[e] = f; + } + c && V(this, 100155); + c = this.q; + null === c ? (c = ea(this.b), E(c, c.b)) : (K(c), c = c.e); + c.a.d = b; + c.a.g[0] = d[0]; + c.a.g[1] = d[1]; + c.a.g[2] = d[2]; + c.f = 1; + c.b.f = - 1; + this.q = c; + }; + n.u = function (a) { + Z(this, Y); + this.d = 1; + this.b = new Ca(); + this.c = a; + }; + n.t = function () { + Z(this, 1); + this.d = 2; + this.q = null; + }; + n.v = function () { + Z(this, 2); + this.d = 1; + }; + n.w = function () { + Z(this, 1); + this.d = Y; + var a = this.j[0], + b = this.j[1], + c = this.j[2], + d = !1, + e = [ + a, + b, + c + ]; + if (0 === a && 0 === b && 0 === c) { + for (var b = [ + - 2 * 1e+150, + - 2 * 1e+150, + - 2 * 1e+150 + ], f = [ + 2 * 1e+150, + 2 * 1e+150, + 2 * 1e+150 + ], c = [ + ], g = [ + ], d = this.b.c, a = d.e; a !== d; a = a.e) for (var h = 0; 3 > h; ++h) { + var k = a.g[h]; + k < f[h] && (f[h] = k, g[h] = a); + k > b[h] && (b[h] = k, c[h] = a); + } + a = 0; + b[1] - f[1] > b[0] - f[0] && (a = 1); + b[2] - f[2] > b[a] - f[a] && (a = 2); + if (f[a] >= b[a]) e[0] = 0, + e[1] = 0, + e[2] = 1; + else { + b = 0; + f = g[a]; + c = c[a]; + g = [ + 0, + 0, + 0 + ]; + f = [ + f.g[0] - c.g[0], + f.g[1] - c.g[1], + f.g[2] - c.g[2] + ]; + h = [ + 0, + 0, + 0 + ]; + for (a = d.e; a !== d; a = a.e) h[0] = a.g[0] - c.g[0], + h[1] = a.g[1] - c.g[1], + h[2] = a.g[2] - c.g[2], + g[0] = f[1] * h[2] - f[2] * h[1], + g[1] = f[2] * h[0] - f[0] * h[2], + g[2] = f[0] * h[1] - f[1] * h[0], + k = g[0] * g[0] + g[1] * g[1] + g[2] * g[2], + k > b && (b = k, e[0] = g[0], e[1] = g[1], e[2] = g[2]); + 0 >= b && (e[0] = e[1] = e[2] = 0, e[ha(f)] = 1); + } + d = !0; + } + g = ha(e); + a = this.b.c; + b = (g + 1) % 3; + c = (g + 2) % 3; + g = 0 < e[g] ? 1 : - 1; + for (e = a.e; e !== a; e = e.e) e.b = e.g[b], + e.a = g * e.g[c]; + if (d) { + e = 0; + d = this.b.a; + for (a = d.b; a !== d; a = a.b) if (b = a.a, !(0 >= b.f)) { + do e += (b.a.b - b.b.a.b) * (b.a.a + b.b.a.a), + b = b.e; + while (b !== a.a); + } + if (0 > e) for (e = this.b.c, d = e.e; d !== e; d = d.e) d.a = - d.a; + } + this.n = !1; + e = this.b.b; + for (a = e.h; a !== e; a = d) if (d = a.h, b = a.e, t(a.a, a.b.a) && a.e.e !== a && (ta(this, b, a), I(a), a = b, b = a.e), b.e === a) { + if (b !== a) { + if (b === d || b === d.b) d = d.h; + I(b); + } + if (a === d || a === d.b) d = d.h; + I(a); + } + this.e = e = new Da(); + d = this.b.c; + for (a = d.e; a !== d; a = a.e) a.h = xa(e, a); + Ea(e); + this.f = new Aa(this); + za(this, - O); + for (za(this, O); null !== (e = Fa(this.e)); ) { + for (; ; ) { + a: if (a = this.e, 0 === a.a) d = Ga(a.b); + else if (d = a.c[a.d[a.a - 1]], 0 !== a.b.a && (a = Ga(a.b), u(a, d))) { + d = a; + break a; + } + if (null === d || !t(d, e)) break; + d = Fa(this.e); + ta(this, e.c, d.c); + } + ya(this, e); + } + this.a = this.f.a.a.b.a.a; + for (e = 0; null !== (d = this.f.a.a.b); ) d.h || ++e, + Q(d); + this.f = null; + e = this.e; + e.b = null; + e.d = null; + this.e = e.c = null; + e = this.b; + for (a = e.a.b; a !== e.a; a = d) d = a.b, + a = a.a, + a.e.e === a && (P(a.c, a), I(a)); + if (!this.n) { + e = this.b; + if (this.m) for (a = e.b.h; a !== e.b; a = d) d = a.h, + a.b.d.c !== a.d.c ? a.f = a.d.c ? 1 : - 1 : I(a); + else for (a = e.a.b; a !== e.a; a = d) if (d = a.b, a.c) { + for (a = a.a; u(a.b.a, a.a); a = a.c.b); + for (; u(a.a, a.b.a); a = a.e); + b = a.c.b; + for (c = void 0; a.e !== b; ) if (u(a.b.a, b.a)) { + for (; b.e !== a && (ca(b.e) || 0 >= x(b.a, b.b.a, b.e.b.a)); ) c = L(b.e, b), + b = c.b; + b = b.c.b; + } else { + for (; b.e !== a && (da(a.c.b) || 0 <= x(a.b.a, a.a, a.c.b.a)); ) c = L(a, a.c.b), + a = c.b; + a = a.e; + } + for (; b.e.e !== a; ) c = L(b.e, b), + b = c.b; + } + if (this.h || this.i || this.k || this.l) if (this.m) for (e = this.b, d = e.a.b; d !== e.a; d = d.b) { + if (d.c) { + this.h && this.h(2, this.c); + a = d.a; + do this.k && this.k(a.a.d, this.c), + a = a.e; + while (a !== d.a); + this.i && this.i(this.c); + } + } else { + e = this.b; + d = !!this.l; + a = !1; + b = - 1; + for (c = e.a.d; c !== e.a; c = c.d) if (c.c) { + a || (this.h && this.h(4, this.c), a = !0); + g = c.a; + do d && (f = g.b.d.c ? 0 : 1, b !== f && (b = f, this.l && this.l(!!b, this.c))), + this.k && this.k(g.a.d, this.c), + g = g.e; + while (g !== c.a); + } + a && this.i && this.i(this.c); + } + if (this.r) { + e = this.b; + for (a = e.a.b; a !== e.a; a = d) if (d = a.b, !a.c) { + b = a.a; + c = b.e; + g = void 0; + do g = c, + c = g.e, + g.d = null, + null === g.b.d && (g.c === g ? F(g.a, null) : (g.a.c = g.c, H(g, J(g))), f = g.b, f.c === f ? F(f.a, null) : (f.a.c = f.c, H(f, J(f))), fa(g)); + while (g !== b); + b = a.d; + a = a.b; + a.d = b; + b.b = a; + } + this.r(this.b); + this.c = this.b = null; + return; + } + } + this.b = this.c = null; + }; + function Z(a, b) { + if (a.d !== b) for (; a.d !== b; ) if (a.d < b) switch (a.d) { + case Y: + V(a, 100151); + a.u(null); + break; + case 1: + V(a, 100152), + a.t(); + } else switch (a.d) { + case 2: + V(a, 100154); + a.v(); + break; + case 1: + V(a, 100153), + a.w(); + } + } + function V(a, b) { + a.p && a.p(b, a.c); + } + ; + function ga(a, b) { + this.b = a || this; + this.d = b || this; + this.a = null; + this.c = !1; + } + ; + function M() { + this.h = this; + this.i = this.d = this.a = this.e = this.c = this.b = null; + this.f = 0; + } + function J(a) { + return a.b.e; + } + ; + function Ca() { + this.c = new N(); + this.a = new ga(); + this.b = new M(); + this.d = new M(); + this.b.b = this.d; + this.d.b = this.b; + } + ; + function N(a, b) { + this.e = a || this; + this.f = b || this; + this.d = this.c = null; + this.g = [ + 0, + 0, + 0 + ]; + this.h = this.a = this.b = 0; + } + ; + function Da() { + this.c = [ + ]; + this.d = null; + this.a = 0; + this.e = !1; + this.b = new Ha(); + } + function Ea(a) { + a.d = [ + ]; + for (var b = 0; b < a.a; b++) a.d[b] = b; + a.d.sort(function (a) { + return function (b, e) { + return u(a[b], a[e]) ? 1 : - 1; + }; + }(a.c)); + a.e = !0; + Ia(a.b); + } + function xa(a, b) { + if (a.e) { + var c = a.b, + d = ++c.a; + 2 * d > c.f && (c.f *= 2, c.c = Ja(c.c, c.f + 1)); + var e; + 0 === c.b ? e = d : (e = c.b, c.b = c.c[c.b]); + c.e[e] = b; + c.c[e] = d; + c.d[d] = e; + c.h && va(c, d); + return e; + } + c = a.a++; + a.c[c] = b; + return - (c + 1); + } + function Fa(a) { + if (0 === a.a) return Ka(a.b); + var b = a.c[a.d[a.a - 1]]; + if (0 !== a.b.a && u(Ga(a.b), b)) return Ka(a.b); + do --a.a; + while (0 < a.a && null === a.c[a.d[a.a - 1]]); + return b; + } + ; + function Ha() { + this.d = Ja([0], 33); + this.e = [ + null, + null + ]; + this.c = [ + 0, + 0 + ]; + this.a = 0; + this.f = 32; + this.b = 0; + this.h = !1; + this.d[1] = 1; + } + function Ja(a, b) { + for (var c = Array(b), d = 0; d < a.length; d++) c[d] = a[d]; + for (; d < b; d++) c[d] = 0; + return c; + } + function Ia(a) { + for (var b = a.a; 1 <= b; --b) W(a, b); + a.h = !0; + } + function Ga(a) { + return a.e[a.d[1]]; + } + function Ka(a) { + var b = a.d, + c = a.e, + d = a.c, + e = b[1], + f = c[e]; + 0 < a.a && (b[1] = b[a.a], d[b[1]] = 1, c[e] = null, d[e] = a.b, a.b = e, 0 < --a.a && W(a, 1)); + return f; + } + function W(a, b) { + for (var c = a.d, d = a.e, e = a.c, f = b, g = c[f]; ; ) { + var h = f << 1; + h < a.a && u(d[c[h + 1]], d[c[h]]) && (h += 1); + var k = c[h]; + if (h > a.a || u(d[g], d[k])) { + c[f] = g; + e[g] = f; + break; + } + c[f] = k; + e[k] = f; + f = h; + } + } + function va(a, b) { + for (var c = a.d, d = a.e, e = a.c, f = b, g = c[f]; ; ) { + var h = f >> 1, + k = c[h]; + if (0 === h || u(d[k], d[g])) { + c[f] = g; + e[g] = f; + break; + } + c[f] = k; + e[k] = f; + f = h; + } + } + ; + function ma() { + this.e = this.a = null; + this.f = 0; + this.c = this.b = this.h = this.d = !1; + } + function S(a) { + return a.e.c.b; + } + function R(a) { + return a.e.a.b; + } + ; + this.libtess = { + GluTesselator: X, + windingRule: { + GLU_TESS_WINDING_ODD: 100130, + GLU_TESS_WINDING_NONZERO: 100131, + GLU_TESS_WINDING_POSITIVE: 100132, + GLU_TESS_WINDING_NEGATIVE: 100133, + GLU_TESS_WINDING_ABS_GEQ_TWO: 100134 + }, + primitiveType: { + GL_LINE_LOOP: 2, + GL_TRIANGLES: 4, + GL_TRIANGLE_STRIP: 5, + GL_TRIANGLE_FAN: 6 + }, + errorType: { + GLU_TESS_MISSING_BEGIN_POLYGON: 100151, + GLU_TESS_MISSING_END_POLYGON: 100153, + GLU_TESS_MISSING_BEGIN_CONTOUR: 100152, + GLU_TESS_MISSING_END_CONTOUR: 100154, + GLU_TESS_COORD_TOO_LARGE: 100155, + GLU_TESS_NEED_COMBINE_CALLBACK: 100156 + }, + gluEnum: { + GLU_TESS_MESH: 100112, + GLU_TESS_TOLERANCE: 100142, + GLU_TESS_WINDING_RULE: 100140, + GLU_TESS_BOUNDARY_ONLY: 100141, + GLU_INVALID_ENUM: 100900, + GLU_INVALID_VALUE: 100901, + GLU_TESS_BEGIN: 100100, + GLU_TESS_VERTEX: 100101, + GLU_TESS_END: 100102, + GLU_TESS_ERROR: 100103, + GLU_TESS_EDGE_FLAG: 100104, + GLU_TESS_COMBINE: 100105, + GLU_TESS_BEGIN_DATA: 100106, + GLU_TESS_VERTEX_DATA: 100107, + GLU_TESS_END_DATA: 100108, + GLU_TESS_ERROR_DATA: 100109, + GLU_TESS_EDGE_FLAG_DATA: 100110, + GLU_TESS_COMBINE_DATA: 100111 + } + }; + X.prototype.gluDeleteTess = X.prototype.x; + X.prototype.gluTessProperty = X.prototype.B; + X.prototype.gluGetTessProperty = X.prototype.y; + X.prototype.gluTessNormal = X.prototype.A; + X.prototype.gluTessCallback = X.prototype.z; + X.prototype.gluTessVertex = X.prototype.C; + X.prototype.gluTessBeginPolygon = X.prototype.u; + X.prototype.gluTessBeginContour = X.prototype.t; + X.prototype.gluTessEndContour = X.prototype.v; + X.prototype.gluTessEndPolygon = X.prototype.w; + if (typeof module !== 'undefined') { + module.exports = this.libtess; + } + }, + { + } + ], + 275: [ + function (_dereq_, module, exports) { + // (c) Dean McNamee , 2013. + // + // https://github.com/deanm/omggif + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to + // deal in the Software without restriction, including without limitation the + // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + // sell copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in + // all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + // IN THE SOFTWARE. + // + // omggif is a JavaScript implementation of a GIF 89a encoder and decoder, + // including animation and compression. It does not rely on any specific + // underlying system, so should run in the browser, Node, or Plask. + 'use strict'; + function GifWriter(buf, width, height, gopts) { + var p = 0; + var gopts = gopts === undefined ? { + } + : gopts; + var loop_count = gopts.loop === undefined ? null : gopts.loop; + var global_palette = gopts.palette === undefined ? null : gopts.palette; + if (width <= 0 || height <= 0 || width > 65535 || height > 65535) throw new Error('Width/Height invalid.'); + function check_palette_and_num_colors(palette) { + var num_colors = palette.length; + if (num_colors < 2 || num_colors > 256 || num_colors & num_colors - 1) { + throw new Error('Invalid code/color length, must be power of 2 and 2 .. 256.'); + } + return num_colors; + } // - Header. + + buf[p++] = 71; + buf[p++] = 73; + buf[p++] = 70; // GIF + buf[p++] = 56; + buf[p++] = 57; + buf[p++] = 97; // 89a + // Handling of Global Color Table (palette) and background index. + var gp_num_colors_pow2 = 0; + var background = 0; + if (global_palette !== null) { + var gp_num_colors = check_palette_and_num_colors(global_palette); + while (gp_num_colors >>= 1) ++gp_num_colors_pow2; + gp_num_colors = 1 << gp_num_colors_pow2; + --gp_num_colors_pow2; + if (gopts.background !== undefined) { + background = gopts.background; + if (background >= gp_num_colors) throw new Error('Background index out of range.'); + // The GIF spec states that a background index of 0 should be ignored, so + // this is probably a mistake and you really want to set it to another + // slot in the palette. But actually in the end most browsers, etc end + // up ignoring this almost completely (including for dispose background). + if (background === 0) throw new Error('Background index explicitly passed as 0.'); + } + } // - Logical Screen Descriptor. + // NOTE(deanm): w/h apparently ignored by implementations, but set anyway. + + buf[p++] = width & 255; + buf[p++] = width >> 8 & 255; + buf[p++] = height & 255; + buf[p++] = height >> 8 & 255; + // NOTE: Indicates 0-bpp original color resolution (unused?). + buf[p++] = (global_palette !== null ? 128 : 0) | // Global Color Table Flag. + gp_num_colors_pow2; // NOTE: No sort flag (unused?). + buf[p++] = background; // Background Color Index. + buf[p++] = 0; // Pixel aspect ratio (unused?). + // - Global Color Table + if (global_palette !== null) { + for (var i = 0, il = global_palette.length; i < il; ++i) { + var rgb = global_palette[i]; + buf[p++] = rgb >> 16 & 255; + buf[p++] = rgb >> 8 & 255; + buf[p++] = rgb & 255; + } + } + if (loop_count !== null) { + // Netscape block for looping. + if (loop_count < 0 || loop_count > 65535) throw new Error('Loop count invalid.'); + // Extension code, label, and length. + buf[p++] = 33; + buf[p++] = 255; + buf[p++] = 11; + // NETSCAPE2.0 + buf[p++] = 78; + buf[p++] = 69; + buf[p++] = 84; + buf[p++] = 83; + buf[p++] = 67; + buf[p++] = 65; + buf[p++] = 80; + buf[p++] = 69; + buf[p++] = 50; + buf[p++] = 46; + buf[p++] = 48; + // Sub-block + buf[p++] = 3; + buf[p++] = 1; + buf[p++] = loop_count & 255; + buf[p++] = loop_count >> 8 & 255; + buf[p++] = 0; // Terminator. + } + var ended = false; + this.addFrame = function (x, y, w, h, indexed_pixels, opts) { + if (ended === true) { + --p; + ended = false; + } // Un-end. + + opts = opts === undefined ? { + } + : opts; + // TODO(deanm): Bounds check x, y. Do they need to be within the virtual + // canvas width/height, I imagine? + if (x < 0 || y < 0 || x > 65535 || y > 65535) throw new Error('x/y invalid.'); + if (w <= 0 || h <= 0 || w > 65535 || h > 65535) throw new Error('Width/Height invalid.'); + if (indexed_pixels.length < w * h) throw new Error('Not enough pixels for the frame size.'); + var using_local_palette = true; + var palette = opts.palette; + if (palette === undefined || palette === null) { + using_local_palette = false; + palette = global_palette; + } + if (palette === undefined || palette === null) throw new Error('Must supply either a local or global palette.'); + var num_colors = check_palette_and_num_colors(palette); + // Compute the min_code_size (power of 2), destroying num_colors. + var min_code_size = 0; + while (num_colors >>= 1) ++min_code_size; + num_colors = 1 << min_code_size; // Now we can easily get it back. + var delay = opts.delay === undefined ? 0 : opts.delay; + // From the spec: + // 0 - No disposal specified. The decoder is + // not required to take any action. + // 1 - Do not dispose. The graphic is to be left + // in place. + // 2 - Restore to background color. The area used by the + // graphic must be restored to the background color. + // 3 - Restore to previous. The decoder is required to + // restore the area overwritten by the graphic with + // what was there prior to rendering the graphic. + // 4-7 - To be defined. + // NOTE(deanm): Dispose background doesn't really work, apparently most + // browsers ignore the background palette index and clear to transparency. + var disposal = opts.disposal === undefined ? 0 : opts.disposal; + if (disposal < 0 || disposal > 3) // 4-7 is reserved. + throw new Error('Disposal out of range.'); + var use_transparency = false; + var transparent_index = 0; + if (opts.transparent !== undefined && opts.transparent !== null) { + use_transparency = true; + transparent_index = opts.transparent; + if (transparent_index < 0 || transparent_index >= num_colors) throw new Error('Transparent color index.'); + } + if (disposal !== 0 || use_transparency || delay !== 0) { + // - Graphics Control Extension + buf[p++] = 33; + buf[p++] = 249; // Extension / Label. + buf[p++] = 4; // Byte size. + buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0); + buf[p++] = delay & 255; + buf[p++] = delay >> 8 & 255; + buf[p++] = transparent_index; // Transparent color index. + buf[p++] = 0; // Block Terminator. + } // - Image Descriptor + + buf[p++] = 44; // Image Seperator. + buf[p++] = x & 255; + buf[p++] = x >> 8 & 255; // Left. + buf[p++] = y & 255; + buf[p++] = y >> 8 & 255; // Top. + buf[p++] = w & 255; + buf[p++] = w >> 8 & 255; + buf[p++] = h & 255; + buf[p++] = h >> 8 & 255; + // NOTE: No sort flag (unused?). + // TODO(deanm): Support interlace. + buf[p++] = using_local_palette === true ? 128 | min_code_size - 1 : 0; + // - Local Color Table + if (using_local_palette === true) { + for (var i = 0, il = palette.length; i < il; ++i) { + var rgb = palette[i]; + buf[p++] = rgb >> 16 & 255; + buf[p++] = rgb >> 8 & 255; + buf[p++] = rgb & 255; + } + } + p = GifWriterOutputLZWCodeStream(buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels); + return p; + }; + this.end = function () { + if (ended === false) { + buf[p++] = 59; // Trailer. + ended = true; + } + return p; + }; + this.getOutputBuffer = function () { + return buf; + }; + this.setOutputBuffer = function (v) { + buf = v; + }; + this.getOutputBufferPosition = function () { + return p; + }; + this.setOutputBufferPosition = function (v) { + p = v; + }; + } // Main compression routine, palette indexes -> LZW code stream. + // |index_stream| must have at least one entry. + + function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) { + buf[p++] = min_code_size; + var cur_subblock = p++; // Pointing at the length field. + var clear_code = 1 << min_code_size; + var code_mask = clear_code - 1; + var eoi_code = clear_code + 1; + var next_code = eoi_code + 1; + var cur_code_size = min_code_size + 1; // Number of bits per code. + var cur_shift = 0; + // We have at most 12-bit codes, so we should have to hold a max of 19 + // bits here (and then we would write out). + var cur = 0; + function emit_bytes_to_buffer(bit_block_size) { + while (cur_shift >= bit_block_size) { + buf[p++] = cur & 255; + cur >>= 8; + cur_shift -= 8; + if (p === cur_subblock + 256) { + // Finished a subblock. + buf[cur_subblock] = 255; + cur_subblock = p++; + } + } + } + function emit_code(c) { + cur |= c << cur_shift; + cur_shift += cur_code_size; + emit_bytes_to_buffer(8); + } // I am not an expert on the topic, and I don't want to write a thesis. + // However, it is good to outline here the basic algorithm and the few data + // structures and optimizations here that make this implementation fast. + // The basic idea behind LZW is to build a table of previously seen runs + // addressed by a short id (herein called output code). All data is + // referenced by a code, which represents one or more values from the + // original input stream. All input bytes can be referenced as the same + // value as an output code. So if you didn't want any compression, you + // could more or less just output the original bytes as codes (there are + // some details to this, but it is the idea). In order to achieve + // compression, values greater then the input range (codes can be up to + // 12-bit while input only 8-bit) represent a sequence of previously seen + // inputs. The decompressor is able to build the same mapping while + // decoding, so there is always a shared common knowledge between the + // encoding and decoder, which is also important for "timing" aspects like + // how to handle variable bit width code encoding. + // + // One obvious but very important consequence of the table system is there + // is always a unique id (at most 12-bits) to map the runs. 'A' might be + // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship + // can be used for an effecient lookup strategy for the code mapping. We + // need to know if a run has been seen before, and be able to map that run + // to the output code. Since we start with known unique ids (input bytes), + // and then from those build more unique ids (table entries), we can + // continue this chain (almost like a linked list) to always have small + // integer values that represent the current byte chains in the encoder. + // This means instead of tracking the input bytes (AAAABCD) to know our + // current state, we can track the table entry for AAAABC (it is guaranteed + // to exist by the nature of the algorithm) and the next character D. + // Therefor the tuple of (table_entry, byte) is guaranteed to also be + // unique. This allows us to create a simple lookup key for mapping input + // sequences to codes (table indices) without having to store or search + // any of the code sequences. So if 'AAAA' has a table entry of 12, the + // tuple of ('AAAA', K) for any input byte K will be unique, and can be our + // key. This leads to a integer value at most 20-bits, which can always + // fit in an SMI value and be used as a fast sparse array / object key. + // Output code for the current contents of the index buffer. + + var ib_code = index_stream[0] & code_mask; // Load first input index. + var code_table = { + }; // Key'd on our 20-bit "tuple". + emit_code(clear_code); // Spec says first code should be a clear code. + // First index already loaded, process the rest of the stream. + for (var i = 1, il = index_stream.length; i < il; ++i) { + var k = index_stream[i] & code_mask; + var cur_key = ib_code << 8 | k; // (prev, k) unique tuple. + var cur_code = code_table[cur_key]; // buffer + k. + // Check if we have to create a new code table entry. + if (cur_code === undefined) { + // We don't have buffer + k. + // Emit index buffer (without k). + // This is an inline version of emit_code, because this is the core + // writing routine of the compressor (and V8 cannot inline emit_code + // because it is a closure here in a different context). Additionally + // we can call emit_byte_to_buffer less often, because we can have + // 30-bits (from our 31-bit signed SMI), and we know our codes will only + // be 12-bits, so can safely have 18-bits there without overflow. + // emit_code(ib_code); + cur |= ib_code << cur_shift; + cur_shift += cur_code_size; + while (cur_shift >= 8) { + buf[p++] = cur & 255; + cur >>= 8; + cur_shift -= 8; + if (p === cur_subblock + 256) { + // Finished a subblock. + buf[cur_subblock] = 255; + cur_subblock = p++; + } + } + if (next_code === 4096) { + // Table full, need a clear. + emit_code(clear_code); + next_code = eoi_code + 1; + cur_code_size = min_code_size + 1; + code_table = { + }; + } else { + // Table not full, insert a new entry. + // Increase our variable bit code sizes if necessary. This is a bit + // tricky as it is based on "timing" between the encoding and + // decoder. From the encoders perspective this should happen after + // we've already emitted the index buffer and are about to create the + // first table entry that would overflow our current code bit size. + if (next_code >= 1 << cur_code_size) ++cur_code_size; + code_table[cur_key] = next_code++; // Insert into code table. + } + ib_code = k; // Index buffer to single input k. + } else { + ib_code = cur_code; // Index buffer to sequence in code table. + } + } + emit_code(ib_code); // There will still be something in the index buffer. + emit_code(eoi_code); // End Of Information. + // Flush / finalize the sub-blocks stream to the buffer. + emit_bytes_to_buffer(1); + // Finish the sub-blocks, writing out any unfinished lengths and + // terminating with a sub-block of length 0. If we have already started + // but not yet used a sub-block it can just become the terminator. + if (cur_subblock + 1 === p) { + // Started but unused. + buf[cur_subblock] = 0; + } else { + // Started and used, write length and additional terminator block. + buf[cur_subblock] = p - cur_subblock - 1; + buf[p++] = 0; + } + return p; + } + function GifReader(buf) { + var p = 0; + // - Header (GIF87a or GIF89a). + if (buf[p++] !== 71 || buf[p++] !== 73 || buf[p++] !== 70 || buf[p++] !== 56 || (buf[p++] + 1 & 253) !== 56 || buf[p++] !== 97) { + throw new Error('Invalid GIF 87a/89a header.'); + } // - Logical Screen Descriptor. + + var width = buf[p++] | buf[p++] << 8; + var height = buf[p++] | buf[p++] << 8; + var pf0 = buf[p++]; // . + var global_palette_flag = pf0 >> 7; + var num_global_colors_pow2 = pf0 & 7; + var num_global_colors = 1 << num_global_colors_pow2 + 1; + var background = buf[p++]; + buf[p++]; // Pixel aspect ratio (unused?). + var global_palette_offset = null; + var global_palette_size = null; + if (global_palette_flag) { + global_palette_offset = p; + global_palette_size = num_global_colors; + p += num_global_colors * 3; // Seek past palette. + } + var no_eof = true; + var frames = [ + ]; + var delay = 0; + var transparent_index = null; + var disposal = 0; // 0 - No disposal specified. + var loop_count = null; + this.width = width; + this.height = height; + while (no_eof && p < buf.length) { + switch (buf[p++]) { + case 33: + // Graphics Control Extension Block + switch (buf[p++]) { + case 255: + // Application specific block + // Try if it's a Netscape block (with animation loop counter). + if (buf[p] !== 11 || // 21 FF already read, check block size. + // NETSCAPE2.0 + buf[p + 1] == 78 && buf[p + 2] == 69 && buf[p + 3] == 84 && buf[p + 4] == 83 && buf[p + 5] == 67 && buf[p + 6] == 65 && buf[p + 7] == 80 && buf[p + 8] == 69 && buf[p + 9] == 50 && buf[p + 10] == 46 && buf[p + 11] == 48 && // Sub-block + buf[p + 12] == 3 && buf[p + 13] == 1 && buf[p + 16] == 0) { + p += 14; + loop_count = buf[p++] | buf[p++] << 8; + p++; // Skip terminator. + } else { + // We don't know what it is, just try to get past it. + p += 12; + while (true) { + // Seek through subblocks. + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error('Invalid block size'); + if (block_size === 0) break; // 0 size is terminator + p += block_size; + } + } + break; + case 249: + // Graphics Control Extension + if (buf[p++] !== 4 || buf[p + 4] !== 0) throw new Error('Invalid graphics extension block.'); + var pf1 = buf[p++]; + delay = buf[p++] | buf[p++] << 8; + transparent_index = buf[p++]; + if ((pf1 & 1) === 0) transparent_index = null; + disposal = pf1 >> 2 & 7; + p++; // Skip terminator. + break; + case 254: + // Comment Extension. + while (true) { + // Seek through subblocks. + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error('Invalid block size'); + if (block_size === 0) break; // 0 size is terminator + // console.log(buf.slice(p, p+block_size).toString('ascii')); + p += block_size; + } + break; + default: + throw new Error('Unknown graphic control label: 0x' + buf[p - 1].toString(16)); + } + break; + case 44: + // Image Descriptor. + var x = buf[p++] | buf[p++] << 8; + var y = buf[p++] | buf[p++] << 8; + var w = buf[p++] | buf[p++] << 8; + var h = buf[p++] | buf[p++] << 8; + var pf2 = buf[p++]; + var local_palette_flag = pf2 >> 7; + var interlace_flag = pf2 >> 6 & 1; + var num_local_colors_pow2 = pf2 & 7; + var num_local_colors = 1 << num_local_colors_pow2 + 1; + var palette_offset = global_palette_offset; + var palette_size = global_palette_size; + var has_local_palette = false; + if (local_palette_flag) { + var has_local_palette = true; + palette_offset = p; // Override with local palette. + palette_size = num_local_colors; + p += num_local_colors * 3; // Seek past palette. + } + var data_offset = p; + p++; // codesize + while (true) { + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error('Invalid block size'); + if (block_size === 0) break; // 0 size is terminator + p += block_size; + } + frames.push({ + x: x, + y: y, + width: w, + height: h, + has_local_palette: has_local_palette, + palette_offset: palette_offset, + palette_size: palette_size, + data_offset: data_offset, + data_length: p - data_offset, + transparent_index: transparent_index, + interlaced: !!interlace_flag, + delay: delay, + disposal: disposal + }); + break; + case 59: + // Trailer Marker (end of file). + no_eof = false; + break; + default: + throw new Error('Unknown gif block: 0x' + buf[p - 1].toString(16)); + break; + } + } + this.numFrames = function () { + return frames.length; + }; + this.loopCount = function () { + return loop_count; + }; + this.frameInfo = function (frame_num) { + if (frame_num < 0 || frame_num >= frames.length) throw new Error('Frame index out of range.'); + return frames[frame_num]; + }; + this.decodeAndBlitFrameBGRA = function (frame_num, pixels) { + var frame = this.frameInfo(frame_num); + var num_pixels = frame.width * frame.height; + var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. + GifReaderLZWOutputIndexStream(buf, frame.data_offset, index_stream, num_pixels); + var palette_offset = frame.palette_offset; + // NOTE(deanm): It seems to be much faster to compare index to 256 than + // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in + // the profile, not sure if it's related to using a Uint8Array. + var trans = frame.transparent_index; + if (trans === null) trans = 256; + // We are possibly just blitting to a portion of the entire frame. + // That is a subrect within the framerect, so the additional pixels + // must be skipped over after we finished a scanline. + var framewidth = frame.width; + var framestride = width - framewidth; + var xleft = framewidth; // Number of subrect pixels left in scanline. + // Output indicies of the top left and bottom right corners of the subrect. + var opbeg = (frame.y * width + frame.x) * 4; + var opend = ((frame.y + frame.height) * width + frame.x) * 4; + var op = opbeg; + var scanstride = framestride * 4; + // Use scanstride to skip past the rows when interlacing. This is skipping + // 7 rows for the first two passes, then 3 then 1. + if (frame.interlaced === true) { + scanstride += width * 4 * 7; // Pass 1. + } + var interlaceskip = 8; // Tracking the row interval in the current pass. + for (var i = 0, il = index_stream.length; i < il; ++i) { + var index = index_stream[i]; + if (xleft === 0) { + // Beginning of new scan line + op += scanstride; + xleft = framewidth; + if (op >= opend) { + // Catch the wrap to switch passes when interlacing. + scanstride = framestride * 4 + width * 4 * (interlaceskip - 1); + // interlaceskip / 2 * 4 is interlaceskip << 1. + op = opbeg + (framewidth + framestride) * (interlaceskip << 1); + interlaceskip >>= 1; + } + } + if (index === trans) { + op += 4; + } else { + var r = buf[palette_offset + index * 3]; + var g = buf[palette_offset + index * 3 + 1]; + var b = buf[palette_offset + index * 3 + 2]; + pixels[op++] = b; + pixels[op++] = g; + pixels[op++] = r; + pixels[op++] = 255; + } + --xleft; + } + }; + // I will go to copy and paste hell one day... + this.decodeAndBlitFrameRGBA = function (frame_num, pixels) { + var frame = this.frameInfo(frame_num); + var num_pixels = frame.width * frame.height; + var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. + GifReaderLZWOutputIndexStream(buf, frame.data_offset, index_stream, num_pixels); + var palette_offset = frame.palette_offset; + // NOTE(deanm): It seems to be much faster to compare index to 256 than + // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in + // the profile, not sure if it's related to using a Uint8Array. + var trans = frame.transparent_index; + if (trans === null) trans = 256; + // We are possibly just blitting to a portion of the entire frame. + // That is a subrect within the framerect, so the additional pixels + // must be skipped over after we finished a scanline. + var framewidth = frame.width; + var framestride = width - framewidth; + var xleft = framewidth; // Number of subrect pixels left in scanline. + // Output indicies of the top left and bottom right corners of the subrect. + var opbeg = (frame.y * width + frame.x) * 4; + var opend = ((frame.y + frame.height) * width + frame.x) * 4; + var op = opbeg; + var scanstride = framestride * 4; + // Use scanstride to skip past the rows when interlacing. This is skipping + // 7 rows for the first two passes, then 3 then 1. + if (frame.interlaced === true) { + scanstride += width * 4 * 7; // Pass 1. + } + var interlaceskip = 8; // Tracking the row interval in the current pass. + for (var i = 0, il = index_stream.length; i < il; ++i) { + var index = index_stream[i]; + if (xleft === 0) { + // Beginning of new scan line + op += scanstride; + xleft = framewidth; + if (op >= opend) { + // Catch the wrap to switch passes when interlacing. + scanstride = framestride * 4 + width * 4 * (interlaceskip - 1); + // interlaceskip / 2 * 4 is interlaceskip << 1. + op = opbeg + (framewidth + framestride) * (interlaceskip << 1); + interlaceskip >>= 1; + } + } + if (index === trans) { + op += 4; + } else { + var r = buf[palette_offset + index * 3]; + var g = buf[palette_offset + index * 3 + 1]; + var b = buf[palette_offset + index * 3 + 2]; + pixels[op++] = r; + pixels[op++] = g; + pixels[op++] = b; + pixels[op++] = 255; + } + --xleft; + } + }; + } + function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) { + var min_code_size = code_stream[p++]; + var clear_code = 1 << min_code_size; + var eoi_code = clear_code + 1; + var next_code = eoi_code + 1; + var cur_code_size = min_code_size + 1; // Number of bits per code. + // NOTE: This shares the same name as the encoder, but has a different + // meaning here. Here this masks each code coming from the code stream. + var code_mask = (1 << cur_code_size) - 1; + var cur_shift = 0; + var cur = 0; + var op = 0; // Output pointer. + var subblock_size = code_stream[p++]; + // TODO(deanm): Would using a TypedArray be any faster? At least it would + // solve the fast mode / backing store uncertainty. + // var code_table = Array(4096); + var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits. + var prev_code = null; // Track code-1. + while (true) { + // Read up to two bytes, making sure we always 12-bits for max sized code. + while (cur_shift < 16) { + if (subblock_size === 0) break; // No more data to be read. + cur |= code_stream[p++] << cur_shift; + cur_shift += 8; + if (subblock_size === 1) { + // Never let it get to 0 to hold logic above. + subblock_size = code_stream[p++]; // Next subblock. + } else { + --subblock_size; + } + } // TODO(deanm): We should never really get here, we should have received + // and EOI. + + if (cur_shift < cur_code_size) break; + var code = cur & code_mask; + cur >>= cur_code_size; + cur_shift -= cur_code_size; + // TODO(deanm): Maybe should check that the first code was a clear code, + // at least this is what you're supposed to do. But actually our encoder + // now doesn't emit a clear code first anyway. + if (code === clear_code) { + // We don't actually have to clear the table. This could be a good idea + // for greater error checking, but we don't really do any anyway. We + // will just track it with next_code and overwrite old entries. + next_code = eoi_code + 1; + cur_code_size = min_code_size + 1; + code_mask = (1 << cur_code_size) - 1; + // Don't update prev_code ? + prev_code = null; + continue; + } else if (code === eoi_code) { + break; + } // We have a similar situation as the decoder, where we want to store + // variable length entries (code table entries), but we want to do in a + // faster manner than an array of arrays. The code below stores sort of a + // linked list within the code table, and then "chases" through it to + // construct the dictionary entries. When a new entry is created, just the + // last byte is stored, and the rest (prefix) of the entry is only + // referenced by its table entry. Then the code chases through the + // prefixes until it reaches a single byte code. We have to chase twice, + // first to compute the length, and then to actually copy the data to the + // output (backwards, since we know the length). The alternative would be + // storing something in an intermediate stack, but that doesn't make any + // more sense. I implemented an approach where it also stored the length + // in the code table, although it's a bit tricky because you run out of + // bits (12 + 12 + 8), but I didn't measure much improvements (the table + // entries are generally not the long). Even when I created benchmarks for + // very long table entries the complexity did not seem worth it. + // The code table stores the prefix entry in 12 bits and then the suffix + // byte in 8 bits, so each entry is 20 bits. + + var chase_code = code < next_code ? code : prev_code; + // Chase what we will output, either {CODE} or {CODE-1}. + var chase_length = 0; + var chase = chase_code; + while (chase > clear_code) { + chase = code_table[chase] >> 8; + ++chase_length; + } + var k = chase; + var op_end = op + chase_length + (chase_code !== code ? 1 : 0); + if (op_end > output_length) { + console.log('Warning, gif stream longer than expected.'); + return; + } // Already have the first byte from the chase, might as well write it fast. + + output[op++] = k; + op += chase_length; + var b = op; // Track pointer, writing backwards. + if (chase_code !== code) // The case of emitting {CODE-1} + k. + output[op++] = k; + chase = chase_code; + while (chase_length--) { + chase = code_table[chase]; + output[--b] = chase & 255; // Write backwards. + chase >>= 8; // Pull down to the prefix code. + } + if (prev_code !== null && next_code < 4096) { + code_table[next_code++] = prev_code << 8 | k; + // TODO(deanm): Figure out this clearing vs code growth logic better. I + // have an feeling that it should just happen somewhere else, for now it + // is awkward between when we grow past the max and then hit a clear code. + // For now just check if we hit the max 12-bits (then a clear code should + // follow, also of course encoded in 12-bits). + if (next_code >= code_mask + 1 && cur_code_size < 12) { + ++cur_code_size; + code_mask = code_mask << 1 | 1; + } + } + prev_code = code; + } + if (op !== output_length) { + console.log('Warning, gif stream shorter than expected.'); + } + return output; + } // CommonJS. + + try { + exports.GifWriter = GifWriter; + exports.GifReader = GifReader; + } catch (e) { + } + }, + { + } + ], + 276: [ + function (_dereq_, module, exports) { + (function (Buffer) { + /** + * https://opentype.js.org v0.9.0 | (c) Frederik De Bleser and other contributors | MIT License | Uses tiny-inflate by Devon Govett and string.prototype.codepointat polyfill by Mathias Bynens + */ + (function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory(global.opentype = { + }); + }) (this, function (exports) { + 'use strict'; + /*! https://mths.be/codepointat v0.2.0 by @mathias */ + if (!String.prototype.codePointAt) { + (function () { + var defineProperty = function () { + // IE 8 only supports `Object.defineProperty` on DOM elements + try { + var object = { + }; + var $defineProperty = Object.defineProperty; + var result = $defineProperty(object, object, object) && $defineProperty; + } catch (error) { + } + return result; + }(); + var codePointAt = function (position) { + if (this == null) { + throw TypeError(); + } + var string = String(this); + var size = string.length; + // `ToInteger` + var index = position ? Number(position) : 0; + if (index != index) { + // better `isNaN` + index = 0; + } // Account for out-of-bounds indices: + + if (index < 0 || index >= size) { + return undefined; + } // Get the first code unit + + var first = string.charCodeAt(index); + var second; + if ( // check if it’s the start of a surrogate pair + first >= 55296 && first <= 56319 && // high surrogate + size > index + 1 // there is a next code unit + ) { + second = string.charCodeAt(index + 1); + if (second >= 56320 && second <= 57343) { + // low surrogate + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 55296) * 1024 + second - 56320 + 65536; + } + } + return first; + }; + if (defineProperty) { + defineProperty(String.prototype, 'codePointAt', { + 'value': codePointAt, + 'configurable': true, + 'writable': true + }); + } else { + String.prototype.codePointAt = codePointAt; + } + }) (); + } + var TINF_OK = 0; + var TINF_DATA_ERROR = - 3; + function Tree() { + this.table = new Uint16Array(16); /* table of code length counts */ + this.trans = new Uint16Array(288); /* code -> symbol translation table */ + } + function Data(source, dest) { + this.source = source; + this.sourceIndex = 0; + this.tag = 0; + this.bitcount = 0; + this.dest = dest; + this.destLen = 0; + this.ltree = new Tree(); /* dynamic length/symbol tree */ + this.dtree = new Tree(); /* dynamic distance tree */ + } /* --------------------------------------------------- * + * -- uninitialized global data (static structures) -- * + * --------------------------------------------------- */ + + var sltree = new Tree(); + var sdtree = new Tree(); + /* extra bits and base tables for length codes */ + var length_bits = new Uint8Array(30); + var length_base = new Uint16Array(30); + /* extra bits and base tables for distance codes */ + var dist_bits = new Uint8Array(30); + var dist_base = new Uint16Array(30); + /* special ordering of code length codes */ + var clcidx = new Uint8Array([16, + 17, + 18, + 0, + 8, + 7, + 9, + 6, + 10, + 5, + 11, + 4, + 12, + 3, + 13, + 2, + 14, + 1, + 15]); + /* used by tinf_decode_trees, avoids allocations every call */ + var code_tree = new Tree(); + var lengths = new Uint8Array(288 + 32); + /* ----------------------- * + * -- utility functions -- * + * ----------------------- */ + /* build extra bits and base tables */ + function tinf_build_bits_base(bits, base, delta, first) { + var i, + sum; + /* build bits table */ + for (i = 0; i < delta; ++i) { + bits[i] = 0; + } + for (i = 0; i < 30 - delta; ++i) { + bits[i + delta] = i / delta | 0; + } /* build base table */ + + for (sum = first, i = 0; i < 30; ++i) { + base[i] = sum; + sum += 1 << bits[i]; + } + } /* build the fixed huffman trees */ + + function tinf_build_fixed_trees(lt, dt) { + var i; + /* build fixed length tree */ + for (i = 0; i < 7; ++i) { + lt.table[i] = 0; + } + lt.table[7] = 24; + lt.table[8] = 152; + lt.table[9] = 112; + for (i = 0; i < 24; ++i) { + lt.trans[i] = 256 + i; + } + for (i = 0; i < 144; ++i) { + lt.trans[24 + i] = i; + } + for (i = 0; i < 8; ++i) { + lt.trans[24 + 144 + i] = 280 + i; + } + for (i = 0; i < 112; ++i) { + lt.trans[24 + 144 + 8 + i] = 144 + i; + } /* build fixed distance tree */ + + for (i = 0; i < 5; ++i) { + dt.table[i] = 0; + } + dt.table[5] = 32; + for (i = 0; i < 32; ++i) { + dt.trans[i] = i; + } + } /* given an array of code lengths, build a tree */ + + var offs = new Uint16Array(16); + function tinf_build_tree(t, lengths, off, num) { + var i, + sum; + /* clear code length count table */ + for (i = 0; i < 16; ++i) { + t.table[i] = 0; + } /* scan symbol lengths, and sum code length counts */ + + for (i = 0; i < num; ++i) { + t.table[lengths[off + i]]++; + } + t.table[0] = 0; + /* compute offset table for distribution sort */ + for (sum = 0, i = 0; i < 16; ++i) { + offs[i] = sum; + sum += t.table[i]; + } /* create code->symbol translation table (symbols sorted by code) */ + + for (i = 0; i < num; ++i) { + if (lengths[off + i]) { + t.trans[offs[lengths[off + i]]++] = i; + } + } + } /* ---------------------- * + * -- decode functions -- * + * ---------------------- */ + /* get one bit from source stream */ + + function tinf_getbit(d) { + /* check if tag is empty */ + if (!d.bitcount--) { + /* load next tag */ + d.tag = d.source[d.sourceIndex++]; + d.bitcount = 7; + } /* shift bit out of tag */ + + var bit = d.tag & 1; + d.tag >>>= 1; + return bit; + } /* read a num bit value from a stream and add base */ + + function tinf_read_bits(d, num, base) { + if (!num) { + return base; + } + while (d.bitcount < 24) { + d.tag |= d.source[d.sourceIndex++] << d.bitcount; + d.bitcount += 8; + } + var val = d.tag & 65535 >>> 16 - num; + d.tag >>>= num; + d.bitcount -= num; + return val + base; + } /* given a data stream and a tree, decode a symbol */ + + function tinf_decode_symbol(d, t) { + while (d.bitcount < 24) { + d.tag |= d.source[d.sourceIndex++] << d.bitcount; + d.bitcount += 8; + } + var sum = 0, + cur = 0, + len = 0; + var tag = d.tag; + /* get more bits while code value is above sum */ + do { + cur = 2 * cur + (tag & 1); + tag >>>= 1; + ++len; + sum += t.table[len]; + cur -= t.table[len]; + } while (cur >= 0); + d.tag = tag; + d.bitcount -= len; + return t.trans[sum + cur]; + } /* given a data stream, decode dynamic trees from it */ + + function tinf_decode_trees(d, lt, dt) { + var hlit, + hdist, + hclen; + var i, + num, + length; + /* get 5 bits HLIT (257-286) */ + hlit = tinf_read_bits(d, 5, 257); + /* get 5 bits HDIST (1-32) */ + hdist = tinf_read_bits(d, 5, 1); + /* get 4 bits HCLEN (4-19) */ + hclen = tinf_read_bits(d, 4, 4); + for (i = 0; i < 19; ++i) { + lengths[i] = 0; + } /* read code lengths for code length alphabet */ + + for (i = 0; i < hclen; ++i) { + /* get 3 bits code length (0-7) */ + var clen = tinf_read_bits(d, 3, 0); + lengths[clcidx[i]] = clen; + } /* build code length tree */ + + tinf_build_tree(code_tree, lengths, 0, 19); + /* decode code lengths for the dynamic trees */ + for (num = 0; num < hlit + hdist; ) { + var sym = tinf_decode_symbol(d, code_tree); + switch (sym) { + case 16: + /* copy previous code length 3-6 times (read 2 bits) */ + var prev = lengths[num - 1]; + for (length = tinf_read_bits(d, 2, 3); length; --length) { + lengths[num++] = prev; + } + break; + case 17: + /* repeat code length 0 for 3-10 times (read 3 bits) */ + for (length = tinf_read_bits(d, 3, 3); length; --length) { + lengths[num++] = 0; + } + break; + case 18: + /* repeat code length 0 for 11-138 times (read 7 bits) */ + for (length = tinf_read_bits(d, 7, 11); length; --length) { + lengths[num++] = 0; + } + break; + default: + /* values 0-15 represent the actual code lengths */ + lengths[num++] = sym; + break; + } + } /* build dynamic trees */ + + tinf_build_tree(lt, lengths, 0, hlit); + tinf_build_tree(dt, lengths, hlit, hdist); + } /* ----------------------------- * + * -- block inflate functions -- * + * ----------------------------- */ + /* given a stream and two trees, inflate a block of data */ + + function tinf_inflate_block_data(d, lt, dt) { + while (1) { + var sym = tinf_decode_symbol(d, lt); + /* check for end of block */ + if (sym === 256) { + return TINF_OK; + } + if (sym < 256) { + d.dest[d.destLen++] = sym; + } else { + var length, + dist, + offs; + var i; + sym -= 257; + /* possibly get more bits from length code */ + length = tinf_read_bits(d, length_bits[sym], length_base[sym]); + dist = tinf_decode_symbol(d, dt); + /* possibly get more bits from distance code */ + offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]); + /* copy match */ + for (i = offs; i < offs + length; ++i) { + d.dest[d.destLen++] = d.dest[i]; + } + } + } + } /* inflate an uncompressed block of data */ + + function tinf_inflate_uncompressed_block(d) { + var length, + invlength; + var i; + /* unread from bitbuffer */ + while (d.bitcount > 8) { + d.sourceIndex--; + d.bitcount -= 8; + } /* get length */ + + length = d.source[d.sourceIndex + 1]; + length = 256 * length + d.source[d.sourceIndex]; + /* get one's complement of length */ + invlength = d.source[d.sourceIndex + 3]; + invlength = 256 * invlength + d.source[d.sourceIndex + 2]; + /* check length */ + if (length !== (~invlength & 65535)) { + return TINF_DATA_ERROR; + } + d.sourceIndex += 4; + /* copy block */ + for (i = length; i; --i) { + d.dest[d.destLen++] = d.source[d.sourceIndex++]; + } /* make sure we start next block on a byte boundary */ + + d.bitcount = 0; + return TINF_OK; + } /* inflate stream from source to dest */ + + function tinf_uncompress(source, dest) { + var d = new Data(source, dest); + var bfinal, + btype, + res; + do { + /* read final block flag */ + bfinal = tinf_getbit(d); + /* read block type (2 bits) */ + btype = tinf_read_bits(d, 2, 0); + /* decompress block */ + switch (btype) { + case 0: + /* decompress uncompressed block */ + res = tinf_inflate_uncompressed_block(d); + break; + case 1: + /* decompress block with fixed huffman trees */ + res = tinf_inflate_block_data(d, sltree, sdtree); + break; + case 2: + /* decompress block with dynamic huffman trees */ + tinf_decode_trees(d, d.ltree, d.dtree); + res = tinf_inflate_block_data(d, d.ltree, d.dtree); + break; + default: + res = TINF_DATA_ERROR; + } + if (res !== TINF_OK) { + throw new Error('Data error'); + } + } while (!bfinal); + if (d.destLen < d.dest.length) { + if (typeof d.dest.slice === 'function') { + return d.dest.slice(0, d.destLen); + } else { + return d.dest.subarray(0, d.destLen); + } + } + return d.dest; + } /* -------------------- * + * -- initialization -- * + * -------------------- */ + /* build fixed huffman trees */ + + tinf_build_fixed_trees(sltree, sdtree); + /* build extra bits and base tables */ + tinf_build_bits_base(length_bits, length_base, 4, 3); + tinf_build_bits_base(dist_bits, dist_base, 2, 1); + /* fix a special case */ + length_bits[28] = 0; + length_base[28] = 258; + var tinyInflate = tinf_uncompress; + // The Bounding Box object + function derive(v0, v1, v2, v3, t) { + return Math.pow(1 - t, 3) * v0 + 3 * Math.pow(1 - t, 2) * t * v1 + 3 * (1 - t) * Math.pow(t, 2) * v2 + Math.pow(t, 3) * v3; + } /** + * A bounding box is an enclosing box that describes the smallest measure within which all the points lie. + * It is used to calculate the bounding box of a glyph or text path. + * + * On initialization, x1/y1/x2/y2 will be NaN. Check if the bounding box is empty using `isEmpty()`. + * + * @exports opentype.BoundingBox + * @class + * @constructor + */ + + function BoundingBox() { + this.x1 = Number.NaN; + this.y1 = Number.NaN; + this.x2 = Number.NaN; + this.y2 = Number.NaN; + } /** + * Returns true if the bounding box is empty, that is, no points have been added to the box yet. + */ + + BoundingBox.prototype.isEmpty = function () { + return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2); + }; + /** + * Add the point to the bounding box. + * The x1/y1/x2/y2 coordinates of the bounding box will now encompass the given point. + * @param {number} x - The X coordinate of the point. + * @param {number} y - The Y coordinate of the point. + */ + BoundingBox.prototype.addPoint = function (x, y) { + if (typeof x === 'number') { + if (isNaN(this.x1) || isNaN(this.x2)) { + this.x1 = x; + this.x2 = x; + } + if (x < this.x1) { + this.x1 = x; + } + if (x > this.x2) { + this.x2 = x; + } + } + if (typeof y === 'number') { + if (isNaN(this.y1) || isNaN(this.y2)) { + this.y1 = y; + this.y2 = y; + } + if (y < this.y1) { + this.y1 = y; + } + if (y > this.y2) { + this.y2 = y; + } + } + }; + /** + * Add a X coordinate to the bounding box. + * This extends the bounding box to include the X coordinate. + * This function is used internally inside of addBezier. + * @param {number} x - The X coordinate of the point. + */ + BoundingBox.prototype.addX = function (x) { + this.addPoint(x, null); + }; + /** + * Add a Y coordinate to the bounding box. + * This extends the bounding box to include the Y coordinate. + * This function is used internally inside of addBezier. + * @param {number} y - The Y coordinate of the point. + */ + BoundingBox.prototype.addY = function (y) { + this.addPoint(null, y); + }; + /** + * Add a Bézier curve to the bounding box. + * This extends the bounding box to include the entire Bézier. + * @param {number} x0 - The starting X coordinate. + * @param {number} y0 - The starting Y coordinate. + * @param {number} x1 - The X coordinate of the first control point. + * @param {number} y1 - The Y coordinate of the first control point. + * @param {number} x2 - The X coordinate of the second control point. + * @param {number} y2 - The Y coordinate of the second control point. + * @param {number} x - The ending X coordinate. + * @param {number} y - The ending Y coordinate. + */ + BoundingBox.prototype.addBezier = function (x0, y0, x1, y1, x2, y2, x, y) { + var this$1 = this; + // This code is based on http://nishiohirokazu.blogspot.com/2009/06/how-to-calculate-bezier-curves-bounding.html + // and https://github.com/icons8/svg-path-bounding-box + var p0 = [ + x0, + y0 + ]; + var p1 = [ + x1, + y1 + ]; + var p2 = [ + x2, + y2 + ]; + var p3 = [ + x, + y + ]; + this.addPoint(x0, y0); + this.addPoint(x, y); + for (var i = 0; i <= 1; i++) { + var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; + var a = - 3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; + var c = 3 * p1[i] - 3 * p0[i]; + if (a === 0) { + if (b === 0) { + continue; + } + var t = - c / b; + if (0 < t && t < 1) { + if (i === 0) { + this$1.addX(derive(p0[i], p1[i], p2[i], p3[i], t)); + } + if (i === 1) { + this$1.addY(derive(p0[i], p1[i], p2[i], p3[i], t)); + } + } + continue; + } + var b2ac = Math.pow(b, 2) - 4 * c * a; + if (b2ac < 0) { + continue; + } + var t1 = ( - b + Math.sqrt(b2ac)) / (2 * a); + if (0 < t1 && t1 < 1) { + if (i === 0) { + this$1.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); + } + if (i === 1) { + this$1.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); + } + } + var t2 = ( - b - Math.sqrt(b2ac)) / (2 * a); + if (0 < t2 && t2 < 1) { + if (i === 0) { + this$1.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); + } + if (i === 1) { + this$1.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); + } + } + } + }; + /** + * Add a quadratic curve to the bounding box. + * This extends the bounding box to include the entire quadratic curve. + * @param {number} x0 - The starting X coordinate. + * @param {number} y0 - The starting Y coordinate. + * @param {number} x1 - The X coordinate of the control point. + * @param {number} y1 - The Y coordinate of the control point. + * @param {number} x - The ending X coordinate. + * @param {number} y - The ending Y coordinate. + */ + BoundingBox.prototype.addQuad = function (x0, y0, x1, y1, x, y) { + var cp1x = x0 + 2 / 3 * (x1 - x0); + var cp1y = y0 + 2 / 3 * (y1 - y0); + var cp2x = cp1x + 1 / 3 * (x - x0); + var cp2y = cp1y + 1 / 3 * (y - y0); + this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y); + }; + // Geometric objects + /** + * A bézier path containing a set of path commands similar to a SVG path. + * Paths can be drawn on a context using `draw`. + * @exports opentype.Path + * @class + * @constructor + */ + function Path() { + this.commands = [ + ]; + this.fill = 'black'; + this.stroke = null; + this.strokeWidth = 1; + } /** + * @param {number} x + * @param {number} y + */ + + Path.prototype.moveTo = function (x, y) { + this.commands.push({ + type: 'M', + x: x, + y: y + }); + }; + /** + * @param {number} x + * @param {number} y + */ + Path.prototype.lineTo = function (x, y) { + this.commands.push({ + type: 'L', + x: x, + y: y + }); + }; + /** + * Draws cubic curve + * @function + * curveTo + * @memberof opentype.Path.prototype + * @param {number} x1 - x of control 1 + * @param {number} y1 - y of control 1 + * @param {number} x2 - x of control 2 + * @param {number} y2 - y of control 2 + * @param {number} x - x of path point + * @param {number} y - y of path point + */ + /** + * Draws cubic curve + * @function + * bezierCurveTo + * @memberof opentype.Path.prototype + * @param {number} x1 - x of control 1 + * @param {number} y1 - y of control 1 + * @param {number} x2 - x of control 2 + * @param {number} y2 - y of control 2 + * @param {number} x - x of path point + * @param {number} y - y of path point + * @see curveTo + */ + Path.prototype.curveTo = Path.prototype.bezierCurveTo = function (x1, y1, x2, y2, x, y) { + this.commands.push({ + type: 'C', + x1: x1, + y1: y1, + x2: x2, + y2: y2, + x: x, + y: y + }); + }; + /** + * Draws quadratic curve + * @function + * quadraticCurveTo + * @memberof opentype.Path.prototype + * @param {number} x1 - x of control + * @param {number} y1 - y of control + * @param {number} x - x of path point + * @param {number} y - y of path point + */ + /** + * Draws quadratic curve + * @function + * quadTo + * @memberof opentype.Path.prototype + * @param {number} x1 - x of control + * @param {number} y1 - y of control + * @param {number} x - x of path point + * @param {number} y - y of path point + */ + Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function (x1, y1, x, y) { + this.commands.push({ + type: 'Q', + x1: x1, + y1: y1, + x: x, + y: y + }); + }; + /** + * Closes the path + * @function closePath + * @memberof opentype.Path.prototype + */ + /** + * Close the path + * @function close + * @memberof opentype.Path.prototype + */ + Path.prototype.close = Path.prototype.closePath = function () { + this.commands.push({ + type: 'Z' + }); + }; + /** + * Add the given path or list of commands to the commands of this path. + * @param {Array} pathOrCommands - another opentype.Path, an opentype.BoundingBox, or an array of commands. + */ + Path.prototype.extend = function (pathOrCommands) { + if (pathOrCommands.commands) { + pathOrCommands = pathOrCommands.commands; + } else if (pathOrCommands instanceof BoundingBox) { + var box = pathOrCommands; + this.moveTo(box.x1, box.y1); + this.lineTo(box.x2, box.y1); + this.lineTo(box.x2, box.y2); + this.lineTo(box.x1, box.y2); + this.close(); + return; + } + Array.prototype.push.apply(this.commands, pathOrCommands); + }; + /** + * Calculate the bounding box of the path. + * @returns {opentype.BoundingBox} + */ + Path.prototype.getBoundingBox = function () { + var this$1 = this; + var box = new BoundingBox(); + var startX = 0; + var startY = 0; + var prevX = 0; + var prevY = 0; + for (var i = 0; i < this.commands.length; i++) { + var cmd = this$1.commands[i]; + switch (cmd.type) { + case 'M': + box.addPoint(cmd.x, cmd.y); + startX = prevX = cmd.x; + startY = prevY = cmd.y; + break; + case 'L': + box.addPoint(cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case 'Q': + box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case 'C': + box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case 'Z': + prevX = startX; + prevY = startY; + break; + default: + throw new Error('Unexpected path command ' + cmd.type); + } + } + if (box.isEmpty()) { + box.addPoint(0, 0); + } + return box; + }; + /** + * Draw the path to a 2D context. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context. + */ + Path.prototype.draw = function (ctx) { + var this$1 = this; + ctx.beginPath(); + for (var i = 0; i < this.commands.length; i += 1) { + var cmd = this$1.commands[i]; + if (cmd.type === 'M') { + ctx.moveTo(cmd.x, cmd.y); + } else if (cmd.type === 'L') { + ctx.lineTo(cmd.x, cmd.y); + } else if (cmd.type === 'C') { + ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === 'Q') { + ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === 'Z') { + ctx.closePath(); + } + } + if (this.fill) { + ctx.fillStyle = this.fill; + ctx.fill(); + } + if (this.stroke) { + ctx.strokeStyle = this.stroke; + ctx.lineWidth = this.strokeWidth; + ctx.stroke(); + } + }; + /** + * Convert the Path to a string of path data instructions + * See http://www.w3.org/TR/SVG/paths.html#PathData + * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values + * @return {string} + */ + Path.prototype.toPathData = function (decimalPlaces) { + var this$1 = this; + decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; + function floatToString(v) { + if (Math.round(v) === v) { + return '' + Math.round(v); + } else { + return v.toFixed(decimalPlaces); + } + } + function packValues() { + var arguments$1 = arguments; + var s = ''; + for (var i = 0; i < arguments.length; i += 1) { + var v = arguments$1[i]; + if (v >= 0 && i > 0) { + s += ' '; + } + s += floatToString(v); + } + return s; + } + var d = ''; + for (var i = 0; i < this.commands.length; i += 1) { + var cmd = this$1.commands[i]; + if (cmd.type === 'M') { + d += 'M' + packValues(cmd.x, cmd.y); + } else if (cmd.type === 'L') { + d += 'L' + packValues(cmd.x, cmd.y); + } else if (cmd.type === 'C') { + d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === 'Q') { + d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === 'Z') { + d += 'Z'; + } + } + return d; + }; + /** + * Convert the path to an SVG element, as a string. + * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values + * @return {string} + */ + Path.prototype.toSVG = function (decimalPlaces) { + var svg = '= 0 && v <= 255, 'Byte value should be between 0 and 255.'); + return [v]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.BYTE = constant(1); + /** + * Convert a 8-bit signed integer to a list of 1 byte. + * @param {string} + * @returns {Array} + */ + encode.CHAR = function (v) { + return [v.charCodeAt(0)]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.CHAR = constant(1); + /** + * Convert an ASCII string to a list of bytes. + * @param {string} + * @returns {Array} + */ + encode.CHARARRAY = function (v) { + var b = [ + ]; + for (var i = 0; i < v.length; i += 1) { + b[i] = v.charCodeAt(i); + } + return b; + }; + /** + * @param {Array} + * @returns {number} + */ + sizeOf.CHARARRAY = function (v) { + return v.length; + }; + /** + * Convert a 16-bit unsigned integer to a list of 2 bytes. + * @param {number} + * @returns {Array} + */ + encode.USHORT = function (v) { + return [v >> 8 & 255, + v & 255]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.USHORT = constant(2); + /** + * Convert a 16-bit signed integer to a list of 2 bytes. + * @param {number} + * @returns {Array} + */ + encode.SHORT = function (v) { + // Two's complement + if (v >= LIMIT16) { + v = - (2 * LIMIT16 - v); + } + return [v >> 8 & 255, + v & 255]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.SHORT = constant(2); + /** + * Convert a 24-bit unsigned integer to a list of 3 bytes. + * @param {number} + * @returns {Array} + */ + encode.UINT24 = function (v) { + return [v >> 16 & 255, + v >> 8 & 255, + v & 255]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.UINT24 = constant(3); + /** + * Convert a 32-bit unsigned integer to a list of 4 bytes. + * @param {number} + * @returns {Array} + */ + encode.ULONG = function (v) { + return [v >> 24 & 255, + v >> 16 & 255, + v >> 8 & 255, + v & 255]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.ULONG = constant(4); + /** + * Convert a 32-bit unsigned integer to a list of 4 bytes. + * @param {number} + * @returns {Array} + */ + encode.LONG = function (v) { + // Two's complement + if (v >= LIMIT32) { + v = - (2 * LIMIT32 - v); + } + return [v >> 24 & 255, + v >> 16 & 255, + v >> 8 & 255, + v & 255]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.LONG = constant(4); + encode.FIXED = encode.ULONG; + sizeOf.FIXED = sizeOf.ULONG; + encode.FWORD = encode.SHORT; + sizeOf.FWORD = sizeOf.SHORT; + encode.UFWORD = encode.USHORT; + sizeOf.UFWORD = sizeOf.USHORT; + /** + * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp. + * @param {number} + * @returns {Array} + */ + encode.LONGDATETIME = function (v) { + return [0, + 0, + 0, + 0, + v >> 24 & 255, + v >> 16 & 255, + v >> 8 & 255, + v & 255]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.LONGDATETIME = constant(8); + /** + * Convert a 4-char tag to a list of 4 bytes. + * @param {string} + * @returns {Array} + */ + encode.TAG = function (v) { + check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.'); + return [v.charCodeAt(0), + v.charCodeAt(1), + v.charCodeAt(2), + v.charCodeAt(3)]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.TAG = constant(4); + // CFF data types /////////////////////////////////////////////////////////// + encode.Card8 = encode.BYTE; + sizeOf.Card8 = sizeOf.BYTE; + encode.Card16 = encode.USHORT; + sizeOf.Card16 = sizeOf.USHORT; + encode.OffSize = encode.BYTE; + sizeOf.OffSize = sizeOf.BYTE; + encode.SID = encode.USHORT; + sizeOf.SID = sizeOf.USHORT; + // Convert a numeric operand or charstring number to a variable-size list of bytes. + /** + * Convert a numeric operand or charstring number to a variable-size list of bytes. + * @param {number} + * @returns {Array} + */ + encode.NUMBER = function (v) { + if (v >= - 107 && v <= 107) { + return [v + 139]; + } else if (v >= 108 && v <= 1131) { + v = v - 108; + return [(v >> 8) + 247, + v & 255]; + } else if (v >= - 1131 && v <= - 108) { + v = - v - 108; + return [(v >> 8) + 251, + v & 255]; + } else if (v >= - 32768 && v <= 32767) { + return encode.NUMBER16(v); + } else { + return encode.NUMBER32(v); + } + }; + /** + * @param {number} + * @returns {number} + */ + sizeOf.NUMBER = function (v) { + return encode.NUMBER(v).length; + }; + /** + * Convert a signed number between -32768 and +32767 to a three-byte value. + * This ensures we always use three bytes, but is not the most compact format. + * @param {number} + * @returns {Array} + */ + encode.NUMBER16 = function (v) { + return [28, + v >> 8 & 255, + v & 255]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.NUMBER16 = constant(3); + /** + * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value. + * This is useful if you want to be sure you always use four bytes, + * at the expense of wasting a few bytes for smaller numbers. + * @param {number} + * @returns {Array} + */ + encode.NUMBER32 = function (v) { + return [29, + v >> 24 & 255, + v >> 16 & 255, + v >> 8 & 255, + v & 255]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.NUMBER32 = constant(5); + /** + * @param {number} + * @returns {Array} + */ + encode.REAL = function (v) { + var value = v.toString(); + // Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7) + // This code converts it back to a number without the epsilon. + var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); + if (m) { + var epsilon = parseFloat('1e' + ((m[2] ? + m[2] : 0) + m[1].length)); + value = (Math.round(v * epsilon) / epsilon).toString(); + } + var nibbles = ''; + for (var i = 0, ii = value.length; i < ii; i += 1) { + var c = value[i]; + if (c === 'e') { + nibbles += value[++i] === '-' ? 'c' : 'b'; + } else if (c === '.') { + nibbles += 'a'; + } else if (c === '-') { + nibbles += 'e'; + } else { + nibbles += c; + } + } + nibbles += nibbles.length & 1 ? 'f' : 'ff'; + var out = [ + 30 + ]; + for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) { + out.push(parseInt(nibbles.substr(i$1, 2), 16)); + } + return out; + }; + /** + * @param {number} + * @returns {number} + */ + sizeOf.REAL = function (v) { + return encode.REAL(v).length; + }; + encode.NAME = encode.CHARARRAY; + sizeOf.NAME = sizeOf.CHARARRAY; + encode.STRING = encode.CHARARRAY; + sizeOf.STRING = sizeOf.CHARARRAY; + /** + * @param {DataView} data + * @param {number} offset + * @param {number} numBytes + * @returns {string} + */ + decode.UTF8 = function (data, offset, numBytes) { + var codePoints = [ + ]; + var numChars = numBytes; + for (var j = 0; j < numChars; j++, offset += 1) { + codePoints[j] = data.getUint8(offset); + } + return String.fromCharCode.apply(null, codePoints); + }; + /** + * @param {DataView} data + * @param {number} offset + * @param {number} numBytes + * @returns {string} + */ + decode.UTF16 = function (data, offset, numBytes) { + var codePoints = [ + ]; + var numChars = numBytes / 2; + for (var j = 0; j < numChars; j++, offset += 2) { + codePoints[j] = data.getUint16(offset); + } + return String.fromCharCode.apply(null, codePoints); + }; + /** + * Convert a JavaScript string to UTF16-BE. + * @param {string} + * @returns {Array} + */ + encode.UTF16 = function (v) { + var b = [ + ]; + for (var i = 0; i < v.length; i += 1) { + var codepoint = v.charCodeAt(i); + b[b.length] = codepoint >> 8 & 255; + b[b.length] = codepoint & 255; + } + return b; + }; + /** + * @param {string} + * @returns {number} + */ + sizeOf.UTF16 = function (v) { + return v.length * 2; + }; + // Data for converting old eight-bit Macintosh encodings to Unicode. + // This representation is optimized for decoding; encoding is slower + // and needs more memory. The assumption is that all opentype.js users + // want to open fonts, but saving a font will be comparatively rare + // so it can be more expensive. Keyed by IANA character set name. + // + // Python script for generating these strings: + // + // s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)]) + // print(s.encode('utf-8')) + /** + * @private + */ + var eightBitMacEncodings = { + 'x-mac-croatian': // Python: 'mac_croatian' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' + '¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ', + 'x-mac-cyrillic': // Python: 'mac_cyrillic' + 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' + 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю', + 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' + 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ', + 'x-mac-greek': // Python: 'mac_greek' + 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' + 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­', + 'x-mac-icelandic': // Python: 'mac_iceland' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', + 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT + 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' + 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł', + 'x-mac-ce': // Python: 'mac_latin2' + 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' + 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ', + macintosh: // Python: 'mac_roman' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', + 'x-mac-romanian': // Python: 'mac_romanian' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', + 'x-mac-turkish': // Python: 'mac_turkish' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ' + }; + /** + * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript + * string, or 'undefined' if the encoding is unsupported. For example, we do + * not support Chinese, Japanese or Korean because these would need large + * mapping tables. + * @param {DataView} dataView + * @param {number} offset + * @param {number} dataLength + * @param {string} encoding + * @returns {string} + */ + decode.MACSTRING = function (dataView, offset, dataLength, encoding) { + var table = eightBitMacEncodings[encoding]; + if (table === undefined) { + return undefined; + } + var result = ''; + for (var i = 0; i < dataLength; i++) { + var c = dataView.getUint8(offset + i); + // In all eight-bit Mac encodings, the characters 0x00..0x7F are + // mapped to U+0000..U+007F; we only need to look up the others. + if (c <= 127) { + result += String.fromCharCode(c); + } else { + result += table[c & 127]; + } + } + return result; + }; + // Helper function for encode.MACSTRING. Returns a dictionary for mapping + // Unicode character codes to their 8-bit MacOS equivalent. This table + // is not exactly a super cheap data structure, but we do not care because + // encoding Macintosh strings is only rarely needed in typical applications. + var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap(); + var macEncodingCacheKeys; + var getMacEncodingTable = function (encoding) { + // Since we use encoding as a cache key for WeakMap, it has to be + // a String object and not a literal. And at least on NodeJS 2.10.1, + // WeakMap requires that the same String instance is passed for cache hits. + if (!macEncodingCacheKeys) { + macEncodingCacheKeys = { + }; + for (var e in eightBitMacEncodings) { + /*jshint -W053 */ // Suppress "Do not use String as a constructor." + macEncodingCacheKeys[e] = new String(e); + } + } + var cacheKey = macEncodingCacheKeys[encoding]; + if (cacheKey === undefined) { + return undefined; + } // We can't do "if (cache.has(key)) {return cache.get(key)}" here: + // since garbage collection may run at any time, it could also kick in + // between the calls to cache.has() and cache.get(). In that case, + // we would return 'undefined' even though we do support the encoding. + + if (macEncodingTableCache) { + var cachedTable = macEncodingTableCache.get(cacheKey); + if (cachedTable !== undefined) { + return cachedTable; + } + } + var decodingTable = eightBitMacEncodings[encoding]; + if (decodingTable === undefined) { + return undefined; + } + var encodingTable = { + }; + for (var i = 0; i < decodingTable.length; i++) { + encodingTable[decodingTable.charCodeAt(i)] = i + 128; + } + if (macEncodingTableCache) { + macEncodingTableCache.set(cacheKey, encodingTable); + } + return encodingTable; + }; + /** + * Encodes an old-style Macintosh string. Returns a byte array upon success. + * If the requested encoding is unsupported, or if the input string contains + * a character that cannot be expressed in the encoding, the function returns + * 'undefined'. + * @param {string} str + * @param {string} encoding + * @returns {Array} + */ + encode.MACSTRING = function (str, encoding) { + var table = getMacEncodingTable(encoding); + if (table === undefined) { + return undefined; + } + var result = [ + ]; + for (var i = 0; i < str.length; i++) { + var c = str.charCodeAt(i); + // In all eight-bit Mac encodings, the characters 0x00..0x7F are + // mapped to U+0000..U+007F; we only need to look up the others. + if (c >= 128) { + c = table[c]; + if (c === undefined) { + // str contains a Unicode character that cannot be encoded + // in the requested encoding. + return undefined; + } + } + result[i] = c; + // result.push(c); + } + return result; + }; + /** + * @param {string} str + * @param {string} encoding + * @returns {number} + */ + sizeOf.MACSTRING = function (str, encoding) { + var b = encode.MACSTRING(str, encoding); + if (b !== undefined) { + return b.length; + } else { + return 0; + } + }; + // Helper for encode.VARDELTAS + function isByteEncodable(value) { + return value >= - 128 && value <= 127; + } // Helper for encode.VARDELTAS + + function encodeVarDeltaRunAsZeroes(deltas, pos, result) { + var runLength = 0; + var numDeltas = deltas.length; + while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) { + ++pos; + ++runLength; + } + result.push(128 | runLength - 1); + return pos; + } // Helper for encode.VARDELTAS + + function encodeVarDeltaRunAsBytes(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value = deltas[pos]; + if (!isByteEncodable(value)) { + break; + } // Within a byte-encoded run of deltas, a single zero is best + // stored literally as 0x00 value. However, if we have two or + // more zeroes in a sequence, it is better to start a new run. + // Fore example, the sequence of deltas [15, 15, 0, 15, 15] + // becomes 6 bytes (04 0F 0F 00 0F 0F) when storing the zero + // within the current run, but 7 bytes (01 0F 0F 80 01 0F 0F) + // when starting a new run. + + if (value === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) { + break; + } + ++pos; + ++runLength; + } + result.push(runLength - 1); + for (var i = offset; i < pos; ++i) { + result.push(deltas[i] + 256 & 255); + } + return pos; + } // Helper for encode.VARDELTAS + + function encodeVarDeltaRunAsWords(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value = deltas[pos]; + // Within a word-encoded run of deltas, it is easiest to start + // a new run (with a different encoding) whenever we encounter + // a zero value. For example, the sequence [0x6666, 0, 0x7777] + // needs 7 bytes when storing the zero inside the current run + // (42 66 66 00 00 77 77), and equally 7 bytes when starting a + // new run (40 66 66 80 40 77 77). + if (value === 0) { + break; + } // Within a word-encoded run of deltas, a single value in the + // range (-128..127) should be encoded within the current run + // because it is more compact. For example, the sequence + // [0x6666, 2, 0x7777] becomes 7 bytes when storing the value + // literally (42 66 66 00 02 77 77), but 8 bytes when starting + // a new run (40 66 66 00 02 40 77 77). + + if (isByteEncodable(value) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) { + break; + } + ++pos; + ++runLength; + } + result.push(64 | runLength - 1); + for (var i = offset; i < pos; ++i) { + var val = deltas[i]; + result.push(val + 65536 >> 8 & 255, val + 256 & 255); + } + return pos; + } /** + * Encode a list of variation adjustment deltas. + * + * Variation adjustment deltas are used in ‘gvar’ and ‘cvar’ tables. + * They indicate how points (in ‘gvar’) or values (in ‘cvar’) get adjusted + * when generating instances of variation fonts. + * + * @see https://www.microsoft.com/typography/otspec/gvar.htm + * @see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html + * @param {Array} + * @return {Array} + */ + + encode.VARDELTAS = function (deltas) { + var pos = 0; + var result = [ + ]; + while (pos < deltas.length) { + var value = deltas[pos]; + if (value === 0) { + pos = encodeVarDeltaRunAsZeroes(deltas, pos, result); + } else if (value >= - 128 && value <= 127) { + pos = encodeVarDeltaRunAsBytes(deltas, pos, result); + } else { + pos = encodeVarDeltaRunAsWords(deltas, pos, result); + } + } + return result; + }; + // Convert a list of values to a CFF INDEX structure. + // The values should be objects containing name / type / value. + /** + * @param {Array} l + * @returns {Array} + */ + encode.INDEX = function (l) { + //var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data, + // i, v; + // Because we have to know which data type to use to encode the offsets, + // we have to go through the values twice: once to encode the data and + // calculate the offsets, then again to encode the offsets using the fitting data type. + var offset = 1; // First offset is always 1. + var offsets = [ + offset + ]; + var data = [ + ]; + for (var i = 0; i < l.length; i += 1) { + var v = encode.OBJECT(l[i]); + Array.prototype.push.apply(data, v); + offset += v.length; + offsets.push(offset); + } + if (data.length === 0) { + return [0, + 0]; + } + var encodedOffsets = [ + ]; + var offSize = 1 + Math.floor(Math.log(offset) / Math.log(2)) / 8 | 0; + var offsetEncoder = [ + undefined, + encode.BYTE, + encode.USHORT, + encode.UINT24, + encode.ULONG + ][offSize]; + for (var i$1 = 0; i$1 < offsets.length; i$1 += 1) { + var encodedOffset = offsetEncoder(offsets[i$1]); + Array.prototype.push.apply(encodedOffsets, encodedOffset); + } + return Array.prototype.concat(encode.Card16(l.length), encode.OffSize(offSize), encodedOffsets, data); + }; + /** + * @param {Array} + * @returns {number} + */ + sizeOf.INDEX = function (v) { + return encode.INDEX(v).length; + }; + /** + * Convert an object to a CFF DICT structure. + * The keys should be numeric. + * The values should be objects containing name / type / value. + * @param {Object} m + * @returns {Array} + */ + encode.DICT = function (m) { + var d = [ + ]; + var keys = Object.keys(m); + var length = keys.length; + for (var i = 0; i < length; i += 1) { + // Object.keys() return string keys, but our keys are always numeric. + var k = parseInt(keys[i], 0); + var v = m[k]; + // Value comes before the key. + d = d.concat(encode.OPERAND(v.value, v.type)); + d = d.concat(encode.OPERATOR(k)); + } + return d; + }; + /** + * @param {Object} + * @returns {number} + */ + sizeOf.DICT = function (m) { + return encode.DICT(m).length; + }; + /** + * @param {number} + * @returns {Array} + */ + encode.OPERATOR = function (v) { + if (v < 1200) { + return [v]; + } else { + return [12, + v - 1200]; + } + }; + /** + * @param {Array} v + * @param {string} + * @returns {Array} + */ + encode.OPERAND = function (v, type) { + var d = [ + ]; + if (Array.isArray(type)) { + for (var i = 0; i < type.length; i += 1) { + check.argument(v.length === type.length, 'Not enough arguments given for type' + type); + d = d.concat(encode.OPERAND(v[i], type[i])); + } + } else { + if (type === 'SID') { + d = d.concat(encode.NUMBER(v)); + } else if (type === 'offset') { + // We make it easy for ourselves and always encode offsets as + // 4 bytes. This makes offset calculation for the top dict easier. + d = d.concat(encode.NUMBER32(v)); + } else if (type === 'number') { + d = d.concat(encode.NUMBER(v)); + } else if (type === 'real') { + d = d.concat(encode.REAL(v)); + } else { + throw new Error('Unknown operand type ' + type); + // FIXME Add support for booleans + } + } + return d; + }; + encode.OP = encode.BYTE; + sizeOf.OP = sizeOf.BYTE; + // memoize charstring encoding using WeakMap if available + var wmm = typeof WeakMap === 'function' && new WeakMap(); + /** + * Convert a list of CharString operations to bytes. + * @param {Array} + * @returns {Array} + */ + encode.CHARSTRING = function (ops) { + // See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))". + if (wmm) { + var cachedValue = wmm.get(ops); + if (cachedValue !== undefined) { + return cachedValue; + } + } + var d = [ + ]; + var length = ops.length; + for (var i = 0; i < length; i += 1) { + var op = ops[i]; + d = d.concat(encode[op.type](op.value)); + } + if (wmm) { + wmm.set(ops, d); + } + return d; + }; + /** + * @param {Array} + * @returns {number} + */ + sizeOf.CHARSTRING = function (ops) { + return encode.CHARSTRING(ops).length; + }; + // Utility functions //////////////////////////////////////////////////////// + /** + * Convert an object containing name / type / value to bytes. + * @param {Object} + * @returns {Array} + */ + encode.OBJECT = function (v) { + var encodingFunction = encode[v.type]; + check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type); + return encodingFunction(v.value); + }; + /** + * @param {Object} + * @returns {number} + */ + sizeOf.OBJECT = function (v) { + var sizeOfFunction = sizeOf[v.type]; + check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type); + return sizeOfFunction(v.value); + }; + /** + * Convert a table object to bytes. + * A table contains a list of fields containing the metadata (name, type and default value). + * The table itself has the field values set as attributes. + * @param {opentype.Table} + * @returns {Array} + */ + encode.TABLE = function (table) { + var d = [ + ]; + var length = table.fields.length; + var subtables = [ + ]; + var subtableOffsets = [ + ]; + for (var i = 0; i < length; i += 1) { + var field = table.fields[i]; + var encodingFunction = encode[field.type]; + check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')'); + var value = table[field.name]; + if (value === undefined) { + value = field.value; + } + var bytes = encodingFunction(value); + if (field.type === 'TABLE') { + subtableOffsets.push(d.length); + d = d.concat([0, + 0]); + subtables.push(bytes); + } else { + d = d.concat(bytes); + } + } + for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) { + var o = subtableOffsets[i$1]; + var offset = d.length; + check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.'); + d[o] = offset >> 8; + d[o + 1] = offset & 255; + d = d.concat(subtables[i$1]); + } + return d; + }; + /** + * @param {opentype.Table} + * @returns {number} + */ + sizeOf.TABLE = function (table) { + var numBytes = 0; + var length = table.fields.length; + for (var i = 0; i < length; i += 1) { + var field = table.fields[i]; + var sizeOfFunction = sizeOf[field.type]; + check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')'); + var value = table[field.name]; + if (value === undefined) { + value = field.value; + } + numBytes += sizeOfFunction(value); + // Subtables take 2 more bytes for offsets. + if (field.type === 'TABLE') { + numBytes += 2; + } + } + return numBytes; + }; + encode.RECORD = encode.TABLE; + sizeOf.RECORD = sizeOf.TABLE; + // Merge in a list of bytes. + encode.LITERAL = function (v) { + return v; + }; + sizeOf.LITERAL = function (v) { + return v.length; + }; + // Table metadata + /** + * @exports opentype.Table + * @class + * @param {string} tableName + * @param {Array} fields + * @param {Object} options + * @constructor + */ + function Table(tableName, fields, options) { + var this$1 = this; + for (var i = 0; i < fields.length; i += 1) { + var field = fields[i]; + this$1[field.name] = field.value; + } + this.tableName = tableName; + this.fields = fields; + if (options) { + var optionKeys = Object.keys(options); + for (var i$1 = 0; i$1 < optionKeys.length; i$1 += 1) { + var k = optionKeys[i$1]; + var v = options[k]; + if (this$1[k] !== undefined) { + this$1[k] = v; + } + } + } + } /** + * Encodes the table and returns an array of bytes + * @return {Array} + */ + + Table.prototype.encode = function () { + return encode.TABLE(this); + }; + /** + * Get the size of the table. + * @return {number} + */ + Table.prototype.sizeOf = function () { + return sizeOf.TABLE(this); + }; + /** + * @private + */ + function ushortList(itemName, list, count) { + if (count === undefined) { + count = list.length; + } + var fields = new Array(list.length + 1); + fields[0] = { + name: itemName + 'Count', + type: 'USHORT', + value: count + }; + for (var i = 0; i < list.length; i++) { + fields[i + 1] = { + name: itemName + i, + type: 'USHORT', + value: list[i] + }; + } + return fields; + } /** + * @private + */ + + function tableList(itemName, records, itemCallback) { + var count = records.length; + var fields = new Array(count + 1); + fields[0] = { + name: itemName + 'Count', + type: 'USHORT', + value: count + }; + for (var i = 0; i < count; i++) { + fields[i + 1] = { + name: itemName + i, + type: 'TABLE', + value: itemCallback(records[i], i) + }; + } + return fields; + } /** + * @private + */ + + function recordList(itemName, records, itemCallback) { + var count = records.length; + var fields = [ + ]; + fields[0] = { + name: itemName + 'Count', + type: 'USHORT', + value: count + }; + for (var i = 0; i < count; i++) { + fields = fields.concat(itemCallback(records[i], i)); + } + return fields; + } // Common Layout Tables + /** + * @exports opentype.Coverage + * @class + * @param {opentype.Table} + * @constructor + * @extends opentype.Table + */ + + function Coverage(coverageTable) { + if (coverageTable.format === 1) { + Table.call(this, 'coverageTable', [ + { + name: 'coverageFormat', + type: 'USHORT', + value: 1 + } + ].concat(ushortList('glyph', coverageTable.glyphs))); + } else { + check.assert(false, 'Can\'t create coverage table format 2 yet.'); + } + } + Coverage.prototype = Object.create(Table.prototype); + Coverage.prototype.constructor = Coverage; + function ScriptList(scriptListTable) { + Table.call(this, 'scriptListTable', recordList('scriptRecord', scriptListTable, function (scriptRecord, i) { + var script = scriptRecord.script; + var defaultLangSys = script.defaultLangSys; + check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.'); + return [{ + name: 'scriptTag' + i, + type: 'TAG', + value: scriptRecord.tag + }, + { + name: 'script' + i, + type: 'TABLE', + value: new Table('scriptTable', [ + { + name: 'defaultLangSys', + type: 'TABLE', + value: new Table('defaultLangSys', [ + { + name: 'lookupOrder', + type: 'USHORT', + value: 0 + }, + { + name: 'reqFeatureIndex', + type: 'USHORT', + value: defaultLangSys.reqFeatureIndex + } + ].concat(ushortList('featureIndex', defaultLangSys.featureIndexes))) + } + ].concat(recordList('langSys', script.langSysRecords, function (langSysRecord, i) { + var langSys = langSysRecord.langSys; + return [{ + name: 'langSysTag' + i, + type: 'TAG', + value: langSysRecord.tag + }, + { + name: 'langSys' + i, + type: 'TABLE', + value: new Table('langSys', [ + { + name: 'lookupOrder', + type: 'USHORT', + value: 0 + }, + { + name: 'reqFeatureIndex', + type: 'USHORT', + value: langSys.reqFeatureIndex + } + ].concat(ushortList('featureIndex', langSys.featureIndexes))) + } + ]; + }))) + } + ]; + })); + } + ScriptList.prototype = Object.create(Table.prototype); + ScriptList.prototype.constructor = ScriptList; + /** + * @exports opentype.FeatureList + * @class + * @param {opentype.Table} + * @constructor + * @extends opentype.Table + */ + function FeatureList(featureListTable) { + Table.call(this, 'featureListTable', recordList('featureRecord', featureListTable, function (featureRecord, i) { + var feature = featureRecord.feature; + return [{ + name: 'featureTag' + i, + type: 'TAG', + value: featureRecord.tag + }, + { + name: 'feature' + i, + type: 'TABLE', + value: new Table('featureTable', [ + { + name: 'featureParams', + type: 'USHORT', + value: feature.featureParams + } + ].concat(ushortList('lookupListIndex', feature.lookupListIndexes))) + } + ]; + })); + } + FeatureList.prototype = Object.create(Table.prototype); + FeatureList.prototype.constructor = FeatureList; + /** + * @exports opentype.LookupList + * @class + * @param {opentype.Table} + * @param {Object} + * @constructor + * @extends opentype.Table + */ + function LookupList(lookupListTable, subtableMakers) { + Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function (lookupTable) { + var subtableCallback = subtableMakers[lookupTable.lookupType]; + check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.'); + return new Table('lookupTable', [ + { + name: 'lookupType', + type: 'USHORT', + value: lookupTable.lookupType + }, + { + name: 'lookupFlag', + type: 'USHORT', + value: lookupTable.lookupFlag + } + ].concat(tableList('subtable', lookupTable.subtables, subtableCallback))); + })); + } + LookupList.prototype = Object.create(Table.prototype); + LookupList.prototype.constructor = LookupList; + // Record = same as Table, but inlined (a Table has an offset and its data is further in the stream) + // Don't use offsets inside Records (probable bug), only in Tables. + var table = { + Table: Table, + Record: Table, + Coverage: Coverage, + ScriptList: ScriptList, + FeatureList: FeatureList, + LookupList: LookupList, + ushortList: ushortList, + tableList: tableList, + recordList: recordList + }; + // Parsing utility functions + // Retrieve an unsigned byte from the DataView. + function getByte(dataView, offset) { + return dataView.getUint8(offset); + } // Retrieve an unsigned 16-bit short from the DataView. + // The value is stored in big endian. + + function getUShort(dataView, offset) { + return dataView.getUint16(offset, false); + } // Retrieve a signed 16-bit short from the DataView. + // The value is stored in big endian. + + function getShort(dataView, offset) { + return dataView.getInt16(offset, false); + } // Retrieve an unsigned 32-bit long from the DataView. + // The value is stored in big endian. + + function getULong(dataView, offset) { + return dataView.getUint32(offset, false); + } // Retrieve a 32-bit signed fixed-point number (16.16) from the DataView. + // The value is stored in big endian. + + function getFixed(dataView, offset) { + var decimal = dataView.getInt16(offset, false); + var fraction = dataView.getUint16(offset + 2, false); + return decimal + fraction / 65535; + } // Retrieve a 4-character tag from the DataView. + // Tags are used to identify tables. + + function getTag(dataView, offset) { + var tag = ''; + for (var i = offset; i < offset + 4; i += 1) { + tag += String.fromCharCode(dataView.getInt8(i)); + } + return tag; + } // Retrieve an offset from the DataView. + // Offsets are 1 to 4 bytes in length, depending on the offSize argument. + + function getOffset(dataView, offset, offSize) { + var v = 0; + for (var i = 0; i < offSize; i += 1) { + v <<= 8; + v += dataView.getUint8(offset + i); + } + return v; + } // Retrieve a number of bytes from start offset to the end offset from the DataView. + + function getBytes(dataView, startOffset, endOffset) { + var bytes = [ + ]; + for (var i = startOffset; i < endOffset; i += 1) { + bytes.push(dataView.getUint8(i)); + } + return bytes; + } // Convert the list of bytes to a string. + + function bytesToString(bytes) { + var s = ''; + for (var i = 0; i < bytes.length; i += 1) { + s += String.fromCharCode(bytes[i]); + } + return s; + } + var typeOffsets = { + byte: 1, + uShort: 2, + short: 2, + uLong: 4, + fixed: 4, + longDateTime: 8, + tag: 4 + }; + // A stateful parser that changes the offset whenever a value is retrieved. + // The data is a DataView. + function Parser(data, offset) { + this.data = data; + this.offset = offset; + this.relativeOffset = 0; + } + Parser.prototype.parseByte = function () { + var v = this.data.getUint8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; + }; + Parser.prototype.parseChar = function () { + var v = this.data.getInt8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; + }; + Parser.prototype.parseCard8 = Parser.prototype.parseByte; + Parser.prototype.parseUShort = function () { + var v = this.data.getUint16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; + }; + Parser.prototype.parseCard16 = Parser.prototype.parseUShort; + Parser.prototype.parseSID = Parser.prototype.parseUShort; + Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; + Parser.prototype.parseShort = function () { + var v = this.data.getInt16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; + }; + Parser.prototype.parseF2Dot14 = function () { + var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; + this.relativeOffset += 2; + return v; + }; + Parser.prototype.parseULong = function () { + var v = getULong(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; + }; + Parser.prototype.parseOffset32 = Parser.prototype.parseULong; + Parser.prototype.parseFixed = function () { + var v = getFixed(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; + }; + Parser.prototype.parseString = function (length) { + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + var string = ''; + this.relativeOffset += length; + for (var i = 0; i < length; i++) { + string += String.fromCharCode(dataView.getUint8(offset + i)); + } + return string; + }; + Parser.prototype.parseTag = function () { + return this.parseString(4); + }; + // LONGDATETIME is a 64-bit integer. + // JavaScript and unix timestamps traditionally use 32 bits, so we + // only take the last 32 bits. + // + Since until 2038 those bits will be filled by zeros we can ignore them. + Parser.prototype.parseLongDateTime = function () { + var v = getULong(this.data, this.offset + this.relativeOffset + 4); + // Subtract seconds between 01/01/1904 and 01/01/1970 + // to convert Apple Mac timestamp to Standard Unix timestamp + v -= 2082844800; + this.relativeOffset += 8; + return v; + }; + Parser.prototype.parseVersion = function (minorBase) { + var major = getUShort(this.data, this.offset + this.relativeOffset); + // How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1 + // Default returns the correct number if minor = 0xN000 where N is 0-9 + // Set minorBase to 1 for tables that use minor = N where N is 0-9 + var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); + this.relativeOffset += 4; + if (minorBase === undefined) { + minorBase = 4096; + } + return major + minor / minorBase / 10; + }; + Parser.prototype.skip = function (type, amount) { + if (amount === undefined) { + amount = 1; + } + this.relativeOffset += typeOffsets[type] * amount; + }; + ///// Parsing lists and records /////////////////////////////// + // Parse a list of 32 bit unsigned integers. + Parser.prototype.parseULongList = function (count) { + if (count === undefined) { + count = this.parseULong(); + } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0; i < count; i++) { + offsets[i] = dataView.getUint32(offset); + offset += 4; + } + this.relativeOffset += count * 4; + return offsets; + }; + // Parse a list of 16 bit unsigned integers. The length of the list can be read on the stream + // or provided as an argument. + Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function (count) { + if (count === undefined) { + count = this.parseUShort(); + } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0; i < count; i++) { + offsets[i] = dataView.getUint16(offset); + offset += 2; + } + this.relativeOffset += count * 2; + return offsets; + }; + // Parses a list of 16 bit signed integers. + Parser.prototype.parseShortList = function (count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0; i < count; i++) { + list[i] = dataView.getInt16(offset); + offset += 2; + } + this.relativeOffset += count * 2; + return list; + }; + // Parses a list of bytes. + Parser.prototype.parseByteList = function (count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0; i < count; i++) { + list[i] = dataView.getUint8(offset++); + } + this.relativeOffset += count; + return list; + }; + /** + * Parse a list of items. + * Record count is optional, if omitted it is read from the stream. + * itemCallback is one of the Parser methods. + */ + Parser.prototype.parseList = function (count, itemCallback) { + var this$1 = this; + if (!itemCallback) { + itemCallback = count; + count = this.parseUShort(); + } + var list = new Array(count); + for (var i = 0; i < count; i++) { + list[i] = itemCallback.call(this$1); + } + return list; + }; + Parser.prototype.parseList32 = function (count, itemCallback) { + var this$1 = this; + if (!itemCallback) { + itemCallback = count; + count = this.parseULong(); + } + var list = new Array(count); + for (var i = 0; i < count; i++) { + list[i] = itemCallback.call(this$1); + } + return list; + }; + /** + * Parse a list of records. + * Record count is optional, if omitted it is read from the stream. + * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } + */ + Parser.prototype.parseRecordList = function (count, recordDescription) { + var this$1 = this; + // If the count argument is absent, read it in the stream. + if (!recordDescription) { + recordDescription = count; + count = this.parseUShort(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0; i < count; i++) { + var rec = { + }; + for (var j = 0; j < fields.length; j++) { + var fieldName = fields[j]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this$1); + } + records[i] = rec; + } + return records; + }; + Parser.prototype.parseRecordList32 = function (count, recordDescription) { + var this$1 = this; + // If the count argument is absent, read it in the stream. + if (!recordDescription) { + recordDescription = count; + count = this.parseULong(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0; i < count; i++) { + var rec = { + }; + for (var j = 0; j < fields.length; j++) { + var fieldName = fields[j]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this$1); + } + records[i] = rec; + } + return records; + }; + // Parse a data structure into an object + // Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } + Parser.prototype.parseStruct = function (description) { + var this$1 = this; + if (typeof description === 'function') { + return description.call(this); + } else { + var fields = Object.keys(description); + var struct = { + }; + for (var j = 0; j < fields.length; j++) { + var fieldName = fields[j]; + var fieldType = description[fieldName]; + struct[fieldName] = fieldType.call(this$1); + } + return struct; + } + }; + /** + * Parse a GPOS valueRecord + * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record + * valueFormat is optional, if omitted it is read from the stream. + */ + Parser.prototype.parseValueRecord = function (valueFormat) { + if (valueFormat === undefined) { + valueFormat = this.parseUShort(); + } + if (valueFormat === 0) { + // valueFormat2 in kerning pairs is most often 0 + // in this case return undefined instead of an empty object, to save space + return; + } + var valueRecord = { + }; + if (valueFormat & 1) { + valueRecord.xPlacement = this.parseShort(); + } + if (valueFormat & 2) { + valueRecord.yPlacement = this.parseShort(); + } + if (valueFormat & 4) { + valueRecord.xAdvance = this.parseShort(); + } + if (valueFormat & 8) { + valueRecord.yAdvance = this.parseShort(); + } // Device table (non-variable font) / VariationIndex table (variable font) not supported + // https://docs.microsoft.com/fr-fr/typography/opentype/spec/chapter2#devVarIdxTbls + + if (valueFormat & 16) { + valueRecord.xPlaDevice = undefined; + this.parseShort(); + } + if (valueFormat & 32) { + valueRecord.yPlaDevice = undefined; + this.parseShort(); + } + if (valueFormat & 64) { + valueRecord.xAdvDevice = undefined; + this.parseShort(); + } + if (valueFormat & 128) { + valueRecord.yAdvDevice = undefined; + this.parseShort(); + } + return valueRecord; + }; + /** + * Parse a list of GPOS valueRecords + * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record + * valueFormat and valueCount are read from the stream. + */ + Parser.prototype.parseValueRecordList = function () { + var this$1 = this; + var valueFormat = this.parseUShort(); + var valueCount = this.parseUShort(); + var values = new Array(valueCount); + for (var i = 0; i < valueCount; i++) { + values[i] = this$1.parseValueRecord(valueFormat); + } + return values; + }; + Parser.prototype.parsePointer = function (description) { + var structOffset = this.parseOffset16(); + if (structOffset > 0) { + // NULL offset => return undefined + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return undefined; + }; + Parser.prototype.parsePointer32 = function (description) { + var structOffset = this.parseOffset32(); + if (structOffset > 0) { + // NULL offset => return undefined + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return undefined; + }; + /** + * Parse a list of offsets to lists of 16-bit integers, + * or a list of offsets to lists of offsets to any kind of items. + * If itemCallback is not provided, a list of list of UShort is assumed. + * If provided, itemCallback is called on each item and must parse the item. + * See examples in tables/gsub.js + */ + Parser.prototype.parseListOfLists = function (itemCallback) { + var this$1 = this; + var offsets = this.parseOffset16List(); + var count = offsets.length; + var relativeOffset = this.relativeOffset; + var list = new Array(count); + for (var i = 0; i < count; i++) { + var start = offsets[i]; + if (start === 0) { + // NULL offset + // Add i as owned property to list. Convenient with assert. + list[i] = undefined; + continue; + } + this$1.relativeOffset = start; + if (itemCallback) { + var subOffsets = this$1.parseOffset16List(); + var subList = new Array(subOffsets.length); + for (var j = 0; j < subOffsets.length; j++) { + this$1.relativeOffset = start + subOffsets[j]; + subList[j] = itemCallback.call(this$1); + } + list[i] = subList; + } else { + list[i] = this$1.parseUShortList(); + } + } + this.relativeOffset = relativeOffset; + return list; + }; + ///// Complex tables parsing ////////////////////////////////// + // Parse a coverage table in a GSUB, GPOS or GDEF table. + // https://www.microsoft.com/typography/OTSPEC/chapter2.htm + // parser.offset must point to the start of the table containing the coverage. + Parser.prototype.parseCoverage = function () { + var this$1 = this; + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + var count = this.parseUShort(); + if (format === 1) { + return { + format: 1, + glyphs: this.parseUShortList(count) + }; + } else if (format === 2) { + var ranges = new Array(count); + for (var i = 0; i < count; i++) { + ranges[i] = { + start: this$1.parseUShort(), + end: this$1.parseUShort(), + index: this$1.parseUShort() + }; + } + return { + format: 2, + ranges: ranges + }; + } + throw new Error('0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.'); + }; + // Parse a Class Definition Table in a GSUB, GPOS or GDEF table. + // https://www.microsoft.com/typography/OTSPEC/chapter2.htm + Parser.prototype.parseClassDef = function () { + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + if (format === 1) { + return { + format: 1, + startGlyph: this.parseUShort(), + classes: this.parseUShortList() + }; + } else if (format === 2) { + return { + format: 2, + ranges: this.parseRecordList({ + start: Parser.uShort, + end: Parser.uShort, + classId: Parser.uShort + }) + }; + } + throw new Error('0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.'); + }; + ///// Static methods /////////////////////////////////// + // These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance. + Parser.list = function (count, itemCallback) { + return function () { + return this.parseList(count, itemCallback); + }; + }; + Parser.list32 = function (count, itemCallback) { + return function () { + return this.parseList32(count, itemCallback); + }; + }; + Parser.recordList = function (count, recordDescription) { + return function () { + return this.parseRecordList(count, recordDescription); + }; + }; + Parser.recordList32 = function (count, recordDescription) { + return function () { + return this.parseRecordList32(count, recordDescription); + }; + }; + Parser.pointer = function (description) { + return function () { + return this.parsePointer(description); + }; + }; + Parser.pointer32 = function (description) { + return function () { + return this.parsePointer32(description); + }; + }; + Parser.tag = Parser.prototype.parseTag; + Parser.byte = Parser.prototype.parseByte; + Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; + Parser.uShortList = Parser.prototype.parseUShortList; + Parser.uLong = Parser.offset32 = Parser.prototype.parseULong; + Parser.uLongList = Parser.prototype.parseULongList; + Parser.struct = Parser.prototype.parseStruct; + Parser.coverage = Parser.prototype.parseCoverage; + Parser.classDef = Parser.prototype.parseClassDef; + ///// Script, Feature, Lookup lists /////////////////////////////////////////////// + // https://www.microsoft.com/typography/OTSPEC/chapter2.htm + var langSysTable = { + reserved: Parser.uShort, + reqFeatureIndex: Parser.uShort, + featureIndexes: Parser.uShortList + }; + Parser.prototype.parseScriptList = function () { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + script: Parser.pointer({ + defaultLangSys: Parser.pointer(langSysTable), + langSysRecords: Parser.recordList({ + tag: Parser.tag, + langSys: Parser.pointer(langSysTable) + }) + }) + })) || [ + ]; + }; + Parser.prototype.parseFeatureList = function () { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + feature: Parser.pointer({ + featureParams: Parser.offset16, + lookupListIndexes: Parser.uShortList + }) + })) || [ + ]; + }; + Parser.prototype.parseLookupList = function (lookupTableParsers) { + return this.parsePointer(Parser.list(Parser.pointer(function () { + var lookupType = this.parseUShort(); + check.argument(1 <= lookupType && lookupType <= 9, 'GPOS/GSUB lookup type ' + lookupType + ' unknown.'); + var lookupFlag = this.parseUShort(); + var useMarkFilteringSet = lookupFlag & 16; + return { + lookupType: lookupType, + lookupFlag: lookupFlag, + subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), + markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined + }; + }))) || [ + ]; + }; + Parser.prototype.parseFeatureVariationsList = function () { + return this.parsePointer32(function () { + var majorVersion = this.parseUShort(); + var minorVersion = this.parseUShort(); + check.argument(majorVersion === 1 && minorVersion < 1, 'GPOS/GSUB feature variations table unknown.'); + var featureVariations = this.parseRecordList32({ + conditionSetOffset: Parser.offset32, + featureTableSubstitutionOffset: Parser.offset32 + }); + return featureVariations; + }) || [ + ]; + }; + var parse = { + getByte: getByte, + getCard8: getByte, + getUShort: getUShort, + getCard16: getUShort, + getShort: getShort, + getULong: getULong, + getFixed: getFixed, + getTag: getTag, + getOffset: getOffset, + getBytes: getBytes, + bytesToString: bytesToString, + Parser: Parser + }; + // The `cmap` table stores the mappings from characters to glyphs. + function parseCmapTableFormat12(cmap, p) { + //Skip reserved. + p.parseUShort(); + // Length in bytes of the sub-tables. + cmap.length = p.parseULong(); + cmap.language = p.parseULong(); + var groupCount; + cmap.groupCount = groupCount = p.parseULong(); + cmap.glyphIndexMap = { + }; + for (var i = 0; i < groupCount; i += 1) { + var startCharCode = p.parseULong(); + var endCharCode = p.parseULong(); + var startGlyphId = p.parseULong(); + for (var c = startCharCode; c <= endCharCode; c += 1) { + cmap.glyphIndexMap[c] = startGlyphId; + startGlyphId++; + } + } + } + function parseCmapTableFormat4(cmap, p, data, start, offset) { + // Length in bytes of the sub-tables. + cmap.length = p.parseUShort(); + cmap.language = p.parseUShort(); + // segCount is stored x 2. + var segCount; + cmap.segCount = segCount = p.parseUShort() >> 1; + // Skip searchRange, entrySelector, rangeShift. + p.skip('uShort', 3); + // The "unrolled" mapping from character codes to glyph indices. + cmap.glyphIndexMap = { + }; + var endCountParser = new parse.Parser(data, start + offset + 14); + var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2); + var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4); + var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6); + var glyphIndexOffset = start + offset + 16 + segCount * 8; + for (var i = 0; i < segCount - 1; i += 1) { + var glyphIndex = void 0; + var endCount = endCountParser.parseUShort(); + var startCount = startCountParser.parseUShort(); + var idDelta = idDeltaParser.parseShort(); + var idRangeOffset = idRangeOffsetParser.parseUShort(); + for (var c = startCount; c <= endCount; c += 1) { + if (idRangeOffset !== 0) { + // The idRangeOffset is relative to the current position in the idRangeOffset array. + // Take the current offset in the idRangeOffset array. + glyphIndexOffset = idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2; + // Add the value of the idRangeOffset, which will move us into the glyphIndex array. + glyphIndexOffset += idRangeOffset; + // Then add the character index of the current segment, multiplied by 2 for USHORTs. + glyphIndexOffset += (c - startCount) * 2; + glyphIndex = parse.getUShort(data, glyphIndexOffset); + if (glyphIndex !== 0) { + glyphIndex = glyphIndex + idDelta & 65535; + } + } else { + glyphIndex = c + idDelta & 65535; + } + cmap.glyphIndexMap[c] = glyphIndex; + } + } + } // Parse the `cmap` table. This table stores the mappings from characters to glyphs. + // There are many available formats, but we only support the Windows format 4 and 12. + // This function returns a `CmapEncoding` object or null if no supported format could be found. + + function parseCmapTable(data, start) { + var cmap = { + }; + cmap.version = parse.getUShort(data, start); + check.argument(cmap.version === 0, 'cmap table version should be 0.'); + // The cmap table can contain many sub-tables, each with their own format. + // We're only interested in a "platform 0" (Unicode format) and "platform 3" (Windows format) table. + cmap.numTables = parse.getUShort(data, start + 2); + var offset = - 1; + for (var i = cmap.numTables - 1; i >= 0; i -= 1) { + var platformId = parse.getUShort(data, start + 4 + i * 8); + var encodingId = parse.getUShort(data, start + 4 + i * 8 + 2); + if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10) || platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4)) { + offset = parse.getULong(data, start + 4 + i * 8 + 4); + break; + } + } + if (offset === - 1) { + // There is no cmap table in the font that we support. + throw new Error('No valid cmap sub-tables found.'); + } + var p = new parse.Parser(data, start + offset); + cmap.format = p.parseUShort(); + if (cmap.format === 12) { + parseCmapTableFormat12(cmap, p); + } else if (cmap.format === 4) { + parseCmapTableFormat4(cmap, p, data, start, offset); + } else { + throw new Error('Only format 4 and 12 cmap tables are supported (found format ' + cmap.format + ').'); + } + return cmap; + } + function addSegment(t, code, glyphIndex) { + t.segments.push({ + end: code, + start: code, + delta: - (code - glyphIndex), + offset: 0, + glyphIndex: glyphIndex + }); + } + function addTerminatorSegment(t) { + t.segments.push({ + end: 65535, + start: 65535, + delta: 1, + offset: 0 + }); + } // Make cmap table, format 4 by default, 12 if needed only + + function makeCmapTable(glyphs) { + // Plan 0 is the base Unicode Plan but emojis, for example are on another plan, and needs cmap 12 format (with 32bit) + var isPlan0Only = true; + var i; + // Check if we need to add cmap format 12 or if format 4 only is fine + for (i = glyphs.length - 1; i > 0; i -= 1) { + var g = glyphs.get(i); + if (g.unicode > 65535) { + console.log('Adding CMAP format 12 (needed!)'); + isPlan0Only = false; + break; + } + } + var cmapTable = [ + { + name: 'version', + type: 'USHORT', + value: 0 + }, + { + name: 'numTables', + type: 'USHORT', + value: isPlan0Only ? 1 : 2 + }, + // CMAP 4 header + { + name: 'platformID', + type: 'USHORT', + value: 3 + }, + { + name: 'encodingID', + type: 'USHORT', + value: 1 + }, + { + name: 'offset', + type: 'ULONG', + value: isPlan0Only ? 12 : 12 + 8 + } + ]; + if (!isPlan0Only) { + cmapTable = cmapTable.concat([ // CMAP 12 header + { + name: 'cmap12PlatformID', + type: 'USHORT', + value: 3 + }, + // We encode only for PlatformID = 3 (Windows) because it is supported everywhere + { + name: 'cmap12EncodingID', + type: 'USHORT', + value: 10 + }, + { + name: 'cmap12Offset', + type: 'ULONG', + value: 0 + } + ]); + } + cmapTable = cmapTable.concat([ // CMAP 4 Subtable + { + name: 'format', + type: 'USHORT', + value: 4 + }, + { + name: 'cmap4Length', + 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 + } + ]); + var t = new table.Table('cmap', cmapTable); + t.segments = [ + ]; + for (i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j = 0; j < glyph.unicodes.length; j += 1) { + addSegment(t, glyph.unicodes[j], i); + } + t.segments = t.segments.sort(function (a, b) { + return a.start - b.start; + }); + } + addTerminatorSegment(t); + var segCount = t.segments.length; + var segCountToRemove = 0; + // CMAP 4 + // Set up parallel segment arrays. + var endCounts = [ + ]; + var startCounts = [ + ]; + var idDeltas = [ + ]; + var idRangeOffsets = [ + ]; + var glyphIds = [ + ]; + // CMAP 12 + var cmap12Groups = [ + ]; + // Reminder this loop is not following the specification at 100% + // The specification -> find suites of characters and make a group + // Here we're doing one group for each letter + // Doing as the spec can save 8 times (or more) space + for (i = 0; i < segCount; i += 1) { + var segment = t.segments[i]; + // CMAP 4 + if (segment.end <= 65535 && segment.start <= 65535) { + endCounts = endCounts.concat({ + name: 'end_' + i, + type: 'USHORT', + value: segment.end + }); + startCounts = startCounts.concat({ + name: 'start_' + i, + type: 'USHORT', + value: segment.start + }); + idDeltas = idDeltas.concat({ + name: 'idDelta_' + i, + type: 'SHORT', + value: segment.delta + }); + idRangeOffsets = idRangeOffsets.concat({ + name: 'idRangeOffset_' + i, + type: 'USHORT', + value: segment.offset + }); + if (segment.glyphId !== undefined) { + glyphIds = glyphIds.concat({ + name: 'glyph_' + i, + type: 'USHORT', + value: segment.glyphId + }); + } + } else { + // Skip Unicode > 65535 (16bit unsigned max) for CMAP 4, will be added in CMAP 12 + segCountToRemove += 1; + } // CMAP 12 + // Skip Terminator Segment + + if (!isPlan0Only && segment.glyphIndex !== undefined) { + cmap12Groups = cmap12Groups.concat({ + name: 'cmap12Start_' + i, + type: 'ULONG', + value: segment.start + }); + cmap12Groups = cmap12Groups.concat({ + name: 'cmap12End_' + i, + type: 'ULONG', + value: segment.end + }); + cmap12Groups = cmap12Groups.concat({ + name: 'cmap12Glyph_' + i, + type: 'ULONG', + value: segment.glyphIndex + }); + } + } // CMAP 4 Subtable + + t.segCountX2 = (segCount - segCountToRemove) * 2; + t.searchRange = Math.pow(2, Math.floor(Math.log(segCount - segCountToRemove) / Math.log(2))) * 2; + t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2); + t.rangeShift = t.segCountX2 - t.searchRange; + t.fields = t.fields.concat(endCounts); + t.fields.push({ + name: 'reservedPad', + type: 'USHORT', + value: 0 + }); + t.fields = t.fields.concat(startCounts); + t.fields = t.fields.concat(idDeltas); + t.fields = t.fields.concat(idRangeOffsets); + t.fields = t.fields.concat(glyphIds); + t.cmap4Length = 14 + // Subtable header + endCounts.length * 2 + 2 + // reservedPad + startCounts.length * 2 + idDeltas.length * 2 + idRangeOffsets.length * 2 + glyphIds.length * 2; + if (!isPlan0Only) { + // CMAP 12 Subtable + var cmap12Length = 16 + // Subtable header + cmap12Groups.length * 4; + t.cmap12Offset = 12 + 2 * 2 + 4 + t.cmap4Length; + t.fields = t.fields.concat([{ + name: 'cmap12Format', + type: 'USHORT', + value: 12 + }, + { + name: 'cmap12Reserved', + type: 'USHORT', + value: 0 + }, + { + name: 'cmap12Length', + type: 'ULONG', + value: cmap12Length + }, + { + name: 'cmap12Language', + type: 'ULONG', + value: 0 + }, + { + name: 'cmap12nGroups', + type: 'ULONG', + value: cmap12Groups.length / 3 + } + ]); + t.fields = t.fields.concat(cmap12Groups); + } + return t; + } + var cmap = { + parse: parseCmapTable, + make: makeCmapTable + }; + // Glyph encoding + var cffStandardStrings = [ + '.notdef', + 'space', + 'exclam', + 'quotedbl', + 'numbersign', + 'dollar', + 'percent', + 'ampersand', + 'quoteright', + 'parenleft', + 'parenright', + 'asterisk', + 'plus', + 'comma', + 'hyphen', + 'period', + 'slash', + 'zero', + 'one', + 'two', + 'three', + 'four', + 'five', + 'six', + 'seven', + 'eight', + 'nine', + 'colon', + 'semicolon', + 'less', + 'equal', + 'greater', + 'question', + 'at', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z', + 'bracketleft', + 'backslash', + 'bracketright', + 'asciicircum', + 'underscore', + 'quoteleft', + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i', + 'j', + 'k', + 'l', + 'm', + 'n', + 'o', + 'p', + 'q', + 'r', + 's', + 't', + 'u', + 'v', + 'w', + 'x', + 'y', + 'z', + 'braceleft', + 'bar', + 'braceright', + 'asciitilde', + 'exclamdown', + 'cent', + 'sterling', + 'fraction', + 'yen', + 'florin', + 'section', + 'currency', + 'quotesingle', + 'quotedblleft', + 'guillemotleft', + 'guilsinglleft', + 'guilsinglright', + 'fi', + 'fl', + 'endash', + 'dagger', + 'daggerdbl', + 'periodcentered', + 'paragraph', + 'bullet', + 'quotesinglbase', + 'quotedblbase', + 'quotedblright', + 'guillemotright', + 'ellipsis', + 'perthousand', + 'questiondown', + 'grave', + 'acute', + 'circumflex', + 'tilde', + 'macron', + 'breve', + 'dotaccent', + 'dieresis', + 'ring', + 'cedilla', + 'hungarumlaut', + 'ogonek', + 'caron', + 'emdash', + 'AE', + 'ordfeminine', + 'Lslash', + 'Oslash', + 'OE', + 'ordmasculine', + 'ae', + 'dotlessi', + 'lslash', + 'oslash', + 'oe', + 'germandbls', + 'onesuperior', + 'logicalnot', + 'mu', + 'trademark', + 'Eth', + 'onehalf', + 'plusminus', + 'Thorn', + 'onequarter', + 'divide', + 'brokenbar', + 'degree', + 'thorn', + 'threequarters', + 'twosuperior', + 'registered', + 'minus', + 'eth', + 'multiply', + 'threesuperior', + 'copyright', + 'Aacute', + 'Acircumflex', + 'Adieresis', + 'Agrave', + 'Aring', + 'Atilde', + 'Ccedilla', + 'Eacute', + 'Ecircumflex', + 'Edieresis', + 'Egrave', + 'Iacute', + 'Icircumflex', + 'Idieresis', + 'Igrave', + 'Ntilde', + 'Oacute', + 'Ocircumflex', + 'Odieresis', + 'Ograve', + 'Otilde', + 'Scaron', + 'Uacute', + 'Ucircumflex', + 'Udieresis', + 'Ugrave', + 'Yacute', + 'Ydieresis', + 'Zcaron', + 'aacute', + 'acircumflex', + 'adieresis', + 'agrave', + 'aring', + 'atilde', + 'ccedilla', + 'eacute', + 'ecircumflex', + 'edieresis', + 'egrave', + 'iacute', + 'icircumflex', + 'idieresis', + 'igrave', + 'ntilde', + 'oacute', + 'ocircumflex', + 'odieresis', + 'ograve', + 'otilde', + 'scaron', + 'uacute', + 'ucircumflex', + 'udieresis', + 'ugrave', + 'yacute', + 'ydieresis', + 'zcaron', + 'exclamsmall', + 'Hungarumlautsmall', + 'dollaroldstyle', + 'dollarsuperior', + 'ampersandsmall', + 'Acutesmall', + 'parenleftsuperior', + 'parenrightsuperior', + '266 ff', + 'onedotenleader', + 'zerooldstyle', + 'oneoldstyle', + 'twooldstyle', + 'threeoldstyle', + 'fouroldstyle', + 'fiveoldstyle', + 'sixoldstyle', + 'sevenoldstyle', + 'eightoldstyle', + 'nineoldstyle', + 'commasuperior', + 'threequartersemdash', + 'periodsuperior', + 'questionsmall', + 'asuperior', + 'bsuperior', + 'centsuperior', + 'dsuperior', + 'esuperior', + 'isuperior', + 'lsuperior', + 'msuperior', + 'nsuperior', + 'osuperior', + 'rsuperior', + 'ssuperior', + 'tsuperior', + 'ff', + 'ffi', + 'ffl', + 'parenleftinferior', + 'parenrightinferior', + 'Circumflexsmall', + 'hyphensuperior', + 'Gravesmall', + 'Asmall', + 'Bsmall', + 'Csmall', + 'Dsmall', + 'Esmall', + 'Fsmall', + 'Gsmall', + 'Hsmall', + 'Ismall', + 'Jsmall', + 'Ksmall', + 'Lsmall', + 'Msmall', + 'Nsmall', + 'Osmall', + 'Psmall', + 'Qsmall', + 'Rsmall', + 'Ssmall', + 'Tsmall', + 'Usmall', + 'Vsmall', + 'Wsmall', + 'Xsmall', + 'Ysmall', + 'Zsmall', + 'colonmonetary', + 'onefitted', + 'rupiah', + 'Tildesmall', + 'exclamdownsmall', + 'centoldstyle', + 'Lslashsmall', + 'Scaronsmall', + 'Zcaronsmall', + 'Dieresissmall', + 'Brevesmall', + 'Caronsmall', + 'Dotaccentsmall', + 'Macronsmall', + 'figuredash', + 'hypheninferior', + 'Ogoneksmall', + 'Ringsmall', + 'Cedillasmall', + 'questiondownsmall', + 'oneeighth', + 'threeeighths', + 'fiveeighths', + 'seveneighths', + 'onethird', + 'twothirds', + 'zerosuperior', + 'foursuperior', + 'fivesuperior', + 'sixsuperior', + 'sevensuperior', + 'eightsuperior', + 'ninesuperior', + 'zeroinferior', + 'oneinferior', + 'twoinferior', + 'threeinferior', + 'fourinferior', + 'fiveinferior', + 'sixinferior', + 'seveninferior', + 'eightinferior', + 'nineinferior', + 'centinferior', + 'dollarinferior', + 'periodinferior', + 'commainferior', + 'Agravesmall', + 'Aacutesmall', + 'Acircumflexsmall', + 'Atildesmall', + 'Adieresissmall', + 'Aringsmall', + 'AEsmall', + 'Ccedillasmall', + 'Egravesmall', + 'Eacutesmall', + 'Ecircumflexsmall', + 'Edieresissmall', + 'Igravesmall', + 'Iacutesmall', + 'Icircumflexsmall', + 'Idieresissmall', + 'Ethsmall', + 'Ntildesmall', + 'Ogravesmall', + 'Oacutesmall', + 'Ocircumflexsmall', + 'Otildesmall', + 'Odieresissmall', + 'OEsmall', + 'Oslashsmall', + 'Ugravesmall', + 'Uacutesmall', + 'Ucircumflexsmall', + 'Udieresissmall', + 'Yacutesmall', + 'Thornsmall', + 'Ydieresissmall', + '001.000', + '001.001', + '001.002', + '001.003', + 'Black', + 'Bold', + 'Book', + 'Light', + 'Medium', + 'Regular', + 'Roman', + 'Semibold' + ]; + var cffStandardEncoding = [ + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + 'space', + 'exclam', + 'quotedbl', + 'numbersign', + 'dollar', + 'percent', + 'ampersand', + 'quoteright', + 'parenleft', + 'parenright', + 'asterisk', + 'plus', + 'comma', + 'hyphen', + 'period', + 'slash', + 'zero', + 'one', + 'two', + 'three', + 'four', + 'five', + 'six', + 'seven', + 'eight', + 'nine', + 'colon', + 'semicolon', + 'less', + 'equal', + 'greater', + 'question', + 'at', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z', + 'bracketleft', + 'backslash', + 'bracketright', + 'asciicircum', + 'underscore', + 'quoteleft', + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i', + 'j', + 'k', + 'l', + 'm', + 'n', + 'o', + 'p', + 'q', + 'r', + 's', + 't', + 'u', + 'v', + 'w', + 'x', + 'y', + 'z', + 'braceleft', + 'bar', + 'braceright', + 'asciitilde', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + 'exclamdown', + 'cent', + 'sterling', + 'fraction', + 'yen', + 'florin', + 'section', + 'currency', + 'quotesingle', + 'quotedblleft', + 'guillemotleft', + 'guilsinglleft', + 'guilsinglright', + 'fi', + 'fl', + '', + 'endash', + 'dagger', + 'daggerdbl', + 'periodcentered', + '', + 'paragraph', + 'bullet', + 'quotesinglbase', + 'quotedblbase', + 'quotedblright', + 'guillemotright', + 'ellipsis', + 'perthousand', + '', + 'questiondown', + '', + 'grave', + 'acute', + 'circumflex', + 'tilde', + 'macron', + 'breve', + 'dotaccent', + 'dieresis', + '', + 'ring', + 'cedilla', + '', + 'hungarumlaut', + 'ogonek', + 'caron', + 'emdash', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + 'AE', + '', + 'ordfeminine', + '', + '', + '', + '', + 'Lslash', + 'Oslash', + 'OE', + 'ordmasculine', + '', + '', + '', + '', + '', + 'ae', + '', + '', + '', + 'dotlessi', + '', + '', + 'lslash', + 'oslash', + 'oe', + 'germandbls' + ]; + var cffExpertEncoding = [ + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + 'space', + 'exclamsmall', + 'Hungarumlautsmall', + '', + 'dollaroldstyle', + 'dollarsuperior', + 'ampersandsmall', + 'Acutesmall', + 'parenleftsuperior', + 'parenrightsuperior', + 'twodotenleader', + 'onedotenleader', + 'comma', + 'hyphen', + 'period', + 'fraction', + 'zerooldstyle', + 'oneoldstyle', + 'twooldstyle', + 'threeoldstyle', + 'fouroldstyle', + 'fiveoldstyle', + 'sixoldstyle', + 'sevenoldstyle', + 'eightoldstyle', + 'nineoldstyle', + 'colon', + 'semicolon', + 'commasuperior', + 'threequartersemdash', + 'periodsuperior', + 'questionsmall', + '', + 'asuperior', + 'bsuperior', + 'centsuperior', + 'dsuperior', + 'esuperior', + '', + '', + 'isuperior', + '', + '', + 'lsuperior', + 'msuperior', + 'nsuperior', + 'osuperior', + '', + '', + 'rsuperior', + 'ssuperior', + 'tsuperior', + '', + 'ff', + 'fi', + 'fl', + 'ffi', + 'ffl', + 'parenleftinferior', + '', + 'parenrightinferior', + 'Circumflexsmall', + 'hyphensuperior', + 'Gravesmall', + 'Asmall', + 'Bsmall', + 'Csmall', + 'Dsmall', + 'Esmall', + 'Fsmall', + 'Gsmall', + 'Hsmall', + 'Ismall', + 'Jsmall', + 'Ksmall', + 'Lsmall', + 'Msmall', + 'Nsmall', + 'Osmall', + 'Psmall', + 'Qsmall', + 'Rsmall', + 'Ssmall', + 'Tsmall', + 'Usmall', + 'Vsmall', + 'Wsmall', + 'Xsmall', + 'Ysmall', + 'Zsmall', + 'colonmonetary', + 'onefitted', + 'rupiah', + 'Tildesmall', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + 'exclamdownsmall', + 'centoldstyle', + 'Lslashsmall', + '', + '', + 'Scaronsmall', + 'Zcaronsmall', + 'Dieresissmall', + 'Brevesmall', + 'Caronsmall', + '', + 'Dotaccentsmall', + '', + '', + 'Macronsmall', + '', + '', + 'figuredash', + 'hypheninferior', + '', + '', + 'Ogoneksmall', + 'Ringsmall', + 'Cedillasmall', + '', + '', + '', + 'onequarter', + 'onehalf', + 'threequarters', + 'questiondownsmall', + 'oneeighth', + 'threeeighths', + 'fiveeighths', + 'seveneighths', + 'onethird', + 'twothirds', + '', + '', + 'zerosuperior', + 'onesuperior', + 'twosuperior', + 'threesuperior', + 'foursuperior', + 'fivesuperior', + 'sixsuperior', + 'sevensuperior', + 'eightsuperior', + 'ninesuperior', + 'zeroinferior', + 'oneinferior', + 'twoinferior', + 'threeinferior', + 'fourinferior', + 'fiveinferior', + 'sixinferior', + 'seveninferior', + 'eightinferior', + 'nineinferior', + 'centinferior', + 'dollarinferior', + 'periodinferior', + 'commainferior', + 'Agravesmall', + 'Aacutesmall', + 'Acircumflexsmall', + 'Atildesmall', + 'Adieresissmall', + 'Aringsmall', + 'AEsmall', + 'Ccedillasmall', + 'Egravesmall', + 'Eacutesmall', + 'Ecircumflexsmall', + 'Edieresissmall', + 'Igravesmall', + 'Iacutesmall', + 'Icircumflexsmall', + 'Idieresissmall', + 'Ethsmall', + 'Ntildesmall', + 'Ogravesmall', + 'Oacutesmall', + 'Ocircumflexsmall', + 'Otildesmall', + 'Odieresissmall', + 'OEsmall', + 'Oslashsmall', + 'Ugravesmall', + 'Uacutesmall', + 'Ucircumflexsmall', + 'Udieresissmall', + 'Yacutesmall', + 'Thornsmall', + 'Ydieresissmall' + ]; + var standardNames = [ + '.notdef', + '.null', + 'nonmarkingreturn', + 'space', + 'exclam', + 'quotedbl', + 'numbersign', + 'dollar', + 'percent', + 'ampersand', + 'quotesingle', + 'parenleft', + 'parenright', + 'asterisk', + 'plus', + 'comma', + 'hyphen', + 'period', + 'slash', + 'zero', + 'one', + 'two', + 'three', + 'four', + 'five', + 'six', + 'seven', + 'eight', + 'nine', + 'colon', + 'semicolon', + 'less', + 'equal', + 'greater', + 'question', + 'at', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z', + 'bracketleft', + 'backslash', + 'bracketright', + 'asciicircum', + 'underscore', + 'grave', + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i', + 'j', + 'k', + 'l', + 'm', + 'n', + 'o', + 'p', + 'q', + 'r', + 's', + 't', + 'u', + 'v', + 'w', + 'x', + 'y', + 'z', + 'braceleft', + 'bar', + 'braceright', + 'asciitilde', + 'Adieresis', + 'Aring', + 'Ccedilla', + 'Eacute', + 'Ntilde', + 'Odieresis', + 'Udieresis', + 'aacute', + 'agrave', + 'acircumflex', + 'adieresis', + 'atilde', + 'aring', + 'ccedilla', + 'eacute', + 'egrave', + 'ecircumflex', + 'edieresis', + 'iacute', + 'igrave', + 'icircumflex', + 'idieresis', + 'ntilde', + 'oacute', + 'ograve', + 'ocircumflex', + 'odieresis', + 'otilde', + 'uacute', + 'ugrave', + 'ucircumflex', + 'udieresis', + 'dagger', + 'degree', + 'cent', + 'sterling', + 'section', + 'bullet', + 'paragraph', + 'germandbls', + 'registered', + 'copyright', + 'trademark', + 'acute', + 'dieresis', + 'notequal', + 'AE', + 'Oslash', + 'infinity', + 'plusminus', + 'lessequal', + 'greaterequal', + 'yen', + 'mu', + 'partialdiff', + 'summation', + 'product', + 'pi', + 'integral', + 'ordfeminine', + 'ordmasculine', + 'Omega', + 'ae', + 'oslash', + 'questiondown', + 'exclamdown', + 'logicalnot', + 'radical', + 'florin', + 'approxequal', + 'Delta', + 'guillemotleft', + 'guillemotright', + 'ellipsis', + 'nonbreakingspace', + 'Agrave', + 'Atilde', + 'Otilde', + 'OE', + 'oe', + 'endash', + 'emdash', + 'quotedblleft', + 'quotedblright', + 'quoteleft', + 'quoteright', + 'divide', + 'lozenge', + 'ydieresis', + 'Ydieresis', + 'fraction', + 'currency', + 'guilsinglleft', + 'guilsinglright', + 'fi', + 'fl', + 'daggerdbl', + 'periodcentered', + 'quotesinglbase', + 'quotedblbase', + 'perthousand', + 'Acircumflex', + 'Ecircumflex', + 'Aacute', + 'Edieresis', + 'Egrave', + 'Iacute', + 'Icircumflex', + 'Idieresis', + 'Igrave', + 'Oacute', + 'Ocircumflex', + 'apple', + 'Ograve', + 'Uacute', + 'Ucircumflex', + 'Ugrave', + 'dotlessi', + 'circumflex', + 'tilde', + 'macron', + 'breve', + 'dotaccent', + 'ring', + 'cedilla', + 'hungarumlaut', + 'ogonek', + 'caron', + 'Lslash', + 'lslash', + 'Scaron', + 'scaron', + 'Zcaron', + 'zcaron', + 'brokenbar', + 'Eth', + 'eth', + 'Yacute', + 'yacute', + 'Thorn', + 'thorn', + 'minus', + 'multiply', + 'onesuperior', + 'twosuperior', + 'threesuperior', + 'onehalf', + 'onequarter', + 'threequarters', + 'franc', + 'Gbreve', + 'gbreve', + 'Idotaccent', + 'Scedilla', + 'scedilla', + 'Cacute', + 'cacute', + 'Ccaron', + 'ccaron', + 'dcroat' + ]; + /** + * This is the encoding used for fonts created from scratch. + * It loops through all glyphs and finds the appropriate unicode value. + * Since it's linear time, other encodings will be faster. + * @exports opentype.DefaultEncoding + * @class + * @constructor + * @param {opentype.Font} + */ + function DefaultEncoding(font) { + this.font = font; + } + DefaultEncoding.prototype.charToGlyphIndex = function (c) { + var code = c.codePointAt(0); + var glyphs = this.font.glyphs; + if (glyphs) { + for (var i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j = 0; j < glyph.unicodes.length; j += 1) { + if (glyph.unicodes[j] === code) { + return i; + } + } + } + } + return null; + }; + /** + * @exports opentype.CmapEncoding + * @class + * @constructor + * @param {Object} cmap - a object with the cmap encoded data + */ + function CmapEncoding(cmap) { + this.cmap = cmap; + } /** + * @param {string} c - the character + * @return {number} The glyph index. + */ + + CmapEncoding.prototype.charToGlyphIndex = function (c) { + return this.cmap.glyphIndexMap[c.codePointAt(0)] || 0; + }; + /** + * @exports opentype.CffEncoding + * @class + * @constructor + * @param {string} encoding - The encoding + * @param {Array} charset - The character set. + */ + function CffEncoding(encoding, charset) { + this.encoding = encoding; + this.charset = charset; + } /** + * @param {string} s - The character + * @return {number} The index. + */ + + CffEncoding.prototype.charToGlyphIndex = function (s) { + var code = s.codePointAt(0); + var charName = this.encoding[code]; + return this.charset.indexOf(charName); + }; + /** + * @exports opentype.GlyphNames + * @class + * @constructor + * @param {Object} post + */ + function GlyphNames(post) { + var this$1 = this; + switch (post.version) { + case 1: + this.names = standardNames.slice(); + break; + case 2: + this.names = new Array(post.numberOfGlyphs); + for (var i = 0; i < post.numberOfGlyphs; i++) { + if (post.glyphNameIndex[i] < standardNames.length) { + this$1.names[i] = standardNames[post.glyphNameIndex[i]]; + } else { + this$1.names[i] = post.names[post.glyphNameIndex[i] - standardNames.length]; + } + } + break; + case 2.5: + this.names = new Array(post.numberOfGlyphs); + for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) { + this$1.names[i$1] = standardNames[i$1 + post.glyphNameIndex[i$1]]; + } + break; + case 3: + this.names = [ + ]; + break; + default: + this.names = [ + ]; + break; + } + } /** + * Gets the index of a glyph by name. + * @param {string} name - The glyph name + * @return {number} The index + */ + + GlyphNames.prototype.nameToGlyphIndex = function (name) { + return this.names.indexOf(name); + }; + /** + * @param {number} gid + * @return {string} + */ + GlyphNames.prototype.glyphIndexToName = function (gid) { + return this.names[gid]; + }; + /** + * @alias opentype.addGlyphNames + * @param {opentype.Font} + */ + function addGlyphNames(font) { + var glyph; + var glyphIndexMap = font.tables.cmap.glyphIndexMap; + var charCodes = Object.keys(glyphIndexMap); + for (var i = 0; i < charCodes.length; i += 1) { + var c = charCodes[i]; + var glyphIndex = glyphIndexMap[c]; + glyph = font.glyphs.get(glyphIndex); + glyph.addUnicode(parseInt(c)); + } + for (var i$1 = 0; i$1 < font.glyphs.length; i$1 += 1) { + glyph = font.glyphs.get(i$1); + if (font.cffEncoding) { + if (font.isCIDFont) { + glyph.name = 'gid' + i$1; + } else { + glyph.name = font.cffEncoding.charset[i$1]; + } + } else if (font.glyphNames.names) { + glyph.name = font.glyphNames.glyphIndexToName(i$1); + } + } + } // Drawing utility functions. + // Draw a line on the given context from point `x1,y1` to point `x2,y2`. + + function line(ctx, x1, y1, x2, y2) { + ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); + } + var draw = { + line: line + }; + // The Glyph object + // import glyf from './tables/glyf' Can't be imported here, because it's a circular dependency + function getPathDefinition(glyph, path) { + var _path = path || new Path(); + return { + configurable: true, + get: function () { + if (typeof _path === 'function') { + _path = _path(); + } + return _path; + }, + set: function (p) { + _path = p; + } + }; + } /** + * @typedef GlyphOptions + * @type Object + * @property {string} [name] - The glyph name + * @property {number} [unicode] + * @property {Array} [unicodes] + * @property {number} [xMin] + * @property {number} [yMin] + * @property {number} [xMax] + * @property {number} [yMax] + * @property {number} [advanceWidth] + */ + // A Glyph is an individual mark that often corresponds to a character. + // Some glyphs, such as ligatures, are a combination of many characters. + // Glyphs are the basic building blocks of a font. + // + // The `Glyph` class contains utility methods for drawing the path and its points. + /** + * @exports opentype.Glyph + * @class + * @param {GlyphOptions} + * @constructor + */ + + function Glyph(options) { + // By putting all the code on a prototype function (which is only declared once) + // we reduce the memory requirements for larger fonts by some 2% + this.bindConstructorValues(options); + } /** + * @param {GlyphOptions} + */ + + Glyph.prototype.bindConstructorValues = function (options) { + this.index = options.index || 0; + // These three values cannot be deferred for memory optimization: + this.name = options.name || null; + this.unicode = options.unicode || undefined; + this.unicodes = options.unicodes || options.unicode !== undefined ? [ + options.unicode + ] : [ + ]; + // But by binding these values only when necessary, we reduce can + // the memory requirements by almost 3% for larger fonts. + if (options.xMin) { + this.xMin = options.xMin; + } + if (options.yMin) { + this.yMin = options.yMin; + } + if (options.xMax) { + this.xMax = options.xMax; + } + if (options.yMax) { + this.yMax = options.yMax; + } + if (options.advanceWidth) { + this.advanceWidth = options.advanceWidth; + } // The path for a glyph is the most memory intensive, and is bound as a value + // with a getter/setter to ensure we actually do path parsing only once the + // path is actually needed by anything. + + Object.defineProperty(this, 'path', getPathDefinition(this, options.path)); + }; + /** + * @param {number} + */ + Glyph.prototype.addUnicode = function (unicode) { + if (this.unicodes.length === 0) { + this.unicode = unicode; + } + this.unicodes.push(unicode); + }; + /** + * Calculate the minimum bounding box for this glyph. + * @return {opentype.BoundingBox} + */ + Glyph.prototype.getBoundingBox = function () { + return this.path.getBoundingBox(); + }; + /** + * Convert the glyph to a Path we can draw on a drawing context. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {Object=} options - xScale, yScale to stretch the glyph. + * @param {opentype.Font} if hinting is to be used, the font + * @return {opentype.Path} + */ + Glyph.prototype.getPath = function (x, y, fontSize, options, font) { + x = x !== undefined ? x : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + var commands; + var hPoints; + if (!options) { + options = { + }; + } + var xScale = options.xScale; + var yScale = options.yScale; + if (options.hinting && font && font.hinting) { + // in case of hinting, the hinting engine takes care + // of scaling the points (not the path) before hinting. + hPoints = this.path && font.hinting.exec(this, fontSize); + // in case the hinting engine failed hPoints is undefined + // and thus reverts to plain rending + } + if (hPoints) { + // Call font.hinting.getCommands instead of `glyf.getPath(hPoints).commands` to avoid a circular dependency + commands = font.hinting.getCommands(hPoints); + x = Math.round(x); + y = Math.round(y); + // TODO in case of hinting xyScaling is not yet supported + xScale = yScale = 1; + } else { + commands = this.path.commands; + var scale = 1 / this.path.unitsPerEm * fontSize; + if (xScale === undefined) { + xScale = scale; + } + if (yScale === undefined) { + yScale = scale; + } + } + var p = new Path(); + for (var i = 0; i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type === 'M') { + p.moveTo(x + cmd.x * xScale, y + - cmd.y * yScale); + } else if (cmd.type === 'L') { + p.lineTo(x + cmd.x * xScale, y + - cmd.y * yScale); + } else if (cmd.type === 'Q') { + p.quadraticCurveTo(x + cmd.x1 * xScale, y + - cmd.y1 * yScale, x + cmd.x * xScale, y + - cmd.y * yScale); + } else if (cmd.type === 'C') { + p.curveTo(x + cmd.x1 * xScale, y + - cmd.y1 * yScale, x + cmd.x2 * xScale, y + - cmd.y2 * yScale, x + cmd.x * xScale, y + - cmd.y * yScale); + } else if (cmd.type === 'Z') { + p.closePath(); + } + } + return p; + }; + /** + * Split the glyph into contours. + * This function is here for backwards compatibility, and to + * provide raw access to the TrueType glyph outlines. + * @return {Array} + */ + Glyph.prototype.getContours = function () { + var this$1 = this; + if (this.points === undefined) { + return []; + } + var contours = [ + ]; + var currentContour = [ + ]; + for (var i = 0; i < this.points.length; i += 1) { + var pt = this$1.points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = [ + ]; + } + } + check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); + return contours; + }; + /** + * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph. + * @return {Object} + */ + Glyph.prototype.getMetrics = function () { + var commands = this.path.commands; + var xCoords = [ + ]; + var yCoords = [ + ]; + for (var i = 0; i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type !== 'Z') { + xCoords.push(cmd.x); + yCoords.push(cmd.y); + } + if (cmd.type === 'Q' || cmd.type === 'C') { + xCoords.push(cmd.x1); + yCoords.push(cmd.y1); + } + if (cmd.type === 'C') { + xCoords.push(cmd.x2); + yCoords.push(cmd.y2); + } + } + var metrics = { + xMin: Math.min.apply(null, xCoords), + yMin: Math.min.apply(null, yCoords), + xMax: Math.max.apply(null, xCoords), + yMax: Math.max.apply(null, yCoords), + leftSideBearing: this.leftSideBearing + }; + if (!isFinite(metrics.xMin)) { + metrics.xMin = 0; + } + if (!isFinite(metrics.xMax)) { + metrics.xMax = this.advanceWidth; + } + if (!isFinite(metrics.yMin)) { + metrics.yMin = 0; + } + if (!isFinite(metrics.yMax)) { + metrics.yMax = 0; + } + metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); + return metrics; + }; + /** + * Draw the glyph on the given context. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {Object=} options - xScale, yScale to stretch the glyph. + */ + Glyph.prototype.draw = function (ctx, x, y, fontSize, options) { + this.getPath(x, y, fontSize, options).draw(ctx); + }; + /** + * Draw the points of the glyph. + * On-curve points will be drawn in blue, off-curve points will be drawn in red. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + */ + Glyph.prototype.drawPoints = function (ctx, x, y, fontSize) { + function drawCircles(l, x, y, scale) { + var PI_SQ = Math.PI * 2; + ctx.beginPath(); + for (var j = 0; j < l.length; j += 1) { + ctx.moveTo(x + l[j].x * scale, y + l[j].y * scale); + ctx.arc(x + l[j].x * scale, y + l[j].y * scale, 2, 0, PI_SQ, false); + } + ctx.closePath(); + ctx.fill(); + } + x = x !== undefined ? x : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + var scale = 1 / this.path.unitsPerEm * fontSize; + var blueCircles = [ + ]; + var redCircles = [ + ]; + var path = this.path; + for (var i = 0; i < path.commands.length; i += 1) { + var cmd = path.commands[i]; + if (cmd.x !== undefined) { + blueCircles.push({ + x: cmd.x, + y: - cmd.y + }); + } + if (cmd.x1 !== undefined) { + redCircles.push({ + x: cmd.x1, + y: - cmd.y1 + }); + } + if (cmd.x2 !== undefined) { + redCircles.push({ + x: cmd.x2, + y: - cmd.y2 + }); + } + } + ctx.fillStyle = 'blue'; + drawCircles(blueCircles, x, y, scale); + ctx.fillStyle = 'red'; + drawCircles(redCircles, x, y, scale); + }; + /** + * Draw lines indicating important font measurements. + * Black lines indicate the origin of the coordinate system (point 0,0). + * Blue lines indicate the glyph bounding box. + * Green line indicates the advance width of the glyph. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + */ + Glyph.prototype.drawMetrics = function (ctx, x, y, fontSize) { + var scale; + x = x !== undefined ? x : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + scale = 1 / this.path.unitsPerEm * fontSize; + ctx.lineWidth = 1; + // Draw the origin + ctx.strokeStyle = 'black'; + draw.line(ctx, x, - 10000, x, 10000); + draw.line(ctx, - 10000, y, 10000, y); + // This code is here due to memory optimization: by not using + // defaults in the constructor, we save a notable amount of memory. + var xMin = this.xMin || 0; + var yMin = this.yMin || 0; + var xMax = this.xMax || 0; + var yMax = this.yMax || 0; + var advanceWidth = this.advanceWidth || 0; + // Draw the glyph box + ctx.strokeStyle = 'blue'; + draw.line(ctx, x + xMin * scale, - 10000, x + xMin * scale, 10000); + draw.line(ctx, x + xMax * scale, - 10000, x + xMax * scale, 10000); + draw.line(ctx, - 10000, y + - yMin * scale, 10000, y + - yMin * scale); + draw.line(ctx, - 10000, y + - yMax * scale, 10000, y + - yMax * scale); + // Draw the advance width + ctx.strokeStyle = 'green'; + draw.line(ctx, x + advanceWidth * scale, - 10000, x + advanceWidth * scale, 10000); + }; + // The GlyphSet object + // Define a property on the glyph that depends on the path being loaded. + function defineDependentProperty(glyph, externalName, internalName) { + Object.defineProperty(glyph, externalName, { + get: function () { + // Request the path property to make sure the path is loaded. + glyph.path; // jshint ignore:line + return glyph[internalName]; + }, + set: function (newValue) { + glyph[internalName] = newValue; + }, + enumerable: true, + configurable: true + }); + } /** + * A GlyphSet represents all glyphs available in the font, but modelled using + * a deferred glyph loader, for retrieving glyphs only once they are absolutely + * necessary, to keep the memory footprint down. + * @exports opentype.GlyphSet + * @class + * @param {opentype.Font} + * @param {Array} + */ + + function GlyphSet(font, glyphs) { + var this$1 = this; + this.font = font; + this.glyphs = { + }; + if (Array.isArray(glyphs)) { + for (var i = 0; i < glyphs.length; i++) { + this$1.glyphs[i] = glyphs[i]; + } + } + this.length = glyphs && glyphs.length || 0; + } /** + * @param {number} index + * @return {opentype.Glyph} + */ + + GlyphSet.prototype.get = function (index) { + if (typeof this.glyphs[index] === 'function') { + this.glyphs[index] = this.glyphs[index](); + } + return this.glyphs[index]; + }; + /** + * @param {number} index + * @param {Object} + */ + GlyphSet.prototype.push = function (index, loader) { + this.glyphs[index] = loader; + this.length++; + }; + /** + * @alias opentype.glyphLoader + * @param {opentype.Font} font + * @param {number} index + * @return {opentype.Glyph} + */ + function glyphLoader(font, index) { + return new Glyph({ + index: index, + font: font + }); + } /** + * Generate a stub glyph that can be filled with all metadata *except* + * the "points" and "path" properties, which must be loaded only once + * the glyph's path is actually requested for text shaping. + * @alias opentype.ttfGlyphLoader + * @param {opentype.Font} font + * @param {number} index + * @param {Function} parseGlyph + * @param {Object} data + * @param {number} position + * @param {Function} buildPath + * @return {opentype.Glyph} + */ + + function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) { + return function () { + var glyph = new Glyph({ + index: index, + font: font + }); + glyph.path = function () { + parseGlyph(glyph, data, position); + var path = buildPath(font.glyphs, glyph); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + defineDependentProperty(glyph, 'xMin', '_xMin'); + defineDependentProperty(glyph, 'xMax', '_xMax'); + defineDependentProperty(glyph, 'yMin', '_yMin'); + defineDependentProperty(glyph, 'yMax', '_yMax'); + return glyph; + }; + } /** + * @alias opentype.cffGlyphLoader + * @param {opentype.Font} font + * @param {number} index + * @param {Function} parseCFFCharstring + * @param {string} charstring + * @return {opentype.Glyph} + */ + + function cffGlyphLoader(font, index, parseCFFCharstring, charstring) { + return function () { + var glyph = new Glyph({ + index: index, + font: font + }); + glyph.path = function () { + var path = parseCFFCharstring(font, glyph, charstring); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + return glyph; + }; + } + var glyphset = { + GlyphSet: GlyphSet, + glyphLoader: glyphLoader, + ttfGlyphLoader: ttfGlyphLoader, + cffGlyphLoader: cffGlyphLoader + }; + // The `CFF` table contains the glyph outlines in PostScript format. + // Custom equals function that can also check lists. + function equals(a, b) { + if (a === b) { + return true; + } else if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return false; + } + for (var i = 0; i < a.length; i += 1) { + if (!equals(a[i], b[i])) { + return false; + } + } + return true; + } else { + return false; + } + } // Subroutines are encoded using the negative half of the number space. + // See type 2 chapter 4.7 "Subroutine operators". + + function calcCFFSubroutineBias(subrs) { + var bias; + if (subrs.length < 1240) { + bias = 107; + } else if (subrs.length < 33900) { + bias = 1131; + } else { + bias = 32768; + } + return bias; + } // Parse a `CFF` INDEX array. + // An index array consists of a list of offsets, then a list of objects at those offsets. + + function parseCFFIndex(data, start, conversionFn) { + var offsets = [ + ]; + var objects = [ + ]; + var count = parse.getCard16(data, start); + var objectOffset; + var endOffset; + if (count !== 0) { + var offsetSize = parse.getByte(data, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + var pos = start + 3; + for (var i = 0; i < count + 1; i += 1) { + offsets.push(parse.getOffset(data, pos, offsetSize)); + pos += offsetSize; + } // The total size of the index array is 4 header bytes + the value of the last offset. + + endOffset = objectOffset + offsets[count]; + } else { + endOffset = start + 2; + } + for (var i$1 = 0; i$1 < offsets.length - 1; i$1 += 1) { + var value = parse.getBytes(data, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]); + if (conversionFn) { + value = conversionFn(value); + } + objects.push(value); + } + return { + objects: objects, + startOffset: start, + endOffset: endOffset + }; + } // Parse a `CFF` DICT real value. + + function parseFloatOperand(parser) { + var s = ''; + var eof = 15; + var lookup = [ + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + '.', + 'E', + 'E-', + null, + '-' + ]; + while (true) { + var b = parser.parseByte(); + var n1 = b >> 4; + var n2 = b & 15; + if (n1 === eof) { + break; + } + s += lookup[n1]; + if (n2 === eof) { + break; + } + s += lookup[n2]; + } + return parseFloat(s); + } // Parse a `CFF` DICT operand. + + function parseOperand(parser, b0) { + var b1; + var b2; + var b3; + var b4; + if (b0 === 28) { + b1 = parser.parseByte(); + b2 = parser.parseByte(); + return b1 << 8 | b2; + } + if (b0 === 29) { + b1 = parser.parseByte(); + b2 = parser.parseByte(); + b3 = parser.parseByte(); + b4 = parser.parseByte(); + return b1 << 24 | b2 << 16 | b3 << 8 | b4; + } + if (b0 === 30) { + return parseFloatOperand(parser); + } + if (b0 >= 32 && b0 <= 246) { + return b0 - 139; + } + if (b0 >= 247 && b0 <= 250) { + b1 = parser.parseByte(); + return (b0 - 247) * 256 + b1 + 108; + } + if (b0 >= 251 && b0 <= 254) { + b1 = parser.parseByte(); + return - (b0 - 251) * 256 - b1 - 108; + } + throw new Error('Invalid b0 ' + b0); + } // Convert the entries returned by `parseDict` to a proper dictionary. + // If a value is a list of one, it is unpacked. + + function entriesToObject(entries) { + var o = { + }; + for (var i = 0; i < entries.length; i += 1) { + var key = entries[i][0]; + var values = entries[i][1]; + var value = void 0; + if (values.length === 1) { + value = values[0]; + } else { + value = values; + } + if (o.hasOwnProperty(key) && !isNaN(o[key])) { + throw new Error('Object ' + o + ' already has key ' + key); + } + o[key] = value; + } + return o; + } // Parse a `CFF` DICT object. + // A dictionary contains key-value pairs in a compact tokenized format. + + function parseCFFDict(data, start, size) { + start = start !== undefined ? start : 0; + var parser = new parse.Parser(data, start); + var entries = [ + ]; + var operands = [ + ]; + size = size !== undefined ? size : data.length; + while (parser.relativeOffset < size) { + var op = parser.parseByte(); + // The first byte for each dict item distinguishes between operator (key) and operand (value). + // Values <= 21 are operators. + if (op <= 21) { + // Two-byte operators have an initial escape byte of 12. + if (op === 12) { + op = 1200 + parser.parseByte(); + } + entries.push([op, + operands]); + operands = [ + ]; + } else { + // Since the operands (values) come before the operators (keys), we store all operands in a list + // until we encounter an operator. + operands.push(parseOperand(parser, op)); + } + } + return entriesToObject(entries); + } // Given a String Index (SID), return the value of the string. + // Strings below index 392 are standard CFF strings and are not encoded in the font. + + function getCFFString(strings, index) { + if (index <= 390) { + index = cffStandardStrings[index]; + } else { + index = strings[index - 391]; + } + return index; + } // Interpret a dictionary and return a new dictionary with readable keys and values for missing entries. + // This function takes `meta` which is a list of objects containing `operand`, `name` and `default`. + + function interpretDict(dict, meta, strings) { + var newDict = { + }; + var value; + // Because we also want to include missing values, we start out from the meta list + // and lookup values in the dict. + for (var i = 0; i < meta.length; i += 1) { + var m = meta[i]; + if (Array.isArray(m.type)) { + var values = [ + ]; + values.length = m.type.length; + for (var j = 0; j < m.type.length; j++) { + value = dict[m.op] !== undefined ? dict[m.op][j] : undefined; + if (value === undefined) { + value = m.value !== undefined && m.value[j] !== undefined ? m.value[j] : null; + } + if (m.type[j] === 'SID') { + value = getCFFString(strings, value); + } + values[j] = value; + } + newDict[m.name] = values; + } else { + value = dict[m.op]; + if (value === undefined) { + value = m.value !== undefined ? m.value : null; + } + if (m.type === 'SID') { + value = getCFFString(strings, value); + } + newDict[m.name] = value; + } + } + return newDict; + } // Parse the CFF header. + + function parseCFFHeader(data, start) { + var header = { + }; + header.formatMajor = parse.getCard8(data, start); + header.formatMinor = parse.getCard8(data, start + 1); + header.size = parse.getCard8(data, start + 2); + header.offsetSize = parse.getCard8(data, start + 3); + header.startOffset = start; + header.endOffset = start + 4; + return header; + } + var TOP_DICT_META = [ + { + name: 'version', + op: 0, + type: 'SID' + }, + { + name: 'notice', + op: 1, + type: 'SID' + }, + { + name: 'copyright', + op: 1200, + type: 'SID' + }, + { + name: 'fullName', + op: 2, + type: 'SID' + }, + { + name: 'familyName', + op: 3, + type: 'SID' + }, + { + name: 'weight', + op: 4, + type: 'SID' + }, + { + name: 'isFixedPitch', + op: 1201, + type: 'number', + value: 0 + }, + { + name: 'italicAngle', + op: 1202, + type: 'number', + value: 0 + }, + { + name: 'underlinePosition', + op: 1203, + type: 'number', + value: - 100 + }, + { + name: 'underlineThickness', + op: 1204, + type: 'number', + value: 50 + }, + { + name: 'paintType', + op: 1205, + type: 'number', + value: 0 + }, + { + name: 'charstringType', + op: 1206, + type: 'number', + value: 2 + }, + { + name: 'fontMatrix', + op: 1207, + type: [ + 'real', + 'real', + 'real', + 'real', + 'real', + 'real' + ], + value: [ + 0.001, + 0, + 0, + 0.001, + 0, + 0 + ] + }, + { + name: 'uniqueId', + op: 13, + type: 'number' + }, + { + name: 'fontBBox', + op: 5, + type: [ + 'number', + 'number', + 'number', + 'number' + ], + value: [ + 0, + 0, + 0, + 0 + ] + }, + { + name: 'strokeWidth', + op: 1208, + type: 'number', + value: 0 + }, + { + name: 'xuid', + op: 14, + type: [ + ], + value: null + }, + { + name: 'charset', + op: 15, + type: 'offset', + value: 0 + }, + { + name: 'encoding', + op: 16, + type: 'offset', + value: 0 + }, + { + name: 'charStrings', + op: 17, + type: 'offset', + value: 0 + }, + { + name: 'private', + op: 18, + type: [ + 'number', + 'offset' + ], + value: [ + 0, + 0 + ] + }, + { + name: 'ros', + op: 1230, + type: [ + 'SID', + 'SID', + 'number' + ] + }, + { + name: 'cidFontVersion', + op: 1231, + type: 'number', + value: 0 + }, + { + name: 'cidFontRevision', + op: 1232, + type: 'number', + value: 0 + }, + { + name: 'cidFontType', + op: 1233, + type: 'number', + value: 0 + }, + { + name: 'cidCount', + op: 1234, + type: 'number', + value: 8720 + }, + { + name: 'uidBase', + op: 1235, + type: 'number' + }, + { + name: 'fdArray', + op: 1236, + type: 'offset' + }, + { + name: 'fdSelect', + op: 1237, + type: 'offset' + }, + { + name: 'fontName', + op: 1238, + type: 'SID' + } + ]; + var PRIVATE_DICT_META = [ + { + name: 'subrs', + op: 19, + type: 'offset', + value: 0 + }, + { + name: 'defaultWidthX', + op: 20, + type: 'number', + value: 0 + }, + { + name: 'nominalWidthX', + op: 21, + type: 'number', + value: 0 + } + ]; + // Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary. + // The top dictionary contains the essential metadata for the font, together with the private dictionary. + function parseCFFTopDict(data, strings) { + var dict = parseCFFDict(data, 0, data.byteLength); + return interpretDict(dict, TOP_DICT_META, strings); + } // Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need. + + function parseCFFPrivateDict(data, start, size, strings) { + var dict = parseCFFDict(data, start, size); + return interpretDict(dict, PRIVATE_DICT_META, strings); + } // Returns a list of "Top DICT"s found using an INDEX list. + // Used to read both the usual high-level Top DICTs and also the FDArray + // discovered inside CID-keyed fonts. When a Top DICT has a reference to + // a Private DICT that is read and saved into the Top DICT. + // + // In addition to the expected/optional values as outlined in TOP_DICT_META + // the following values might be saved into the Top DICT. + // + // _subrs [] array of local CFF subroutines from Private DICT + // _subrsBias bias value computed from number of subroutines + // (see calcCFFSubroutineBias() and parseCFFCharstring()) + // _defaultWidthX default widths for CFF characters + // _nominalWidthX bias added to width embedded within glyph description + // + // _privateDict saved copy of parsed Private DICT from Top DICT + + function gatherCFFTopDicts(data, start, cffIndex, strings) { + var topDictArray = [ + ]; + for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) { + var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer); + var topDict = parseCFFTopDict(topDictData, strings); + topDict._subrs = [ + ]; + topDict._subrsBias = 0; + var privateSize = topDict.private[0]; + var privateOffset = topDict.private[1]; + if (privateSize !== 0 && privateOffset !== 0) { + var privateDict = parseCFFPrivateDict(data, privateOffset + start, privateSize, strings); + topDict._defaultWidthX = privateDict.defaultWidthX; + topDict._nominalWidthX = privateDict.nominalWidthX; + if (privateDict.subrs !== 0) { + var subrOffset = privateOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data, subrOffset + start); + topDict._subrs = subrIndex.objects; + topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs); + } + topDict._privateDict = privateDict; + } + topDictArray.push(topDict); + } + return topDictArray; + } // Parse the CFF charset table, which contains internal names for all the glyphs. + // This function will return a list of glyph names. + // See Adobe TN #5176 chapter 13, "Charsets". + + function parseCFFCharset(data, start, nGlyphs, strings) { + var sid; + var count; + var parser = new parse.Parser(data, start); + // The .notdef glyph is not included, so subtract 1. + nGlyphs -= 1; + var charset = [ + '.notdef' + ]; + var format = parser.parseCard8(); + if (format === 0) { + for (var i = 0; i < nGlyphs; i += 1) { + sid = parser.parseSID(); + charset.push(getCFFString(strings, sid)); + } + } else if (format === 1) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard8(); + for (var i$1 = 0; i$1 <= count; i$1 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else if (format === 2) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard16(); + for (var i$2 = 0; i$2 <= count; i$2 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else { + throw new Error('Unknown charset format ' + format); + } + return charset; + } // Parse the CFF encoding data. Only one encoding can be specified per font. + // See Adobe TN #5176 chapter 12, "Encodings". + + function parseCFFEncoding(data, start, charset) { + var code; + var enc = { + }; + var parser = new parse.Parser(data, start); + var format = parser.parseCard8(); + if (format === 0) { + var nCodes = parser.parseCard8(); + for (var i = 0; i < nCodes; i += 1) { + code = parser.parseCard8(); + enc[code] = i; + } + } else if (format === 1) { + var nRanges = parser.parseCard8(); + code = 1; + for (var i$1 = 0; i$1 < nRanges; i$1 += 1) { + var first = parser.parseCard8(); + var nLeft = parser.parseCard8(); + for (var j = first; j <= first + nLeft; j += 1) { + enc[j] = code; + code += 1; + } + } + } else { + throw new Error('Unknown encoding format ' + format); + } + return new CffEncoding(enc, charset); + } // Take in charstring code and return a Glyph object. + // The encoding is described in the Type 2 Charstring Format + // https://www.microsoft.com/typography/OTSPEC/charstr2.htm + + function parseCFFCharstring(font, glyph, code) { + var c1x; + var c1y; + var c2x; + var c2y; + var p = new Path(); + var stack = [ + ]; + var nStems = 0; + var haveWidth = false; + var open = false; + var x = 0; + var y = 0; + var subrs; + var subrsBias; + var defaultWidthX; + var nominalWidthX; + if (font.isCIDFont) { + var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index]; + var fdDict = font.tables.cff.topDict._fdArray[fdIndex]; + subrs = fdDict._subrs; + subrsBias = fdDict._subrsBias; + defaultWidthX = fdDict._defaultWidthX; + nominalWidthX = fdDict._nominalWidthX; + } else { + subrs = font.tables.cff.topDict._subrs; + subrsBias = font.tables.cff.topDict._subrsBias; + defaultWidthX = font.tables.cff.topDict._defaultWidthX; + nominalWidthX = font.tables.cff.topDict._nominalWidthX; + } + var width = defaultWidthX; + function newContour(x, y) { + if (open) { + p.closePath(); + } + p.moveTo(x, y); + open = true; + } + function parseStems() { + var hasWidthArg; + // The number of stem operators on the stack is always even. + // If the value is uneven, that means a width is specified. + hasWidthArg = stack.length % 2 !== 0; + if (hasWidthArg && !haveWidth) { + width = stack.shift() + nominalWidthX; + } + nStems += stack.length >> 1; + stack.length = 0; + haveWidth = true; + } + function parse$$1(code) { + var b1; + var b2; + var b3; + var b4; + var codeIndex; + var subrCode; + var jpx; + var jpy; + var c3x; + var c3y; + var c4x; + var c4y; + var i = 0; + while (i < code.length) { + var v = code[i]; + i += 1; + switch (v) { + case 1: + // hstem + parseStems(); + break; + case 3: + // vstem + parseStems(); + break; + case 4: + // vmoveto + if (stack.length > 1 && !haveWidth) { + width = stack.shift() + nominalWidthX; + haveWidth = true; + } + y += stack.pop(); + newContour(x, y); + break; + case 5: + // rlineto + while (stack.length > 0) { + x += stack.shift(); + y += stack.shift(); + p.lineTo(x, y); + } + break; + case 6: + // hlineto + while (stack.length > 0) { + x += stack.shift(); + p.lineTo(x, y); + if (stack.length === 0) { + break; + } + y += stack.shift(); + p.lineTo(x, y); + } + break; + case 7: + // vlineto + while (stack.length > 0) { + y += stack.shift(); + p.lineTo(x, y); + if (stack.length === 0) { + break; + } + x += stack.shift(); + p.lineTo(x, y); + } + break; + case 8: + // rrcurveto + while (stack.length > 0) { + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + break; + case 10: + // callsubr + codeIndex = stack.pop() + subrsBias; + subrCode = subrs[codeIndex]; + if (subrCode) { + parse$$1(subrCode); + } + break; + case 11: + // return + return; + case 12: + // flex operators + v = code[i]; + i += 1; + switch (v) { + case 35: + // flex + // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |- + c1x = x + stack.shift(); // dx1 + c1y = y + stack.shift(); // dy1 + c2x = c1x + stack.shift(); // dx2 + c2y = c1y + stack.shift(); // dy2 + jpx = c2x + stack.shift(); // dx3 + jpy = c2y + stack.shift(); // dy3 + c3x = jpx + stack.shift(); // dx4 + c3y = jpy + stack.shift(); // dy4 + c4x = c3x + stack.shift(); // dx5 + c4y = c3y + stack.shift(); // dy5 + x = c4x + stack.shift(); // dx6 + y = c4y + stack.shift(); // dy6 + stack.shift(); // flex depth + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x, y); + break; + case 34: + // hflex + // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |- + c1x = x + stack.shift(); // dx1 + c1y = y; // dy1 + c2x = c1x + stack.shift(); // dx2 + c2y = c1y + stack.shift(); // dy2 + jpx = c2x + stack.shift(); // dx3 + jpy = c2y; // dy3 + c3x = jpx + stack.shift(); // dx4 + c3y = c2y; // dy4 + c4x = c3x + stack.shift(); // dx5 + c4y = y; // dy5 + x = c4x + stack.shift(); // dx6 + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x, y); + break; + case 36: + // hflex1 + // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |- + c1x = x + stack.shift(); // dx1 + c1y = y + stack.shift(); // dy1 + c2x = c1x + stack.shift(); // dx2 + c2y = c1y + stack.shift(); // dy2 + jpx = c2x + stack.shift(); // dx3 + jpy = c2y; // dy3 + c3x = jpx + stack.shift(); // dx4 + c3y = c2y; // dy4 + c4x = c3x + stack.shift(); // dx5 + c4y = c3y + stack.shift(); // dy5 + x = c4x + stack.shift(); // dx6 + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x, y); + break; + case 37: + // flex1 + // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |- + c1x = x + stack.shift(); // dx1 + c1y = y + stack.shift(); // dy1 + c2x = c1x + stack.shift(); // dx2 + c2y = c1y + stack.shift(); // dy2 + jpx = c2x + stack.shift(); // dx3 + jpy = c2y + stack.shift(); // dy3 + c3x = jpx + stack.shift(); // dx4 + c3y = jpy + stack.shift(); // dy4 + c4x = c3x + stack.shift(); // dx5 + c4y = c3y + stack.shift(); // dy5 + if (Math.abs(c4x - x) > Math.abs(c4y - y)) { + x = c4x + stack.shift(); + } else { + y = c4y + stack.shift(); + } + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x, y); + break; + default: + console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v); + stack.length = 0; + } + break; + case 14: + // endchar + if (stack.length > 0 && !haveWidth) { + width = stack.shift() + nominalWidthX; + haveWidth = true; + } + if (open) { + p.closePath(); + open = false; + } + break; + case 18: + // hstemhm + parseStems(); + break; + case 19: // hintmask + case 20: + // cntrmask + parseStems(); + i += nStems + 7 >> 3; + break; + case 21: + // rmoveto + if (stack.length > 2 && !haveWidth) { + width = stack.shift() + nominalWidthX; + haveWidth = true; + } + y += stack.pop(); + x += stack.pop(); + newContour(x, y); + break; + case 22: + // hmoveto + if (stack.length > 1 && !haveWidth) { + width = stack.shift() + nominalWidthX; + haveWidth = true; + } + x += stack.pop(); + newContour(x, y); + break; + case 23: + // vstemhm + parseStems(); + break; + case 24: + // rcurveline + while (stack.length > 2) { + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + x += stack.shift(); + y += stack.shift(); + p.lineTo(x, y); + break; + case 25: + // rlinecurve + while (stack.length > 6) { + x += stack.shift(); + y += stack.shift(); + p.lineTo(x, y); + } + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + break; + case 26: + // vvcurveto + if (stack.length % 2) { + x += stack.shift(); + } + while (stack.length > 0) { + c1x = x; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x; + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + break; + case 27: + // hhcurveto + if (stack.length % 2) { + y += stack.shift(); + } + while (stack.length > 0) { + c1x = x + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y; + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + break; + case 28: + // shortint + b1 = code[i]; + b2 = code[i + 1]; + stack.push((b1 << 24 | b2 << 16) >> 16); + i += 2; + break; + case 29: + // callgsubr + codeIndex = stack.pop() + font.gsubrsBias; + subrCode = font.gsubrs[codeIndex]; + if (subrCode) { + parse$$1(subrCode); + } + break; + case 30: + // vhcurveto + while (stack.length > 0) { + c1x = x; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + if (stack.length === 0) { + break; + } + c1x = x + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y = c2y + stack.shift(); + x = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + break; + case 31: + // hvcurveto + while (stack.length > 0) { + c1x = x + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y = c2y + stack.shift(); + x = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + if (stack.length === 0) { + break; + } + c1x = x; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + break; + default: + if (v < 32) { + console.log('Glyph ' + glyph.index + ': unknown operator ' + v); + } else if (v < 247) { + stack.push(v - 139); + } else if (v < 251) { + b1 = code[i]; + i += 1; + stack.push((v - 247) * 256 + b1 + 108); + } else if (v < 255) { + b1 = code[i]; + i += 1; + stack.push( - (v - 251) * 256 - b1 - 108); + } else { + b1 = code[i]; + b2 = code[i + 1]; + b3 = code[i + 2]; + b4 = code[i + 3]; + i += 4; + stack.push((b1 << 24 | b2 << 16 | b3 << 8 | b4) / 65536); + } + } + } + } + parse$$1(code); + glyph.advanceWidth = width; + return p; + } + function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) { + var fdSelect = [ + ]; + var fdIndex; + var parser = new parse.Parser(data, start); + var format = parser.parseCard8(); + if (format === 0) { + // Simple list of nGlyphs elements + for (var iGid = 0; iGid < nGlyphs; iGid++) { + fdIndex = parser.parseCard8(); + if (fdIndex >= fdArrayCount) { + throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); + } + fdSelect.push(fdIndex); + } + } else if (format === 3) { + // Ranges + var nRanges = parser.parseCard16(); + var first = parser.parseCard16(); + if (first !== 0) { + throw new Error('CFF Table CID Font FDSelect format 3 range has bad initial GID ' + first); + } + var next; + for (var iRange = 0; iRange < nRanges; iRange++) { + fdIndex = parser.parseCard8(); + next = parser.parseCard16(); + if (fdIndex >= fdArrayCount) { + throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); + } + if (next > nGlyphs) { + throw new Error('CFF Table CID Font FDSelect format 3 range has bad GID ' + next); + } + for (; first < next; first++) { + fdSelect.push(fdIndex); + } + first = next; + } + if (next !== nGlyphs) { + throw new Error('CFF Table CID Font FDSelect format 3 range has bad final GID ' + next); + } + } else { + throw new Error('CFF Table CID Font FDSelect table has unsupported format ' + format); + } + return fdSelect; + } // Parse the `CFF` table, which contains the glyph outlines in PostScript format. + + function parseCFFTable(data, start, font) { + font.tables.cff = { + }; + var header = parseCFFHeader(data, start); + var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString); + var topDictIndex = parseCFFIndex(data, nameIndex.endOffset); + var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString); + var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset); + font.gsubrs = globalSubrIndex.objects; + font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); + var topDictArray = gatherCFFTopDicts(data, start, topDictIndex.objects, stringIndex.objects); + if (topDictArray.length !== 1) { + throw new Error('CFF table has too many fonts in \'FontSet\' - count of fonts NameIndex.length = ' + topDictArray.length); + } + var topDict = topDictArray[0]; + font.tables.cff.topDict = topDict; + if (topDict._privateDict) { + font.defaultWidthX = topDict._privateDict.defaultWidthX; + font.nominalWidthX = topDict._privateDict.nominalWidthX; + } + if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) { + font.isCIDFont = true; + } + if (font.isCIDFont) { + var fdArrayOffset = topDict.fdArray; + var fdSelectOffset = topDict.fdSelect; + if (fdArrayOffset === 0 || fdSelectOffset === 0) { + throw new Error('Font is marked as a CID font, but FDArray and/or FDSelect information is missing'); + } + fdArrayOffset += start; + var fdArrayIndex = parseCFFIndex(data, fdArrayOffset); + var fdArray = gatherCFFTopDicts(data, start, fdArrayIndex.objects, stringIndex.objects); + topDict._fdArray = fdArray; + fdSelectOffset += start; + topDict._fdSelect = parseCFFFDSelect(data, fdSelectOffset, font.numGlyphs, fdArray.length); + } + var privateDictOffset = start + topDict.private[1]; + var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict.private[0], stringIndex.objects); + font.defaultWidthX = privateDict.defaultWidthX; + font.nominalWidthX = privateDict.nominalWidthX; + if (privateDict.subrs !== 0) { + var subrOffset = privateDictOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data, subrOffset); + font.subrs = subrIndex.objects; + font.subrsBias = calcCFFSubroutineBias(font.subrs); + } else { + font.subrs = [ + ]; + font.subrsBias = 0; + } // Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset. + + var charStringsIndex = parseCFFIndex(data, start + topDict.charStrings); + font.nGlyphs = charStringsIndex.objects.length; + var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects); + if (topDict.encoding === 0) { + // Standard encoding + font.cffEncoding = new CffEncoding(cffStandardEncoding, charset); + } else if (topDict.encoding === 1) { + // Expert encoding + font.cffEncoding = new CffEncoding(cffExpertEncoding, charset); + } else { + font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset); + } // Prefer the CMAP encoding to the CFF encoding. + + font.encoding = font.encoding || font.cffEncoding; + font.glyphs = new glyphset.GlyphSet(font); + for (var i = 0; i < font.nGlyphs; i += 1) { + var charString = charStringsIndex.objects[i]; + font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); + } + } // Convert a string to a String ID (SID). + // The list of strings is modified in place. + + function encodeString(s, strings) { + var sid; + // Is the string in the CFF standard strings? + var i = cffStandardStrings.indexOf(s); + if (i >= 0) { + sid = i; + } // Is the string already in the string index? + + i = strings.indexOf(s); + if (i >= 0) { + sid = i + cffStandardStrings.length; + } else { + sid = cffStandardStrings.length + strings.length; + strings.push(s); + } + return sid; + } + function makeHeader() { + return new table.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 makeNameIndex(fontNames) { + var t = new table.Record('Name INDEX', [ + { + name: 'names', + type: 'INDEX', + value: [ + ] + } + ]); + t.names = [ + ]; + for (var i = 0; i < fontNames.length; i += 1) { + t.names.push({ + name: 'name_' + i, + type: 'NAME', + value: fontNames[i] + }); + } + return t; + } // Given a dictionary's metadata, create a DICT structure. + + function makeDict(meta, attrs, strings) { + var m = { + }; + for (var i = 0; i < meta.length; i += 1) { + var entry = meta[i]; + var value = attrs[entry.name]; + if (value !== undefined && !equals(value, entry.value)) { + if (entry.type === 'SID') { + value = encodeString(value, strings); + } + m[entry.op] = { + name: entry.name, + type: entry.type, + value: value + }; + } + } + return m; + } // The Top DICT houses the global font attributes. + + function makeTopDict(attrs, strings) { + var t = new table.Record('Top DICT', [ + { + name: 'dict', + type: 'DICT', + value: { + } + } + ]); + t.dict = makeDict(TOP_DICT_META, attrs, strings); + return t; + } + function makeTopDictIndex(topDict) { + var t = new table.Record('Top DICT INDEX', [ + { + name: 'topDicts', + type: 'INDEX', + value: [ + ] + } + ]); + t.topDicts = [ + { + name: 'topDict_0', + type: 'TABLE', + value: topDict + } + ]; + return t; + } + function makeStringIndex(strings) { + var t = new table.Record('String INDEX', [ + { + name: 'strings', + type: 'INDEX', + value: [ + ] + } + ]); + t.strings = [ + ]; + for (var i = 0; i < strings.length; i += 1) { + t.strings.push({ + name: 'string_' + i, + type: 'STRING', + value: strings[i] + }); + } + return t; + } + function makeGlobalSubrIndex() { + // Currently we don't use subroutines. + return new table.Record('Global Subr INDEX', [ + { + name: 'subrs', + type: 'INDEX', + value: [ + ] + } + ]); + } + function makeCharsets(glyphNames, strings) { + var t = new table.Record('Charsets', [ + { + name: 'format', + type: 'Card8', + value: 0 + } + ]); + for (var i = 0; i < glyphNames.length; i += 1) { + var glyphName = glyphNames[i]; + var glyphSID = encodeString(glyphName, strings); + t.fields.push({ + name: 'glyph_' + i, + type: 'SID', + value: glyphSID + }); + } + return t; + } + function glyphToOps(glyph) { + var ops = [ + ]; + var path = glyph.path; + ops.push({ + name: 'width', + type: 'NUMBER', + value: glyph.advanceWidth + }); + var x = 0; + var y = 0; + for (var i = 0; i < path.commands.length; i += 1) { + var dx = void 0; + var dy = void 0; + var cmd = path.commands[i]; + if (cmd.type === 'Q') { + // CFF only supports bézier curves, so convert the quad to a bézier. + var _13 = 1 / 3; + var _23 = 2 / 3; + // We're going to create a new command so we don't change the original path. + cmd = { + type: 'C', + x: cmd.x, + y: cmd.y, + x1: _13 * x + _23 * cmd.x1, + y1: _13 * y + _23 * cmd.y1, + x2: _13 * cmd.x + _23 * cmd.x1, + y2: _13 * cmd.y + _23 * cmd.y1 + }; + } + if (cmd.type === 'M') { + dx = Math.round(cmd.x - x); + dy = Math.round(cmd.y - y); + ops.push({ + name: 'dx', + type: 'NUMBER', + value: dx + }); + ops.push({ + name: 'dy', + type: 'NUMBER', + value: dy + }); + ops.push({ + name: 'rmoveto', + type: 'OP', + value: 21 + }); + x = Math.round(cmd.x); + y = Math.round(cmd.y); + } else if (cmd.type === 'L') { + dx = Math.round(cmd.x - x); + dy = Math.round(cmd.y - y); + ops.push({ + name: 'dx', + type: 'NUMBER', + value: dx + }); + ops.push({ + name: 'dy', + type: 'NUMBER', + value: dy + }); + ops.push({ + name: 'rlineto', + type: 'OP', + value: 5 + }); + x = Math.round(cmd.x); + y = Math.round(cmd.y); + } else if (cmd.type === 'C') { + var dx1 = Math.round(cmd.x1 - x); + var dy1 = Math.round(cmd.y1 - y); + var dx2 = Math.round(cmd.x2 - cmd.x1); + var dy2 = Math.round(cmd.y2 - cmd.y1); + dx = Math.round(cmd.x - cmd.x2); + dy = Math.round(cmd.y - cmd.y2); + ops.push({ + name: 'dx1', + type: 'NUMBER', + value: dx1 + }); + ops.push({ + name: 'dy1', + type: 'NUMBER', + value: dy1 + }); + ops.push({ + name: 'dx2', + type: 'NUMBER', + value: dx2 + }); + ops.push({ + name: 'dy2', + type: 'NUMBER', + value: dy2 + }); + ops.push({ + name: 'dx', + type: 'NUMBER', + value: dx + }); + ops.push({ + name: 'dy', + type: 'NUMBER', + value: dy + }); + ops.push({ + name: 'rrcurveto', + type: 'OP', + value: 8 + }); + x = Math.round(cmd.x); + y = Math.round(cmd.y); + } // Contours are closed automatically. + + } + ops.push({ + name: 'endchar', + type: 'OP', + value: 14 + }); + return ops; + } + function makeCharStringsIndex(glyphs) { + var t = new table.Record('CharStrings INDEX', [ + { + name: 'charStrings', + type: 'INDEX', + value: [ + ] + } + ]); + for (var i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var ops = glyphToOps(glyph); + t.charStrings.push({ + name: glyph.name, + type: 'CHARSTRING', + value: ops + }); + } + return t; + } + function makePrivateDict(attrs, strings) { + var t = new table.Record('Private DICT', [ + { + name: 'dict', + type: 'DICT', + value: { + } + } + ]); + t.dict = makeDict(PRIVATE_DICT_META, attrs, strings); + return t; + } + function makeCFFTable(glyphs, options) { + var t = new table.Table('CFF ', [ + { + name: 'header', + type: 'RECORD' + }, + { + name: 'nameIndex', + type: 'RECORD' + }, + { + name: 'topDictIndex', + type: 'RECORD' + }, + { + name: 'stringIndex', + type: 'RECORD' + }, + { + name: 'globalSubrIndex', + type: 'RECORD' + }, + { + name: 'charsets', + type: 'RECORD' + }, + { + name: 'charStringsIndex', + type: 'RECORD' + }, + { + name: 'privateDict', + type: 'RECORD' + } + ]); + var fontScale = 1 / options.unitsPerEm; + // We use non-zero values for the offsets so that the DICT encodes them. + // This is important because the size of the Top DICT plays a role in offset calculation, + // and the size shouldn't change after we've written correct offsets. + var attrs = { + version: options.version, + fullName: options.fullName, + familyName: options.familyName, + weight: options.weightName, + fontBBox: options.fontBBox || [ + 0, + 0, + 0, + 0 + ], + fontMatrix: [ + fontScale, + 0, + 0, + fontScale, + 0, + 0 + ], + charset: 999, + encoding: 0, + charStrings: 999, + private: [ + 0, + 999 + ] + }; + var privateAttrs = { + }; + var glyphNames = [ + ]; + var glyph; + // Skip first glyph (.notdef) + for (var i = 1; i < glyphs.length; i += 1) { + glyph = glyphs.get(i); + glyphNames.push(glyph.name); + } + var strings = [ + ]; + t.header = makeHeader(); + t.nameIndex = makeNameIndex([options.postScriptName]); + var topDict = makeTopDict(attrs, strings); + t.topDictIndex = makeTopDictIndex(topDict); + t.globalSubrIndex = makeGlobalSubrIndex(); + t.charsets = makeCharsets(glyphNames, strings); + t.charStringsIndex = makeCharStringsIndex(glyphs); + t.privateDict = makePrivateDict(privateAttrs, strings); + // Needs to come at the end, to encode all custom strings used in the font. + t.stringIndex = makeStringIndex(strings); + var startOffset = t.header.sizeOf() + t.nameIndex.sizeOf() + t.topDictIndex.sizeOf() + t.stringIndex.sizeOf() + t.globalSubrIndex.sizeOf(); + attrs.charset = startOffset; + // We use the CFF standard encoding; proper encoding will be handled in cmap. + attrs.encoding = 0; + attrs.charStrings = attrs.charset + t.charsets.sizeOf(); + attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf(); + // Recreate the Top DICT INDEX with the correct offsets. + topDict = makeTopDict(attrs, strings); + t.topDictIndex = makeTopDictIndex(topDict); + return t; + } + var cff = { + parse: parseCFFTable, + make: makeCFFTable + }; + // The `head` table contains global information about the font. + // Parse the header `head` table + function parseHeadTable(data, start) { + var head = { + }; + var p = new parse.Parser(data, start); + head.version = p.parseVersion(); + head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; + head.checkSumAdjustment = p.parseULong(); + head.magicNumber = p.parseULong(); + check.argument(head.magicNumber === 1594834165, 'Font header has wrong magic number.'); + head.flags = p.parseUShort(); + head.unitsPerEm = p.parseUShort(); + head.created = p.parseLongDateTime(); + head.modified = p.parseLongDateTime(); + head.xMin = p.parseShort(); + head.yMin = p.parseShort(); + head.xMax = p.parseShort(); + head.yMax = p.parseShort(); + head.macStyle = p.parseUShort(); + head.lowestRecPPEM = p.parseUShort(); + head.fontDirectionHint = p.parseShort(); + head.indexToLocFormat = p.parseShort(); + head.glyphDataFormat = p.parseShort(); + return head; + } + function makeHeadTable(options) { + // Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970 + var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; + var createdTimestamp = timestamp; + if (options.createdTimestamp) { + createdTimestamp = options.createdTimestamp + 2082844800; + } + return new table.Table('head', [ + { + name: 'version', + type: 'FIXED', + value: 65536 + }, + { + name: 'fontRevision', + type: 'FIXED', + value: 65536 + }, + { + name: 'checkSumAdjustment', + type: 'ULONG', + value: 0 + }, + { + name: 'magicNumber', + type: 'ULONG', + value: 1594834165 + }, + { + name: 'flags', + type: 'USHORT', + value: 0 + }, + { + name: 'unitsPerEm', + type: 'USHORT', + value: 1000 + }, + { + name: 'created', + type: 'LONGDATETIME', + value: createdTimestamp + }, + { + name: 'modified', + type: 'LONGDATETIME', + value: timestamp + }, + { + name: 'xMin', + type: 'SHORT', + value: 0 + }, + { + name: 'yMin', + type: 'SHORT', + value: 0 + }, + { + name: 'xMax', + type: 'SHORT', + value: 0 + }, + { + name: 'yMax', + type: 'SHORT', + value: 0 + }, + { + name: 'macStyle', + type: 'USHORT', + value: 0 + }, + { + name: 'lowestRecPPEM', + type: 'USHORT', + value: 0 + }, + { + name: 'fontDirectionHint', + type: 'SHORT', + value: 2 + }, + { + name: 'indexToLocFormat', + type: 'SHORT', + value: 0 + }, + { + name: 'glyphDataFormat', + type: 'SHORT', + value: 0 + } + ], options); + } + var head = { + parse: parseHeadTable, + make: makeHeadTable + }; + // The `hhea` table contains information for horizontal layout. + // Parse the horizontal header `hhea` table + function parseHheaTable(data, start) { + var hhea = { + }; + var p = new parse.Parser(data, start); + hhea.version = p.parseVersion(); + hhea.ascender = p.parseShort(); + hhea.descender = p.parseShort(); + hhea.lineGap = p.parseShort(); + hhea.advanceWidthMax = p.parseUShort(); + hhea.minLeftSideBearing = p.parseShort(); + hhea.minRightSideBearing = p.parseShort(); + hhea.xMaxExtent = p.parseShort(); + hhea.caretSlopeRise = p.parseShort(); + hhea.caretSlopeRun = p.parseShort(); + hhea.caretOffset = p.parseShort(); + p.relativeOffset += 8; + hhea.metricDataFormat = p.parseShort(); + hhea.numberOfHMetrics = p.parseUShort(); + return hhea; + } + function makeHheaTable(options) { + return new table.Table('hhea', [ + { + name: 'version', + type: 'FIXED', + value: 65536 + }, + { + name: 'ascender', + type: 'FWORD', + value: 0 + }, + { + name: 'descender', + type: 'FWORD', + value: 0 + }, + { + name: 'lineGap', + type: 'FWORD', + value: 0 + }, + { + name: 'advanceWidthMax', + type: 'UFWORD', + value: 0 + }, + { + name: 'minLeftSideBearing', + type: 'FWORD', + value: 0 + }, + { + name: 'minRightSideBearing', + type: 'FWORD', + value: 0 + }, + { + name: 'xMaxExtent', + type: 'FWORD', + value: 0 + }, + { + name: 'caretSlopeRise', + type: 'SHORT', + value: 1 + }, + { + name: 'caretSlopeRun', + type: 'SHORT', + value: 0 + }, + { + name: 'caretOffset', + type: 'SHORT', + value: 0 + }, + { + name: 'reserved1', + type: 'SHORT', + value: 0 + }, + { + name: 'reserved2', + type: 'SHORT', + value: 0 + }, + { + name: 'reserved3', + type: 'SHORT', + value: 0 + }, + { + name: 'reserved4', + type: 'SHORT', + value: 0 + }, + { + name: 'metricDataFormat', + type: 'SHORT', + value: 0 + }, + { + name: 'numberOfHMetrics', + type: 'USHORT', + value: 0 + } + ], options); + } + var hhea = { + parse: parseHheaTable, + make: makeHheaTable + }; + // The `hmtx` table contains the horizontal metrics for all glyphs. + // Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. + // This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. + function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) { + var advanceWidth; + var leftSideBearing; + var p = new parse.Parser(data, start); + for (var i = 0; i < numGlyphs; i += 1) { + // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. + if (i < numMetrics) { + advanceWidth = p.parseUShort(); + leftSideBearing = p.parseShort(); + } + var glyph = glyphs.get(i); + glyph.advanceWidth = advanceWidth; + glyph.leftSideBearing = leftSideBearing; + } + } + function makeHmtxTable(glyphs) { + var t = new table.Table('hmtx', [ + ]); + for (var i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var advanceWidth = glyph.advanceWidth || 0; + var leftSideBearing = glyph.leftSideBearing || 0; + t.fields.push({ + name: 'advanceWidth_' + i, + type: 'USHORT', + value: advanceWidth + }); + t.fields.push({ + name: 'leftSideBearing_' + i, + type: 'SHORT', + value: leftSideBearing + }); + } + return t; + } + var hmtx = { + parse: parseHmtxTable, + make: makeHmtxTable + }; + // The `ltag` table stores IETF BCP-47 language tags. It allows supporting + function makeLtagTable(tags) { + var result = new table.Table('ltag', [ + { + name: 'version', + type: 'ULONG', + value: 1 + }, + { + name: 'flags', + type: 'ULONG', + value: 0 + }, + { + name: 'numTags', + type: 'ULONG', + value: tags.length + } + ]); + var stringPool = ''; + var stringPoolOffset = 12 + tags.length * 4; + for (var i = 0; i < tags.length; ++i) { + var pos = stringPool.indexOf(tags[i]); + if (pos < 0) { + pos = stringPool.length; + stringPool += tags[i]; + } + result.fields.push({ + name: 'offset ' + i, + type: 'USHORT', + value: stringPoolOffset + pos + }); + result.fields.push({ + name: 'length ' + i, + type: 'USHORT', + value: tags[i].length + }); + } + result.fields.push({ + name: 'stringPool', + type: 'CHARARRAY', + value: stringPool + }); + return result; + } + function parseLtagTable(data, start) { + var p = new parse.Parser(data, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, 'Unsupported ltag table version.'); + // The 'ltag' specification does not define any flags; skip the field. + p.skip('uLong', 1); + var numTags = p.parseULong(); + var tags = [ + ]; + for (var i = 0; i < numTags; i++) { + var tag = ''; + var offset = start + p.parseUShort(); + var length = p.parseUShort(); + for (var j = offset; j < offset + length; ++j) { + tag += String.fromCharCode(data.getInt8(j)); + } + tags.push(tag); + } + return tags; + } + var ltag = { + make: makeLtagTable, + parse: parseLtagTable + }; + // The `maxp` table establishes the memory requirements for the font. + // Parse the maximum profile `maxp` table. + function parseMaxpTable(data, start) { + var maxp = { + }; + var p = new parse.Parser(data, start); + maxp.version = p.parseVersion(); + maxp.numGlyphs = p.parseUShort(); + if (maxp.version === 1) { + maxp.maxPoints = p.parseUShort(); + maxp.maxContours = p.parseUShort(); + maxp.maxCompositePoints = p.parseUShort(); + maxp.maxCompositeContours = p.parseUShort(); + maxp.maxZones = p.parseUShort(); + maxp.maxTwilightPoints = p.parseUShort(); + maxp.maxStorage = p.parseUShort(); + maxp.maxFunctionDefs = p.parseUShort(); + maxp.maxInstructionDefs = p.parseUShort(); + maxp.maxStackElements = p.parseUShort(); + maxp.maxSizeOfInstructions = p.parseUShort(); + maxp.maxComponentElements = p.parseUShort(); + maxp.maxComponentDepth = p.parseUShort(); + } + return maxp; + } + function makeMaxpTable(numGlyphs) { + return new table.Table('maxp', [ + { + name: 'version', + type: 'FIXED', + value: 20480 + }, + { + name: 'numGlyphs', + type: 'USHORT', + value: numGlyphs + } + ]); + } + var maxp = { + parse: parseMaxpTable, + make: makeMaxpTable + }; + // The `name` naming table. + // NameIDs for the name table. + var nameTableNames = [ + 'copyright', + // 0 + 'fontFamily', + // 1 + 'fontSubfamily', + // 2 + 'uniqueID', + // 3 + 'fullName', + // 4 + 'version', + // 5 + 'postScriptName', + // 6 + 'trademark', + // 7 + 'manufacturer', + // 8 + 'designer', + // 9 + 'description', + // 10 + 'manufacturerURL', + // 11 + 'designerURL', + // 12 + 'license', + // 13 + 'licenseURL', + // 14 + 'reserved', + // 15 + 'preferredFamily', + // 16 + 'preferredSubfamily', + // 17 + 'compatibleFullName', + // 18 + 'sampleText', + // 19 + 'postScriptFindFontName', + // 20 + 'wwsFamily', + // 21 + 'wwsSubfamily' // 22 + ]; + var macLanguages = { + 0: 'en', + 1: 'fr', + 2: 'de', + 3: 'it', + 4: 'nl', + 5: 'sv', + 6: 'es', + 7: 'da', + 8: 'pt', + 9: 'no', + 10: 'he', + 11: 'ja', + 12: 'ar', + 13: 'fi', + 14: 'el', + 15: 'is', + 16: 'mt', + 17: 'tr', + 18: 'hr', + 19: 'zh-Hant', + 20: 'ur', + 21: 'hi', + 22: 'th', + 23: 'ko', + 24: 'lt', + 25: 'pl', + 26: 'hu', + 27: 'es', + 28: 'lv', + 29: 'se', + 30: 'fo', + 31: 'fa', + 32: 'ru', + 33: 'zh', + 34: 'nl-BE', + 35: 'ga', + 36: 'sq', + 37: 'ro', + 38: 'cz', + 39: 'sk', + 40: 'si', + 41: 'yi', + 42: 'sr', + 43: 'mk', + 44: 'bg', + 45: 'uk', + 46: 'be', + 47: 'uz', + 48: 'kk', + 49: 'az-Cyrl', + 50: 'az-Arab', + 51: 'hy', + 52: 'ka', + 53: 'mo', + 54: 'ky', + 55: 'tg', + 56: 'tk', + 57: 'mn-CN', + 58: 'mn', + 59: 'ps', + 60: 'ks', + 61: 'ku', + 62: 'sd', + 63: 'bo', + 64: 'ne', + 65: 'sa', + 66: 'mr', + 67: 'bn', + 68: 'as', + 69: 'gu', + 70: 'pa', + 71: 'or', + 72: 'ml', + 73: 'kn', + 74: 'ta', + 75: 'te', + 76: 'si', + 77: 'my', + 78: 'km', + 79: 'lo', + 80: 'vi', + 81: 'id', + 82: 'tl', + 83: 'ms', + 84: 'ms-Arab', + 85: 'am', + 86: 'ti', + 87: 'om', + 88: 'so', + 89: 'sw', + 90: 'rw', + 91: 'rn', + 92: 'ny', + 93: 'mg', + 94: 'eo', + 128: 'cy', + 129: 'eu', + 130: 'ca', + 131: 'la', + 132: 'qu', + 133: 'gn', + 134: 'ay', + 135: 'tt', + 136: 'ug', + 137: 'dz', + 138: 'jv', + 139: 'su', + 140: 'gl', + 141: 'af', + 142: 'br', + 143: 'iu', + 144: 'gd', + 145: 'gv', + 146: 'ga', + 147: 'to', + 148: 'el-polyton', + 149: 'kl', + 150: 'az', + 151: 'nn' + }; + // MacOS language ID → MacOS script ID + // + // Note that the script ID is not sufficient to determine what encoding + // to use in TrueType files. For some languages, MacOS used a modification + // of a mainstream script. For example, an Icelandic name would be stored + // with smRoman in the TrueType naming table, but the actual encoding + // is a special Icelandic version of the normal Macintosh Roman encoding. + // As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal + // Syllables but MacOS had run out of available script codes, so this was + // done as a (pretty radical) "modification" of Ethiopic. + // + // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt + var macLanguageToScript = { + 0: 0, + // langEnglish → smRoman + 1: 0, + // langFrench → smRoman + 2: 0, + // langGerman → smRoman + 3: 0, + // langItalian → smRoman + 4: 0, + // langDutch → smRoman + 5: 0, + // langSwedish → smRoman + 6: 0, + // langSpanish → smRoman + 7: 0, + // langDanish → smRoman + 8: 0, + // langPortuguese → smRoman + 9: 0, + // langNorwegian → smRoman + 10: 5, + // langHebrew → smHebrew + 11: 1, + // langJapanese → smJapanese + 12: 4, + // langArabic → smArabic + 13: 0, + // langFinnish → smRoman + 14: 6, + // langGreek → smGreek + 15: 0, + // langIcelandic → smRoman (modified) + 16: 0, + // langMaltese → smRoman + 17: 0, + // langTurkish → smRoman (modified) + 18: 0, + // langCroatian → smRoman (modified) + 19: 2, + // langTradChinese → smTradChinese + 20: 4, + // langUrdu → smArabic + 21: 9, + // langHindi → smDevanagari + 22: 21, + // langThai → smThai + 23: 3, + // langKorean → smKorean + 24: 29, + // langLithuanian → smCentralEuroRoman + 25: 29, + // langPolish → smCentralEuroRoman + 26: 29, + // langHungarian → smCentralEuroRoman + 27: 29, + // langEstonian → smCentralEuroRoman + 28: 29, + // langLatvian → smCentralEuroRoman + 29: 0, + // langSami → smRoman + 30: 0, + // langFaroese → smRoman (modified) + 31: 4, + // langFarsi → smArabic (modified) + 32: 7, + // langRussian → smCyrillic + 33: 25, + // langSimpChinese → smSimpChinese + 34: 0, + // langFlemish → smRoman + 35: 0, + // langIrishGaelic → smRoman (modified) + 36: 0, + // langAlbanian → smRoman + 37: 0, + // langRomanian → smRoman (modified) + 38: 29, + // langCzech → smCentralEuroRoman + 39: 29, + // langSlovak → smCentralEuroRoman + 40: 0, + // langSlovenian → smRoman (modified) + 41: 5, + // langYiddish → smHebrew + 42: 7, + // langSerbian → smCyrillic + 43: 7, + // langMacedonian → smCyrillic + 44: 7, + // langBulgarian → smCyrillic + 45: 7, + // langUkrainian → smCyrillic (modified) + 46: 7, + // langByelorussian → smCyrillic + 47: 7, + // langUzbek → smCyrillic + 48: 7, + // langKazakh → smCyrillic + 49: 7, + // langAzerbaijani → smCyrillic + 50: 4, + // langAzerbaijanAr → smArabic + 51: 24, + // langArmenian → smArmenian + 52: 23, + // langGeorgian → smGeorgian + 53: 7, + // langMoldavian → smCyrillic + 54: 7, + // langKirghiz → smCyrillic + 55: 7, + // langTajiki → smCyrillic + 56: 7, + // langTurkmen → smCyrillic + 57: 27, + // langMongolian → smMongolian + 58: 7, + // langMongolianCyr → smCyrillic + 59: 4, + // langPashto → smArabic + 60: 4, + // langKurdish → smArabic + 61: 4, + // langKashmiri → smArabic + 62: 4, + // langSindhi → smArabic + 63: 26, + // langTibetan → smTibetan + 64: 9, + // langNepali → smDevanagari + 65: 9, + // langSanskrit → smDevanagari + 66: 9, + // langMarathi → smDevanagari + 67: 13, + // langBengali → smBengali + 68: 13, + // langAssamese → smBengali + 69: 11, + // langGujarati → smGujarati + 70: 10, + // langPunjabi → smGurmukhi + 71: 12, + // langOriya → smOriya + 72: 17, + // langMalayalam → smMalayalam + 73: 16, + // langKannada → smKannada + 74: 14, + // langTamil → smTamil + 75: 15, + // langTelugu → smTelugu + 76: 18, + // langSinhalese → smSinhalese + 77: 19, + // langBurmese → smBurmese + 78: 20, + // langKhmer → smKhmer + 79: 22, + // langLao → smLao + 80: 30, + // langVietnamese → smVietnamese + 81: 0, + // langIndonesian → smRoman + 82: 0, + // langTagalog → smRoman + 83: 0, + // langMalayRoman → smRoman + 84: 4, + // langMalayArabic → smArabic + 85: 28, + // langAmharic → smEthiopic + 86: 28, + // langTigrinya → smEthiopic + 87: 28, + // langOromo → smEthiopic + 88: 0, + // langSomali → smRoman + 89: 0, + // langSwahili → smRoman + 90: 0, + // langKinyarwanda → smRoman + 91: 0, + // langRundi → smRoman + 92: 0, + // langNyanja → smRoman + 93: 0, + // langMalagasy → smRoman + 94: 0, + // langEsperanto → smRoman + 128: 0, + // langWelsh → smRoman (modified) + 129: 0, + // langBasque → smRoman + 130: 0, + // langCatalan → smRoman + 131: 0, + // langLatin → smRoman + 132: 0, + // langQuechua → smRoman + 133: 0, + // langGuarani → smRoman + 134: 0, + // langAymara → smRoman + 135: 7, + // langTatar → smCyrillic + 136: 4, + // langUighur → smArabic + 137: 26, + // langDzongkha → smTibetan + 138: 0, + // langJavaneseRom → smRoman + 139: 0, + // langSundaneseRom → smRoman + 140: 0, + // langGalician → smRoman + 141: 0, + // langAfrikaans → smRoman + 142: 0, + // langBreton → smRoman (modified) + 143: 28, + // langInuktitut → smEthiopic (modified) + 144: 0, + // langScottishGaelic → smRoman (modified) + 145: 0, + // langManxGaelic → smRoman (modified) + 146: 0, + // langIrishGaelicScript → smRoman (modified) + 147: 0, + // langTongan → smRoman + 148: 6, + // langGreekAncient → smRoman + 149: 0, + // langGreenlandic → smRoman + 150: 0, + // langAzerbaijanRoman → smRoman + 151: 0 // langNynorsk → smRoman + }; + // While Microsoft indicates a region/country for all its language + // IDs, we omit the region code if it's equal to the "most likely + // region subtag" according to Unicode CLDR. For scripts, we omit + // the subtag if it is equal to the Suppress-Script entry in the + // IANA language subtag registry for IETF BCP 47. + // + // For example, Microsoft states that its language code 0x041A is + // Croatian in Croatia. We transform this to the BCP 47 language code 'hr' + // and not 'hr-HR' because Croatia is the default country for Croatian, + // according to Unicode CLDR. As another example, Microsoft states + // that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform + // this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script + // for the Croatian language, according to IANA. + // + // http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html + // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry + var windowsLanguages = { + 1078: 'af', + 1052: 'sq', + 1156: 'gsw', + 1118: 'am', + 5121: 'ar-DZ', + 15361: 'ar-BH', + 3073: 'ar', + 2049: 'ar-IQ', + 11265: 'ar-JO', + 13313: 'ar-KW', + 12289: 'ar-LB', + 4097: 'ar-LY', + 6145: 'ary', + 8193: 'ar-OM', + 16385: 'ar-QA', + 1025: 'ar-SA', + 10241: 'ar-SY', + 7169: 'aeb', + 14337: 'ar-AE', + 9217: 'ar-YE', + 1067: 'hy', + 1101: 'as', + 2092: 'az-Cyrl', + 1068: 'az', + 1133: 'ba', + 1069: 'eu', + 1059: 'be', + 2117: 'bn', + 1093: 'bn-IN', + 8218: 'bs-Cyrl', + 5146: 'bs', + 1150: 'br', + 1026: 'bg', + 1027: 'ca', + 3076: 'zh-HK', + 5124: 'zh-MO', + 2052: 'zh', + 4100: 'zh-SG', + 1028: 'zh-TW', + 1155: 'co', + 1050: 'hr', + 4122: 'hr-BA', + 1029: 'cs', + 1030: 'da', + 1164: 'prs', + 1125: 'dv', + 2067: 'nl-BE', + 1043: 'nl', + 3081: 'en-AU', + 10249: 'en-BZ', + 4105: 'en-CA', + 9225: 'en-029', + 16393: 'en-IN', + 6153: 'en-IE', + 8201: 'en-JM', + 17417: 'en-MY', + 5129: 'en-NZ', + 13321: 'en-PH', + 18441: 'en-SG', + 7177: 'en-ZA', + 11273: 'en-TT', + 2057: 'en-GB', + 1033: 'en', + 12297: 'en-ZW', + 1061: 'et', + 1080: 'fo', + 1124: 'fil', + 1035: 'fi', + 2060: 'fr-BE', + 3084: 'fr-CA', + 1036: 'fr', + 5132: 'fr-LU', + 6156: 'fr-MC', + 4108: 'fr-CH', + 1122: 'fy', + 1110: 'gl', + 1079: 'ka', + 3079: 'de-AT', + 1031: 'de', + 5127: 'de-LI', + 4103: 'de-LU', + 2055: 'de-CH', + 1032: 'el', + 1135: 'kl', + 1095: 'gu', + 1128: 'ha', + 1037: 'he', + 1081: 'hi', + 1038: 'hu', + 1039: 'is', + 1136: 'ig', + 1057: 'id', + 1117: 'iu', + 2141: 'iu-Latn', + 2108: 'ga', + 1076: 'xh', + 1077: 'zu', + 1040: 'it', + 2064: 'it-CH', + 1041: 'ja', + 1099: 'kn', + 1087: 'kk', + 1107: 'km', + 1158: 'quc', + 1159: 'rw', + 1089: 'sw', + 1111: 'kok', + 1042: 'ko', + 1088: 'ky', + 1108: 'lo', + 1062: 'lv', + 1063: 'lt', + 2094: 'dsb', + 1134: 'lb', + 1071: 'mk', + 2110: 'ms-BN', + 1086: 'ms', + 1100: 'ml', + 1082: 'mt', + 1153: 'mi', + 1146: 'arn', + 1102: 'mr', + 1148: 'moh', + 1104: 'mn', + 2128: 'mn-CN', + 1121: 'ne', + 1044: 'nb', + 2068: 'nn', + 1154: 'oc', + 1096: 'or', + 1123: 'ps', + 1045: 'pl', + 1046: 'pt', + 2070: 'pt-PT', + 1094: 'pa', + 1131: 'qu-BO', + 2155: 'qu-EC', + 3179: 'qu', + 1048: 'ro', + 1047: 'rm', + 1049: 'ru', + 9275: 'smn', + 4155: 'smj-NO', + 5179: 'smj', + 3131: 'se-FI', + 1083: 'se', + 2107: 'se-SE', + 8251: 'sms', + 6203: 'sma-NO', + 7227: 'sms', + 1103: 'sa', + 7194: 'sr-Cyrl-BA', + 3098: 'sr', + 6170: 'sr-Latn-BA', + 2074: 'sr-Latn', + 1132: 'nso', + 1074: 'tn', + 1115: 'si', + 1051: 'sk', + 1060: 'sl', + 11274: 'es-AR', + 16394: 'es-BO', + 13322: 'es-CL', + 9226: 'es-CO', + 5130: 'es-CR', + 7178: 'es-DO', + 12298: 'es-EC', + 17418: 'es-SV', + 4106: 'es-GT', + 18442: 'es-HN', + 2058: 'es-MX', + 19466: 'es-NI', + 6154: 'es-PA', + 15370: 'es-PY', + 10250: 'es-PE', + 20490: 'es-PR', + // Microsoft has defined two different language codes for + // “Spanish with modern sorting” and “Spanish with traditional + // sorting”. This makes sense for collation APIs, and it would be + // possible to express this in BCP 47 language tags via Unicode + // extensions (eg., es-u-co-trad is Spanish with traditional + // sorting). However, for storing names in fonts, the distinction + // does not make sense, so we give “es” in both cases. + 3082: 'es', + 1034: 'es', + 21514: 'es-US', + 14346: 'es-UY', + 8202: 'es-VE', + 2077: 'sv-FI', + 1053: 'sv', + 1114: 'syr', + 1064: 'tg', + 2143: 'tzm', + 1097: 'ta', + 1092: 'tt', + 1098: 'te', + 1054: 'th', + 1105: 'bo', + 1055: 'tr', + 1090: 'tk', + 1152: 'ug', + 1058: 'uk', + 1070: 'hsb', + 1056: 'ur', + 2115: 'uz-Cyrl', + 1091: 'uz', + 1066: 'vi', + 1106: 'cy', + 1160: 'wo', + 1157: 'sah', + 1144: 'ii', + 1130: 'yo' + }; + // Returns a IETF BCP 47 language code, for example 'zh-Hant' + // for 'Chinese in the traditional script'. + function getLanguageCode(platformID, languageID, ltag) { + switch (platformID) { + case 0: + // Unicode + if (languageID === 65535) { + return 'und'; + } else if (ltag) { + return ltag[languageID]; + } + break; + case 1: + // Macintosh + return macLanguages[languageID]; + case 3: + // Windows + return windowsLanguages[languageID]; + } + return undefined; + } + var utf16 = 'utf-16'; + // MacOS script ID → encoding. This table stores the default case, + // which can be overridden by macLanguageEncodings. + var macScriptEncodings = { + 0: 'macintosh', + // smRoman + 1: 'x-mac-japanese', + // smJapanese + 2: 'x-mac-chinesetrad', + // smTradChinese + 3: 'x-mac-korean', + // smKorean + 6: 'x-mac-greek', + // smGreek + 7: 'x-mac-cyrillic', + // smCyrillic + 9: 'x-mac-devanagai', + // smDevanagari + 10: 'x-mac-gurmukhi', + // smGurmukhi + 11: 'x-mac-gujarati', + // smGujarati + 12: 'x-mac-oriya', + // smOriya + 13: 'x-mac-bengali', + // smBengali + 14: 'x-mac-tamil', + // smTamil + 15: 'x-mac-telugu', + // smTelugu + 16: 'x-mac-kannada', + // smKannada + 17: 'x-mac-malayalam', + // smMalayalam + 18: 'x-mac-sinhalese', + // smSinhalese + 19: 'x-mac-burmese', + // smBurmese + 20: 'x-mac-khmer', + // smKhmer + 21: 'x-mac-thai', + // smThai + 22: 'x-mac-lao', + // smLao + 23: 'x-mac-georgian', + // smGeorgian + 24: 'x-mac-armenian', + // smArmenian + 25: 'x-mac-chinesesimp', + // smSimpChinese + 26: 'x-mac-tibetan', + // smTibetan + 27: 'x-mac-mongolian', + // smMongolian + 28: 'x-mac-ethiopic', + // smEthiopic + 29: 'x-mac-ce', + // smCentralEuroRoman + 30: 'x-mac-vietnamese', + // smVietnamese + 31: 'x-mac-extarabic' // smExtArabic + }; + // MacOS language ID → encoding. This table stores the exceptional + // cases, which override macScriptEncodings. For writing MacOS naming + // tables, we need to emit a MacOS script ID. Therefore, we cannot + // merge macScriptEncodings into macLanguageEncodings. + // + // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt + var macLanguageEncodings = { + 15: 'x-mac-icelandic', + // langIcelandic + 17: 'x-mac-turkish', + // langTurkish + 18: 'x-mac-croatian', + // langCroatian + 24: 'x-mac-ce', + // langLithuanian + 25: 'x-mac-ce', + // langPolish + 26: 'x-mac-ce', + // langHungarian + 27: 'x-mac-ce', + // langEstonian + 28: 'x-mac-ce', + // langLatvian + 30: 'x-mac-icelandic', + // langFaroese + 37: 'x-mac-romanian', + // langRomanian + 38: 'x-mac-ce', + // langCzech + 39: 'x-mac-ce', + // langSlovak + 40: 'x-mac-ce', + // langSlovenian + 143: 'x-mac-inuit', + // langInuktitut + 146: 'x-mac-gaelic' // langIrishGaelicScript + }; + function getEncoding(platformID, encodingID, languageID) { + switch (platformID) { + case 0: + // Unicode + return utf16; + case 1: + // Apple Macintosh + return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; + case 3: + // Microsoft Windows + if (encodingID === 1 || encodingID === 10) { + return utf16; + } + break; + } + return undefined; + } // Parse the naming `name` table. + // FIXME: Format 1 additional fields are not supported yet. + // ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904']. + + function parseNameTable(data, start, ltag) { + var name = { + }; + var p = new parse.Parser(data, start); + var format = p.parseUShort(); + var count = p.parseUShort(); + var stringOffset = p.offset + p.parseUShort(); + for (var i = 0; i < count; i++) { + var platformID = p.parseUShort(); + var encodingID = p.parseUShort(); + var languageID = p.parseUShort(); + var nameID = p.parseUShort(); + var property = nameTableNames[nameID] || nameID; + var byteLength = p.parseUShort(); + var offset = p.parseUShort(); + var language = getLanguageCode(platformID, languageID, ltag); + var encoding = getEncoding(platformID, encodingID, languageID); + if (encoding !== undefined && language !== undefined) { + var text = void 0; + if (encoding === utf16) { + text = decode.UTF16(data, stringOffset + offset, byteLength); + } else { + text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding); + } + if (text) { + var translations = name[property]; + if (translations === undefined) { + translations = name[property] = { + }; + } + translations[language] = text; + } + } + } + var langTagCount = 0; + if (format === 1) { + // FIXME: Also handle Microsoft's 'name' table 1. + langTagCount = p.parseUShort(); + } + return name; + } // {23: 'foo'} → {'foo': 23} + // ['bar', 'baz'] → {'bar': 0, 'baz': 1} + + function reverseDict(dict) { + var result = { + }; + for (var key in dict) { + result[dict[key]] = parseInt(key); + } + return result; + } + function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) { + return new table.Record('NameRecord', [ + { + name: 'platformID', + type: 'USHORT', + value: platformID + }, + { + name: 'encodingID', + type: 'USHORT', + value: encodingID + }, + { + name: 'languageID', + type: 'USHORT', + value: languageID + }, + { + name: 'nameID', + type: 'USHORT', + value: nameID + }, + { + name: 'length', + type: 'USHORT', + value: length + }, + { + name: 'offset', + type: 'USHORT', + value: offset + } + ]); + } // Finds the position of needle in haystack, or -1 if not there. + // Like String.indexOf(), but for arrays. + + function findSubArray(needle, haystack) { + var needleLength = needle.length; + var limit = haystack.length - needleLength + 1; + loop: for (var pos = 0; pos < limit; pos++) { + for (; pos < limit; pos++) { + for (var k = 0; k < needleLength; k++) { + if (haystack[pos + k] !== needle[k]) { + continue loop; + } + } + return pos; + } + } + return - 1; + } + function addStringToPool(s, pool) { + var offset = findSubArray(s, pool); + if (offset < 0) { + offset = pool.length; + var i = 0; + var len = s.length; + for (; i < len; ++i) { + pool.push(s[i]); + } + } + return offset; + } + function makeNameTable(names, ltag) { + var nameID; + var nameIDs = [ + ]; + var namesWithNumericKeys = { + }; + var nameTableIds = reverseDict(nameTableNames); + for (var key in names) { + var id = nameTableIds[key]; + if (id === undefined) { + id = key; + } + nameID = parseInt(id); + if (isNaN(nameID)) { + throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.'); + } + namesWithNumericKeys[nameID] = names[key]; + nameIDs.push(nameID); + } + var macLanguageIds = reverseDict(macLanguages); + var windowsLanguageIds = reverseDict(windowsLanguages); + var nameRecords = [ + ]; + var stringPool = [ + ]; + for (var i = 0; i < nameIDs.length; i++) { + nameID = nameIDs[i]; + var translations = namesWithNumericKeys[nameID]; + for (var lang in translations) { + var text = translations[lang]; + // For MacOS, we try to emit the name in the form that was introduced + // in the initial version of the TrueType spec (in the late 1980s). + // However, this can fail for various reasons: the requested BCP 47 + // language code might not have an old-style Mac equivalent; + // we might not have a codec for the needed character encoding; + // or the name might contain characters that cannot be expressed + // in the old-style Macintosh encoding. In case of failure, we emit + // the name in a more modern fashion (Unicode encoding with BCP 47 + // language tags) that is recognized by MacOS 10.5, released in 2009. + // If fonts were only read by operating systems, we could simply + // emit all names in the modern form; this would be much easier. + // However, there are many applications and libraries that read + // 'name' tables directly, and these will usually only recognize + // the ancient form (silently skipping the unrecognized names). + var macPlatform = 1; // Macintosh + var macLanguage = macLanguageIds[lang]; + var macScript = macLanguageToScript[macLanguage]; + var macEncoding = getEncoding(macPlatform, macScript, macLanguage); + var macName = encode.MACSTRING(text, macEncoding); + if (macName === undefined) { + macPlatform = 0; // Unicode + macLanguage = ltag.indexOf(lang); + if (macLanguage < 0) { + macLanguage = ltag.length; + ltag.push(lang); + } + macScript = 4; // Unicode 2.0 and later + macName = encode.UTF16(text); + } + var macNameOffset = addStringToPool(macName, stringPool); + nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, nameID, macName.length, macNameOffset)); + var winLanguage = windowsLanguageIds[lang]; + if (winLanguage !== undefined) { + var winName = encode.UTF16(text); + var winNameOffset = addStringToPool(winName, stringPool); + nameRecords.push(makeNameRecord(3, 1, winLanguage, nameID, winName.length, winNameOffset)); + } + } + } + nameRecords.sort(function (a, b) { + return a.platformID - b.platformID || a.encodingID - b.encodingID || a.languageID - b.languageID || a.nameID - b.nameID; + }); + var t = new table.Table('name', [ + { + name: 'format', + type: 'USHORT', + value: 0 + }, + { + name: 'count', + type: 'USHORT', + value: nameRecords.length + }, + { + name: 'stringOffset', + type: 'USHORT', + value: 6 + nameRecords.length * 12 + } + ]); + for (var r = 0; r < nameRecords.length; r++) { + t.fields.push({ + name: 'record_' + r, + type: 'RECORD', + value: nameRecords[r] + }); + } + t.fields.push({ + name: 'strings', + type: 'LITERAL', + value: stringPool + }); + return t; + } + var _name = { + parse: parseNameTable, + make: makeNameTable + }; + // The `OS/2` table contains metrics required in OpenType fonts. + var unicodeRanges = [ + { + begin: 0, + end: 127 + }, + // Basic Latin + { + begin: 128, + end: 255 + }, + // Latin-1 Supplement + { + begin: 256, + end: 383 + }, + // Latin Extended-A + { + begin: 384, + end: 591 + }, + // Latin Extended-B + { + begin: 592, + end: 687 + }, + // IPA Extensions + { + begin: 688, + end: 767 + }, + // Spacing Modifier Letters + { + begin: 768, + end: 879 + }, + // Combining Diacritical Marks + { + begin: 880, + end: 1023 + }, + // Greek and Coptic + { + begin: 11392, + end: 11519 + }, + // Coptic + { + begin: 1024, + end: 1279 + }, + // Cyrillic + { + begin: 1328, + end: 1423 + }, + // Armenian + { + begin: 1424, + end: 1535 + }, + // Hebrew + { + begin: 42240, + end: 42559 + }, + // Vai + { + begin: 1536, + end: 1791 + }, + // Arabic + { + begin: 1984, + end: 2047 + }, + // NKo + { + begin: 2304, + end: 2431 + }, + // Devanagari + { + begin: 2432, + end: 2559 + }, + // Bengali + { + begin: 2560, + end: 2687 + }, + // Gurmukhi + { + begin: 2688, + end: 2815 + }, + // Gujarati + { + begin: 2816, + end: 2943 + }, + // Oriya + { + begin: 2944, + end: 3071 + }, + // Tamil + { + begin: 3072, + end: 3199 + }, + // Telugu + { + begin: 3200, + end: 3327 + }, + // Kannada + { + begin: 3328, + end: 3455 + }, + // Malayalam + { + begin: 3584, + end: 3711 + }, + // Thai + { + begin: 3712, + end: 3839 + }, + // Lao + { + begin: 4256, + end: 4351 + }, + // Georgian + { + begin: 6912, + end: 7039 + }, + // Balinese + { + begin: 4352, + end: 4607 + }, + // Hangul Jamo + { + begin: 7680, + end: 7935 + }, + // Latin Extended Additional + { + begin: 7936, + end: 8191 + }, + // Greek Extended + { + begin: 8192, + end: 8303 + }, + // General Punctuation + { + begin: 8304, + end: 8351 + }, + // Superscripts And Subscripts + { + begin: 8352, + end: 8399 + }, + // Currency Symbol + { + begin: 8400, + end: 8447 + }, + // Combining Diacritical Marks For Symbols + { + begin: 8448, + end: 8527 + }, + // Letterlike Symbols + { + begin: 8528, + end: 8591 + }, + // Number Forms + { + begin: 8592, + end: 8703 + }, + // Arrows + { + begin: 8704, + end: 8959 + }, + // Mathematical Operators + { + begin: 8960, + end: 9215 + }, + // Miscellaneous Technical + { + begin: 9216, + end: 9279 + }, + // Control Pictures + { + begin: 9280, + end: 9311 + }, + // Optical Character Recognition + { + begin: 9312, + end: 9471 + }, + // Enclosed Alphanumerics + { + begin: 9472, + end: 9599 + }, + // Box Drawing + { + begin: 9600, + end: 9631 + }, + // Block Elements + { + begin: 9632, + end: 9727 + }, + // Geometric Shapes + { + begin: 9728, + end: 9983 + }, + // Miscellaneous Symbols + { + begin: 9984, + end: 10175 + }, + // Dingbats + { + begin: 12288, + end: 12351 + }, + // CJK Symbols And Punctuation + { + begin: 12352, + end: 12447 + }, + // Hiragana + { + begin: 12448, + end: 12543 + }, + // Katakana + { + begin: 12544, + end: 12591 + }, + // Bopomofo + { + begin: 12592, + end: 12687 + }, + // Hangul Compatibility Jamo + { + begin: 43072, + end: 43135 + }, + // Phags-pa + { + begin: 12800, + end: 13055 + }, + // Enclosed CJK Letters And Months + { + begin: 13056, + end: 13311 + }, + // CJK Compatibility + { + begin: 44032, + end: 55215 + }, + // Hangul Syllables + { + begin: 55296, + end: 57343 + }, + // Non-Plane 0 * + { + begin: 67840, + end: 67871 + }, + // Phoenicia + { + begin: 19968, + end: 40959 + }, + // CJK Unified Ideographs + { + begin: 57344, + end: 63743 + }, + // Private Use Area (plane 0) + { + begin: 12736, + end: 12783 + }, + // CJK Strokes + { + begin: 64256, + end: 64335 + }, + // Alphabetic Presentation Forms + { + begin: 64336, + end: 65023 + }, + // Arabic Presentation Forms-A + { + begin: 65056, + end: 65071 + }, + // Combining Half Marks + { + begin: 65040, + end: 65055 + }, + // Vertical Forms + { + begin: 65104, + end: 65135 + }, + // Small Form Variants + { + begin: 65136, + end: 65279 + }, + // Arabic Presentation Forms-B + { + begin: 65280, + end: 65519 + }, + // Halfwidth And Fullwidth Forms + { + begin: 65520, + end: 65535 + }, + // Specials + { + begin: 3840, + end: 4095 + }, + // Tibetan + { + begin: 1792, + end: 1871 + }, + // Syriac + { + begin: 1920, + end: 1983 + }, + // Thaana + { + begin: 3456, + end: 3583 + }, + // Sinhala + { + begin: 4096, + end: 4255 + }, + // Myanmar + { + begin: 4608, + end: 4991 + }, + // Ethiopic + { + begin: 5024, + end: 5119 + }, + // Cherokee + { + begin: 5120, + end: 5759 + }, + // Unified Canadian Aboriginal Syllabics + { + begin: 5760, + end: 5791 + }, + // Ogham + { + begin: 5792, + end: 5887 + }, + // Runic + { + begin: 6016, + end: 6143 + }, + // Khmer + { + begin: 6144, + end: 6319 + }, + // Mongolian + { + begin: 10240, + end: 10495 + }, + // Braille Patterns + { + begin: 40960, + end: 42127 + }, + // Yi Syllables + { + begin: 5888, + end: 5919 + }, + // Tagalog + { + begin: 66304, + end: 66351 + }, + // Old Italic + { + begin: 66352, + end: 66383 + }, + // Gothic + { + begin: 66560, + end: 66639 + }, + // Deseret + { + begin: 118784, + end: 119039 + }, + // Byzantine Musical Symbols + { + begin: 119808, + end: 120831 + }, + // Mathematical Alphanumeric Symbols + { + begin: 1044480, + end: 1048573 + }, + // Private Use (plane 15) + { + begin: 65024, + end: 65039 + }, + // Variation Selectors + { + begin: 917504, + end: 917631 + }, + // Tags + { + begin: 6400, + end: 6479 + }, + // Limbu + { + begin: 6480, + end: 6527 + }, + // Tai Le + { + begin: 6528, + end: 6623 + }, + // New Tai Lue + { + begin: 6656, + end: 6687 + }, + // Buginese + { + begin: 11264, + end: 11359 + }, + // Glagolitic + { + begin: 11568, + end: 11647 + }, + // Tifinagh + { + begin: 19904, + end: 19967 + }, + // Yijing Hexagram Symbols + { + begin: 43008, + end: 43055 + }, + // Syloti Nagri + { + begin: 65536, + end: 65663 + }, + // Linear B Syllabary + { + begin: 65856, + end: 65935 + }, + // Ancient Greek Numbers + { + begin: 66432, + end: 66463 + }, + // Ugaritic + { + begin: 66464, + end: 66527 + }, + // Old Persian + { + begin: 66640, + end: 66687 + }, + // Shavian + { + begin: 66688, + end: 66735 + }, + // Osmanya + { + begin: 67584, + end: 67647 + }, + // Cypriot Syllabary + { + begin: 68096, + end: 68191 + }, + // Kharoshthi + { + begin: 119552, + end: 119647 + }, + // Tai Xuan Jing Symbols + { + begin: 73728, + end: 74751 + }, + // Cuneiform + { + begin: 119648, + end: 119679 + }, + // Counting Rod Numerals + { + begin: 7040, + end: 7103 + }, + // Sundanese + { + begin: 7168, + end: 7247 + }, + // Lepcha + { + begin: 7248, + end: 7295 + }, + // Ol Chiki + { + begin: 43136, + end: 43231 + }, + // Saurashtra + { + begin: 43264, + end: 43311 + }, + // Kayah Li + { + begin: 43312, + end: 43359 + }, + // Rejang + { + begin: 43520, + end: 43615 + }, + // Cham + { + begin: 65936, + end: 65999 + }, + // Ancient Symbols + { + begin: 66000, + end: 66047 + }, + // Phaistos Disc + { + begin: 66208, + end: 66271 + }, + // Carian + { + begin: 127024, + end: 127135 + } // Domino Tiles + + ]; + function getUnicodeRange(unicode) { + for (var i = 0; i < unicodeRanges.length; i += 1) { + var range = unicodeRanges[i]; + if (unicode >= range.begin && unicode < range.end) { + return i; + } + } + return - 1; + } // Parse the OS/2 and Windows metrics `OS/2` table + + function parseOS2Table(data, start) { + var os2 = { + }; + var p = new parse.Parser(data, start); + os2.version = p.parseUShort(); + os2.xAvgCharWidth = p.parseShort(); + os2.usWeightClass = p.parseUShort(); + os2.usWidthClass = p.parseUShort(); + os2.fsType = p.parseUShort(); + os2.ySubscriptXSize = p.parseShort(); + os2.ySubscriptYSize = p.parseShort(); + os2.ySubscriptXOffset = p.parseShort(); + os2.ySubscriptYOffset = p.parseShort(); + os2.ySuperscriptXSize = p.parseShort(); + os2.ySuperscriptYSize = p.parseShort(); + os2.ySuperscriptXOffset = p.parseShort(); + os2.ySuperscriptYOffset = p.parseShort(); + os2.yStrikeoutSize = p.parseShort(); + os2.yStrikeoutPosition = p.parseShort(); + os2.sFamilyClass = p.parseShort(); + os2.panose = [ + ]; + for (var i = 0; i < 10; i++) { + os2.panose[i] = p.parseByte(); + } + os2.ulUnicodeRange1 = p.parseULong(); + os2.ulUnicodeRange2 = p.parseULong(); + os2.ulUnicodeRange3 = p.parseULong(); + os2.ulUnicodeRange4 = p.parseULong(); + os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); + os2.fsSelection = p.parseUShort(); + os2.usFirstCharIndex = p.parseUShort(); + os2.usLastCharIndex = p.parseUShort(); + os2.sTypoAscender = p.parseShort(); + os2.sTypoDescender = p.parseShort(); + os2.sTypoLineGap = p.parseShort(); + os2.usWinAscent = p.parseUShort(); + os2.usWinDescent = p.parseUShort(); + if (os2.version >= 1) { + os2.ulCodePageRange1 = p.parseULong(); + os2.ulCodePageRange2 = p.parseULong(); + } + if (os2.version >= 2) { + os2.sxHeight = p.parseShort(); + os2.sCapHeight = p.parseShort(); + os2.usDefaultChar = p.parseUShort(); + os2.usBreakChar = p.parseUShort(); + os2.usMaxContent = p.parseUShort(); + } + return os2; + } + function makeOS2Table(options) { + return new table.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 + } + ], options); + } + var os2 = { + parse: parseOS2Table, + make: makeOS2Table, + unicodeRanges: unicodeRanges, + getUnicodeRange: getUnicodeRange + }; + // The `post` table stores additional PostScript information, such as glyph names. + // Parse the PostScript `post` table + function parsePostTable(data, start) { + var post = { + }; + var p = new parse.Parser(data, start); + post.version = p.parseVersion(); + post.italicAngle = p.parseFixed(); + post.underlinePosition = p.parseShort(); + post.underlineThickness = p.parseShort(); + post.isFixedPitch = p.parseULong(); + post.minMemType42 = p.parseULong(); + post.maxMemType42 = p.parseULong(); + post.minMemType1 = p.parseULong(); + post.maxMemType1 = p.parseULong(); + switch (post.version) { + case 1: + post.names = standardNames.slice(); + break; + case 2: + post.numberOfGlyphs = p.parseUShort(); + post.glyphNameIndex = new Array(post.numberOfGlyphs); + for (var i = 0; i < post.numberOfGlyphs; i++) { + post.glyphNameIndex[i] = p.parseUShort(); + } + post.names = [ + ]; + for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) { + if (post.glyphNameIndex[i$1] >= standardNames.length) { + var nameLength = p.parseChar(); + post.names.push(p.parseString(nameLength)); + } + } + break; + case 2.5: + post.numberOfGlyphs = p.parseUShort(); + post.offset = new Array(post.numberOfGlyphs); + for (var i$2 = 0; i$2 < post.numberOfGlyphs; i$2++) { + post.offset[i$2] = p.parseChar(); + } + break; + } + return post; + } + function makePostTable() { + return new table.Table('post', [ + { + name: 'version', + type: 'FIXED', + value: 196608 + }, + { + name: 'italicAngle', + type: 'FIXED', + value: 0 + }, + { + name: 'underlinePosition', + type: 'FWORD', + value: 0 + }, + { + name: 'underlineThickness', + type: 'FWORD', + value: 0 + }, + { + name: 'isFixedPitch', + type: 'ULONG', + value: 0 + }, + { + name: 'minMemType42', + type: 'ULONG', + value: 0 + }, + { + name: 'maxMemType42', + type: 'ULONG', + value: 0 + }, + { + name: 'minMemType1', + type: 'ULONG', + value: 0 + }, + { + name: 'maxMemType1', + type: 'ULONG', + value: 0 + } + ]); + } + var post = { + parse: parsePostTable, + make: makePostTable + }; + // The `GSUB` table contains ligatures, among other things. + var subtableParsers = new Array(9); // subtableParsers[0] is unused + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS + subtableParsers[1] = function parseLookup1() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + deltaGlyphId: this.parseUShort() + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + substitute: this.parseOffset16List() + }; + } + check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.'); + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS + subtableParsers[2] = function parseLookup2() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1'); + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + sequences: this.parseListOfLists() + }; + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS + subtableParsers[3] = function parseLookup3() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1'); + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + alternateSets: this.parseListOfLists() + }; + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS + subtableParsers[4] = function parseLookup4() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1'); + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + ligatureSets: this.parseListOfLists(function () { + return { + ligGlyph: this.parseUShort(), + components: this.parseUShortList(this.parseUShort() - 1) + }; + }) + }; + }; + var lookupRecordDesc = { + sequenceIndex: Parser.uShort, + lookupListIndex: Parser.uShort + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF + subtableParsers[5] = function parseLookup5() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + ruleSets: this.parseListOfLists(function () { + var glyphCount = this.parseUShort(); + var substCount = this.parseUShort(); + return { + input: this.parseUShortList(glyphCount - 1), + lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + classDef: this.parsePointer(Parser.classDef), + classSets: this.parseListOfLists(function () { + var glyphCount = this.parseUShort(); + var substCount = this.parseUShort(); + return { + classes: this.parseUShortList(glyphCount - 1), + lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + var glyphCount = this.parseUShort(); + var substCount = this.parseUShort(); + return { + substFormat: substFormat, + coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) + }; + } + check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.'); + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC + subtableParsers[6] = function parseLookup6() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + chainRuleSets: this.parseListOfLists(function () { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + backtrackClassDef: this.parsePointer(Parser.classDef), + inputClassDef: this.parsePointer(Parser.classDef), + lookaheadClassDef: this.parsePointer(Parser.classDef), + chainClassSet: this.parseListOfLists(function () { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + return { + substFormat: 3, + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + } + check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.'); + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES + subtableParsers[7] = function parseLookup7() { + // Extension Substitution subtable + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1'); + var extensionLookupType = this.parseUShort(); + var extensionParser = new Parser(this.data, this.offset + this.parseULong()); + return { + substFormat: 1, + lookupType: extensionLookupType, + extension: subtableParsers[extensionLookupType].call(extensionParser) + }; + }; + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS + subtableParsers[8] = function parseLookup8() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1'); + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + substitutes: this.parseUShortList() + }; + }; + // https://www.microsoft.com/typography/OTSPEC/gsub.htm + function parseGsubTable(data, start) { + start = start || 0; + var p = new Parser(data, start); + var tableVersion = p.parseVersion(1); + check.argument(tableVersion === 1 || tableVersion === 1.1, 'Unsupported GSUB table version.'); + if (tableVersion === 1) { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers) + }; + } else { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers), + variations: p.parseFeatureVariationsList() + }; + } + } // GSUB Writing ////////////////////////////////////////////// + + var subtableMakers = new Array(9); + subtableMakers[1] = function makeLookup1(subtable) { + if (subtable.substFormat === 1) { + return new table.Table('substitutionTable', [ + { + name: 'substFormat', + type: 'USHORT', + value: 1 + }, + { + name: 'coverage', + type: 'TABLE', + value: new table.Coverage(subtable.coverage) + }, + { + name: 'deltaGlyphID', + type: 'USHORT', + value: subtable.deltaGlyphId + } + ]); + } else { + return new table.Table('substitutionTable', [ + { + name: 'substFormat', + type: 'USHORT', + value: 2 + }, + { + name: 'coverage', + type: 'TABLE', + value: new table.Coverage(subtable.coverage) + } + ].concat(table.ushortList('substitute', subtable.substitute))); + } + check.fail('Lookup type 1 substFormat must be 1 or 2.'); + }; + subtableMakers[3] = function makeLookup3(subtable) { + check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.'); + return new table.Table('substitutionTable', [ + { + name: 'substFormat', + type: 'USHORT', + value: 1 + }, + { + name: 'coverage', + type: 'TABLE', + value: new table.Coverage(subtable.coverage) + } + ].concat(table.tableList('altSet', subtable.alternateSets, function (alternateSet) { + return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet)); + }))); + }; + subtableMakers[4] = function makeLookup4(subtable) { + check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.'); + return new table.Table('substitutionTable', [ + { + name: 'substFormat', + type: 'USHORT', + value: 1 + }, + { + name: 'coverage', + type: 'TABLE', + value: new table.Coverage(subtable.coverage) + } + ].concat(table.tableList('ligSet', subtable.ligatureSets, function (ligatureSet) { + return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function (ligature) { + return new table.Table('ligatureTable', [ + { + name: 'ligGlyph', + type: 'USHORT', + value: ligature.ligGlyph + } + ].concat(table.ushortList('component', ligature.components, ligature.components.length + 1))); + })); + }))); + }; + function makeGsubTable(gsub) { + return new table.Table('GSUB', [ + { + name: 'version', + type: 'ULONG', + value: 65536 + }, + { + name: 'scripts', + type: 'TABLE', + value: new table.ScriptList(gsub.scripts) + }, + { + name: 'features', + type: 'TABLE', + value: new table.FeatureList(gsub.features) + }, + { + name: 'lookups', + type: 'TABLE', + value: new table.LookupList(gsub.lookups, subtableMakers) + } + ]); + } + var gsub = { + parse: parseGsubTable, + make: makeGsubTable + }; + // The `GPOS` table contains kerning pairs, among other things. + // Parse the metadata `meta` table. + // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html + function parseMetaTable(data, start) { + var p = new parse.Parser(data, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, 'Unsupported META table version.'); + p.parseULong(); // flags - currently unused and set to 0 + p.parseULong(); // tableOffset + var numDataMaps = p.parseULong(); + var tags = { + }; + for (var i = 0; i < numDataMaps; i++) { + var tag = p.parseTag(); + var dataOffset = p.parseULong(); + var dataLength = p.parseULong(); + var text = decode.UTF8(data, start + dataOffset, dataLength); + tags[tag] = text; + } + return tags; + } + function makeMetaTable(tags) { + var numTags = Object.keys(tags).length; + var stringPool = ''; + var stringPoolOffset = 16 + numTags * 12; + var result = new table.Table('meta', [ + { + name: 'version', + type: 'ULONG', + value: 1 + }, + { + name: 'flags', + type: 'ULONG', + value: 0 + }, + { + name: 'offset', + type: 'ULONG', + value: stringPoolOffset + }, + { + name: 'numTags', + type: 'ULONG', + value: numTags + } + ]); + for (var tag in tags) { + var pos = stringPool.length; + stringPool += tags[tag]; + result.fields.push({ + name: 'tag ' + tag, + type: 'TAG', + value: tag + }); + result.fields.push({ + name: 'offset ' + tag, + type: 'ULONG', + value: stringPoolOffset + pos + }); + result.fields.push({ + name: 'length ' + tag, + type: 'ULONG', + value: tags[tag].length + }); + } + result.fields.push({ + name: 'stringPool', + type: 'CHARARRAY', + value: stringPool + }); + return result; + } + var meta = { + parse: parseMetaTable, + make: makeMetaTable + }; + // The `sfnt` wrapper provides organization for the tables in the font. + function log2(v) { + return Math.log(v) / Math.log(2) | 0; + } + function computeCheckSum(bytes) { + while (bytes.length % 4 !== 0) { + bytes.push(0); + } + var sum = 0; + for (var i = 0; i < bytes.length; i += 4) { + sum += (bytes[i] << 24) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3]; + } + sum %= Math.pow(2, 32); + return sum; + } + function makeTableRecord(tag, checkSum, offset, length) { + return new table.Record('Table Record', [ + { + name: 'tag', + type: 'TAG', + value: tag !== undefined ? tag : '' + }, + { + name: 'checkSum', + type: 'ULONG', + value: checkSum !== undefined ? checkSum : 0 + }, + { + name: 'offset', + type: 'ULONG', + value: offset !== undefined ? offset : 0 + }, + { + name: 'length', + type: 'ULONG', + value: length !== undefined ? length : 0 + } + ]); + } + function makeSfntTable(tables) { + var sfnt = new table.Table('sfnt', [ + { + name: 'version', + type: 'TAG', + value: 'OTTO' + }, + { + name: 'numTables', + type: 'USHORT', + value: 0 + }, + { + name: 'searchRange', + type: 'USHORT', + value: 0 + }, + { + name: 'entrySelector', + type: 'USHORT', + value: 0 + }, + { + name: 'rangeShift', + type: 'USHORT', + value: 0 + } + ]); + sfnt.tables = tables; + sfnt.numTables = tables.length; + var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); + sfnt.searchRange = 16 * highestPowerOf2; + sfnt.entrySelector = log2(highestPowerOf2); + sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; + var recordFields = [ + ]; + var tableFields = [ + ]; + var offset = sfnt.sizeOf() + makeTableRecord().sizeOf() * sfnt.numTables; + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({ + name: 'padding', + type: 'BYTE', + value: 0 + }); + } + for (var i = 0; i < tables.length; i += 1) { + var t = tables[i]; + check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.'); + var tableLength = t.sizeOf(); + var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength); + recordFields.push({ + name: tableRecord.tag + ' Table Record', + type: 'RECORD', + value: tableRecord + }); + tableFields.push({ + name: t.tableName + ' table', + type: 'RECORD', + value: t + }); + offset += tableLength; + check.argument(!isNaN(offset), 'Something went wrong calculating the offset.'); + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({ + name: 'padding', + type: 'BYTE', + value: 0 + }); + } + } // Table records need to be sorted alphabetically. + + recordFields.sort(function (r1, r2) { + if (r1.value.tag > r2.value.tag) { + return 1; + } else { + return - 1; + } + }); + sfnt.fields = sfnt.fields.concat(recordFields); + sfnt.fields = sfnt.fields.concat(tableFields); + return sfnt; + } // Get the metrics for a character. If the string has more than one character + // this function returns metrics for the first available character. + // You can provide optional fallback metrics if no characters are available. + + function metricsForChar(font, chars, notFoundMetrics) { + for (var i = 0; i < chars.length; i += 1) { + var glyphIndex = font.charToGlyphIndex(chars[i]); + if (glyphIndex > 0) { + var glyph = font.glyphs.get(glyphIndex); + return glyph.getMetrics(); + } + } + return notFoundMetrics; + } + function average(vs) { + var sum = 0; + for (var i = 0; i < vs.length; i += 1) { + sum += vs[i]; + } + return sum / vs.length; + } // Convert the font object to a SFNT data structure. + // This structure contains all the necessary tables and metadata to create a binary OTF file. + + function fontToSfntTable(font) { + var xMins = [ + ]; + var yMins = [ + ]; + var xMaxs = [ + ]; + var yMaxs = [ + ]; + var advanceWidths = [ + ]; + var leftSideBearings = [ + ]; + var rightSideBearings = [ + ]; + var firstCharIndex; + var lastCharIndex = 0; + var ulUnicodeRange1 = 0; + var ulUnicodeRange2 = 0; + var ulUnicodeRange3 = 0; + var ulUnicodeRange4 = 0; + for (var i = 0; i < font.glyphs.length; i += 1) { + var glyph = font.glyphs.get(i); + var unicode = glyph.unicode | 0; + if (isNaN(glyph.advanceWidth)) { + throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.'); + } + if (firstCharIndex > unicode || firstCharIndex === undefined) { + // ignore .notdef char + if (unicode > 0) { + firstCharIndex = unicode; + } + } + if (lastCharIndex < unicode) { + lastCharIndex = unicode; + } + var position = os2.getUnicodeRange(unicode); + if (position < 32) { + ulUnicodeRange1 |= 1 << position; + } else if (position < 64) { + ulUnicodeRange2 |= 1 << position - 32; + } else if (position < 96) { + ulUnicodeRange3 |= 1 << position - 64; + } else if (position < 123) { + ulUnicodeRange4 |= 1 << position - 96; + } else { + throw new Error('Unicode ranges bits > 123 are reserved for internal usage'); + } // Skip non-important characters. + + if (glyph.name === '.notdef') { + continue; + } + var metrics = glyph.getMetrics(); + xMins.push(metrics.xMin); + yMins.push(metrics.yMin); + xMaxs.push(metrics.xMax); + yMaxs.push(metrics.yMax); + leftSideBearings.push(metrics.leftSideBearing); + rightSideBearings.push(metrics.rightSideBearing); + advanceWidths.push(glyph.advanceWidth); + } + var globals = { + xMin: Math.min.apply(null, xMins), + yMin: Math.min.apply(null, yMins), + xMax: Math.max.apply(null, xMaxs), + yMax: Math.max.apply(null, yMaxs), + advanceWidthMax: Math.max.apply(null, advanceWidths), + advanceWidthAvg: average(advanceWidths), + minLeftSideBearing: Math.min.apply(null, leftSideBearings), + maxLeftSideBearing: Math.max.apply(null, leftSideBearings), + minRightSideBearing: Math.min.apply(null, rightSideBearings) + }; + globals.ascender = font.ascender; + globals.descender = font.descender; + var headTable = head.make({ + flags: 3, + // 00000011 (baseline for font at y=0; left sidebearing point at x=0) + unitsPerEm: font.unitsPerEm, + xMin: globals.xMin, + yMin: globals.yMin, + xMax: globals.xMax, + yMax: globals.yMax, + lowestRecPPEM: 3, + createdTimestamp: font.createdTimestamp + }); + var hheaTable = hhea.make({ + ascender: globals.ascender, + descender: globals.descender, + advanceWidthMax: globals.advanceWidthMax, + minLeftSideBearing: globals.minLeftSideBearing, + minRightSideBearing: globals.minRightSideBearing, + xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), + numberOfHMetrics: font.glyphs.length + }); + var maxpTable = maxp.make(font.glyphs.length); + var os2Table = os2.make({ + xAvgCharWidth: Math.round(globals.advanceWidthAvg), + usWeightClass: font.tables.os2.usWeightClass, + usWidthClass: font.tables.os2.usWidthClass, + usFirstCharIndex: firstCharIndex, + usLastCharIndex: lastCharIndex, + ulUnicodeRange1: ulUnicodeRange1, + ulUnicodeRange2: ulUnicodeRange2, + ulUnicodeRange3: ulUnicodeRange3, + ulUnicodeRange4: ulUnicodeRange4, + fsSelection: font.tables.os2.fsSelection, + // REGULAR + // See http://typophile.com/node/13081 for more info on vertical metrics. + // We get metrics for typical characters (such as "x" for xHeight). + // We provide some fallback characters if characters are unavailable: their + // ordering was chosen experimentally. + sTypoAscender: globals.ascender, + sTypoDescender: globals.descender, + sTypoLineGap: 0, + usWinAscent: globals.yMax, + usWinDescent: Math.abs(globals.yMin), + ulCodePageRange1: 1, + // FIXME: hard-code Latin 1 support for now + sxHeight: metricsForChar(font, 'xyvw', { + yMax: Math.round(globals.ascender / 2) + }).yMax, + sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax, + usDefaultChar: font.hasChar(' ') ? 32 : 0, + // Use space as the default character, if available. + usBreakChar: font.hasChar(' ') ? 32 : 0 // Use space as the break character, if available. + }); + var hmtxTable = hmtx.make(font.glyphs); + var cmapTable = cmap.make(font.glyphs); + var englishFamilyName = font.getEnglishName('fontFamily'); + var englishStyleName = font.getEnglishName('fontSubfamily'); + var englishFullName = englishFamilyName + ' ' + englishStyleName; + var postScriptName = font.getEnglishName('postScriptName'); + if (!postScriptName) { + postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName; + } + var names = { + }; + for (var n in font.names) { + names[n] = font.names[n]; + } + if (!names.uniqueID) { + names.uniqueID = { + en: font.getEnglishName('manufacturer') + ':' + englishFullName + }; + } + if (!names.postScriptName) { + names.postScriptName = { + en: postScriptName + }; + } + if (!names.preferredFamily) { + names.preferredFamily = font.names.fontFamily; + } + if (!names.preferredSubfamily) { + names.preferredSubfamily = font.names.fontSubfamily; + } + var languageTags = [ + ]; + var nameTable = _name.make(names, languageTags); + var ltagTable = languageTags.length > 0 ? ltag.make(languageTags) : undefined; + var postTable = post.make(); + var cffTable = cff.make(font.glyphs, { + version: font.getEnglishName('version'), + fullName: englishFullName, + familyName: englishFamilyName, + weightName: englishStyleName, + postScriptName: postScriptName, + unitsPerEm: font.unitsPerEm, + fontBBox: [ + 0, + globals.yMin, + globals.ascender, + globals.advanceWidthMax + ] + }); + var metaTable = font.metas && Object.keys(font.metas).length > 0 ? meta.make(font.metas) : undefined; + // The order does not matter because makeSfntTable() will sort them. + var tables = [ + headTable, + hheaTable, + maxpTable, + os2Table, + nameTable, + cmapTable, + postTable, + cffTable, + hmtxTable + ]; + if (ltagTable) { + tables.push(ltagTable); + } // Optional tables + + if (font.tables.gsub) { + tables.push(gsub.make(font.tables.gsub)); + } + if (metaTable) { + tables.push(metaTable); + } + var sfntTable = makeSfntTable(tables); + // Compute the font's checkSum and store it in head.checkSumAdjustment. + var bytes = sfntTable.encode(); + var checkSum = computeCheckSum(bytes); + var tableFields = sfntTable.fields; + var checkSumAdjusted = false; + for (var i$1 = 0; i$1 < tableFields.length; i$1 += 1) { + if (tableFields[i$1].name === 'head table') { + tableFields[i$1].value.checkSumAdjustment = 2981146554 - checkSum; + checkSumAdjusted = true; + break; + } + } + if (!checkSumAdjusted) { + throw new Error('Could not find head table with checkSum to adjust.'); + } + return sfntTable; + } + var sfnt = { + make: makeSfntTable, + fontToTable: fontToSfntTable, + computeCheckSum: computeCheckSum + }; + // The Layout object is the prototype of Substitution objects, and provides + function searchTag(arr, tag) { + /* jshint bitwise: false */ + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + var val = arr[imid].tag; + if (val === tag) { + return imid; + } else if (val < tag) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } // Not found: return -1-insertion point + + return - imin - 1; + } + function binSearch(arr, value) { + /* jshint bitwise: false */ + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + var val = arr[imid]; + if (val === value) { + return imid; + } else if (val < value) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } // Not found: return -1-insertion point + + return - imin - 1; + } // binary search in a list of ranges (coverage, class definition) + + function searchRange(ranges, value) { + // jshint bitwise: false + var range; + var imin = 0; + var imax = ranges.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + range = ranges[imid]; + var start = range.start; + if (start === value) { + return range; + } else if (start < value) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + if (imin > 0) { + range = ranges[imin - 1]; + if (value > range.end) { + return 0; + } + return range; + } + } /** + * @exports opentype.Layout + * @class + */ + + function Layout(font, tableName) { + this.font = font; + this.tableName = tableName; + } + Layout.prototype = { + /** + * Binary search an object by "tag" property + * @instance + * @function searchTag + * @memberof opentype.Layout + * @param {Array} arr + * @param {string} tag + * @return {number} + */ + searchTag: searchTag, + /** + * Binary search in a list of numbers + * @instance + * @function binSearch + * @memberof opentype.Layout + * @param {Array} arr + * @param {number} value + * @return {number} + */ + binSearch: binSearch, + /** + * Get or create the Layout table (GSUB, GPOS etc). + * @param {boolean} create - Whether to create a new one. + * @return {Object} The GSUB or GPOS table. + */ + getTable: function (create) { + var layout = this.font.tables[this.tableName]; + if (!layout && create) { + layout = this.font.tables[this.tableName] = this.createDefaultTable(); + } + return layout; + }, + /** + * Returns all scripts in the substitution table. + * @instance + * @return {Array} + */ + getScriptNames: function () { + var layout = this.getTable(); + if (!layout) { + return []; + } + return layout.scripts.map(function (script) { + return script.tag; + }); + }, + /** + * Returns the best bet for a script name. + * Returns 'DFLT' if it exists. + * If not, returns 'latn' if it exists. + * If neither exist, returns undefined. + */ + getDefaultScriptName: function () { + var layout = this.getTable(); + if (!layout) { + return; + } + var hasLatn = false; + for (var i = 0; i < layout.scripts.length; i++) { + var name = layout.scripts[i].tag; + if (name === 'DFLT') { + return name; + } + if (name === 'latn') { + hasLatn = true; + } + } + if (hasLatn) { + return 'latn'; + } + }, + /** + * Returns all LangSysRecords in the given script. + * @instance + * @param {string} [script='DFLT'] + * @param {boolean} create - forces the creation of this script table if it doesn't exist. + * @return {Object} An object with tag and script properties. + */ + getScriptTable: function (script, create) { + var layout = this.getTable(create); + if (layout) { + script = script || 'DFLT'; + var scripts = layout.scripts; + var pos = searchTag(layout.scripts, script); + if (pos >= 0) { + return scripts[pos].script; + } else if (create) { + var scr = { + tag: script, + script: { + defaultLangSys: { + reserved: 0, + reqFeatureIndex: 65535, + featureIndexes: [ + ] + }, + langSysRecords: [ + ] + } + }; + scripts.splice( - 1 - pos, 0, scr); + return scr.script; + } + } + }, + /** + * Returns a language system table + * @instance + * @param {string} [script='DFLT'] + * @param {string} [language='dlft'] + * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist. + * @return {Object} + */ + getLangSysTable: function (script, language, create) { + var scriptTable = this.getScriptTable(script, create); + if (scriptTable) { + if (!language || language === 'dflt' || language === 'DFLT') { + return scriptTable.defaultLangSys; + } + var pos = searchTag(scriptTable.langSysRecords, language); + if (pos >= 0) { + return scriptTable.langSysRecords[pos].langSys; + } else if (create) { + var langSysRecord = { + tag: language, + langSys: { + reserved: 0, + reqFeatureIndex: 65535, + featureIndexes: [ + ] + } + }; + scriptTable.langSysRecords.splice( - 1 - pos, 0, langSysRecord); + return langSysRecord.langSys; + } + } + }, + /** + * Get a specific feature table. + * @instance + * @param {string} [script='DFLT'] + * @param {string} [language='dlft'] + * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm + * @param {boolean} create - forces the creation of the feature table if it doesn't exist. + * @return {Object} + */ + getFeatureTable: function (script, language, feature, create) { + var langSysTable = this.getLangSysTable(script, language, create); + if (langSysTable) { + var featureRecord; + var featIndexes = langSysTable.featureIndexes; + var allFeatures = this.font.tables[this.tableName].features; + // The FeatureIndex array of indices is in arbitrary order, + // even if allFeatures is sorted alphabetically by feature tag. + for (var i = 0; i < featIndexes.length; i++) { + featureRecord = allFeatures[featIndexes[i]]; + if (featureRecord.tag === feature) { + return featureRecord.feature; + } + } + if (create) { + var index = allFeatures.length; + // Automatic ordering of features would require to shift feature indexes in the script list. + check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.'); + featureRecord = { + tag: feature, + feature: { + params: 0, + lookupListIndexes: [ + ] + } + }; + allFeatures.push(featureRecord); + featIndexes.push(index); + return featureRecord.feature; + } + } + }, + /** + * Get the lookup tables of a given type for a script/language/feature. + * @instance + * @param {string} [script='DFLT'] + * @param {string} [language='dlft'] + * @param {string} feature - 4-letter feature code + * @param {number} lookupType - 1 to 9 + * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables. + * @return {Object[]} + */ + getLookupTables: function (script, language, feature, lookupType, create) { + var featureTable = this.getFeatureTable(script, language, feature, create); + var tables = [ + ]; + if (featureTable) { + var lookupTable; + var lookupListIndexes = featureTable.lookupListIndexes; + var allLookups = this.font.tables[this.tableName].lookups; + // lookupListIndexes are in no particular order, so use naive search. + for (var i = 0; i < lookupListIndexes.length; i++) { + lookupTable = allLookups[lookupListIndexes[i]]; + if (lookupTable.lookupType === lookupType) { + tables.push(lookupTable); + } + } + if (tables.length === 0 && create) { + lookupTable = { + lookupType: lookupType, + lookupFlag: 0, + subtables: [ + ], + markFilteringSet: undefined + }; + var index = allLookups.length; + allLookups.push(lookupTable); + lookupListIndexes.push(index); + return [lookupTable]; + } + } + return tables; + }, + /** + * Find a glyph in a class definition table + * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table + * @param {object} classDefTable - an OpenType Layout class definition table + * @param {number} glyphIndex - the index of the glyph to find + * @returns {number} -1 if not found + */ + getGlyphClass: function (classDefTable, glyphIndex) { + switch (classDefTable.format) { + case 1: + if (classDefTable.startGlyph <= glyphIndex && glyphIndex < classDefTable.startGlyph + classDefTable.classes.length) { + return classDefTable.classes[glyphIndex - classDefTable.startGlyph]; + } + return 0; + case 2: + var range = searchRange(classDefTable.ranges, glyphIndex); + return range ? range.classId : 0; + } + }, + /** + * Find a glyph in a coverage table + * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-table + * @param {object} coverageTable - an OpenType Layout coverage table + * @param {number} glyphIndex - the index of the glyph to find + * @returns {number} -1 if not found + */ + getCoverageIndex: function (coverageTable, glyphIndex) { + switch (coverageTable.format) { + case 1: + var index = binSearch(coverageTable.glyphs, glyphIndex); + return index >= 0 ? index : - 1; + case 2: + var range = searchRange(coverageTable.ranges, glyphIndex); + return range ? range.index + glyphIndex - range.start : - 1; + } + }, + /** + * Returns the list of glyph indexes of a coverage table. + * Format 1: the list is stored raw + * Format 2: compact list as range records. + * @instance + * @param {Object} coverageTable + * @return {Array} + */ + expandCoverage: function (coverageTable) { + if (coverageTable.format === 1) { + return coverageTable.glyphs; + } else { + var glyphs = [ + ]; + var ranges = coverageTable.ranges; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + var start = range.start; + var end = range.end; + for (var j = start; j <= end; j++) { + glyphs.push(j); + } + } + return glyphs; + } + } + }; + // The Position object provides utility methods to manipulate + /** + * @exports opentype.Position + * @class + * @extends opentype.Layout + * @param {opentype.Font} + * @constructor + */ + function Position(font) { + Layout.call(this, font, 'gpos'); + } + Position.prototype = Layout.prototype; + /** + * Init some data for faster and easier access later. + */ + Position.prototype.init = function () { + var script = this.getDefaultScriptName(); + this.defaultKerningTables = this.getKerningTables(script); + }; + /** + * Find a glyph pair in a list of lookup tables of type 2 and retrieve the xAdvance kerning value. + * + * @param {integer} leftIndex - left glyph index + * @param {integer} rightIndex - right glyph index + * @returns {integer} + */ + Position.prototype.getKerningValue = function (kerningLookups, leftIndex, rightIndex) { + var this$1 = this; + for (var i = 0; i < kerningLookups.length; i++) { + var subtables = kerningLookups[i].subtables; + for (var j = 0; j < subtables.length; j++) { + var subtable = subtables[j]; + var covIndex = this$1.getCoverageIndex(subtable.coverage, leftIndex); + if (covIndex < 0) { + continue; + } + switch (subtable.posFormat) { + case 1: + // Search Pair Adjustment Positioning Format 1 + var pairSet = subtable.pairSets[covIndex]; + for (var k = 0; k < pairSet.length; k++) { + var pair = pairSet[k]; + if (pair.secondGlyph === rightIndex) { + return pair.value1 && pair.value1.xAdvance || 0; + } + } + break; + // left glyph found, not right glyph - try next subtable + case 2: + // Search Pair Adjustment Positioning Format 2 + var class1 = this$1.getGlyphClass(subtable.classDef1, leftIndex); + var class2 = this$1.getGlyphClass(subtable.classDef2, rightIndex); + var pair$1 = subtable.classRecords[class1][class2]; + return pair$1.value1 && pair$1.value1.xAdvance || 0; + } + } + } + return 0; + }; + /** + * List all kerning lookup tables. + * + * @param {string} [script='DFLT'] - use font.position.getDefaultScriptName() for a better default value + * @param {string} [language='dflt'] + * @return {object[]} The list of kerning lookup tables (may be empty), or undefined if there is no GPOS table (and we should use the kern table) + */ + Position.prototype.getKerningTables = function (script, language) { + if (this.font.tables.gpos) { + return this.getLookupTables(script, language, 'kern', 2); + } + }; + // The Substitution object provides utility methods to manipulate + /** + * @exports opentype.Substitution + * @class + * @extends opentype.Layout + * @param {opentype.Font} + * @constructor + */ + function Substitution(font) { + Layout.call(this, font, 'gsub'); + } // Check if 2 arrays of primitives are equal. + + function arraysEqual(ar1, ar2) { + var n = ar1.length; + if (n !== ar2.length) { + return false; + } + for (var i = 0; i < n; i++) { + if (ar1[i] !== ar2[i]) { + return false; + } + } + return true; + } // Find the first subtable of a lookup table in a particular format. + + function getSubstFormat(lookupTable, format, defaultSubtable) { + var subtables = lookupTable.subtables; + for (var i = 0; i < subtables.length; i++) { + var subtable = subtables[i]; + if (subtable.substFormat === format) { + return subtable; + } + } + if (defaultSubtable) { + subtables.push(defaultSubtable); + return defaultSubtable; + } + return undefined; + } + Substitution.prototype = Layout.prototype; + /** + * Create a default GSUB table. + * @return {Object} gsub - The GSUB table. + */ + Substitution.prototype.createDefaultTable = function () { + // Generate a default empty GSUB table with just a DFLT script and dflt lang sys. + return { + version: 1, + scripts: [ + { + tag: 'DFLT', + script: { + defaultLangSys: { + reserved: 0, + reqFeatureIndex: 65535, + featureIndexes: [ + ] + }, + langSysRecords: [ + ] + } + } + ], + features: [ + ], + lookups: [ + ] + }; + }; + /** + * List all single substitutions (lookup type 1) for a given script, language, and feature. + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + * @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...) + * @return {Array} substitutions - The list of substitutions. + */ + Substitution.prototype.getSingle = function (feature, script, language) { + var this$1 = this; + var substitutions = [ + ]; + var lookupTables = this.getLookupTables(script, language, feature, 1); + for (var idx = 0; idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0; i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this$1.expandCoverage(subtable.coverage); + var j = void 0; + if (subtable.substFormat === 1) { + var delta = subtable.deltaGlyphId; + for (j = 0; j < glyphs.length; j++) { + var glyph = glyphs[j]; + substitutions.push({ + sub: glyph, + by: glyph + delta + }); + } + } else { + var substitute = subtable.substitute; + for (j = 0; j < glyphs.length; j++) { + substitutions.push({ + sub: glyphs[j], + by: substitute[j] + }); + } + } + } + } + return substitutions; + }; + /** + * List all alternates (lookup type 3) for a given script, language, and feature. + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + * @param {string} feature - 4-character feature name ('aalt', 'salt'...) + * @return {Array} alternates - The list of alternates + */ + Substitution.prototype.getAlternates = function (feature, script, language) { + var this$1 = this; + var alternates = [ + ]; + var lookupTables = this.getLookupTables(script, language, feature, 3); + for (var idx = 0; idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0; i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this$1.expandCoverage(subtable.coverage); + var alternateSets = subtable.alternateSets; + for (var j = 0; j < glyphs.length; j++) { + alternates.push({ + sub: glyphs[j], + by: alternateSets[j] + }); + } + } + } + return alternates; + }; + /** + * List all ligatures (lookup type 4) for a given script, language, and feature. + * The result is an array of ligature objects like { sub: [ids], by: id } + * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + * @return {Array} ligatures - The list of ligatures. + */ + Substitution.prototype.getLigatures = function (feature, script, language) { + var this$1 = this; + var ligatures = [ + ]; + var lookupTables = this.getLookupTables(script, language, feature, 4); + for (var idx = 0; idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0; i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this$1.expandCoverage(subtable.coverage); + var ligatureSets = subtable.ligatureSets; + for (var j = 0; j < glyphs.length; j++) { + var startGlyph = glyphs[j]; + var ligSet = ligatureSets[j]; + for (var k = 0; k < ligSet.length; k++) { + var lig = ligSet[k]; + ligatures.push({ + sub: [ + startGlyph + ].concat(lig.components), + by: lig.ligGlyph + }); + } + } + } + } + return ligatures; + }; + /** + * Add or modify a single substitution (lookup type 1) + * Format 2, more flexible, is always used. + * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) + * @param {Object} substitution - { sub: id, delta: number } for format 1 or { sub: id, by: id } for format 2. + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + */ + Substitution.prototype.addSingle = function (feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 1, true) [0]; + var subtable = getSubstFormat(lookupTable, 2, { + // lookup type 1 subtable, format 2, coverage format 1 + substFormat: 2, + coverage: { + format: 1, + glyphs: [ + ] + }, + substitute: [ + ] + }); + check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = - 1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.substitute.splice(pos, 0, 0); + } + subtable.substitute[pos] = substitution.by; + }; + /** + * Add or modify an alternate substitution (lookup type 1) + * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) + * @param {Object} substitution - { sub: id, by: [ids] } + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + */ + Substitution.prototype.addAlternate = function (feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 3, true) [0]; + var subtable = getSubstFormat(lookupTable, 1, { + // lookup type 3 subtable, format 1, coverage format 1 + substFormat: 1, + coverage: { + format: 1, + glyphs: [ + ] + }, + alternateSets: [ + ] + }); + check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = - 1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.alternateSets.splice(pos, 0, 0); + } + subtable.alternateSets[pos] = substitution.by; + }; + /** + * Add a ligature (lookup type 4) + * Ligatures with more components must be stored ahead of those with fewer components in order to be found + * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) + * @param {Object} ligature - { sub: [ids], by: id } + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + */ + Substitution.prototype.addLigature = function (feature, ligature, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 4, true) [0]; + var subtable = lookupTable.subtables[0]; + if (!subtable) { + subtable = { + // lookup type 4 subtable, format 1, coverage format 1 + substFormat: 1, + coverage: { + format: 1, + glyphs: [ + ] + }, + ligatureSets: [ + ] + }; + lookupTable.subtables[0] = subtable; + } + check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); + var coverageGlyph = ligature.sub[0]; + var ligComponents = ligature.sub.slice(1); + var ligatureTable = { + ligGlyph: ligature.by, + components: ligComponents + }; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos >= 0) { + // ligatureSet already exists + var ligatureSet = subtable.ligatureSets[pos]; + for (var i = 0; i < ligatureSet.length; i++) { + // If ligature already exists, return. + if (arraysEqual(ligatureSet[i].components, ligComponents)) { + return; + } + } // ligature does not exist: add it. + + ligatureSet.push(ligatureTable); + } else { + // Create a new ligatureSet and add coverage for the first glyph. + pos = - 1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.ligatureSets.splice(pos, 0, [ + ligatureTable + ]); + } + }; + /** + * List all feature data for a given script and language. + * @param {string} feature - 4-letter feature name + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + * @return {Array} substitutions - The list of substitutions. + */ + Substitution.prototype.getFeature = function (feature, script, language) { + if (/ss\d\d/.test(feature)) { + // ss01 - ss20 + return this.getSingle(feature, script, language); + } + switch (feature) { + case 'aalt': + case 'salt': + return this.getSingle(feature, script, language).concat(this.getAlternates(feature, script, language)); + case 'dlig': + case 'liga': + case 'rlig': + return this.getLigatures(feature, script, language); + } + return undefined; + }; + /** + * Add a substitution to a feature for a given script and language. + * @param {string} feature - 4-letter feature name + * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] }) + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + */ + Substitution.prototype.add = function (feature, sub, script, language) { + if (/ss\d\d/.test(feature)) { + // ss01 - ss20 + return this.addSingle(feature, sub, script, language); + } + switch (feature) { + case 'aalt': + case 'salt': + if (typeof sub.by === 'number') { + return this.addSingle(feature, sub, script, language); + } + return this.addAlternate(feature, sub, script, language); + case 'dlig': + case 'liga': + case 'rlig': + return this.addLigature(feature, sub, script, language); + } + return undefined; + }; + function isBrowser() { + return typeof window !== 'undefined'; + } + function nodeBufferToArrayBuffer(buffer) { + var ab = new ArrayBuffer(buffer.length); + var view = new Uint8Array(ab); + for (var i = 0; i < buffer.length; ++i) { + view[i] = buffer[i]; + } + return ab; + } + function arrayBufferToNodeBuffer(ab) { + var buffer = new Buffer(ab.byteLength); + var view = new Uint8Array(ab); + for (var i = 0; i < buffer.length; ++i) { + buffer[i] = view[i]; + } + return buffer; + } + function checkArgument(expression, message) { + if (!expression) { + throw message; + } + } // The `glyf` table describes the glyphs in TrueType outline format. + // Parse the coordinate data for a glyph. + + function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { + var v; + if ((flag & shortVectorBitMask) > 0) { + // The coordinate is 1 byte long. + v = p.parseByte(); + // The `same` bit is re-used for short values to signify the sign of the value. + if ((flag & sameBitMask) === 0) { + v = - v; + } + v = previousValue + v; + } else { + // The coordinate is 2 bytes long. + // If the `same` bit is set, the coordinate is the same as the previous coordinate. + if ((flag & sameBitMask) > 0) { + v = previousValue; + } else { + // Parse the coordinate as a signed 16-bit delta value. + v = previousValue + p.parseShort(); + } + } + return v; + } // Parse a TrueType glyph. + + function parseGlyph(glyph, data, start) { + var p = new parse.Parser(data, start); + glyph.numberOfContours = p.parseShort(); + glyph._xMin = p.parseShort(); + glyph._yMin = p.parseShort(); + glyph._xMax = p.parseShort(); + glyph._yMax = p.parseShort(); + var flags; + var flag; + if (glyph.numberOfContours > 0) { + // This glyph is not a composite. + var endPointIndices = glyph.endPointIndices = [ + ]; + for (var i = 0; i < glyph.numberOfContours; i += 1) { + endPointIndices.push(p.parseUShort()); + } + glyph.instructionLength = p.parseUShort(); + glyph.instructions = [ + ]; + for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) { + glyph.instructions.push(p.parseByte()); + } + var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; + flags = [ + ]; + for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) { + flag = p.parseByte(); + flags.push(flag); + // If bit 3 is set, we repeat this flag n times, where n is the next byte. + if ((flag & 8) > 0) { + var repeatCount = p.parseByte(); + for (var j = 0; j < repeatCount; j += 1) { + flags.push(flag); + i$2 += 1; + } + } + } + check.argument(flags.length === numberOfCoordinates, 'Bad flags.'); + if (endPointIndices.length > 0) { + var points = [ + ]; + var point; + // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. + if (numberOfCoordinates > 0) { + for (var i$3 = 0; i$3 < numberOfCoordinates; i$3 += 1) { + flag = flags[i$3]; + point = { + }; + point.onCurve = !!(flag & 1); + point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0; + points.push(point); + } + var px = 0; + for (var i$4 = 0; i$4 < numberOfCoordinates; i$4 += 1) { + flag = flags[i$4]; + point = points[i$4]; + point.x = parseGlyphCoordinate(p, flag, px, 2, 16); + px = point.x; + } + var py = 0; + for (var i$5 = 0; i$5 < numberOfCoordinates; i$5 += 1) { + flag = flags[i$5]; + point = points[i$5]; + point.y = parseGlyphCoordinate(p, flag, py, 4, 32); + py = point.y; + } + } + glyph.points = points; + } else { + glyph.points = [ + ]; + } + } else if (glyph.numberOfContours === 0) { + glyph.points = [ + ]; + } else { + glyph.isComposite = true; + glyph.points = [ + ]; + glyph.components = [ + ]; + var moreComponents = true; + while (moreComponents) { + flags = p.parseUShort(); + var component = { + glyphIndex: p.parseUShort(), + xScale: 1, + scale01: 0, + scale10: 0, + yScale: 1, + dx: 0, + dy: 0 + }; + if ((flags & 1) > 0) { + // The arguments are words + if ((flags & 2) > 0) { + // values are offset + component.dx = p.parseShort(); + component.dy = p.parseShort(); + } else { + // values are matched points + component.matchedPoints = [ + p.parseUShort(), + p.parseUShort() + ]; + } + } else { + // The arguments are bytes + if ((flags & 2) > 0) { + // values are offset + component.dx = p.parseChar(); + component.dy = p.parseChar(); + } else { + // values are matched points + component.matchedPoints = [ + p.parseByte(), + p.parseByte() + ]; + } + } + if ((flags & 8) > 0) { + // We have a scale + component.xScale = component.yScale = p.parseF2Dot14(); + } else if ((flags & 64) > 0) { + // We have an X / Y scale + component.xScale = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } else if ((flags & 128) > 0) { + // We have a 2x2 transformation + component.xScale = p.parseF2Dot14(); + component.scale01 = p.parseF2Dot14(); + component.scale10 = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } + glyph.components.push(component); + moreComponents = !!(flags & 32); + } + if (flags & 256) { + // We have instructions + glyph.instructionLength = p.parseUShort(); + glyph.instructions = [ + ]; + for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) { + glyph.instructions.push(p.parseByte()); + } + } + } + } // Transform an array of points and return a new array. + + function transformPoints(points, transform) { + var newPoints = [ + ]; + for (var i = 0; i < points.length; i += 1) { + var pt = points[i]; + var newPt = { + x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, + y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, + onCurve: pt.onCurve, + lastPointOfContour: pt.lastPointOfContour + }; + newPoints.push(newPt); + } + return newPoints; + } + function getContours(points) { + var contours = [ + ]; + var currentContour = [ + ]; + for (var i = 0; i < points.length; i += 1) { + var pt = points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = [ + ]; + } + } + check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); + return contours; + } // Convert the TrueType glyph outline to a Path. + + function getPath(points) { + var p = new Path(); + if (!points) { + return p; + } + var contours = getContours(points); + for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) { + var contour = contours[contourIndex]; + var prev = null; + var curr = contour[contour.length - 1]; + var next = contour[0]; + if (curr.onCurve) { + p.moveTo(curr.x, curr.y); + } else { + if (next.onCurve) { + p.moveTo(next.x, next.y); + } else { + // If both first and last points are off-curve, start at their middle. + var start = { + x: (curr.x + next.x) * 0.5, + y: (curr.y + next.y) * 0.5 + }; + p.moveTo(start.x, start.y); + } + } + for (var i = 0; i < contour.length; ++i) { + prev = curr; + curr = next; + next = contour[(i + 1) % contour.length]; + if (curr.onCurve) { + // This is a straight line. + p.lineTo(curr.x, curr.y); + } else { + var prev2 = prev; + var next2 = next; + if (!prev.onCurve) { + prev2 = { + x: (curr.x + prev.x) * 0.5, + y: (curr.y + prev.y) * 0.5 + }; + } + if (!next.onCurve) { + next2 = { + x: (curr.x + next.x) * 0.5, + y: (curr.y + next.y) * 0.5 + }; + } + p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); + } + } + p.closePath(); + } + return p; + } + function buildPath(glyphs, glyph) { + if (glyph.isComposite) { + for (var j = 0; j < glyph.components.length; j += 1) { + var component = glyph.components[j]; + var componentGlyph = glyphs.get(component.glyphIndex); + // Force the ttfGlyphLoader to parse the glyph. + componentGlyph.getPath(); + if (componentGlyph.points) { + var transformedPoints = void 0; + if (component.matchedPoints === undefined) { + // component positioned by offset + transformedPoints = transformPoints(componentGlyph.points, component); + } else { + // component positioned by matched points + if (component.matchedPoints[0] > glyph.points.length - 1 || component.matchedPoints[1] > componentGlyph.points.length - 1) { + throw Error('Matched points out of range in ' + glyph.name); + } + var firstPt = glyph.points[component.matchedPoints[0]]; + var secondPt = componentGlyph.points[component.matchedPoints[1]]; + var transform = { + xScale: component.xScale, + scale01: component.scale01, + scale10: component.scale10, + yScale: component.yScale, + dx: 0, + dy: 0 + }; + secondPt = transformPoints([secondPt], transform) [0]; + transform.dx = firstPt.x - secondPt.x; + transform.dy = firstPt.y - secondPt.y; + transformedPoints = transformPoints(componentGlyph.points, transform); + } + glyph.points = glyph.points.concat(transformedPoints); + } + } + } + return getPath(glyph.points); + } // Parse all the glyphs according to the offsets from the `loca` table. + + function parseGlyfTable(data, start, loca, font) { + var glyphs = new glyphset.GlyphSet(font); + // The last element of the loca table is invalid. + for (var i = 0; i < loca.length - 1; i += 1) { + var offset = loca[i]; + var nextOffset = loca[i + 1]; + if (offset !== nextOffset) { + glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); + } else { + glyphs.push(i, glyphset.glyphLoader(font, i)); + } + } + return glyphs; + } + var glyf = { + getPath: getPath, + parse: parseGlyfTable + }; + /* A TrueType font hinting interpreter. + * + * (c) 2017 Axel Kittenberger + * + * This interpreter has been implemented according to this documentation: + * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html + * + * According to the documentation F24DOT6 values are used for pixels. + * That means calculation is 1/64 pixel accurate and uses integer operations. + * However, Javascript has floating point operations by default and only + * those are available. One could make a case to simulate the 1/64 accuracy + * exactly by truncating after every division operation + * (for example with << 0) to get pixel exactly results as other TrueType + * implementations. It may make sense since some fonts are pixel optimized + * by hand using DELTAP instructions. The current implementation doesn't + * and rather uses full floating point precision. + * + * xScale, yScale and rotation is currently ignored. + * + * A few non-trivial instructions are missing as I didn't encounter yet + * a font that used them to test a possible implementation. + * + * Some fonts seem to use undocumented features regarding the twilight zone. + * Only some of them are implemented as they were encountered. + * + * The exports.DEBUG statements are removed on the minified distribution file. + */ + var instructionTable; + var exec; + var execGlyph; + var execComponent; + /* + * Creates a hinting object. + * + * There ought to be exactly one + * for each truetype font that is used for hinting. + */ + function Hinting(font) { + // the font this hinting object is for + this.font = font; + this.getCommands = function (hPoints) { + return glyf.getPath(hPoints).commands; + }; + // cached states + this._fpgmState = this._prepState = undefined; + // errorState + // 0 ... all okay + // 1 ... had an error in a glyf, + // continue working but stop spamming + // the console + // 2 ... error at prep, stop hinting at this ppem + // 3 ... error at fpeg, stop hinting for this font at all + this._errorState = 0; + } /* + * Not rounding. + */ + + function roundOff(v) { + return v; + } /* + * Rounding to grid. + */ + + function roundToGrid(v) { + //Rounding in TT is supposed to "symmetrical around zero" + return Math.sign(v) * Math.round(Math.abs(v)); + } /* + * Rounding to double grid. + */ + + function roundToDoubleGrid(v) { + return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2; + } /* + * Rounding to half grid. + */ + + function roundToHalfGrid(v) { + return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5); + } /* + * Rounding to up to grid. + */ + + function roundUpToGrid(v) { + return Math.sign(v) * Math.ceil(Math.abs(v)); + } /* + * Rounding to down to grid. + */ + + function roundDownToGrid(v) { + return Math.sign(v) * Math.floor(Math.abs(v)); + } /* + * Super rounding. + */ + + var roundSuper = function (v) { + var period = this.srPeriod; + var phase = this.srPhase; + var threshold = this.srThreshold; + var sign = 1; + if (v < 0) { + v = - v; + sign = - 1; + } + v += threshold - phase; + v = Math.trunc(v / period) * period; + v += phase; + // according to http://xgridfit.sourceforge.net/round.html + if (v < 0) { + return phase * sign; + } + return v * sign; + }; + /* + * Unit vector of x-axis. + */ + var xUnitVector = { + x: 1, + y: 0, + axis: 'x', + // Gets the projected distance between two points. + // o1/o2 ... if true, respective original position is used. + distance: function (p1, p2, o1, o2) { + return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x); + }, + // Moves point p so the moved position has the same relative + // position to the moved positions of rp1 and rp2 than the + // original positions had. + // + // See APPENDIX on INTERPOLATE at the bottom of this file. + interpolate: function (p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + if (!pv || pv === this) { + do1 = p.xo - rp1.xo; + do2 = p.xo - rp2.xo; + dm1 = rp1.x - rp1.xo; + dm2 = rp2.x - rp2.xo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + p.x = p.xo + (dm1 + dm2) / 2; + return; + } + p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + // Slope of line normal to this + normalSlope: Number.NEGATIVE_INFINITY, + // Sets the point 'p' relative to point 'rp' + // by the distance 'd'. + // + // See APPENDIX on SETRELATIVE at the bottom of this file. + // + // p ... point to set + // rp ... reference point + // d ... distance on projection vector + // pv ... projection vector (undefined = this) + // org ... if true, uses the original position of rp as reference. + setRelative: function (p, rp, d, pv, org) { + if (!pv || pv === this) { + p.x = (org ? rp.xo : rp.x) + d; + return; + } + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + p.x = rpdx + (p.y - rpdy) / pv.normalSlope; + }, + // Slope of vector line. + slope: 0, + // Touches the point p. + touch: function (p) { + p.xTouched = true; + }, + // Tests if a point p is touched. + touched: function (p) { + return p.xTouched; + }, + // Untouches the point p. + untouch: function (p) { + p.xTouched = false; + } + }; + /* + * Unit vector of y-axis. + */ + var yUnitVector = { + x: 0, + y: 1, + axis: 'y', + // Gets the projected distance between two points. + // o1/o2 ... if true, respective original position is used. + distance: function (p1, p2, o1, o2) { + return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y); + }, + // Moves point p so the moved position has the same relative + // position to the moved positions of rp1 and rp2 than the + // original positions had. + // + // See APPENDIX on INTERPOLATE at the bottom of this file. + interpolate: function (p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + if (!pv || pv === this) { + do1 = p.yo - rp1.yo; + do2 = p.yo - rp2.yo; + dm1 = rp1.y - rp1.yo; + dm2 = rp2.y - rp2.yo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + p.y = p.yo + (dm1 + dm2) / 2; + return; + } + p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + // Slope of line normal to this. + normalSlope: 0, + // Sets the point 'p' relative to point 'rp' + // by the distance 'd' + // + // See APPENDIX on SETRELATIVE at the bottom of this file. + // + // p ... point to set + // rp ... reference point + // d ... distance on projection vector + // pv ... projection vector (undefined = this) + // org ... if true, uses the original position of rp as reference. + setRelative: function (p, rp, d, pv, org) { + if (!pv || pv === this) { + p.y = (org ? rp.yo : rp.y) + d; + return; + } + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + p.y = rpdy + pv.normalSlope * (p.x - rpdx); + }, + // Slope of vector line. + slope: Number.POSITIVE_INFINITY, + // Touches the point p. + touch: function (p) { + p.yTouched = true; + }, + // Tests if a point p is touched. + touched: function (p) { + return p.yTouched; + }, + // Untouches the point p. + untouch: function (p) { + p.yTouched = false; + } + }; + Object.freeze(xUnitVector); + Object.freeze(yUnitVector); + /* + * Creates a unit vector that is not x- or y-axis. + */ + function UnitVector(x, y) { + this.x = x; + this.y = y; + this.axis = undefined; + this.slope = y / x; + this.normalSlope = - x / y; + Object.freeze(this); + } /* + * Gets the projected distance between two points. + * o1/o2 ... if true, respective original position is used. + */ + + UnitVector.prototype.distance = function (p1, p2, o1, o2) { + return this.x * xUnitVector.distance(p1, p2, o1, o2) + this.y * yUnitVector.distance(p1, p2, o1, o2); + }; + /* + * Moves point p so the moved position has the same relative + * position to the moved positions of rp1 and rp2 than the + * original positions had. + * + * See APPENDIX on INTERPOLATE at the bottom of this file. + */ + UnitVector.prototype.interpolate = function (p, rp1, rp2, pv) { + var dm1; + var dm2; + var do1; + var do2; + var doa1; + var doa2; + var dt; + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + this.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }; + /* + * Sets the point 'p' relative to point 'rp' + * by the distance 'd' + * + * See APPENDIX on SETRELATIVE at the bottom of this file. + * + * p ... point to set + * rp ... reference point + * d ... distance on projection vector + * pv ... projection vector (undefined = this) + * org ... if true, uses the original position of rp as reference. + */ + UnitVector.prototype.setRelative = function (p, rp, d, pv, org) { + pv = pv || this; + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + var pvns = pv.normalSlope; + var fvs = this.slope; + var px = p.x; + var py = p.y; + p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns); + p.y = fvs * (p.x - px) + py; + }; + /* + * Touches the point p. + */ + UnitVector.prototype.touch = function (p) { + p.xTouched = true; + p.yTouched = true; + }; + /* + * Returns a unit vector with x/y coordinates. + */ + function getUnitVector(x, y) { + var d = Math.sqrt(x * x + y * y); + x /= d; + y /= d; + if (x === 1 && y === 0) { + return xUnitVector; + } else if (x === 0 && y === 1) { + return yUnitVector; + } else { + return new UnitVector(x, y); + } + } /* + * Creates a point in the hinting engine. + */ + + function HPoint(x, y, lastPointOfContour, onCurve) { + this.x = this.xo = Math.round(x * 64) / 64; // hinted x value and original x-value + this.y = this.yo = Math.round(y * 64) / 64; // hinted y value and original y-value + this.lastPointOfContour = lastPointOfContour; + this.onCurve = onCurve; + this.prevPointOnContour = undefined; + this.nextPointOnContour = undefined; + this.xTouched = false; + this.yTouched = false; + Object.preventExtensions(this); + } /* + * Returns the next touched point on the contour. + * + * v ... unit vector to test touch axis. + */ + + HPoint.prototype.nextTouched = function (v) { + var p = this.nextPointOnContour; + while (!v.touched(p) && p !== this) { + p = p.nextPointOnContour; + } + return p; + }; + /* + * Returns the previous touched point on the contour + * + * v ... unit vector to test touch axis. + */ + HPoint.prototype.prevTouched = function (v) { + var p = this.prevPointOnContour; + while (!v.touched(p) && p !== this) { + p = p.prevPointOnContour; + } + return p; + }; + /* + * The zero point. + */ + var HPZero = Object.freeze(new HPoint(0, 0)); + /* + * The default state of the interpreter. + * + * Note: Freezing the defaultState and then deriving from it + * makes the V8 Javascript engine going awkward, + * so this is avoided, albeit the defaultState shouldn't + * ever change. + */ + var defaultState = { + cvCutIn: 17 / 16, + // control value cut in + deltaBase: 9, + deltaShift: 0.125, + loop: 1, + // loops some instructions + minDis: 1, + // minimum distance + autoFlip: true + }; + /* + * The current state of the interpreter. + * + * env ... 'fpgm' or 'prep' or 'glyf' + * prog ... the program + */ + function State(env, prog) { + this.env = env; + this.stack = [ + ]; + this.prog = prog; + switch (env) { + case 'glyf': + this.zp0 = this.zp1 = this.zp2 = 1; + this.rp0 = this.rp1 = this.rp2 = 0; + /* fall through */ + case 'prep': + this.fv = this.pv = this.dpv = xUnitVector; + this.round = roundToGrid; + } + } /* + * Executes a glyph program. + * + * This does the hinting for each glyph. + * + * Returns an array of moved points. + * + * glyph: the glyph to hint + * ppem: the size the glyph is rendered for + */ + + Hinting.prototype.exec = function (glyph, ppem) { + if (typeof ppem !== 'number') { + throw new Error('Point size is not a number!'); + } // Received a fatal error, don't do any hinting anymore. + + if (this._errorState > 2) { + return; + } + var font = this.font; + var prepState = this._prepState; + if (!prepState || prepState.ppem !== ppem) { + var fpgmState = this._fpgmState; + if (!fpgmState) { + // Executes the fpgm state. + // This is used by fonts to define functions. + State.prototype = defaultState; + fpgmState = this._fpgmState = new State('fpgm', font.tables.fpgm); + fpgmState.funcs = [ + ]; + fpgmState.font = font; + if (exports.DEBUG) { + console.log('---EXEC FPGM---'); + fpgmState.step = - 1; + } + try { + exec(fpgmState); + } catch (e) { + console.log('Hinting error in FPGM:' + e); + this._errorState = 3; + return; + } + } // Executes the prep program for this ppem setting. + // This is used by fonts to set cvt values + // depending on to be rendered font size. + + State.prototype = fpgmState; + prepState = this._prepState = new State('prep', font.tables.prep); + prepState.ppem = ppem; + // Creates a copy of the cvt table + // and scales it to the current ppem setting. + var oCvt = font.tables.cvt; + if (oCvt) { + var cvt = prepState.cvt = new Array(oCvt.length); + var scale = ppem / font.unitsPerEm; + for (var c = 0; c < oCvt.length; c++) { + cvt[c] = oCvt[c] * scale; + } + } else { + prepState.cvt = [ + ]; + } + if (exports.DEBUG) { + console.log('---EXEC PREP---'); + prepState.step = - 1; + } + try { + exec(prepState); + } catch (e) { + if (this._errorState < 2) { + console.log('Hinting error in PREP:' + e); + } + this._errorState = 2; + } + } + if (this._errorState > 1) { + return; + } + try { + return execGlyph(glyph, prepState); + } catch (e) { + if (this._errorState < 1) { + console.log('Hinting error:' + e); + console.log('Note: further hinting errors are silenced'); + } + this._errorState = 1; + return undefined; + } + }; + /* + * Executes the hinting program for a glyph. + */ + execGlyph = function (glyph, prepState) { + // original point positions + var xScale = prepState.ppem / prepState.font.unitsPerEm; + var yScale = xScale; + var components = glyph.components; + var contours; + var gZone; + var state; + State.prototype = prepState; + if (!components) { + state = new State('glyf', glyph.instructions); + if (exports.DEBUG) { + console.log('---EXEC GLYPH---'); + state.step = - 1; + } + execComponent(glyph, state, xScale, yScale); + gZone = state.gZone; + } else { + var font = prepState.font; + gZone = [ + ]; + contours = [ + ]; + for (var i = 0; i < components.length; i++) { + var c = components[i]; + var cg = font.glyphs.get(c.glyphIndex); + state = new State('glyf', cg.instructions); + if (exports.DEBUG) { + console.log('---EXEC COMP ' + i + '---'); + state.step = - 1; + } + execComponent(cg, state, xScale, yScale); + // appends the computed points to the result array + // post processes the component points + var dx = Math.round(c.dx * xScale); + var dy = Math.round(c.dy * yScale); + var gz = state.gZone; + var cc = state.contours; + for (var pi = 0; pi < gz.length; pi++) { + var p = gz[pi]; + p.xTouched = p.yTouched = false; + p.xo = p.x = p.x + dx; + p.yo = p.y = p.y + dy; + } + var gLen = gZone.length; + gZone.push.apply(gZone, gz); + for (var j = 0; j < cc.length; j++) { + contours.push(cc[j] + gLen); + } + } + if (glyph.instructions && !state.inhibitGridFit) { + // the composite has instructions on its own + state = new State('glyf', glyph.instructions); + state.gZone = state.z0 = state.z1 = state.z2 = gZone; + state.contours = contours; + // note: HPZero cannot be used here, since + // the point might be modified + gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); + if (exports.DEBUG) { + console.log('---EXEC COMPOSITE---'); + state.step = - 1; + } + exec(state); + gZone.length -= 2; + } + } + return gZone; + }; + /* + * Executes the hinting program for a component of a multi-component glyph + * or of the glyph itself for a non-component glyph. + */ + execComponent = function (glyph, state, xScale, yScale) { + var points = glyph.points || [ + ]; + var pLen = points.length; + var gZone = state.gZone = state.z0 = state.z1 = state.z2 = [ + ]; + var contours = state.contours = [ + ]; + // Scales the original points and + // makes copies for the hinted points. + var cp; // current point + for (var i = 0; i < pLen; i++) { + cp = points[i]; + gZone[i] = new HPoint(cp.x * xScale, cp.y * yScale, cp.lastPointOfContour, cp.onCurve); + } // Chain links the contours. + + var sp; // start point + var np; // next point + for (var i$1 = 0; i$1 < pLen; i$1++) { + cp = gZone[i$1]; + if (!sp) { + sp = cp; + contours.push(i$1); + } + if (cp.lastPointOfContour) { + cp.nextPointOnContour = sp; + sp.prevPointOnContour = cp; + sp = undefined; + } else { + np = gZone[i$1 + 1]; + cp.nextPointOnContour = np; + np.prevPointOnContour = cp; + } + } + if (state.inhibitGridFit) { + return; + } + if (exports.DEBUG) { + console.log('PROCESSING GLYPH', state.stack); + for (var i$2 = 0; i$2 < pLen; i$2++) { + console.log(i$2, gZone[i$2].x, gZone[i$2].y); + } + } + gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); + exec(state); + // Removes the extra points. + gZone.length -= 2; + if (exports.DEBUG) { + console.log('FINISHED GLYPH', state.stack); + for (var i$3 = 0; i$3 < pLen; i$3++) { + console.log(i$3, gZone[i$3].x, gZone[i$3].y); + } + } + }; + /* + * Executes the program loaded in state. + */ + exec = function (state) { + var prog = state.prog; + if (!prog) { + return; + } + var pLen = prog.length; + var ins; + for (state.ip = 0; state.ip < pLen; state.ip++) { + if (exports.DEBUG) { + state.step++; + } + ins = instructionTable[prog[state.ip]]; + if (!ins) { + throw new Error('unknown instruction: 0x' + Number(prog[state.ip]).toString(16)); + } + ins(state); + // very extensive debugging for each step + /* + if (exports.DEBUG) { + var da; + if (state.gZone) { + da = []; + for (let i = 0; i < state.gZone.length; i++) + { + da.push(i + ' ' + + state.gZone[i].x * 64 + ' ' + + state.gZone[i].y * 64 + ' ' + + (state.gZone[i].xTouched ? 'x' : '') + + (state.gZone[i].yTouched ? 'y' : '') + ); + } + console.log('GZ', da); + } + if (state.tZone) { + da = []; + for (let i = 0; i < state.tZone.length; i++) { + da.push(i + ' ' + + state.tZone[i].x * 64 + ' ' + + state.tZone[i].y * 64 + ' ' + + (state.tZone[i].xTouched ? 'x' : '') + + (state.tZone[i].yTouched ? 'y' : '') + ); + } + console.log('TZ', da); + } + if (state.stack.length > 10) { + console.log( + state.stack.length, + '...', state.stack.slice(state.stack.length - 10) + ); + } else { + console.log(state.stack.length, state.stack); + } + } + */ + } + }; + /* + * Initializes the twilight zone. + * + * This is only done if a SZPx instruction + * refers to the twilight zone. + */ + function initTZone(state) { + var tZone = state.tZone = new Array(state.gZone.length); + // no idea if this is actually correct... + for (var i = 0; i < tZone.length; i++) { + tZone[i] = new HPoint(0, 0); + } + } /* + * Skips the instruction pointer ahead over an IF/ELSE block. + * handleElse .. if true breaks on matching ELSE + */ + + function skip(state, handleElse) { + var prog = state.prog; + var ip = state.ip; + var nesting = 1; + var ins; + do { + ins = prog[++ip]; + if (ins === 88) // IF + { + nesting++; + } else if (ins === 89) // EIF + { + nesting--; + } else if (ins === 64) // NPUSHB + { + ip += prog[ip + 1] + 1; + } else if (ins === 65) // NPUSHW + { + ip += 2 * prog[ip + 1] + 1; + } else if (ins >= 176 && ins <= 183) // PUSHB + { + ip += ins - 176 + 1; + } else if (ins >= 184 && ins <= 191) // PUSHW + { + ip += (ins - 184 + 1) * 2; + } else if (handleElse && nesting === 1 && ins === 27) // ELSE + { + break; + } + } while (nesting > 0); + state.ip = ip; + } /*----------------------------------------------------------* + * And then a lot of instructions... * + *----------------------------------------------------------*/ + // SVTCA[a] Set freedom and projection Vectors To Coordinate Axis + // 0x00-0x01 + + function SVTCA(v, state) { + if (exports.DEBUG) { + console.log(state.step, 'SVTCA[' + v.axis + ']'); + } + state.fv = state.pv = state.dpv = v; + } // SPVTCA[a] Set Projection Vector to Coordinate Axis + // 0x02-0x03 + + function SPVTCA(v, state) { + if (exports.DEBUG) { + console.log(state.step, 'SPVTCA[' + v.axis + ']'); + } + state.pv = state.dpv = v; + } // SFVTCA[a] Set Freedom Vector to Coordinate Axis + // 0x04-0x05 + + function SFVTCA(v, state) { + if (exports.DEBUG) { + console.log(state.step, 'SFVTCA[' + v.axis + ']'); + } + state.fv = v; + } // SPVTL[a] Set Projection Vector To Line + // 0x06-0x07 + + function SPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports.DEBUG) { + console.log('SPVTL[' + a + ']', p2i, p1i); + } + var dx; + var dy; + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + state.pv = state.dpv = getUnitVector(dx, dy); + } // SFVTL[a] Set Freedom Vector To Line + // 0x08-0x09 + + function SFVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports.DEBUG) { + console.log('SFVTL[' + a + ']', p2i, p1i); + } + var dx; + var dy; + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + state.fv = getUnitVector(dx, dy); + } // SPVFS[] Set Projection Vector From Stack + // 0x0A + + function SPVFS(state) { + var stack = state.stack; + var y = stack.pop(); + var x = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SPVFS[]', y, x); + } + state.pv = state.dpv = getUnitVector(x, y); + } // SFVFS[] Set Freedom Vector From Stack + // 0x0B + + function SFVFS(state) { + var stack = state.stack; + var y = stack.pop(); + var x = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SPVFS[]', y, x); + } + state.fv = getUnitVector(x, y); + } // GPV[] Get Projection Vector + // 0x0C + + function GPV(state) { + var stack = state.stack; + var pv = state.pv; + if (exports.DEBUG) { + console.log(state.step, 'GPV[]'); + } + stack.push(pv.x * 16384); + stack.push(pv.y * 16384); + } // GFV[] Get Freedom Vector + // 0x0C + + function GFV(state) { + var stack = state.stack; + var fv = state.fv; + if (exports.DEBUG) { + console.log(state.step, 'GFV[]'); + } + stack.push(fv.x * 16384); + stack.push(fv.y * 16384); + } // SFVTPV[] Set Freedom Vector To Projection Vector + // 0x0E + + function SFVTPV(state) { + state.fv = state.pv; + if (exports.DEBUG) { + console.log(state.step, 'SFVTPV[]'); + } + } // ISECT[] moves point p to the InterSECTion of two lines + // 0x0F + + function ISECT(state) { + var stack = state.stack; + var pa0i = stack.pop(); + var pa1i = stack.pop(); + var pb0i = stack.pop(); + var pb1i = stack.pop(); + var pi = stack.pop(); + var z0 = state.z0; + var z1 = state.z1; + var pa0 = z0[pa0i]; + var pa1 = z0[pa1i]; + var pb0 = z1[pb0i]; + var pb1 = z1[pb1i]; + var p = state.z2[pi]; + if (exports.DEBUG) { + console.log('ISECT[], ', pa0i, pa1i, pb0i, pb1i, pi); + } // math from + // en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line + + var x1 = pa0.x; + var y1 = pa0.y; + var x2 = pa1.x; + var y2 = pa1.y; + var x3 = pb0.x; + var y3 = pb0.y; + var x4 = pb1.x; + var y4 = pb1.y; + var div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); + var f1 = x1 * y2 - y1 * x2; + var f2 = x3 * y4 - y3 * x4; + p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div; + p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div; + } // SRP0[] Set Reference Point 0 + // 0x10 + + function SRP0(state) { + state.rp0 = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SRP0[]', state.rp0); + } + } // SRP1[] Set Reference Point 1 + // 0x11 + + function SRP1(state) { + state.rp1 = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SRP1[]', state.rp1); + } + } // SRP1[] Set Reference Point 2 + // 0x12 + + function SRP2(state) { + state.rp2 = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SRP2[]', state.rp2); + } + } // SZP0[] Set Zone Pointer 0 + // 0x13 + + function SZP0(state) { + var n = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SZP0[]', n); + } + state.zp0 = n; + switch (n) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z0 = state.tZone; + break; + case 1: + state.z0 = state.gZone; + break; + default: + throw new Error('Invalid zone pointer'); + } + } // SZP1[] Set Zone Pointer 1 + // 0x14 + + function SZP1(state) { + var n = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SZP1[]', n); + } + state.zp1 = n; + switch (n) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z1 = state.tZone; + break; + case 1: + state.z1 = state.gZone; + break; + default: + throw new Error('Invalid zone pointer'); + } + } // SZP2[] Set Zone Pointer 2 + // 0x15 + + function SZP2(state) { + var n = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SZP2[]', n); + } + state.zp2 = n; + switch (n) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z2 = state.tZone; + break; + case 1: + state.z2 = state.gZone; + break; + default: + throw new Error('Invalid zone pointer'); + } + } // SZPS[] Set Zone PointerS + // 0x16 + + function SZPS(state) { + var n = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SZPS[]', n); + } + state.zp0 = state.zp1 = state.zp2 = n; + switch (n) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z0 = state.z1 = state.z2 = state.tZone; + break; + case 1: + state.z0 = state.z1 = state.z2 = state.gZone; + break; + default: + throw new Error('Invalid zone pointer'); + } + } // SLOOP[] Set LOOP variable + // 0x17 + + function SLOOP(state) { + state.loop = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SLOOP[]', state.loop); + } + } // RTG[] Round To Grid + // 0x18 + + function RTG(state) { + if (exports.DEBUG) { + console.log(state.step, 'RTG[]'); + } + state.round = roundToGrid; + } // RTHG[] Round To Half Grid + // 0x19 + + function RTHG(state) { + if (exports.DEBUG) { + console.log(state.step, 'RTHG[]'); + } + state.round = roundToHalfGrid; + } // SMD[] Set Minimum Distance + // 0x1A + + function SMD(state) { + var d = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SMD[]', d); + } + state.minDis = d / 64; + } // ELSE[] ELSE clause + // 0x1B + + function ELSE(state) { + // This instruction has been reached by executing a then branch + // so it just skips ahead until matching EIF. + // + // In case the IF was negative the IF[] instruction already + // skipped forward over the ELSE[] + if (exports.DEBUG) { + console.log(state.step, 'ELSE[]'); + } + skip(state, false); + } // JMPR[] JuMP Relative + // 0x1C + + function JMPR(state) { + var o = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'JMPR[]', o); + } // A jump by 1 would do nothing. + + state.ip += o - 1; + } // SCVTCI[] Set Control Value Table Cut-In + // 0x1D + + function SCVTCI(state) { + var n = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SCVTCI[]', n); + } + state.cvCutIn = n / 64; + } // DUP[] DUPlicate top stack element + // 0x20 + + function DUP(state) { + var stack = state.stack; + if (exports.DEBUG) { + console.log(state.step, 'DUP[]'); + } + stack.push(stack[stack.length - 1]); + } // POP[] POP top stack element + // 0x21 + + function POP(state) { + if (exports.DEBUG) { + console.log(state.step, 'POP[]'); + } + state.stack.pop(); + } // CLEAR[] CLEAR the stack + // 0x22 + + function CLEAR(state) { + if (exports.DEBUG) { + console.log(state.step, 'CLEAR[]'); + } + state.stack.length = 0; + } // SWAP[] SWAP the top two elements on the stack + // 0x23 + + function SWAP(state) { + var stack = state.stack; + var a = stack.pop(); + var b = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SWAP[]'); + } + stack.push(a); + stack.push(b); + } // DEPTH[] DEPTH of the stack + // 0x24 + + function DEPTH(state) { + var stack = state.stack; + if (exports.DEBUG) { + console.log(state.step, 'DEPTH[]'); + } + stack.push(stack.length); + } // LOOPCALL[] LOOPCALL function + // 0x2A + + function LOOPCALL(state) { + var stack = state.stack; + var fn = stack.pop(); + var c = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'LOOPCALL[]', fn, c); + } // saves callers program + + var cip = state.ip; + var cprog = state.prog; + state.prog = state.funcs[fn]; + // executes the function + for (var i = 0; i < c; i++) { + exec(state); + if (exports.DEBUG) { + console.log(++state.step, i + 1 < c ? 'next loopcall' : 'done loopcall', i); + } + } // restores the callers program + + state.ip = cip; + state.prog = cprog; + } // CALL[] CALL function + // 0x2B + + function CALL(state) { + var fn = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'CALL[]', fn); + } // saves callers program + + var cip = state.ip; + var cprog = state.prog; + state.prog = state.funcs[fn]; + // executes the function + exec(state); + // restores the callers program + state.ip = cip; + state.prog = cprog; + if (exports.DEBUG) { + console.log(++state.step, 'returning from', fn); + } + } // CINDEX[] Copy the INDEXed element to the top of the stack + // 0x25 + + function CINDEX(state) { + var stack = state.stack; + var k = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'CINDEX[]', k); + } // In case of k == 1, it copies the last element after popping + // thus stack.length - k. + + stack.push(stack[stack.length - k]); + } // MINDEX[] Move the INDEXed element to the top of the stack + // 0x26 + + function MINDEX(state) { + var stack = state.stack; + var k = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'MINDEX[]', k); + } + stack.push(stack.splice(stack.length - k, 1) [0]); + } // FDEF[] Function DEFinition + // 0x2C + + function FDEF(state) { + if (state.env !== 'fpgm') { + throw new Error('FDEF not allowed here'); + } + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + var fn = stack.pop(); + var ipBegin = ip; + if (exports.DEBUG) { + console.log(state.step, 'FDEF[]', fn); + } + while (prog[++ip] !== 45) { + } + state.ip = ip; + state.funcs[fn] = prog.slice(ipBegin + 1, ip); + } // MDAP[a] Move Direct Absolute Point + // 0x2E-0x2F + + function MDAP(round, state) { + var pi = state.stack.pop(); + var p = state.z0[pi]; + var fv = state.fv; + var pv = state.pv; + if (exports.DEBUG) { + console.log(state.step, 'MDAP[' + round + ']', pi); + } + var d = pv.distance(p, HPZero); + if (round) { + d = state.round(d); + } + fv.setRelative(p, HPZero, d, pv); + fv.touch(p); + state.rp0 = state.rp1 = pi; + } // IUP[a] Interpolate Untouched Points through the outline + // 0x30 + + function IUP(v, state) { + var z2 = state.z2; + var pLen = z2.length - 2; + var cp; + var pp; + var np; + if (exports.DEBUG) { + console.log(state.step, 'IUP[' + v.axis + ']'); + } + for (var i = 0; i < pLen; i++) { + cp = z2[i]; // current point + // if this point has been touched go on + if (v.touched(cp)) { + continue; + } + pp = cp.prevTouched(v); + // no point on the contour has been touched? + if (pp === cp) { + continue; + } + np = cp.nextTouched(v); + if (pp === np) { + // only one point on the contour has been touched + // so simply moves the point like that + v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true); + } + v.interpolate(cp, pp, np, v); + } + } // SHP[] SHift Point using reference point + // 0x32-0x33 + + function SHP(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1) [rpi]; + var fv = state.fv; + var pv = state.pv; + var loop = state.loop; + var z2 = state.z2; + while (loop--) { + var pi = stack.pop(); + var p = z2[pi]; + var d = pv.distance(rp, rp, false, true); + fv.setRelative(p, p, d, pv); + fv.touch(p); + if (exports.DEBUG) { + console.log(state.step, (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + 'SHP[' + (a ? 'rp1' : 'rp2') + ']', pi); + } + } + state.loop = 1; + } // SHC[] SHift Contour using reference point + // 0x36-0x37 + + function SHC(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1) [rpi]; + var fv = state.fv; + var pv = state.pv; + var ci = stack.pop(); + var sp = state.z2[state.contours[ci]]; + var p = sp; + if (exports.DEBUG) { + console.log(state.step, 'SHC[' + a + ']', ci); + } + var d = pv.distance(rp, rp, false, true); + do { + if (p !== rp) { + fv.setRelative(p, p, d, pv); + } + p = p.nextPointOnContour; + } while (p !== sp); + } // SHZ[] SHift Zone using reference point + // 0x36-0x37 + + function SHZ(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1) [rpi]; + var fv = state.fv; + var pv = state.pv; + var e = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SHZ[' + a + ']', e); + } + var z; + switch (e) { + case 0: + z = state.tZone; + break; + case 1: + z = state.gZone; + break; + default: + throw new Error('Invalid zone'); + } + var p; + var d = pv.distance(rp, rp, false, true); + var pLen = z.length - 2; + for (var i = 0; i < pLen; i++) { + p = z[i]; + fv.setRelative(p, p, d, pv); + //if (p !== rp) fv.setRelative(p, p, d, pv); + } + } // SHPIX[] SHift point by a PIXel amount + // 0x38 + + function SHPIX(state) { + var stack = state.stack; + var loop = state.loop; + var fv = state.fv; + var d = stack.pop() / 64; + var z2 = state.z2; + while (loop--) { + var pi = stack.pop(); + var p = z2[pi]; + if (exports.DEBUG) { + console.log(state.step, (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + 'SHPIX[]', pi, d); + } + fv.setRelative(p, p, d); + fv.touch(p); + } + state.loop = 1; + } // IP[] Interpolate Point + // 0x39 + + function IP(state) { + var stack = state.stack; + var rp1i = state.rp1; + var rp2i = state.rp2; + var loop = state.loop; + var rp1 = state.z0[rp1i]; + var rp2 = state.z1[rp2i]; + var fv = state.fv; + var pv = state.dpv; + var z2 = state.z2; + while (loop--) { + var pi = stack.pop(); + var p = z2[pi]; + if (exports.DEBUG) { + console.log(state.step, (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + 'IP[]', pi, rp1i, '<->', rp2i); + } + fv.interpolate(p, rp1, rp2, pv); + fv.touch(p); + } + state.loop = 1; + } // MSIRP[a] Move Stack Indirect Relative Point + // 0x3A-0x3B + + function MSIRP(a, state) { + var stack = state.stack; + var d = stack.pop() / 64; + var pi = stack.pop(); + var p = state.z1[pi]; + var rp0 = state.z0[state.rp0]; + var fv = state.fv; + var pv = state.pv; + fv.setRelative(p, rp0, d, pv); + fv.touch(p); + if (exports.DEBUG) { + console.log(state.step, 'MSIRP[' + a + ']', d, pi); + } + state.rp1 = state.rp0; + state.rp2 = pi; + if (a) { + state.rp0 = pi; + } + } // ALIGNRP[] Align to reference point. + // 0x3C + + function ALIGNRP(state) { + var stack = state.stack; + var rp0i = state.rp0; + var rp0 = state.z0[rp0i]; + var loop = state.loop; + var fv = state.fv; + var pv = state.pv; + var z1 = state.z1; + while (loop--) { + var pi = stack.pop(); + var p = z1[pi]; + if (exports.DEBUG) { + console.log(state.step, (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + 'ALIGNRP[]', pi); + } + fv.setRelative(p, rp0, 0, pv); + fv.touch(p); + } + state.loop = 1; + } // RTG[] Round To Double Grid + // 0x3D + + function RTDG(state) { + if (exports.DEBUG) { + console.log(state.step, 'RTDG[]'); + } + state.round = roundToDoubleGrid; + } // MIAP[a] Move Indirect Absolute Point + // 0x3E-0x3F + + function MIAP(round, state) { + var stack = state.stack; + var n = stack.pop(); + var pi = stack.pop(); + var p = state.z0[pi]; + var fv = state.fv; + var pv = state.pv; + var cv = state.cvt[n]; + if (exports.DEBUG) { + console.log(state.step, 'MIAP[' + round + ']', n, '(', cv, ')', pi); + } + var d = pv.distance(p, HPZero); + if (round) { + if (Math.abs(d - cv) < state.cvCutIn) { + d = cv; + } + d = state.round(d); + } + fv.setRelative(p, HPZero, d, pv); + if (state.zp0 === 0) { + p.xo = p.x; + p.yo = p.y; + } + fv.touch(p); + state.rp0 = state.rp1 = pi; + } // NPUSB[] PUSH N Bytes + // 0x40 + + function NPUSHB(state) { + var prog = state.prog; + var ip = state.ip; + var stack = state.stack; + var n = prog[++ip]; + if (exports.DEBUG) { + console.log(state.step, 'NPUSHB[]', n); + } + for (var i = 0; i < n; i++) { + stack.push(prog[++ip]); + } + state.ip = ip; + } // NPUSHW[] PUSH N Words + // 0x41 + + function NPUSHW(state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + var n = prog[++ip]; + if (exports.DEBUG) { + console.log(state.step, 'NPUSHW[]', n); + } + for (var i = 0; i < n; i++) { + var w = prog[++ip] << 8 | prog[++ip]; + if (w & 32768) { + w = - ((w ^ 65535) + 1); + } + stack.push(w); + } + state.ip = ip; + } // WS[] Write Store + // 0x42 + + function WS(state) { + var stack = state.stack; + var store = state.store; + if (!store) { + store = state.store = [ + ]; + } + var v = stack.pop(); + var l = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'WS', v, l); + } + store[l] = v; + } // RS[] Read Store + // 0x43 + + function RS(state) { + var stack = state.stack; + var store = state.store; + var l = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'RS', l); + } + var v = store && store[l] || 0; + stack.push(v); + } // WCVTP[] Write Control Value Table in Pixel units + // 0x44 + + function WCVTP(state) { + var stack = state.stack; + var v = stack.pop(); + var l = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'WCVTP', v, l); + } + state.cvt[l] = v / 64; + } // RCVT[] Read Control Value Table entry + // 0x45 + + function RCVT(state) { + var stack = state.stack; + var cvte = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'RCVT', cvte); + } + stack.push(state.cvt[cvte] * 64); + } // GC[] Get Coordinate projected onto the projection vector + // 0x46-0x47 + + function GC(a, state) { + var stack = state.stack; + var pi = stack.pop(); + var p = state.z2[pi]; + if (exports.DEBUG) { + console.log(state.step, 'GC[' + a + ']', pi); + } + stack.push(state.dpv.distance(p, HPZero, a, false) * 64); + } // MD[a] Measure Distance + // 0x49-0x4A + + function MD(a, state) { + var stack = state.stack; + var pi2 = stack.pop(); + var pi1 = stack.pop(); + var p2 = state.z1[pi2]; + var p1 = state.z0[pi1]; + var d = state.dpv.distance(p1, p2, a, a); + if (exports.DEBUG) { + console.log(state.step, 'MD[' + a + ']', pi2, pi1, '->', d); + } + state.stack.push(Math.round(d * 64)); + } // MPPEM[] Measure Pixels Per EM + // 0x4B + + function MPPEM(state) { + if (exports.DEBUG) { + console.log(state.step, 'MPPEM[]'); + } + state.stack.push(state.ppem); + } // FLIPON[] set the auto FLIP Boolean to ON + // 0x4D + + function FLIPON(state) { + if (exports.DEBUG) { + console.log(state.step, 'FLIPON[]'); + } + state.autoFlip = true; + } // LT[] Less Than + // 0x50 + + function LT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'LT[]', e2, e1); + } + stack.push(e1 < e2 ? 1 : 0); + } // LTEQ[] Less Than or EQual + // 0x53 + + function LTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'LTEQ[]', e2, e1); + } + stack.push(e1 <= e2 ? 1 : 0); + } // GTEQ[] Greater Than + // 0x52 + + function GT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'GT[]', e2, e1); + } + stack.push(e1 > e2 ? 1 : 0); + } // GTEQ[] Greater Than or EQual + // 0x53 + + function GTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'GTEQ[]', e2, e1); + } + stack.push(e1 >= e2 ? 1 : 0); + } // EQ[] EQual + // 0x54 + + function EQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'EQ[]', e2, e1); + } + stack.push(e2 === e1 ? 1 : 0); + } // NEQ[] Not EQual + // 0x55 + + function NEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'NEQ[]', e2, e1); + } + stack.push(e2 !== e1 ? 1 : 0); + } // ODD[] ODD + // 0x56 + + function ODD(state) { + var stack = state.stack; + var n = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'ODD[]', n); + } + stack.push(Math.trunc(n) % 2 ? 1 : 0); + } // EVEN[] EVEN + // 0x57 + + function EVEN(state) { + var stack = state.stack; + var n = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'EVEN[]', n); + } + stack.push(Math.trunc(n) % 2 ? 0 : 1); + } // IF[] IF test + // 0x58 + + function IF(state) { + var test = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'IF[]', test); + } // if test is true it just continues + // if not the ip is skipped until matching ELSE or EIF + + if (!test) { + skip(state, true); + if (exports.DEBUG) { + console.log(state.step, 'EIF[]'); + } + } + } // EIF[] End IF + // 0x59 + + function EIF(state) { + // this can be reached normally when + // executing an else branch. + // -> just ignore it + if (exports.DEBUG) { + console.log(state.step, 'EIF[]'); + } + } // AND[] logical AND + // 0x5A + + function AND(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'AND[]', e2, e1); + } + stack.push(e2 && e1 ? 1 : 0); + } // OR[] logical OR + // 0x5B + + function OR(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'OR[]', e2, e1); + } + stack.push(e2 || e1 ? 1 : 0); + } // NOT[] logical NOT + // 0x5C + + function NOT(state) { + var stack = state.stack; + var e = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'NOT[]', e); + } + stack.push(e ? 0 : 1); + } // DELTAP1[] DELTA exception P1 + // DELTAP2[] DELTA exception P2 + // DELTAP3[] DELTA exception P3 + // 0x5D, 0x71, 0x72 + + function DELTAP123(b, state) { + var stack = state.stack; + var n = stack.pop(); + var fv = state.fv; + var pv = state.pv; + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + var z0 = state.z0; + if (exports.DEBUG) { + console.log(state.step, 'DELTAP[' + b + ']', n, stack); + } + for (var i = 0; i < n; i++) { + var pi = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 240) >> 4); + if (appem !== ppem) { + continue; + } + var mag = (arg & 15) - 8; + if (mag >= 0) { + mag++; + } + if (exports.DEBUG) { + console.log(state.step, 'DELTAPFIX', pi, 'by', mag * ds); + } + var p = z0[pi]; + fv.setRelative(p, p, mag * ds, pv); + } + } // SDB[] Set Delta Base in the graphics state + // 0x5E + + function SDB(state) { + var stack = state.stack; + var n = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SDB[]', n); + } + state.deltaBase = n; + } // SDS[] Set Delta Shift in the graphics state + // 0x5F + + function SDS(state) { + var stack = state.stack; + var n = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SDS[]', n); + } + state.deltaShift = Math.pow(0.5, n); + } // ADD[] ADD + // 0x60 + + function ADD(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'ADD[]', n2, n1); + } + stack.push(n1 + n2); + } // SUB[] SUB + // 0x61 + + function SUB(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SUB[]', n2, n1); + } + stack.push(n1 - n2); + } // DIV[] DIV + // 0x62 + + function DIV(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'DIV[]', n2, n1); + } + stack.push(n1 * 64 / n2); + } // MUL[] MUL + // 0x63 + + function MUL(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'MUL[]', n2, n1); + } + stack.push(n1 * n2 / 64); + } // ABS[] ABSolute value + // 0x64 + + function ABS(state) { + var stack = state.stack; + var n = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'ABS[]', n); + } + stack.push(Math.abs(n)); + } // NEG[] NEGate + // 0x65 + + function NEG(state) { + var stack = state.stack; + var n = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'NEG[]', n); + } + stack.push( - n); + } // FLOOR[] FLOOR + // 0x66 + + function FLOOR(state) { + var stack = state.stack; + var n = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'FLOOR[]', n); + } + stack.push(Math.floor(n / 64) * 64); + } // CEILING[] CEILING + // 0x67 + + function CEILING(state) { + var stack = state.stack; + var n = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'CEILING[]', n); + } + stack.push(Math.ceil(n / 64) * 64); + } // ROUND[ab] ROUND value + // 0x68-0x6B + + function ROUND(dt, state) { + var stack = state.stack; + var n = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'ROUND[]'); + } + stack.push(state.round(n / 64) * 64); + } // WCVTF[] Write Control Value Table in Funits + // 0x70 + + function WCVTF(state) { + var stack = state.stack; + var v = stack.pop(); + var l = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'WCVTF[]', v, l); + } + state.cvt[l] = v * state.ppem / state.font.unitsPerEm; + } // DELTAC1[] DELTA exception C1 + // DELTAC2[] DELTA exception C2 + // DELTAC3[] DELTA exception C3 + // 0x73, 0x74, 0x75 + + function DELTAC123(b, state) { + var stack = state.stack; + var n = stack.pop(); + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + if (exports.DEBUG) { + console.log(state.step, 'DELTAC[' + b + ']', n, stack); + } + for (var i = 0; i < n; i++) { + var c = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 240) >> 4); + if (appem !== ppem) { + continue; + } + var mag = (arg & 15) - 8; + if (mag >= 0) { + mag++; + } + var delta = mag * ds; + if (exports.DEBUG) { + console.log(state.step, 'DELTACFIX', c, 'by', delta); + } + state.cvt[c] += delta; + } + } // SROUND[] Super ROUND + // 0x76 + + function SROUND(state) { + var n = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'SROUND[]', n); + } + state.round = roundSuper; + var period; + switch (n & 192) { + case 0: + period = 0.5; + break; + case 64: + period = 1; + break; + case 128: + period = 2; + break; + default: + throw new Error('invalid SROUND value'); + } + state.srPeriod = period; + switch (n & 48) { + case 0: + state.srPhase = 0; + break; + case 16: + state.srPhase = 0.25 * period; + break; + case 32: + state.srPhase = 0.5 * period; + break; + case 48: + state.srPhase = 0.75 * period; + break; + default: + throw new Error('invalid SROUND value'); + } + n &= 15; + if (n === 0) { + state.srThreshold = 0; + } else { + state.srThreshold = (n / 8 - 0.5) * period; + } + } // S45ROUND[] Super ROUND 45 degrees + // 0x77 + + function S45ROUND(state) { + var n = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'S45ROUND[]', n); + } + state.round = roundSuper; + var period; + switch (n & 192) { + case 0: + period = Math.sqrt(2) / 2; + break; + case 64: + period = Math.sqrt(2); + break; + case 128: + period = 2 * Math.sqrt(2); + break; + default: + throw new Error('invalid S45ROUND value'); + } + state.srPeriod = period; + switch (n & 48) { + case 0: + state.srPhase = 0; + break; + case 16: + state.srPhase = 0.25 * period; + break; + case 32: + state.srPhase = 0.5 * period; + break; + case 48: + state.srPhase = 0.75 * period; + break; + default: + throw new Error('invalid S45ROUND value'); + } + n &= 15; + if (n === 0) { + state.srThreshold = 0; + } else { + state.srThreshold = (n / 8 - 0.5) * period; + } + } // ROFF[] Round Off + // 0x7A + + function ROFF(state) { + if (exports.DEBUG) { + console.log(state.step, 'ROFF[]'); + } + state.round = roundOff; + } // RUTG[] Round Up To Grid + // 0x7C + + function RUTG(state) { + if (exports.DEBUG) { + console.log(state.step, 'RUTG[]'); + } + state.round = roundUpToGrid; + } // RDTG[] Round Down To Grid + // 0x7D + + function RDTG(state) { + if (exports.DEBUG) { + console.log(state.step, 'RDTG[]'); + } + state.round = roundDownToGrid; + } // SCANCTRL[] SCAN conversion ConTRoL + // 0x85 + + function SCANCTRL(state) { + var n = state.stack.pop(); + // ignored by opentype.js + if (exports.DEBUG) { + console.log(state.step, 'SCANCTRL[]', n); + } + } // SDPVTL[a] Set Dual Projection Vector To Line + // 0x86-0x87 + + function SDPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports.DEBUG) { + console.log(state.step, 'SDPVTL[' + a + ']', p2i, p1i); + } + var dx; + var dy; + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + state.dpv = getUnitVector(dx, dy); + } // GETINFO[] GET INFOrmation + // 0x88 + + function GETINFO(state) { + var stack = state.stack; + var sel = stack.pop(); + var r = 0; + if (exports.DEBUG) { + console.log(state.step, 'GETINFO[]', sel); + } // v35 as in no subpixel hinting + + if (sel & 1) { + r = 35; + } // TODO rotation and stretch currently not supported + // and thus those GETINFO are always 0. + // opentype.js is always gray scaling + + if (sel & 32) { + r |= 4096; + } + stack.push(r); + } // ROLL[] ROLL the top three stack elements + // 0x8A + + function ROLL(state) { + var stack = state.stack; + var a = stack.pop(); + var b = stack.pop(); + var c = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'ROLL[]'); + } + stack.push(b); + stack.push(a); + stack.push(c); + } // MAX[] MAXimum of top two stack elements + // 0x8B + + function MAX(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'MAX[]', e2, e1); + } + stack.push(Math.max(e1, e2)); + } // MIN[] MINimum of top two stack elements + // 0x8C + + function MIN(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'MIN[]', e2, e1); + } + stack.push(Math.min(e1, e2)); + } // SCANTYPE[] SCANTYPE + // 0x8D + + function SCANTYPE(state) { + var n = state.stack.pop(); + // ignored by opentype.js + if (exports.DEBUG) { + console.log(state.step, 'SCANTYPE[]', n); + } + } // INSTCTRL[] INSTCTRL + // 0x8D + + function INSTCTRL(state) { + var s = state.stack.pop(); + var v = state.stack.pop(); + if (exports.DEBUG) { + console.log(state.step, 'INSTCTRL[]', s, v); + } + switch (s) { + case 1: + state.inhibitGridFit = !!v; + return; + case 2: + state.ignoreCvt = !!v; + return; + default: + throw new Error('invalid INSTCTRL[] selector'); + } + } // PUSHB[abc] PUSH Bytes + // 0xB0-0xB7 + + function PUSHB(n, state) { + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + if (exports.DEBUG) { + console.log(state.step, 'PUSHB[' + n + ']'); + } + for (var i = 0; i < n; i++) { + stack.push(prog[++ip]); + } + state.ip = ip; + } // PUSHW[abc] PUSH Words + // 0xB8-0xBF + + function PUSHW(n, state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + if (exports.DEBUG) { + console.log(state.ip, 'PUSHW[' + n + ']'); + } + for (var i = 0; i < n; i++) { + var w = prog[++ip] << 8 | prog[++ip]; + if (w & 32768) { + w = - ((w ^ 65535) + 1); + } + stack.push(w); + } + state.ip = ip; + } // MDRP[abcde] Move Direct Relative Point + // 0xD0-0xEF + // (if indirect is 0) + // + // and + // + // MIRP[abcde] Move Indirect Relative Point + // 0xE0-0xFF + // (if indirect is 1) + + function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) { + var stack = state.stack; + var cvte = indirect && stack.pop(); + var pi = stack.pop(); + var rp0i = state.rp0; + var rp = state.z0[rp0i]; + var p = state.z1[pi]; + var md = state.minDis; + var fv = state.fv; + var pv = state.dpv; + var od; // original distance + var d; // moving distance + var sign; // sign of distance + var cv; + d = od = pv.distance(p, rp, true, true); + sign = d >= 0 ? 1 : - 1; // Math.sign would be 0 in case of 0 + // TODO consider autoFlip + d = Math.abs(d); + if (indirect) { + cv = state.cvt[cvte]; + if (ro && Math.abs(d - cv) < state.cvCutIn) { + d = cv; + } + } + if (keepD && d < md) { + d = md; + } + if (ro) { + d = state.round(d); + } + fv.setRelative(p, rp, sign * d, pv); + fv.touch(p); + if (exports.DEBUG) { + console.log(state.step, (indirect ? 'MIRP[' : 'MDRP[') + (setRp0 ? 'M' : 'm') + (keepD ? '>' : '_') + (ro ? 'R' : '_') + (dt === 0 ? 'Gr' : dt === 1 ? 'Bl' : dt === 2 ? 'Wh' : '') + ']', indirect ? cvte + '(' + state.cvt[cvte] + ',' + cv + ')' : '', pi, '(d =', od, '->', sign * d, ')'); + } + state.rp1 = state.rp0; + state.rp2 = pi; + if (setRp0) { + state.rp0 = pi; + } + } /* + * The instruction table. + */ + + instructionTable = [ /* 0x00 */ SVTCA.bind(undefined, yUnitVector), /* 0x01 */ SVTCA.bind(undefined, xUnitVector), /* 0x02 */ SPVTCA.bind(undefined, yUnitVector), /* 0x03 */ SPVTCA.bind(undefined, xUnitVector), /* 0x04 */ SFVTCA.bind(undefined, yUnitVector), /* 0x05 */ SFVTCA.bind(undefined, xUnitVector), /* 0x06 */ SPVTL.bind(undefined, 0), /* 0x07 */ SPVTL.bind(undefined, 1), /* 0x08 */ SFVTL.bind(undefined, 0), /* 0x09 */ SFVTL.bind(undefined, 1), /* 0x0A */ SPVFS, /* 0x0B */ SFVFS, /* 0x0C */ GPV, /* 0x0D */ GFV, /* 0x0E */ SFVTPV, /* 0x0F */ ISECT, /* 0x10 */ SRP0, /* 0x11 */ SRP1, /* 0x12 */ SRP2, /* 0x13 */ SZP0, /* 0x14 */ SZP1, /* 0x15 */ SZP2, /* 0x16 */ SZPS, /* 0x17 */ SLOOP, /* 0x18 */ RTG, /* 0x19 */ RTHG, /* 0x1A */ SMD, /* 0x1B */ ELSE, /* 0x1C */ JMPR, /* 0x1D */ SCVTCI, /* 0x1E */ undefined, + // TODO SSWCI + /* 0x1F */ + undefined, + // TODO SSW + /* 0x20 */ + DUP, /* 0x21 */ POP, /* 0x22 */ CLEAR, /* 0x23 */ SWAP, /* 0x24 */ DEPTH, /* 0x25 */ CINDEX, /* 0x26 */ MINDEX, /* 0x27 */ undefined, + // TODO ALIGNPTS + /* 0x28 */ + undefined, /* 0x29 */ undefined, + // TODO UTP + /* 0x2A */ + LOOPCALL, /* 0x2B */ CALL, /* 0x2C */ FDEF, /* 0x2D */ undefined, + // ENDF (eaten by FDEF) + /* 0x2E */ + MDAP.bind(undefined, 0), /* 0x2F */ MDAP.bind(undefined, 1), /* 0x30 */ IUP.bind(undefined, yUnitVector), /* 0x31 */ IUP.bind(undefined, xUnitVector), /* 0x32 */ SHP.bind(undefined, 0), /* 0x33 */ SHP.bind(undefined, 1), /* 0x34 */ SHC.bind(undefined, 0), /* 0x35 */ SHC.bind(undefined, 1), /* 0x36 */ SHZ.bind(undefined, 0), /* 0x37 */ SHZ.bind(undefined, 1), /* 0x38 */ SHPIX, /* 0x39 */ IP, /* 0x3A */ MSIRP.bind(undefined, 0), /* 0x3B */ MSIRP.bind(undefined, 1), /* 0x3C */ ALIGNRP, /* 0x3D */ RTDG, /* 0x3E */ MIAP.bind(undefined, 0), /* 0x3F */ MIAP.bind(undefined, 1), /* 0x40 */ NPUSHB, /* 0x41 */ NPUSHW, /* 0x42 */ WS, /* 0x43 */ RS, /* 0x44 */ WCVTP, /* 0x45 */ RCVT, /* 0x46 */ GC.bind(undefined, 0), /* 0x47 */ GC.bind(undefined, 1), /* 0x48 */ undefined, + // TODO SCFS + /* 0x49 */ + MD.bind(undefined, 0), /* 0x4A */ MD.bind(undefined, 1), /* 0x4B */ MPPEM, /* 0x4C */ undefined, + // TODO MPS + /* 0x4D */ + FLIPON, /* 0x4E */ undefined, + // TODO FLIPOFF + /* 0x4F */ + undefined, + // TODO DEBUG + /* 0x50 */ + LT, /* 0x51 */ LTEQ, /* 0x52 */ GT, /* 0x53 */ GTEQ, /* 0x54 */ EQ, /* 0x55 */ NEQ, /* 0x56 */ ODD, /* 0x57 */ EVEN, /* 0x58 */ IF, /* 0x59 */ EIF, /* 0x5A */ AND, /* 0x5B */ OR, /* 0x5C */ NOT, /* 0x5D */ DELTAP123.bind(undefined, 1), /* 0x5E */ SDB, /* 0x5F */ SDS, /* 0x60 */ ADD, /* 0x61 */ SUB, /* 0x62 */ DIV, /* 0x63 */ MUL, /* 0x64 */ ABS, /* 0x65 */ NEG, /* 0x66 */ FLOOR, /* 0x67 */ CEILING, /* 0x68 */ ROUND.bind(undefined, 0), /* 0x69 */ ROUND.bind(undefined, 1), /* 0x6A */ ROUND.bind(undefined, 2), /* 0x6B */ ROUND.bind(undefined, 3), /* 0x6C */ undefined, + // TODO NROUND[ab] + /* 0x6D */ + undefined, + // TODO NROUND[ab] + /* 0x6E */ + undefined, + // TODO NROUND[ab] + /* 0x6F */ + undefined, + // TODO NROUND[ab] + /* 0x70 */ + WCVTF, /* 0x71 */ DELTAP123.bind(undefined, 2), /* 0x72 */ DELTAP123.bind(undefined, 3), /* 0x73 */ DELTAC123.bind(undefined, 1), /* 0x74 */ DELTAC123.bind(undefined, 2), /* 0x75 */ DELTAC123.bind(undefined, 3), /* 0x76 */ SROUND, /* 0x77 */ S45ROUND, /* 0x78 */ undefined, + // TODO JROT[] + /* 0x79 */ + undefined, + // TODO JROF[] + /* 0x7A */ + ROFF, /* 0x7B */ undefined, /* 0x7C */ RUTG, /* 0x7D */ RDTG, /* 0x7E */ POP, + // actually SANGW, supposed to do only a pop though + /* 0x7F */ + POP, + // actually AA, supposed to do only a pop though + /* 0x80 */ + undefined, + // TODO FLIPPT + /* 0x81 */ + undefined, + // TODO FLIPRGON + /* 0x82 */ + undefined, + // TODO FLIPRGOFF + /* 0x83 */ + undefined, /* 0x84 */ undefined, /* 0x85 */ SCANCTRL, /* 0x86 */ SDPVTL.bind(undefined, 0), /* 0x87 */ SDPVTL.bind(undefined, 1), /* 0x88 */ GETINFO, /* 0x89 */ undefined, + // TODO IDEF + /* 0x8A */ + ROLL, /* 0x8B */ MAX, /* 0x8C */ MIN, /* 0x8D */ SCANTYPE, /* 0x8E */ INSTCTRL, /* 0x8F */ undefined, /* 0x90 */ undefined, /* 0x91 */ undefined, /* 0x92 */ undefined, /* 0x93 */ undefined, /* 0x94 */ undefined, /* 0x95 */ undefined, /* 0x96 */ undefined, /* 0x97 */ undefined, /* 0x98 */ undefined, /* 0x99 */ undefined, /* 0x9A */ undefined, /* 0x9B */ undefined, /* 0x9C */ undefined, /* 0x9D */ undefined, /* 0x9E */ undefined, /* 0x9F */ undefined, /* 0xA0 */ undefined, /* 0xA1 */ undefined, /* 0xA2 */ undefined, /* 0xA3 */ undefined, /* 0xA4 */ undefined, /* 0xA5 */ undefined, /* 0xA6 */ undefined, /* 0xA7 */ undefined, /* 0xA8 */ undefined, /* 0xA9 */ undefined, /* 0xAA */ undefined, /* 0xAB */ undefined, /* 0xAC */ undefined, /* 0xAD */ undefined, /* 0xAE */ undefined, /* 0xAF */ undefined, /* 0xB0 */ PUSHB.bind(undefined, 1), /* 0xB1 */ PUSHB.bind(undefined, 2), /* 0xB2 */ PUSHB.bind(undefined, 3), /* 0xB3 */ PUSHB.bind(undefined, 4), /* 0xB4 */ PUSHB.bind(undefined, 5), /* 0xB5 */ PUSHB.bind(undefined, 6), /* 0xB6 */ PUSHB.bind(undefined, 7), /* 0xB7 */ PUSHB.bind(undefined, 8), /* 0xB8 */ PUSHW.bind(undefined, 1), /* 0xB9 */ PUSHW.bind(undefined, 2), /* 0xBA */ PUSHW.bind(undefined, 3), /* 0xBB */ PUSHW.bind(undefined, 4), /* 0xBC */ PUSHW.bind(undefined, 5), /* 0xBD */ PUSHW.bind(undefined, 6), /* 0xBE */ PUSHW.bind(undefined, 7), /* 0xBF */ PUSHW.bind(undefined, 8), /* 0xC0 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0), /* 0xC1 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1), /* 0xC2 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2), /* 0xC3 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3), /* 0xC4 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0), /* 0xC5 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1), /* 0xC6 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2), /* 0xC7 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3), /* 0xC8 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0), /* 0xC9 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1), /* 0xCA */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2), /* 0xCB */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3), /* 0xCC */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0), /* 0xCD */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1), /* 0xCE */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2), /* 0xCF */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3), /* 0xD0 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0), /* 0xD1 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1), /* 0xD2 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2), /* 0xD3 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3), /* 0xD4 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0), /* 0xD5 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1), /* 0xD6 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2), /* 0xD7 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3), /* 0xD8 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0), /* 0xD9 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1), /* 0xDA */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2), /* 0xDB */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3), /* 0xDC */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0), /* 0xDD */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1), /* 0xDE */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2), /* 0xDF */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3), /* 0xE0 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0), /* 0xE1 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1), /* 0xE2 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2), /* 0xE3 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3), /* 0xE4 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0), /* 0xE5 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1), /* 0xE6 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2), /* 0xE7 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3), /* 0xE8 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0), /* 0xE9 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1), /* 0xEA */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2), /* 0xEB */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3), /* 0xEC */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0), /* 0xED */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1), /* 0xEE */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2), /* 0xEF */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3), /* 0xF0 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0), /* 0xF1 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1), /* 0xF2 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2), /* 0xF3 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3), /* 0xF4 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0), /* 0xF5 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1), /* 0xF6 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2), /* 0xF7 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3), /* 0xF8 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0), /* 0xF9 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1), /* 0xFA */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2), /* 0xFB */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3), /* 0xFC */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0), /* 0xFD */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1), /* 0xFE */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2), /* 0xFF */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3) + ]; + /***************************** + Mathematical Considerations + ****************************** + fv ... refers to freedom vector + pv ... refers to projection vector + rp ... refers to reference point + p ... refers to to point being operated on + d ... refers to distance + SETRELATIVE: + ============ + case freedom vector == x-axis: + ------------------------------ + (pv) + .-' + rpd .-' + .-* + d .-'90°' + .-' ' + .-' ' + *-' ' b + rp ' + ' + ' + p *----------*-------------- (fv) + pm + rpdx = rpx + d * pv.x + rpdy = rpy + d * pv.y + equation of line b + y - rpdy = pvns * (x- rpdx) + y = p.y + x = rpdx + ( p.y - rpdy ) / pvns + + case freedom vector == y-axis: + ------------------------------ + * pm + |\ + | \ + | \ + | \ + | \ + | \ + | \ + | \ + | \ + | \ b + | \ + | \ + | \ .-' (pv) + | 90° \.-' + | .-'* rpd + | .-' + * *-' d + p rp + rpdx = rpx + d * pv.x + rpdy = rpy + d * pv.y + equation of line b: + pvns ... normal slope to pv + y - rpdy = pvns * (x - rpdx) + x = p.x + y = rpdy + pvns * (p.x - rpdx) + + generic case: + ------------- + + .'(fv) + .' + .* pm + .' ! + .' . + .' ! + .' . b + .' ! + * . + p ! + 90° . ... (pv) + ...-*-''' + ...---''' rpd + ...---''' d + *--''' + rp + rpdx = rpx + d * pv.x + rpdy = rpy + d * pv.y + equation of line b: + pvns... normal slope to pv + y - rpdy = pvns * (x - rpdx) + equation of freedom vector line: + fvs ... slope of freedom vector (=fy/fx) + y - py = fvs * (x - px) + + on pm both equations are true for same x/y + y - rpdy = pvns * (x - rpdx) + y - py = fvs * (x - px) + form to y and set equal: + pvns * (x - rpdx) + rpdy = fvs * (x - px) + py + expand: + pvns * x - pvns * rpdx + rpdy = fvs * x - fvs * px + py + switch: + fvs * x - fvs * px + py = pvns * x - pvns * rpdx + rpdy + solve for x: + fvs * x - pvns * x = fvs * px - pvns * rpdx - py + rpdy + + fvs * px - pvns * rpdx + rpdy - py + x = ----------------------------------- + fvs - pvns + and: + y = fvs * (x - px) + py + + INTERPOLATE: + ============ + Examples of point interpolation. + The weight of the movement of the reference point gets bigger + the further the other reference point is away, thus the safest + option (that is avoiding 0/0 divisions) is to weight the + original distance of the other point by the sum of both distances. + If the sum of both distances is 0, then move the point by the + arithmetic average of the movement of both reference points. + + + (+6) + rp1o *---->*rp1 + . . (+12) + . . rp2o *---------->* rp2 + . . . . + . . . . + . 10 20 . . + |.........|...................| . + . . . + . . (+8) . + po *------>*p . + . . . + . 12 . 24 . + |...........|.......................| + 36 + + ------- + + (+10) + rp1o *-------->*rp1 + . . (-10) + . . rp2 *<---------* rpo2 + . . . . + . . . . + . 10 . 30 . . + |.........|.............................| + . . + . (+5) . + po *--->* p . + . . . + . . 20 . + |....|..............| + 5 15 + + ------- + + (+10) + rp1o *-------->*rp1 + . . + . . + rp2o *-------->*rp2 + + (+10) + po *-------->* p + ------- + + (+10) + rp1o *-------->*rp1 + . . + . .(+30) + rp2o *---------------------------->*rp2 + + (+25) + po *----------------------->* p + + vim: set ts=4 sw=4 expandtab: + *****/ + // The Font object + // This code is based on Array.from implementation for strings in https://github.com/mathiasbynens/Array.from + var arrayFromString = Array.from || function (s) { + return s.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]?|[^\uD800-\uDFFF]|./g) || [ + ]; + }; + /** + * @typedef FontOptions + * @type Object + * @property {Boolean} empty - whether to create a new empty font + * @property {string} familyName + * @property {string} styleName + * @property {string=} fullName + * @property {string=} postScriptName + * @property {string=} designer + * @property {string=} designerURL + * @property {string=} manufacturer + * @property {string=} manufacturerURL + * @property {string=} license + * @property {string=} licenseURL + * @property {string=} version + * @property {string=} description + * @property {string=} copyright + * @property {string=} trademark + * @property {Number} unitsPerEm + * @property {Number} ascender + * @property {Number} descender + * @property {Number} createdTimestamp + * @property {string=} weightClass + * @property {string=} widthClass + * @property {string=} fsSelection + */ + /** + * A Font represents a loaded OpenType font file. + * It contains a set of glyphs and methods to draw text on a drawing context, + * or to get a path representing the text. + * @exports opentype.Font + * @class + * @param {FontOptions} + * @constructor + */ + function Font(options) { + options = options || { + }; + if (!options.empty) { + // Check that we've provided the minimum set of names. + checkArgument(options.familyName, 'When creating a new Font object, familyName is required.'); + checkArgument(options.styleName, 'When creating a new Font object, styleName is required.'); + checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.'); + checkArgument(options.ascender, 'When creating a new Font object, ascender is required.'); + checkArgument(options.descender, 'When creating a new Font object, descender is required.'); + checkArgument(options.descender < 0, 'Descender should be negative (e.g. -512).'); + // OS X will complain if the names are empty, so we put a single space everywhere by default. + this.names = { + fontFamily: { + en: options.familyName || ' ' + }, + fontSubfamily: { + en: options.styleName || ' ' + }, + fullName: { + en: options.fullName || options.familyName + ' ' + options.styleName + }, + // postScriptName may not contain any whitespace + postScriptName: { + en: options.postScriptName || (options.familyName + options.styleName).replace(/\s/g, '') + }, + designer: { + en: options.designer || ' ' + }, + designerURL: { + en: options.designerURL || ' ' + }, + manufacturer: { + en: options.manufacturer || ' ' + }, + manufacturerURL: { + en: options.manufacturerURL || ' ' + }, + license: { + en: options.license || ' ' + }, + licenseURL: { + en: options.licenseURL || ' ' + }, + version: { + en: options.version || 'Version 0.1' + }, + description: { + en: options.description || ' ' + }, + copyright: { + en: options.copyright || ' ' + }, + trademark: { + en: options.trademark || ' ' + } + }; + this.unitsPerEm = options.unitsPerEm || 1000; + this.ascender = options.ascender; + this.descender = options.descender; + this.createdTimestamp = options.createdTimestamp; + this.tables = { + os2: { + usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, + usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, + fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR + } + }; + } + this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported. + this.glyphs = new glyphset.GlyphSet(this, options.glyphs || [ + ]); + this.encoding = new DefaultEncoding(this); + this.position = new Position(this); + this.substitution = new Substitution(this); + this.tables = this.tables || { + }; + Object.defineProperty(this, 'hinting', { + get: function () { + if (this._hinting) { + return this._hinting; + } + if (this.outlinesFormat === 'truetype') { + return this._hinting = new Hinting(this); + } + } + }); + } /** + * Check if the font has a glyph for the given character. + * @param {string} + * @return {Boolean} + */ + + Font.prototype.hasChar = function (c) { + return this.encoding.charToGlyphIndex(c) !== null; + }; + /** + * Convert the given character to a single glyph index. + * Note that this function assumes that there is a one-to-one mapping between + * the given character and a glyph; for complex scripts this might not be the case. + * @param {string} + * @return {Number} + */ + Font.prototype.charToGlyphIndex = function (s) { + return this.encoding.charToGlyphIndex(s); + }; + /** + * Convert the given character to a single Glyph object. + * Note that this function assumes that there is a one-to-one mapping between + * the given character and a glyph; for complex scripts this might not be the case. + * @param {string} + * @return {opentype.Glyph} + */ + Font.prototype.charToGlyph = function (c) { + var glyphIndex = this.charToGlyphIndex(c); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + // .notdef + glyph = this.glyphs.get(0); + } + return glyph; + }; + /** + * Convert the given text to a list of Glyph objects. + * Note that there is no strict one-to-one mapping between characters and + * glyphs, so the list of returned glyphs can be larger or smaller than the + * length of the given string. + * @param {string} + * @param {GlyphRenderOptions} [options] + * @return {opentype.Glyph[]} + */ + Font.prototype.stringToGlyphs = function (s, options) { + var this$1 = this; + options = options || this.defaultRenderOptions; + // Get glyph indexes + var chars = arrayFromString(s); + var indexes = [ + ]; + for (var i = 0; i < chars.length; i += 1) { + var c = chars[i]; + indexes.push(this$1.charToGlyphIndex(c)); + } + var length = indexes.length; + // Apply substitutions on glyph indexes + if (options.features) { + var script = options.script || this.substitution.getDefaultScriptName(); + var manyToOne = [ + ]; + if (options.features.liga) { + manyToOne = manyToOne.concat(this.substitution.getFeature('liga', script, options.language)); + } + if (options.features.rlig) { + manyToOne = manyToOne.concat(this.substitution.getFeature('rlig', script, options.language)); + } + for (var i$1 = 0; i$1 < length; i$1 += 1) { + for (var j = 0; j < manyToOne.length; j++) { + var ligature = manyToOne[j]; + var components = ligature.sub; + var compCount = components.length; + var k = 0; + while (k < compCount && components[k] === indexes[i$1 + k]) { + k++; + } + if (k === compCount) { + indexes.splice(i$1, compCount, ligature.by); + length = length - compCount + 1; + } + } + } + } // convert glyph indexes to glyph objects + + var glyphs = new Array(length); + var notdef = this.glyphs.get(0); + for (var i$2 = 0; i$2 < length; i$2 += 1) { + glyphs[i$2] = this$1.glyphs.get(indexes[i$2]) || notdef; + } + return glyphs; + }; + /** + * @param {string} + * @return {Number} + */ + Font.prototype.nameToGlyphIndex = function (name) { + return this.glyphNames.nameToGlyphIndex(name); + }; + /** + * @param {string} + * @return {opentype.Glyph} + */ + Font.prototype.nameToGlyph = function (name) { + var glyphIndex = this.nameToGlyphIndex(name); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + // .notdef + glyph = this.glyphs.get(0); + } + return glyph; + }; + /** + * @param {Number} + * @return {String} + */ + Font.prototype.glyphIndexToName = function (gid) { + if (!this.glyphNames.glyphIndexToName) { + return ''; + } + return this.glyphNames.glyphIndexToName(gid); + }; + /** + * Retrieve the value of the kerning pair between the left glyph (or its index) + * and the right glyph (or its index). If no kerning pair is found, return 0. + * The kerning value gets added to the advance width when calculating the spacing + * between glyphs. + * For GPOS kerning, this method uses the default script and language, which covers + * most use cases. To have greater control, use font.position.getKerningValue . + * @param {opentype.Glyph} leftGlyph + * @param {opentype.Glyph} rightGlyph + * @return {Number} + */ + Font.prototype.getKerningValue = function (leftGlyph, rightGlyph) { + leftGlyph = leftGlyph.index || leftGlyph; + rightGlyph = rightGlyph.index || rightGlyph; + var gposKerning = this.position.defaultKerningTables; + if (gposKerning) { + return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph); + } // "kern" table + + return this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0; + }; + /** + * @typedef GlyphRenderOptions + * @type Object + * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used. + * See https://www.microsoft.com/typography/otspec/scripttags.htm + * @property {string} [language='dflt'] - language system used to determine which features to apply. + * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx + * @property {boolean} [kerning=true] - whether to include kerning values + * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system. + * See https://www.microsoft.com/typography/otspec/featuretags.htm + */ + Font.prototype.defaultRenderOptions = { + kerning: true, + features: { + liga: true, + rlig: true + } + }; + /** + * Helper function that invokes the given callback for each glyph in the given text. + * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text + * @param {string} text - The text to apply. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + * @param {Function} callback + */ + Font.prototype.forEachGlyph = function (text, x, y, fontSize, options, callback) { + var this$1 = this; + x = x !== undefined ? x : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + options = options || this.defaultRenderOptions; + var fontScale = 1 / this.unitsPerEm * fontSize; + var glyphs = this.stringToGlyphs(text, options); + var kerningLookups; + if (options.kerning) { + var script = options.script || this.position.getDefaultScriptName(); + kerningLookups = this.position.getKerningTables(script, options.language); + } + for (var i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs[i]; + callback.call(this$1, glyph, x, y, fontSize, options); + if (glyph.advanceWidth) { + x += glyph.advanceWidth * fontScale; + } + if (options.kerning && i < glyphs.length - 1) { + // We should apply position adjustment lookups in a more generic way. + // Here we only use the xAdvance value. + var kerningValue = kerningLookups ? this$1.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) : this$1.getKerningValue(glyph, glyphs[i + 1]); + x += kerningValue * fontScale; + } + if (options.letterSpacing) { + x += options.letterSpacing * fontSize; + } else if (options.tracking) { + x += options.tracking / 1000 * fontSize; + } + } + return x; + }; + /** + * Create a Path object that represents the given text. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + * @return {opentype.Path} + */ + Font.prototype.getPath = function (text, x, y, fontSize, options) { + var fullPath = new Path(); + this.forEachGlyph(text, x, y, fontSize, options, function (glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + fullPath.extend(glyphPath); + }); + return fullPath; + }; + /** + * Create an array of Path objects that represent the glyphs of a given text. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + * @return {opentype.Path[]} + */ + Font.prototype.getPaths = function (text, x, y, fontSize, options) { + var glyphPaths = [ + ]; + this.forEachGlyph(text, x, y, fontSize, options, function (glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + glyphPaths.push(glyphPath); + }); + return glyphPaths; + }; + /** + * Returns the advance width of a text. + * + * This is something different than Path.getBoundingBox() as for example a + * suffixed whitespace increases the advanceWidth but not the bounding box + * or an overhanging letter like a calligraphic 'f' might have a quite larger + * bounding box than its advance width. + * + * This corresponds to canvas2dContext.measureText(text).width + * + * @param {string} text - The text to create. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + * @return advance width + */ + Font.prototype.getAdvanceWidth = function (text, fontSize, options) { + return this.forEachGlyph(text, 0, 0, fontSize, options, function () { + }); + }; + /** + * Draw the text on the given drawing context. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + */ + Font.prototype.draw = function (ctx, text, x, y, fontSize, options) { + this.getPath(text, x, y, fontSize, options).draw(ctx); + }; + /** + * Draw the points of all glyphs in the text. + * On-curve points will be drawn in blue, off-curve points will be drawn in red. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + */ + Font.prototype.drawPoints = function (ctx, text, x, y, fontSize, options) { + this.forEachGlyph(text, x, y, fontSize, options, function (glyph, gX, gY, gFontSize) { + glyph.drawPoints(ctx, gX, gY, gFontSize); + }); + }; + /** + * Draw lines indicating important font measurements for all glyphs in the text. + * Black lines indicate the origin of the coordinate system (point 0,0). + * Blue lines indicate the glyph bounding box. + * Green line indicates the advance width of the glyph. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + */ + Font.prototype.drawMetrics = function (ctx, text, x, y, fontSize, options) { + this.forEachGlyph(text, x, y, fontSize, options, function (glyph, gX, gY, gFontSize) { + glyph.drawMetrics(ctx, gX, gY, gFontSize); + }); + }; + /** + * @param {string} + * @return {string} + */ + Font.prototype.getEnglishName = function (name) { + var translations = this.names[name]; + if (translations) { + return translations.en; + } + }; + /** + * Validate + */ + Font.prototype.validate = function () { + var _this = this; + function assert(predicate, message) { + } + function assertNamePresent(name) { + var englishName = _this.getEnglishName(name); + assert(englishName && englishName.trim().length > 0, 'No English ' + name + ' specified.'); + } // Identification information + + assertNamePresent('fontFamily'); + assertNamePresent('weightName'); + assertNamePresent('manufacturer'); + assertNamePresent('copyright'); + assertNamePresent('version'); + // Dimension information + assert(this.unitsPerEm > 0, 'No unitsPerEm specified.'); + }; + /** + * Convert the font object to a SFNT data structure. + * This structure contains all the necessary tables and metadata to create a binary OTF file. + * @return {opentype.Table} + */ + Font.prototype.toTables = function () { + return sfnt.fontToTable(this); + }; + /** + * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. + */ + Font.prototype.toBuffer = function () { + console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'); + return this.toArrayBuffer(); + }; + /** + * Converts a `opentype.Font` into an `ArrayBuffer` + * @return {ArrayBuffer} + */ + Font.prototype.toArrayBuffer = function () { + var sfntTable = this.toTables(); + var bytes = sfntTable.encode(); + var buffer = new ArrayBuffer(bytes.length); + var intArray = new Uint8Array(buffer); + for (var i = 0; i < bytes.length; i++) { + intArray[i] = bytes[i]; + } + return buffer; + }; + /** + * Initiate a download of the OpenType font. + */ + Font.prototype.download = function (fileName) { + var familyName = this.getEnglishName('fontFamily'); + var styleName = this.getEnglishName('fontSubfamily'); + fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf'; + var arrayBuffer = this.toArrayBuffer(); + if (isBrowser()) { + window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; + window.requestFileSystem(window.TEMPORARY, arrayBuffer.byteLength, function (fs) { + fs.root.getFile(fileName, { + create: true + }, function (fileEntry) { + fileEntry.createWriter(function (writer) { + var dataView = new DataView(arrayBuffer); + var blob = new Blob([dataView], { + type: 'font/opentype' + }); + writer.write(blob); + writer.addEventListener('writeend', function () { + // Navigating to the file will download it. + location.href = fileEntry.toURL(); + }, false); + }); + }); + }, function (err) { + throw new Error(err.name + ': ' + err.message); + }); + } else { + var fs = _dereq_('fs'); + var buffer = arrayBufferToNodeBuffer(arrayBuffer); + fs.writeFileSync(fileName, buffer); + } + }; + /** + * @private + */ + Font.prototype.fsSelectionValues = { + ITALIC: 1, + //1 + UNDERSCORE: 2, + //2 + NEGATIVE: 4, + //4 + OUTLINED: 8, + //8 + STRIKEOUT: 16, + //16 + BOLD: 32, + //32 + REGULAR: 64, + //64 + USER_TYPO_METRICS: 128, + //128 + WWS: 256, + //256 + OBLIQUE: 512 //512 + }; + /** + * @private + */ + Font.prototype.usWidthClasses = { + ULTRA_CONDENSED: 1, + EXTRA_CONDENSED: 2, + CONDENSED: 3, + SEMI_CONDENSED: 4, + MEDIUM: 5, + SEMI_EXPANDED: 6, + EXPANDED: 7, + EXTRA_EXPANDED: 8, + ULTRA_EXPANDED: 9 + }; + /** + * @private + */ + Font.prototype.usWeightClasses = { + THIN: 100, + EXTRA_LIGHT: 200, + LIGHT: 300, + NORMAL: 400, + MEDIUM: 500, + SEMI_BOLD: 600, + BOLD: 700, + EXTRA_BOLD: 800, + BLACK: 900 + }; + // The `fvar` table stores font variation axes and instances. + function addName(name, names) { + var nameString = JSON.stringify(name); + var nameID = 256; + for (var nameKey in names) { + var n = parseInt(nameKey); + if (!n || n < 256) { + continue; + } + if (JSON.stringify(names[nameKey]) === nameString) { + return n; + } + if (nameID <= n) { + nameID = n + 1; + } + } + names[nameID] = name; + return nameID; + } + function makeFvarAxis(n, axis, names) { + var nameID = addName(axis.name, names); + return [{ + name: 'tag_' + n, + type: 'TAG', + value: axis.tag + }, + { + name: 'minValue_' + n, + type: 'FIXED', + value: axis.minValue << 16 + }, + { + name: 'defaultValue_' + n, + type: 'FIXED', + value: axis.defaultValue << 16 + }, + { + name: 'maxValue_' + n, + type: 'FIXED', + value: axis.maxValue << 16 + }, + { + name: 'flags_' + n, + type: 'USHORT', + value: 0 + }, + { + name: 'nameID_' + n, + type: 'USHORT', + value: nameID + } + ]; + } + function parseFvarAxis(data, start, names) { + var axis = { + }; + var p = new parse.Parser(data, start); + axis.tag = p.parseTag(); + axis.minValue = p.parseFixed(); + axis.defaultValue = p.parseFixed(); + axis.maxValue = p.parseFixed(); + p.skip('uShort', 1); // reserved for flags; no values defined + axis.name = names[p.parseUShort()] || { + }; + return axis; + } + function makeFvarInstance(n, inst, axes, names) { + var nameID = addName(inst.name, names); + var fields = [ + { + name: 'nameID_' + n, + type: 'USHORT', + value: nameID + }, + { + name: 'flags_' + n, + type: 'USHORT', + value: 0 + } + ]; + for (var i = 0; i < axes.length; ++i) { + var axisTag = axes[i].tag; + fields.push({ + name: 'axis_' + n + ' ' + axisTag, + type: 'FIXED', + value: inst.coordinates[axisTag] << 16 + }); + } + return fields; + } + function parseFvarInstance(data, start, axes, names) { + var inst = { + }; + var p = new parse.Parser(data, start); + inst.name = names[p.parseUShort()] || { + }; + p.skip('uShort', 1); // reserved for flags; no values defined + inst.coordinates = { + }; + for (var i = 0; i < axes.length; ++i) { + inst.coordinates[axes[i].tag] = p.parseFixed(); + } + return inst; + } + function makeFvarTable(fvar, names) { + var result = new table.Table('fvar', [ + { + name: 'version', + type: 'ULONG', + value: 65536 + }, + { + name: 'offsetToData', + type: 'USHORT', + value: 0 + }, + { + name: 'countSizePairs', + type: 'USHORT', + value: 2 + }, + { + name: 'axisCount', + type: 'USHORT', + value: fvar.axes.length + }, + { + name: 'axisSize', + type: 'USHORT', + value: 20 + }, + { + name: 'instanceCount', + type: 'USHORT', + value: fvar.instances.length + }, + { + name: 'instanceSize', + type: 'USHORT', + value: 4 + fvar.axes.length * 4 + } + ]); + result.offsetToData = result.sizeOf(); + for (var i = 0; i < fvar.axes.length; i++) { + result.fields = result.fields.concat(makeFvarAxis(i, fvar.axes[i], names)); + } + for (var j = 0; j < fvar.instances.length; j++) { + result.fields = result.fields.concat(makeFvarInstance(j, fvar.instances[j], fvar.axes, names)); + } + return result; + } + function parseFvarTable(data, start, names) { + var p = new parse.Parser(data, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 65536, 'Unsupported fvar table version.'); + var offsetToData = p.parseOffset16(); + // Skip countSizePairs. + p.skip('uShort', 1); + var axisCount = p.parseUShort(); + var axisSize = p.parseUShort(); + var instanceCount = p.parseUShort(); + var instanceSize = p.parseUShort(); + var axes = [ + ]; + for (var i = 0; i < axisCount; i++) { + axes.push(parseFvarAxis(data, start + offsetToData + i * axisSize, names)); + } + var instances = [ + ]; + var instanceStart = start + offsetToData + axisCount * axisSize; + for (var j = 0; j < instanceCount; j++) { + instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names)); + } + return { + axes: axes, + instances: instances + }; + } + var fvar = { + make: makeFvarTable, + parse: parseFvarTable + }; + // The `GPOS` table contains kerning pairs, among other things. + var subtableParsers$1 = new Array(10); // subtableParsers[0] is unused + // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-1-single-adjustment-positioning-subtable + // this = Parser instance + subtableParsers$1[1] = function parseLookup1() { + var start = this.offset + this.relativeOffset; + var posformat = this.parseUShort(); + if (posformat === 1) { + return { + posFormat: 1, + coverage: this.parsePointer(Parser.coverage), + value: this.parseValueRecord() + }; + } else if (posformat === 2) { + return { + posFormat: 2, + coverage: this.parsePointer(Parser.coverage), + values: this.parseValueRecordList() + }; + } + check.assert(false, '0x' + start.toString(16) + ': GPOS lookup type 1 format must be 1 or 2.'); + }; + // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable + subtableParsers$1[2] = function parseLookup2() { + var start = this.offset + this.relativeOffset; + var posFormat = this.parseUShort(); + check.assert(posFormat === 1 || posFormat === 2, '0x' + start.toString(16) + ': GPOS lookup type 2 format must be 1 or 2.'); + var coverage = this.parsePointer(Parser.coverage); + var valueFormat1 = this.parseUShort(); + var valueFormat2 = this.parseUShort(); + if (posFormat === 1) { + // Adjustments for Glyph Pairs + return { + posFormat: posFormat, + coverage: coverage, + valueFormat1: valueFormat1, + valueFormat2: valueFormat2, + pairSets: this.parseList(Parser.pointer(Parser.list(function () { + return { + // pairValueRecord + secondGlyph: this.parseUShort(), + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + }))) + }; + } else if (posFormat === 2) { + var classDef1 = this.parsePointer(Parser.classDef); + var classDef2 = this.parsePointer(Parser.classDef); + var class1Count = this.parseUShort(); + var class2Count = this.parseUShort(); + return { + // Class Pair Adjustment + posFormat: posFormat, + coverage: coverage, + valueFormat1: valueFormat1, + valueFormat2: valueFormat2, + classDef1: classDef1, + classDef2: classDef2, + class1Count: class1Count, + class2Count: class2Count, + classRecords: this.parseList(class1Count, Parser.list(class2Count, function () { + return { + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + })) + }; + } + }; + subtableParsers$1[3] = function parseLookup3() { + return { + error: 'GPOS Lookup 3 not supported' + }; + }; + subtableParsers$1[4] = function parseLookup4() { + return { + error: 'GPOS Lookup 4 not supported' + }; + }; + subtableParsers$1[5] = function parseLookup5() { + return { + error: 'GPOS Lookup 5 not supported' + }; + }; + subtableParsers$1[6] = function parseLookup6() { + return { + error: 'GPOS Lookup 6 not supported' + }; + }; + subtableParsers$1[7] = function parseLookup7() { + return { + error: 'GPOS Lookup 7 not supported' + }; + }; + subtableParsers$1[8] = function parseLookup8() { + return { + error: 'GPOS Lookup 8 not supported' + }; + }; + subtableParsers$1[9] = function parseLookup9() { + return { + error: 'GPOS Lookup 9 not supported' + }; + }; + // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos + function parseGposTable(data, start) { + start = start || 0; + var p = new Parser(data, start); + var tableVersion = p.parseVersion(1); + check.argument(tableVersion === 1 || tableVersion === 1.1, 'Unsupported GPOS table version ' + tableVersion); + if (tableVersion === 1) { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers$1) + }; + } else { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers$1), + variations: p.parseFeatureVariationsList() + }; + } + } // GPOS Writing ////////////////////////////////////////////// + // NOT SUPPORTED + + var subtableMakers$1 = new Array(10); + function makeGposTable(gpos) { + return new table.Table('GPOS', [ + { + name: 'version', + type: 'ULONG', + value: 65536 + }, + { + name: 'scripts', + type: 'TABLE', + value: new table.ScriptList(gpos.scripts) + }, + { + name: 'features', + type: 'TABLE', + value: new table.FeatureList(gpos.features) + }, + { + name: 'lookups', + type: 'TABLE', + value: new table.LookupList(gpos.lookups, subtableMakers$1) + } + ]); + } + var gpos = { + parse: parseGposTable, + make: makeGposTable + }; + // The `kern` table contains kerning pairs. + function parseWindowsKernTable(p) { + var pairs = { + }; + // Skip nTables. + p.skip('uShort'); + var subtableVersion = p.parseUShort(); + check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.'); + // Skip subtableLength, subtableCoverage + p.skip('uShort', 2); + var nPairs = p.parseUShort(); + // Skip searchRange, entrySelector, rangeShift. + p.skip('uShort', 3); + for (var i = 0; i < nPairs; i += 1) { + var leftIndex = p.parseUShort(); + var rightIndex = p.parseUShort(); + var value = p.parseShort(); + pairs[leftIndex + ',' + rightIndex] = value; + } + return pairs; + } + function parseMacKernTable(p) { + var pairs = { + }; + // The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits. + // Skip the rest. + p.skip('uShort'); + var nTables = p.parseULong(); + //check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').'); + if (nTables > 1) { + console.warn('Only the first kern subtable is supported.'); + } + p.skip('uLong'); + var coverage = p.parseUShort(); + var subtableVersion = coverage & 255; + p.skip('uShort'); + if (subtableVersion === 0) { + var nPairs = p.parseUShort(); + // Skip searchRange, entrySelector, rangeShift. + p.skip('uShort', 3); + for (var i = 0; i < nPairs; i += 1) { + var leftIndex = p.parseUShort(); + var rightIndex = p.parseUShort(); + var value = p.parseShort(); + pairs[leftIndex + ',' + rightIndex] = value; + } + } + return pairs; + } // Parse the `kern` table which contains kerning pairs. + + function parseKernTable(data, start) { + var p = new parse.Parser(data, start); + var tableVersion = p.parseUShort(); + if (tableVersion === 0) { + return parseWindowsKernTable(p); + } else if (tableVersion === 1) { + return parseMacKernTable(p); + } else { + throw new Error('Unsupported kern table version (' + tableVersion + ').'); + } + } + var kern = { + parse: parseKernTable + }; + // The `loca` table stores the offsets to the locations of the glyphs in the font. + // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font, + // relative to the beginning of the glyphData table. + // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs) + // The loca table has two versions: a short version where offsets are stored as uShorts, and a long + // version where offsets are stored as uLongs. The `head` table specifies which version to use + // (under indexToLocFormat). + function parseLocaTable(data, start, numGlyphs, shortVersion) { + var p = new parse.Parser(data, start); + var parseFn = shortVersion ? p.parseUShort : p.parseULong; + // There is an extra entry after the last index element to compute the length of the last glyph. + // That's why we use numGlyphs + 1. + var glyphOffsets = [ + ]; + for (var i = 0; i < numGlyphs + 1; i += 1) { + var glyphOffset = parseFn.call(p); + if (shortVersion) { + // The short table version stores the actual offset divided by 2. + glyphOffset *= 2; + } + glyphOffsets.push(glyphOffset); + } + return glyphOffsets; + } + var loca = { + parse: parseLocaTable + }; + // opentype.js + /** + * The opentype library. + * @namespace opentype + */ + // File loaders ///////////////////////////////////////////////////////// + /** + * Loads a font from a file. The callback throws an error message as the first parameter if it fails + * and the font as an ArrayBuffer in the second parameter if it succeeds. + * @param {string} path - The path of the file + * @param {Function} callback - The function to call when the font load completes + */ + function loadFromFile(path, callback) { + var fs = _dereq_('fs'); + fs.readFile(path, function (err, buffer) { + if (err) { + return callback(err.message); + } + callback(null, nodeBufferToArrayBuffer(buffer)); + }); + } /** + * Loads a font from a URL. The callback throws an error message as the first parameter if it fails + * and the font as an ArrayBuffer in the second parameter if it succeeds. + * @param {string} url - The URL of the font file. + * @param {Function} callback - The function to call when the font load completes + */ + + function loadFromUrl(url, callback) { + var request = new XMLHttpRequest(); + request.open('get', url, true); + request.responseType = 'arraybuffer'; + request.onload = function () { + if (request.response) { + return callback(null, request.response); + } else { + return callback('Font could not be loaded: ' + request.statusText); + } + }; + request.onerror = function () { + callback('Font could not be loaded'); + }; + request.send(); + } // Table Directory Entries ////////////////////////////////////////////// + /** + * Parses OpenType table entries. + * @param {DataView} + * @param {Number} + * @return {Object[]} + */ + + function parseOpenTypeTableEntries(data, numTables) { + var tableEntries = [ + ]; + var p = 12; + for (var i = 0; i < numTables; i += 1) { + var tag = parse.getTag(data, p); + var checksum = parse.getULong(data, p + 4); + var offset = parse.getULong(data, p + 8); + var length = parse.getULong(data, p + 12); + tableEntries.push({ + tag: tag, + checksum: checksum, + offset: offset, + length: length, + compression: false + }); + p += 16; + } + return tableEntries; + } /** + * Parses WOFF table entries. + * @param {DataView} + * @param {Number} + * @return {Object[]} + */ + + function parseWOFFTableEntries(data, numTables) { + var tableEntries = [ + ]; + var p = 44; // offset to the first table directory entry. + for (var i = 0; i < numTables; i += 1) { + var tag = parse.getTag(data, p); + var offset = parse.getULong(data, p + 4); + var compLength = parse.getULong(data, p + 8); + var origLength = parse.getULong(data, p + 12); + var compression = void 0; + if (compLength < origLength) { + compression = 'WOFF'; + } else { + compression = false; + } + tableEntries.push({ + tag: tag, + offset: offset, + compression: compression, + compressedLength: compLength, + length: origLength + }); + p += 20; + } + return tableEntries; + } /** + * @typedef TableData + * @type Object + * @property {DataView} data - The DataView + * @property {number} offset - The data offset. + */ + /** + * @param {DataView} + * @param {Object} + * @return {TableData} + */ + + function uncompressTable(data, tableEntry) { + if (tableEntry.compression === 'WOFF') { + var inBuffer = new Uint8Array(data.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2); + var outBuffer = new Uint8Array(tableEntry.length); + tinyInflate(inBuffer, outBuffer); + if (outBuffer.byteLength !== tableEntry.length) { + throw new Error('Decompression error: ' + tableEntry.tag + ' decompressed length doesn\'t match recorded length'); + } + var view = new DataView(outBuffer.buffer, 0); + return { + data: view, + offset: 0 + }; + } else { + return { + data: data, + offset: tableEntry.offset + }; + } + } // Public API /////////////////////////////////////////////////////////// + /** + * Parse the OpenType file data (as an ArrayBuffer) and return a Font object. + * Throws an error if the font could not be parsed. + * @param {ArrayBuffer} + * @return {opentype.Font} + */ + + function parseBuffer(buffer) { + var indexToLocFormat; + var ltagTable; + // Since the constructor can also be called to create new fonts from scratch, we indicate this + // should be an empty font that we'll fill with our own data. + var font = new Font({ + empty: true + }); + // OpenType fonts use big endian byte ordering. + // We can't rely on typed array view types, because they operate with the endianness of the host computer. + // Instead we use DataViews where we can specify endianness. + var data = new DataView(buffer, 0); + var numTables; + var tableEntries = [ + ]; + var signature = parse.getTag(data, 0); + if (signature === String.fromCharCode(0, 1, 0, 0) || signature === 'true' || signature === 'typ1') { + font.outlinesFormat = 'truetype'; + numTables = parse.getUShort(data, 4); + tableEntries = parseOpenTypeTableEntries(data, numTables); + } else if (signature === 'OTTO') { + font.outlinesFormat = 'cff'; + numTables = parse.getUShort(data, 4); + tableEntries = parseOpenTypeTableEntries(data, numTables); + } else if (signature === 'wOFF') { + var flavor = parse.getTag(data, 4); + if (flavor === String.fromCharCode(0, 1, 0, 0)) { + font.outlinesFormat = 'truetype'; + } else if (flavor === 'OTTO') { + font.outlinesFormat = 'cff'; + } else { + throw new Error('Unsupported OpenType flavor ' + signature); + } + numTables = parse.getUShort(data, 12); + tableEntries = parseWOFFTableEntries(data, numTables); + } else { + throw new Error('Unsupported OpenType signature ' + signature); + } + var cffTableEntry; + var fvarTableEntry; + var glyfTableEntry; + var gposTableEntry; + var gsubTableEntry; + var hmtxTableEntry; + var kernTableEntry; + var locaTableEntry; + var nameTableEntry; + var metaTableEntry; + var p; + for (var i = 0; i < numTables; i += 1) { + var tableEntry = tableEntries[i]; + var table = void 0; + switch (tableEntry.tag) { + case 'cmap': + table = uncompressTable(data, tableEntry); + font.tables.cmap = cmap.parse(table.data, table.offset); + font.encoding = new CmapEncoding(font.tables.cmap); + break; + case 'cvt ': + table = uncompressTable(data, tableEntry); + p = new parse.Parser(table.data, table.offset); + font.tables.cvt = p.parseShortList(tableEntry.length / 2); + break; + case 'fvar': + fvarTableEntry = tableEntry; + break; + case 'fpgm': + table = uncompressTable(data, tableEntry); + p = new parse.Parser(table.data, table.offset); + font.tables.fpgm = p.parseByteList(tableEntry.length); + break; + case 'head': + table = uncompressTable(data, tableEntry); + font.tables.head = head.parse(table.data, table.offset); + font.unitsPerEm = font.tables.head.unitsPerEm; + indexToLocFormat = font.tables.head.indexToLocFormat; + break; + case 'hhea': + table = uncompressTable(data, tableEntry); + font.tables.hhea = hhea.parse(table.data, table.offset); + font.ascender = font.tables.hhea.ascender; + font.descender = font.tables.hhea.descender; + font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics; + break; + case 'hmtx': + hmtxTableEntry = tableEntry; + break; + case 'ltag': + table = uncompressTable(data, tableEntry); + ltagTable = ltag.parse(table.data, table.offset); + break; + case 'maxp': + table = uncompressTable(data, tableEntry); + font.tables.maxp = maxp.parse(table.data, table.offset); + font.numGlyphs = font.tables.maxp.numGlyphs; + break; + case 'name': + nameTableEntry = tableEntry; + break; + case 'OS/2': + table = uncompressTable(data, tableEntry); + font.tables.os2 = os2.parse(table.data, table.offset); + break; + case 'post': + table = uncompressTable(data, tableEntry); + font.tables.post = post.parse(table.data, table.offset); + font.glyphNames = new GlyphNames(font.tables.post); + break; + case 'prep': + table = uncompressTable(data, tableEntry); + p = new parse.Parser(table.data, table.offset); + font.tables.prep = p.parseByteList(tableEntry.length); + break; + case 'glyf': + glyfTableEntry = tableEntry; + break; + case 'loca': + locaTableEntry = tableEntry; + break; + case 'CFF ': + cffTableEntry = tableEntry; + break; + case 'kern': + kernTableEntry = tableEntry; + break; + case 'GPOS': + gposTableEntry = tableEntry; + break; + case 'GSUB': + gsubTableEntry = tableEntry; + break; + case 'meta': + metaTableEntry = tableEntry; + break; + } + } + var nameTable = uncompressTable(data, nameTableEntry); + font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable); + font.names = font.tables.name; + if (glyfTableEntry && locaTableEntry) { + var shortVersion = indexToLocFormat === 0; + var locaTable = uncompressTable(data, locaTableEntry); + var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion); + var glyfTable = uncompressTable(data, glyfTableEntry); + font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font); + } else if (cffTableEntry) { + var cffTable = uncompressTable(data, cffTableEntry); + cff.parse(cffTable.data, cffTable.offset, font); + } else { + throw new Error('Font doesn\'t contain TrueType or CFF outlines.'); + } + var hmtxTable = uncompressTable(data, hmtxTableEntry); + hmtx.parse(hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs); + addGlyphNames(font); + if (kernTableEntry) { + var kernTable = uncompressTable(data, kernTableEntry); + font.kerningPairs = kern.parse(kernTable.data, kernTable.offset); + } else { + font.kerningPairs = { + }; + } + if (gposTableEntry) { + var gposTable = uncompressTable(data, gposTableEntry); + font.tables.gpos = gpos.parse(gposTable.data, gposTable.offset); + font.position.init(); + } + if (gsubTableEntry) { + var gsubTable = uncompressTable(data, gsubTableEntry); + font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset); + } + if (fvarTableEntry) { + var fvarTable = uncompressTable(data, fvarTableEntry); + font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names); + } + if (metaTableEntry) { + var metaTable = uncompressTable(data, metaTableEntry); + font.tables.meta = meta.parse(metaTable.data, metaTable.offset); + font.metas = font.tables.meta; + } + return font; + } /** + * Asynchronously load the font from a URL or a filesystem. When done, call the callback + * with two arguments `(err, font)`. The `err` will be null on success, + * the `font` is a Font object. + * We use the node.js callback convention so that + * opentype.js can integrate with frameworks like async.js. + * @alias opentype.load + * @param {string} url - The URL of the font to load. + * @param {Function} callback - The callback. + */ + + function load(url, callback) { + var isNode$$1 = typeof window === 'undefined'; + var loadFn = isNode$$1 ? loadFromFile : loadFromUrl; + loadFn(url, function (err, arrayBuffer) { + if (err) { + return callback(err); + } + var font; + try { + font = parseBuffer(arrayBuffer); + } catch (e) { + return callback(e, null); + } + return callback(null, font); + }); + } /** + * Synchronously load the font from a URL or file. + * When done, returns the font object or throws an error. + * @alias opentype.loadSync + * @param {string} url - The URL of the font to load. + * @return {opentype.Font} + */ + + function loadSync(url) { + var fs = _dereq_('fs'); + var buffer = fs.readFileSync(url); + return parseBuffer(nodeBufferToArrayBuffer(buffer)); + } + exports.Font = Font; + exports.Glyph = Glyph; + exports.Path = Path; + exports.BoundingBox = BoundingBox; + exports._parse = parse; + exports.parse = parseBuffer; + exports.load = load; + exports.loadSync = loadSync; + Object.defineProperty(exports, '__esModule', { + value: true + }); + }); + }).call(this, _dereq_('buffer').Buffer) + }, + { + 'buffer': 22, + 'fs': 21 + } + ], + 277: [ + function (_dereq_, module, exports) { + (function (process) { + // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1, + // backported and transplited with Babel, with backwards-compat fixes + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + // resolves . and .. elements in a path array with directory names there + // must be no slashes, empty elements, or device names (c:\) in the array + // (so also no leading and trailing slashes - it does not distinguish + // relative and absolute paths) + function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } // if the path is allowed to go above the root, restore leading ..s + + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + return parts; + } // path.resolve([from ...], to) + // posix version + + exports.resolve = function () { + var resolvedPath = '', + resolvedAbsolute = false; + for (var i = arguments.length - 1; i >= - 1 && !resolvedAbsolute; i--) { + var path = i >= 0 ? arguments[i] : process.cwd(); + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + // Normalize the path + + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function (p) { + return !!p; + }), !resolvedAbsolute).join('/'); + return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; + }; + // path.normalize(path) + // posix version + exports.normalize = function (path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, - 1) === '/'; + // Normalize the path + path = normalizeArray(filter(path.split('/'), function (p) { + return !!p; + }), !isAbsolute).join('/'); + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + return (isAbsolute ? '/' : '') + path; + }; + // posix version + exports.isAbsolute = function (path) { + return path.charAt(0) === '/'; + }; + // posix version + exports.join = function () { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function (p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); + }; + // path.relative(from, to) + // posix version + exports.relative = function (from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + var outputParts = [ + ]; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + return outputParts.join('/'); + }; + exports.sep = '/'; + exports.delimiter = ':'; + exports.dirname = function (path) { + if (typeof path !== 'string') path = path + ''; + if (path.length === 0) return '.'; + var code = path.charCodeAt(0); + var hasRoot = code === 47 /*/*/ ; + var end = - 1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/ ) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + if (end === - 1) return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) { + // return '//'; + // Backwards-compat fix: + return '/'; + } + return path.slice(0, end); + }; + function basename(path) { + if (typeof path !== 'string') path = path + ''; + var start = 0; + var end = - 1; + var matchedSlash = true; + var i; + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47 /*/*/ ) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === - 1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + if (end === - 1) return ''; + return path.slice(start, end); + } // Uses a mixed approach for backwards-compatibility, as ext behavior changed + // in new Node.js versions, so only basename() above is backported here + + exports.basename = function (path, ext) { + var f = basename(path); + if (ext && f.substr( - 1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; + }; + exports.extname = function (path) { + if (typeof path !== 'string') path = path + ''; + var startDot = - 1; + var startPart = 0; + var end = - 1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/ ) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === - 1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/ ) { + // If this is our first dot, mark it as the start of our extension + if (startDot === - 1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== - 1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = - 1; + } + } + if (startDot === - 1 || end === - 1 || // We saw a non-dot character immediately before the dot + preDotState === 0 || // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); + }; + function filter(xs, f) { + if (xs.filter) return xs.filter(f); + var res = [ + ]; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; + } // String.prototype.substr - negative index don't work in IE8 + + var substr = 'ab'.substr( - 1) === 'b' ? function (str, start, len) { + return str.substr(start, len); + } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + }; + }).call(this, _dereq_('_process')) + }, + { + '_process': 278 + } + ], + 278: [ + function (_dereq_, module, exports) { + // shim for using process in browser + var process = module.exports = { + }; + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + var cachedSetTimeout; + var cachedClearTimeout; + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined'); + }(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + }) (); + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } // if setTimeout wasn't available but was latter defined + + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } // if clearTimeout wasn't available but was latter defined + + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + } + var queue = [ + ]; + var draining = false; + var currentQueue; + var queueIndex = - 1; + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = - 1; + } + if (queue.length) { + drainQueue(); + } + } + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while (len) { + currentQueue = queue; + queue = [ + ]; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = - 1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = { + }; + process.argv = [ + ]; + process.version = ''; // empty string to avoid regexp issues + process.versions = { + }; + function noop() { + } + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + process.listeners = function (name) { + return []; + }; + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + process.cwd = function () { + return '/'; + }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function () { + return 0; + }; + }, + { + } + ], + 279: [ + function (_dereq_, module, exports) { + /** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + var runtime = function (exports) { + 'use strict'; + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === 'function' ? Symbol : { + }; + var iteratorSymbol = $Symbol.iterator || '@@iterator'; + var asyncIteratorSymbol = $Symbol.asyncIterator || '@@asyncIterator'; + var toStringTagSymbol = $Symbol.toStringTag || '@@toStringTag'; + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || [ + ]); + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + return generator; + } + exports.wrap = wrap; + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { + type: 'normal', + arg: fn.call(obj, arg) + }; + } catch (err) { + return { + type: 'throw', + arg: err + }; + } + } + var GenStateSuspendedStart = 'suspendedStart'; + var GenStateSuspendedYield = 'suspendedYield'; + var GenStateExecuting = 'executing'; + var GenStateCompleted = 'completed'; + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = { + }; + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() { + } + function GeneratorFunction() { + } + function GeneratorFunctionPrototype() { + } // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + + var IteratorPrototype = { + }; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = 'GeneratorFunction'; + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + [ + 'next', + 'throw', + 'return' + ].forEach(function (method) { + prototype[method] = function (arg) { + return this._invoke(method, arg); + }; + }); + } + exports.isGeneratorFunction = function (genFun) { + var ctor = typeof genFun === 'function' && genFun.constructor; + return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === 'GeneratorFunction' : false; + }; + exports.mark = function (genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = 'GeneratorFunction'; + } + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function (arg) { + return { + __await: arg + }; + }; + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === 'throw') { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && typeof value === 'object' && hasOwn.call(value, '__await')) { + return Promise.resolve(value.__await).then(function (value) { + invoke('next', value, resolve, reject); + }, function (err) { + invoke('throw', err, resolve, reject); + }); + } + return Promise.resolve(value).then(function (unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function (error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke('throw', error, resolve, reject); + }); + } + } + var previousPromise; + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function (resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + return previousPromise = // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + } // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + + this._invoke = enqueue; + } + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + exports.AsyncIterator = AsyncIterator; + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function (innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList)); + return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); + }; + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error('Generator is already running'); + } + if (state === GenStateCompleted) { + if (method === 'throw') { + throw arg; + } // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + + return doneResult(); + } + context.method = method; + context.arg = arg; + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + if (context.method === 'next') { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + } else if (context.method === 'throw') { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + context.dispatchException(context.arg); + } else if (context.method === 'return') { + context.abrupt('return', context.arg); + } + state = GenStateExecuting; + var record = tryCatch(innerFn, self, context); + if (record.type === 'normal') { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done ? GenStateCompleted : GenStateSuspendedYield; + if (record.arg === ContinueSentinel) { + continue; + } + return { + value: record.arg, + done: context.done + }; + } else if (record.type === 'throw') { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = 'throw'; + context.arg = record.arg; + } + } + }; + } // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + if (context.method === 'throw') { + // Note: ["return"] must be used for ES3 parsing compatibility. + if (delegate.iterator['return']) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = 'return'; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + if (context.method === 'throw') { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + context.method = 'throw'; + context.arg = new TypeError('The iterator does not provide a \'throw\' method'); + } + return ContinueSentinel; + } + var record = tryCatch(method, delegate.iterator, context.arg); + if (record.type === 'throw') { + context.method = 'throw'; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + var info = record.arg; + if (!info) { + context.method = 'throw'; + context.arg = new TypeError('iterator result is not an object'); + context.delegate = null; + return ContinueSentinel; + } + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== 'return') { + context.method = 'next'; + context.arg = undefined; + } + } else { + // Re-yield the result returned by the delegate method. + return info; + } // The delegate iterator is finished, so forget it and continue with + // the outer generator. + + context.delegate = null; + return ContinueSentinel; + } // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + + defineIteratorMethods(Gp); + Gp[toStringTagSymbol] = 'Generator'; + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function () { + return this; + }; + Gp.toString = function () { + return '[object Generator]'; + }; + function pushTryEntry(locs) { + var entry = { + tryLoc: locs[0] + }; + if (1 in locs) { + entry.catchLoc = locs[1]; + } + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + this.tryEntries.push(entry); + } + function resetTryEntry(entry) { + var record = entry.completion || { + }; + record.type = 'normal'; + delete record.arg; + entry.completion = record; + } + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [ + { + tryLoc: 'root' + } + ]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + exports.keys = function (object) { + var keys = [ + ]; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + + next.done = true; + return next; + }; + }; + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + if (typeof iterable.next === 'function') { + return iterable; + } + if (!isNaN(iterable.length)) { + var i = - 1, + next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + next.value = undefined; + next.done = true; + return next; + }; + return next.next = next; + } + } // Return an iterator with no values. + + return { + next: doneResult + }; + } + exports.values = values; + function doneResult() { + return { + value: undefined, + done: true + }; + } + Context.prototype = { + constructor: Context, + reset: function (skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + this.method = 'next'; + this.arg = undefined; + this.tryEntries.forEach(resetTryEntry); + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === 't' && hasOwn.call(this, name) && !isNaN( + name.slice(1))) { + this[name] = undefined; + } + } + } + }, + stop: function () { + this.done = true; + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === 'throw') { + throw rootRecord.arg; + } + return this.rval; + }, + dispatchException: function (exception) { + if (this.done) { + throw exception; + } + var context = this; + function handle(loc, caught) { + record.type = 'throw'; + record.arg = exception; + context.next = loc; + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = 'next'; + context.arg = undefined; + } + return !!caught; + } + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + if (entry.tryLoc === 'root') { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle('end'); + } + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, 'catchLoc'); + var hasFinally = hasOwn.call(entry, 'finallyLoc'); + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + } else { + throw new Error('try statement without catch or finally'); + } + } + } + }, + abrupt: function (type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && hasOwn.call(entry, 'finallyLoc') && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + if (finallyEntry && (type === 'break' || type === 'continue') && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + var record = finallyEntry ? finallyEntry.completion : { + }; + record.type = type; + record.arg = arg; + if (finallyEntry) { + this.method = 'next'; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + return this.complete(record); + }, + complete: function (record, afterLoc) { + if (record.type === 'throw') { + throw record.arg; + } + if (record.type === 'break' || record.type === 'continue') { + this.next = record.arg; + } else if (record.type === 'return') { + this.rval = this.arg = record.arg; + this.method = 'return'; + this.next = 'end'; + } else if (record.type === 'normal' && afterLoc) { + this.next = afterLoc; + } + return ContinueSentinel; + }, + finish: function (finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + 'catch': function (tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === 'throw') { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + + throw new Error('illegal catch attempt'); + }, + delegateYield: function (iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + if (this.method === 'next') { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + return ContinueSentinel; + } + }; + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; + }( // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + typeof module === 'object' ? module.exports : { + }); + try { + regeneratorRuntime = runtime; + } catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + Function('r', 'regeneratorRuntime = r') (runtime); + } + }, + { + } + ], + 280: [ + function (_dereq_, module, exports) { + (function (self) { + 'use strict'; + if (self.fetch) { + return; + } + var support = { + searchParams: 'URLSearchParams' in self, + iterable: 'Symbol' in self && 'iterator' in Symbol, + blob: 'FileReader' in self && 'Blob' in self && function () { + try { + new Blob(); + return true; + } catch (e) { + return false; + } + }(), + formData: 'FormData' in self, + arrayBuffer: 'ArrayBuffer' in self + }; + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[object Float32Array]', + '[object Float64Array]' + ]; + var isDataView = function (obj) { + return obj && DataView.prototype.isPrototypeOf(obj); + }; + var isArrayBufferView = ArrayBuffer.isView || function (obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > - 1; + }; + } + function normalizeName(name) { + if (typeof name !== 'string') { + name = String(name); + } + if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { + throw new TypeError('Invalid character in header field name'); + } + return name.toLowerCase(); + } + function normalizeValue(value) { + if (typeof value !== 'string') { + value = String(value); + } + return value; + } // Build a destructive iterator for the value list + + function iteratorFor(items) { + var iterator = { + next: function () { + var value = items.shift(); + return { + done: value === undefined, + value: value + }; + } + }; + if (support.iterable) { + iterator[Symbol.iterator] = function () { + return iterator; + }; + } + return iterator; + } + function Headers(headers) { + this.map = { + }; + if (headers instanceof Headers) { + headers.forEach(function (value, name) { + this.append(name, value); + }, this); + } else if (Array.isArray(headers)) { + headers.forEach(function (header) { + this.append(header[0], header[1]); + }, this); + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function (name) { + this.append(name, headers[name]); + }, this); + } + } + Headers.prototype.append = function (name, value) { + name = normalizeName(name); + value = normalizeValue(value); + var oldValue = this.map[name]; + this.map[name] = oldValue ? oldValue + ',' + value : value; + }; + Headers.prototype['delete'] = function (name) { + delete this.map[normalizeName(name)]; + }; + Headers.prototype.get = function (name) { + name = normalizeName(name); + return this.has(name) ? this.map[name] : null; + }; + Headers.prototype.has = function (name) { + return this.map.hasOwnProperty(normalizeName(name)); + }; + Headers.prototype.set = function (name, value) { + this.map[normalizeName(name)] = normalizeValue(value); + }; + Headers.prototype.forEach = function (callback, thisArg) { + for (var name in this.map) { + if (this.map.hasOwnProperty(name)) { + callback.call(thisArg, this.map[name], name, this); + } + } + }; + Headers.prototype.keys = function () { + var items = [ + ]; + this.forEach(function (value, name) { + items.push(name); + }); + return iteratorFor(items); + }; + Headers.prototype.values = function () { + var items = [ + ]; + this.forEach(function (value) { + items.push(value); + }); + return iteratorFor(items); + }; + Headers.prototype.entries = function () { + var items = [ + ]; + this.forEach(function (value, name) { + items.push([name, + value]); + }); + return iteratorFor(items); + }; + if (support.iterable) { + Headers.prototype[Symbol.iterator] = Headers.prototype.entries; + } + function consumed(body) { + if (body.bodyUsed) { + return Promise.reject(new TypeError('Already read')); + } + body.bodyUsed = true; + } + function fileReaderReady(reader) { + return new Promise(function (resolve, reject) { + reader.onload = function () { + resolve(reader.result); + }; + reader.onerror = function () { + reject(reader.error); + }; + }); + } + function readBlobAsArrayBuffer(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsArrayBuffer(blob); + return promise; + } + function readBlobAsText(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsText(blob); + return promise; + } + function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf); + var chars = new Array(view.length); + for (var i = 0; i < view.length; i++) { + chars[i] = String.fromCharCode(view[i]); + } + return chars.join(''); + } + function bufferClone(buf) { + if (buf.slice) { + return buf.slice(0); + } else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer; + } + } + function Body() { + this.bodyUsed = false; + this._initBody = function (body) { + this._bodyInit = body; + if (!body) { + this._bodyText = ''; + } else if (typeof body === 'string') { + this._bodyText = body; + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body; + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body; + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString(); + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body); + } else { + throw new Error('unsupported BodyInit type'); + } + if (!this.headers.get('content-type')) { + if (typeof body === 'string') { + this.headers.set('content-type', 'text/plain;charset=UTF-8'); + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type); + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + } + }; + if (support.blob) { + this.blob = function () { + var rejected = consumed(this); + if (rejected) { + return rejected; + } + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob); + } else if (this._bodyArrayBuffer) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])); + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob'); + } else { + return Promise.resolve(new Blob([this._bodyText])); + } + }; + this.arrayBuffer = function () { + if (this._bodyArrayBuffer) { + return consumed(this) || Promise.resolve(this._bodyArrayBuffer); + } else { + return this.blob().then(readBlobAsArrayBuffer); + } + }; + } + this.text = function () { + var rejected = consumed(this); + if (rejected) { + return rejected; + } + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob); + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)); + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text'); + } else { + return Promise.resolve(this._bodyText); + } + }; + if (support.formData) { + this.formData = function () { + return this.text().then(decode); + }; + } + this.json = function () { + return this.text().then(JSON.parse); + }; + return this; + } // HTTP methods whose capitalization should be normalized + + var methods = [ + 'DELETE', + 'GET', + 'HEAD', + 'OPTIONS', + 'POST', + 'PUT' + ]; + function normalizeMethod(method) { + var upcased = method.toUpperCase(); + return methods.indexOf(upcased) > - 1 ? upcased : method; + } + function Request(input, options) { + options = options || { + }; + var body = options.body; + if (input instanceof Request) { + if (input.bodyUsed) { + throw new TypeError('Already read'); + } + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) { + this.headers = new Headers(input.headers); + } + this.method = input.method; + this.mode = input.mode; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else { + this.url = String(input); + } + this.credentials = options.credentials || this.credentials || 'omit'; + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers); + } + this.method = normalizeMethod(options.method || this.method || 'GET'); + this.mode = options.mode || this.mode || null; + this.referrer = null; + if ((this.method === 'GET' || this.method === 'HEAD') && body) { + throw new TypeError('Body not allowed for GET or HEAD requests'); + } + this._initBody(body); + } + Request.prototype.clone = function () { + return new Request(this, { + body: this._bodyInit + }); + }; + function decode(body) { + var form = new FormData(); + body.trim().split('&').forEach(function (bytes) { + if (bytes) { + var split = bytes.split('='); + var name = split.shift().replace(/\+/g, ' '); + var value = split.join('=').replace(/\+/g, ' '); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + return form; + } + function parseHeaders(rawHeaders) { + var headers = new Headers(); + // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space + // https://tools.ietf.org/html/rfc7230#section-3.2 + var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); + preProcessedHeaders.split(/\r?\n/).forEach(function (line) { + var parts = line.split(':'); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(':').trim(); + headers.append(key, value); + } + }); + return headers; + } + Body.call(Request.prototype); + function Response(bodyInit, options) { + if (!options) { + options = { + }; + } + this.type = 'default'; + this.status = options.status === undefined ? 200 : options.status; + this.ok = this.status >= 200 && this.status < 300; + this.statusText = 'statusText' in options ? options.statusText : 'OK'; + this.headers = new Headers(options.headers); + this.url = options.url || ''; + this._initBody(bodyInit); + } + Body.call(Response.prototype); + Response.prototype.clone = function () { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + url: this.url + }); + }; + Response.error = function () { + var response = new Response(null, { + status: 0, + statusText: '' + }); + response.type = 'error'; + return response; + }; + var redirectStatuses = [ + 301, + 302, + 303, + 307, + 308 + ]; + Response.redirect = function (url, status) { + if (redirectStatuses.indexOf(status) === - 1) { + throw new RangeError('Invalid status code'); + } + return new Response(null, { + status: status, + headers: { + location: url + } + }); + }; + self.Headers = Headers; + self.Request = Request; + self.Response = Response; + self.fetch = function (input, init) { + return new Promise(function (resolve, reject) { + var request = new Request(input, init); + var xhr = new XMLHttpRequest(); + xhr.onload = function () { + var options = { + status: xhr.status, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + }; + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); + var body = 'response' in xhr ? xhr.response : xhr.responseText; + resolve(new Response(body, options)); + }; + xhr.onerror = function () { + reject(new TypeError('Network request failed')); + }; + xhr.ontimeout = function () { + reject(new TypeError('Network request failed')); + }; + xhr.open(request.method, request.url, true); + if (request.credentials === 'include') { + xhr.withCredentials = true; + } else if (request.credentials === 'omit') { + xhr.withCredentials = false; + } + if ('responseType' in xhr && support.blob) { + xhr.responseType = 'blob'; + } + request.headers.forEach(function (value, name) { + xhr.setRequestHeader(name, value); + }); + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); + }); + }; + self.fetch.polyfill = true; + }) (typeof self !== 'undefined' ? self : this); + }, + { + } + ], + 281: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.split'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var _color_conversion = _interopRequireDefault(_dereq_('../color/color_conversion')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Environment + * @submodule Environment + * @for p5 + * @requires core + */ + //stores the original hsb values + + var originalHSB; + //stores values for color name exceptions + var colorExceptions = [ + { + h: 0, + s: 0, + b: 0.8275, + name: 'gray' + }, + { + h: 0, + s: 0, + b: 0.8627, + name: 'gray' + }, + { + h: 0, + s: 0, + b: 0.7529, + name: 'gray' + }, + { + h: 0.0167, + s: 0.1176, + b: 1, + name: 'light pink' + } + ]; + //stores values for color names + var colorLookUp = [ + { + h: 0, + s: 0, + b: 0, + name: 'black' + }, + { + h: 0, + s: 0, + b: 0.5, + name: 'gray' + }, + { + h: 0, + s: 0, + b: 1, + name: 'white' + }, + { + h: 0, + s: 0.5, + b: 0.5, + name: 'dark maroon' + }, + { + h: 0, + s: 0.5, + b: 1, + name: 'salmon pink' + }, + { + h: 0, + s: 1, + b: 0, + name: 'black' + }, + { + h: 0, + s: 1, + b: 0.5, + name: 'dark red' + }, + { + h: 0, + s: 1, + b: 1, + name: 'red' + }, + { + h: 5, + s: 0, + b: 1, + name: 'very light peach' + }, + { + h: 5, + s: 0.5, + b: 0.5, + name: 'brown' + }, + { + h: 5, + s: 0.5, + b: 1, + name: 'peach' + }, + { + h: 5, + s: 1, + b: 0.5, + name: 'brick red' + }, + { + h: 5, + s: 1, + b: 1, + name: 'crimson' + }, + { + h: 10, + s: 0, + b: 1, + name: 'light peach' + }, + { + h: 10, + s: 0.5, + b: 0.5, + name: 'brown' + }, + { + h: 10, + s: 0.5, + b: 1, + name: 'light orange' + }, + { + h: 10, + s: 1, + b: 0.5, + name: 'brown' + }, + { + h: 10, + s: 1, + b: 1, + name: 'orange' + }, + { + h: 15, + s: 0, + b: 1, + name: 'very light yellow' + }, + { + h: 15, + s: 0.5, + b: 0.5, + name: 'olive green' + }, + { + h: 15, + s: 0.5, + b: 1, + name: 'light yellow' + }, + { + h: 15, + s: 1, + b: 0, + name: 'dark olive green' + }, + { + h: 15, + s: 1, + b: 0.5, + name: 'olive green' + }, + { + h: 15, + s: 1, + b: 1, + name: 'yellow' + }, + { + h: 20, + s: 0, + b: 1, + name: 'very light yellow' + }, + { + h: 20, + s: 0.5, + b: 0.5, + name: 'olive green' + }, + { + h: 20, + s: 0.5, + b: 1, + name: 'light yellow green' + }, + { + h: 20, + s: 1, + b: 0, + name: 'dark olive green' + }, + { + h: 20, + s: 1, + b: 0.5, + name: 'dark yellow green' + }, + { + h: 20, + s: 1, + b: 1, + name: 'yellow green' + }, + { + h: 25, + s: 0.5, + b: 0.5, + name: 'dark yellow green' + }, + { + h: 25, + s: 0.5, + b: 1, + name: 'light green' + }, + { + h: 25, + s: 1, + b: 0.5, + name: 'dark green' + }, + { + h: 25, + s: 1, + b: 1, + name: 'green' + }, + { + h: 30, + s: 0.5, + b: 1, + name: 'light green' + }, + { + h: 30, + s: 1, + b: 0.5, + name: 'dark green' + }, + { + h: 30, + s: 1, + b: 1, + name: 'green' + }, + { + h: 35, + s: 0, + b: 0.5, + name: 'light green' + }, + { + h: 35, + s: 0, + b: 1, + name: 'very light green' + }, + { + h: 35, + s: 0.5, + b: 0.5, + name: 'dark green' + }, + { + h: 35, + s: 0.5, + b: 1, + name: 'light green' + }, + { + h: 35, + s: 1, + b: 0, + name: 'very dark green' + }, + { + h: 35, + s: 1, + b: 0.5, + name: 'dark green' + }, + { + h: 35, + s: 1, + b: 1, + name: 'green' + }, + { + h: 40, + s: 0, + b: 1, + name: 'very light green' + }, + { + h: 40, + s: 0.5, + b: 0.5, + name: 'dark green' + }, + { + h: 40, + s: 0.5, + b: 1, + name: 'light green' + }, + { + h: 40, + s: 1, + b: 0.5, + name: 'dark green' + }, + { + h: 40, + s: 1, + b: 1, + name: 'green' + }, + { + h: 45, + s: 0.5, + b: 1, + name: 'light turquoise' + }, + { + h: 45, + s: 1, + b: 0.5, + name: 'dark turquoise' + }, + { + h: 45, + s: 1, + b: 1, + name: 'turquoise' + }, + { + h: 50, + s: 0, + b: 1, + name: 'light sky blue' + }, + { + h: 50, + s: 0.5, + b: 0.5, + name: 'dark cyan' + }, + { + h: 50, + s: 0.5, + b: 1, + name: 'light cyan' + }, + { + h: 50, + s: 1, + b: 0.5, + name: 'dark cyan' + }, + { + h: 50, + s: 1, + b: 1, + name: 'cyan' + }, + { + h: 55, + s: 0, + b: 1, + name: 'light sky blue' + }, + { + h: 55, + s: 0.5, + b: 1, + name: 'light sky blue' + }, + { + h: 55, + s: 1, + b: 0.5, + name: 'dark blue' + }, + { + h: 55, + s: 1, + b: 1, + name: 'sky blue' + }, + { + h: 60, + s: 0, + b: 0.5, + name: 'gray' + }, + { + h: 60, + s: 0, + b: 1, + name: 'very light blue' + }, + { + h: 60, + s: 0.5, + b: 0.5, + name: 'blue' + }, + { + h: 60, + s: 0.5, + b: 1, + name: 'light blue' + }, + { + h: 60, + s: 1, + b: 0.5, + name: 'navy blue' + }, + { + h: 60, + s: 1, + b: 1, + name: 'blue' + }, + { + h: 65, + s: 0, + b: 1, + name: 'lavender' + }, + { + h: 65, + s: 0.5, + b: 0.5, + name: 'navy blue' + }, + { + h: 65, + s: 0.5, + b: 1, + name: 'light purple' + }, + { + h: 65, + s: 1, + b: 0.5, + name: 'dark navy blue' + }, + { + h: 65, + s: 1, + b: 1, + name: 'blue' + }, + { + h: 70, + s: 0, + b: 1, + name: 'lavender' + }, + { + h: 70, + s: 0.5, + b: 0.5, + name: 'navy blue' + }, + { + h: 70, + s: 0.5, + b: 1, + name: 'lavender blue' + }, + { + h: 70, + s: 1, + b: 0.5, + name: 'dark navy blue' + }, + { + h: 70, + s: 1, + b: 1, + name: 'blue' + }, + { + h: 75, + s: 0.5, + b: 1, + name: 'lavender' + }, + { + h: 75, + s: 1, + b: 0.5, + name: 'dark purple' + }, + { + h: 75, + s: 1, + b: 1, + name: 'purple' + }, + { + h: 80, + s: 0.5, + b: 1, + name: 'pinkish purple' + }, + { + h: 80, + s: 1, + b: 0.5, + name: 'dark purple' + }, + { + h: 80, + s: 1, + b: 1, + name: 'purple' + }, + { + h: 85, + s: 0, + b: 1, + name: 'light pink' + }, + { + h: 85, + s: 0.5, + b: 0.5, + name: 'purple' + }, + { + h: 85, + s: 0.5, + b: 1, + name: 'light fuchsia' + }, + { + h: 85, + s: 1, + b: 0.5, + name: 'dark fuchsia' + }, + { + h: 85, + s: 1, + b: 1, + name: 'fuchsia' + }, + { + h: 90, + s: 0.5, + b: 0.5, + name: 'dark fuchsia' + }, + { + h: 90, + s: 0.5, + b: 1, + name: 'hot pink' + }, + { + h: 90, + s: 1, + b: 0.5, + name: 'dark fuchsia' + }, + { + h: 90, + s: 1, + b: 1, + name: 'fuchsia' + }, + { + h: 95, + s: 0, + b: 1, + name: 'pink' + }, + { + h: 95, + s: 0.5, + b: 1, + name: 'light pink' + }, + { + h: 95, + s: 1, + b: 0.5, + name: 'dark magenta' + }, + { + h: 95, + s: 1, + b: 1, + name: 'magenta' + } + ]; + //returns text with color name + function _calculateColor(hsb) { + var colortext; + //round hue + if (hsb[0] !== 0) { + hsb[0] = Math.round(hsb[0] * 100); + var hue = hsb[0].toString().split(''); + var last = hue.length - 1; + hue[last] = parseInt(hue[last]); + //if last digit of hue is < 2.5 make it 0 + if (hue[last] < 2.5) { + hue[last] = 0; + //if last digit of hue is >= 2.5 and less than 7.5 make it 5 + } else if (hue[last] >= 2.5 && hue[last] < 7.5) { + hue[last] = 5; + } //if hue only has two digits + + if (hue.length === 2) { + hue[0] = parseInt(hue[0]); + //if last is greater than 7.5 + if (hue[last] >= 7.5) { + //add one to the tens + hue[last] = 0; + hue[0] = hue[0] + 1; + } + hsb[0] = hue[0] * 10 + hue[1]; + } else { + if (hue[last] >= 7.5) { + hsb[0] = 10; + } else { + hsb[0] = hue[last]; + } + } + } //map brightness from 0 to 1 + + hsb[2] = hsb[2] / 255; + //round saturation and brightness + for (var i = hsb.length - 1; i >= 1; i--) { + if (hsb[i] <= 0.25) { + hsb[i] = 0; + } else if (hsb[i] > 0.25 && hsb[i] < 0.75) { + hsb[i] = 0.5; + } else { + hsb[i] = 1; + } + } //after rounding, if the values are hue 0, saturation 0 and brightness 1 + //look at color exceptions which includes several tones from white to gray + + if (hsb[0] === 0 && hsb[1] === 0 && hsb[2] === 1) { + //round original hsb values + for (var _i = 2; _i >= 0; _i--) { + originalHSB[_i] = Math.round(originalHSB[_i] * 10000) / 10000; + } //compare with the values in the colorExceptions array + + for (var e = 0; e < colorExceptions.length; e++) { + if (colorExceptions[e].h === originalHSB[0] && colorExceptions[e].s === originalHSB[1] && colorExceptions[e].b === originalHSB[2]) { + colortext = colorExceptions[e].name; + break; + } else { + //if there is no match return white + colortext = 'white'; + } + } + } else { + //otherwise, compare with values in colorLookUp + for (var _i2 = 0; _i2 < colorLookUp.length; _i2++) { + if (colorLookUp[_i2].h === hsb[0] && colorLookUp[_i2].s === hsb[1] && colorLookUp[_i2].b === hsb[2]) { + colortext = colorLookUp[_i2].name; + break; + } + } + } + return colortext; + } //gets rgba and returs a color name + + _main.default.prototype._rgbColorName = function (arg) { + //conversts rgba to hsb + var hsb = _color_conversion.default._rgbaToHSBA(arg); + //stores hsb in global variable + originalHSB = hsb; + //calculate color name + return _calculateColor([hsb[0], + hsb[1], + hsb[2]]); + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../color/color_conversion': 287, + '../core/main': 303, + 'core-js/modules/es.function.name': 191, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.split': 221 + } + ], + 282: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.ends-with'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.ends-with'); + _dereq_('core-js/modules/es.string.replace'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Environment + * @submodule Environment + * @for p5 + * @requires core + */ + + var descContainer = '_Description'; //Fallback container + var fallbackDescId = '_fallbackDesc'; //Fallback description + var fallbackTableId = '_fallbackTable'; //Fallback Table + var fallbackTableElId = '_fte_'; //Fallback Table Element + var labelContainer = '_Label'; //Label container + var labelDescId = '_labelDesc'; //Label description + var labelTableId = '_labelTable'; //Label Table + var labelTableElId = '_lte_'; //Label Table Element + /** + * Creates a screen reader-accessible description of the canvas. + * + * The first parameter, `text`, is the description of the canvas. + * + * The second parameter, `display`, is optional. It determines how the + * description is displayed. If `LABEL` is passed, as in + * `describe('A description.', LABEL)`, the description will be visible in + * a div element next to the canvas. If `FALLBACK` is passed, as in + * `describe('A description.', FALLBACK)`, the description will only be + * visible to screen readers. This is the default mode. + * + * Read + * Writing accessible canvas descriptions + * to learn more about making sketches accessible. + * + * @method describe + * @param {String} text description of the canvas. + * @param {Constant} [display] either LABEL or FALLBACK. + * + * @example + *
+ * + * function setup() { + * background('pink'); + * + * // Draw a heart. + * fill('red'); + * noStroke(); + * circle(67, 67, 20); + * circle(83, 67, 20); + * triangle(91, 73, 75, 95, 59, 73); + * + * // Add a general description of the canvas. + * describe('A pink square with a red heart in the bottom-right corner.'); + * } + * + *
+ * + *
+ * + * function setup() { + * background('pink'); + * + * // Draw a heart. + * fill('red'); + * noStroke(); + * circle(67, 67, 20); + * circle(83, 67, 20); + * triangle(91, 73, 75, 95, 59, 73); + * + * // Add a general description of the canvas + * // and display it for debugging. + * describe('A pink square with a red heart in the bottom-right corner.', LABEL); + * } + * + *
+ * + *
+ * + * function draw() { + * background(200); + * + * // The expression + * // frameCount % 100 + * // causes x to increase from 0 + * // to 99, then restart from 0. + * let x = frameCount % 100; + * + * // Draw the circle. + * fill(0, 255, 0); + * circle(x, 50, 40); + * + * // Add a general description of the canvas. + * describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`); + * } + * + *
+ * + *
+ * + * function draw() { + * background(200); + * + * // The expression + * // frameCount % 100 + * // causes x to increase from 0 + * // to 99, then restart from 0. + * let x = frameCount % 100; + * + * // Draw the circle. + * fill(0, 255, 0); + * circle(x, 50, 40); + * + * // Add a general description of the canvas + * // and display it for debugging. + * describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`, LABEL); + * } + * + *
+ */ + _main.default.prototype.describe = function (text, display) { + _main.default._validateParameters('describe', arguments); + if (typeof text !== 'string') { + return; + } + var cnvId = this.canvas.id; + //calls function that adds punctuation for better screen reading + text = _descriptionText(text); + //if there is no dummyDOM + if (!this.dummyDOM) { + this.dummyDOM = document.getElementById(cnvId).parentNode; + } + if (!this.descriptions) { + this.descriptions = { + }; + } //check if html structure for description is ready + + if (this.descriptions.fallback) { + //check if text is different from current description + if (this.descriptions.fallback.innerHTML !== text) { + //update description + this.descriptions.fallback.innerHTML = text; + } + } else { + //create fallback html structure + this._describeHTML('fallback', text); + } //if display is LABEL + + if (display === this.LABEL) { + //check if html structure for label is ready + if (this.descriptions.label) { + //check if text is different from current label + if (this.descriptions.label.innerHTML !== text) { + //update label description + this.descriptions.label.innerHTML = text; + } + } else { + //create label html structure + this._describeHTML('label', text); + } + } + }; + /** + * Creates a screen reader-accessible description of elements in the canvas. + * + * Elements are shapes or groups of shapes that create meaning together. For + * example, a few overlapping circles could make an "eye" element. + * + * The first parameter, `name`, is the name of the element. + * + * The second parameter, `text`, is the description of the element. + * + * The third parameter, `display`, is optional. It determines how the + * description is displayed. If `LABEL` is passed, as in + * `describe('A description.', LABEL)`, the description will be visible in + * a div element next to the canvas. Using `LABEL` creates unhelpful + * duplicates for screen readers. Only use `LABEL` during development. If + * `FALLBACK` is passed, as in `describe('A description.', FALLBACK)`, the + * description will only be visible to screen readers. This is the default + * mode. + * + * Read + * Writing accessible canvas descriptions + * to learn more about making sketches accessible. + * + * @method describeElement + * @param {String} name name of the element. + * @param {String} text description of the element. + * @param {Constant} [display] either LABEL or FALLBACK. + * + * @example + *
+ * + * function setup() { + * background('pink'); + * + * // Describe the first element + * // and draw it. + * describeElement('Circle', 'A yellow circle in the top-left corner.'); + * noStroke(); + * fill('yellow'); + * circle(25, 25, 40); + * + * // Describe the second element + * // and draw it. + * describeElement('Heart', 'A red heart in the bottom-right corner.'); + * fill('red'); + * circle(66.6, 66.6, 20); + * circle(83.2, 66.6, 20); + * triangle(91.2, 72.6, 75, 95, 58.6, 72.6); + * + * // Add a general description of the canvas. + * describe('A red heart and yellow circle over a pink background.'); + * } + * + *
+ * + *
+ * + * function setup() { + * background('pink'); + * + * // Describe the first element + * // and draw it. Display the + * // description for debugging. + * describeElement('Circle', 'A yellow circle in the top-left corner.', LABEL); + * noStroke(); + * fill('yellow'); + * circle(25, 25, 40); + * + * // Describe the second element + * // and draw it. Display the + * // description for debugging. + * describeElement('Heart', 'A red heart in the bottom-right corner.', LABEL); + * fill('red'); + * circle(66.6, 66.6, 20); + * circle(83.2, 66.6, 20); + * triangle(91.2, 72.6, 75, 95, 58.6, 72.6); + * + * // Add a general description of the canvas. + * describe('A red heart and yellow circle over a pink background.'); + * } + * + *
+ */ + _main.default.prototype.describeElement = function (name, text, display) { + _main.default._validateParameters('describeElement', arguments); + if (typeof text !== 'string' || typeof name !== 'string') { + return; + } + var cnvId = this.canvas.id; + //calls function that adds punctuation for better screen reading + text = _descriptionText(text); + //calls function that adds punctuation for better screen reading + var elementName = _elementName(name); + //remove any special characters from name to use it as html id + name = name.replace(/[^a-zA-Z0-9]/g, ''); + //store element description + var inner = ''.concat(elementName, '').concat(text, ''); + //if there is no dummyDOM + if (!this.dummyDOM) { + this.dummyDOM = document.getElementById(cnvId).parentNode; + } + if (!this.descriptions) { + this.descriptions = { + fallbackElements: { + } + }; + } else if (!this.descriptions.fallbackElements) { + this.descriptions.fallbackElements = { + }; + } //check if html structure for element description is ready + + if (this.descriptions.fallbackElements[name]) { + //if current element description is not the same as inner + if (this.descriptions.fallbackElements[name].innerHTML !== inner) { + //update element description + this.descriptions.fallbackElements[name].innerHTML = inner; + } + } else { + //create fallback html structure + this._describeElementHTML('fallback', name, inner); + } //if display is LABEL + + if (display === this.LABEL) { + if (!this.descriptions.labelElements) { + this.descriptions.labelElements = { + }; + } //if html structure for label element description is ready + + if (this.descriptions.labelElements[name]) { + //if label element description is different + if (this.descriptions.labelElements[name].innerHTML !== inner) { + //update label element description + this.descriptions.labelElements[name].innerHTML = inner; + } + } else { + //create label element html structure + this._describeElementHTML('label', name, inner); + } + } + }; + /* + * + * Helper functions for describe() and describeElement(). + * + */ + // check that text is not LABEL or FALLBACK and ensure text ends with punctuation mark + function _descriptionText(text) { + if (text === 'label' || text === 'fallback') { + throw new Error('description should not be LABEL or FALLBACK'); + } //if string does not end with '.' + + if (!text.endsWith('.') && !text.endsWith(';') && !text.endsWith(',') && !text.endsWith('?') && !text.endsWith('!')) { + //add '.' to the end of string + text = text + '.'; + } + return text; + } /* + * Helper functions for describe() + */ + //creates HTML structure for canvas descriptions + + _main.default.prototype._describeHTML = function (type, text) { + var cnvId = this.canvas.id; + if (type === 'fallback') { + //if there is no description container + if (!this.dummyDOM.querySelector('#'.concat(cnvId + descContainer))) { + //if there are no accessible outputs (see textOutput() and gridOutput()) + var html = '

'); + if (!this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutput'))) { + //create description container +

for fallback description + this.dummyDOM.querySelector('#'.concat(cnvId)).innerHTML = html; + } else { + //create description container +

for fallback description before outputs + this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutput')).insertAdjacentHTML('beforebegin', html); + } + } else { + //if describeElement() has already created the container and added a table of elements + //create fallback description

before the table + this.dummyDOM.querySelector('#' + cnvId + fallbackTableId).insertAdjacentHTML('beforebegin', '

')); + } //if the container for the description exists + + this.descriptions.fallback = this.dummyDOM.querySelector('#'.concat(cnvId).concat(fallbackDescId)); + this.descriptions.fallback.innerHTML = text; + return; + } else if (type === 'label') { + //if there is no label container + if (!this.dummyDOM.querySelector('#'.concat(cnvId + labelContainer))) { + var _html = '

'); + //if there are no accessible outputs (see textOutput() and gridOutput()) + if (!this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutputLabel'))) { + //create label container +

for label description + this.dummyDOM.querySelector('#' + cnvId).insertAdjacentHTML('afterend', _html); + } else { + //create label container +

for label description before outputs + this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutputLabel')).insertAdjacentHTML('beforebegin', _html); + } + } else if (this.dummyDOM.querySelector('#'.concat(cnvId + labelTableId))) { + //if describeElement() has already created the container and added a table of elements + //create label description

before the table + this.dummyDOM.querySelector('#'.concat(cnvId + labelTableId)).insertAdjacentHTML('beforebegin', '

')); + } + this.descriptions.label = this.dummyDOM.querySelector('#' + cnvId + labelDescId); + this.descriptions.label.innerHTML = text; + return; + } + }; + /* + * Helper functions for describeElement(). + */ + //check that name is not LABEL or FALLBACK and ensure text ends with colon + function _elementName(name) { + if (name === 'label' || name === 'fallback') { + throw new Error('element name should not be LABEL or FALLBACK'); + } //check if last character of string n is '.', ';', or ',' + + if (name.endsWith('.') || name.endsWith(';') || name.endsWith(',')) { + //replace last character with ':' + name = name.replace(/.$/, ':'); + } else if (!name.endsWith(':')) { + //if string n does not end with ':' + //add ':'' at the end of string + name = name + ':'; + } + return name; + } //creates HTML structure for element descriptions + + _main.default.prototype._describeElementHTML = function (type, name, text) { + var cnvId = this.canvas.id; + if (type === 'fallback') { + //if there is no description container + if (!this.dummyDOM.querySelector('#'.concat(cnvId + descContainer))) { + //if there are no accessible outputs (see textOutput() and gridOutput()) + var html = '
Canvas elements and their descriptions
'); + if (!this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutput'))) { + //create container + table for element descriptions + this.dummyDOM.querySelector('#' + cnvId).innerHTML = html; + } else { + //create container + table for element descriptions before outputs + this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutput')).insertAdjacentHTML('beforebegin', html); + } + } else if (!this.dummyDOM.querySelector('#' + cnvId + fallbackTableId)) { + //if describe() has already created the container and added a description + //and there is no table create fallback table for element description after + //fallback description + this.dummyDOM.querySelector('#' + cnvId + fallbackDescId).insertAdjacentHTML('afterend', '
Canvas elements and their descriptions
')); + } //create a table row for the element + + var tableRow = document.createElement('tr'); + tableRow.id = cnvId + fallbackTableElId + name; + this.dummyDOM.querySelector('#' + cnvId + fallbackTableId).appendChild(tableRow); + //update element description + this.descriptions.fallbackElements[name] = this.dummyDOM.querySelector('#'.concat(cnvId).concat(fallbackTableElId).concat(name)); + this.descriptions.fallbackElements[name].innerHTML = text; + return; + } else if (type === 'label') { + //If display is LABEL creates a div adjacent to the canvas element with + //a table, a row header cell with the name of the elements, + //and adds the description of the element in adjacent cell. + //if there is no label description container + if (!this.dummyDOM.querySelector('#'.concat(cnvId + labelContainer))) { + //if there are no accessible outputs (see textOutput() and gridOutput()) + var _html2 = '
'); + if (!this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutputLabel'))) { + //create container + table for element descriptions + this.dummyDOM.querySelector('#' + cnvId).insertAdjacentHTML('afterend', _html2); + } else { + //create container + table for element descriptions before outputs + this.dummyDOM.querySelector('#'.concat(cnvId, 'accessibleOutputLabel')).insertAdjacentHTML('beforebegin', _html2); + } + } else if (!this.dummyDOM.querySelector('#'.concat(cnvId + labelTableId))) { + //if describe() has already created the label container and added a description + //and there is no table create label table for element description after + //label description + this.dummyDOM.querySelector('#' + cnvId + labelDescId).insertAdjacentHTML('afterend', '
')); + } //create a table row for the element label description + + var _tableRow = document.createElement('tr'); + _tableRow.id = cnvId + labelTableElId + name; + this.dummyDOM.querySelector('#' + cnvId + labelTableId).appendChild(_tableRow); + //update element label description + this.descriptions.labelElements[name] = this.dummyDOM.querySelector('#'.concat(cnvId).concat(labelTableElId).concat(name)); + this.descriptions.labelElements[name].innerHTML = text; + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.string.ends-with': 213, + 'core-js/modules/es.string.replace': 219 + } + ], + 283: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.string.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Environment + * @submodule Environment + * @for p5 + * @requires core + */ + //the functions in this file support updating the grid output + //updates gridOutput + + _main.default.prototype._updateGridOutput = function (idT) { + //if html structure is not there yet + if (!this.dummyDOM.querySelector('#'.concat(idT, '_summary'))) { + return; + } + var current = this._accessibleOutputs[idT]; + //create shape details list + var innerShapeDetails = _gridShapeDetails(idT, this.ingredients.shapes); + //create summary + var innerSummary = _gridSummary(innerShapeDetails.numShapes, this.ingredients.colors.background, this.width, this.height); + //create grid map + var innerMap = _gridMap(idT, this.ingredients.shapes); + //if it is different from current summary + if (innerSummary !== current.summary.innerHTML) { + //update + current.summary.innerHTML = innerSummary; + } //if it is different from current map + + if (innerMap !== current.map.innerHTML) { + //update + current.map.innerHTML = innerMap; + } //if it is different from current shape details + + if (innerShapeDetails.details !== current.shapeDetails.innerHTML) { + //update + current.shapeDetails.innerHTML = innerShapeDetails.details; + } + this._accessibleOutputs[idT] = current; + }; + //creates spatial grid that maps the location of shapes + function _gridMap(idT, ingredients) { + var shapeNumber = 0; + var table = ''; + //create an array of arrays 10*10 of empty cells + var cells = Array.from(Array(10), function () { + return Array(10); + }); + for (var x in ingredients) { + for (var y in ingredients[x]) { + var fill = void 0; + if (x !== 'line') { + fill = '').concat(ingredients[x][y].color, ' ').concat(x, ''); + } else { + fill = '').concat(ingredients[x][y].color, ' ').concat(x, ' midpoint'); + } //if empty cell of location of shape is undefined + + if (!cells[ingredients[x][y].loc.locY][ingredients[x][y].loc.locX]) { + //fill it with shape info + cells[ingredients[x][y].loc.locY][ingredients[x][y].loc.locX] = fill; + //if a shape is already in that location + } else { + //add it + cells[ingredients[x][y].loc.locY][ingredients[x][y].loc.locX] = cells[ingredients[x][y].loc.locY][ingredients[x][y].loc.locX] + ' ' + fill; + } + shapeNumber++; + } + } //make table based on array + + for (var _r in cells) { + var row = ''; + for (var c in cells[_r]) { + row = row + ''; + if (cells[_r][c] !== undefined) { + row = row + cells[_r][c]; + } + row = row + ''; + } + table = table + row + ''; + } + return table; + } //creates grid summary + + function _gridSummary(numShapes, background, width, height) { + var text = ''.concat(background, ' canvas, ').concat(width, ' by ').concat(height, ' pixels, contains ').concat(numShapes[0]); + if (numShapes[0] === 1) { + text = ''.concat(text, ' shape: ').concat(numShapes[1]); + } else { + text = ''.concat(text, ' shapes: ').concat(numShapes[1]); + } + return text; + } //creates list of shapes + + function _gridShapeDetails(idT, ingredients) { + var shapeDetails = ''; + var shapes = ''; + var totalShapes = 0; + //goes trhough every shape type in ingredients + for (var x in ingredients) { + var shapeNum = 0; + for (var y in ingredients[x]) { + //it creates a line in a list + var line = '
  • ').concat(ingredients[x][y].color, ' ').concat(x, ','); + if (x === 'line') { + line = line + ' location = '.concat(ingredients[x][y].pos, ', length = ').concat(ingredients[x][y].length, ' pixels'); + } else { + line = line + ' location = '.concat(ingredients[x][y].pos); + if (x !== 'point') { + line = line + ', area = '.concat(ingredients[x][y].area, ' %'); + } + line = line + '
  • '; + } + shapeDetails = shapeDetails + line; + shapeNum++; + totalShapes++; + } + if (shapeNum > 1) { + shapes = ''.concat(shapes, ' ').concat(shapeNum, ' ').concat(x, 's'); + } else { + shapes = ''.concat(shapes, ' ').concat(shapeNum, ' ').concat(x); + } + } + return { + numShapes: [ + totalShapes, + shapes + ], + details: shapeDetails + }; + } + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.string.iterator': 215 + } + ], + 284: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.number.to-fixed'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } /** + * @module Environment + * @submodule Environment + * @for p5 + * @requires core + */ + /** + * Creates a screen reader-accessible description of shapes on the canvas. + * + * `textOutput()` adds a general description, list of shapes, and + * table of shapes to the web page. The general description includes the + * canvas size, canvas color, and number of shapes. For example, + * `Your output is a, 100 by 100 pixels, gray canvas containing the following 2 shapes:`. + * + * A list of shapes follows the general description. The list describes the + * color, location, and area of each shape. For example, + * `a red circle at middle covering 3% of the canvas`. Each shape can be + * selected to get more details. + * + * `textOutput()` uses its table of shapes as a list. The table describes the + * shape, color, location, coordinates and area. For example, + * `red circle location = middle area = 3%`. This is different from + * gridOutput(), which uses its table as a grid. + * + * The `display` parameter is optional. It determines how the description is + * displayed. If `LABEL` is passed, as in `textOutput(LABEL)`, the description + * will be visible in a div element next to the canvas. Using `LABEL` creates + * unhelpful duplicates for screen readers. Only use `LABEL` during + * development. If `FALLBACK` is passed, as in `textOutput(FALLBACK)`, the + * description will only be visible to screen readers. This is the default + * mode. + * + * Read + * Writing accessible canvas descriptions + * to learn more about making sketches accessible. + * + * @method textOutput + * @param {Constant} [display] either FALLBACK or LABEL. + * + * @example + *
    + * + * function setup() { + * // Add the text description. + * textOutput(); + * + * // Draw a couple of shapes. + * background(200); + * fill(255, 0, 0); + * circle(20, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle and a blue square on a gray background.'); + * } + * + *
    + * + *
    + * + * function setup() { + * // Add the text description and + * // display it for debugging. + * textOutput(LABEL); + * + * // Draw a couple of shapes. + * background(200); + * fill(255, 0, 0); + * circle(20, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle and a blue square on a gray background.'); + * } + * + *
    + * + *
    + * + * function draw() { + * // Add the text description. + * textOutput(); + * + * // Draw a moving circle. + * background(200); + * let x = frameCount * 0.1; + * fill(255, 0, 0); + * circle(x, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle moves from left to right above a blue square.'); + * } + * + *
    + * + *
    + * + * function draw() { + * // Add the text description and + * // display it for debugging. + * textOutput(LABEL); + * + * // Draw a moving circle. + * background(200); + * let x = frameCount * 0.1; + * fill(255, 0, 0); + * circle(x, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle moves from left to right above a blue square.'); + * } + * + *
    + */ + + _main.default.prototype.textOutput = function (display) { + _main.default._validateParameters('textOutput', arguments); + //if textOutput is already true + if (this._accessibleOutputs.text) { + return; + } else { + //make textOutput true + this._accessibleOutputs.text = true; + //create output for fallback + this._createOutput('textOutput', 'Fallback'); + if (display === this.LABEL) { + //make textOutput label true + this._accessibleOutputs.textLabel = true; + //create output for label + this._createOutput('textOutput', 'Label'); + } + } + }; + /** + * Creates a screen reader-accessible description of shapes on the canvas. + * + * `gridOutput()` adds a general description, table of shapes, and list of + * shapes to the web page. The general description includes the canvas size, + * canvas color, and number of shapes. For example, + * `gray canvas, 100 by 100 pixels, contains 2 shapes: 1 circle 1 square`. + * + * `gridOutput()` uses its table of shapes as a grid. Each shape in the grid + * is placed in a cell whose row and column correspond to the shape's location + * on the canvas. The grid cells describe the color and type of shape at that + * location. For example, `red circle`. These descriptions can be selected + * individually to get more details. This is different from + * textOutput(), which uses its table as a list. + * + * A list of shapes follows the table. The list describes the color, type, + * location, and area of each shape. For example, + * `red circle, location = middle, area = 3 %`. + * + * The `display` parameter is optional. It determines how the description is + * displayed. If `LABEL` is passed, as in `gridOutput(LABEL)`, the description + * will be visible in a div element next to the canvas. Using `LABEL` creates + * unhelpful duplicates for screen readers. Only use `LABEL` during + * development. If `FALLBACK` is passed, as in `gridOutput(FALLBACK)`, the + * description will only be visible to screen readers. This is the default + * mode. + * + * Read + * Writing accessible canvas descriptions + * to learn more about making sketches accessible. + * + * @method gridOutput + * @param {Constant} [display] either FALLBACK or LABEL. + * + * @example + *
    + * + * function setup() { + * // Add the grid description. + * gridOutput(); + * + * // Draw a couple of shapes. + * background(200); + * fill(255, 0, 0); + * circle(20, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle and a blue square on a gray background.'); + * } + * + *
    + * + *
    + * + * function setup() { + * // Add the grid description and + * // display it for debugging. + * gridOutput(LABEL); + * + * // Draw a couple of shapes. + * background(200); + * fill(255, 0, 0); + * circle(20, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle and a blue square on a gray background.'); + * } + * + *
    + * + *
    + * + * function draw() { + * // Add the grid description. + * gridOutput(); + * + * // Draw a moving circle. + * background(200); + * let x = frameCount * 0.1; + * fill(255, 0, 0); + * circle(x, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle moves from left to right above a blue square.'); + * } + * + *
    + * + *
    + * + * function draw() { + * // Add the grid description and + * // display it for debugging. + * gridOutput(LABEL); + * + * // Draw a moving circle. + * background(200); + * let x = frameCount * 0.1; + * fill(255, 0, 0); + * circle(x, 20, 20); + * fill(0, 0, 255); + * square(50, 50, 50); + * + * // Add a general description of the canvas. + * describe('A red circle moves from left to right above a blue square.'); + * } + * + *
    + */ + _main.default.prototype.gridOutput = function (display) { + _main.default._validateParameters('gridOutput', arguments); + //if gridOutput is already true + if (this._accessibleOutputs.grid) { + return; + } else { + //make gridOutput true + this._accessibleOutputs.grid = true; + //create output for fallback + this._createOutput('gridOutput', 'Fallback'); + if (display === this.LABEL) { + //make gridOutput label true + this._accessibleOutputs.gridLabel = true; + //create output for label + this._createOutput('gridOutput', 'Label'); + } + } + }; + //helper function returns true when accessible outputs are true + _main.default.prototype._addAccsOutput = function () { + //if there are no accessible outputs create object with all false + if (!this._accessibleOutputs) { + this._accessibleOutputs = { + text: false, + grid: false, + textLabel: false, + gridLabel: false + }; + } + return this._accessibleOutputs.grid || this._accessibleOutputs.text; + }; + //helper function that creates html structure for accessible outputs + _main.default.prototype._createOutput = function (type, display) { + var cnvId = this.canvas.id; + //if there are no ingredients create object. this object stores data for the outputs + if (!this.ingredients) { + this.ingredients = { + shapes: { + }, + colors: { + background: 'white', + fill: 'white', + stroke: 'black' + }, + pShapes: '', + pBackground: '' + }; + } //if there is no dummyDOM create it + + if (!this.dummyDOM) { + this.dummyDOM = document.getElementById(cnvId).parentNode; + } + var cIdT, + container, + inner; + var query = ''; + if (display === 'Fallback') { + cIdT = cnvId + type; + container = cnvId + 'accessibleOutput'; + if (!this.dummyDOM.querySelector('#'.concat(container))) { + //if there is no canvas description (see describe() and describeElement()) + if (!this.dummyDOM.querySelector('#'.concat(cnvId, '_Description'))) { + //create html structure inside of canvas + this.dummyDOM.querySelector('#'.concat(cnvId)).innerHTML = '
    '); + } else { + //create html structure after canvas description container + this.dummyDOM.querySelector('#'.concat(cnvId, '_Description')).insertAdjacentHTML('afterend', '
    ')); + } + } + } else if (display === 'Label') { + query = display; + cIdT = cnvId + type + display; + container = cnvId + 'accessibleOutput' + display; + if (!this.dummyDOM.querySelector('#'.concat(container))) { + //if there is no canvas description label (see describe() and describeElement()) + if (!this.dummyDOM.querySelector('#'.concat(cnvId, '_Label'))) { + //create html structure adjacent to canvas + this.dummyDOM.querySelector('#'.concat(cnvId)).insertAdjacentHTML('afterend', '
    ')); + } else { + //create html structure after canvas label + this.dummyDOM.querySelector('#'.concat(cnvId, '_Label')).insertAdjacentHTML('afterend', '
    ')); + } + } + } //create an object to store the latest output. this object is used in _updateTextOutput() and _updateGridOutput() + + this._accessibleOutputs[cIdT] = { + }; + if (type === 'textOutput') { + query = '#'.concat(cnvId, 'gridOutput').concat(query); //query is used to check if gridOutput already exists + inner = '
    Text Output

      '); + //if gridOutput already exists + if (this.dummyDOM.querySelector(query)) { + //create textOutput before gridOutput + this.dummyDOM.querySelector(query).insertAdjacentHTML('beforebegin', inner); + } else { + //create output inside of container + this.dummyDOM.querySelector('#'.concat(container)).innerHTML = inner; + } //store output html elements + + this._accessibleOutputs[cIdT].list = this.dummyDOM.querySelector('#'.concat(cIdT, '_list')); + } else if (type === 'gridOutput') { + query = '#'.concat(cnvId, 'textOutput').concat(query); //query is used to check if textOutput already exists + inner = '
      Grid Output

        '); + //if textOutput already exists + if (this.dummyDOM.querySelector(query)) { + //create gridOutput after textOutput + this.dummyDOM.querySelector(query).insertAdjacentHTML('afterend', inner); + } else { + //create output inside of container + this.dummyDOM.querySelector('#'.concat(container)).innerHTML = inner; + } //store output html elements + + this._accessibleOutputs[cIdT].map = this.dummyDOM.querySelector('#'.concat(cIdT, '_map')); + } + this._accessibleOutputs[cIdT].shapeDetails = this.dummyDOM.querySelector('#'.concat(cIdT, '_shapeDetails')); + this._accessibleOutputs[cIdT].summary = this.dummyDOM.querySelector('#'.concat(cIdT, '_summary')); + }; + //this function is called at the end of setup and draw if using + //accessibleOutputs and calls update functions of outputs + _main.default.prototype._updateAccsOutput = function () { + var cnvId = this.canvas.id; + //if the shapes are not the same as before + if (JSON.stringify(this.ingredients.shapes) !== this.ingredients.pShapes || this.ingredients.colors.background !== this.ingredients.pBackground) { + //save current shapes as string in pShapes + this.ingredients.pShapes = JSON.stringify(this.ingredients.shapes); + if (this._accessibleOutputs.text) { + this._updateTextOutput(cnvId + 'textOutput'); + } + if (this._accessibleOutputs.grid) { + this._updateGridOutput(cnvId + 'gridOutput'); + } + if (this._accessibleOutputs.textLabel) { + this._updateTextOutput(cnvId + 'textOutputLabel'); + } + if (this._accessibleOutputs.gridLabel) { + this._updateGridOutput(cnvId + 'gridOutputLabel'); + } + } + }; + //helper function that resets all ingredients when background is called + //and saves background color name + _main.default.prototype._accsBackground = function (args) { + //save current shapes as string in pShapes + this.ingredients.pShapes = JSON.stringify(this.ingredients.shapes); + this.ingredients.pBackground = this.ingredients.colors.background; + //empty shapes JSON + this.ingredients.shapes = { + }; + //update background different + if (this.ingredients.colors.backgroundRGBA !== args) { + this.ingredients.colors.backgroundRGBA = args; + this.ingredients.colors.background = this._rgbColorName(args); + } + }; + //helper function that gets fill and stroke of shapes + _main.default.prototype._accsCanvasColors = function (f, args) { + if (f === 'fill') { + //update fill different + if (this.ingredients.colors.fillRGBA !== args) { + this.ingredients.colors.fillRGBA = args; + this.ingredients.colors.fill = this._rgbColorName(args); + } + } else if (f === 'stroke') { + //update stroke if different + if (this.ingredients.colors.strokeRGBA !== args) { + this.ingredients.colors.strokeRGBA = args; + this.ingredients.colors.stroke = this._rgbColorName(args); + } + } + }; + //builds ingredients.shapes used for building outputs + _main.default.prototype._accsOutput = function (f, args) { + if (f === 'ellipse' && args[2] === args[3]) { + f = 'circle'; + } else if (f === 'rectangle' && args[2] === args[3]) { + f = 'square'; + } + var include = { + }; + var add = true; + var middle = _getMiddle(f, args); + if (f === 'line') { + //make color stroke + include.color = this.ingredients.colors.stroke; + //get lenght + include.length = Math.round(this.dist(args[0], args[1], args[2], args[3])); + //get position of end points + var p1 = this._getPos(args[0], [ + 1 + ]); + var p2 = this._getPos(args[2], [ + 3 + ]); + include.loc = _canvasLocator(middle, this.width, this.height); + if (p1 === p2) { + include.pos = 'at '.concat(p1); + } else { + include.pos = 'from '.concat(p1, ' to ').concat(p2); + } + } else { + if (f === 'point') { + //make color stroke + include.color = this.ingredients.colors.stroke; + } else { + //make color fill + include.color = this.ingredients.colors.fill; + //get area of shape + include.area = this._getArea(f, args); + } //get middle of shapes + //calculate position using middle of shape + + include.pos = this._getPos.apply(this, _toConsumableArray(middle)); + //calculate location using middle of shape + include.loc = _canvasLocator(middle, this.width, this.height); + } //if it is the first time this shape is created + + if (!this.ingredients.shapes[f]) { + this.ingredients.shapes[f] = [ + include + ]; + //if other shapes of this type have been created + } else if (this.ingredients.shapes[f] !== [include]) { + //for every shape of this type + for (var y in this.ingredients.shapes[f]) { + //compare it with current shape and if it already exists make add false + if (JSON.stringify(this.ingredients.shapes[f][y]) === JSON.stringify(include)) { + add = false; + } + } //add shape by pushing it to the end + + if (add === true) { + this.ingredients.shapes[f].push(include); + } + } + }; + //gets middle point / centroid of shape + function _getMiddle(f, args) { + var x, + y; + if (f === 'rectangle' || f === 'ellipse' || f === 'arc' || f === 'circle' || f === 'square') { + x = Math.round(args[0] + args[2] / 2); + y = Math.round(args[1] + args[3] / 2); + } else if (f === 'triangle') { + x = (args[0] + args[2] + args[4]) / 3; + y = (args[1] + args[3] + args[5]) / 3; + } else if (f === 'quadrilateral') { + x = (args[0] + args[2] + args[4] + args[6]) / 4; + y = (args[1] + args[3] + args[5] + args[7]) / 4; + } else if (f === 'line') { + x = (args[0] + args[2]) / 2; + y = (args[1] + args[3]) / 2; + } else { + x = args[0]; + y = args[1]; + } + return [x, + y]; + } //gets position of shape in the canvas + + _main.default.prototype._getPos = function (x, y) { + var untransformedPosition = new DOMPointReadOnly(x, y); + var currentTransform = this._renderer.isP3D ? new DOMMatrix(this._renderer.uMVMatrix.mat4) : this.drawingContext.getTransform(); + var _untransformedPositio = untransformedPosition.matrixTransform(currentTransform), + transformedX = _untransformedPositio.x, + transformedY = _untransformedPositio.y; + var canvasWidth = this.width * this._pixelDensity; + var canvasHeight = this.height * this._pixelDensity; + if (transformedX < 0.4 * canvasWidth) { + if (transformedY < 0.4 * canvasHeight) { + return 'top left'; + } else if (transformedY > 0.6 * canvasHeight) { + return 'bottom left'; + } else { + return 'mid left'; + } + } else if (transformedX > 0.6 * canvasWidth) { + if (transformedY < 0.4 * canvasHeight) { + return 'top right'; + } else if (transformedY > 0.6 * canvasHeight) { + return 'bottom right'; + } else { + return 'mid right'; + } + } else { + if (transformedY < 0.4 * canvasHeight) { + return 'top middle'; + } else if (transformedY > 0.6 * canvasHeight) { + return 'bottom middle'; + } else { + return 'middle'; + } + } + }; + //locates shape in a 10*10 grid + function _canvasLocator(args, canvasWidth, canvasHeight) { + var noRows = 10; + var noCols = 10; + var locX = Math.floor(args[0] / canvasWidth * noRows); + var locY = Math.floor(args[1] / canvasHeight * noCols); + if (locX === noRows) { + locX = locX - 1; + } + if (locY === noCols) { + locY = locY - 1; + } + return { + locX: locX, + locY: locY + }; + } //calculates area of shape + + _main.default.prototype._getArea = function (objectType, shapeArgs) { + var objectArea = 0; + if (objectType === 'arc') { + // area of full ellipse = PI * horizontal radius * vertical radius. + // therefore, area of arc = difference bet. arc's start and end radians * horizontal radius * vertical radius. + // the below expression is adjusted for negative values and differences in arc's start and end radians over PI*2 + var arcSizeInRadians = ((shapeArgs[5] - shapeArgs[4]) % (Math.PI * 2) + Math.PI * 2) % (Math.PI * 2); + objectArea = arcSizeInRadians * shapeArgs[2] * shapeArgs[3] / 8; + if (shapeArgs[6] === 'open' || shapeArgs[6] === 'chord') { + // when the arc's mode is OPEN or CHORD, we need to account for the area of the triangle that is formed to close the arc + // (Ax( By − Cy) + Bx(Cy − Ay) + Cx(Ay − By ) )/2 + var Ax = shapeArgs[0]; + var Ay = shapeArgs[1]; + var Bx = shapeArgs[0] + shapeArgs[2] / 2 * Math.cos(shapeArgs[4]).toFixed(2); + var By = shapeArgs[1] + shapeArgs[3] / 2 * Math.sin(shapeArgs[4]).toFixed(2); + var Cx = shapeArgs[0] + shapeArgs[2] / 2 * Math.cos(shapeArgs[5]).toFixed(2); + var Cy = shapeArgs[1] + shapeArgs[3] / 2 * Math.sin(shapeArgs[5]).toFixed(2); + var areaOfExtraTriangle = Math.abs(Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By)) / 2; + if (arcSizeInRadians > Math.PI) { + objectArea = objectArea + areaOfExtraTriangle; + } else { + objectArea = objectArea - areaOfExtraTriangle; + } + } + } else if (objectType === 'ellipse' || objectType === 'circle') { + objectArea = 3.14 * shapeArgs[2] / 2 * shapeArgs[3] / 2; + } else if (objectType === 'line') { + objectArea = 0; + } else if (objectType === 'point') { + objectArea = 0; + } else if (objectType === 'quadrilateral') { + // ((x4+x1)*(y4-y1)+(x1+x2)*(y1-y2)+(x2+x3)*(y2-y3)+(x3+x4)*(y3-y4))/2 + objectArea = Math.abs((shapeArgs[6] + shapeArgs[0]) * (shapeArgs[7] - shapeArgs[1]) + (shapeArgs[0] + shapeArgs[2]) * (shapeArgs[1] - shapeArgs[3]) + (shapeArgs[2] + shapeArgs[4]) * (shapeArgs[3] - shapeArgs[5]) + (shapeArgs[4] + shapeArgs[6]) * (shapeArgs[5] - shapeArgs[7])) / 2; + } else if (objectType === 'rectangle' || objectType === 'square') { + objectArea = shapeArgs[2] * shapeArgs[3]; + } else if (objectType === 'triangle') { + objectArea = Math.abs(shapeArgs[0] * (shapeArgs[3] - shapeArgs[5]) + shapeArgs[2] * (shapeArgs[5] - shapeArgs[1]) + shapeArgs[4] * (shapeArgs[1] - shapeArgs[3])) / 2; + // (Ax( By − Cy) + Bx(Cy − Ay) + Cx(Ay − By ))/2 + } // Store the positions of the canvas corners + + var canvasWidth = this.width * this._pixelDensity; + var canvasHeight = this.height * this._pixelDensity; + var canvasCorners = [ + new DOMPoint(0, 0), + new DOMPoint(canvasWidth, 0), + new DOMPoint(canvasWidth, canvasHeight), + new DOMPoint(0, canvasHeight) + ]; + // Apply the inverse of the current transformations to the canvas corners + var currentTransform = this._renderer.isP3D ? new DOMMatrix(this._renderer.uMVMatrix.mat4) : this.drawingContext.getTransform(); + var invertedTransform = currentTransform.inverse(); + var tc = canvasCorners.map(function (corner) { + return corner.matrixTransform(invertedTransform); + }); + /* Use same shoelace formula used for quad area (above) to calculate + the area of the canvas with inverted transformation applied */ + var transformedCanvasArea = Math.abs((tc[3].x + tc[0].x) * (tc[3].y - tc[0].y) + (tc[0].x + tc[1].x) * (tc[0].y - tc[1].y) + (tc[1].x + tc[2].x) * (tc[1].y - tc[2].y) + (tc[2].x + tc[3].x) * (tc[2].y - tc[3].y)) / 2; + /* Compare area of shape (minus transformations) to area of canvas + with inverted transformation applied. + Return percentage */ + var untransformedArea = Math.round(objectArea * 100 / transformedCanvasArea); + return untransformedArea; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.fill': 173, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.number.to-fixed': 198, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 285: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.concat'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Environment + * @submodule Environment + * @for p5 + * @requires core + */ + //the functions in this file support updating the text output + //updates textOutput + + _main.default.prototype._updateTextOutput = function (idT) { + //if html structure is not there yet + if (!this.dummyDOM.querySelector('#'.concat(idT, '_summary'))) { + return; + } + var current = this._accessibleOutputs[idT]; + //create shape list + var innerList = _shapeList(idT, this.ingredients.shapes); + //create output summary + var innerSummary = _textSummary(innerList.numShapes, this.ingredients.colors.background, this.width, this.height); + //create shape details + var innerShapeDetails = _shapeDetails(idT, this.ingredients.shapes); + //if it is different from current summary + if (innerSummary !== current.summary.innerHTML) { + //update + current.summary.innerHTML = innerSummary; + } //if it is different from current shape list + + if (innerList.listShapes !== current.list.innerHTML) { + //update + current.list.innerHTML = innerList.listShapes; + } //if it is different from current shape details + + if (innerShapeDetails !== current.shapeDetails.innerHTML) { + //update + current.shapeDetails.innerHTML = innerShapeDetails; + } + this._accessibleOutputs[idT] = current; + }; + //Builds textOutput summary + function _textSummary(numShapes, background, width, height) { + var text = 'Your output is a, '.concat(width, ' by ').concat(height, ' pixels, ').concat(background, ' canvas containing the following'); + if (numShapes === 1) { + text = ''.concat(text, ' shape:'); + } else { + text = ''.concat(text, ' ').concat(numShapes, ' shapes:'); + } + return text; + } //Builds textOutput table with shape details + + function _shapeDetails(idT, ingredients) { + var shapeDetails = ''; + var shapeNumber = 0; + //goes trhough every shape type in ingredients + for (var x in ingredients) { + //and for every shape + for (var y in ingredients[x]) { + //it creates a table row + var row = '').concat(ingredients[x][y].color, ' ').concat(x, ''); + if (x === 'line') { + row = row + 'location = '.concat(ingredients[x][y].pos, 'length = ').concat(ingredients[x][y].length, ' pixels'); + } else { + row = row + 'location = '.concat(ingredients[x][y].pos, ''); + if (x !== 'point') { + row = row + ' area = '.concat(ingredients[x][y].area, '%'); + } + row = row + ''; + } + shapeDetails = shapeDetails + row; + shapeNumber++; + } + } + return shapeDetails; + } //Builds textOutput shape list + + function _shapeList(idT, ingredients) { + var shapeList = ''; + var shapeNumber = 0; + //goes trhough every shape type in ingredients + for (var x in ingredients) { + for (var y in ingredients[x]) { + //it creates a line in a list + var _line = '
      • ').concat(ingredients[x][y].color, ' ').concat(x, ''); + if (x === 'line') { + _line = _line + ', '.concat(ingredients[x][y].pos, ', ').concat(ingredients[x][y].length, ' pixels long.
      • '); + } else { + _line = _line + ', at '.concat(ingredients[x][y].pos); + if (x !== 'point') { + _line = _line + ', covering '.concat(ingredients[x][y].area, '% of the canvas'); + } + _line = _line + '.'; + } + shapeList = shapeList + _line; + shapeNumber++; + } + } + return { + numShapes: shapeNumber, + listShapes: shapeList + }; + } + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.concat': 170 + } + ], + 286: [ + function (_dereq_, module, exports) { + 'use strict'; + var _main = _interopRequireDefault(_dereq_('./core/main')); + _dereq_('./core/constants'); + _dereq_('./core/environment'); + _dereq_('./core/friendly_errors/stacktrace'); + _dereq_('./core/friendly_errors/validate_params'); + _dereq_('./core/friendly_errors/file_errors'); + _dereq_('./core/friendly_errors/fes_core'); + _dereq_('./core/friendly_errors/sketch_reader'); + _dereq_('./core/helpers'); + _dereq_('./core/legacy'); + _dereq_('./core/preload'); + _dereq_('./core/p5.Element'); + _dereq_('./core/p5.Graphics'); + _dereq_('./core/p5.Renderer'); + _dereq_('./core/p5.Renderer2D'); + _dereq_('./core/rendering'); + _dereq_('./core/shim'); + _dereq_('./core/structure'); + _dereq_('./core/transform'); + _dereq_('./core/shape/2d_primitives'); + _dereq_('./core/shape/attributes'); + _dereq_('./core/shape/curves'); + _dereq_('./core/shape/vertex'); + _dereq_('./accessibility/outputs'); + _dereq_('./accessibility/textOutput'); + _dereq_('./accessibility/gridOutput'); + _dereq_('./accessibility/color_namer'); + _dereq_('./color/color_conversion'); + _dereq_('./color/creating_reading'); + _dereq_('./color/p5.Color'); + _dereq_('./color/setting'); + _dereq_('./data/p5.TypedDict'); + _dereq_('./data/local_storage.js'); + _dereq_('./dom/dom'); + _dereq_('./accessibility/describe'); + _dereq_('./events/acceleration'); + _dereq_('./events/keyboard'); + _dereq_('./events/mouse'); + _dereq_('./events/touch'); + _dereq_('./image/filters'); + _dereq_('./image/image'); + _dereq_('./image/loading_displaying'); + _dereq_('./image/p5.Image'); + _dereq_('./image/pixels'); + _dereq_('./io/files'); + _dereq_('./io/p5.Table'); + _dereq_('./io/p5.TableRow'); + _dereq_('./io/p5.XML'); + _dereq_('./math/calculation'); + _dereq_('./math/math'); + _dereq_('./math/noise'); + _dereq_('./math/p5.Vector'); + _dereq_('./math/random'); + _dereq_('./math/trigonometry'); + _dereq_('./typography/attributes'); + _dereq_('./typography/loading_displaying'); + _dereq_('./typography/p5.Font'); + _dereq_('./utilities/array_functions'); + _dereq_('./utilities/conversion'); + _dereq_('./utilities/string_functions'); + _dereq_('./utilities/time_date'); + _dereq_('./webgl/3d_primitives'); + _dereq_('./webgl/interaction'); + _dereq_('./webgl/light'); + _dereq_('./webgl/loading'); + _dereq_('./webgl/material'); + _dereq_('./webgl/p5.Camera'); + _dereq_('./webgl/p5.DataArray'); + _dereq_('./webgl/p5.Geometry'); + _dereq_('./webgl/p5.Matrix'); + _dereq_('./webgl/p5.RendererGL.Immediate'); + _dereq_('./webgl/p5.RendererGL'); + _dereq_('./webgl/p5.RendererGL.Retained'); + _dereq_('./webgl/p5.Framebuffer'); + _dereq_('./webgl/p5.Shader'); + _dereq_('./webgl/p5.RenderBuffer'); + _dereq_('./webgl/p5.Texture'); + _dereq_('./webgl/text'); + _dereq_('./core/init'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } // core + //accessibility + // color + // data + // DOM + // accessibility + // events + // image + // io + // math + // typography + // utilities + // webgl + + module.exports = _main.default; + }, + { + './accessibility/color_namer': 281, + './accessibility/describe': 282, + './accessibility/gridOutput': 283, + './accessibility/outputs': 284, + './accessibility/textOutput': 285, + './color/color_conversion': 287, + './color/creating_reading': 288, + './color/p5.Color': 289, + './color/setting': 290, + './core/constants': 291, + './core/environment': 292, + './core/friendly_errors/fes_core': 294, + './core/friendly_errors/file_errors': 295, + './core/friendly_errors/sketch_reader': 296, + './core/friendly_errors/stacktrace': 297, + './core/friendly_errors/validate_params': 298, + './core/helpers': 299, + './core/init': 300, + './core/legacy': 302, + './core/main': 303, + './core/p5.Element': 304, + './core/p5.Graphics': 305, + './core/p5.Renderer': 306, + './core/p5.Renderer2D': 307, + './core/preload': 308, + './core/rendering': 309, + './core/shape/2d_primitives': 310, + './core/shape/attributes': 311, + './core/shape/curves': 312, + './core/shape/vertex': 313, + './core/shim': 314, + './core/structure': 315, + './core/transform': 316, + './data/local_storage.js': 317, + './data/p5.TypedDict': 318, + './dom/dom': 319, + './events/acceleration': 320, + './events/keyboard': 321, + './events/mouse': 322, + './events/touch': 323, + './image/filters': 324, + './image/image': 325, + './image/loading_displaying': 326, + './image/p5.Image': 327, + './image/pixels': 328, + './io/files': 329, + './io/p5.Table': 330, + './io/p5.TableRow': 331, + './io/p5.XML': 332, + './math/calculation': 333, + './math/math': 334, + './math/noise': 335, + './math/p5.Vector': 336, + './math/random': 337, + './math/trigonometry': 338, + './typography/attributes': 339, + './typography/loading_displaying': 340, + './typography/p5.Font': 341, + './utilities/array_functions': 342, + './utilities/conversion': 343, + './utilities/string_functions': 344, + './utilities/time_date': 345, + './webgl/3d_primitives': 346, + './webgl/interaction': 348, + './webgl/light': 349, + './webgl/loading': 350, + './webgl/material': 351, + './webgl/p5.Camera': 352, + './webgl/p5.DataArray': 353, + './webgl/p5.Framebuffer': 354, + './webgl/p5.Geometry': 355, + './webgl/p5.Matrix': 356, + './webgl/p5.RenderBuffer': 357, + './webgl/p5.RendererGL': 360, + './webgl/p5.RendererGL.Immediate': 358, + './webgl/p5.RendererGL.Retained': 359, + './webgl/p5.Shader': 361, + './webgl/p5.Texture': 362, + './webgl/text': 363 + } + ], + 287: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Color + * @submodule Color Conversion + * @for p5 + * @requires core + */ + /** + * Conversions adapted from . + * + * In these functions, hue is always in the range [0, 1], just like all other + * components are in the range [0, 1]. 'Brightness' and 'value' are used + * interchangeably. + */ + + _main.default.ColorConversion = { + /** + * Convert an HSBA array to HSLA. + */ + _hsbaToHSLA: function _hsbaToHSLA(hsba) { + var hue = hsba[0]; + var sat = hsba[1]; + var val = hsba[2]; + // Calculate lightness. + var li = (2 - sat) * val / 2; + // Convert saturation. + if (li !== 0) { + if (li === 1) { + sat = 0; + } else if (li < 0.5) { + sat = sat / (2 - sat); + } else { + sat = sat * val / (2 - li * 2); + } + } // Hue and alpha stay the same. + + return [hue, + sat, + li, + hsba[3]]; + }, + /** + * Convert an HSBA array to RGBA. + */ + _hsbaToRGBA: function _hsbaToRGBA(hsba) { + var hue = hsba[0] * 6; // We will split hue into 6 sectors. + var sat = hsba[1]; + var val = hsba[2]; + var RGBA = [ + ]; + if (sat === 0) { + RGBA = [ + val, + val, + val, + hsba[3] + ]; // Return early if grayscale. + } else { + var sector = Math.floor(hue); + var tint1 = val * (1 - sat); + var tint2 = val * (1 - sat * (hue - sector)); + var tint3 = val * (1 - sat * (1 + sector - hue)); + var red, + green, + blue; + if (sector === 1) { + // Yellow to green. + red = tint2; + green = val; + blue = tint1; + } else if (sector === 2) { + // Green to cyan. + red = tint1; + green = val; + blue = tint3; + } else if (sector === 3) { + // Cyan to blue. + red = tint1; + green = tint2; + blue = val; + } else if (sector === 4) { + // Blue to magenta. + red = tint3; + green = tint1; + blue = val; + } else if (sector === 5) { + // Magenta to red. + red = val; + green = tint1; + blue = tint2; + } else { + // Red to yellow (sector could be 0 or 6). + red = val; + green = tint3; + blue = tint1; + } + RGBA = [ + red, + green, + blue, + hsba[3] + ]; + } + return RGBA; + }, + /** + * Convert an HSLA array to HSBA. + */ + _hslaToHSBA: function _hslaToHSBA(hsla) { + var hue = hsla[0]; + var sat = hsla[1]; + var li = hsla[2]; + // Calculate brightness. + var val; + if (li < 0.5) { + val = (1 + sat) * li; + } else { + val = li + sat - li * sat; + } // Convert saturation. + + sat = 2 * (val - li) / val; + // Hue and alpha stay the same. + return [hue, + sat, + val, + hsla[3]]; + }, + /** + * Convert an HSLA array to RGBA. + * + * We need to change basis from HSLA to something that can be more easily be + * projected onto RGBA. We will choose hue and brightness as our first two + * components, and pick a convenient third one ('zest') so that we don't need + * to calculate formal HSBA saturation. + */ + _hslaToRGBA: function _hslaToRGBA(hsla) { + var hue = hsla[0] * 6; // We will split hue into 6 sectors. + var sat = hsla[1]; + var li = hsla[2]; + var RGBA = [ + ]; + if (sat === 0) { + RGBA = [ + li, + li, + li, + hsla[3] + ]; // Return early if grayscale. + } else { + // Calculate brightness. + var val; + if (li < 0.5) { + val = (1 + sat) * li; + } else { + val = li + sat - li * sat; + } // Define zest. + + var zest = 2 * li - val; + // Implement projection (project onto green by default). + var hzvToRGB = function hzvToRGB(hue, zest, val) { + if (hue < 0) { + // Hue must wrap to allow projection onto red and blue. + hue += 6; + } else if (hue >= 6) { + hue -= 6; + } + if (hue < 1) { + // Red to yellow (increasing green). + return zest + (val - zest) * hue; + } else if (hue < 3) { + // Yellow to cyan (greatest green). + return val; + } else if (hue < 4) { + // Cyan to blue (decreasing green). + return zest + (val - zest) * (4 - hue); + } else { + // Blue to red (least green). + return zest; + } + }; + // Perform projections, offsetting hue as necessary. + RGBA = [ + hzvToRGB(hue + 2, zest, val), + hzvToRGB(hue, zest, val), + hzvToRGB(hue - 2, zest, val), + hsla[3] + ]; + } + return RGBA; + }, + /** + * Convert an RGBA array to HSBA. + */ + _rgbaToHSBA: function _rgbaToHSBA(rgba) { + var red = rgba[0]; + var green = rgba[1]; + var blue = rgba[2]; + var val = Math.max(red, green, blue); + var chroma = val - Math.min(red, green, blue); + var hue, + sat; + if (chroma === 0) { + // Return early if grayscale. + hue = 0; + sat = 0; + } else { + sat = chroma / val; + if (red === val) { + // Magenta to yellow. + hue = (green - blue) / chroma; + } else if (green === val) { + // Yellow to cyan. + hue = 2 + (blue - red) / chroma; + } else if (blue === val) { + // Cyan to magenta. + hue = 4 + (red - green) / chroma; + } + if (hue < 0) { + // Confine hue to the interval [0, 1). + hue += 6; + } else if (hue >= 6) { + hue -= 6; + } + } + return [hue / 6, + sat, + val, + rgba[3]]; + }, + /** + * Convert an RGBA array to HSLA. + */ + _rgbaToHSLA: function _rgbaToHSLA(rgba) { + var red = rgba[0]; + var green = rgba[1]; + var blue = rgba[2]; + var val = Math.max(red, green, blue); + var min = Math.min(red, green, blue); + var li = val + min; // We will halve this later. + var chroma = val - min; + var hue, + sat; + if (chroma === 0) { + // Return early if grayscale. + hue = 0; + sat = 0; + } else { + if (li < 1) { + sat = chroma / li; + } else { + sat = chroma / (2 - li); + } + if (red === val) { + // Magenta to yellow. + hue = (green - blue) / chroma; + } else if (green === val) { + // Yellow to cyan. + hue = 2 + (blue - red) / chroma; + } else if (blue === val) { + // Cyan to magenta. + hue = 4 + (red - green) / chroma; + } + if (hue < 0) { + // Confine hue to the interval [0, 1). + hue += 6; + } else if (hue >= 6) { + hue -= 6; + } + } + return [hue / 6, + sat, + li / 2, + rgba[3]]; + } + }; + var _default = _main.default.ColorConversion; + exports.default = _default; + }, + { + '../core/main': 303 + } + ], + 288: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.map'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + _dereq_('./p5.Color'); + _dereq_('../core/friendly_errors/validate_params'); + _dereq_('../core/friendly_errors/file_errors'); + _dereq_('../core/friendly_errors/fes_core'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Color + * @submodule Creating & Reading + * @for p5 + * @requires core + * @requires constants + */ + /** + * Gets the alpha (transparency) value of a color. + * + * `alpha()` extracts the alpha value from a + * p5.Color object, an array of color components, or + * a CSS color string. + * + * @method alpha + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the alpha value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let c = color(0, 126, 255, 102); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'alphaValue' to 102. + * let alphaValue = alpha(c); + * + * // Draw the right rectangle. + * fill(alphaValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light blue and the right one is charcoal gray.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a color array. + * let c = [0, 126, 255, 102]; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'alphaValue' to 102. + * let alphaValue = alpha(c); + * + * // Draw the left rectangle. + * fill(alphaValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light blue and the right one is charcoal gray.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a CSS color string. + * let c = 'rgba(0, 126, 255, 0.4)'; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'alphaValue' to 102. + * let alphaValue = alpha(c); + * + * // Draw the right rectangle. + * fill(alphaValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light blue and the right one is charcoal gray.'); + * } + * + *
        + */ + + _main.default.prototype.alpha = function (c) { + _main.default._validateParameters('alpha', arguments); + return this.color(c)._getAlpha(); + }; + /** + * Gets the blue value of a color. + * + * `blue()` extracts the blue value from a + * p5.Color object, an array of color components, or + * a CSS color string. + * + * By default, `blue()` returns a color's blue value in the range 0 + * to 255. If the colorMode() is set to RGB, it + * returns the blue value in the given range. + * + * @method blue + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the blue value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object using RGB values. + * let c = color(175, 100, 220); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'blueValue' to 220. + * let blueValue = blue(c); + * + * // Draw the right rectangle. + * fill(0, 0, blueValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is royal blue.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a color array. + * let c = [175, 100, 220]; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'blueValue' to 220. + * let blueValue = blue(c); + * + * // Draw the right rectangle. + * fill(0, 0, blueValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is royal blue.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a CSS color string. + * let c = 'rgb(175, 100, 220)'; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'blueValue' to 220. + * let blueValue = blue(c); + * + * // Draw the right rectangle. + * fill(0, 0, blueValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is royal blue.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use RGB color with values in the range 0-100. + * colorMode(RGB, 100); + * + * // Create a p5.Color object using RGB values. + * let c = color(69, 39, 86); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'blueValue' to 86. + * let blueValue = blue(c); + * + * // Draw the right rectangle. + * fill(0, 0, blueValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is royal blue.'); + * } + * + *
        + */ + _main.default.prototype.blue = function (c) { + _main.default._validateParameters('blue', arguments); + return this.color(c)._getBlue(); + }; + /** + * Gets the brightness value of a color. + * + * `brightness()` extracts the HSB brightness value from a + * p5.Color object, an array of color components, or + * a CSS color string. + * + * By default, `brightness()` returns a color's HSB brightness in the range 0 + * to 100. If the colorMode() is set to HSB, it + * returns the brightness value in the given range. + * + * @method brightness + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the brightness value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSB color. + * colorMode(HSB); + * + * // Create a p5.Color object. + * let c = color(0, 50, 100); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'brightValue' to 100. + * let brightValue = brightness(c); + * + * // Draw the right rectangle. + * fill(brightValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is white.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSB color. + * colorMode(HSB); + * + * // Create a color array. + * let c = [0, 50, 100]; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'brightValue' to 100. + * let brightValue = brightness(c); + * + * // Draw the right rectangle. + * fill(brightValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is white.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSB color. + * colorMode(HSB); + * + * // Create a CSS color string. + * let c = 'rgb(255, 128, 128)'; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'brightValue' to 100. + * let brightValue = brightness(c); + * + * // Draw the right rectangle. + * fill(brightValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is white.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSB color with values in the range 0-255. + * colorMode(HSB, 255); + * + * // Create a p5.Color object. + * let c = color(0, 127, 255); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'brightValue' to 255. + * let brightValue = brightness(c); + * + * // Draw the right rectangle. + * fill(brightValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is white.'); + * } + * + *
        + */ + _main.default.prototype.brightness = function (c) { + _main.default._validateParameters('brightness', arguments); + return this.color(c)._getBrightness(); + }; + /** + * Creates a p5.Color object. + * + * By default, the parameters are interpreted as RGB values. Calling + * `color(255, 204, 0)` will return a bright yellow color. The way these + * parameters are interpreted may be changed with the + * colorMode() function. + * + * The version of `color()` with one parameter interprets the value one of two + * ways. If the parameter is a number, it's interpreted as a grayscale value. + * If the parameter is a string, it's interpreted as a CSS color string. + * + * The version of `color()` with two parameters interprets the first one as a + * grayscale value. The second parameter sets the alpha (transparency) value. + * + * The version of `color()` with three parameters interprets them as RGB, HSB, + * or HSL colors, depending on the current `colorMode()`. + * + * The version of `color()` with four parameters interprets them as RGBA, HSBA, + * or HSLA colors, depending on the current `colorMode()`. The last parameter + * sets the alpha (transparency) value. + * + * @method color + * @param {Number} gray number specifying value between white and black. + * @param {Number} [alpha] alpha value relative to current color range + * (default is 0-255). + * @return {p5.Color} resulting color. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object using RGB values. + * let c = color(255, 204, 0); + * + * // Draw the square. + * fill(c); + * noStroke(); + * square(30, 20, 55); + * + * describe('A yellow square on a gray canvas.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object using RGB values. + * let c1 = color(255, 204, 0); + * + * // Draw the left circle. + * fill(c1); + * noStroke(); + * circle(25, 25, 80); + * + * // Create a p5.Color object using a grayscale value. + * let c2 = color(65); + * + * // Draw the right circle. + * fill(c2); + * circle(75, 75, 80); + * + * describe( + * 'Two circles on a gray canvas. The circle in the top-left corner is yellow and the one at the bottom-right is gray.' + * ); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object using a named color. + * let c = color('magenta'); + * + * // Draw the square. + * fill(c); + * noStroke(); + * square(20, 20, 60); + * + * describe('A magenta square on a gray canvas.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object using a hex color code. + * let c1 = color('#0f0'); + * + * // Draw the left rectangle. + * fill(c1); + * noStroke(); + * rect(0, 10, 45, 80); + * + * // Create a p5.Color object using a hex color code. + * let c2 = color('#00ff00'); + * + * // Draw the right rectangle. + * fill(c2); + * rect(55, 10, 45, 80); + * + * describe('Two bright green rectangles on a gray canvas.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object using a RGB color string. + * let c1 = color('rgb(0, 0, 255)'); + * + * // Draw the top-left square. + * fill(c1); + * square(10, 10, 35); + * + * // Create a p5.Color object using a RGB color string. + * let c2 = color('rgb(0%, 0%, 100%)'); + * + * // Draw the top-right square. + * fill(c2); + * square(55, 10, 35); + * + * // Create a p5.Color object using a RGBA color string. + * let c3 = color('rgba(0, 0, 255, 1)'); + * + * // Draw the bottom-left square. + * fill(c3); + * square(10, 55, 35); + * + * // Create a p5.Color object using a RGBA color string. + * let c4 = color('rgba(0%, 0%, 100%, 1)'); + * + * // Draw the bottom-right square. + * fill(c4); + * square(55, 55, 35); + * + * describe('Four blue squares in the corners of a gray canvas.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object using a HSL color string. + * let c1 = color('hsl(160, 100%, 50%)'); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c1); + * rect(0, 10, 45, 80); + * + * // Create a p5.Color object using a HSLA color string. + * let c2 = color('hsla(160, 100%, 50%, 0.5)'); + * + * // Draw the right rectangle. + * fill(c2); + * rect(55, 10, 45, 80); + * + * describe('Two sea green rectangles. A darker rectangle on the left and a brighter one on the right.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object using a HSB color string. + * let c1 = color('hsb(160, 100%, 50%)'); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c1); + * rect(0, 10, 45, 80); + * + * // Create a p5.Color object using a HSBA color string. + * let c2 = color('hsba(160, 100%, 50%, 0.5)'); + * + * // Draw the right rectangle. + * fill(c2); + * rect(55, 10, 45, 80); + * + * describe('Two green rectangles. A darker rectangle on the left and a brighter one on the right.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object using RGB values. + * let c1 = color(50, 55, 100); + * + * // Draw the left rectangle. + * fill(c1); + * rect(0, 10, 45, 80); + * + * // Switch the color mode to HSB. + * colorMode(HSB, 100); + * + * // Create a p5.Color object using HSB values. + * let c2 = color(50, 55, 100); + * + * // Draw the right rectangle. + * fill(c2); + * rect(55, 10, 45, 80); + * + * describe('Two blue rectangles. A darker rectangle on the left and a brighter one on the right.'); + * } + * + *
        + */ + /** + * @method color + * @param {Number} v1 red or hue value relative to + * the current color range. + * @param {Number} v2 green or saturation value + * relative to the current color range. + * @param {Number} v3 blue or brightness value + * relative to the current color range. + * @param {Number} [alpha] + * @return {p5.Color} + */ + /** + * @method color + * @param {String} value a color string. + * @return {p5.Color} + */ + /** + * @method color + * @param {Number[]} values an array containing the red, green, blue, + * and alpha components of the color. + * @return {p5.Color} + */ + /** + * @method color + * @param {p5.Color} color + * @return {p5.Color} + */ + _main.default.prototype.color = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('color', args); + if (args[0] instanceof _main.default.Color) { + return args[0]; // Do nothing if argument is already a color object. + } + var arg = Array.isArray(args[0]) ? args[0] : args; + return new _main.default.Color(this, arg); + }; + /** + * Gets the green value of a color. + * + * `green()` extracts the green value from a + * p5.Color object, an array of color components, or + * a CSS color string. + * + * By default, `green()` returns a color's green value in the range 0 + * to 255. If the colorMode() is set to RGB, it + * returns the green value in the given range. + * + * @method green + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the green value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let c = color(175, 100, 220); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'greenValue' to 100. + * let greenValue = green(c); + * + * // Draw the right rectangle. + * fill(0, greenValue, 0); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is dark green.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a color array. + * let c = [175, 100, 220]; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'greenValue' to 100. + * let greenValue = green(c); + * + * // Draw the right rectangle. + * fill(0, greenValue, 0); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is dark green.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a CSS color string. + * let c = 'rgb(175, 100, 220)'; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'greenValue' to 100. + * let greenValue = green(c); + * + * // Draw the right rectangle. + * fill(0, greenValue, 0); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is dark green.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use RGB color with values in the range 0-100. + * colorMode(RGB, 100); + * + * // Create a p5.Color object using RGB values. + * let c = color(69, 39, 86); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'greenValue' to 39. + * let greenValue = green(c); + * + * // Draw the right rectangle. + * fill(0, greenValue, 0); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is dark green.'); + * } + * + *
        + */ + _main.default.prototype.green = function (c) { + _main.default._validateParameters('green', arguments); + return this.color(c)._getGreen(); + }; + /** + * Gets the hue value of a color. + * + * `hue()` extracts the hue value from a + * p5.Color object, an array of color components, or + * a CSS color string. + * + * Hue describes a color's position on the color wheel. By default, `hue()` + * returns a color's HSL hue in the range 0 to 360. If the + * colorMode() is set to HSB or HSL, it returns the hue + * value in the given mode. + * + * @method hue + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the hue value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSL color. + * colorMode(HSL); + * + * // Create a p5.Color object. + * let c = color(0, 50, 100); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 20, 35, 60); + * + * // Set 'hueValue' to 0. + * let hueValue = hue(c); + * + * // Draw the right rectangle. + * fill(hueValue); + * rect(50, 20, 35, 60); + * + * describe( + * 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.' + * ); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSL color. + * colorMode(HSL); + * + * // Create a color array. + * let c = [0, 50, 100]; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 20, 35, 60); + * + * // Set 'hueValue' to 0. + * let hueValue = hue(c); + * + * // Draw the right rectangle. + * fill(hueValue); + * rect(50, 20, 35, 60); + * + * describe( + * 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.' + * ); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSL color. + * colorMode(HSL); + * + * // Create a CSS color string. + * let c = 'rgb(255, 128, 128)'; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 20, 35, 60); + * + * // Set 'hueValue' to 0. + * let hueValue = hue(c); + * + * // Draw the right rectangle. + * fill(hueValue); + * rect(50, 20, 35, 60); + * + * describe( + * 'Two rectangles. The rectangle on the left is salmon pink and the one on the right is black.' + * ); + * } + * + *
        + */ + _main.default.prototype.hue = function (c) { + _main.default._validateParameters('hue', arguments); + return this.color(c)._getHue(); + }; + /** + * Blends two colors to find a third color between them. + * + * The `amt` parameter specifies the amount to interpolate between the two + * values. 0 is equal to the first color, 0.1 is very near the first color, + * 0.5 is halfway between the two colors, and so on. Negative numbers are set + * to 0. Numbers greater than 1 are set to 1. This differs from the behavior of + * lerp. It's necessary because numbers outside of the + * interval [0, 1] will produce strange and unexpected colors. + * + * The way that colors are interpolated depends on the current + * colorMode(). + * + * @method lerpColor + * @param {p5.Color} c1 interpolate from this color. + * @param {p5.Color} c2 interpolate to this color. + * @param {Number} amt number between 0 and 1. + * @return {p5.Color} interpolated color. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create p5.Color objects to interpolate between. + * let from = color(218, 165, 32); + * let to = color(72, 61, 139); + * + * // Create intermediate colors. + * let interA = lerpColor(from, to, 0.33); + * let interB = lerpColor(from, to, 0.66); + * + * // Draw the left rectangle. + * noStroke(); + * fill(from); + * rect(10, 20, 20, 60); + * + * // Draw the left-center rectangle. + * fill(interA); + * rect(30, 20, 20, 60); + * + * // Draw the right-center rectangle. + * fill(interB); + * rect(50, 20, 20, 60); + * + * // Draw the right rectangle. + * fill(to); + * rect(70, 20, 20, 60); + * + * describe( + * 'Four rectangles. From left to right, the rectangles are tan, brown, brownish purple, and purple.' + * ); + * } + * + *
        + */ + _main.default.prototype.lerpColor = function (c1, c2, amt) { + _main.default._validateParameters('lerpColor', arguments); + var mode = this._colorMode; + var maxes = this._colorMaxes; + var l0, + l1, + l2, + l3; + var fromArray, + toArray; + if (mode === constants.RGB) { + fromArray = c1.levels.map(function (level) { + return level / 255; + }); + toArray = c2.levels.map(function (level) { + return level / 255; + }); + } else if (mode === constants.HSB) { + c1._getBrightness(); // Cache hsba so it definitely exists. + c2._getBrightness(); + fromArray = c1.hsba; + toArray = c2.hsba; + } else if (mode === constants.HSL) { + c1._getLightness(); // Cache hsla so it definitely exists. + c2._getLightness(); + fromArray = c1.hsla; + toArray = c2.hsla; + } else { + throw new Error(''.concat(mode, ' cannot be used for interpolation.')); + } // Prevent extrapolation. + + amt = Math.max(Math.min(amt, 1), 0); + // Define lerp here itself if user isn't using math module. + // Maintains the definition as found in math/calculation.js + if (typeof this.lerp === 'undefined') { + this.lerp = function (start, stop, amt) { + return amt * (stop - start) + start; + }; + } // Perform interpolation. + + if (mode === constants.RGB) { + l0 = this.lerp(fromArray[0], toArray[0], amt); + } // l0 (hue) has to wrap around (and it's between 0 and 1) + else { + // find shortest path in the color wheel + if (Math.abs(fromArray[0] - toArray[0]) > 0.5) { + if (fromArray[0] > toArray[0]) { + toArray[0] += 1; + } else { + fromArray[0] += 1; + } + } + l0 = this.lerp(fromArray[0], toArray[0], amt); + if (l0 >= 1) { + l0 -= 1; + } + } + l1 = this.lerp(fromArray[1], toArray[1], amt); + l2 = this.lerp(fromArray[2], toArray[2], amt); + l3 = this.lerp(fromArray[3], toArray[3], amt); + // Scale components. + l0 *= maxes[mode][0]; + l1 *= maxes[mode][1]; + l2 *= maxes[mode][2]; + l3 *= maxes[mode][3]; + return this.color(l0, l1, l2, l3); + }; + /** + * Gets the lightness value of a color. + * + * `lightness()` extracts the HSL lightness value from a + * p5.Color object, an array of color components, or + * a CSS color string. + * + * By default, `lightness()` returns a color's HSL lightness in the range 0 + * to 100. If the colorMode() is set to HSL, it + * returns the lightness value in the given range. + * + * @method lightness + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the lightness value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use HSL color. + * colorMode(HSL); + * + * // Create a p5.Color object using HSL values. + * let c = color(0, 100, 75); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'lightValue' to 75. + * let lightValue = lightness(c); + * + * // Draw the right rectangle. + * fill(lightValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is gray.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use HSL color. + * colorMode(HSL); + * + * // Create a color array. + * let c = [0, 100, 75]; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'lightValue' to 75. + * let lightValue = lightness(c); + * + * // Draw the right rectangle. + * fill(lightValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is gray.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use HSL color. + * colorMode(HSL); + * + * // Create a CSS color string. + * let c = 'rgb(255, 128, 128)'; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'lightValue' to 75. + * let lightValue = lightness(c); + * + * // Draw the right rectangle. + * fill(lightValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is gray.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use HSL color with values in the range 0-255. + * colorMode(HSL, 255); + * + * // Create a p5.Color object using HSL values. + * let c = color(0, 255, 191.5); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'lightValue' to 191.5. + * let lightValue = lightness(c); + * + * // Draw the right rectangle. + * fill(lightValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is gray.'); + * } + * + *
        + */ + _main.default.prototype.lightness = function (c) { + _main.default._validateParameters('lightness', arguments); + return this.color(c)._getLightness(); + }; + /** + * Gets the red value of a color. + * + * `red()` extracts the red value from a + * p5.Color object, an array of color components, or + * a CSS color string. + * + * By default, `red()` returns a color's red value in the range 0 + * to 255. If the colorMode() is set to RGB, it + * returns the red value in the given range. + * + * @method red + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the red value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let c = color(175, 100, 220); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'redValue' to 175. + * let redValue = red(c); + * + * // Draw the right rectangle. + * fill(redValue, 0, 0); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is red.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a color array. + * let c = [175, 100, 220]; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'redValue' to 175. + * let redValue = red(c); + * + * // Draw the right rectangle. + * fill(redValue, 0, 0); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is red.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a CSS color string. + * let c = 'rgb(175, 100, 220)'; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'redValue' to 175. + * let redValue = red(c); + * + * // Draw the right rectangle. + * fill(redValue, 0, 0); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is red.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use RGB color with values in the range 0-100. + * colorMode(RGB, 100); + * + * // Create a p5.Color object. + * let c = color(69, 39, 86); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'redValue' to 69. + * let redValue = red(c); + * + * // Draw the right rectangle. + * fill(redValue, 0, 0); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is light purple and the right one is red.'); + * } + * + *
        + */ + _main.default.prototype.red = function (c) { + _main.default._validateParameters('red', arguments); + return this.color(c)._getRed(); + }; + /** + * Gets the saturation value of a color. + * + * `saturation()` extracts the saturation value from a + * p5.Color object, an array of color components, or + * a CSS color string. + * + * Saturation is scaled differently in HSB and HSL. By default, `saturation()` + * returns a color's HSL saturation in the range 0 to 100. If the + * colorMode() is set to HSB or HSL, it returns the + * saturation value in the given mode. + * + * @method saturation + * @param {p5.Color|Number[]|String} color p5.Color object, array of + * color components, or CSS color string. + * @return {Number} the saturation value + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use HSB color. + * colorMode(HSB); + * + * // Create a p5.Color object. + * let c = color(0, 50, 100); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'satValue' to 50. + * let satValue = saturation(c); + * + * // Draw the right rectangle. + * fill(satValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is dark gray.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use HSB color. + * colorMode(HSB); + * + * // Create a color array. + * let c = [0, 50, 100]; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'satValue' to 100. + * let satValue = saturation(c); + * + * // Draw the right rectangle. + * fill(satValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is gray.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use HSB color. + * colorMode(HSB); + * + * // Create a CSS color string. + * let c = 'rgb(255, 128, 128)'; + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'satValue' to 100. + * let satValue = saturation(c); + * + * // Draw the right rectangle. + * fill(satValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is gray.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use HSL color. + * colorMode(HSL); + * + * // Create a p5.Color object. + * let c = color(0, 100, 75); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'satValue' to 100. + * let satValue = saturation(c); + * + * // Draw the right rectangle. + * fill(satValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is white.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use HSL color with values in the range 0-255. + * colorMode(HSL, 255); + * + * // Create a p5.Color object. + * let c = color(0, 255, 191.5); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 15, 35, 70); + * + * // Set 'satValue' to 255. + * let satValue = saturation(c); + * + * // Draw the right rectangle. + * fill(satValue); + * rect(50, 15, 35, 70); + * + * describe('Two rectangles. The left one is salmon pink and the right one is white.'); + * } + * + *
        + */ + _main.default.prototype.saturation = function (c) { + _main.default._validateParameters('saturation', arguments); + return this.color(c)._getSaturation(); + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/friendly_errors/fes_core': 294, + '../core/friendly_errors/file_errors': 295, + '../core/friendly_errors/validate_params': 298, + '../core/main': 303, + './p5.Color': 289, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 289: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.trim'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + var _color_conversion = _interopRequireDefault(_dereq_('./color_conversion')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * @module Color + * @submodule Creating & Reading + * @for p5 + * @requires core + * @requires constants + * @requires color_conversion + */ + /** + * CSS named colors. + */ + + var namedColors = { + 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', + rebeccapurple: '#663399', + 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' + }; + /** + * These regular expressions are used to build up the patterns for matching + * viable CSS color strings: fragmenting the regexes in this way increases the + * legibility and comprehensibility of the code. + * + * Note that RGB values of .9 are not parsed by IE, but are supported here for + * color string consistency. + */ + var WHITESPACE = /\s*/; // Match zero or more whitespace characters. + var INTEGER = /(\d{1,3})/; // Match integers: 79, 255, etc. + var DECIMAL = /((?:\d+(?:\.\d+)?)|(?:\.\d+))/; // Match 129.6, 79, .9, etc. + var PERCENT = new RegExp(''.concat(DECIMAL.source, '%')); // Match 12.9%, 79%, .9%, etc. + /** + * Full color string patterns. The capture groups are necessary. + */ + var colorPatterns = { + // Match colors in format #XXX, e.g. #416. + HEX3: /^#([a-f0-9])([a-f0-9])([a-f0-9])$/i, + // Match colors in format #XXXX, e.g. #5123. + HEX4: /^#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])$/i, + // Match colors in format #XXXXXX, e.g. #b4d455. + HEX6: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i, + // Match colors in format #XXXXXXXX, e.g. #b4d45535. + HEX8: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i, + // Match colors in format rgb(R, G, B), e.g. rgb(255, 0, 128). + RGB: new RegExp(['^rgb\\(', + INTEGER.source, + ',', + INTEGER.source, + ',', + INTEGER.source, + '\\)$'].join(WHITESPACE.source), 'i'), + // Match colors in format rgb(R%, G%, B%), e.g. rgb(100%, 0%, 28.9%). + RGB_PERCENT: new RegExp(['^rgb\\(', + PERCENT.source, + ',', + PERCENT.source, + ',', + PERCENT.source, + '\\)$'].join(WHITESPACE.source), 'i'), + // Match colors in format rgb(R, G, B, A), e.g. rgb(255, 0, 128, 0.25). + RGBA: new RegExp(['^rgba\\(', + INTEGER.source, + ',', + INTEGER.source, + ',', + INTEGER.source, + ',', + DECIMAL.source, + '\\)$'].join(WHITESPACE.source), 'i'), + // Match colors in format rgb(R%, G%, B%, A), e.g. rgb(100%, 0%, 28.9%, 0.5). + RGBA_PERCENT: new RegExp(['^rgba\\(', + PERCENT.source, + ',', + PERCENT.source, + ',', + PERCENT.source, + ',', + DECIMAL.source, + '\\)$'].join(WHITESPACE.source), 'i'), + // Match colors in format hsla(H, S%, L%), e.g. hsl(100, 40%, 28.9%). + HSL: new RegExp(['^hsl\\(', + INTEGER.source, + ',', + PERCENT.source, + ',', + PERCENT.source, + '\\)$'].join(WHITESPACE.source), 'i'), + // Match colors in format hsla(H, S%, L%, A), e.g. hsla(100, 40%, 28.9%, 0.5). + HSLA: new RegExp(['^hsla\\(', + INTEGER.source, + ',', + PERCENT.source, + ',', + PERCENT.source, + ',', + DECIMAL.source, + '\\)$'].join(WHITESPACE.source), 'i'), + // Match colors in format hsb(H, S%, B%), e.g. hsb(100, 40%, 28.9%). + HSB: new RegExp(['^hsb\\(', + INTEGER.source, + ',', + PERCENT.source, + ',', + PERCENT.source, + '\\)$'].join(WHITESPACE.source), 'i'), + // Match colors in format hsba(H, S%, B%, A), e.g. hsba(100, 40%, 28.9%, 0.5). + HSBA: new RegExp(['^hsba\\(', + INTEGER.source, + ',', + PERCENT.source, + ',', + PERCENT.source, + ',', + DECIMAL.source, + '\\)$'].join(WHITESPACE.source), 'i') + }; + /** + * A class to describe a color. + * + * Each `p5.Color` object stores the color mode + * and level maxes that were active during its construction. These values are + * used to interpret the arguments passed to the object's constructor. They + * also determine output formatting such as when + * saturation() is called. + * + * Color is stored internally as an array of ideal RGBA values in floating + * point form, normalized from 0 to 1. These values are used to calculate the + * closest screen colors, which are RGBA levels from 0 to 255. Screen colors + * are sent to the renderer. + * + * When different color representations are calculated, the results are cached + * for performance. These values are normalized, floating-point numbers. + * + * Note: color() is the recommended way to create an + * instance of this class. + * + * @class p5.Color + * @constructor + * @param {p5} [pInst] pointer to p5 instance. + * + * @param {Number[]|String} vals an array containing the color values + * for red, green, blue and alpha channel + * or CSS color. + */ + _main.default.Color = /*#__PURE__*/ function () { + function Color(pInst, vals) { + _classCallCheck(this, Color); + // Record color mode and maxes at time of construction. + this._storeModeAndMaxes(pInst._colorMode, pInst._colorMaxes); + // Calculate normalized RGBA values. + if (![constants.RGB, + constants.HSL, + constants.HSB].includes(this.mode)) { + throw new Error(''.concat(this.mode, ' is an invalid colorMode.')); + } else { + this._array = Color._parseInputs.apply(this, vals); + } // Expose closest screen color. + + this._calculateLevels(); + } /** + * Returns the color formatted as a `String`. + * + * Calling `myColor.toString()` can be useful for debugging, as in + * `print(myColor.toString())`. It's also helpful for using p5.js with other + * libraries. + * + * The parameter, `format`, is optional. If a format string is passed, as in + * `myColor.toString('#rrggbb')`, it will determine how the color string is + * formatted. By default, color strings are formatted as `'rgba(r, g, b, a)'`. + * + * @method toString + * @param {String} [format] how the color string will be formatted. + * Leaving this empty formats the string as rgba(r, g, b, a). + * '#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes. + * 'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode. + * 'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels. + * 'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages. + * @return {String} the formatted string. + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let myColor = color('darkorchid'); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the text. + * text(myColor.toString('#rrggbb'), 50, 50); + * + * describe('The text "#9932cc" written in purple on a gray background.'); + * } + * + *
        + */ + + _createClass(Color, [ + { + key: 'toString', + value: function toString(format) { + var a = this.levels; + var f = this._array; + var alpha = f[3]; // String representation uses normalized alpha + switch (format) { + case '#rrggbb': + return '#'.concat(a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16), a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16), a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16)); + case '#rrggbbaa': + return '#'.concat(a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16), a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16), a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16), a[3] < 16 ? '0'.concat(a[3].toString(16)) : a[3].toString(16)); + case '#rgb': + return '#'.concat(Math.round(f[0] * 15).toString(16), Math.round(f[1] * 15).toString(16), Math.round(f[2] * 15).toString(16)); + case '#rgba': + return '#'.concat(Math.round(f[0] * 15).toString(16), Math.round(f[1] * 15).toString(16), Math.round(f[2] * 15).toString(16), Math.round(f[3] * 15).toString(16)); + case 'rgb': + return 'rgb('.concat(a[0], ', ', a[1], ', ', a[2], ')'); + case 'rgb%': + return 'rgb('.concat((100 * f[0]).toPrecision(3), '%, ', (100 * f[1]).toPrecision(3), '%, ', (100 * f[2]).toPrecision(3), '%)'); + case 'rgba%': + return 'rgba('.concat((100 * f[0]).toPrecision(3), '%, ', (100 * f[1]).toPrecision(3), '%, ', (100 * f[2]).toPrecision(3), '%, ', (100 * f[3]).toPrecision(3), '%)'); + case 'hsb': + case 'hsv': + if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + return 'hsb('.concat(this.hsba[0] * this.maxes[constants.HSB][0], ', ', this.hsba[1] * this.maxes[constants.HSB][1], ', ', this.hsba[2] * this.maxes[constants.HSB][2], ')'); + case 'hsb%': + case 'hsv%': + if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + return 'hsb('.concat((100 * this.hsba[0]).toPrecision(3), '%, ', (100 * this.hsba[1]).toPrecision(3), '%, ', (100 * this.hsba[2]).toPrecision(3), '%)'); + case 'hsba': + case 'hsva': + if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + return 'hsba('.concat(this.hsba[0] * this.maxes[constants.HSB][0], ', ', this.hsba[1] * this.maxes[constants.HSB][1], ', ', this.hsba[2] * this.maxes[constants.HSB][2], ', ', alpha, ')'); + case 'hsba%': + case 'hsva%': + if (!this.hsba) this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + return 'hsba('.concat((100 * this.hsba[0]).toPrecision(3), '%, ', (100 * this.hsba[1]).toPrecision(3), '%, ', (100 * this.hsba[2]).toPrecision(3), '%, ', (100 * alpha).toPrecision(3), '%)'); + case 'hsl': + if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + return 'hsl('.concat(this.hsla[0] * this.maxes[constants.HSL][0], ', ', this.hsla[1] * this.maxes[constants.HSL][1], ', ', this.hsla[2] * this.maxes[constants.HSL][2], ')'); + case 'hsl%': + if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + return 'hsl('.concat((100 * this.hsla[0]).toPrecision(3), '%, ', (100 * this.hsla[1]).toPrecision(3), '%, ', (100 * this.hsla[2]).toPrecision(3), '%)'); + case 'hsla': + if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + return 'hsla('.concat(this.hsla[0] * this.maxes[constants.HSL][0], ', ', this.hsla[1] * this.maxes[constants.HSL][1], ', ', this.hsla[2] * this.maxes[constants.HSL][2], ', ', alpha, ')'); + case 'hsla%': + if (!this.hsla) this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + return 'hsl('.concat((100 * this.hsla[0]).toPrecision(3), '%, ', (100 * this.hsla[1]).toPrecision(3), '%, ', (100 * this.hsla[2]).toPrecision(3), '%, ', (100 * alpha).toPrecision(3), '%)'); + case 'rgba': + default: + return 'rgba('.concat(a[0], ',', a[1], ',', a[2], ',', alpha, ')'); + } + } /** + * Sets the red component of a color. + * + * The range depends on the colorMode(). In the + * default RGB mode it's between 0 and 255. + * + * @method setRed + * @param {Number} red the new red value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let c = color(255, 128, 128); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 20, 35, 60); + * + * // Change the red value. + * c.setRed(64); + * + * // Draw the right rectangle. + * fill(c); + * rect(50, 20, 35, 60); + * + * describe('Two rectangles. The left one is salmon pink and the right one is teal.'); + * } + * + *
        + */ + + }, + { + key: 'setRed', + value: function setRed(new_red) { + this._array[0] = new_red / this.maxes[constants.RGB][0]; + this._calculateLevels(); + } /** + * Sets the green component of a color. + * + * The range depends on the colorMode(). In the + * default RGB mode it's between 0 and 255. + * + * @method setGreen + * @param {Number} green the new green value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let c = color(255, 128, 128); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 20, 35, 60); + * + * // Change the green value. + * c.setGreen(255); + * + * // Draw the right rectangle. + * fill(c); + * rect(50, 20, 35, 60); + * + * describe('Two rectangles. The left one is salmon pink and the right one is yellow.'); + * } + * + *
        + **/ + + }, + { + key: 'setGreen', + value: function setGreen(new_green) { + this._array[1] = new_green / this.maxes[constants.RGB][1]; + this._calculateLevels(); + } /** + * Sets the blue component of a color. + * + * The range depends on the colorMode(). In the + * default RGB mode it's between 0 and 255. + * + * @method setBlue + * @param {Number} blue the new blue value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let c = color(255, 128, 128); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 20, 35, 60); + * + * // Change the blue value. + * c.setBlue(255); + * + * // Draw the right rectangle. + * fill(c); + * rect(50, 20, 35, 60); + * + * describe('Two rectangles. The left one is salmon pink and the right one is pale fuchsia.'); + * } + * + *
        + **/ + + }, + { + key: 'setBlue', + value: function setBlue(new_blue) { + this._array[2] = new_blue / this.maxes[constants.RGB][2]; + this._calculateLevels(); + } /** + * Sets the alpha (transparency) value of a color. + * + * The range depends on the + * colorMode(). In the default RGB mode it's + * between 0 and 255. + * + * @method setAlpha + * @param {Number} alpha the new alpha value. + * + * @example + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let c = color(255, 128, 128); + * + * // Draw the left rectangle. + * noStroke(); + * fill(c); + * rect(15, 20, 35, 60); + * + * // Change the alpha value. + * c.setAlpha(128); + * + * // Draw the right rectangle. + * fill(c); + * rect(50, 20, 35, 60); + * + * describe('Two rectangles. The left one is salmon pink and the right one is faded pink.'); + * } + * + *
        + **/ + + }, + { + key: 'setAlpha', + value: function setAlpha(new_alpha) { + this._array[3] = new_alpha / this.maxes[this.mode][3]; + this._calculateLevels(); + } // calculates and stores the closest screen levels + + }, + { + key: '_calculateLevels', + value: function _calculateLevels() { + var array = this._array; + // (loop backwards for performance) + var levels = this.levels = new Array(array.length); + for (var i = array.length - 1; i >= 0; --i) { + levels[i] = Math.round(array[i] * 255); + } // Clear cached HSL/HSB values + + this.hsla = null; + this.hsba = null; + } + }, + { + key: '_getAlpha', + value: function _getAlpha() { + return this._array[3] * this.maxes[this.mode][3]; + } // stores the color mode and maxes in this instance of Color + // for later use (by _parseInputs()) + + }, + { + key: '_storeModeAndMaxes', + value: function _storeModeAndMaxes(new_mode, new_maxes) { + this.mode = new_mode; + this.maxes = new_maxes; + } + }, + { + key: '_getMode', + value: function _getMode() { + return this.mode; + } + }, + { + key: '_getMaxes', + value: function _getMaxes() { + return this.maxes; + } + }, + { + key: '_getBlue', + value: function _getBlue() { + return this._array[2] * this.maxes[constants.RGB][2]; + } + }, + { + key: '_getBrightness', + value: function _getBrightness() { + if (!this.hsba) { + this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + } + return this.hsba[2] * this.maxes[constants.HSB][2]; + } + }, + { + key: '_getGreen', + value: function _getGreen() { + return this._array[1] * this.maxes[constants.RGB][1]; + } /** + * Hue is the same in HSB and HSL, but the maximum value may be different. + * This function will return the HSB-normalized saturation when supplied with + * an HSB color object, but will default to the HSL-normalized saturation + * otherwise. + */ + + }, + { + key: '_getHue', + value: function _getHue() { + if (this.mode === constants.HSB) { + if (!this.hsba) { + this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + } + return this.hsba[0] * this.maxes[constants.HSB][0]; + } else { + if (!this.hsla) { + this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + } + return this.hsla[0] * this.maxes[constants.HSL][0]; + } + } + }, + { + key: '_getLightness', + value: function _getLightness() { + if (!this.hsla) { + this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + } + return this.hsla[2] * this.maxes[constants.HSL][2]; + } + }, + { + key: '_getRed', + value: function _getRed() { + return this._array[0] * this.maxes[constants.RGB][0]; + } /** + * Saturation is scaled differently in HSB and HSL. This function will return + * the HSB saturation when supplied with an HSB color object, but will default + * to the HSL saturation otherwise. + */ + + }, + { + key: '_getSaturation', + value: function _getSaturation() { + if (this.mode === constants.HSB) { + if (!this.hsba) { + this.hsba = _color_conversion.default._rgbaToHSBA(this._array); + } + return this.hsba[1] * this.maxes[constants.HSB][1]; + } else { + if (!this.hsla) { + this.hsla = _color_conversion.default._rgbaToHSLA(this._array); + } + return this.hsla[1] * this.maxes[constants.HSL][1]; + } + } /** + * For a number of different inputs, returns a color formatted as [r, g, b, a] + * arrays, with each component normalized between 0 and 1. + * + * @private + * @param {Array} [...args] An 'array-like' object that represents a list of + * arguments + * @return {Number[]} a color formatted as [r, g, b, a] + * Example: + * input ==> output + * g ==> [g, g, g, 255] + * g,a ==> [g, g, g, a] + * r, g, b ==> [r, g, b, 255] + * r, g, b, a ==> [r, g, b, a] + * [g] ==> [g, g, g, 255] + * [g, a] ==> [g, g, g, a] + * [r, g, b] ==> [r, g, b, 255] + * [r, g, b, a] ==> [r, g, b, a] + * @example + *
        + * + * // todo + * // + * // describe(''); + * + *
        + */ + + } + ], [ + { + key: '_parseInputs', + value: function _parseInputs(r, g, b, a) { + var numArgs = arguments.length; + var mode = this.mode; + var maxes = this.maxes[mode]; + var results = [ + ]; + var i; + if (numArgs >= 3) { + // Argument is a list of component values. + results[0] = r / maxes[0]; + results[1] = g / maxes[1]; + results[2] = b / maxes[2]; + // Alpha may be undefined, so default it to 100%. + if (typeof a === 'number') { + results[3] = a / maxes[3]; + } else { + results[3] = 1; + } // Constrain components to the range [0,1]. + // (loop backwards for performance) + + for (i = results.length - 1; i >= 0; --i) { + var result = results[i]; + if (result < 0) { + results[i] = 0; + } else if (result > 1) { + results[i] = 1; + } + } // Convert to RGBA and return. + + if (mode === constants.HSL) { + return _color_conversion.default._hslaToRGBA(results); + } else if (mode === constants.HSB) { + return _color_conversion.default._hsbaToRGBA(results); + } else { + return results; + } + } else if (numArgs === 1 && typeof r === 'string') { + var str = r.trim().toLowerCase(); + // Return if string is a named colour. + if (namedColors[str]) { + return Color._parseInputs.call(this, namedColors[str]); + } // Try RGBA pattern matching. + + if (colorPatterns.HEX3.test(str)) { + // #rgb + results = colorPatterns.HEX3.exec(str).slice(1).map(function (color) { + return parseInt(color + color, 16) / 255; + }); + results[3] = 1; + return results; + } else if (colorPatterns.HEX6.test(str)) { + // #rrggbb + results = colorPatterns.HEX6.exec(str).slice(1).map(function (color) { + return parseInt(color, 16) / 255; + }); + results[3] = 1; + return results; + } else if (colorPatterns.HEX4.test(str)) { + // #rgba + results = colorPatterns.HEX4.exec(str).slice(1).map(function (color) { + return parseInt(color + color, 16) / 255; + }); + return results; + } else if (colorPatterns.HEX8.test(str)) { + // #rrggbbaa + results = colorPatterns.HEX8.exec(str).slice(1).map(function (color) { + return parseInt(color, 16) / 255; + }); + return results; + } else if (colorPatterns.RGB.test(str)) { + // rgb(R,G,B) + results = colorPatterns.RGB.exec(str).slice(1).map(function (color) { + return color / 255; + }); + results[3] = 1; + return results; + } else if (colorPatterns.RGB_PERCENT.test(str)) { + // rgb(R%,G%,B%) + results = colorPatterns.RGB_PERCENT.exec(str).slice(1).map(function (color) { + return parseFloat(color) / 100; + }); + results[3] = 1; + return results; + } else if (colorPatterns.RGBA.test(str)) { + // rgba(R,G,B,A) + results = colorPatterns.RGBA.exec(str).slice(1).map(function (color, idx) { + if (idx === 3) { + return parseFloat(color); + } + return color / 255; + }); + return results; + } else if (colorPatterns.RGBA_PERCENT.test(str)) { + // rgba(R%,G%,B%,A%) + results = colorPatterns.RGBA_PERCENT.exec(str).slice(1).map(function (color, idx) { + if (idx === 3) { + return parseFloat(color); + } + return parseFloat(color) / 100; + }); + return results; + } // Try HSLA pattern matching. + + if (colorPatterns.HSL.test(str)) { + // hsl(H,S,L) + results = colorPatterns.HSL.exec(str).slice(1).map(function (color, idx) { + if (idx === 0) { + return parseInt(color, 10) / 360; + } + return parseInt(color, 10) / 100; + }); + results[3] = 1; + } else if (colorPatterns.HSLA.test(str)) { + // hsla(H,S,L,A) + results = colorPatterns.HSLA.exec(str).slice(1).map(function (color, idx) { + if (idx === 0) { + return parseInt(color, 10) / 360; + } else if (idx === 3) { + return parseFloat(color); + } + return parseInt(color, 10) / 100; + }); + } + results = results.map(function (value) { + return Math.max(Math.min(value, 1), 0); + }); + if (results.length) { + return _color_conversion.default._hslaToRGBA(results); + } // Try HSBA pattern matching. + + if (colorPatterns.HSB.test(str)) { + // hsb(H,S,B) + results = colorPatterns.HSB.exec(str).slice(1).map(function (color, idx) { + if (idx === 0) { + return parseInt(color, 10) / 360; + } + return parseInt(color, 10) / 100; + }); + results[3] = 1; + } else if (colorPatterns.HSBA.test(str)) { + // hsba(H,S,B,A) + results = colorPatterns.HSBA.exec(str).slice(1).map(function (color, idx) { + if (idx === 0) { + return parseInt(color, 10) / 360; + } else if (idx === 3) { + return parseFloat(color); + } + return parseInt(color, 10) / 100; + }); + } + if (results.length) { + // (loop backwards for performance) + for (i = results.length - 1; i >= 0; --i) { + results[i] = Math.max(Math.min(results[i], 1), 0); + } + return _color_conversion.default._hsbaToRGBA(results); + } // Input did not match any CSS color pattern: default to white. + + results = [ + 1, + 1, + 1, + 1 + ]; + } else if ((numArgs === 1 || numArgs === 2) && typeof r === 'number') { + // 'Grayscale' mode. + /** + * For HSB and HSL, interpret the gray level as a brightness/lightness + * value (they are equivalent when chroma is zero). For RGB, normalize the + * gray level according to the blue maximum. + */ + results[0] = r / maxes[2]; + results[1] = r / maxes[2]; + results[2] = r / maxes[2]; + // Alpha may be undefined, so default it to 100%. + if (typeof g === 'number') { + results[3] = g / maxes[3]; + } else { + results[3] = 1; + } // Constrain components to the range [0,1]. + + results = results.map(function (value) { + return Math.max(Math.min(value, 1), 0); + }); + } else { + throw new Error(''.concat(arguments, 'is not a valid color representation.')); + } + return results; + } + } + ]); + return Color; + }(); + var _default = _main.default.Color; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + './color_conversion': 287, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.constructor': 209, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.trim': 224, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 290: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.fill'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + _dereq_('./p5.Color'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Color + * @submodule Setting + * @for p5 + * @requires core + * @requires constants + */ + /** + * Starts defining a shape that will mask any shapes drawn afterward. + * + * Any shapes drawn between `beginClip()` and + * endClip() will add to the mask shape. The mask + * will apply to anything drawn after endClip(). + * + * The parameter, `options`, is optional. If an object with an `invert` + * property is passed, as in `beginClip({ invert: true })`, it will be used to + * set the masking mode. `{ invert: true }` inverts the mask, creating holes + * in shapes that are masked. `invert` is `false` by default. + * + * Masks can be contained between the + * push() and pop() functions. + * Doing so allows unmasked shapes to be drawn after masked shapes. + * + * Masks can also be defined in a callback function that's passed to + * clip(). + * + * @method beginClip + * @param {Object} [options] an object containing clip settings. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a mask. + * beginClip(); + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * endClip(); + * + * // Draw a backing shape. + * square(5, 5, 45); + * + * describe('A white triangle and circle on a gray background.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an inverted mask. + * beginClip({ invert: true }); + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * endClip(); + * + * // Draw a backing shape. + * square(5, 5, 45); + * + * describe('A white square at the top-left corner of a gray square. The white square has a triangle and a circle cut out of it.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * noStroke(); + * + * // Draw a masked shape. + * push(); + * // Create a mask. + * beginClip(); + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * endClip(); + * + * // Draw a backing shape. + * square(5, 5, 45); + * pop(); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw an inverted masked shape. + * push(); + * // Create an inverted mask. + * beginClip({ invert: true }); + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * endClip(); + * + * // Draw a backing shape. + * square(5, 5, 45); + * pop(); + * + * describe('In the top left, a white triangle and circle. In the bottom right, a white square with a triangle and circle cut out of it.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A silhouette of a rotating torus colored fuchsia.'); + * } + * + * function draw() { + * background(200); + * + * // Create a mask. + * beginClip(); + * push(); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * scale(0.5); + * torus(30, 15); + * pop(); + * endClip(); + * + * // Draw a backing shape. + * noStroke(); + * fill('fuchsia'); + * plane(100); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A silhouette of a rotating torus colored with a gradient from cyan to purple.'); + * } + * + * function draw() { + * background(200); + * + * // Create a mask. + * beginClip(); + * push(); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * scale(0.5); + * torus(30, 15); + * pop(); + * endClip(); + * + * // Draw a backing shape. + * noStroke(); + * beginShape(QUAD_STRIP); + * fill(0, 255, 255); + * vertex(-width / 2, -height / 2); + * vertex(width / 2, -height / 2); + * fill(100, 0, 100); + * vertex(-width / 2, height / 2); + * vertex(width / 2, height / 2); + * endShape(); + * } + * + *
        + */ + + _main.default.prototype.beginClip = function () { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + this._renderer.beginClip(options); + }; + /** + * Ends defining a mask that was started with + * beginClip(). + * + * @method endClip + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a mask. + * beginClip(); + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * endClip(); + * + * // Draw a backing shape. + * square(5, 5, 45); + * + * describe('A white triangle and circle on a gray background.'); + * } + * + *
        + */ + _main.default.prototype.endClip = function () { + this._renderer.endClip(); + }; + /** + * Defines a shape that will mask any shapes drawn afterward. + * + * The first parameter, `callback`, is a function that defines the mask. + * Any shapes drawn in `callback` will add to the mask shape. The mask + * will apply to anything drawn after `clip()` is called. + * + * The second parameter, `options`, is optional. If an object with an `invert` + * property is passed, as in `beginClip({ invert: true })`, it will be used to + * set the masking mode. `{ invert: true }` inverts the mask, creating holes + * in shapes that are masked. `invert` is `false` by default. + * + * Masks can be contained between the + * push() and pop() functions. + * Doing so allows unmasked shapes to be drawn after masked shapes. + * + * Masks can also be defined with beginClip() + * and endClip(). + * + * @method clip + * @param {Function} callback a function that draws the mask shape. + * @param {Object} [options] an object containing clip settings. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a mask. + * clip(mask); + * + * // Draw a backing shape. + * square(5, 5, 45); + * + * describe('A white triangle and circle on a gray background.'); + * } + * + * // Declare a function that defines the mask. + * function mask() { + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an inverted mask. + * clip(mask, { invert: true }); + * + * // Draw a backing shape. + * square(5, 5, 45); + * + * describe('A white square at the top-left corner of a gray square. The white square has a triangle and a circle cut out of it.'); + * } + * + * // Declare a function that defines the mask. + * function mask() { + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * noStroke(); + * + * // Draw a masked shape. + * push(); + * // Create a mask. + * clip(mask); + * + * // Draw a backing shape. + * square(5, 5, 45); + * pop(); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw an inverted masked shape. + * push(); + * // Create an inverted mask. + * clip(mask, { invert: true }); + * + * // Draw a backing shape. + * square(5, 5, 45); + * pop(); + * + * describe('In the top left, a white triangle and circle. In the bottom right, a white square with a triangle and circle cut out of it.'); + * } + * + * // Declare a function that defines the mask. + * function mask() { + * triangle(15, 37, 30, 13, 43, 37); + * circle(45, 45, 7); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A silhouette of a rotating torus colored fuchsia.'); + * } + * + * function draw() { + * background(200); + * + * // Create a mask. + * clip(mask); + * + * // Draw a backing shape. + * noStroke(); + * fill('fuchsia'); + * plane(100); + * } + * + * // Declare a function that defines the mask. + * function mask() { + * push(); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * scale(0.5); + * torus(30, 15); + * pop(); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A silhouette of a rotating torus colored with a gradient from cyan to purple.'); + * } + * + * function draw() { + * background(200); + * + * // Create a mask. + * clip(mask); + * + * // Draw a backing shape. + * noStroke(); + * beginShape(QUAD_STRIP); + * fill(0, 255, 255); + * vertex(-width / 2, -height / 2); + * vertex(width / 2, -height / 2); + * fill(100, 0, 100); + * vertex(-width / 2, height / 2); + * vertex(width / 2, height / 2); + * endShape(); + * } + * + * // Declare a function that defines the mask. + * function mask() { + * push(); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * scale(0.5); + * torus(30, 15); + * pop(); + * } + * + *
        + */ + _main.default.prototype.clip = function (callback, options) { + this._renderer.beginClip(options); + callback(); + this._renderer.endClip(options); + }; + /** + * Sets the color used for the background of the canvas. + * + * By default, the background is transparent. `background()` is typically used + * within draw() to clear the display window at the + * beginning of each frame. It can also be used inside + * setup() to set the background on the first frame + * of animation. + * + * The version of `background()` with one parameter interprets the value one + * of four ways. If the parameter is a `Number`, it's interpreted as a grayscale + * value. If the parameter is a `String`, it's interpreted as a CSS color string. + * RGB, RGBA, HSL, HSLA, hex, and named color strings are supported. If the + * parameter is a p5.Color object, it will be used as + * the background color. If the parameter is a + * p5.Image object, it will be used as the background + * image. + * + * The version of `background()` with two parameters interprets the first one + * as a grayscale value. The second parameter sets the alpha (transparency) + * value. + * + * The version of `background()` with three parameters interprets them as RGB, + * HSB, or HSL colors, depending on the current + * colorMode(). By default, colors are specified + * in RGB values. Calling `background(255, 204, 0)` sets the background a bright + * yellow color. + * + * @method background + * @param {p5.Color} color any value created by the color() function + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // A grayscale value. + * background(51); + * + * describe('A canvas with a dark charcoal gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // A grayscale value and an alpha value. + * background(51, 0.4); + * describe('A canvas with a transparent gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // R, G & B values. + * background(255, 204, 0); + * + * describe('A canvas with a yellow background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Use HSB color. + * colorMode(HSB); + * + * // H, S & B values. + * background(255, 204, 100); + * + * describe('A canvas with a royal blue background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // A CSS named color. + * background('red'); + * + * describe('A canvas with a red background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Three-digit hex RGB notation. + * background('#fae'); + * + * describe('A canvas with a pink background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Six-digit hex RGB notation. + * background('#222222'); + * + * describe('A canvas with a black background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Integer RGB notation. + * background('rgb(0, 255, 0)'); + * + * describe('A canvas with a bright green background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Integer RGBA notation. + * background('rgba(0, 255, 0, 0.25)'); + * + * describe('A canvas with a transparent green background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Percentage RGB notation. + * background('rgb(100%, 0%, 10%)'); + * + * describe('A canvas with a red background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Percentage RGBA notation. + * background('rgba(100%, 0%, 100%, 0.5)'); + * + * describe('A canvas with a transparent purple background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // A p5.Color object. + * let c = color(0, 0, 255); + * background(c); + * + * describe('A canvas with a blue background.'); + * } + * + *
        + * + */ + /** + * @method background + * @param {String} colorstring color string, possible formats include: integer + * rgb() or rgba(), percentage rgb() or rgba(), + * 3-digit hex, 6-digit hex. + * @param {Number} [a] opacity of the background relative to current + * color range (default is 0-255). + * @chainable + */ + /** + * @method background + * @param {Number} gray specifies a value between white and black. + * @param {Number} [a] + * @chainable + */ + /** + * @method background + * @param {Number} v1 red value if color mode is RGB, or hue value if color mode is HSB. + * @param {Number} v2 green value if color mode is RGB, or saturation value if color mode is HSB. + * @param {Number} v3 blue value if color mode is RGB, or brightness value if color mode is HSB. + * @param {Number} [a] + * @chainable + */ + /** + * @method background + * @param {Number[]} values an array containing the red, green, blue + * and alpha components of the color. + * @chainable + */ + /** + * @method background + * @param {p5.Image} image image created with loadImage() + * or createImage(), + * to set as background. + * (must be same size as the sketch window). + * @param {Number} [a] + * @chainable + */ + _main.default.prototype.background = function () { + var _this$_renderer; + (_this$_renderer = this._renderer).background.apply(_this$_renderer, arguments); + return this; + }; + /** + * Clears the pixels on the canvas. + * + * `clear()` makes every pixel 100% transparent. Calling `clear()` doesn't + * clear objects created by `createX()` functions such as + * createGraphics(), + * createVideo(), and + * createImg(). These objects will remain + * unchanged after calling `clear()` and can be redrawn. + * + * In WebGL mode, this function can clear the screen to a specific color. It + * interprets four numeric parameters as normalized RGBA color values. It also + * clears the depth buffer. If you are not using the WebGL renderer, these + * parameters will have no effect. + * + * @method clear + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A gray square. White circles are drawn as the user moves the mouse. The circles disappear when the user presses the mouse.'); + * } + * + * function draw() { + * circle(mouseX, mouseY, 20); + * } + * + * function mousePressed() { + * clear(); + * background(200); + * } + * + *
        + * + *
        + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * + * pg = createGraphics(60, 60); + * pg.background(200); + * pg.noStroke(); + * pg.circle(pg.width / 2, pg.height / 2, 15); + * image(pg, 20, 20); + * + * describe('A white circle drawn on a gray square. The square gets smaller when the mouse is pressed.'); + * } + * + * function mousePressed() { + * clear(); + * image(pg, 20, 20); + * } + * + *
        + * + * @param {Number} [r] normalized red value. + * @param {Number} [g] normalized green value. + * @param {Number} [b] normalized blue value. + * @param {Number} [a] normalized alpha value. + */ + _main.default.prototype.clear = function () { + var _r = (arguments.length <= 0 ? undefined : arguments[0]) || 0; + var _g = (arguments.length <= 1 ? undefined : arguments[1]) || 0; + var _b = (arguments.length <= 2 ? undefined : arguments[2]) || 0; + var _a = (arguments.length <= 3 ? undefined : arguments[3]) || 0; + this._renderer.clear(_r, _g, _b, _a); + return this; + }; + /** + * Changes the way color values are interpreted. + * + * By default, the `Number` parameters for fill(), + * stroke(), + * background(), and + * color() are defined by values between 0 and 255 + * using the RGB color model. This is equivalent to calling + * `colorMode(RGB, 255)`. Pure red is `color(255, 0, 0)` in this model. + * + * Calling `colorMode(RGB, 100)` sets colors to use RGB color values + * between 0 and 100. Pure red is `color(100, 0, 0)` in this model. + * + * Calling `colorMode(HSB)` or `colorMode(HSL)` changes to HSB or HSL system + * instead of RGB. Pure red is `color(0, 100, 100)` in HSB and + * `color(0, 100, 50)` in HSL. + * + * p5.Color objects remember the mode that they were + * created in. Changing modes doesn't affect their appearance. + * + * @method colorMode + * @param {Constant} mode either RGB, HSB or HSL, corresponding to + * Red/Green/Blue and Hue/Saturation/Brightness + * (or Lightness). + * @param {Number} [max] range for all values. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Fill with pure red. + * fill(255, 0, 0); + * + * circle(50, 50, 25); + * + * describe('A gray square with a red circle at its center.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use RGB color with values in the range 0-100. + * colorMode(RGB, 100); + * + * // Fill with pure red. + * fill(100, 0, 0); + * + * circle(50, 50, 25); + * + * describe('A gray square with a red circle at its center.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSB color. + * colorMode(HSB); + * + * // Fill with pure red. + * fill(0, 100, 100); + * + * circle(50, 50, 25); + * + * describe('A gray square with a red circle at its center.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSL color. + * colorMode(HSL); + * + * // Fill with pure red. + * fill(0, 100, 50); + * + * circle(50, 50, 25); + * + * describe('A gray square with a red circle at its center.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Use RGB color with values in the range 0-100. + * colorMode(RGB, 100); + * + * for (let x = 0; x < 100; x += 1) { + * for (let y = 0; y < 100; y += 1) { + * stroke(x, y, 0); + * point(x, y); + * } + * } + * + * describe( + * 'A diagonal green to red gradient from bottom-left to top-right with shading transitioning to black at top-left corner.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Use HSB color with values in the range 0-100. + * colorMode(HSB, 100); + * + * for (let x = 0; x < 100; x += 1) { + * for (let y = 0; y < 100; y += 1) { + * stroke(x, y, 100); + * point(x, y); + * } + * } + * + * describe('A rainbow gradient from left-to-right. Brightness transitions to white at the top.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Color object. + * let myColor = color(180, 175, 230); + * background(myColor); + * + * // Use RGB color with values in the range 0-1. + * colorMode(RGB, 1); + * + * // Get the red, green, and blue color components. + * let redValue = red(myColor); + * let greenValue = green(myColor); + * let blueValue = blue(myColor); + * + * // Round the color components for display. + * redValue = round(redValue, 2); + * greenValue = round(greenValue, 2); + * blueValue = round(blueValue, 2); + * + * // Display the color components. + * text(`Red: ${redValue}`, 10, 10, 80, 80); + * text(`Green: ${greenValue}`, 10, 40, 80, 80); + * text(`Blue: ${blueValue}`, 10, 70, 80, 80); + * + * describe('A purple canvas with the red, green, and blue decimal values of the color written on it.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(255); + * + * // Use RGB color with alpha values in the range 0-1. + * colorMode(RGB, 255, 255, 255, 1); + * + * noFill(); + * strokeWeight(4); + * stroke(255, 0, 10, 0.3); + * circle(40, 40, 50); + * circle(50, 60, 50); + * + * describe('Two overlapping translucent pink circle outlines.'); + * } + * + *
        + */ + /** + * @method colorMode + * @param {Constant} mode + * @param {Number} max1 range for the red or hue depending on the + * current color mode. + * @param {Number} max2 range for the green or saturation depending + * on the current color mode. + * @param {Number} max3 range for the blue or brightness/lightness + * depending on the current color mode. + * @param {Number} [maxA] range for the alpha. + * @chainable + */ + _main.default.prototype.colorMode = function (mode, max1, max2, max3, maxA) { + _main.default._validateParameters('colorMode', arguments); + if (mode === constants.RGB || mode === constants.HSB || mode === constants.HSL) { + // Set color mode. + this._colorMode = mode; + // Set color maxes. + var maxes = this._colorMaxes[mode]; + if (arguments.length === 2) { + maxes[0] = max1; // Red + maxes[1] = max1; // Green + maxes[2] = max1; // Blue + maxes[3] = max1; // Alpha + } else if (arguments.length === 4) { + maxes[0] = max1; // Red + maxes[1] = max2; // Green + maxes[2] = max3; // Blue + } else if (arguments.length === 5) { + maxes[0] = max1; // Red + maxes[1] = max2; // Green + maxes[2] = max3; // Blue + maxes[3] = maxA; // Alpha + } + } + return this; + }; + /** + * Sets the color used to fill shapes. + * + * Calling `fill(255, 165, 0)` or `fill('orange')` means all shapes drawn + * after the fill command will be filled with the color orange. + * + * The version of `fill()` with one parameter interprets the value one of + * three ways. If the parameter is a `Number`, it's interpreted as a grayscale + * value. If the parameter is a `String`, it's interpreted as a CSS color + * string. A p5.Color object can also be provided to + * set the fill color. + * + * The version of `fill()` with three parameters interprets them as RGB, HSB, + * or HSL colors, depending on the current + * colorMode(). The default color space is RGB, + * with each value in the range from 0 to 255. + * + * @method fill + * @param {Number} v1 red value if color mode is RGB or hue value if color mode is HSB. + * @param {Number} v2 green value if color mode is RGB or saturation value if color mode is HSB. + * @param {Number} v3 blue value if color mode is RGB or brightness value if color mode is HSB. + * @param {Number} [alpha] + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // A grayscale value. + * fill(51); + * square(20, 20, 60); + * + * describe('A dark charcoal gray square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // R, G & B values. + * fill(255, 204, 0); + * square(20, 20, 60); + * + * describe('A yellow square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(100); + * + * // Use HSB color. + * colorMode(HSB); + * + * // H, S & B values. + * fill(255, 204, 100); + * square(20, 20, 60); + * + * describe('A royal blue square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // A CSS named color. + * fill('red'); + * square(20, 20, 60); + * + * describe('A red square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Three-digit hex RGB notation. + * fill('#fae'); + * square(20, 20, 60); + * + * describe('A pink square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Six-digit hex RGB notation. + * fill('#A251FA'); + * square(20, 20, 60); + * + * describe('A purple square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Integer RGB notation. + * fill('rgb(0, 255, 0)'); + * square(20, 20, 60); + * + * describe('A bright green square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Integer RGBA notation. + * fill('rgba(0, 255, 0, 0.25)'); + * square(20, 20, 60); + * + * describe('A soft green rectange with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Percentage RGB notation. + * fill('rgb(100%, 0%, 10%)'); + * square(20, 20, 60); + * + * describe('A red square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Percentage RGBA notation. + * fill('rgba(100%, 0%, 100%, 0.5)'); + * square(20, 20, 60); + * + * describe('A dark fuchsia square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // A p5.Color object. + * let c = color(0, 0, 255); + * fill(c); + * square(20, 20, 60); + * + * describe('A blue square with a black outline.'); + * } + * + *
        + */ + /** + * @method fill + * @param {String} value a color string. + * @chainable + */ + /** + * @method fill + * @param {Number} gray a grayscale value. + * @param {Number} [alpha] + * @chainable + */ + /** + * @method fill + * @param {Number[]} values an array containing the red, green, blue & + * and alpha components of the color. + * @chainable + */ + /** + * @method fill + * @param {p5.Color} color the fill color. + * @chainable + */ + _main.default.prototype.fill = function () { + var _this$_renderer2; + this._renderer._setProperty('_fillSet', true); + this._renderer._setProperty('_doFill', true); + (_this$_renderer2 = this._renderer).fill.apply(_this$_renderer2, arguments); + return this; + }; + /** + * Disables setting the fill color for shapes. + * + * Calling `noFill()` is the same as making the fill completely transparent, + * as in `fill(0, 0)`. If both noStroke() and + * `noFill()` are called, nothing will be drawn to the screen. + * + * @method noFill + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw the top square. + * square(32, 10, 35); + * + * // Draw the bottom square. + * noFill(); + * square(32, 55, 35); + * + * describe('A white square on above an empty square. Both squares have black outlines.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A purple cube wireframe spinning on a black canvas.'); + * } + * + * function draw() { + * background(0); + * + * // Style the box. + * noFill(); + * stroke(100, 100, 240); + * + * // Rotate the coordinates. + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * + * // Draw the box. + * box(45); + * } + * + *
        + */ + _main.default.prototype.noFill = function () { + this._renderer._setProperty('_doFill', false); + return this; + }; + /** + * Disables drawing points, lines, and the outlines of shapes. + * + * Calling `noStroke()` is the same as making the stroke completely transparent, + * as in `stroke(0, 0)`. If both `noStroke()` and + * noFill() are called, nothing will be drawn to the + * screen. + * + * @method noStroke + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * noStroke(); + * square(20, 20, 60); + * + * describe('A white square with no outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A pink cube with no edge outlines spinning on a black canvas.'); + * } + * + * function draw() { + * background(0); + * + * // Style the box. + * noStroke(); + * fill(240, 150, 150); + * + * // Rotate the coordinates. + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * + * // Draw the box. + * box(45); + * } + * + *
        + */ + _main.default.prototype.noStroke = function () { + this._renderer._setProperty('_doStroke', false); + return this; + }; + /** + * Sets the color used to draw points, lines, and the outlines of shapes. + * + * Calling `stroke(255, 165, 0)` or `stroke('orange')` means all shapes drawn + * after calling `stroke()` will be filled with the color orange. The way + * these parameters are interpreted may be changed with the + * colorMode() function. + * + * The version of `stroke()` with one parameter interprets the value one of + * three ways. If the parameter is a `Number`, it's interpreted as a grayscale + * value. If the parameter is a `String`, it's interpreted as a CSS color + * string. A p5.Color object can also be provided to + * set the stroke color. + * + * The version of `stroke()` with two parameters interprets the first one as a + * grayscale value. The second parameter sets the alpha (transparency) value. + * + * The version of `stroke()` with three parameters interprets them as RGB, HSB, + * or HSL colors, depending on the current `colorMode()`. + * + * The version of `stroke()` with four parameters interprets them as RGBA, HSBA, + * or HSLA colors, depending on the current `colorMode()`. The last parameter + * sets the alpha (transparency) value. + * + * @method stroke + * @param {Number} v1 red value if color mode is RGB or hue value if color mode is HSB. + * @param {Number} v2 green value if color mode is RGB or saturation value if color mode is HSB. + * @param {Number} v3 blue value if color mode is RGB or brightness value if color mode is HSB. + * @param {Number} [alpha] + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // A grayscale value. + * strokeWeight(4); + * stroke(51); + * square(20, 20, 60); + * + * describe('A white square with a dark charcoal gray outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // R, G & B values. + * stroke(255, 204, 0); + * strokeWeight(4); + * square(20, 20, 60); + * + * describe('A white square with a yellow outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use HSB color. + * colorMode(HSB); + * + * // H, S & B values. + * strokeWeight(4); + * stroke(255, 204, 100); + * square(20, 20, 60); + * + * describe('A white square with a royal blue outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // A CSS named color. + * stroke('red'); + * strokeWeight(4); + * square(20, 20, 60); + * + * describe('A white square with a red outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Three-digit hex RGB notation. + * stroke('#fae'); + * strokeWeight(4); + * square(20, 20, 60); + * + * describe('A white square with a pink outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Six-digit hex RGB notation. + * stroke('#222222'); + * strokeWeight(4); + * square(20, 20, 60); + * + * describe('A white square with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Integer RGB notation. + * stroke('rgb(0, 255, 0)'); + * strokeWeight(4); + * square(20, 20, 60); + * + * describe('A whiite square with a bright green outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Integer RGBA notation. + * stroke('rgba(0, 255, 0, 0.25)'); + * strokeWeight(4); + * square(20, 20, 60); + * + * describe('A white square with a soft green outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Percentage RGB notation. + * stroke('rgb(100%, 0%, 10%)'); + * strokeWeight(4); + * square(20, 20, 60); + * + * describe('A white square with a red outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Percentage RGBA notation. + * stroke('rgba(100%, 0%, 100%, 0.5)'); + * strokeWeight(4); + * square(20, 20, 60); + * + * describe('A white square with a dark fuchsia outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // A p5.Color object. + * stroke(color(0, 0, 255)); + * strokeWeight(4); + * square(20, 20, 60); + * + * describe('A white square with a blue outline.'); + * } + * + *
        + */ + /** + * @method stroke + * @param {String} value a color string. + * @chainable + */ + /** + * @method stroke + * @param {Number} gray a grayscale value. + * @param {Number} [alpha] + * @chainable + */ + /** + * @method stroke + * @param {Number[]} values an array containing the red, green, blue, + * and alpha components of the color. + * @chainable + */ + /** + * @method stroke + * @param {p5.Color} color the stroke color. + * @chainable + */ + _main.default.prototype.stroke = function () { + var _this$_renderer3; + this._renderer._setProperty('_strokeSet', true); + this._renderer._setProperty('_doStroke', true); + (_this$_renderer3 = this._renderer).stroke.apply(_this$_renderer3, arguments); + return this; + }; + /** + * Starts using shapes to erase parts of the canvas. + * + * All drawing that follows `erase()` will subtract from the canvas, revealing + * the web page underneath. The erased areas will become transparent, allowing + * the content behind the canvas to show through. The + * fill(), stroke(), and + * blendMode() have no effect once `erase()` is + * called. + * + * The `erase()` function has two optional parameters. The first parameter + * sets the strength of erasing by the shape's interior. A value of 0 means + * that no erasing will occur. A value of 255 means that the shape's interior + * will fully erase the content underneath. The default value is 255 + * (full strength). + * + * The second parameter sets the strength of erasing by the shape's edge. A + * value of 0 means that no erasing will occur. A value of 255 means that the + * shape's edge will fully erase the content underneath. The default value is + * 255 (full strength). + * + * To cancel the erasing effect, use the noErase() + * function. + * + * `erase()` has no effect on drawing done with the + * image() and + * background() functions. + * + * @method erase + * @param {Number} [strengthFill] a number (0-255) for the strength of erasing under a shape's interior. + * Defaults to 255, which is full strength. + * @param {Number} [strengthStroke] a number (0-255) for the strength of erasing under a shape's edge. + * Defaults to 255, which is full strength. + * + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(100, 100, 250); + * + * // Draw a pink square. + * fill(250, 100, 100); + * square(20, 20, 60); + * + * // Erase a circular area. + * erase(); + * circle(25, 30, 30); + * noErase(); + * + * describe('A purple canvas with a pink square in the middle. A circle is erased from the top-left, leaving a hole.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(100, 100, 250); + * + * // Draw a pink square. + * fill(250, 100, 100); + * square(20, 20, 60); + * + * // Erase a circular area. + * strokeWeight(5); + * erase(150, 255); + * circle(25, 30, 30); + * noErase(); + * + * describe('A purple canvas with a pink square in the middle. A circle at the top-left partially erases its interior and a fully erases its outline.'); + * } + * + *
        + */ + _main.default.prototype.erase = function () { + var opacityFill = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 255; + var opacityStroke = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 255; + this._renderer.erase(opacityFill, opacityStroke); + return this; + }; + /** + * Ends erasing that was started with erase(). + * + * The fill(), stroke(), and + * blendMode() settings will return to what they + * were prior to calling erase(). + * + * @method noErase + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(235, 145, 15); + * + * // Draw the left rectangle. + * noStroke(); + * fill(30, 45, 220); + * rect(30, 10, 10, 80); + * + * // Erase a circle. + * erase(); + * circle(50, 50, 60); + * noErase(); + * + * // Draw the right rectangle. + * rect(70, 10, 10, 80); + * + * describe('An orange canvas with two tall blue rectangles. A circular hole in the center erases the rectangle on the left but not the one on the right.'); + * } + * + *
        + */ + _main.default.prototype.noErase = function () { + this._renderer.noErase(); + return this; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + './p5.Color': 289, + 'core-js/modules/es.array.fill': 173, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 291: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.QUADRATIC = exports.LINEAR = exports._CTX_MIDDLE = exports._DEFAULT_LEADMULT = exports._DEFAULT_TEXT_FILL = exports.WORD = exports.CHAR = exports.BOLDITALIC = exports.BOLD = exports.ITALIC = exports.NORMAL = exports.BLUR = exports.ERODE = exports.DILATE = exports.POSTERIZE = exports.INVERT = exports.OPAQUE = exports.GRAY = exports.THRESHOLD = exports.BURN = exports.DODGE = exports.SOFT_LIGHT = exports.HARD_LIGHT = exports.OVERLAY = exports.REPLACE = exports.SCREEN = exports.MULTIPLY = exports.EXCLUSION = exports.SUBTRACT = exports.DIFFERENCE = exports.LIGHTEST = exports.DARKEST = exports.ADD = exports.REMOVE = exports.BLEND = exports.UP_ARROW = exports.TAB = exports.SHIFT = exports.RIGHT_ARROW = exports.RETURN = exports.OPTION = exports.LEFT_ARROW = exports.ESCAPE = exports.ENTER = exports.DOWN_ARROW = exports.DELETE = exports.CONTROL = exports.BACKSPACE = exports.ALT = exports.AUTO = exports.HSL = exports.HSB = exports.RGB = exports.MITER = exports.BEVEL = exports.ROUND = exports.SQUARE = exports.PROJECT = exports.PIE = exports.CHORD = exports.OPEN = exports.CLOSE = exports.TESS = exports.QUAD_STRIP = exports.QUADS = exports.TRIANGLE_STRIP = exports.TRIANGLE_FAN = exports.TRIANGLES = exports.LINE_LOOP = exports.LINE_STRIP = exports.LINES = exports.POINTS = exports.BASELINE = exports.BOTTOM = exports.TOP = exports.CENTER = exports.LEFT = exports.RIGHT = exports.RADIUS = exports.CORNERS = exports.CORNER = exports.RAD_TO_DEG = exports.DEG_TO_RAD = exports.RADIANS = exports.DEGREES = exports.TWO_PI = exports.TAU = exports.QUARTER_PI = exports.PI = exports.HALF_PI = exports.WAIT = exports.TEXT = exports.MOVE = exports.HAND = exports.CROSS = exports.ARROW = exports.WEBGL2 = exports.WEBGL = exports.P2D = exports.VERSION = void 0; + exports.RGBA = exports.HALF_FLOAT = exports.FLOAT = exports.UNSIGNED_INT = exports.UNSIGNED_BYTE = exports.COVER = exports.CONTAIN = exports.FALLBACK = exports.LABEL = exports.AXES = exports.GRID = exports._DEFAULT_FILL = exports._DEFAULT_STROKE = exports.PORTRAIT = exports.LANDSCAPE = exports.SMOOTH = exports.FLAT = exports.MIRROR = exports.CLAMP = exports.REPEAT = exports.NEAREST = exports.IMAGE = exports.IMMEDIATE = exports.TEXTURE = exports.FILL = exports.STROKE = exports.CURVE = exports.BEZIER = void 0; + /** + * @module Constants + * @submodule Constants + * @for p5 + */ + var _PI = Math.PI; + /** + * Version of this p5.js. + * @property {String} VERSION + * @final + */ + var VERSION = '1.9.4'; + // GRAPHICS RENDERER + /** + * The default, two-dimensional renderer. + * @property {String} P2D + * @final + */ + exports.VERSION = VERSION; + var P2D = 'p2d'; + /** + * One of the two render modes in p5.js, used for computationally intensive tasks like 3D rendering and shaders. + * + * `WEBGL` differs from the default `P2D` renderer in the following ways: + * + * - **Coordinate System** - When drawing in `WEBGL` mode, the origin point (0,0,0) is located at the center of the screen, not the top-left corner. See the learn page about coordinates and transformations. + * - **3D Shapes** - `WEBGL` mode can be used to draw 3-dimensional shapes like box(), sphere(), cone(), and more. See the learn page about custom geometry to make more complex objects. + * - **Shape Detail** - When drawing in `WEBGL` mode, you can specify how smooth curves should be drawn by using a `detail` parameter. See the wiki section about shapes for a more information and an example. + * - **Textures** - A texture is like a skin that wraps onto a shape. See the wiki section about textures for examples of mapping images onto surfaces with textures. + * - **Materials and Lighting** - `WEBGL` offers different types of lights like ambientLight() to place around a scene. Materials like specularMaterial() reflect the lighting to convey shape and depth. See the learn page for styling and appearance to experiment with different combinations. + * - **Camera** - The viewport of a `WEBGL` sketch can be adjusted by changing camera attributes. See the learn page section about cameras for an explanation of camera controls. + * - **Text** - `WEBGL` requires opentype/truetype font files to be preloaded using loadFont(). See the wiki section about text for details, along with a workaround. + * - **Shaders** - Shaders are hardware accelerated programs that can be used for a variety of effects and graphics. See the introduction to shaders to get started with shaders in p5.js. + * - **Graphics Acceleration** - `WEBGL` mode uses the graphics card instead of the CPU, so it may help boost the performance of your sketch (example: drawing more shapes on the screen at once). + * + * To learn more about WEBGL mode, check out all the interactive WEBGL tutorials in the "Learn" section of this website, or read the wiki article "Getting started with WebGL in p5". + * + * @property {String} WEBGL + * @final + */ + exports.P2D = P2D; + var WEBGL = 'webgl'; + /** + * One of the two possible values of a WebGL canvas (either WEBGL or WEBGL2), + * which can be used to determine what capabilities the rendering environment + * has. + * @property {String} WEBGL2 + * @final + */ + exports.WEBGL = WEBGL; + var WEBGL2 = 'webgl2'; + // ENVIRONMENT + /** + * @property {String} ARROW + * @final + */ + exports.WEBGL2 = WEBGL2; + var ARROW = 'default'; + /** + * @property {String} CROSS + * @final + */ + exports.ARROW = ARROW; + var CROSS = 'crosshair'; + /** + * @property {String} HAND + * @final + */ + exports.CROSS = CROSS; + var HAND = 'pointer'; + /** + * @property {String} MOVE + * @final + */ + exports.HAND = HAND; + var MOVE = 'move'; + /** + * @property {String} TEXT + * @final + */ + exports.MOVE = MOVE; + var TEXT = 'text'; + /** + * @property {String} WAIT + * @final + */ + exports.TEXT = TEXT; + var WAIT = 'wait'; + // TRIGONOMETRY + /** + * A `Number` constant that's approximately 1.5708. + * + * `HALF_PI` is half the value of the mathematical constant π. It's useful for + * many tasks that involve rotation and oscillation. For example, calling + * `rotate(HALF_PI)` rotates the coordinate system `HALF_PI` radians, which is + * a quarter turn (90˚). + * + * Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` + * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. + * + * @property {Number} HALF_PI + * @final + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw an arc from 0 to HALF_PI. + * arc(50, 50, 80, 80, 0, HALF_PI); + * + * describe('The bottom-right quarter of a circle drawn in white on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw a line. + * line(0, 0, 40, 0); + * + * // Rotate a quarter turn. + * rotate(HALF_PI); + * + * // Draw the same line, rotated. + * line(0, 0, 40, 0); + * + * describe('Two black lines on a gray background. One line extends from the center to the right. The other line extends from the center to the bottom.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A red circle and a blue circle oscillate from left to right on a gray background. The red circle appears to chase the blue circle.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Calculate the x-coordinates. + * let x1 = 40 * sin(frameCount * 0.05); + * let x2 = 40 * sin(frameCount * 0.05 + HALF_PI); + * + * // Style the oscillators. + * noStroke(); + * + * // Draw the red oscillator. + * fill(255, 0, 0); + * circle(x1, 0, 20); + * + * // Draw the blue oscillator. + * fill(0, 0, 255); + * circle(x2, 0, 20); + * } + * + *
        + */ + exports.WAIT = WAIT; + var HALF_PI = _PI / 2; + /** + * A `Number` constant that's approximately 3.1416. + * + * `PI` is the mathematical constant π. It's useful for many tasks that + * involve rotation and oscillation. For example, calling `rotate(PI)` rotates + * the coordinate system `PI` radians, which is a half turn (180˚). + * + * Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` + * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. + * + * @property {Number} PI + * @final + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw an arc from 0 to PI. + * arc(50, 50, 80, 80, 0, PI); + * + * describe('The bottom half of a circle drawn in white on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw a line. + * line(0, 0, 40, 0); + * + * // Rotate a half turn. + * rotate(PI); + * + * // Draw the same line, rotated. + * line(0, 0, 40, 0); + * + * describe('A horizontal black line on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A red circle and a blue circle oscillate from left to right on a gray background. The circles drift apart, then meet in the middle, over and over again.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Calculate the x-coordinates. + * let x1 = 40 * sin(frameCount * 0.05); + * let x2 = 40 * sin(frameCount * 0.05 + PI); + * + * // Style the oscillators. + * noStroke(); + * + * // Draw the red oscillator. + * fill(255, 0, 0); + * circle(x1, 0, 20); + * + * // Draw the blue oscillator. + * fill(0, 0, 255); + * circle(x2, 0, 20); + * } + * + *
        + */ + exports.HALF_PI = HALF_PI; + var PI = _PI; + /** + * A `Number` constant that's approximately 0.7854. + * + * `QUARTER_PI` is one-fourth the value of the mathematical constant π. It's + * useful for many tasks that involve rotation and oscillation. For example, + * calling `rotate(QUARTER_PI)` rotates the coordinate system `QUARTER_PI` + * radians, which is an eighth of a turn (45˚). + * + * Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` + * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. + * + * @property {Number} QUARTER_PI + * @final + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw an arc from 0 to QUARTER_PI. + * arc(50, 50, 80, 80, 0, QUARTER_PI); + * + * describe('A one-eighth slice of a circle drawn in white on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw a line. + * line(0, 0, 40, 0); + * + * // Rotate an eighth turn. + * rotate(QUARTER_PI); + * + * // Draw the same line, rotated. + * line(0, 0, 40, 0); + * + * describe('Two black lines that form a "V" opening towards the bottom-right corner of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A red circle and a blue circle oscillate from left to right on a gray background. The red circle appears to chase the blue circle.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Calculate the x-coordinates. + * let x1 = 40 * sin(frameCount * 0.05); + * let x2 = 40 * sin(frameCount * 0.05 + QUARTER_PI); + * + * // Style the oscillators. + * noStroke(); + * + * // Draw the red oscillator. + * fill(255, 0, 0); + * circle(x1, 0, 20); + * + * // Draw the blue oscillator. + * fill(0, 0, 255); + * circle(x2, 0, 20); + * } + * + *
        + */ + exports.PI = PI; + var QUARTER_PI = _PI / 4; + /** + * A `Number` constant that's approximately 6.2382. + * + * `TAU` is twice the value of the mathematical constant π. It's useful for + * many tasks that involve rotation and oscillation. For example, calling + * `rotate(TAU)` rotates the coordinate system `TAU` radians, which is one + * full turn (360˚). `TAU` and `TWO_PI` are equal. + * + * Note: `TAU` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` + * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. + * + * @property {Number} TAU + * @final + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw an arc from 0 to TAU. + * arc(50, 50, 80, 80, 0, TAU); + * + * describe('A white circle drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw a line. + * line(0, 0, 40, 0); + * + * // Rotate a full turn. + * rotate(TAU); + * + * // Style the second line. + * strokeWeight(5); + * + * // Draw the same line, shorter and rotated. + * line(0, 0, 20, 0); + * + * describe( + * 'Two horizontal black lines on a gray background. A thick line extends from the center toward the right. A thin line extends from the end of the thick line.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A red circle with a blue center oscillates from left to right on a gray background.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Calculate the x-coordinates. + * let x1 = 40 * sin(frameCount * 0.05); + * let x2 = 40 * sin(frameCount * 0.05 + TAU); + * + * // Style the oscillators. + * noStroke(); + * + * // Draw the red oscillator. + * fill(255, 0, 0); + * circle(x1, 0, 20); + * + * // Draw the blue oscillator, smaller. + * fill(0, 0, 255); + * circle(x2, 0, 10); + * } + * + *
        + */ + exports.QUARTER_PI = QUARTER_PI; + var TAU = _PI * 2; + /** + * A `Number` constant that's approximately 6.2382. + * + * `TWO_PI` is twice the value of the mathematical constant π. It's useful for + * many tasks that involve rotation and oscillation. For example, calling + * `rotate(TWO_PI)` rotates the coordinate system `TWO_PI` radians, which is + * one full turn (360˚). `TWO_PI` and `TAU` are equal. + * + * Note: `TWO_PI` radians equals 360˚, `PI` radians equals 180˚, `HALF_PI` + * radians equals 90˚, and `QUARTER_PI` radians equals 45˚. + * + * @property {Number} TWO_PI + * @final + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw an arc from 0 to TWO_PI. + * arc(50, 50, 80, 80, 0, TWO_PI); + * + * describe('A white circle drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw a line. + * line(0, 0, 40, 0); + * + * // Rotate a full turn. + * rotate(TWO_PI); + * + * // Style the second line. + * strokeWeight(5); + * + * // Draw the same line, shorter and rotated. + * line(0, 0, 20, 0); + * + * describe( + * 'Two horizontal black lines on a gray background. A thick line extends from the center toward the right. A thin line extends from the end of the thick line.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A red circle with a blue center oscillates from left to right on a gray background.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Calculate the x-coordinates. + * let x1 = 40 * sin(frameCount * 0.05); + * let x2 = 40 * sin(frameCount * 0.05 + TWO_PI); + * + * // Style the oscillators. + * noStroke(); + * + * // Draw the red oscillator. + * fill(255, 0, 0); + * circle(x1, 0, 20); + * + * // Draw the blue oscillator, smaller. + * fill(0, 0, 255); + * circle(x2, 0, 10); + * } + * + *
        + */ + exports.TAU = TAU; + var TWO_PI = _PI * 2; + /** + * A `String` constant that's used to set the + * angleMode(). + * + * By default, functions such as rotate() and + * sin() expect angles measured in units of radians. + * Calling `angleMode(DEGREES)` ensures that angles are measured in units of + * degrees. + * + * Note: `TWO_PI` radians equals 360˚. + * + * @property {String} DEGREES + * @final + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw a red arc from 0 to HALF_PI radians. + * fill(255, 0, 0); + * arc(50, 50, 80, 80, 0, HALF_PI); + * + * // Use degrees. + * angleMode(DEGREES); + * + * // Draw a blue arc from 90˚ to 180˚. + * fill(0, 0, 255); + * arc(50, 50, 80, 80, 90, 180); + * + * describe('The bottom half of a circle drawn on a gray background. The bottom-right quarter is red. The bottom-left quarter is blue.'); + * } + * + *
        + */ + exports.TWO_PI = TWO_PI; + var DEGREES = 'degrees'; + /** + * A `String` constant that's used to set the + * angleMode(). + * + * By default, functions such as rotate() and + * sin() expect angles measured in units of radians. + * Calling `angleMode(RADIANS)` ensures that angles are measured in units of + * radians. Doing so can be useful if the + * angleMode() has been set to + * DEGREES. + * + * Note: `TWO_PI` radians equals 360˚. + * + * @property {String} RADIANS + * @final + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use degrees. + * angleMode(DEGREES); + * + * // Draw a red arc from 0˚ to 90˚. + * fill(255, 0, 0); + * arc(50, 50, 80, 80, 0, 90); + * + * // Use radians. + * angleMode(RADIANS); + * + * // Draw a blue arc from HALF_PI to PI. + * fill(0, 0, 255); + * arc(50, 50, 80, 80, HALF_PI, PI); + * + * describe('The bottom half of a circle drawn on a gray background. The bottom-right quarter is red. The bottom-left quarter is blue.'); + * } + * + *
        + */ + exports.DEGREES = DEGREES; + var RADIANS = 'radians'; + exports.RADIANS = RADIANS; + var DEG_TO_RAD = _PI / 180; + exports.DEG_TO_RAD = DEG_TO_RAD; + var RAD_TO_DEG = 180 / _PI; + // SHAPE + /** + * @property {String} CORNER + * @final + */ + exports.RAD_TO_DEG = RAD_TO_DEG; + var CORNER = 'corner'; + /** + * @property {String} CORNERS + * @final + */ + exports.CORNER = CORNER; + var CORNERS = 'corners'; + /** + * @property {String} RADIUS + * @final + */ + exports.CORNERS = CORNERS; + var RADIUS = 'radius'; + /** + * @property {String} RIGHT + * @final + */ + exports.RADIUS = RADIUS; + var RIGHT = 'right'; + /** + * @property {String} LEFT + * @final + */ + exports.RIGHT = RIGHT; + var LEFT = 'left'; + /** + * @property {String} CENTER + * @final + */ + exports.LEFT = LEFT; + var CENTER = 'center'; + /** + * @property {String} TOP + * @final + */ + exports.CENTER = CENTER; + var TOP = 'top'; + /** + * @property {String} BOTTOM + * @final + */ + exports.TOP = TOP; + var BOTTOM = 'bottom'; + /** + * @property {String} BASELINE + * @final + * @default alphabetic + */ + exports.BOTTOM = BOTTOM; + var BASELINE = 'alphabetic'; + /** + * @property {Number} POINTS + * @final + * @default 0x0000 + */ + exports.BASELINE = BASELINE; + var POINTS = 0; + /** + * @property {Number} LINES + * @final + * @default 0x0001 + */ + exports.POINTS = POINTS; + var LINES = 1; + /** + * @property {Number} LINE_STRIP + * @final + * @default 0x0003 + */ + exports.LINES = LINES; + var LINE_STRIP = 3; + /** + * @property {Number} LINE_LOOP + * @final + * @default 0x0002 + */ + exports.LINE_STRIP = LINE_STRIP; + var LINE_LOOP = 2; + /** + * @property {Number} TRIANGLES + * @final + * @default 0x0004 + */ + exports.LINE_LOOP = LINE_LOOP; + var TRIANGLES = 4; + /** + * @property {Number} TRIANGLE_FAN + * @final + * @default 0x0006 + */ + exports.TRIANGLES = TRIANGLES; + var TRIANGLE_FAN = 6; + /** + * @property {Number} TRIANGLE_STRIP + * @final + * @default 0x0005 + */ + exports.TRIANGLE_FAN = TRIANGLE_FAN; + var TRIANGLE_STRIP = 5; + /** + * @property {String} QUADS + * @final + */ + exports.TRIANGLE_STRIP = TRIANGLE_STRIP; + var QUADS = 'quads'; + /** + * @property {String} QUAD_STRIP + * @final + * @default quad_strip + */ + exports.QUADS = QUADS; + var QUAD_STRIP = 'quad_strip'; + /** + * @property {String} TESS + * @final + * @default tess + */ + exports.QUAD_STRIP = QUAD_STRIP; + var TESS = 'tess'; + /** + * @property {String} CLOSE + * @final + */ + exports.TESS = TESS; + var CLOSE = 'close'; + /** + * @property {String} OPEN + * @final + */ + exports.CLOSE = CLOSE; + var OPEN = 'open'; + /** + * @property {String} CHORD + * @final + */ + exports.OPEN = OPEN; + var CHORD = 'chord'; + /** + * @property {String} PIE + * @final + */ + exports.CHORD = CHORD; + var PIE = 'pie'; + /** + * @property {String} PROJECT + * @final + * @default square + */ + exports.PIE = PIE; + var PROJECT = 'square'; // PEND: careful this is counterintuitive + /** + * @property {String} SQUARE + * @final + * @default butt + */ + exports.PROJECT = PROJECT; + var SQUARE = 'butt'; + /** + * @property {String} ROUND + * @final + */ + exports.SQUARE = SQUARE; + var ROUND = 'round'; + /** + * @property {String} BEVEL + * @final + */ + exports.ROUND = ROUND; + var BEVEL = 'bevel'; + /** + * @property {String} MITER + * @final + */ + exports.BEVEL = BEVEL; + var MITER = 'miter'; + // COLOR + /** + * @property {String} RGB + * @final + */ + exports.MITER = MITER; + var RGB = 'rgb'; + /** + * HSB (hue, saturation, brightness) is a type of color model. + * You can learn more about it at + * HSB. + * + * @property {String} HSB + * @final + */ + exports.RGB = RGB; + var HSB = 'hsb'; + /** + * @property {String} HSL + * @final + */ + exports.HSB = HSB; + var HSL = 'hsl'; + // DOM EXTENSION + /** + * AUTO allows us to automatically set the width or height of an element (but not both), + * based on the current height and width of the element. Only one parameter can + * be passed to the size function as AUTO, at a time. + * + * @property {String} AUTO + * @final + */ + exports.HSL = HSL; + var AUTO = 'auto'; + /** + * @property {Number} ALT + * @final + */ + // INPUT + exports.AUTO = AUTO; + var ALT = 18; + /** + * @property {Number} BACKSPACE + * @final + */ + exports.ALT = ALT; + var BACKSPACE = 8; + /** + * @property {Number} CONTROL + * @final + */ + exports.BACKSPACE = BACKSPACE; + var CONTROL = 17; + /** + * @property {Number} DELETE + * @final + */ + exports.CONTROL = CONTROL; + var DELETE = 46; + /** + * @property {Number} DOWN_ARROW + * @final + */ + exports.DELETE = DELETE; + var DOWN_ARROW = 40; + /** + * @property {Number} ENTER + * @final + */ + exports.DOWN_ARROW = DOWN_ARROW; + var ENTER = 13; + /** + * @property {Number} ESCAPE + * @final + */ + exports.ENTER = ENTER; + var ESCAPE = 27; + /** + * @property {Number} LEFT_ARROW + * @final + */ + exports.ESCAPE = ESCAPE; + var LEFT_ARROW = 37; + /** + * @property {Number} OPTION + * @final + */ + exports.LEFT_ARROW = LEFT_ARROW; + var OPTION = 18; + /** + * @property {Number} RETURN + * @final + */ + exports.OPTION = OPTION; + var RETURN = 13; + /** + * @property {Number} RIGHT_ARROW + * @final + */ + exports.RETURN = RETURN; + var RIGHT_ARROW = 39; + /** + * @property {Number} SHIFT + * @final + */ + exports.RIGHT_ARROW = RIGHT_ARROW; + var SHIFT = 16; + /** + * @property {Number} TAB + * @final + */ + exports.SHIFT = SHIFT; + var TAB = 9; + /** + * @property {Number} UP_ARROW + * @final + */ + exports.TAB = TAB; + var UP_ARROW = 38; + // RENDERING + /** + * @property {String} BLEND + * @final + * @default source-over + */ + exports.UP_ARROW = UP_ARROW; + var BLEND = 'source-over'; + /** + * @property {String} REMOVE + * @final + * @default destination-out + */ + exports.BLEND = BLEND; + var REMOVE = 'destination-out'; + /** + * @property {String} ADD + * @final + * @default lighter + */ + exports.REMOVE = REMOVE; + var ADD = 'lighter'; + //ADD: 'add', // + //SUBTRACT: 'subtract', // + /** + * @property {String} DARKEST + * @final + */ + exports.ADD = ADD; + var DARKEST = 'darken'; + /** + * @property {String} LIGHTEST + * @final + * @default lighten + */ + exports.DARKEST = DARKEST; + var LIGHTEST = 'lighten'; + /** + * @property {String} DIFFERENCE + * @final + */ + exports.LIGHTEST = LIGHTEST; + var DIFFERENCE = 'difference'; + /** + * @property {String} SUBTRACT + * @final + */ + exports.DIFFERENCE = DIFFERENCE; + var SUBTRACT = 'subtract'; + /** + * @property {String} EXCLUSION + * @final + */ + exports.SUBTRACT = SUBTRACT; + var EXCLUSION = 'exclusion'; + /** + * @property {String} MULTIPLY + * @final + */ + exports.EXCLUSION = EXCLUSION; + var MULTIPLY = 'multiply'; + /** + * @property {String} SCREEN + * @final + */ + exports.MULTIPLY = MULTIPLY; + var SCREEN = 'screen'; + /** + * @property {String} REPLACE + * @final + * @default copy + */ + exports.SCREEN = SCREEN; + var REPLACE = 'copy'; + /** + * @property {String} OVERLAY + * @final + */ + exports.REPLACE = REPLACE; + var OVERLAY = 'overlay'; + /** + * @property {String} HARD_LIGHT + * @final + */ + exports.OVERLAY = OVERLAY; + var HARD_LIGHT = 'hard-light'; + /** + * @property {String} SOFT_LIGHT + * @final + */ + exports.HARD_LIGHT = HARD_LIGHT; + var SOFT_LIGHT = 'soft-light'; + /** + * @property {String} DODGE + * @final + * @default color-dodge + */ + exports.SOFT_LIGHT = SOFT_LIGHT; + var DODGE = 'color-dodge'; + /** + * @property {String} BURN + * @final + * @default color-burn + */ + exports.DODGE = DODGE; + var BURN = 'color-burn'; + // FILTERS + /** + * @property {String} THRESHOLD + * @final + */ + exports.BURN = BURN; + var THRESHOLD = 'threshold'; + /** + * @property {String} GRAY + * @final + */ + exports.THRESHOLD = THRESHOLD; + var GRAY = 'gray'; + /** + * @property {String} OPAQUE + * @final + */ + exports.GRAY = GRAY; + var OPAQUE = 'opaque'; + /** + * @property {String} INVERT + * @final + */ + exports.OPAQUE = OPAQUE; + var INVERT = 'invert'; + /** + * @property {String} POSTERIZE + * @final + */ + exports.INVERT = INVERT; + var POSTERIZE = 'posterize'; + /** + * @property {String} DILATE + * @final + */ + exports.POSTERIZE = POSTERIZE; + var DILATE = 'dilate'; + /** + * @property {String} ERODE + * @final + */ + exports.DILATE = DILATE; + var ERODE = 'erode'; + /** + * @property {String} BLUR + * @final + */ + exports.ERODE = ERODE; + var BLUR = 'blur'; + // TYPOGRAPHY + /** + * @property {String} NORMAL + * @final + */ + exports.BLUR = BLUR; + var NORMAL = 'normal'; + /** + * @property {String} ITALIC + * @final + */ + exports.NORMAL = NORMAL; + var ITALIC = 'italic'; + /** + * @property {String} BOLD + * @final + */ + exports.ITALIC = ITALIC; + var BOLD = 'bold'; + /** + * @property {String} BOLDITALIC + * @final + */ + exports.BOLD = BOLD; + var BOLDITALIC = 'bold italic'; + /** + * @property {String} CHAR + * @final + */ + exports.BOLDITALIC = BOLDITALIC; + var CHAR = 'CHAR'; + /** + * @property {String} WORD + * @final + */ + exports.CHAR = CHAR; + var WORD = 'WORD'; + // TYPOGRAPHY-INTERNAL + exports.WORD = WORD; + var _DEFAULT_TEXT_FILL = '#000000'; + exports._DEFAULT_TEXT_FILL = _DEFAULT_TEXT_FILL; + var _DEFAULT_LEADMULT = 1.25; + exports._DEFAULT_LEADMULT = _DEFAULT_LEADMULT; + var _CTX_MIDDLE = 'middle'; + // VERTICES + /** + * @property {String} LINEAR + * @final + */ + exports._CTX_MIDDLE = _CTX_MIDDLE; + var LINEAR = 'linear'; + /** + * @property {String} QUADRATIC + * @final + */ + exports.LINEAR = LINEAR; + var QUADRATIC = 'quadratic'; + /** + * @property {String} BEZIER + * @final + */ + exports.QUADRATIC = QUADRATIC; + var BEZIER = 'bezier'; + /** + * @property {String} CURVE + * @final + */ + exports.BEZIER = BEZIER; + var CURVE = 'curve'; + // WEBGL DRAWMODES + /** + * @property {String} STROKE + * @final + */ + exports.CURVE = CURVE; + var STROKE = 'stroke'; + /** + * @property {String} FILL + * @final + */ + exports.STROKE = STROKE; + var FILL = 'fill'; + /** + * @property {String} TEXTURE + * @final + */ + exports.FILL = FILL; + var TEXTURE = 'texture'; + /** + * @property {String} IMMEDIATE + * @final + */ + exports.TEXTURE = TEXTURE; + var IMMEDIATE = 'immediate'; + // WEBGL TEXTURE MODE + // NORMAL already exists for typography + /** + * @property {String} IMAGE + * @final + */ + exports.IMMEDIATE = IMMEDIATE; + var IMAGE = 'image'; + // WEBGL TEXTURE WRAP AND FILTERING + // LINEAR already exists above + /** + * @property {String} NEAREST + * @final + */ + exports.IMAGE = IMAGE; + var NEAREST = 'nearest'; + /** + * @property {String} REPEAT + * @final + */ + exports.NEAREST = NEAREST; + var REPEAT = 'repeat'; + /** + * @property {String} CLAMP + * @final + */ + exports.REPEAT = REPEAT; + var CLAMP = 'clamp'; + /** + * @property {String} MIRROR + * @final + */ + exports.CLAMP = CLAMP; + var MIRROR = 'mirror'; + // WEBGL GEOMETRY SHADING + /** + * @property {String} FLAT + * @final + */ + exports.MIRROR = MIRROR; + var FLAT = 'flat'; + /** + * @property {String} SMOOTH + * @final + */ + exports.FLAT = FLAT; + var SMOOTH = 'smooth'; + // DEVICE-ORIENTATION + /** + * @property {String} LANDSCAPE + * @final + */ + exports.SMOOTH = SMOOTH; + var LANDSCAPE = 'landscape'; + /** + * @property {String} PORTRAIT + * @final + */ + exports.LANDSCAPE = LANDSCAPE; + var PORTRAIT = 'portrait'; + // DEFAULTS + exports.PORTRAIT = PORTRAIT; + var _DEFAULT_STROKE = '#000000'; + exports._DEFAULT_STROKE = _DEFAULT_STROKE; + var _DEFAULT_FILL = '#FFFFFF'; + /** + * @property {String} GRID + * @final + */ + exports._DEFAULT_FILL = _DEFAULT_FILL; + var GRID = 'grid'; + /** + * @property {String} AXES + * @final + */ + exports.GRID = GRID; + var AXES = 'axes'; + /** + * @property {String} LABEL + * @final + */ + exports.AXES = AXES; + var LABEL = 'label'; + /** + * @property {String} FALLBACK + * @final + */ + exports.LABEL = LABEL; + var FALLBACK = 'fallback'; + /** + * @property {String} CONTAIN + * @final + */ + exports.FALLBACK = FALLBACK; + var CONTAIN = 'contain'; + /** + * @property {String} COVER + * @final + */ + exports.CONTAIN = CONTAIN; + var COVER = 'cover'; + /** + * @property {String} UNSIGNED_BYTE + * @final + */ + exports.COVER = COVER; + var UNSIGNED_BYTE = 'unsigned-byte'; + /** + * @property {String} UNSIGNED_INT + * @final + */ + exports.UNSIGNED_BYTE = UNSIGNED_BYTE; + var UNSIGNED_INT = 'unsigned-int'; + /** + * @property {String} FLOAT + * @final + */ + exports.UNSIGNED_INT = UNSIGNED_INT; + var FLOAT = 'float'; + /** + * @property {String} HALF_FLOAT + * @final + */ + exports.FLOAT = FLOAT; + var HALF_FLOAT = 'half-float'; + /** + * @property {String} RGBA + * @final + */ + exports.HALF_FLOAT = HALF_FLOAT; + var RGBA = 'rgba'; + exports.RGBA = RGBA; + }, + { + } + ], + 292: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.search'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.search'); + _dereq_('core-js/modules/es.string.split'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('./main')); + var C = _interopRequireWildcard(_dereq_('./constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Environment + * @submodule Environment + * @for p5 + * @requires core + * @requires constants + */ + + var standardCursors = [ + C.ARROW, + C.CROSS, + C.HAND, + C.MOVE, + C.TEXT, + C.WAIT + ]; + _main.default.prototype._frameRate = 0; + _main.default.prototype._lastFrameTime = window.performance.now(); + _main.default.prototype._targetFrameRate = 60; + var _windowPrint = window.print; + var windowPrintDisabled = false; + /** + * Displays text in the web browser's console. + * + * `print()` is helpful for printing values while debugging. Each call to + * `print()` creates a new line of text. + * + * Note: Call `print('\n')` to print a blank line. Calling `print()` without + * an argument opens the browser's dialog for printing documents. + * + * @method print + * @param {Any} contents content to print to the console. + * @example + *
        + * + * function setup() { + * // Prints "hello, world" to the console. + * print('hello, world'); + * } + * + *
        + * + *
        + * + * function setup() { + * let name = 'ada'; + * // Prints "hello, ada" to the console. + * print(`hello, ${name}`); + * } + * + *
        + */ + _main.default.prototype.print = function () { + if (!arguments.length) { + if (!windowPrintDisabled) { + _windowPrint(); + if (window.confirm('You just tried to print the webpage. Do you want to prevent this from running again?')) { + windowPrintDisabled = true; + } + } + } else { + var _console; + (_console = console).log.apply(_console, arguments); + } + }; + /** + * A `Number` variable that tracks the number of frames drawn since the sketch + * started. + * + * `frameCount`'s value is 0 inside setup(). It + * increments by 1 each time the code in draw() + * finishes executing. + * + * @property {Integer} frameCount + * @readOnly + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Display the value of + * // frameCount. + * textSize(30); + * textAlign(CENTER, CENTER); + * text(frameCount, 50, 50); + * + * describe('The number 0 written in black in the middle of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Set the frameRate to 30. + * frameRate(30); + * + * textSize(30); + * textAlign(CENTER, CENTER); + * + * describe('A number written in black in the middle of a gray square. Its value increases rapidly.'); + * } + * + * function draw() { + * background(200); + * + * // Display the value of + * // frameCount. + * text(frameCount, 50, 50); + * } + * + *
        + */ + _main.default.prototype.frameCount = 0; + /** + * A `Number` variable that tracks the number of milliseconds it took to draw + * the last frame. + * + * `deltaTime` contains the amount of time it took + * draw() to execute during the previous frame. It's + * useful for simulating physics. + * + * @property {Integer} deltaTime + * @readOnly + * @example + *
        + * + * let x = 0; + * let speed = 0.05; + * + * function setup() { + * createCanvas(100, 100); + * + * // Set the frameRate to 30. + * frameRate(30); + * + * describe('A white circle moves from left to right on a gray background. It reappears on the left side when it reaches the right side.'); + * } + * + * function draw() { + * background(200); + * + * // Use deltaTime to calculate + * // a change in position. + * let deltaX = speed * deltaTime; + * + * // Update the x variable. + * x += deltaX; + * + * // Reset x to 0 if it's + * // greater than 100. + * if (x > 100) { + * x = 0; + * } + * + * // Use x to set the circle's + * // position. + * circle(x, 50, 20); + * } + * + *
        + */ + _main.default.prototype.deltaTime = 0; + /** + * A `Boolean` variable that's `true` if the browser is focused and `false` if + * not. + * + * Note: The browser window can only receive input if it's focused. + * + * @property {Boolean} focused + * @readOnly + * @example + *
        + * + * // Open this example in two separate browser + * // windows placed side-by-side to demonstrate. + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A square changes color from green to red when the browser window is out of focus.'); + * } + * + * function draw() { + * // Change the background color + * // when the browser window + * // goes in/out of focus. + * if (focused === true) { + * background(0, 255, 0); + * } else { + * background(255, 0, 0); + * } + * } + * + *
        + */ + _main.default.prototype.focused = document.hasFocus(); + /** + * Changes the cursor's appearance. + * + * The first parameter, `type`, sets the type of cursor to display. The + * built-in options are `ARROW`, `CROSS`, `HAND`, `MOVE`, `TEXT`, and `WAIT`. + * `cursor()` also recognizes standard CSS cursor properties passed as + * strings: `'help'`, `'wait'`, `'crosshair'`, `'not-allowed'`, `'zoom-in'`, + * and `'grab'`. If the path to an image is passed, as in + * `cursor('assets/target.png')`, then the image will be used as the cursor. + * Images must be in .cur, .gif, .jpg, .jpeg, or .png format and should be at most 32 by 32 pixels large. + * + * The parameters `x` and `y` are optional. If an image is used for the + * cursor, `x` and `y` set the location pointed to within the image. They are + * both 0 by default, so the cursor points to the image's top-left corner. `x` + * and `y` must be less than the image's width and height, respectively. + * + * @method cursor + * @param {String|Constant} type Built-in: either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT. + * Native CSS properties: 'grab', 'progress', and so on. + * Path to cursor image. + * @param {Number} [x] horizontal active spot of the cursor. + * @param {Number} [y] vertical active spot of the cursor. + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A gray square. The cursor appears as crosshairs.'); + * } + * + * function draw() { + * background(200); + * + * // Set the cursor to crosshairs: + + * cursor(CROSS); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A gray square divided into quadrants. The cursor image changes when the mouse moves to each quadrant.'); + * } + * + * function draw() { + * background(200); + * + * // Divide the canvas into quadrants. + * line(50, 0, 50, 100); + * line(0, 50, 100, 50); + * + * // Change cursor based on mouse position. + * if (mouseX < 50 && mouseY < 50) { + * cursor(CROSS); + * } else if (mouseX > 50 && mouseY < 50) { + * cursor('progress'); + * } else if (mouseX > 50 && mouseY > 50) { + * cursor('https://avatars0.githubusercontent.com/u/1617169?s=16'); + * } else { + * cursor('grab'); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('An image of three purple curves follows the mouse. The image shifts when the mouse is pressed.'); + * } + * + * function draw() { + * background(200); + * + * // Change the cursor's active spot + * // when the mouse is pressed. + * if (mouseIsPressed === true) { + * cursor('https://avatars0.githubusercontent.com/u/1617169?s=16', 8, 8); + * } else { + * cursor('https://avatars0.githubusercontent.com/u/1617169?s=16'); + * } + * } + * + *
        + */ + _main.default.prototype.cursor = function (type, x, y) { + var cursor = 'auto'; + var canvas = this._curElement.elt; + if (standardCursors.includes(type)) { + // Standard css cursor + cursor = type; + } else if (typeof type === 'string') { + var coords = ''; + if (x && y && typeof x === 'number' && typeof y === 'number') { + // Note that x and y values must be unit-less positive integers < 32 + // https://developer.mozilla.org/en-US/docs/Web/CSS/cursor + coords = ''.concat(x, ' ').concat(y); + } + if (type.substring(0, 7) === 'http://' || type.substring(0, 8) === 'https://') { + // Image (absolute url) + cursor = 'url('.concat(type, ') ').concat(coords, ', auto'); + } else if (/\.(cur|jpg|jpeg|gif|png|CUR|JPG|JPEG|GIF|PNG)$/.test(type)) { + // Image file (relative path) - Separated for performance reasons + cursor = 'url('.concat(type, ') ').concat(coords, ', auto'); + } else { + // Any valid string for the css cursor property + cursor = type; + } + } + canvas.style.cursor = cursor; + }; + /** + * Sets the number of frames to draw per second. + * + * Calling `frameRate()` with one numeric argument, as in `frameRate(30)`, + * attempts to draw 30 frames per second (FPS). The target frame rate may not + * be achieved depending on the sketch's processing needs. Most computers + * default to a frame rate of 60 FPS. Frame rates of 24 FPS and above are + * fast enough for smooth animations. + * + * Calling `frameRate()` without an argument returns the current frame rate. + * The value returned is an approximation. + * + * @method frameRate + * @param {Number} fps number of frames to draw per second. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white circle on a gray background. The circle moves from left to right in a loop. It slows down when the mouse is pressed.'); + * } + * + * function draw() { + * background(200); + * + * // Set the x variable based + * // on the current frameCount. + * let x = frameCount % 100; + * + * // If the mouse is pressed, + * // decrease the frame rate. + * if (mouseIsPressed === true) { + * frameRate(10); + * } else { + * frameRate(60); + * } + * + * // Use x to set the circle's + * // position. + * circle(x, 50, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A number written in black on a gray background. The number decreases when the mouse is pressed.'); + * } + * + * function draw() { + * background(200); + * + * // If the mouse is pressed, do lots + * // of math to slow down drawing. + * if (mouseIsPressed === true) { + * for (let i = 0; i < 1000000; i += 1) { + * random(); + * } + * } + * + * // Get the current frame rate + * // and display it. + * let fps = frameRate(); + * text(fps, 50, 50); + * } + * + *
        + */ + /** + * @method frameRate + * @return {Number} current frame rate. + */ + _main.default.prototype.frameRate = function (fps) { + _main.default._validateParameters('frameRate', arguments); + if (typeof fps !== 'number' || fps < 0) { + return this._frameRate; + } else { + this._setProperty('_targetFrameRate', fps); + if (fps === 0) { + this._setProperty('_frameRate', fps); + } + return this; + } + }; + /** + * Returns the current framerate. + * + * @private + * @return {Number} current frameRate + */ + _main.default.prototype.getFrameRate = function () { + return this.frameRate(); + }; + /** + * Specifies the number of frames to be displayed every second. For example, + * the function call frameRate(30) will attempt to refresh 30 times a second. + * If the processor is not fast enough to maintain the specified rate, the + * frame rate will not be achieved. Setting the frame rate within setup() is + * recommended. The default rate is 60 frames per second. + * + * Calling `frameRate()` with no arguments returns the current frame rate. + * + * @private + * @param {Number} [fps] number of frames to be displayed every second + */ + _main.default.prototype.setFrameRate = function (fps) { + return this.frameRate(fps); + }; + /** + * Returns the target frame rate. + * + * The value is either the system frame rate or the last value passed to + * frameRate(). + * + * @method getTargetFrameRate + * @return {Number} _targetFrameRate + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('The number 20 written in black on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Set the frame rate to 20. + * frameRate(20); + * + * // Get the target frame rate and + * // display it. + * let fps = getTargetFrameRate(); + * text(fps, 43, 54); + * } + * + *
        + */ + _main.default.prototype.getTargetFrameRate = function () { + return this._targetFrameRate; + }; + /** + * Hides the cursor from view. + * + * @method noCursor + * @example + *
        + * + * function setup() { + * // Hide the cursor. + * noCursor(); + * } + * + * function draw() { + * background(200); + * + * circle(mouseX, mouseY, 10); + * + * describe('A white circle on a gray background. The circle follows the mouse as it moves. The cursor is hidden.'); + * } + * + *
        + */ + _main.default.prototype.noCursor = function () { + this._curElement.elt.style.cursor = 'none'; + }; + /** + * A `String` variable with the WebGL version in use. + * + * `webglVersion`'s value equals one of the following string constants: + * + * - `WEBGL2` whose value is `'webgl2'`, + * - `WEBGL` whose value is `'webgl'`, or + * - `P2D` whose value is `'p2d'`. This is the default for 2D sketches. + * + * See setAttributes() for ways to set the + * WebGL version. + * + * @property {String} webglVersion + * @readOnly + * @example + *
        + * + * function setup() { + * background(200); + * + * // Display the current WebGL version. + * text(webglVersion, 42, 54); + * + * describe('The text "p2d" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * let font; + * + * function preload() { + * // Load a font to use. + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * // Create a canvas using WEBGL mode. + * createCanvas(100, 50, WEBGL); + * background(200); + * + * // Display the current WebGL version. + * fill(0); + * textFont(font); + * text(webglVersion, -15, 5); + * + * describe('The text "webgl2" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * let font; + * + * function preload() { + * // Load a font to use. + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * // Create a canvas using WEBGL mode. + * createCanvas(100, 50, WEBGL); + * + * // Set WebGL to version 1. + * setAttributes({ version: 1 }); + * + * background(200); + * + * // Display the current WebGL version. + * fill(0); + * textFont(font); + * text(webglVersion, -14, 5); + * + * describe('The text "webgl" written in black on a gray background.'); + * } + * + *
        + */ + _main.default.prototype.webglVersion = C.P2D; + /** + * A `Number` variable that stores the width of the screen display. + * + * `displayWidth` is useful for running full-screen programs. Its value + * depends on the current pixelDensity(). + * + * Note: The actual screen width can be computed as + * `displayWidth * pixelDensity()`. + * + * @property {Number} displayWidth + * @readOnly + * @example + *
        + * + * function setup() { + * // Set the canvas' width and height + * // using the display's dimensions. + * createCanvas(displayWidth, displayHeight); + * + * background(200); + * + * describe('A gray canvas that is the same size as the display.'); + * } + * + *
        + * + * @alt + * This example does not render anything. + */ + _main.default.prototype.displayWidth = screen.width; + /** + * A `Number` variable that stores the height of the screen display. + * + * `displayHeight` is useful for running full-screen programs. Its value + * depends on the current pixelDensity(). + * + * Note: The actual screen height can be computed as + * `displayHeight * pixelDensity()`. + * + * @property {Number} displayHeight + * @readOnly + * @example + *
        + * + * function setup() { + * // Set the canvas' width and height + * // using the display's dimensions. + * createCanvas(displayWidth, displayHeight); + * + * background(200); + * + * describe('A gray canvas that is the same size as the display.'); + * } + * + *
        + * + * @alt + * This example does not render anything. + */ + _main.default.prototype.displayHeight = screen.height; + /** + * A `Number` variable that stores the width of the browser's viewport. + * + * The layout viewport + * is the area within the browser that's available for drawing. + * + * @property {Number} windowWidth + * @readOnly + * @example + *
        + * + * function setup() { + * // Set the canvas' width and height + * // using the browser's dimensions. + * createCanvas(windowWidth, windowHeight); + * + * background(200); + * + * describe('A gray canvas that takes up the entire browser window.'); + * } + * + *
        + * + * @alt + * This example does not render anything. + */ + _main.default.prototype.windowWidth = getWindowWidth(); + /** + * A `Number` variable that stores the height of the browser's viewport. + * + * The layout viewport + * is the area within the browser that's available for drawing. + * + * @property {Number} windowHeight + * @readOnly + * @example + *
        + * + * function setup() { + * // Set the canvas' width and height + * // using the browser's dimensions. + * createCanvas(windowWidth, windowHeight); + * + * background(200); + * + * describe('A gray canvas that takes up the entire browser window.'); + * } + * + *
        + * + * @alt + * This example does not render anything. + */ + _main.default.prototype.windowHeight = getWindowHeight(); + /** + * A function that's called when the browser window is resized. + * + * Code placed in the body of `windowResized()` will run when the + * browser window's size changes. It's a good place to call + * resizeCanvas() or make other + * adjustments to accommodate the new window size. + * + * The `event` parameter is optional. If added to the function declaration, it + * can be used for debugging or other purposes. + * + * @method windowResized + * @param {UIEvent} [event] optional resize Event. + * @example + *
        + * + * function setup() { + * createCanvas(windowWidth, windowHeight); + * + * describe('A gray canvas with a white circle at its center. The canvas takes up the entire browser window. It changes size to match the browser window.'); + * } + * + * function draw() { + * background(200); + * + * // Draw a circle at the center. + * circle(width / 2, height / 2, 50); + * } + * + * // Resize the canvas when the + * // browser's size changes. + * function windowResized() { + * resizeCanvas(windowWidth, windowHeight); + * } + * + *
        + * @alt + * This example does not render anything. + * + *
        + * + * function setup() { + * createCanvas(windowWidth, windowHeight); + * } + * + * function draw() { + * background(200); + * + * describe('A gray canvas that takes up the entire browser window. It changes size to match the browser window.'); + * } + * + * function windowResized(event) { + * // Resize the canvas when the + * // browser's size changes. + * resizeCanvas(windowWidth, windowHeight); + * + * // Print the resize event to the console for debugging. + * print(event); + * } + * + *
        + * @alt + * This example does not render anything. + */ + _main.default.prototype._onresize = function (e) { + this._setProperty('windowWidth', getWindowWidth()); + this._setProperty('windowHeight', getWindowHeight()); + var context = this._isGlobal ? window : this; + var executeDefault; + if (typeof context.windowResized === 'function') { + executeDefault = context.windowResized(e); + if (executeDefault !== undefined && !executeDefault) { + e.preventDefault(); + } + } + }; + function getWindowWidth() { + return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth || 0; + } + function getWindowHeight() { + return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight || 0; + } /** + * A `Number` variable that stores the width of the canvas in pixels. + * + * `width`'s default value is 100. Calling + * createCanvas() or + * resizeCanvas() changes the value of + * `width`. Calling noCanvas() sets its value to + * 0. + * + * @example + *
        + * + * function setup() { + * background(200); + * + * // Display the canvas' width. + * text(width, 42, 54); + * + * describe('The number 100 written in black on a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(50, 100); + * + * background(200); + * + * // Display the canvas' width. + * text(width, 21, 54); + * + * describe('The number 50 written in black on a gray rectangle.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Display the canvas' width. + * text(width, 42, 54); + * + * describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.'); + * } + * + * // If the mouse is pressed, reisze + * // the canvas and display its new + * // width. + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * resizeCanvas(50, 100); + * background(200); + * text(width, 21, 54); + * } + * } + * + *
        + * + * @property {Number} width + * @readOnly + */ + + _main.default.prototype.width = 0; + /** + * A `Number` variable that stores the height of the canvas in pixels. + * + * `height`'s default value is 100. Calling + * createCanvas() or + * resizeCanvas() changes the value of + * `height`. Calling noCanvas() sets its value to + * 0. + * + * @example + *
        + * + * function setup() { + * background(200); + * + * // Display the canvas' height. + * text(height, 42, 54); + * + * describe('The number 100 written in black on a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 50); + * + * background(200); + * + * // Display the canvas' height. + * text(height, 42, 27); + * + * describe('The number 50 written in black on a gray rectangle.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Display the canvas' height. + * text(height, 42, 54); + * + * describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.'); + * } + * + * // If the mouse is pressed, reisze + * // the canvas and display its new + * // height. + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * resizeCanvas(100, 50); + * background(200); + * text(height, 42, 27); + * } + * } + * + *
        + * + * @property {Number} height + * @readOnly + */ + _main.default.prototype.height = 0; + /** + * Toggles full-screen mode or returns the current mode. + * + * Calling `fullscreen(true)` makes the sketch full-screen. Calling + * `fullscreen(false)` makes the sketch its original size. + * + * Calling `fullscreen()` without an argument returns `true` if the sketch + * is in full-screen mode and `false` if not. + * + * Note: Due to browser restrictions, `fullscreen()` can only be called with + * user input such as a mouse press. + * + * @method fullscreen + * @param {Boolean} [val] whether the sketch should be in fullscreen mode. + * @return {Boolean} current fullscreen state. + * @example + *
        + * + * function setup() { + * background(200); + * + * describe('A gray canvas that switches between default and full-screen display when clicked.'); + * } + * + * // If the mouse is pressed, + * // toggle full-screen mode. + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * let fs = fullscreen(); + * fullscreen(!fs); + * } + * } + * + *
        + */ + _main.default.prototype.fullscreen = function (val) { + _main.default._validateParameters('fullscreen', arguments); + // no arguments, return fullscreen or not + if (typeof val === 'undefined') { + return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; + } else { + // otherwise set to fullscreen or not + if (val) { + launchFullscreen(document.documentElement); + } else { + exitFullscreen(); + } + } + }; + /** + * Sets the pixel density or returns the current density. + * + * Computer displays are grids of little lights called pixels. A + * display's pixel density describes how many pixels it packs into an + * area. Displays with smaller pixels have a higher pixel density and create + * sharper images. + * + * `pixelDensity()` sets the pixel scaling for high pixel density displays. + * By default, the pixel density is set to match the display's density. + * Calling `pixelDensity(1)` turn this off. + * + * Calling `pixelDensity()` without an argument returns the current pixel + * density. + * + * @method pixelDensity + * @param {Number} [val] desired pixel density. + * @chainable + * @example + *
        + * + * function setup() { + * // Set the pixel density to 1. + * pixelDensity(1); + * + * // Create a canvas and draw + * // a circle. + * createCanvas(100, 100); + * background(200); + * circle(50, 50, 70); + * + * describe('A fuzzy white circle on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * // Set the pixel density to 3. + * pixelDensity(3); + * + * // Create a canvas, paint the + * // background, and draw a + * // circle. + * createCanvas(100, 100); + * background(200); + * circle(50, 50, 70); + * + * describe('A sharp white circle on a gray canvas.'); + * } + * + *
        + */ + /** + * @method pixelDensity + * @returns {Number} current pixel density of the sketch. + */ + _main.default.prototype.pixelDensity = function (val) { + _main.default._validateParameters('pixelDensity', arguments); + var returnValue; + if (typeof val === 'number') { + if (val !== this._pixelDensity) { + this._pixelDensity = this._maxAllowedPixelDimensions = val; + } + returnValue = this; + this.resizeCanvas(this.width, this.height, true); // as a side effect, it will clear the canvas + } else { + returnValue = this._pixelDensity; + } + return returnValue; + }; + /** + * Returns the display's current pixel density. + * + * @method displayDensity + * @returns {Number} current pixel density of the display. + * @example + *
        + * + * function setup() { + * // Set the pixel density to 1. + * pixelDensity(1); + * + * // Create a canvas and draw + * // a circle. + * createCanvas(100, 100); + * background(200); + * circle(50, 50, 70); + * + * describe('A fuzzy white circle drawn on a gray background. The circle becomes sharper when the mouse is pressed.'); + * } + * + * function mousePressed() { + * // Get the current display density. + * let d = displayDensity(); + * + * // Use the display density to set + * // the sketch's pixel density. + * pixelDensity(d); + * + * // Paint the background and + * // draw a circle. + * background(200); + * circle(50, 50, 70); + * } + * + *
        + */ + _main.default.prototype.displayDensity = function () { + return window.devicePixelRatio; + }; + function launchFullscreen(element) { + var enabled = document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled; + if (!enabled) { + throw new Error('Fullscreen not enabled in this browser.'); + } + if (element.requestFullscreen) { + element.requestFullscreen(); + } else if (element.mozRequestFullScreen) { + element.mozRequestFullScreen(); + } else if (element.webkitRequestFullscreen) { + element.webkitRequestFullscreen(); + } else if (element.msRequestFullscreen) { + element.msRequestFullscreen(); + } + } + function exitFullscreen() { + if (document.exitFullscreen) { + document.exitFullscreen(); + } else if (document.mozCancelFullScreen) { + document.mozCancelFullScreen(); + } else if (document.webkitExitFullscreen) { + document.webkitExitFullscreen(); + } else if (document.msExitFullscreen) { + document.msExitFullscreen(); + } + } /** + * Returns the sketch's current + * URL + * as a `String`. + * + * @method getURL + * @return {String} url + * @example + *
        + * + * function setup() { + * background(200); + * + * // Get the sketch's URL + * // and display it. + * let url = getURL(); + * textWrap(CHAR); + * text(url, 0, 40, 100); + * + * describe('The URL "https://p5js.org/reference/#/p5/getURL" written in black on a gray background.'); + * } + * + *
        + */ + + _main.default.prototype.getURL = function () { + return location.href; + }; + /** + * Returns the current + * URL + * path as an `Array` of `String`s. + * + * For example, consider a sketch hosted at the URL + * `https://example.com/sketchbook`. Calling `getURLPath()` returns + * `['sketchbook']`. For a sketch hosted at the URL + * `https://example.com/sketchbook/monday`, `getURLPath()` returns + * `['sketchbook', 'monday']`. + * + * @method getURLPath + * @return {String[]} path components. + * @example + *
        + * + * function setup() { + * background(200); + * + * // Get the sketch's URL path + * // and display the first + * // part. + * let path = getURLPath(); + * text(path[0], 25, 54); + * + * describe('The word "reference" written in black on a gray background.'); + * } + * + *
        + */ + _main.default.prototype.getURLPath = function () { + return location.pathname.split('/').filter(function (v) { + return v !== ''; + }); + }; + /** + * Returns the current + * URL parameters + * in an `Object`. + * + * For example, calling `getURLParams()` in a sketch hosted at the URL + * `http://p5js.org?year=2014&month=May&day=15` returns + * `{ year: 2014, month: 'May', day: 15 }`. + * + * @method getURLParams + * @return {Object} URL params + * @example + *
        + * + * // Imagine this sketch is hosted at the following URL: + * // https://p5js.org?year=2014&month=May&day=15 + * + * function setup() { + * background(200); + * + * // Get the sketch's URL + * // parameters and display + * // them. + * let params = getURLParams(); + * text(params.day, 10, 20); + * text(params.month, 10, 40); + * text(params.year, 10, 60); + * + * describe('The text "15", "May", and "2014" written in black on separate lines.'); + * } + * + *
        + * + * @alt + * This example does not render anything. + */ + _main.default.prototype.getURLParams = function () { + var re = /[?&]([^&=]+)(?:[&=])([^&=]+)/gim; + var m; + var v = { + }; + while ((m = re.exec(location.search)) != null) { + if (m.index === re.lastIndex) { + re.lastIndex++; + } + v[m[1]] = m[2]; + } + return v; + }; + var _default = _main.default; + exports.default = _default; + }, + { + './constants': 291, + './main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.filter': 174, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.search': 220, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 293: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + // This contains a data table used by ./fes_core.js/fesErrorMonitor(). + // + // Note: Different browsers use different error strings for the same error. + // Extracting info from the browser error messages is easier and cleaner + // if we have a predefined lookup. This file serves as that lookup. + // Using this lookup we match the errors obtained from the browser, classify + // them into types and extract the required information. + // The FES can use the extracted info to generate a friendly error message + // for the matching error. + var strings = { + ReferenceError: [ + { + msg: '{{}} is not defined', + type: 'NOTDEFINED', + browser: 'all' + }, + { + msg: 'Can\'t find variable: {{}}', + type: 'NOTDEFINED', + browser: 'Safari' + }, + { + msg: 'Cannot access \'{{.}}\' before initialization', + type: 'CANNOTACCESS', + browser: 'Chrome' + }, + { + msg: 'can\'t access lexical declaration \'{{.}}\' before initialization', + type: 'CANNOTACCESS', + browser: 'Firefox' + } + ], + SyntaxError: [ + { + msg: 'illegal character', + type: 'INVALIDTOKEN', + browser: 'Firefox' + }, + { + msg: 'Invalid character', + type: 'INVALIDTOKEN', + browser: 'Safari' + }, + { + msg: 'Invalid or unexpected token', + type: 'INVALIDTOKEN', + browser: 'Chrome' + }, + { + msg: 'Unexpected token \'{{.}}\'', + type: 'UNEXPECTEDTOKEN', + browser: 'Chrome' + }, + { + msg: 'expected {{.}}, got \'{{.}}\'', + type: 'UNEXPECTEDTOKEN', + browser: 'Chrome' + }, + { + msg: 'Identifier \'{{.}}\' has already been declared', + type: 'REDECLAREDVARIABLE', + browser: 'Chrome' + }, + { + msg: 'redeclaration of {} {{.}}', + type: 'REDECLAREDVARIABLE', + browser: 'Firefox' + }, + { + msg: 'Missing initializer in const declaration', + type: 'MISSINGINITIALIZER', + browser: 'Chrome' + }, + { + msg: 'missing = in const declaration', + type: 'MISSINGINITIALIZER', + browser: 'Firefox' + }, + { + msg: 'Illegal return statement', + type: 'BADRETURNORYIELD', + browser: 'Chrome' + }, + { + msg: 'return not in function', + type: 'BADRETURNORYIELD', + browser: 'Firefox' + } + ], + TypeError: [ + { + msg: '{{.}} is not a function', + type: 'NOTFUNC', + browser: 'all' + }, + { + msg: 'Cannot read {{.}} null', + type: 'READNULL', + browser: 'Chrome' + }, + { + msg: '{{.}} is null', + type: 'READNULL', + browser: 'Firefox' + }, + { + msg: 'Cannot read {{.}} undefined', + type: 'READUDEFINED', + browser: 'Chrome' + }, + { + msg: '{{.}} is undefined', + type: 'READUDEFINED', + browser: 'Firefox' + }, + { + msg: 'Assignment to constant variable', + type: 'CONSTASSIGN', + browser: 'Chrome' + }, + { + msg: 'invalid assignment to const \'{{.}}\'', + type: 'CONSTASSIGN', + browser: 'Firefox' + } + ] + }; + var _default = strings; + exports.default = _default; + }, + { + } + ], + 294: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.get-own-property-names'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.starts-with'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.get-own-property-names'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.starts-with'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../main')); + var _internationalization = _dereq_('../internationalization'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); + } + function _nonIterableRest() { + throw new TypeError('Invalid attempt to destructure non-iterable instance'); + } + function _iterableToArrayLimit(arr, i) { + if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === '[object Arguments]')) { + return; + } + var _arr = [ + ]; + var _n = true; + var _d = false; + var _e = undefined; + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i['return'] != null) _i['return'](); + } finally { + if (_d) throw _e; + } + } + return _arr; + } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } /** + * @for p5 + * @requires core + * + * This is the main file for the Friendly Error System (FES), containing + * the core as well as miscellaneous functionality of the FES. Here is a + * brief outline of the functions called in this system. + * + * The FES may be invoked by a call to either + * (1) _validateParameters, (2) _friendlyFileLoadError, (3) _friendlyError, + * (4) helpForMisusedAtTopLevelCode, or (5) _fesErrorMonitor. + * + * _validateParameters is located in validate_params.js along with other code + * used for parameter validation. + * _friendlyFileLoadError is located in file_errors.js along with other code + * used for dealing with file load errors. + * Apart from this, there's also a file stacktrace.js, which contains the code + * to parse the error stack, borrowed from: + * https://github.com/stacktracejs/stacktrace.js + * + * For more detailed information on the FES functions, including the call + * sequence of each function, please look at the FES Reference + Dev Notes: + * https://github.com/processing/p5.js/blob/main/contributor_docs/fes_reference_dev_notes.md + */ + // p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta + // See testColors below for all the color codes and names + + var typeColors = [ + '#2D7BB6', + '#EE9900', + '#4DB200', + '#C83C00' + ]; + var misusedAtTopLevelCode = null; + var defineMisusedAtTopLevelCode = null; + // the threshold for the maximum allowed levenshtein distance + // used in misspelling detection + var EDIT_DIST_THRESHOLD = 2; + // to enable or disable styling (color, font-size, etc. ) for fes messages + var ENABLE_FES_STYLING = false; + if (typeof IS_MINIFIED !== 'undefined') { + _main.default._friendlyError = _main.default._checkForUserDefinedFunctions = _main.default._fesErrorMonitor = function () { + }; + } else { + var doFriendlyWelcome = false; // TEMP until we get it all working LM + var errorTable = _dereq_('./browser_errors').default; + // -- Borrowed from jQuery 1.11.3 -- + var class2type = { + }; + var _toString = class2type.toString; + var names = [ + 'Boolean', + 'Number', + 'String', + 'Function', + 'Array', + 'Date', + 'RegExp', + 'Object', + 'Error' + ]; + for (var n = 0; n < names.length; n++) { + class2type['[object '.concat(names[n], ']')] = names[n].toLowerCase(); + } + var getType = function getType(obj) { + if (obj == null) { + return ''.concat(obj); + } + return _typeof(obj) === 'object' || typeof obj === 'function' ? class2type[_toString.call(obj)] || 'object' : _typeof(obj); + }; + // -- End borrow -- + // entry points into user-defined code + var entryPoints = [ + 'setup', + 'draw', + 'preload', + 'deviceMoved', + 'deviceTurned', + 'deviceShaken', + 'doubleClicked', + 'mousePressed', + 'mouseReleased', + 'mouseMoved', + 'mouseDragged', + 'mouseClicked', + 'mouseWheel', + 'touchStarted', + 'touchMoved', + 'touchEnded', + 'keyPressed', + 'keyReleased', + 'keyTyped', + 'windowResized' + ]; + var friendlyWelcome = function friendlyWelcome() { + // p5.js brand - magenta: #ED225D + //const astrixBgColor = 'transparent'; + //const astrixTxtColor = '#ED225D'; + //const welcomeBgColor = '#ED225D'; + //const welcomeTextColor = 'white'; + var welcomeMessage = (0, _internationalization.translator) ('fes.pre', { + message: (0, _internationalization.translator) ('fes.welcome') + }); + console.log(' _ \n' + ' /\\| |/\\ \n' + ' \\ ` \' / \n' + ' / , . \\ \n' + ' \\/|_|\\/ ' + '\n\n' + welcomeMessage); + }; + /** + * Takes a message and a p5 function func, and adds a link pointing to + * the reference documentation of func at the end of the message + * + * @method mapToReference + * @private + * @param {String} message the words to be said + * @param {String} [func] the name of function + * + * @returns {String} + */ + var mapToReference = function mapToReference(message, func) { + var msgWithReference = ''; + if (func == null || func.substring(0, 4) === 'load') { + msgWithReference = message; + } else { + var methodParts = func.split('.'); + var referenceSection = methodParts.length > 1 ? ''.concat(methodParts[0], '.').concat(methodParts[1]) : 'p5'; + var funcName = methodParts.length === 1 ? func : methodParts.slice(2).join('/'); + //Whenever func having p5.[Class] is encountered, we need to have the error link as mentioned below else different link + funcName.startsWith('p5.') ? msgWithReference = ''.concat(message, ' (http://p5js.org/reference/#/').concat(referenceSection, '.').concat(funcName, ')') : msgWithReference = ''.concat(message, ' (http://p5js.org/reference/#/').concat(referenceSection, '/').concat(funcName, ')'); + } + return msgWithReference; + }; + /** + * Prints out a fancy, colorful message to the console log + * Attaches Friendly Errors prefix [fes.pre] to the message. + * + * @method _report + * @private + * @param {String} message Message to be printed + * @param {String} [func] Name of function + * @param {Number|String} [color] CSS color code + * + * @return console logs + */ + _main.default._report = function (message, func, color) { + // if p5._fesLogger is set ( i.e we are running tests ), use that + // instead of console.log + var log = _main.default._fesLogger == null ? console.log.bind(console) : _main.default._fesLogger; + if (doFriendlyWelcome) { + friendlyWelcome(); + doFriendlyWelcome = false; + } + if ('undefined' === getType(color)) { + color = '#B40033'; // dark magenta + } else if (getType(color) === 'number') { + // Type to color + color = typeColors[color]; + } // Add a link to the reference docs of func at the end of the message + + message = mapToReference(message, func); + var style = [ + 'color: '.concat(color), + 'font-family: Arial', + 'font-size: larger' + ]; + var prefixedMsg = (0, _internationalization.translator) ('fes.pre', { + message: message + }); + if (ENABLE_FES_STYLING) { + log('%c' + prefixedMsg, style.join(';')); + } else { + log(prefixedMsg); + } + }; + /** + * This is a generic method that can be called from anywhere in the p5 + * library to alert users to a common error. + * + * @method _friendlyError + * @private + * @param {String} message Message to be printed + * @param {String} [func] Name of the function linked to error + * @param {Number|String} [color] CSS color code + */ + _main.default._friendlyError = function (message, func, color) { + _main.default._report(message, func, color); + }; + /** + * This is called internally if there is an error with autoplay. Generates + * and prints a friendly error message [fes.autoplay]. + * + * @method _friendlyAutoplayError + * @private + */ + _main.default._friendlyAutoplayError = function (src) { + var message = (0, _internationalization.translator) ('fes.autoplay', { + src: src, + url: 'https://developer.mozilla.org/docs/Web/Media/Autoplay_guide' + }); + console.log((0, _internationalization.translator) ('fes.pre', { + message: message + })); + }; + /** + * Measures dissimilarity between two strings by calculating + * the Levenshtein distance. + * + * If the "distance" between them is small enough, it is + * reasonable to think that one is the misspelled version of the other. + * + * Specifically, this uses the Wagner–Fischer algorithm. + * @method computeEditDistance + * @private + * @param {String} w1 the first word + * @param {String} w2 the second word + * + * @returns {Number} the "distance" between the two words, a smaller value + * indicates that the words are similar + */ + var computeEditDistance = function computeEditDistance(w1, w2) { + var l1 = w1.length, + l2 = w2.length; + if (l1 === 0) return w2; + if (l2 === 0) return w1; + var prev = [ + ]; + var cur = [ + ]; + for (var j = 0; j < l2 + 1; j++) { + cur[j] = j; + } + prev = cur; + for (var i = 1; i < l1 + 1; i++) { + cur = [ + ]; + for (var _j = 0; _j < l2 + 1; _j++) { + if (_j === 0) { + cur[_j] = i; + } else { + var a1 = w1[i - 1], + a2 = w2[_j - 1]; + var temp = 999999; + var cost = a1.toLowerCase() === a2.toLowerCase() ? 0 : 1; + temp = temp > cost + prev[_j - 1] ? cost + prev[_j - 1] : temp; + temp = temp > 1 + cur[_j - 1] ? 1 + cur[_j - 1] : temp; + temp = temp > 1 + prev[_j] ? 1 + prev[_j] : temp; + cur[_j] = temp; + } + } + prev = cur; + } + return cur[l2]; + }; + /** + * Checks capitalization for user defined functions. + * + * Generates and prints a friendly error message using key: + * "fes.checkUserDefinedFns". + * + * @method checkForUserDefinedFunctions + * @private + * @param {*} context Current default context. Set to window in + * "global mode" and to a p5 instance in "instance mode" + */ + var checkForUserDefinedFunctions = function checkForUserDefinedFunctions(context) { + if (_main.default.disableFriendlyErrors) return; + // if using instance mode, this function would be called with the current + // instance as context + var instanceMode = context instanceof _main.default; + context = instanceMode ? context : window; + var fnNames = entryPoints; + var fxns = { + }; + // lowercasename -> actualName mapping + fnNames.forEach(function (symbol) { + fxns[symbol.toLowerCase()] = symbol; + }); + for (var _i = 0, _Object$keys = Object.keys(context); _i < _Object$keys.length; _i++) { + var prop = _Object$keys[_i]; + var lowercase = prop.toLowerCase(); + // check if the lowercase property name has an entry in fxns, if the + // actual name with correct capitalization doesnt exist in context, + // and if the user-defined symbol is of the type function + if (fxns[lowercase] && !context[fxns[lowercase]] && typeof context[prop] === 'function') { + var msg = (0, _internationalization.translator) ('fes.checkUserDefinedFns', { + name: prop, + actualName: fxns[lowercase] + }); + _main.default._friendlyError(msg, fxns[lowercase]); + } + } + }; + /** + * Compares the symbol caught in the ReferenceError to everything in + * misusedAtTopLevel ( all public p5 properties ). + * + * Generates and prints a friendly error message using key: "fes.misspelling". + * + * @method handleMisspelling + * @private + * @param {String} errSym Symbol to whose spelling to check + * @param {Error} error ReferenceError object + * + * @returns {Boolean} tell whether error was likely due to typo + */ + var handleMisspelling = function handleMisspelling(errSym, error) { + if (!misusedAtTopLevelCode) { + defineMisusedAtTopLevelCode(); + } + var distanceMap = { + }; + var min = 999999; + // compute the levenshtein distance for the symbol against all known + // public p5 properties. Find the property with the minimum distance + misusedAtTopLevelCode.forEach(function (symbol) { + var dist = computeEditDistance(errSym, symbol.name); + if (distanceMap[dist]) distanceMap[dist].push(symbol); + else distanceMap[dist] = [ + symbol + ]; + if (dist < min) min = dist; + }); + // if the closest match has more "distance" than the max allowed threshold + if (min > Math.min(EDIT_DIST_THRESHOLD, errSym.length)) return false; + // Show a message only if the caught symbol and the matched property name + // differ in their name ( either letter difference or difference of case ) + var matchedSymbols = distanceMap[min].filter(function (symbol) { + return symbol.name !== errSym; + }); + if (matchedSymbols.length !== 0) { + var parsed = _main.default._getErrorStackParser().parse(error); + var locationObj; + if (parsed && parsed[0] && parsed[0].fileName && parsed[0].lineNumber && parsed[0].columnNumber) { + locationObj = { + location: ''.concat(parsed[0].fileName, ':').concat(parsed[0].lineNumber, ':').concat(parsed[0].columnNumber), + file: parsed[0].fileName.split('/').slice( - 1), + line: parsed[0].lineNumber + }; + } + var msg; + if (matchedSymbols.length === 1) { + // To be used when there is only one closest match. The count parameter + // allows i18n to pick between the keys "fes.misspelling" and + // "fes.misspelling_plural" + msg = (0, _internationalization.translator) ('fes.misspelling', { + name: errSym, + actualName: matchedSymbols[0].name, + type: matchedSymbols[0].type, + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '', + count: matchedSymbols.length + }); + } else { + // To be used when there are multiple closest matches. Gives each + // suggestion on its own line, the function name followed by a link to + // reference documentation + var suggestions = matchedSymbols.map(function (symbol) { + var message = '▶️ ' + symbol.name + (symbol.type === 'function' ? '()' : ''); + return mapToReference(message, symbol.name); + }).join('\n'); + msg = (0, _internationalization.translator) ('fes.misspelling', { + name: errSym, + suggestions: suggestions, + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '', + count: matchedSymbols.length + }); + } // If there is only one closest match, tell _friendlyError to also add + // a link to the reference documentation. In case of multiple matches, + // this is already done in the suggestions variable, one link for each + // suggestion. + + _main.default._friendlyError(msg, matchedSymbols.length === 1 ? matchedSymbols[0].name : undefined); + return true; + } + return false; + }; + /** + * Prints a friendly stacktrace for user-written functions for "global" errors + * + * Generates and prints a friendly error message using key: + * "fes.globalErrors.stackTop", "fes.globalErrors.stackSubseq". + * + * @method printFriendlyStack + * @private + * @param {Array} friendlyStack + */ + var printFriendlyStack = function printFriendlyStack(friendlyStack) { + var log = _main.default._fesLogger && typeof _main.default._fesLogger === 'function' ? _main.default._fesLogger : console.log.bind(console); + if (friendlyStack.length > 1) { + var stacktraceMsg = ''; + friendlyStack.forEach(function (frame, idx) { + var location = ''.concat(frame.fileName, ':').concat(frame.lineNumber, ':').concat(frame.columnNumber); + var frameMsg, + translationObj = { + func: frame.functionName, + line: frame.lineNumber, + location: location, + file: frame.fileName.split('/').slice( - 1) + }; + if (idx === 0) { + frameMsg = (0, _internationalization.translator) ('fes.globalErrors.stackTop', translationObj); + } else { + frameMsg = (0, _internationalization.translator) ('fes.globalErrors.stackSubseq', translationObj); + } + stacktraceMsg += frameMsg; + }); + log(stacktraceMsg); + } + }; + /** + * Takes a stacktrace array and filters out all frames that show internal p5 + * details. + * + * Generates and prints a friendly error message using key: + * "fes.wrongPreload", "fes.libraryError". + * + * The processed stack is used to find whether the error happened internally + * within the library, and if the error was due to a non-loadX() method + * being used in preload. + * + * "Internally" here means that the exact location of the error (the top of + * the stack) is a piece of code written in the p5.js library (which may or + * may not have been called from the user's sketch). + * + * @method processStack + * @private + * @param {Error} error + * @param {Array} stacktrace + * + * @returns {Array} An array with two elements, [isInternal, friendlyStack] + * isInternal: a boolean value indicating whether the error + * happened internally + * friendlyStack: the filtered (simplified) stacktrace + */ + var processStack = function processStack(error, stacktrace) { + // cannot process a stacktrace that doesn't exist + if (!stacktrace) return [false, + null]; + stacktrace.forEach(function (frame) { + frame.functionName = frame.functionName || ''; + }); + // isInternal - Did this error happen inside the library + var isInternal = false; + var p5FileName, + friendlyStack, + currentEntryPoint; + // Intentionally throw an error that we catch so that we can check the name + // of the current file. Any errors we see from this file, we treat as + // internal errors. + try { + throw new Error(); + } catch (testError) { + var testStacktrace = _main.default._getErrorStackParser().parse(testError); + p5FileName = testStacktrace[0].fileName; + } + for (var i = stacktrace.length - 1; i >= 0; i--) { + var splitted = stacktrace[i].functionName.split('.'); + if (entryPoints.includes(splitted[splitted.length - 1])) { + // remove everything below an entry point function (setup, draw, etc). + // (it's usually the internal initialization calls) + friendlyStack = stacktrace.slice(0, i + 1); + currentEntryPoint = splitted[splitted.length - 1]; + // We call the error "internal" if the source of the error was a + // function from within the p5.js library file, but called from the + // user's code directly. We only need to check the topmost frame in + // the stack trace since any function internal to p5 should pass this + // check, not just public p5 functions. + if (stacktrace[0].fileName === p5FileName) { + isInternal = true; + break; + } + break; + } + } // in some cases ( errors in promises, callbacks, etc), no entry-point + // function may be found in the stacktrace. In that case just use the + // entire stacktrace for friendlyStack + + if (!friendlyStack) friendlyStack = stacktrace; + if (isInternal) { + // the frameIndex property is added before the filter, so frameIndex + // corresponds to the index of a frame in the original stacktrace. + // Then we filter out all frames which belong to the file that contains + // the p5 library + friendlyStack = friendlyStack.map(function (frame, index) { + frame.frameIndex = index; + return frame; + }).filter(function (frame) { + return frame.fileName !== p5FileName; + }); + // a weird case, if for some reason we can't identify the function called + // from user's code + if (friendlyStack.length === 0) return [true, + null]; + // get the function just above the topmost frame in the friendlyStack. + // i.e the name of the library function called from user's code + var func = stacktrace[friendlyStack[0].frameIndex - 1].functionName.split('.').slice( - 1) [0]; + // Try and get the location (line no.) from the top element of the stack + var locationObj; + if (friendlyStack[0].fileName && friendlyStack[0].lineNumber && friendlyStack[0].columnNumber) { + locationObj = { + location: ''.concat(friendlyStack[0].fileName, ':').concat(friendlyStack[0].lineNumber, ':').concat(friendlyStack[0].columnNumber), + file: friendlyStack[0].fileName.split('/').slice( - 1), + line: friendlyStack[0].lineNumber + }; + // if already handled by another part of the FES, don't handle again + if (_main.default._fesLogCache[locationObj.location]) return [true, + null]; + } // Check if the error is due to a non loadX method being used incorrectly + // in preload + + if (currentEntryPoint === 'preload' && _main.default.prototype._preloadMethods[func] == null) { + _main.default._friendlyError((0, _internationalization.translator) ('fes.wrongPreload', { + func: func, + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '', + error: error.message + }), 'preload'); + } else { + // Library error + _main.default._friendlyError((0, _internationalization.translator) ('fes.libraryError', { + func: func, + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '', + error: error.message + }), func); + } // Finally, if it's an internal error, print the friendlyStack + // ( fesErrorMonitor won't handle this error ) + + if (friendlyStack && friendlyStack.length) { + printFriendlyStack(friendlyStack); + } + } + return [isInternal, + friendlyStack]; + }; + /** + * Handles "global" errors that the browser catches. + * + * Called when an error event happens and detects the type of error. + * + * Generates and prints a friendly error message using key: + * "fes.globalErrors.syntax.[*]", "fes.globalErrors.reference.[*]", + * "fes.globalErrors.type.[*]". + * + * @method fesErrorMonitor + * @private + * @param {*} e Event object to extract error details from + */ + var fesErrorMonitor = function fesErrorMonitor(e) { + if (_main.default.disableFriendlyErrors) return; + // Try to get the error object from e + var error; + if (e instanceof Error) { + error = e; + } else if (e instanceof ErrorEvent) { + error = e.error; + } else if (e instanceof PromiseRejectionEvent) { + error = e.reason; + if (!(error instanceof Error)) return; + } + if (!error) return; + var stacktrace = _main.default._getErrorStackParser().parse(error); + // process the stacktrace from the browser and simplify it to give + // friendlyStack. + var _processStack = processStack(error, stacktrace), + _processStack2 = _slicedToArray(_processStack, 2), + isInternal = _processStack2[0], + friendlyStack = _processStack2[1]; // if this is an internal library error, the type of the error is not relevant, + // only the user code that lead to it is. + if (isInternal) { + return; + } + var errList = errorTable[error.name]; + if (!errList) return; // this type of error can't be handled yet + var matchedError; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = errList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var obj = _step.value; + var string = obj.msg; + // capture the primary symbol mentioned in the error + string = string.replace(new RegExp('{{}}', 'g'), '([a-zA-Z0-9_]+)'); + string = string.replace(new RegExp('{{.}}', 'g'), '(.+)'); + string = string.replace(new RegExp('{}', 'g'), '(?:[a-zA-Z0-9_]+)'); + var matched = error.message.match(string); + if (matched) { + matchedError = Object.assign({ + }, obj); + matchedError.match = matched; + break; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + if (!matchedError) return; + // Try and get the location from the top element of the stack + var locationObj; + if (stacktrace && stacktrace[0].fileName && stacktrace[0].lineNumber && stacktrace[0].columnNumber) { + locationObj = { + location: ''.concat(stacktrace[0].fileName, ':').concat(stacktrace[0].lineNumber, ':').concat(stacktrace[0].columnNumber), + file: stacktrace[0].fileName.split('/').slice( - 1), + line: friendlyStack[0].lineNumber + }; + } + switch (error.name) { + case 'SyntaxError': + { + // We can't really do much with syntax errors other than try to use + // a simpler framing of the error message. The stack isn't available + // for syntax errors + switch (matchedError.type) { + case 'INVALIDTOKEN': + { + //Error if there is an invalid or unexpected token that doesn't belong at this position in the code + //let x = “not a string”; -> string not in proper quotes + var url = 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Illegal_character#What_went_wrong'; + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.syntax.invalidToken', { + url: url + })); + break; + } + case 'UNEXPECTEDTOKEN': + { + //Error if a specific language construct(, { ; etc) was expected, but something else was provided + //for (let i = 0; i < 5,; ++i) -> a comma after i<5 instead of a semicolon + var _url = 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Unexpected_token#What_went_wrong'; + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.syntax.unexpectedToken', { + url: _url + })); + break; + } + case 'REDECLAREDVARIABLE': + { + //Error if a variable is redeclared by the user. Example=> + //let a = 10; + //let a = 100; + var errSym = matchedError.match[1]; + var _url2 = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Redeclared_parameter#what_went_wrong'; + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.syntax.redeclaredVariable', { + symbol: errSym, + url: _url2 + })); + break; + } + case 'MISSINGINITIALIZER': + { + //Error if a const variable is not initialized during declaration + //Example => const a; + var _url3 = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_initializer_in_const#what_went_wrong'; + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.syntax.missingInitializer', { + url: _url3 + })); + break; + } + case 'BADRETURNORYIELD': + { + //Error when a return statement is misplaced(usually outside of a function) + // const a = function(){ + // ..... + // } + // return; -> misplaced return statement + var _url4 = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Bad_return_or_yield#what_went_wrong'; + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.syntax.badReturnOrYield', { + url: _url4 + })); + break; + } + } + break; + } + case 'ReferenceError': + { + switch (matchedError.type) { + case 'NOTDEFINED': + { + //Error if there is a non-existent variable referenced somewhere + //let a = 10; + //console.log(x); + var _errSym = matchedError.match[1]; + if (_errSym && handleMisspelling(_errSym, error)) { + break; + } // if the flow gets this far, this is likely not a misspelling + // of a p5 property/function + + var _url5 = 'https://p5js.org/examples/data-variable-scope.html'; + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.reference.notDefined', { + url: _url5, + symbol: _errSym, + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '' + })); + if (friendlyStack) printFriendlyStack(friendlyStack); + break; + } + case 'CANNOTACCESS': + { + //Error if a lexical variable was accessed before it was initialized + //console.log(a); -> variable accessed before it was initialized + //let a=100; + var _errSym2 = matchedError.match[1]; + var _url6 = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init#what_went_wrong'; + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.reference.cannotAccess', { + url: _url6, + symbol: _errSym2, + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '' + })); + if (friendlyStack) printFriendlyStack(friendlyStack); + break; + } + } + break; + } + case 'TypeError': + { + switch (matchedError.type) { + case 'NOTFUNC': + { + //Error when some code expects you to provide a function, but that didn't happen + //let a = document.getElementByID('foo'); -> getElementById instead of getElementByID + var _errSym3 = matchedError.match[1]; + var splitSym = _errSym3.split('.'); + var _url7 = 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Not_a_function#What_went_wrong'; + // if errSym is aa.bb.cc , symbol would be cc and obj would aa.bb + var translationObj = { + url: _url7, + symbol: splitSym[splitSym.length - 1], + obj: splitSym.slice(0, splitSym.length - 1).join('.'), + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '' + }; + // There are two cases to handle here. When the function is called + // as a property of an object and when it's called independently. + // Both have different explanations. + if (splitSym.length > 1) { + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.type.notfuncObj', translationObj)); + } else { + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.type.notfunc', translationObj)); + } + if (friendlyStack) printFriendlyStack(friendlyStack); + break; + } + case 'READNULL': + { + //Error if a property of null is accessed + //let a = null; + //console.log(a.property); -> a is null + var _errSym4 = matchedError.match[1]; + var _url8 = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_property#what_went_wrong'; + /*let url2 = + 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null';*/ + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.type.readFromNull', { + url: _url8, + symbol: _errSym4, + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '' + })); + if (friendlyStack) printFriendlyStack(friendlyStack); + break; + } + case 'READUDEFINED': + { + //Error if a property of undefined is accessed + //let a; -> default value of a is undefined + //console.log(a.property); -> a is undefined + var _errSym5 = matchedError.match[1]; + var _url9 = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_property#what_went_wrong'; + /*let url2 = + 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined#description';*/ + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.type.readFromUndefined', { + url: _url9, + symbol: _errSym5, + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '' + })); + if (friendlyStack) printFriendlyStack(friendlyStack); + break; + } + case 'CONSTASSIGN': + { + //Error when a const variable is reassigned a value + //const a = 100; + //a=10; + var _url10 = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_const_assignment#what_went_wrong'; + _main.default._friendlyError((0, _internationalization.translator) ('fes.globalErrors.type.constAssign', { + url: _url10, + location: locationObj ? (0, _internationalization.translator) ('fes.location', locationObj) : '' + })); + if (friendlyStack) printFriendlyStack(friendlyStack); + break; + } + } + } + } + }; + _main.default._fesErrorMonitor = fesErrorMonitor; + _main.default._checkForUserDefinedFunctions = checkForUserDefinedFunctions; + // logger for testing purposes. + _main.default._fesLogger = null; + _main.default._fesLogCache = { + }; + window.addEventListener('load', checkForUserDefinedFunctions, false); + window.addEventListener('error', _main.default._fesErrorMonitor, false); + window.addEventListener('unhandledrejection', _main.default._fesErrorMonitor, false); + /** + * Prints out all the colors in the color pallete with white text. + * For color blindness testing. + */ + /* function testColors() { + const str = 'A box of biscuits, a box of mixed biscuits and a biscuit mixer'; + p5._friendlyError(str, 'print', '#ED225D'); // p5.js magenta + p5._friendlyError(str, 'print', '#2D7BB6'); // p5.js blue + p5._friendlyError(str, 'print', '#EE9900'); // p5.js orange + p5._friendlyError(str, 'print', '#A67F59'); // p5.js light brown + p5._friendlyError(str, 'print', '#704F21'); // p5.js gold + p5._friendlyError(str, 'print', '#1CC581'); // auto cyan + p5._friendlyError(str, 'print', '#FF6625'); // auto orange + p5._friendlyError(str, 'print', '#79EB22'); // auto green + p5._friendlyError(str, 'print', '#B40033'); // p5.js darkened magenta + p5._friendlyError(str, 'print', '#084B7F'); // p5.js darkened blue + p5._friendlyError(str, 'print', '#945F00'); // p5.js darkened orange + p5._friendlyError(str, 'print', '#6B441D'); // p5.js darkened brown + p5._friendlyError(str, 'print', '#2E1B00'); // p5.js darkened gold + p5._friendlyError(str, 'print', '#008851'); // auto dark cyan + p5._friendlyError(str, 'print', '#C83C00'); // auto dark orange + p5._friendlyError(str, 'print', '#4DB200'); // auto dark green + } */ + } // This is a lazily-defined list of p5 symbols that may be + // misused by beginners at top-level code, outside of setup/draw. We'd like + // to detect these errors and help the user by suggesting they move them + // into setup/draw. + // + // For more details, see https://github.com/processing/p5.js/issues/1121. + + misusedAtTopLevelCode = null; + var FAQ_URL = 'https://github.com/processing/p5.js/wiki/p5.js-overview#why-cant-i-assign-variables-using-p5-functions-and-variables-before-setup'; + /** + * A helper function for populating misusedAtTopLevel list. + * + * @method defineMisusedAtTopLevelCode + * @private + */ + defineMisusedAtTopLevelCode = function defineMisusedAtTopLevelCode() { + var uniqueNamesFound = { + }; + var getSymbols = function getSymbols(obj) { + return Object.getOwnPropertyNames(obj).filter(function (name) { + if (name[0] === '_') { + return false; + } + if (name in uniqueNamesFound) { + return false; + } + uniqueNamesFound[name] = true; + return true; + }).map(function (name) { + var type; + if (typeof obj[name] === 'function') { + type = 'function'; + } else if (name === name.toUpperCase()) { + type = 'constant'; + } else { + type = 'variable'; + } + return { + name: name, + type: type + }; + }); + }; + misusedAtTopLevelCode = [ + ].concat(getSymbols(_main.default.prototype), // At present, p5 only adds its constants to p5.prototype during + // construction, which may not have happened at the time a + // ReferenceError is thrown, so we'll manually add them to our list. + getSymbols(_dereq_('../constants'))); + // This will ultimately ensure that we report the most specific error + // possible to the user, e.g. advising them about HALF_PI instead of PI + // when their code misuses the former. + misusedAtTopLevelCode.sort(function (a, b) { + return b.name.length - a.name.length; + }); + }; + /** + * Detects browser level error event for p5 constants/functions used outside + * of setup() and draw(). + * + * Generates and prints a friendly error message using key: + * "fes.misusedTopLevel". + * + * @method helpForMisusedAtTopLevelCode + * @private + * @param {Event} e Error event + * @param {Boolean} log false + * + * @returns {Boolean} true + */ + var helpForMisusedAtTopLevelCode = function helpForMisusedAtTopLevelCode(e, log) { + if (!log) { + log = console.log.bind(console); + } + if (!misusedAtTopLevelCode) { + defineMisusedAtTopLevelCode(); + } // If we find that we're logging lots of false positives, we can + // uncomment the following code to avoid displaying anything if the + // user's code isn't likely to be using p5's global mode. (Note that + // setup/draw are more likely to be defined due to JS function hoisting.) + // + //if (!('setup' in window || 'draw' in window)) { + // return; + //} + + misusedAtTopLevelCode.some(function (symbol) { + // Note that while just checking for the occurrence of the + // symbol name in the error message could result in false positives, + // a more rigorous test is difficult because different browsers + // log different messages, and the format of those messages may + // change over time. + // + // For example, if the user uses 'PI' in their code, it may result + // in any one of the following messages: + // + // * 'PI' is undefined (Microsoft Edge) + // * ReferenceError: PI is undefined (Firefox) + // * Uncaught ReferenceError: PI is not defined (Chrome) + if (e.message && e.message.match('\\W?'.concat(symbol.name, '\\W')) !== null) { + var symbolName = symbol.type === 'function' ? ''.concat(symbol.name, '()') : symbol.name; + if (typeof IS_MINIFIED !== 'undefined') { + log('Did you just try to use p5.js\'s '.concat(symbolName, ' ').concat(symbol.type, '? If so, you may want to move it into your sketch\'s setup() function.\n\nFor more details, see: ').concat(FAQ_URL)); + } else { + log((0, _internationalization.translator) ('fes.misusedTopLevel', { + symbolName: symbolName, + symbolType: symbol.type, + url: FAQ_URL + })); + } + return true; + } + }); + }; + // Exposing this primarily for unit testing. + _main.default.prototype._helpForMisusedAtTopLevelCode = helpForMisusedAtTopLevelCode; + if (document.readyState !== 'complete') { + window.addEventListener('error', helpForMisusedAtTopLevelCode, false); + // Our job is only to catch ReferenceErrors that are thrown when + // global (non-instance mode) p5 APIs are used at the top-level + // scope of a file, so we'll unbind our error listener now to make + // sure we don't log false positives later. + window.addEventListener('load', function () { + window.removeEventListener('error', helpForMisusedAtTopLevelCode, false); + }); + } + var _default = _main.default; + exports.default = _default; + }, + { + '../constants': 291, + '../internationalization': 301, + '../main': 303, + './browser_errors': 293, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.filter': 174, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.some': 187, + 'core-js/modules/es.function.name': 191, + 'core-js/modules/es.object.assign': 199, + 'core-js/modules/es.object.get-own-property-names': 202, + 'core-js/modules/es.object.keys': 204, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.constructor': 209, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.match': 216, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.string.starts-with': 222, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.for-each': 260, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 295: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../main')); + var _internationalization = _dereq_('../internationalization'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @for p5 + * @requires core + */ + + if (typeof IS_MINIFIED !== 'undefined') { + _main.default._friendlyFileLoadError = function () { + }; + } else { + // mapping used by `_friendlyFileLoadError` + var fileLoadErrorCases = function fileLoadErrorCases(num, filePath) { + var suggestion = (0, _internationalization.translator) ('fes.fileLoadError.suggestion', { + filePath: filePath, + url: 'https://github.com/processing/p5.js/wiki/Local-server' + }); + switch (num) { + case 0: + return { + message: (0, _internationalization.translator) ('fes.fileLoadError.image', { + suggestion: suggestion + }), + method: 'loadImage' + }; + case 1: + return { + message: (0, _internationalization.translator) ('fes.fileLoadError.xml', { + suggestion: suggestion + }), + method: 'loadXML' + }; + case 2: + return { + message: (0, _internationalization.translator) ('fes.fileLoadError.table', { + suggestion: suggestion + }), + method: 'loadTable' + }; + case 3: + return { + message: (0, _internationalization.translator) ('fes.fileLoadError.strings', { + suggestion: suggestion + }), + method: 'loadStrings' + }; + case 4: + return { + message: (0, _internationalization.translator) ('fes.fileLoadError.font', { + suggestion: suggestion + }), + method: 'loadFont' + }; + case 5: + return { + message: (0, _internationalization.translator) ('fes.fileLoadError.json', { + suggestion: suggestion + }), + method: 'loadJSON' + }; + case 6: + return { + message: (0, _internationalization.translator) ('fes.fileLoadError.bytes', { + suggestion: suggestion + }), + method: 'loadBytes' + }; + case 7: + return { + message: (0, _internationalization.translator) ('fes.fileLoadError.large'), + method: 'loadX' + }; + case 8: + return { + message: (0, _internationalization.translator) ('fes.fileLoadError.gif'), + method: 'loadImage' + }; + } + }; + /** + * Called internally if there is an error during file loading. + * + * Generates and prints a friendly error message using key: + * "fes.fileLoadError.[*]". + * + * @method _friendlyFileLoadError + * @private + * @param {Number} errorType Number of file load error type + * @param {String} filePath Path to file caused the error + */ + _main.default._friendlyFileLoadError = function (errorType, filePath) { + var _fileLoadErrorCases = fileLoadErrorCases(errorType, filePath), + message = _fileLoadErrorCases.message, + method = _fileLoadErrorCases.method; + _main.default._friendlyError(message, method, 3); + }; + } + var _default = _main.default; + exports.default = _default; + }, + { + '../internationalization': 301, + '../main': 303 + } + ], + 296: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../main')); + var _internationalization = _dereq_('../internationalization'); + var constants = _interopRequireWildcard(_dereq_('../constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } /** + * @for p5 + * @requires core + */ + /** + * Checks if any p5.js constant/function is declared outside of setup() + * and draw() function. Also checks any reserved constant/function is + * redeclared. + * + * Generates and prints a friendly error message using key: + * "fes.sketchReaderErrors.reservedConst", + * "fes.sketchReaderErrors.reservedFunc". + * + * @method _fesCodeReader + * @private + */ + + if (typeof IS_MINIFIED !== 'undefined') { + _main.default._fesCodeReader = function () { + }; + } else { + //list of functions to ignore as they either + //are ment to be defined or generate false positive + //outputs + var ignoreFunction = [ + 'setup', + 'draw', + 'preload', + 'deviceMoved', + 'deviceTurned', + 'deviceShaken', + 'doubleClicked', + 'mousePressed', + 'mouseReleased', + 'mouseMoved', + 'mouseDragged', + 'mouseClicked', + 'mouseWheel', + 'touchStarted', + 'touchMoved', + 'touchEnded', + 'keyPressed', + 'keyReleased', + 'keyTyped', + 'windowResized', + 'name', + 'parent', + 'toString', + 'print', + 'stop', + 'onended' + ]; + /** + * Takes a list of variables defined by the user in the code + * as an array and checks if the list contains p5.js constants and functions. + * + * @method checkForConstsAndFuncs + * @private + * @param {Array} variableArray + */ + var checkForConstsAndFuncs = function checkForConstsAndFuncs(variableArray) { + for (var i = 0; i < variableArray.length; i++) { + //if the element in variableArray is a p5.js constant then the below condidion + //will be true, hence a match is found + if (constants[variableArray[i]] !== undefined) { + var url = 'https://p5js.org/reference/#/p5/'.concat(variableArray[i]); + //display the FES message if a match is found + _main.default._friendlyError((0, _internationalization.translator) ('fes.sketchReaderErrors.reservedConst', { + url: url, + symbol: variableArray[i] + })); + return; + //if match found then end search + } + } + var p5Constructors = { + }; + for (var _i = 0, _Object$keys = Object.keys(_main.default); _i < _Object$keys.length; _i++) { + var key = _Object$keys[_i]; + // Get a list of all constructors in p5. They are functions whose names + // start with a capital letter + if (typeof _main.default[key] === 'function' && key[0] !== key[0].toLowerCase()) { + p5Constructors[key] = _main.default[key]; + } + } + for (var _i2 = 0; _i2 < variableArray.length; _i2++) { + //ignoreFunction contains the list of functions to be ignored + if (!ignoreFunction.includes(variableArray[_i2])) { + var keyArray = Object.keys(p5Constructors); + var j = 0; + //for every function name obtained check if it matches any p5.js function name + for (; j < keyArray.length; j++) { + if (p5Constructors[keyArray[j]].prototype[variableArray[_i2]] !== undefined) { + //if a p5.js function is used ie it is in the funcs array + var _url = 'https://p5js.org/reference/#/p5/'.concat(variableArray[_i2]); + _main.default._friendlyError((0, _internationalization.translator) ('fes.sketchReaderErrors.reservedFunc', { + url: _url, + symbol: variableArray[_i2] + })); + return; + } + } + } + } + }; + //these regex are used to perform variable extraction + //visit https://regexr.com/ for the detailed view + var optionalVarKeyword = /(?:(?:let|const|var)\s+)?/; + // Bracketed expressions start with an opening bracket, some amount of non + // bracket characters, then a closing bracket. Note that this won't properly + // parse nested brackets: `constrain(millis(), 0, 1000)` will match + // `constrain(millis()` only, but will still fail gracefully and not try to + // mistakenly read any subsequent code as assignment expressions. + var roundBracketedExpr = /(?:\([^)]*\))/; + var squareBracketedExpr = /(?:\[[^\]]*\])/; + var curlyBracketedExpr = /(?:\{[^}]*\})/; + var bracketedExpr = new RegExp([roundBracketedExpr, + squareBracketedExpr, + curlyBracketedExpr].map(function (regex) { + return regex.source; + }).join('|')); + // In an a = b expression, `b` can be any character up to a newline or comma, + // unless the comma is inside of a bracketed expression of some kind (to make + // sure we parse function calls with multiple arguments properly.) + var rightHandSide = new RegExp('(?:' + bracketedExpr.source + '|[^\\n,])+'); + var leftHandSide = /([\w$]+)/; + var assignmentOperator = /\s*=\s*/; + var singleAssignment = new RegExp(leftHandSide.source + assignmentOperator.source + rightHandSide.source); + var listSeparator = /,\s*/; + var oneOrMoreAssignments = new RegExp('(?:' + singleAssignment.source + listSeparator.source + ')*' + singleAssignment.source); + var assignmentStatement = new RegExp('^' + optionalVarKeyword.source + oneOrMoreAssignments.source); + var letConstName = /(?:(?:let|const)\s+)([\w$]+)/; + /** + * Takes an array in which each element is a line of code + * containing a variable definition(Eg: arr=['let x = 100', 'const y = 200']) + * and extracts the variables defined. + * + * @method extractVariables + * @private + * @param {Array} linesArray array of lines of code + */ + var extractVariables = function extractVariables(linesArray) { + //extract variable names from the user's code + var matches = [ + ]; + linesArray.forEach(function (ele) { + // Match 0 is the part of the line of code that the regex looked at. + // Matches 1 and onward will be only the variable names on the left hand + // side of assignment expressions. + var match = ele.match(assignmentStatement); + if (!match) return; + matches.push.apply(matches, _toConsumableArray(match.slice(1).filter(function (group) { + return group !== undefined; + }))); + }); + //check if the obtained variables are a part of p5.js or not + checkForConstsAndFuncs(matches); + }; + /** + * Takes an array in which each element is a line of code + * containing a function definition(array=['let x = () => {...}']) + * and extracts the functions defined. + * + * @method extractFuncVariables + * @private + * @param {Array} linesArray array of lines of code + */ + var extractFuncVariables = function extractFuncVariables(linesArray) { + var matches = [ + ]; + //RegExp to extract function names from let/const x = function()... + //visit https://regexr.com/ for the detailed view. + linesArray.forEach(function (ele) { + var m = ele.match(letConstName); + if (m !== null) matches.push(ele.match(letConstName) [1]); + }); + //matches array contains the names of the functions + checkForConstsAndFuncs(matches); + }; + /** + * Converts code written by the user to an array + * every element of which is a seperate line of code. + * + * @method codeToLines + * @private + * @param {String} code code written by the user + */ + var codeToLines = function codeToLines(code) { + //convert code to array of code and filter out + //unnecessary lines + var arrayVariables = code.split('\n').map(function (line) { + return line.trim(); + }).filter(function (line) { + return line !== '' && !line.includes('//') && (line.includes('let') || line.includes('const')) && !line.includes('=>') && !line.includes('function'); + } //filter out lines containing variable names + ); + //filter out lines containing function names + var arrayFunctions = code.split('\n').map(function (line) { + return line.trim(); + }).filter(function (line) { + return line !== '' && !line.includes('//') && (line.includes('let') || line.includes('const')) && (line.includes('=>') || line.includes('function')); + }); + //pass the relevant array to a function which will extract all the variables/functions names + extractVariables(arrayVariables); + extractFuncVariables(arrayFunctions); + }; + /** + * Remove multiline comments and the content inside it. + * + * @method removeMultilineComments + * @private + * @param {String} code code written by the user + * @returns {String} + */ + var removeMultilineComments = function removeMultilineComments(code) { + var start = code.indexOf('/*'); + var end = code.indexOf('*/'); + //create a new string which don't have multiline comments + while (start !== - 1 && end !== - 1) { + if (start === 0) { + code = code.slice(end + 2); + } else code = code.slice(0, start) + code.slice(end + 2); + start = code.indexOf('/*'); + end = code.indexOf('*/'); + } + return code; + }; + /** + * Checks if any p5.js constant or function is declared outside a function + * and reports it if found. + * + * @method globalConstFuncCheck + * @private + * @returns {Boolean} + */ + var globalConstFuncCheck = function globalConstFuncCheck() { + // generate all the const key data as an array + var tempArray = Object.keys(constants); + var element; + for (var i = 0; i < tempArray.length; i++) { + try { + //if the user has not declared p5.js constant anywhere outside the + //setup or draw function then this will throw an + //error. + element = eval(tempArray[i]); + } catch (e) { + //We are catching the error due to the above mentioned + //reason. Since there is no declaration of constant everything + //is OK so we will skip the current iteration and check for the + //next element. + continue; + } //if we are not getting an error this means + //user have changed the value. We will check + //if the value is changed and if it is changed + //then report. + + if (constants[tempArray[i]] !== element) { + var url = 'https://p5js.org/reference/#/p5/'.concat(tempArray[i]); + _main.default._friendlyError((0, _internationalization.translator) ('fes.sketchReaderErrors.reservedConst', { + url: url, + symbol: tempArray[i] + })); + //if a p5.js constant is already reported then no need to check + //for p5.js functions. + return true; + } + } //the below code gets a list of p5.js functions + + var p5Constructors = { + }; + for (var _i3 = 0, _Object$keys2 = Object.keys(_main.default); _i3 < _Object$keys2.length; _i3++) { + var key = _Object$keys2[_i3]; + // Get a list of all constructors in p5. They are functions whose names + // start with a capital letter + if (typeof _main.default[key] === 'function' && key[0] !== key[0].toLowerCase()) { + p5Constructors[key] = _main.default[key]; + } + } + var keyArray = Object.keys(p5Constructors); + var classesWithGlobalFns = [ + 'Renderer', + 'Renderer2D', + 'RendererGL' + ]; + var functionArray = [ + ]; + //get the names of all p5.js functions which are available globally + for (var _i4 = 0; _i4 < classesWithGlobalFns.length; _i4++) { + functionArray.push.apply(functionArray, _toConsumableArray(Object.keys(p5Constructors[classesWithGlobalFns[_i4]].prototype))); + } //we have p5.js function names with us so we will check + //if they have been declared or not. + + for (var _i5 = 0; _i5 < functionArray.length; _i5++) { + //ignoreFunction contains the list of functions to be ignored + if (!ignoreFunction.includes(functionArray[_i5])) { + try { + //if we get an error that means the function is not declared + element = eval(functionArray[_i5]); + } catch (e) { + //we will skip the iteration + continue; + } //if we are not getting an error this means + //user have used p5.js function. Check if it is + //changed and if so then report it. + + for (var k = 0; k < keyArray.length; k++) { + if (p5Constructors[keyArray[k]].prototype[functionArray[_i5]] === undefined); + else { + if (p5Constructors[keyArray[k]].prototype[functionArray[_i5]] !== element) { + var _url2 = 'https://p5js.org/reference/#/p5/'.concat(functionArray[_i5]); + _main.default._friendlyError((0, _internationalization.translator) ('fes.sketchReaderErrors.reservedFunc', { + url: _url2, + symbol: functionArray[_i5] + })); + return true; + } + } + } + } + } + }; + /** + * Initiates the sketch_reader's processes. + * Obtains the code in setup and draw function + * and forwards it for further processing and evaluation. + * + * @method fesCodeReader + * @private + */ + var fesCodeReader = function fesCodeReader() { + //moveAhead will determine if a match is found outside + //the setup and draw function. If a match is found then + //to prevent further potential reporting we will exit immidiately + var moveAhead = globalConstFuncCheck(); + if (moveAhead) return; + var code = ''; + try { + //get code from setup + code += '' + setup; + } catch (e) { + code += ''; + } + try { + //get code from draw + code += '\n' + draw; + } catch (e) { + code += ''; + } + if (code === '') return; + code = removeMultilineComments(code); + codeToLines(code); + }; + _main.default._fesCodeReader = fesCodeReader; + window.addEventListener('load', _main.default._fesCodeReader); + } + var _default = _main.default; + exports.default = _default; + }, + { + '../constants': 291, + '../internationalization': 301, + '../main': 303, + 'core-js/modules/es.array.filter': 174, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.keys': 204, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.constructor': 209, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.match': 216, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.string.trim': 224, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.for-each': 260, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 297: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @for p5 + * @requires core + */ + // Borrow from stacktracejs https://github.com/stacktracejs/stacktrace.js with + // minor modifications. The license for the same and the code is included below + // Copyright (c) 2017 Eric Wendelin and other contributors + // Permission is hereby granted, free of charge, to any person obtaining a copy of + // this software and associated documentation files (the "Software"), to deal in + // the Software without restriction, including without limitation the rights to + // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + // of the Software, and to permit persons to whom the Software is furnished to do + // so, subject to the following conditions: + // The above copyright notice and this permission notice shall be included in all + // copies or substantial portions of the Software. + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + // SOFTWARE. + + function ErrorStackParser() { + var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+:\d+/; + var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+:\d+|\(native\))/m; + var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code])?$/; + return { + /** + * Given an Error object, extract the most information from it. + * @private + * @param {Error} error object + * @return {Array} of stack frames + */ + parse: function ErrorStackParser$$parse(error) { + if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') { + return this.parseOpera(error); + } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) { + return this.parseV8OrIE(error); + } else if (error.stack) { + return this.parseFFOrSafari(error); + } else { + // throw new Error('Cannot parse given Error object'); + } + }, + // Separate line and column numbers from a string of the form: (URI:Line:Column) + extractLocation: function ErrorStackParser$$extractLocation(urlLike) { + // Fail-fast but return locations like "(native)" + if (urlLike.indexOf(':') === - 1) { + return [urlLike]; + } + var regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; + var parts = regExp.exec(urlLike.replace(/[()]/g, '')); + return [parts[1], + parts[2] || undefined, + parts[3] || undefined]; + }, + parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) { + var filtered = error.stack.split('\n').filter(function (line) { + return !!line.match(CHROME_IE_STACK_REGEXP); + }, this); + return filtered.map(function (line) { + if (line.indexOf('(eval ') > - 1) { + // Throw away eval information until we implement stacktrace.js/stackframe#8 + line = line.replace(/eval code/g, 'eval').replace(/(\(eval at [^()]*)|(\),.*$)/g, ''); + } + var sanitizedLine = line.replace(/^\s+/, '').replace(/\(eval code/g, '('); + // capture and preseve the parenthesized location "(/foo/my bar.js:12:87)" in + // case it has spaces in it, as the string is split on \s+ later on + var location = sanitizedLine.match(/ (\((.+):(\d+):(\d+)\)$)/); + // remove the parenthesized location from the line, if it was matched + sanitizedLine = location ? sanitizedLine.replace(location[0], '') : sanitizedLine; + var tokens = sanitizedLine.split(/\s+/).slice(1); + // if a location was matched, pass it to extractLocation() otherwise pop the last token + var locationParts = this.extractLocation(location ? location[1] : tokens.pop()); + var functionName = tokens.join(' ') || undefined; + var fileName = [ + 'eval', + '' + ].indexOf(locationParts[0]) > - 1 ? undefined : locationParts[0]; + return { + functionName: functionName, + fileName: fileName, + lineNumber: locationParts[1], + columnNumber: locationParts[2], + source: line + }; + }, this); + }, + parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) { + var filtered = error.stack.split('\n').filter(function (line) { + return !line.match(SAFARI_NATIVE_CODE_REGEXP); + }, this); + return filtered.map(function (line) { + // Throw away eval information until we implement stacktrace.js/stackframe#8 + if (line.indexOf(' > eval') > - 1) { + line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ':$1'); + } + if (line.indexOf('@') === - 1 && line.indexOf(':') === - 1) { + // Safari eval frames only have function names and nothing else + return { + functionName: line + }; + } else { + var functionNameRegex = /((.*".+"[^@]*)?[^@]*)(?:@)/; + var matches = line.match(functionNameRegex); + var functionName = matches && matches[1] ? matches[1] : undefined; + var locationParts = this.extractLocation(line.replace(functionNameRegex, '')); + return { + functionName: functionName, + fileName: locationParts[0], + lineNumber: locationParts[1], + columnNumber: locationParts[2], + source: line + }; + } + }, this); + }, + parseOpera: function ErrorStackParser$$parseOpera(e) { + if (!e.stacktrace || e.message.indexOf('\n') > - 1 && e.message.split('\n').length > e.stacktrace.split('\n').length) { + return this.parseOpera9(e); + } else if (!e.stack) { + return this.parseOpera10(e); + } else { + return this.parseOpera11(e); + } + }, + parseOpera9: function ErrorStackParser$$parseOpera9(e) { + var lineRE = /Line (\d+).*script (?:in )?(\S+)/i; + var lines = e.message.split('\n'); + var result = [ + ]; + for (var i = 2, len = lines.length; i < len; i += 2) { + var match = lineRE.exec(lines[i]); + if (match) { + result.push({ + fileName: match[2], + lineNumber: match[1], + source: lines[i] + }); + } + } + return result; + }, + parseOpera10: function ErrorStackParser$$parseOpera10(e) { + var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i; + var lines = e.stacktrace.split('\n'); + var result = [ + ]; + for (var i = 0, len = lines.length; i < len; i += 2) { + var match = lineRE.exec(lines[i]); + if (match) { + result.push({ + functionName: match[3] || undefined, + fileName: match[2], + lineNumber: match[1], + source: lines[i] + }); + } + } + return result; + }, + // Opera 10.65+ Error.stack very similar to FF/Safari + parseOpera11: function ErrorStackParser$$parseOpera11(error) { + var filtered = error.stack.split('\n').filter(function (line) { + return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/); + }, this); + return filtered.map(function (line) { + var tokens = line.split('@'); + var locationParts = this.extractLocation(tokens.pop()); + var functionCall = tokens.shift() || ''; + var functionName = functionCall.replace(//, '$2').replace(/\([^)]*\)/g, '') || undefined; + var argsRaw; + if (functionCall.match(/\(([^)]*)\)/)) { + argsRaw = functionCall.replace(/^[^(]+\(([^)]*)\)$/, '$1'); + } + var args = argsRaw === undefined || argsRaw === '[arguments not available]' ? undefined : argsRaw.split(','); + return { + functionName: functionName, + args: args, + fileName: locationParts[0], + lineNumber: locationParts[1], + columnNumber: locationParts[2], + source: line + }; + }, this); + } + }; + } // End borrow + // wrapper exposing ErrorStackParser + + _main.default._getErrorStackParser = function getErrorStackParser() { + return new ErrorStackParser(); + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../main': 303, + 'core-js/modules/es.array.filter': 174, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.string.match': 216, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.string.split': 221 + } + ], + 298: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.map'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../main')); + var constants = _interopRequireWildcard(_dereq_('../constants')); + var _internationalization = _dereq_('../internationalization'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + 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 _createSuper(Derived) { + function 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; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_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 _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); + } + function 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; + } + } + function _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); + } + function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf('[native code]') !== - 1; + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } /** + * @for p5 + * @requires core + */ + + if (typeof IS_MINIFIED !== 'undefined') { + _main.default._validateParameters = _main.default._clearValidateParamsCache = function () { + }; + } else { + // for parameter validation + var dataDoc = _dereq_('../../../docs/parameterData.json'); + var arrDoc = JSON.parse(JSON.stringify(dataDoc)); + var docCache = { + }; + var builtinTypes = new Set(['null', + 'number', + 'string', + 'boolean', + 'constant', + 'function', + 'any', + 'integer']); + var basicTypes = { + number: true, + boolean: true, + string: true, + function : true, + undefined: true + }; + // reverse map of all constants + var constantsReverseMap = { + }; + for (var key in constants) { + constantsReverseMap[constants[key]] = key; + } // mapping names of p5 types to their constructor function + // p5Constructors: + // - Color: f() + // - Graphics: f() + // - Vector: f() + // and so on + + var p5Constructors = { + }; + // For speedup over many runs. funcSpecificConstructors[func] only has the + // constructors for types which were seen earlier as args of "func" + var funcSpecificConstructors = { + }; + window.addEventListener('load', function () { + // Make a list of all p5 classes to be used for argument validation + // This must be done only when everything has loaded otherwise we get + // an empty array + for (var _i = 0, _Object$keys = Object.keys(_main.default); _i < _Object$keys.length; _i++) { + var _key = _Object$keys[_i]; + // Get a list of all constructors in p5. They are functions whose names + // start with a capital letter + if (typeof _main.default[_key] === 'function' && _key[0] !== _key[0].toLowerCase()) { + p5Constructors[_key] = _main.default[_key]; + } + } + }); + var argumentTree = { + }; + // The following two functions are responsible for querying and inserting + // into the argument tree. It stores the types of arguments that each + // function has seen so far. It is used to query if a sequence of + // arguments seen in validate parameters was seen before. + // Lets consider that the following segment of code runs repeatedly, perhaps + // in a loop or in draw() + // color(10, 10, 10); + // color(10, 10); + // color('r', 'g', 'b'); + // After the first of run the code segment, the argument tree looks like + // - color + // - number + // - number + // - number + // - seen: true + // - seen: true + // - string + // - string + // - string + // - seen: true + // seen: true signifies that this argument was also seen as the last + // argument in a call. Now in the second run of the sketch, it would traverse + // the existing tree and see seen: true, i.e this sequence was seen + // before and so scoring can be skipped. This also prevents logging multiple + // validation messages for the same thing. + /** + * Query type and return the result as an object + * + * This would be called repeatedly over and over again, + * so it needs to be as optimized for performance as possible + * @method addType + * @private + */ + var addType = function addType(value, obj, func) { + var type = _typeof(value); + if (basicTypes[type]) { + if (constantsReverseMap[value]) { + // check if the value is a p5 constant and if it is, we would want the + // value itself to be stored in the tree instead of the type + obj = obj[value] || (obj[value] = { + }); + } else { + obj = obj[type] || (obj[type] = { + }); + } + } else if (value === null) { + // typeof null -> "object". don't want that + obj = obj['null'] || (obj['null'] = { + }); + } else { + // objects which are instances of p5 classes have nameless constructors. + // native objects have a constructor named "Object". This check + // differentiates between the two so that we dont waste time finding the + // p5 class if we just have a native object + if (value.constructor && value.constructor.name) { + obj = obj[value.constructor.name] || (obj[value.constructor.name] = { + }); + return obj; + } // constructors for types defined in p5 do not have a name property. + // e.constructor.name gives "". Code in this segment is a workaround for it + // p5C will only have the name: constructor mapping for types + // which were already seen as args of "func" + + var p5C = funcSpecificConstructors[func]; + // p5C would contain much fewer items than p5Constructors. if we find our + // answer in p5C, we don't have to scan through p5Constructors + if (p5C === undefined) { + // if there isn't an entry yet for func + // make an entry of empty object + p5C = funcSpecificConstructors[func] = { + }; + } + for (var _key2 in p5C) { + // search on the constructors we have already seen (smaller search space) + if (value instanceof p5C[_key2]) { + obj = obj[_key2] || (obj[_key2] = { + }); + return obj; + } + } + for (var _key3 in p5Constructors) { + // if the above search didn't work, search on all p5 constructors + if (value instanceof p5Constructors[_key3]) { + obj = obj[_key3] || (obj[_key3] = { + }); + // if found, add to known constructors for this function + p5C[_key3] = p5Constructors[_key3]; + return obj; + } + } // nothing worked, put the type as it is + + obj = obj[type] || (obj[type] = { + }); + } + return obj; + }; + /** + * Build the argument type tree, argumentTree + * + * This would be called repeatedly over and over again, + * so it needs to be as optimized for performance as possible + * @method buildArgTypeCache + * @private + */ + var buildArgTypeCache = function buildArgTypeCache(func, arr) { + // get the if an argument tree for current function already exists + var obj = argumentTree[func]; + if (obj === undefined) { + // if it doesn't, create an empty tree + obj = argumentTree[func] = { + }; + } + for (var i = 0, len = arr.length; i < len; ++i) { + var value = arr[i]; + if (value instanceof Array) { + // an array is passed as an argument, expand it and get the type of + // each of its element. We distinguish the start of an array with 'as' + // or arraystart. This would help distinguish between the arguments + // (number, number, number) and (number, [number, number]) + obj = obj['as'] || (obj['as'] = { + }); + for (var j = 0, lenA = value.length; j < lenA; ++j) { + obj = addType(value[j], obj, func); + } + } else { + obj = addType(value, obj, func); + } + } + return obj; + }; + /** + * Query data.json + * This is a helper function for validateParameters() + * @method lookupParamDoc + * @private + */ + var lookupParamDoc = function lookupParamDoc(func) { + // look for the docs in the `data.json` datastructure + var ichDot = func.lastIndexOf('.'); + var funcName = func.slice(ichDot + 1); + var funcClass = func.slice(0, ichDot !== - 1 ? ichDot : 0) || 'p5'; + var classitems = arrDoc; + var queryResult = classitems[funcClass][funcName]; + // different JSON structure for funct with multi-format + var overloads = [ + ]; + if (queryResult.hasOwnProperty('overloads')) { + // add all the overloads + for (var i = 0; i < queryResult.overloads.length; i++) { + overloads.push({ + formats: queryResult.overloads[i].params + }); + } + } else { + // no overloads, just add the main method definition + overloads.push({ + formats: queryResult.params || [ + ] + }); + } // parse the parameter types for each overload + + var mapConstants = { + }; + var maxParams = 0; + overloads.forEach(function (overload) { + var formats = overload.formats; + // keep a record of the maximum number of arguments + // this method requires. + if (maxParams < formats.length) { + maxParams = formats.length; + } // calculate the minimum number of arguments + // this overload requires. + + var minParams = formats.length; + while (minParams > 0 && formats[minParams - 1].optional) { + minParams--; + } + overload.minParams = minParams; + // loop through each parameter position, and parse its types + formats.forEach(function (format) { + // split this parameter's types + format.types = format.type.split('|').map(function ct(type) { + // array + if (type.slice( - 2) === '[]') { + return { + name: type, + array: ct(type.slice(0, - 2)) + }; + } + var lowerType = type.toLowerCase(); + // constant + if (lowerType === 'constant') { + var constant; + if (mapConstants.hasOwnProperty(format.name)) { + constant = mapConstants[format.name]; + } else { + // parse possible constant values from description + var myRe = /either\s+(?:[A-Z0-9_]+\s*,?\s*(?:or)?\s*)+/g; + var values = { + }; + var names = [ + ]; + constant = mapConstants[format.name] = { + values: values, + names: names + }; + var myArray = myRe.exec(format.description); + if (func === 'endShape' && format.name === 'mode') { + values[constants.CLOSE] = true; + names.push('CLOSE'); + } else { + var match = myArray[0]; + var reConst = /[A-Z0-9_]+/g; + var matchConst; + while ((matchConst = reConst.exec(match)) !== null) { + var name = matchConst[0]; + if (constants.hasOwnProperty(name)) { + values[constants[name]] = true; + names.push(name); + } + } + } + } + return { + name: type, + builtin: lowerType, + names: constant.names, + values: constant.values + }; + } // function + + if (lowerType.slice(0, 'function'.length) === 'function') { + lowerType = 'function'; + } // builtin + + if (builtinTypes.has(lowerType)) { + return { + name: type, + builtin: lowerType + }; + } // find type's prototype + + var t = window; + var typeParts = type.split('.'); + // special-case 'p5' since it may be non-global + if (typeParts[0] === 'p5') { + t = _main.default; + typeParts.shift(); + } + typeParts.forEach(function (p) { + t = t && t[p]; + }); + if (t) { + return { + name: type, + prototype: t + }; + } + return { + name: type, + type: lowerType + }; + }); + }); + }); + return { + overloads: overloads, + maxParams: maxParams + }; + }; + /** + * Checks whether input type is Number + * This is a helper function for validateParameters() + * @method isNumber + * @private + * + * @returns {Boolean} a boolean indicating whether input type is Number + */ + var isNumber = function isNumber(param) { + if (isNaN(parseFloat(param))) return false; + switch (_typeof(param)) { + case 'number': + return true; + case 'string': + return !isNaN(param); + default: + return false; + } + }; + /** + * Test type for non-object type parameter validation + * @method testParamType + * @private + */ + var testParamType = function testParamType(param, type) { + var isArray = param instanceof Array; + var matches = true; + if (type.array && isArray) { + for (var i = 0; i < param.length; i++) { + var error = testParamType(param[i], type.array); + if (error) return error / 2; // half error for elements + } + } else if (type.prototype) { + matches = param instanceof type.prototype; + } else if (type.builtin) { + switch (type.builtin) { + case 'number': + matches = isNumber(param); + break; + case 'integer': + matches = isNumber(param) && Number(param) === Math.floor(param); + break; + case 'boolean': + case 'any': + matches = true; + break; + case 'array': + matches = isArray; + break; + case 'string': + matches = /*typeof param === 'number' ||*/ typeof param === 'string'; + break; + case 'constant': + matches = type.values.hasOwnProperty(param); + break; + case 'function': + matches = param instanceof Function; + break; + case 'null': + matches = param === null; + break; + } + } else { + matches = _typeof(param) === type.t; + } + return matches ? 0 : 1; + }; + /** + * Test type for multiple parameters + * @method testParamTypes + * @private + */ + var testParamTypes = function testParamTypes(param, types) { + var minScore = 9999; + for (var i = 0; minScore > 0 && i < types.length; i++) { + var score = testParamType(param, types[i]); + if (minScore > score) minScore = score; + } + return minScore; + }; + /** + * generate a score (higher is worse) for applying these args to + * this overload. + * @method scoreOverload + * @private + */ + var scoreOverload = function scoreOverload(args, argCount, overload, minScore) { + var score = 0; + var formats = overload.formats; + var minParams = overload.minParams; + // check for too few/many args + // the score is double number of extra/missing args + if (argCount < minParams) { + score = (minParams - argCount) * 2; + } else if (argCount > formats.length) { + score = (argCount - formats.length) * 2; + } // loop through the formats, adding up the error score for each arg. + // quit early if the score gets higher than the previous best overload. + + for (var p = 0; score <= minScore && p < formats.length; p++) { + var arg = args[p]; + var format = formats[p]; + // '== null' checks for 'null' and typeof 'undefined' + if (arg == null) { + // handle undefined args + if (!format.optional || p < minParams || p < argCount) { + score += 1; + } + } else { + score += testParamTypes(arg, format.types); + } + } + return score; + }; + /** + * Gets a list of errors for this overload + * @method getOverloadErrors + * @private + */ + var getOverloadErrors = function getOverloadErrors(args, argCount, overload) { + var formats = overload.formats; + var minParams = overload.minParams; + // check for too few/many args + if (argCount < minParams) { + return [{ + type: 'TOO_FEW_ARGUMENTS', + argCount: argCount, + minParams: minParams + } + ]; + } else if (argCount > formats.length) { + return [{ + type: 'TOO_MANY_ARGUMENTS', + argCount: argCount, + maxParams: formats.length + } + ]; + } + var errorArray = [ + ]; + for (var p = 0; p < formats.length; p++) { + var arg = args[p]; + var format = formats[p]; + // '== null' checks for 'null' and typeof 'undefined' + if (arg == null) { + // handle undefined args + if (!format.optional || p < minParams || p < argCount) { + errorArray.push({ + type: 'EMPTY_VAR', + position: p, + format: format + }); + } + } else if (testParamTypes(arg, format.types) > 0) { + errorArray.push({ + type: 'WRONG_TYPE', + position: p, + format: format, + arg: arg + }); + } + } + return errorArray; + }; + /** + * a custom error type, used by the mocha + * tests when expecting validation errors + * @method ValidationError + * @private + */ + _main.default.ValidationError = function (name) { + var err = /*#__PURE__*/ function (_Error) { + _inherits(err, _Error); + var _super = _createSuper(err); + function err(message, func, type) { + var _this; + _classCallCheck(this, err); + _this = _super.call(this); + _this.message = message; + _this.func = func; + _this.type = type; + if ('captureStackTrace' in Error) Error.captureStackTrace(_assertThisInitialized(_this), err); + else _this.stack = new Error().stack; + return _this; + } + return err; + }( /*#__PURE__*/ _wrapNativeSuper(Error)); + err.prototype.name = name; + return err; + }('ValidationError'); + /** + * Prints a friendly msg after parameter validation + * @method _friendlyParamError + * @private + */ + _main.default._friendlyParamError = function (errorObj, func) { + var message; + var translationObj; + function formatType() { + var format = errorObj.format; + return format.types.map(function (type) { + return type.names ? type.names.join('|') : type.name; + }).join('|'); + } + switch (errorObj.type) { + case 'EMPTY_VAR': + { + translationObj = { + func: func, + formatType: formatType(), + // It needs to be this way for i18next-extract to work. The comment + // specifies the values that the context can take so that it can + // statically prepare the translation files with them. + /* i18next-extract-mark-context-next-line ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"] */ + position: (0, _internationalization.translator) ('fes.positions.p', { + context: (errorObj.position + 1).toString(), + defaultValue: (errorObj.position + 1).toString() + }), + url: 'https://p5js.org/examples/data-variable-scope.html' + }; + break; + } + case 'WRONG_TYPE': + { + var arg = errorObj.arg; + var argType = arg instanceof Array ? 'array' : arg === null ? 'null' : arg === undefined ? 'undefined' : typeof arg === 'number' && isNaN(arg) ? 'NaN' : arg.name || _typeof(arg); + translationObj = { + func: func, + formatType: formatType(), + argType: argType, + /* i18next-extract-mark-context-next-line ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"] */ + position: (0, _internationalization.translator) ('fes.positions.p', { + context: (errorObj.position + 1).toString(), + defaultValue: (errorObj.position + 1).toString() + }) + }; + break; + } + case 'TOO_FEW_ARGUMENTS': + { + translationObj = { + func: func, + minParams: errorObj.minParams, + argCount: errorObj.argCount + }; + break; + } + case 'TOO_MANY_ARGUMENTS': + { + translationObj = { + func: func, + maxParams: errorObj.maxParams, + argCount: errorObj.argCount + }; + break; + } + } + if (translationObj) { + try { + // const re = /Function\.validateParameters.*[\r\n].*[\r\n].*\(([^)]*)/; + var myError = new Error(); + var parsed = _main.default._getErrorStackParser().parse(myError); + if (parsed[3] && parsed[3].functionName && parsed[3].functionName.includes('.') && _main.default.prototype[parsed[3].functionName.split('.').slice( - 1) [0]]) { + return; + } + if (_main.default._throwValidationErrors) { + throw new _main.default.ValidationError(message, func, errorObj.type); + } // try to extract the location from where the function was called + + if (parsed[3] && parsed[3].fileName && parsed[3].lineNumber && parsed[3].columnNumber) { + var location = ''.concat(parsed[3].fileName, ':').concat(parsed[3].lineNumber, ':').concat(parsed[3].columnNumber); + translationObj.location = (0, _internationalization.translator) ('fes.location', { + location: location, + // for e.g. get "sketch.js" from "https://example.com/abc/sketch.js" + file: parsed[3].fileName.split('/').slice( - 1), + line: parsed[3].lineNumber + }); + // tell fesErrorMonitor that we have already given a friendly message + // for this line, so it need not to do the same in case of an error + _main.default._fesLogCache[location] = true; + } + } catch (err) { + if (err instanceof _main.default.ValidationError) { + throw err; + } + } + translationObj.context = errorObj.type; + // i18next-extract-mark-context-next-line ["EMPTY_VAR", "TOO_MANY_ARGUMENTS", "TOO_FEW_ARGUMENTS", "WRONG_TYPE"] + message = (0, _internationalization.translator) ('fes.friendlyParamError.type', translationObj); + _main.default._friendlyError(''.concat(message), func, 3); + } + }; + /** + * Clears cache to avoid having multiple FES messages for the same set of + * parameters. + * + * If a function is called with some set of wrong arguments, and then called + * again with the same set of arguments, the messages due to the second call + * will be supressed. If two tests test on the same wrong arguments, the + * second test won't see the validationError. clearing argumentTree solves it + * + * @method _clearValidateParamsCache + * @private + */ + _main.default._clearValidateParamsCache = function clearValidateParamsCache() { + for (var _i2 = 0, _Object$keys2 = Object.keys(argumentTree); _i2 < _Object$keys2.length; _i2++) { + var _key4 = _Object$keys2[_i2]; + delete argumentTree[_key4]; + } + }; + // allowing access to argumentTree for testing + _main.default._getValidateParamsArgTree = function getValidateParamsArgTree() { + return argumentTree; + }; + /** + * Runs parameter validation by matching the input parameters with information + * from `docs/reference/data.json`. + * Generates and prints a friendly error message using key: + * "fes.friendlyParamError.[*]". + * + * @method _validateParameters + * @private + * @param {String} func Name of the function + * @param {Array} args User input arguments + * + * @example: + * const a; + * ellipse(10,10,a,5); + * console output: + * "It looks like ellipse received an empty variable in spot #2." + * + * @example: + * ellipse(10,"foo",5,5); + * console output: + * "ellipse was expecting a number for parameter #1, + * received "foo" instead." + */ + _main.default._validateParameters = function validateParameters(func, args) { + if (_main.default.disableFriendlyErrors) { + return; // skip FES + } // query / build the argument type tree and check if this sequence + // has already been seen before. + + var obj = buildArgTypeCache(func, args); + if (obj.seen) { + return; + } // mark this sequence as seen + + obj.seen = true; + // lookup the docs in the 'data.json' file + var docs = docCache[func] || (docCache[func] = lookupParamDoc(func)); + var overloads = docs.overloads; + var argCount = args.length; + // the following line ignores trailing undefined arguments, commenting + // it to resolve https://github.com/processing/p5.js/issues/4571 + // '== null' checks for 'null' and typeof 'undefined' + // while (argCount > 0 && args[argCount - 1] == null) argCount--; + // find the overload with the best score + var minScore = 99999; + var minOverload; + for (var i = 0; i < overloads.length; i++) { + var score = scoreOverload(args, argCount, overloads[i], minScore); + if (score === 0) { + return; // done! + } else if (minScore > score) { + // this score is better that what we have so far... + minScore = score; + minOverload = i; + } + } // this should _always_ be true here... + + if (minScore > 0) { + // get the errors for the best overload + var errorArray = getOverloadErrors(args, argCount, overloads[minOverload]); + // generate err msg + for (var n = 0; n < errorArray.length; n++) { + _main.default._friendlyParamError(errorArray[n], func); + } + } + }; + _main.default.prototype._validateParameters = _main.default.validateParameters; + } + var _default = _main.default; + exports.default = _default; + }, + { + '../../../docs/parameterData.json': 1, + '../constants': 291, + '../internationalization': 301, + '../main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.last-index-of': 184, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.function.name': 191, + 'core-js/modules/es.map': 192, + 'core-js/modules/es.number.constructor': 196, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.keys': 204, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.set': 212, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.for-each': 260, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 299: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var constants = _interopRequireWildcard(_dereq_('./constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } /** + * @requires constants + */ + + function modeAdjust(a, b, c, d, mode) { + if (mode === constants.CORNER) { + return { + x: a, + y: b, + w: c, + h: d + }; + } else if (mode === constants.CORNERS) { + return { + x: a, + y: b, + w: c - a, + h: d - b + }; + } else if (mode === constants.RADIUS) { + return { + x: a - c, + y: b - d, + w: 2 * c, + h: 2 * d + }; + } else if (mode === constants.CENTER) { + return { + x: a - c * 0.5, + y: b - d * 0.5, + w: c, + h: d + }; + } + } + var _default = { + modeAdjust: modeAdjust + }; + exports.default = _default; + }, + { + './constants': 291, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 300: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + var _main = _interopRequireDefault(_dereq_('../core/main')); + var _internationalization = _dereq_('./internationalization'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * _globalInit + * + * TODO: ??? + * if sketch is on window + * assume "global" mode + * and instantiate p5 automatically + * otherwise do nothing + * + * @private + * @return {Undefined} + */ + + var _globalInit = function _globalInit() { + // Could have been any property defined within the p5 constructor. + // If that property is already a part of the global object, + // this code has already run before, likely due to a duplicate import + if (typeof window._setupDone !== 'undefined') { + console.warn('p5.js seems to have been imported multiple times. Please remove the duplicate import'); + return; + } + if (!window.mocha) { + // If there is a setup or draw function on the window + // then instantiate p5 in "global" mode + if ((window.setup && typeof window.setup === 'function' || window.draw && typeof window.draw === 'function') && !_main.default.instance) { + new _main.default(); + } + } + }; + // make a promise that resolves when the document is ready + var waitForDocumentReady = function waitForDocumentReady() { + return new Promise(function (resolve, reject) { + // if the page is ready, initialize p5 immediately + if (document.readyState === 'complete') { + resolve(); + // if the page is still loading, add an event listener + // and initialize p5 as soon as it finishes loading + } else { + window.addEventListener('load', resolve, false); + } + }); + }; + // only load translations if we're using the full, un-minified library + var waitingForTranslator = typeof IS_MINIFIED === 'undefined' ? (0, _internationalization.initialize) () : Promise.resolve(); + Promise.all([waitForDocumentReady(), + waitingForTranslator]).then(_globalInit); + }, + { + '../core/main': 303, + './internationalization': 301, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.promise': 206, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 301: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.setTranslatorLanguage = exports.currentTranslatorLanguage = exports.availableTranslatorLanguages = exports.initialize = exports.translator = void 0; + var _i18next = _interopRequireDefault(_dereq_('i18next')); + var _i18nextBrowserLanguagedetector = _interopRequireDefault(_dereq_('i18next-browser-languagedetector')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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 fallbackResources, + languages; + if (typeof IS_MINIFIED === 'undefined') { + // internationalization is only for the unminified build + var translationsModule = _dereq_('../../translations'); + fallbackResources = translationsModule.default; + languages = translationsModule.languages; + if (typeof P5_DEV_BUILD !== 'undefined') { + // When the library is built in development mode ( using npm run dev ) + // we want to use the current translation files on the disk, which may have + // been updated but not yet pushed to the CDN. + var completeResources = _dereq_('../../translations/dev'); + for (var _i = 0, _Object$keys = Object.keys(completeResources); _i < _Object$keys.length; _i++) { + var language = _Object$keys[_i]; + // In es_translation, language is es and namespace is translation + // In es_MX_translation, language is es-MX and namespace is translation + var parts = language.split('_'); + var lng = parts.slice(0, parts.length - 1).join('-'); + var ns = parts[parts.length - 1]; + fallbackResources[lng] = fallbackResources[lng] || { + }; + fallbackResources[lng][ns] = completeResources[language]; + } + } + } /** + * This is our i18next "backend" plugin. It tries to fetch languages + * from a CDN. + */ + + var FetchResources = /*#__PURE__*/ function () { + function FetchResources(services, options) { + _classCallCheck(this, FetchResources); + this.init(services, options); + } // run fetch with a timeout. Automatically rejects on timeout + // default timeout = 2000 ms + + _createClass(FetchResources, [ + { + key: 'fetchWithTimeout', + value: function fetchWithTimeout(url, options) { + var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2000; + return Promise.race([fetch(url, options), + new Promise(function (_, reject) { + return setTimeout(function () { + return reject(new Error('timeout')); + }, timeout); + })]); + } + }, + { + key: 'init', + value: function init(services) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + this.services = services; + this.options = options; + } + }, + { + key: 'read', + value: function read(language, namespace, callback) { + var loadPath = this.options.loadPath; + if (language === this.options.fallback) { + // if the default language of the user is the same as our inbuilt fallback, + // there's no need to fetch resources from the cdn. This won't actually + // need to run when we use "partialBundledLanguages" in the init + // function. + callback(null, fallbackResources[language][namespace]); + } else if (languages.includes(language)) { + // The user's language is included in the list of languages + // that we so far added translations for. + var url = this.services.interpolator.interpolate(loadPath, { + lng: language, + ns: namespace + }); + this.loadUrl(url, callback); + } else { + // We don't have translations for this language. i18next will use + // the default language instead. + callback('Not found', false); + } + } + }, + { + key: 'loadUrl', + value: function loadUrl(url, callback) { + this.fetchWithTimeout(url).then(function (response) { + var ok = response.ok; + if (!ok) { + // caught in the catch() below + throw new Error('failed loading '.concat(url)); + } + return response.json(); + }, function () { + // caught in the catch() below + throw new Error('failed loading '.concat(url)); + }).then(function (data) { + return callback(null, data); + }).catch(callback); + } + } + ]); + return FetchResources; + }(); + FetchResources.type = 'backend'; + /** + * This is our translation function. Give it a key and + * it will retrieve the appropriate string + * (within supported languages) according to the + * user's browser's language settings. + * @function translator + * @param {String} key a key that corresponds to a message in our translation files + * @param {Object} values values for use in the message under the given `key` + * @returns {String} message (with values inserted) in the user's browser language + * @private + */ + var translator = function translator(key, values) { + console.debug('p5.js translator called before translations were loaded'); + // Certain FES functionality may trigger before translations are downloaded. + // Using "partialBundledLanguages" option during initialization, we can + // still use our fallback language to display messages + _i18next.default.t(key, values); /* i18next-extract-disable-line */ + }; + // (We'll set this to a real value in the init function below!) + /** + * Set up our translation function, with loaded languages + */ + exports.translator = translator; + var initialize = function initialize() { + var i18init = _i18next.default.use(_i18nextBrowserLanguagedetector.default).use(FetchResources).init({ + fallbackLng: 'en', + nestingPrefix: '$tr(', + nestingSuffix: ')', + defaultNS: 'translation', + returnEmptyString: false, + interpolation: { + escapeValue: false + }, + detection: { + checkWhitelist: false, + // prevent storing or locating language from cookie or localStorage + // more info on https://github.com/processing/p5.js/issues/4862 + order: [ + 'querystring', + 'navigator', + 'htmlTag', + 'path', + 'subdomain' + ], + caches: [ + ] + }, + backend: { + fallback: 'en', + loadPath: 'https://cdn.jsdelivr.net/npm/p5/translations/{{lng}}/{{ns}}.json' + }, + partialBundledLanguages: true, + resources: fallbackResources + }).then(function (translateFn) { + exports.translator = translator = translateFn; + }, function (e) { + return console.debug('Translations failed to load ('.concat(e, ')')); + }); + // i18next.init() returns a promise that resolves when the translations + // are loaded. We use this in core/init.js to hold p5 initialization until + // we have the translation files. + return i18init; + }; + /** + * Returns a list of languages we have translations loaded for + */ + exports.initialize = initialize; + var availableTranslatorLanguages = function availableTranslatorLanguages() { + return _i18next.default.languages; + }; + /** + * Returns the current language selected for translation + */ + exports.availableTranslatorLanguages = availableTranslatorLanguages; + var currentTranslatorLanguage = function currentTranslatorLanguage(language) { + return _i18next.default.language; + }; + /** + * Sets the current language for translation + * Returns a promise that resolved when loading is finished, + * or rejects if it fails. + */ + exports.currentTranslatorLanguage = currentTranslatorLanguage; + var setTranslatorLanguage = function setTranslatorLanguage(language) { + return _i18next.default.changeLanguage(language || undefined, function (e) { + return console.debug('Translations failed to load ('.concat(e, ')')); + }); + }; + exports.setTranslatorLanguage = setTranslatorLanguage; + }, + { + '../../translations': 365, + '../../translations/dev': undefined, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.object.keys': 204, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.promise': 206, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/web.dom-collections.iterator': 261, + 'i18next': 272, + 'i18next-browser-languagedetector': 269 + } + ], + 302: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('./main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @for p5 + * @requires core + * These are functions that are part of the Processing API but are not part of + * the p5.js API. In some cases they have a new name, in others, they are + * removed completely. Not all unsupported Processing functions are listed here + * but we try to include ones that a user coming from Processing might likely + * call. + */ + + _main.default.prototype.pushStyle = function () { + throw new Error('pushStyle() not used, see push()'); + }; + _main.default.prototype.popStyle = function () { + throw new Error('popStyle() not used, see pop()'); + }; + _main.default.prototype.popMatrix = function () { + throw new Error('popMatrix() not used, see pop()'); + }; + _main.default.prototype.pushMatrix = function () { + throw new Error('pushMatrix() not used, see push()'); + }; + var _default = _main.default; + exports.default = _default; + }, + { + './main': 303 + } + ], + 303: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-own-property-names'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.object.get-own-property-names'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + _dereq_('./shim'); + var constants = _interopRequireWildcard(_dereq_('./constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _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; + } /** + * @module Structure + * @submodule Structure + * @for p5 + * @requires constants + */ + // Core needs the PVariables object + /** + * This is the p5 instance constructor. + * + * A p5 instance holds all the properties and methods related to + * a p5 sketch. It expects an incoming sketch closure and it can also + * take an optional node parameter for attaching the generated p5 canvas + * to a node. The sketch closure takes the newly created p5 instance as + * its sole argument and may optionally set preload(), + * setup(), and/or + * draw() properties on it for running a sketch. + * + * A p5 sketch can run in "global" or "instance" mode: + * "global" - all properties and methods are attached to the window + * "instance" - all properties and methods are bound to this p5 object + * + * @class p5 + * @constructor + * @param {function(p5)} sketch a closure that can set optional preload(), + * setup(), and/or draw() properties on the + * given p5 instance + * @param {HTMLElement} [node] element to attach canvas to + * @return {p5} a p5 instance + */ + + var p5 = /*#__PURE__*/ function () { + function p5(sketch, node) { + var _this = this; + _classCallCheck(this, p5); + ////////////////////////////////////////////// + // PUBLIC p5 PROPERTIES AND METHODS + ////////////////////////////////////////////// + /** + * A function that's called once to load assets before the sketch runs. + * + * Declaring the function `preload()` sets a code block to run once + * automatically before setup() or + * draw(). It's used to load assets including + * multimedia files, fonts, data, and 3D models: + * + * ```js + * function preload() { + * // Code to run before the rest of the sketch. + * } + * ``` + * + * Functions such as loadImage(), + * loadFont(), + * loadJSON(), and + * loadModel() are guaranteed to either + * finish loading or raise an error if they're called within `preload()`. + * Doing so ensures that assets are available when the sketch begins + * running. + * + * @method preload + * + * @example + *
        + * + * let img; + * + * // Load an image and create a p5.Image object. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Draw the image. + * image(img, 0, 0); + * + * describe('A red brick wall.'); + * } + * + *
        + */ + /** + * A function that's called once when the sketch begins running. + * + * Declaring the function `setup()` sets a code block to run once + * automatically when the sketch starts running. It's used to perform + * setup tasks such as creating the canvas and initializing variables: + * + * ```js + * function setup() { + * // Code to run once at the start of the sketch. + * } + * ``` + * + * Code placed in `setup()` will run once before code placed in + * draw() begins looping. If the + * preload() is declared, then `setup()` will + * run immediately after preload() finishes + * loading assets. + * + * Note: `setup()` doesn’t have to be declared, but it’s common practice to do so. + * + * @method setup + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw the circle. + * circle(50, 50, 40); + * + * describe('A white circle on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Paint the background once. + * background(200); + * + * describe( + * 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.' + * ); + * } + * + * function draw() { + * // Draw circles repeatedly. + * circle(mouseX, mouseY, 40); + * } + * + *
        + * + *
        + * + * let img; + * + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Draw the image. + * image(img, 0, 0); + * + * describe( + * 'A white circle on a brick wall. The circle follows the mouse as the user moves, leaving a trail.' + * ); + * } + * + * function draw() { + * // Style the circle. + * noStroke(); + * + * // Draw the circle. + * circle(mouseX, mouseY, 10); + * } + * + *
        + */ + /** + * A function that's called repeatedly while the sketch runs. + * + * Declaring the function `draw()` sets a code block to run repeatedly + * once the sketch starts. It’s used to create animations and respond to + * user inputs: + * + * ```js + * function draw() { + * // Code to run repeatedly. + * } + * ``` + * + * This is often called the "draw loop" because p5.js calls the code in + * `draw()` in a loop behind the scenes. By default, `draw()` tries to run + * 60 times per second. The actual rate depends on many factors. The + * drawing rate, called the "frame rate", can be controlled by calling + * frameRate(). The number of times `draw()` + * has run is stored in the system variable + * frameCount(). + * + * Code placed within `draw()` begins looping after + * setup() runs. `draw()` will run until the user + * closes the sketch. `draw()` can be stopped by calling the + * noLoop() function. `draw()` can be resumed by + * calling the loop() function. + * + * @method draw + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Paint the background once. + * background(200); + * + * describe( + * 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.' + * ); + * } + * + * function draw() { + * // Draw circles repeatedly. + * circle(mouseX, mouseY, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A white circle on a gray background. The circle follows the mouse as the user moves.' + * ); + * } + * + * function draw() { + * // Paint the background repeatedly. + * background(200); + * + * // Draw circles repeatedly. + * circle(mouseX, mouseY, 40); + * } + * + *
        + * + *
        + * + * // Double-click the canvas to change the circle's color. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A white circle on a gray background. The circle follows the mouse as the user moves. The circle changes color to pink when the user double-clicks.' + * ); + * } + * + * function draw() { + * // Paint the background repeatedly. + * background(200); + * + * // Draw circles repeatedly. + * circle(mouseX, mouseY, 40); + * } + * + * // Change the fill color when the user double-clicks. + * function doubleClicked() { + * fill('deeppink'); + * } + * + *
        + */ + ////////////////////////////////////////////// + // PRIVATE p5 PROPERTIES AND METHODS + ////////////////////////////////////////////// + this._setupDone = false; + this._preloadDone = false; + // for handling hidpi + this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1; + this._maxAllowedPixelDimensions = 0; + this._userNode = node; + this._curElement = null; + this._elements = [ + ]; + this._glAttributes = null; + this._requestAnimId = 0; + this._preloadCount = 0; + this._isGlobal = false; + this._loop = true; + this._startListener = null; + this._initializeInstanceVariables(); + this._defaultCanvasSize = { + width: 100, + height: 100 + }; + this._events = { + // keep track of user-events for unregistering later + mousemove: null, + mousedown: null, + mouseup: null, + dragend: null, + dragover: null, + click: null, + dblclick: null, + mouseover: null, + mouseout: null, + keydown: null, + keyup: null, + keypress: null, + touchstart: null, + touchmove: null, + touchend: null, + resize: null, + blur: null + }; + this._millisStart = - 1; + this._recording = false; + this.touchstart = false; + this.touchend = false; + // States used in the custom random generators + this._lcg_random_state = null; + this._gaussian_previous = false; + this._events.wheel = null; + this._loadingScreenId = 'p5_loading'; + // Allows methods to be registered on an instance that + // are instance-specific. + this._registeredMethods = { + }; + var methods = Object.getOwnPropertyNames(p5.prototype._registeredMethods); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var prop = _step.value; + this._registeredMethods[prop] = p5.prototype._registeredMethods[prop].slice(); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + if (window.DeviceOrientationEvent) { + this._events.deviceorientation = null; + } + if (window.DeviceMotionEvent && !window._isNodeWebkit) { + this._events.devicemotion = null; + } // Function to invoke registered hooks before or after events such as preload, setup, and pre/post draw. + + p5.prototype.callRegisteredHooksFor = function (hookName) { + var target = this || p5.prototype; + var context = this._isGlobal ? window : this; + if (target._registeredMethods.hasOwnProperty(hookName)) { + var _methods = target._registeredMethods[hookName]; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = _methods[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var method = _step2.value; + if (typeof method === 'function') { + method.call(context); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + }; + this._start = function () { + // Find node if id given + if (_this._userNode) { + if (typeof _this._userNode === 'string') { + _this._userNode = document.getElementById(_this._userNode); + } + } + var context = _this._isGlobal ? window : _this; + if (context.preload) { + _this.callRegisteredHooksFor('beforePreload'); + // Setup loading screen + // Set loading screen into dom if not present + // Otherwise displays and removes user provided loading screen + var loadingScreen = document.getElementById(_this._loadingScreenId); + if (!loadingScreen) { + loadingScreen = document.createElement('div'); + loadingScreen.innerHTML = 'Loading...'; + loadingScreen.style.position = 'absolute'; + loadingScreen.id = _this._loadingScreenId; + var _node = _this._userNode || document.body; + _node.appendChild(loadingScreen); + } + var _methods2 = _this._preloadMethods; + for (var method in _methods2) { + // default to p5 if no object defined + _methods2[method] = _methods2[method] || p5; + var obj = _methods2[method]; + //it's p5, check if it's global or instance + if (obj === p5.prototype || obj === p5) { + if (_this._isGlobal) { + window[method] = _this._wrapPreload(_this, method); + } + obj = _this; + } + _this._registeredPreloadMethods[method] = obj[method]; + obj[method] = _this._wrapPreload(obj, method); + } + context.preload(); + _this._runIfPreloadsAreDone(); + } else { + _this._setup(); + if (!_this._recording) { + _this._draw(); + } + } + }; + this._runIfPreloadsAreDone = function () { + var context = this._isGlobal ? window : this; + if (context._preloadCount === 0) { + var loadingScreen = document.getElementById(context._loadingScreenId); + if (loadingScreen) { + loadingScreen.parentNode.removeChild(loadingScreen); + } + this.callRegisteredHooksFor('afterPreload'); + if (!this._setupDone) { + this._lastTargetFrameTime = window.performance.now(); + this._lastRealFrameTime = window.performance.now(); + context._setup(); + if (!this._recording) { + context._draw(); + } + } + } + }; + this._decrementPreload = function () { + var context = this._isGlobal ? window : this; + if (!context._preloadDone && typeof context.preload === 'function') { + context._setProperty('_preloadCount', context._preloadCount - 1); + context._runIfPreloadsAreDone(); + } + }; + this._wrapPreload = function (obj, fnName) { + var _this2 = this; + return function () { + //increment counter + _this2._incrementPreload(); + //call original function + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _this2._registeredPreloadMethods[fnName].apply(obj, args); + }; + }; + this._incrementPreload = function () { + var context = this._isGlobal ? window : this; + // Do nothing if we tried to increment preloads outside of `preload` + if (context._preloadDone) return; + context._setProperty('_preloadCount', context._preloadCount + 1); + }; + this._setup = function () { + _this.callRegisteredHooksFor('beforeSetup'); + // Always create a default canvas. + // Later on if the user calls createCanvas, this default one + // will be replaced + _this.createCanvas(_this._defaultCanvasSize.width, _this._defaultCanvasSize.height, 'p2d'); + // return preload functions to their normal vals if switched by preload + var context = _this._isGlobal ? window : _this; + if (typeof context.preload === 'function') { + for (var f in _this._preloadMethods) { + context[f] = _this._preloadMethods[f][f]; + if (context[f] && _this) { + context[f] = context[f].bind(_this); + } + } + } // Record the time when sketch starts + + _this._millisStart = window.performance.now(); + context._preloadDone = true; + // Short-circuit on this, in case someone used the library in "global" + // mode earlier + if (typeof context.setup === 'function') { + context.setup(); + } // unhide any hidden canvases that were created + + var canvases = document.getElementsByTagName('canvas'); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = canvases[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var k = _step3.value; + if (k.dataset.hidden === 'true') { + k.style.visibility = ''; + delete k.dataset.hidden; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + _this._lastTargetFrameTime = window.performance.now(); + _this._lastRealFrameTime = window.performance.now(); + _this._setupDone = true; + if (_this._accessibleOutputs.grid || _this._accessibleOutputs.text) { + _this._updateAccsOutput(); + } + _this.callRegisteredHooksFor('afterSetup'); + }; + this._draw = function () { + var now = window.performance.now(); + var time_since_last = now - _this._lastTargetFrameTime; + var target_time_between_frames = 1000 / _this._targetFrameRate; + // only draw if we really need to; don't overextend the browser. + // draw if we're within 5ms of when our next frame should paint + // (this will prevent us from giving up opportunities to draw + // again when it's really about time for us to do so). fixes an + // issue where the frameRate is too low if our refresh loop isn't + // in sync with the browser. note that we have to draw once even + // if looping is off, so we bypass the time delay if that + // is the case. + var epsilon = 5; + if (!_this._loop || time_since_last >= target_time_between_frames - epsilon) { + //mandatory update values(matrixes and stack) + _this.deltaTime = now - _this._lastRealFrameTime; + _this._setProperty('deltaTime', _this.deltaTime); + _this._frameRate = 1000 / _this.deltaTime; + _this.redraw(); + _this._lastTargetFrameTime = Math.max(_this._lastTargetFrameTime + target_time_between_frames, now); + _this._lastRealFrameTime = now; + // If the user is actually using mouse module, then update + // coordinates, otherwise skip. We can test this by simply + // checking if any of the mouse functions are available or not. + // NOTE : This reflects only in complete build or modular build. + if (typeof _this._updateMouseCoords !== 'undefined') { + _this._updateMouseCoords(); + //reset delta values so they reset even if there is no mouse event to set them + // for example if the mouse is outside the screen + _this._setProperty('movedX', 0); + _this._setProperty('movedY', 0); + } + } // get notified the next time the browser gives us + // an opportunity to draw. + + if (_this._loop) { + _this._requestAnimId = window.requestAnimationFrame(_this._draw); + } + }; + this._setProperty = function (prop, value) { + _this[prop] = value; + if (_this._isGlobal) { + window[prop] = value; + } + }; + /** + * Removes the sketch from the web page. + * + * Calling `remove()` stops the draw loop and removes any HTML elements + * created by the sketch, including the canvas. A new sketch can be + * created by using the p5() constructor, as in + * `new p5()`. + * + * @method remove + * + * @example + *
        + * + * // Double-click to remove the canvas. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A white circle on a gray background. The circle follows the mouse as the user moves. The sketch disappears when the user double-clicks.' + * ); + * } + * + * function draw() { + * // Paint the background repeatedly. + * background(200); + * + * // Draw circles repeatedly. + * circle(mouseX, mouseY, 40); + * } + * + * // Remove the sketch when the user double-clicks. + * function doubleClicked() { + * remove(); + * } + * + *
        + */ + this.remove = function () { + // Remove start listener to prevent orphan canvas being created + if (_this._startListener) { + window.removeEventListener('load', _this._startListener, false); + } + var loadingScreen = document.getElementById(_this._loadingScreenId); + if (loadingScreen) { + loadingScreen.parentNode.removeChild(loadingScreen); + // Add 1 to preload counter to prevent the sketch ever executing setup() + _this._incrementPreload(); + } + if (_this._curElement) { + // stop draw + _this._loop = false; + if (_this._requestAnimId) { + window.cancelAnimationFrame(_this._requestAnimId); + } // unregister events sketch-wide + + for (var ev in _this._events) { + window.removeEventListener(ev, _this._events[ev]); + } // remove DOM elements created by p5, and listeners + + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + try { + for (var _iterator4 = _this._elements[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var e = _step4.value; + if (e.elt && e.elt.parentNode) { + e.elt.parentNode.removeChild(e.elt); + } + for (var elt_ev in e._events) { + e.elt.removeEventListener(elt_ev, e._events[elt_ev]); + } + } // call any registered remove functions + + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + var self = _this; + _this._registeredMethods.remove.forEach(function (f) { + if (typeof f !== 'undefined') { + f.call(self); + } + }); + } // remove window bound properties and methods + + if (_this._isGlobal) { + for (var p in p5.prototype) { + try { + delete window[p]; + } catch (x) { + window[p] = undefined; + } + } + for (var p2 in _this) { + if (_this.hasOwnProperty(p2)) { + try { + delete window[p2]; + } catch (x) { + window[p2] = undefined; + } + } + } + p5.instance = null; + } + }; + // call any registered init functions + this._registeredMethods.init.forEach(function (f) { + if (typeof f !== 'undefined') { + f.call(this); + } + }, this); + // Set up promise preloads + this._setupPromisePreloads(); + var friendlyBindGlobal = this._createFriendlyGlobalFunctionBinder(); + // If the user has created a global setup or draw function, + // assume "global" mode and make everything global (i.e. on the window) + if (!sketch) { + this._isGlobal = true; + p5.instance = this; + // Loop through methods on the prototype and attach them to the window + for (var p in p5.prototype) { + if (typeof p5.prototype[p] === 'function') { + var ev = p.substring(2); + if (!this._events.hasOwnProperty(ev)) { + if (Math.hasOwnProperty(p) && Math[p] === p5.prototype[p]) { + // Multiple p5 methods are just native Math functions. These can be + // called without any binding. + friendlyBindGlobal(p, p5.prototype[p]); + } else { + friendlyBindGlobal(p, p5.prototype[p].bind(this)); + } + } + } else { + friendlyBindGlobal(p, p5.prototype[p]); + } + } // Attach its properties to the window + + for (var p2 in this) { + if (this.hasOwnProperty(p2)) { + friendlyBindGlobal(p2, this[p2]); + } + } + } else { + // Else, the user has passed in a sketch closure that may set + // user-provided 'setup', 'draw', etc. properties on this instance of p5 + sketch(this); + // Run a check to see if the user has misspelled 'setup', 'draw', etc + // detects capitalization mistakes only ( Setup, SETUP, MouseClicked, etc) + p5._checkForUserDefinedFunctions(this); + } // Bind events to window (not using container div bc key events don't work) + + for (var e in this._events) { + var f = this['_on'.concat(e)]; + if (f) { + var m = f.bind(this); + window.addEventListener(e, m, { + passive: false + }); + this._events[e] = m; + } + } + var focusHandler = function focusHandler() { + _this._setProperty('focused', true); + }; + var blurHandler = function blurHandler() { + _this._setProperty('focused', false); + }; + window.addEventListener('focus', focusHandler); + window.addEventListener('blur', blurHandler); + this.registerMethod('remove', function () { + window.removeEventListener('focus', focusHandler); + window.removeEventListener('blur', blurHandler); + }); + if (document.readyState === 'complete') { + this._start(); + } else { + this._startListener = this._start.bind(this); + window.addEventListener('load', this._startListener, false); + } + } + _createClass(p5, [ + { + key: '_initializeInstanceVariables', + value: function _initializeInstanceVariables() { + this._accessibleOutputs = { + text: false, + grid: false, + textLabel: false, + gridLabel: false + }; + this._styles = [ + ]; + this._bezierDetail = 20; + this._curveDetail = 20; + this._colorMode = constants.RGB; + this._colorMaxes = { + rgb: [ + 255, + 255, + 255, + 255 + ], + hsb: [ + 360, + 100, + 100, + 1 + ], + hsl: [ + 360, + 100, + 100, + 1 + ] + }; + this._downKeys = { + }; //Holds the key codes of currently pressed keys + } + }, + { + key: 'registerPreloadMethod', + value: function registerPreloadMethod(fnString, obj) { + // obj = obj || p5.prototype; + if (!p5.prototype._preloadMethods.hasOwnProperty(fnString)) { + p5.prototype._preloadMethods[fnString] = obj; + } + } + }, + { + key: 'registerMethod', + value: function registerMethod(name, m) { + var target = this || p5.prototype; + if (!target._registeredMethods.hasOwnProperty(name)) { + target._registeredMethods[name] = [ + ]; + } + target._registeredMethods[name].push(m); + } + }, + { + key: 'unregisterMethod', + value: function unregisterMethod(name, m) { + var target = this || p5.prototype; + if (target._registeredMethods.hasOwnProperty(name)) { + var methods = target._registeredMethods[name]; + var indexesToRemove = [ + ]; + // Find all indexes of the method `m` in the array of registered methods + for (var i = 0; i < methods.length; i++) { + if (methods[i] === m) { + indexesToRemove.push(i); + } + } // Remove all instances of the method `m` from the array + + for (var _i = indexesToRemove.length - 1; _i >= 0; _i--) { + methods.splice(indexesToRemove[_i], 1); + } + } + } // create a function which provides a standardized process for binding + // globals; this is implemented as a factory primarily so that there's a + // way to redefine what "global" means for the binding function so it + // can be used in scenarios like unit testing where the window object + // might not exist + + }, + { + key: '_createFriendlyGlobalFunctionBinder', + value: function _createFriendlyGlobalFunctionBinder() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + var globalObject = options.globalObject || window; + var log = options.log || console.log.bind(console); + var propsToForciblyOverwrite = { + // p5.print actually always overwrites an existing global function, + // albeit one that is very unlikely to be used: + // + // https://developer.mozilla.org/en-US/docs/Web/API/Window/print + print: true + }; + return function (prop, value) { + if (!p5.disableFriendlyErrors && typeof IS_MINIFIED === 'undefined' && typeof value === 'function' && !(prop in p5.prototype._preloadMethods)) { + try { + // Because p5 has so many common function names, it's likely + // that users may accidentally overwrite global p5 functions with + // their own variables. Let's allow this but log a warning to + // help users who may be doing this unintentionally. + // + // For more information, see: + // + // https://github.com/processing/p5.js/issues/1317 + if (prop in globalObject && !(prop in propsToForciblyOverwrite)) { + throw new Error('global "'.concat(prop, '" already exists')); + } // It's possible that this might throw an error because there + // are a lot of edge-cases in which `Object.defineProperty` might + // not succeed; since this functionality is only intended to + // help beginners anyways, we'll just catch such an exception + // if it occurs, and fall back to legacy behavior. + + Object.defineProperty(globalObject, prop, { + configurable: true, + enumerable: true, + get: function get() { + return value; + }, + set: function set(newValue) { + Object.defineProperty(globalObject, prop, { + configurable: true, + enumerable: true, + value: newValue, + writable: true + }); + log('You just changed the value of "'.concat(prop, '", which was a p5 function. This could cause problems later if you\'re not careful.')); + } + }); + } catch (e) { + var message = 'p5 had problems creating the global function "'.concat(prop, '", possibly because your code is already using that name as a variable. You may want to rename your variable to something else.'); + p5._friendlyError(message, prop); + globalObject[prop] = value; + } + } else { + globalObject[prop] = value; + } + }; + } + } + ]); + return p5; + }(); // This is a pointer to our global mode p5 instance, if we're in + // global mode. + p5.instance = null; + /** + * Turns off the parts of the Friendly Error System (FES) that impact performance. + * + * The FES + * can cause sketches to draw slowly because it does extra work behind the + * scenes. For example, the FES checks the arguments passed to functions, + * which takes time to process. Disabling the FES can significantly improve + * performance by turning off these checks. + * + * @property {Boolean} disableFriendlyErrors + * + * @example + *
        + * + * // Disable the FES. + * p5.disableFriendlyErrors = true; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // The circle() function requires three arguments. The + * // next line would normally display a friendly error that + * // points this out. Instead, nothing happens and it fails + * // silently. + * circle(50, 50); + * + * describe('A gray square.'); + * } + * + *
        + */ + p5.disableFriendlyErrors = false; + // attach constants to p5 prototype + for (var k in constants) { + p5.prototype[k] = constants[k]; + } // makes the `VERSION` constant available on the p5 object + // in instance mode, even if it hasn't been instantiated yet + + p5.VERSION = constants.VERSION; + // functions that cause preload to wait + // more can be added by using registerPreloadMethod(func) + p5.prototype._preloadMethods = { + loadJSON: p5.prototype, + loadImage: p5.prototype, + loadStrings: p5.prototype, + loadXML: p5.prototype, + loadBytes: p5.prototype, + loadTable: p5.prototype, + loadFont: p5.prototype, + loadModel: p5.prototype, + loadShader: p5.prototype + }; + p5.prototype._registeredMethods = { + init: [ + ], + pre: [ + ], + post: [ + ], + remove: [ + ] + }; + p5.prototype._registeredPreloadMethods = { + }; + var _default = p5; + exports.default = _default; + }, + { + './constants': 291, + './shim': 314, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.splice': 188, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.get-own-property-names': 202, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.for-each': 260, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 304: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('./main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * @module DOM + * @submodule DOM + * @for p5.Element + */ + /** + * A class to describe an + * HTML element. + * + * Sketches can use many elements. Common elements include the drawing canvas, + * buttons, sliders, webcam feeds, and so on. + * + * All elements share the methods of the `p5.Element` class. They're created + * with functions such as createCanvas() and + * createButton(). + * + * @class p5.Element + * @constructor + * @param {HTMLElement} elt wrapped DOM element. + * @param {p5} [pInst] pointer to p5 instance. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a button element and + * // place it beneath the canvas. + * let btn = createButton('change'); + * btn.position(0, 100); + * + * // Call randomColor() when + * // the button is pressed. + * btn.mousePressed(randomColor); + * + * describe('A gray square with a button that says "change" beneath it. The square changes color when the user presses the button.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + _main.default.Element = /*#__PURE__*/ function () { + function _class(elt, pInst) { + _classCallCheck(this, _class); + /** + * The element's underlying `HTMLElement` object. + * + * The + * HTMLElement + * object's properties and methods can be used directly. + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Set the border style for the + * // canvas. + * cnv.elt.style.border = '5px dashed deeppink'; + * + * describe('A gray square with a pink border drawn with dashed lines.'); + * } + * + *
        + * + * @property elt + * @name elt + * @readOnly + */ + this.elt = elt; + /** + * @private + * @type {p5.Element} + * @name _pInst + */ + this._pInst = this._pixelsState = pInst; + this._events = { + }; + /** + * A `Number` property that stores the element's width. + * + * @type {Number} + * @property width + * @name width + */ + this.width = this.elt.offsetWidth; + /** + * A `Number` property that stores the element's height. + * + * @type {Number} + * @property height + * @name height + */ + this.height = this.elt.offsetHeight; + } /** + * Attaches the element to a parent element. + * + * For example, a `<div></div>` element may be used as a box to + * hold two pieces of text, a header and a paragraph. The + * `<div></div>` is the parent element of both the header and + * paragraph. + * + * The parameter `parent` can have one of three types. `parent` can be a + * string with the parent element's ID, as in + * `myElement.parent('container')`. It can also be another + * p5.Element object, as in + * `myElement.parent(myDiv)`. Finally, `parent` can be an `HTMLElement` + * object, as in `myElement.parent(anotherElement)`. + * + * Calling `myElement.parent()` without an argument returns the element's + * parent. + * + * @method parent + * @param {String|p5.Element|Object} parent ID, p5.Element, + * or HTMLElement of desired parent element. + * @chainable + * + * @example + *
        + * + * function setup() { + * background(200); + * + * // Create a div element. + * let div = createDiv(); + * + * // Place the div in the top-left corner. + * div.position(10, 20); + * + * // Set its width and height. + * div.size(80, 60); + * + * // Set its background color to white + * div.style('background-color', 'white'); + * + * // Align any text to the center. + * div.style('text-align', 'center'); + * + * // Set its ID to "container". + * div.id('container'); + * + * // Create a paragraph element. + * let p = createP('p5*js'); + * + * // Make the div its parent + * // using its ID "container". + * p.parent('container'); + * + * describe('The text "p5*js" written in black at the center of a white rectangle. The rectangle is inside a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background(200); + * + * // Create rectangular div element. + * let div = createDiv(); + * + * // Place the div in the top-left corner. + * div.position(10, 20); + * + * // Set its width and height. + * div.size(80, 60); + * + * // Set its background color and align + * // any text to the center. + * div.style('background-color', 'white'); + * div.style('text-align', 'center'); + * + * // Create a paragraph element. + * let p = createP('p5*js'); + * + * // Make the div its parent. + * p.parent(div); + * + * describe('The text "p5*js" written in black at the center of a white rectangle. The rectangle is inside a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background(200); + * + * // Create rectangular div element. + * let div = createDiv(); + * + * // Place the div in the top-left corner. + * div.position(10, 20); + * + * // Set its width and height. + * div.size(80, 60); + * + * // Set its background color and align + * // any text to the center. + * div.style('background-color', 'white'); + * div.style('text-align', 'center'); + * + * // Create a paragraph element. + * let p = createP('p5*js'); + * + * // Make the div its parent + * // using the underlying + * // HTMLElement. + * p.parent(div.elt); + * + * describe('The text "p5*js" written in black at the center of a white rectangle. The rectangle is inside a gray square.'); + * } + * + *
        + */ + /** + * @method parent + * @return {p5.Element} + */ + + _createClass(_class, [ + { + key: 'parent', + value: function parent(p) { + if (typeof p === 'undefined') { + return this.elt.parentNode; + } + if (typeof p === 'string') { + if (p[0] === '#') { + p = p.substring(1); + } + p = document.getElementById(p); + } else if (p instanceof _main.default.Element) { + p = p.elt; + } + p.appendChild(this.elt); + return this; + } /** + * Sets the element's ID using a given string. + * + * Calling `myElement.id()` without an argument returns its ID as a string. + * + * @method id + * @param {String} id ID of the element. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Set the canvas' ID + * // to "mycanvas". + * cnv.id('mycanvas'); + * + * // Get the canvas' ID. + * let id = cnv.id(); + * text(id, 24, 54); + * + * describe('The text "mycanvas" written in black on a gray background.'); + * } + * + *
        + */ + /** + * @method id + * @return {String} ID of the element. + */ + + }, + { + key: 'id', + value: function id(_id) { + if (typeof _id === 'undefined') { + return this.elt.id; + } + this.elt.id = _id; + this.width = this.elt.offsetWidth; + this.height = this.elt.offsetHeight; + return this; + } /** + * Adds a + * class attribute + * to the element using a given string. + * + * Calling `myElement.class()` without an argument returns a string with its current classes. + * + * @method class + * @param {String} class class to add. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Add the class "small" to the + * // canvas element. + * cnv.class('small'); + * + * // Get the canvas element's class + * // and display it. + * let c = cnv.class(); + * text(c, 35, 54); + * + * describe('The word "small" written in black on a gray canvas.'); + * + * } + * + *
        + */ + /** + * @method class + * @return {String} element's classes, if any. + */ + + }, + { + key: 'class', + value: function _class(c) { + if (typeof c === 'undefined') { + return this.elt.className; + } + this.elt.className = c; + return this; + } /** + * Calls a function when the mouse is pressed over the element. + * + * Calling `myElement.mousePressed(false)` disables the function. + * + * Note: Some mobile browsers may also trigger this event when the element + * receives a quick tap. + * + * @method mousePressed + * @param {Function|Boolean} fxn function to call when the mouse is + * pressed over the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the canvas + * // is pressed. + * cnv.mousePressed(randomColor); + * + * describe('A gray square changes color when the mouse is pressed.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'mousePressed', + value: function mousePressed(fxn) { + // Prepend the mouse property setters to the event-listener. + // This is required so that mouseButton is set correctly prior to calling the callback (fxn). + // For details, see https://github.com/processing/p5.js/issues/3087. + var eventPrependedFxn = function eventPrependedFxn(event) { + this._pInst._setProperty('mouseIsPressed', true); + this._pInst._setMouseButton(event); + // Pass along the return-value of the callback: + return fxn.call(this, event); + }; + // Pass along the event-prepended form of the callback. + _main.default.Element._adjustListener('mousedown', eventPrependedFxn, this); + return this; + } /** + * Calls a function when the mouse is pressed twice over the element. + * + * Calling `myElement.doubleClicked(false)` disables the function. + * + * @method doubleClicked + * @param {Function|Boolean} fxn function to call when the mouse is + * double clicked over the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // canvas is double-clicked. + * cnv.doubleClicked(randomColor); + * + * describe('A gray square changes color when the user double-clicks the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'doubleClicked', + value: function doubleClicked(fxn) { + _main.default.Element._adjustListener('dblclick', fxn, this); + return this; + } /** + * Calls a function when the mouse wheel scrolls over the element. + * + * The callback function, `fxn`, is passed an `event` object. `event` has + * two numeric properties, `deltaY` and `deltaX`. `event.deltaY` is + * negative if the mouse wheel rotates away from the user. It's positive if + * the mouse wheel rotates toward the user. `event.deltaX` is positive if + * the mouse wheel moves to the right. It's negative if the mouse wheel moves + * to the left. + * + * Calling `myElement.mouseWheel(false)` disables the function. + * + * @method mouseWheel + * @param {Function|Boolean} fxn function to call when the mouse wheel is + * scrolled over the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // mouse wheel moves. + * cnv.mouseWheel(randomColor); + * + * describe('A gray square changes color when the user scrolls the mouse wheel over the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call changeBackground() when the + * // mouse wheel moves. + * cnv.mouseWheel(changeBackground); + * + * describe('A gray square. When the mouse wheel scrolls over the square, it changes color and displays shapes.'); + * } + * + * function changeBackground(event) { + * // Change the background color + * // based on deltaY. + * if (event.deltaY > 0) { + * background('deeppink'); + * } else if (event.deltaY < 0) { + * background('cornflowerblue'); + * } else { + * background(200); + * } + * + * // Draw a shape based on deltaX. + * if (event.deltaX > 0) { + * circle(50, 50, 20); + * } else if (event.deltaX < 0) { + * square(40, 40, 20); + * } + * } + * + *
        + */ + + }, + { + key: 'mouseWheel', + value: function mouseWheel(fxn) { + _main.default.Element._adjustListener('wheel', fxn, this); + return this; + } /** + * Calls a function when the mouse is released over the element. + * + * Calling `myElement.mouseReleased(false)` disables the function. + * + * Note: Some mobile browsers may also trigger this event when the element + * receives a quick tap. + * + * @method mouseReleased + * @param {Function|Boolean} fxn function to call when the mouse is + * pressed over the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when a + * // mouse press ends. + * cnv.mouseReleased(randomColor); + * + * describe('A gray square changes color when the user releases a mouse press.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'mouseReleased', + value: function mouseReleased(fxn) { + _main.default.Element._adjustListener('mouseup', fxn, this); + return this; + } /** + * Calls a function when the mouse is pressed and released over the element. + * + * Calling `myElement.mouseReleased(false)` disables the function. + * + * Note: Some mobile browsers may also trigger this event when the element + * receives a quick tap. + * + * @method mouseClicked + * @param {Function|Boolean} fxn function to call when the mouse is + * pressed and released over the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when a + * // mouse press ends. + * cnv.mouseClicked(randomColor); + * + * describe('A gray square changes color when the user releases a mouse press.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'mouseClicked', + value: function mouseClicked(fxn) { + _main.default.Element._adjustListener('click', fxn, this); + return this; + } /** + * Calls a function when the mouse moves over the element. + * + * Calling `myElement.mouseMoved(false)` disables the function. + * + * @method mouseMoved + * @param {Function|Boolean} fxn function to call when the mouse + * moves over the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // mouse moves. + * cnv.mouseMoved(randomColor); + * + * describe('A gray square changes color when the mouse moves over the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'mouseMoved', + value: function mouseMoved(fxn) { + _main.default.Element._adjustListener('mousemove', fxn, this); + return this; + } /** + * Calls a function when the mouse moves onto the element. + * + * Calling `myElement.mouseOver(false)` disables the function. + * + * @method mouseOver + * @param {Function|Boolean} fxn function to call when the mouse + * moves onto the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // mouse moves onto the canvas. + * cnv.mouseOver(randomColor); + * + * describe('A gray square changes color when the mouse moves onto the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'mouseOver', + value: function mouseOver(fxn) { + _main.default.Element._adjustListener('mouseover', fxn, this); + return this; + } /** + * Calls a function when the mouse moves off the element. + * + * Calling `myElement.mouseOut(false)` disables the function. + * + * @method mouseOut + * @param {Function|Boolean} fxn function to call when the mouse + * moves off the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // mouse moves off the canvas. + * cnv.mouseOut(randomColor); + * + * describe('A gray square changes color when the mouse moves off the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'mouseOut', + value: function mouseOut(fxn) { + _main.default.Element._adjustListener('mouseout', fxn, this); + return this; + } /** + * Calls a function when the element is touched. + * + * Calling `myElement.touchStarted(false)` disables the function. + * + * Note: Touch functions only work on mobile devices. + * + * @method touchStarted + * @param {Function|Boolean} fxn function to call when the touch + * starts. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // user touches the canvas. + * cnv.touchStarted(randomColor); + * + * describe('A gray square changes color when the user touches the canvas.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'touchStarted', + value: function touchStarted(fxn) { + _main.default.Element._adjustListener('touchstart', fxn, this); + return this; + } /** + * Calls a function when the user touches the element and moves. + * + * Calling `myElement.touchMoved(false)` disables the function. + * + * Note: Touch functions only work on mobile devices. + * + * @method touchMoved + * @param {Function|Boolean} fxn function to call when the touch + * moves over the element. + * `false` disables the function. + * @chainable + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // user touches the canvas + * // and moves. + * cnv.touchMoved(randomColor); + * + * describe('A gray square changes color when the user touches the canvas and moves.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'touchMoved', + value: function touchMoved(fxn) { + _main.default.Element._adjustListener('touchmove', fxn, this); + return this; + } /** + * Calls a function when the user stops touching the element. + * + * Calling `myElement.touchMoved(false)` disables the function. + * + * Note: Touch functions only work on mobile devices. + * + * @method touchEnded + * @param {Function|Boolean} fxn function to call when the touch + * ends. + * `false` disables the function. + * @chainable + * @example + *
        + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call randomColor() when the + * // user touches the canvas, + * // then lifts their finger. + * cnv.touchEnded(randomColor); + * + * describe('A gray square changes color when the user touches the canvas, then lifts their finger.'); + * } + * + * // Paint the background either + * // red, yellow, blue, or green. + * function randomColor() { + * let c = random(['red', 'yellow', 'blue', 'green']); + * background(c); + * } + * + *
        + */ + + }, + { + key: 'touchEnded', + value: function touchEnded(fxn) { + _main.default.Element._adjustListener('touchend', fxn, this); + return this; + } /** + * Calls a function when a file is dragged over the element. + * + * Calling `myElement.dragOver(false)` disables the function. + * + * @method dragOver + * @param {Function|Boolean} fxn function to call when the file is + * dragged over the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * // Drag a file over the canvas to test. + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call helloFile() when a + * // file is dragged over + * // the canvas. + * cnv.dragOver(helloFile); + * + * describe('A gray square. The text "hello, file" appears when a file is dragged over the square.'); + * } + * + * function helloFile() { + * text('hello, file', 50, 50); + * } + * + *
        + */ + + }, + { + key: 'dragOver', + value: function dragOver(fxn) { + _main.default.Element._adjustListener('dragover', fxn, this); + return this; + } /** + * Calls a function when a file is dragged off the element. + * + * Calling `myElement.dragLeave(false)` disables the function. + * + * @method dragLeave + * @param {Function|Boolean} fxn function to call when the file is + * dragged off the element. + * `false` disables the function. + * @chainable + * @example + *
        + * + * // Drag a file over, then off + * // the canvas to test. + * + * function setup() { + * // Create a canvas element and + * // assign it to cnv. + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Call byeFile() when a + * // file is dragged over, + * // then off the canvas. + * cnv.dragLeave(byeFile); + * + * describe('A gray square. The text "bye, file" appears when a file is dragged over, then off the square.'); + * } + * + * function byeFile() { + * text('bye, file', 50, 50); + * } + * + *
        + */ + + }, + { + key: 'dragLeave', + value: function dragLeave(fxn) { + _main.default.Element._adjustListener('dragleave', fxn, this); + return this; + } /** + * + * @private + * @static + * @param {String} ev + * @param {Boolean|Function} fxn + * @param {Element} ctx + * @chainable + * @alt + * General handler for event attaching and detaching + */ + + }, + { + key: '_setProperty', + /** + * Helper fxn for sharing pixel methods + */ + value: function _setProperty(prop, value) { + this[prop] = value; + } + } + ], [ + { + key: '_adjustListener', + value: function _adjustListener(ev, fxn, ctx) { + if (fxn === false) { + _main.default.Element._detachListener(ev, ctx); + } else { + _main.default.Element._attachListener(ev, fxn, ctx); + } + return this; + } /** + * + * @private + * @static + * @param {String} ev + * @param {Function} fxn + * @param {Element} ctx + */ + + }, + { + key: '_attachListener', + value: function _attachListener(ev, fxn, ctx) { + // detach the old listener if there was one + if (ctx._events[ev]) { + _main.default.Element._detachListener(ev, ctx); + } + var f = fxn.bind(ctx); + ctx.elt.addEventListener(ev, f, false); + ctx._events[ev] = f; + } /** + * + * @private + * @static + * @param {String} ev + * @param {Element} ctx + */ + + }, + { + key: '_detachListener', + value: function _detachListener(ev, ctx) { + var f = ctx._events[ev]; + ctx.elt.removeEventListener(ev, f, false); + ctx._events[ev] = null; + } + } + ]); + return _class; + }(); + var _default = _main.default.Element; + exports.default = _default; + }, + { + './main': 303 + } + ], + 305: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('./main')); + var constants = _interopRequireWildcard(_dereq_('./constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } + 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 _createSuper(Derived) { + function 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; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_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); + } /** + * @module Rendering + * @submodule Rendering + * @for p5 + */ + /** + * A class to describe a drawing surface that's separate from the main canvas. + * + * Each `p5.Graphics` object provides a dedicated drawing surface called a + * *graphics buffer*. Graphics buffers are helpful when drawing should happen + * offscreen. For example, separate scenes can be drawn offscreen and + * displayed only when needed. + * + * `p5.Graphics` objects have nearly all the drawing features of the main + * canvas. For example, calling the method `myGraphics.circle(50, 50, 20)` + * draws to the graphics buffer. The resulting image can be displayed on the + * main canvas by passing the `p5.Graphics` object to the + * image() function, as in `image(myGraphics, 0, 0)`. + * + * Note: createGraphics() is the recommended + * way to create an instance of this class. + * + * @class p5.Graphics + * @constructor + * @extends p5.Element + * @param {Number} width width of the graphics buffer in pixels. + * @param {Number} height height of the graphics buffer in pixels. + * @param {Constant} renderer renderer to use, either P2D or WEBGL. + * @param {p5} [pInst] sketch instance. + * @param {HTMLCanvasElement} [canvas] existing `<canvas>` element to use. + * + * @example + *
        + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Graphics object. + * pg = createGraphics(50, 50); + * + * // Draw to the p5.Graphics object. + * pg.background(100); + * pg.circle(25, 25, 20); + * + * describe('A dark gray square with a white circle at its center drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Display the p5.Graphics object. + * image(pg, 25, 25); + * } + * + *
        + * + *
        + * + * // Click the canvas to display the graphics buffer. + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Graphics object. + * pg = createGraphics(50, 50); + * + * describe('A square appears on a gray background when the user presses the mouse. The square cycles between white and black.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the background color. + * let bg = frameCount % 255; + * + * // Draw to the p5.Graphics object. + * pg.background(bg); + * + * // Display the p5.Graphics object while + * // the user presses the mouse. + * if (mouseIsPressed === true) { + * image(pg, 25, 25); + * } + * } + * + *
        + */ + + _main.default.Graphics = /*#__PURE__*/ function (_p5$Element) { + _inherits(_class, _p5$Element); + var _super = _createSuper(_class); + function _class(w, h, renderer, pInst, canvas) { + var _this; + _classCallCheck(this, _class); + var canvasTemp; + if (canvas) { + canvasTemp = canvas; + } else { + canvasTemp = document.createElement('canvas'); + } + _this = _super.call(this, canvasTemp, pInst); + _this.canvas = canvasTemp; + var r = renderer || constants.P2D; + var node = pInst._userNode || document.body; + if (!canvas) { + node.appendChild(_this.canvas); + } // bind methods and props of p5 to the new object + + for (var p in _main.default.prototype) { + if (!_this[p]) { + if (typeof _main.default.prototype[p] === 'function') { + _this[p] = _main.default.prototype[p].bind(_assertThisInitialized(_this)); + } else { + _this[p] = _main.default.prototype[p]; + } + } + } + _main.default.prototype._initializeInstanceVariables.apply(_assertThisInitialized(_this)); + _this.width = w; + _this.height = h; + _this._pixelDensity = pInst._pixelDensity; + if (r === constants.WEBGL) { + _this._renderer = new _main.default.RendererGL(_this.canvas, _assertThisInitialized(_this), false); + var _this$_renderer$_adju = _this._renderer._adjustDimensions(w, h), + adjustedWidth = _this$_renderer$_adju.adjustedWidth, + adjustedHeight = _this$_renderer$_adju.adjustedHeight; + w = adjustedWidth; + h = adjustedHeight; + } else { + _this._renderer = new _main.default.Renderer2D(_this.canvas, _assertThisInitialized(_this), false); + } + pInst._elements.push(_assertThisInitialized(_this)); + Object.defineProperty(_assertThisInitialized(_this), 'deltaTime', { + get: function get() { + return this._pInst.deltaTime; + } + }); + _this._renderer.resize(w, h); + _this._renderer._applyDefaults(); + return _possibleConstructorReturn(_this, _assertThisInitialized(_this)); + } /** + * Resets the graphics buffer's transformations and lighting. + * + * By default, the main canvas resets certain transformation and lighting + * values each time draw() executes. `p5.Graphics` + * objects must reset these values manually by calling `myGraphics.reset()`. + * + * @method reset + * + * @example + *
        + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Graphics object. + * pg = createGraphics(60, 60); + * + * describe('A white circle moves downward slowly within a dark square. The circle resets at the top of the dark square when the user presses the mouse.'); + * } + * + * function draw() { + * background(200); + * + * // Translate the p5.Graphics object's coordinate system. + * // The translation accumulates; the white circle moves. + * pg.translate(0, 0.1); + * + * // Draw to the p5.Graphics object. + * pg.background(100); + * pg.circle(30, 0, 10); + * + * // Display the p5.Graphics object. + * image(pg, 20, 20); + * + * // Translate the main canvas' coordinate system. + * // The translation doesn't accumulate; the dark + * // square is always in the same place. + * translate(0, 0.1); + * + * // Reset the p5.Graphics object when the + * // user presses the mouse. + * if (mouseIsPressed === true) { + * pg.reset(); + * } + * } + * + *
        + * + *
        + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Graphics object. + * pg = createGraphics(60, 60); + * + * describe('A white circle at the center of a dark gray square. The image is drawn on a light gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Translate the p5.Graphics object's coordinate system. + * pg.translate(30, 30); + * + * // Draw to the p5.Graphics object. + * pg.background(100); + * pg.circle(0, 0, 10); + * + * // Display the p5.Graphics object. + * image(pg, 20, 20); + * + * // Reset the p5.Graphics object automatically. + * pg.reset(); + * } + * + *
        + * + *
        + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Graphics object using WebGL mode. + * pg = createGraphics(100, 100, WEBGL); + * + * describe("A sphere lit from above with a red light. The sphere's surface becomes glossy while the user clicks and holds the mouse."); + * } + * + * function draw() { + * background(200); + * + * // Add a red point light from the top-right. + * pg.pointLight(255, 0, 0, 50, -100, 50); + * + * // Style the sphere. + * // It should appear glossy when the + * // lighting values are reset. + * pg.noStroke(); + * pg.specularMaterial(255); + * pg.shininess(100); + * + * // Draw the sphere. + * pg.sphere(30); + * + * // Display the p5.Graphics object. + * image(pg, -50, -50); + * + * // Reset the p5.Graphics object when + * // the user presses the mouse. + * if (mouseIsPressed === true) { + * pg.reset(); + * } + * } + * + *
        + * + *
        + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Graphics object using WebGL mode. + * pg = createGraphics(100, 100, WEBGL); + * + * describe('A sphere with a glossy surface is lit from the top-right by a red light.'); + * } + * + * function draw() { + * background(200); + * + * // Add a red point light from the top-right. + * pg.pointLight(255, 0, 0, 50, -100, 50); + * + * // Style the sphere. + * pg.noStroke(); + * pg.specularMaterial(255); + * pg.shininess(100); + * + * // Draw the sphere. + * pg.sphere(30); + * + * // Display the p5.Graphics object. + * image(pg, 0, 0); + * + * // Reset the p5.Graphics object automatically. + * pg.reset(); + * } + * + *
        + */ + + _createClass(_class, [ + { + key: 'reset', + value: function reset() { + this._renderer.resetMatrix(); + if (this._renderer.isP3D) { + this._renderer._update(); + } + } /** + * Removes the graphics buffer from the web page. + * + * Calling `myGraphics.remove()` removes the graphics buffer's + * `<canvas>` element from the web page. The graphics buffer also uses + * a bit of memory on the CPU that can be freed like so: + * + * ```js + * // Remove the graphics buffer from the web page. + * myGraphics.remove(); + * + * // Delete the graphics buffer from CPU memory. + * myGraphics = undefined; + * ``` + * + * Note: All variables that reference the graphics buffer must be assigned + * the value `undefined` to delete the graphics buffer from CPU memory. If any + * variable still refers to the graphics buffer, then it won't be garbage + * collected. + * + * @method remove + * + * @example + *
        + * + * // Double-click to remove the p5.Graphics object. + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Graphics object. + * pg = createGraphics(60, 60); + * + * // Draw to the p5.Graphics object. + * pg.background(100); + * pg.circle(30, 30, 20); + * + * describe('A white circle at the center of a dark gray square disappears when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Display the p5.Graphics object if + * // it's available. + * if (pg) { + * image(pg, 20, 20); + * } + * } + * + * // Remove the p5.Graphics object when the + * // the user double-clicks. + * function doubleClicked() { + * // Remove the p5.Graphics object from the web page. + * pg.remove(); + * + * // Delete the p5.Graphics object from CPU memory. + * pg = undefined; + * } + * + *
        + */ + + }, + { + key: 'remove', + value: function remove() { + if (this.elt.parentNode) { + this.elt.parentNode.removeChild(this.elt); + } + var idx = this._pInst._elements.indexOf(this); + if (idx !== - 1) { + this._pInst._elements.splice(idx, 1); + } + for (var elt_ev in this._events) { + this.elt.removeEventListener(elt_ev, this._events[elt_ev]); + } + } /** + * Creates a new p5.Framebuffer object with + * the same WebGL context as the graphics buffer. + * + * p5.Framebuffer objects are separate drawing + * surfaces that can be used as textures in WebGL mode. They're similar to + * p5.Graphics objects and generally run much + * faster when used as textures. Creating a + * p5.Framebuffer object in the same context + * as the graphics buffer makes this speedup possible. + * + * The parameter, `options`, is optional. An object can be passed to configure + * the p5.Framebuffer object. The available + * properties are: + * + * - `format`: data format of the texture, either `UNSIGNED_BYTE`, `FLOAT`, or `HALF_FLOAT`. Default is `UNSIGNED_BYTE`. + * - `channels`: whether to store `RGB` or `RGBA` color channels. Default is to match the graphics buffer which is `RGBA`. + * - `depth`: whether to include a depth buffer. Default is `true`. + * - `depthFormat`: data format of depth information, either `UNSIGNED_INT` or `FLOAT`. Default is `FLOAT`. + * - `stencil`: whether to include a stencil buffer for masking. `depth` must be `true` for this feature to work. Defaults to the value of `depth` which is `true`. + * - `antialias`: whether to perform anti-aliasing. If set to `true`, as in `{ antialias: true }`, 2 samples will be used by default. The number of samples can also be set, as in `{ antialias: 4 }`. Default is to match setAttributes() which is `false` (`true` in Safari). + * - `width`: width of the p5.Framebuffer object. Default is to always match the graphics buffer width. + * - `height`: height of the p5.Framebuffer object. Default is to always match the graphics buffer height. + * - `density`: pixel density of the p5.Framebuffer object. Default is to always match the graphics buffer pixel density. + * - `textureFiltering`: how to read values from the p5.Framebuffer object. Either `LINEAR` (nearby pixels will be interpolated) or `NEAREST` (no interpolation). Generally, use `LINEAR` when using the texture as an image and `NEAREST` if reading the texture as data. Default is `LINEAR`. + * + * If the `width`, `height`, or `density` attributes are set, they won't + * automatically match the graphics buffer and must be changed manually. + * + * @method createFramebuffer + * @param {Object} [options] configuration options. + * @return {p5.Framebuffer} new framebuffer. + * + * @example + *
        + * + * // Click and hold a mouse button to change shapes. + * + * let pg; + * let torusLayer; + * let boxLayer; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Graphics object using WebGL mode. + * pg = createGraphics(100, 100, WEBGL); + * + * // Create the p5.Framebuffer objects. + * torusLayer = pg.createFramebuffer(); + * boxLayer = pg.createFramebuffer(); + * + * describe('A grid of white toruses rotating against a dark gray background. The shapes become boxes while the user holds a mouse button.'); + * } + * + * function draw() { + * // Update and draw the layers offscreen. + * drawTorus(); + * drawBox(); + * + * // Choose the layer to display. + * let layer; + * if (mouseIsPressed === true) { + * layer = boxLayer; + * } else { + * layer = torusLayer; + * } + * + * // Draw to the p5.Graphics object. + * pg.background(50); + * + * // Iterate from left to right. + * for (let x = -50; x < 50; x += 25) { + * // Iterate from top to bottom. + * for (let y = -50; y < 50; y += 25) { + * // Draw the layer to the p5.Graphics object + * pg.image(layer, x, y, 25, 25); + * } + * } + * + * // Display the p5.Graphics object. + * image(pg, 0, 0); + * } + * + * // Update and draw the torus layer offscreen. + * function drawTorus() { + * // Start drawing to the torus p5.Framebuffer. + * torusLayer.begin(); + * + * // Clear the drawing surface. + * pg.clear(); + * + * // Turn on the lights. + * pg.lights(); + * + * // Rotate the coordinate system. + * pg.rotateX(frameCount * 0.01); + * pg.rotateY(frameCount * 0.01); + * + * // Style the torus. + * pg.noStroke(); + * + * // Draw the torus. + * pg.torus(20); + * + * // Start drawing to the torus p5.Framebuffer. + * torusLayer.end(); + * } + * + * // Update and draw the box layer offscreen. + * function drawBox() { + * // Start drawing to the box p5.Framebuffer. + * boxLayer.begin(); + * + * // Clear the drawing surface. + * pg.clear(); + * + * // Turn on the lights. + * pg.lights(); + * + * // Rotate the coordinate system. + * pg.rotateX(frameCount * 0.01); + * pg.rotateY(frameCount * 0.01); + * + * // Style the box. + * pg.noStroke(); + * + * // Draw the box. + * pg.box(30); + * + * // Start drawing to the box p5.Framebuffer. + * boxLayer.end(); + * } + * + *
        + * + *
        + * + * // Click and hold a mouse button to change shapes. + * + * let pg; + * let torusLayer; + * let boxLayer; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create an options object. + * let options = { width: 25, height: 25 }; + * + * // Create a p5.Graphics object using WebGL mode. + * pg = createGraphics(100, 100, WEBGL); + * + * // Create the p5.Framebuffer objects. + * // Use options for configuration. + * torusLayer = pg.createFramebuffer(options); + * boxLayer = pg.createFramebuffer(options); + * + * describe('A grid of white toruses rotating against a dark gray background. The shapes become boxes while the user holds a mouse button.'); + * } + * + * function draw() { + * // Update and draw the layers offscreen. + * drawTorus(); + * drawBox(); + * + * // Choose the layer to display. + * let layer; + * if (mouseIsPressed === true) { + * layer = boxLayer; + * } else { + * layer = torusLayer; + * } + * + * // Draw to the p5.Graphics object. + * pg.background(50); + * + * // Iterate from left to right. + * for (let x = -50; x < 50; x += 25) { + * // Iterate from top to bottom. + * for (let y = -50; y < 50; y += 25) { + * // Draw the layer to the p5.Graphics object + * pg.image(layer, x, y); + * } + * } + * + * // Display the p5.Graphics object. + * image(pg, 0, 0); + * } + * + * // Update and draw the torus layer offscreen. + * function drawTorus() { + * // Start drawing to the torus p5.Framebuffer. + * torusLayer.begin(); + * + * // Clear the drawing surface. + * pg.clear(); + * + * // Turn on the lights. + * pg.lights(); + * + * // Rotate the coordinate system. + * pg.rotateX(frameCount * 0.01); + * pg.rotateY(frameCount * 0.01); + * + * // Style the torus. + * pg.noStroke(); + * + * // Draw the torus. + * pg.torus(5, 2.5); + * + * // Start drawing to the torus p5.Framebuffer. + * torusLayer.end(); + * } + * + * // Update and draw the box layer offscreen. + * function drawBox() { + * // Start drawing to the box p5.Framebuffer. + * boxLayer.begin(); + * + * // Clear the drawing surface. + * pg.clear(); + * + * // Turn on the lights. + * pg.lights(); + * + * // Rotate the coordinate system. + * pg.rotateX(frameCount * 0.01); + * pg.rotateY(frameCount * 0.01); + * + * // Style the box. + * pg.noStroke(); + * + * // Draw the box. + * pg.box(7.5); + * + * // Start drawing to the box p5.Framebuffer. + * boxLayer.end(); + * } + * + *
        + */ + + }, + { + key: 'createFramebuffer', + value: function createFramebuffer(options) { + return new _main.default.Framebuffer(this, options); + } + } + ]); + return _class; + }(_main.default.Element); + var _default = _main.default.Graphics; + exports.default = _default; + }, + { + './constants': 291, + './main': 303, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.splice': 188, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 306: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('./main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + function _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; + } + 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 _createSuper(Derived) { + function 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; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_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); + } /** + * @module Rendering + * @submodule Rendering + * @for p5 + */ + /** + * Main graphics and rendering context, as well as the base API + * implementation for p5.js "core". To be used as the superclass for + * Renderer2D and Renderer3D classes, respectively. + * + * @class p5.Renderer + * @constructor + * @extends p5.Element + * @param {HTMLElement} elt DOM node that is wrapped + * @param {p5} [pInst] pointer to p5 instance + * @param {Boolean} [isMainCanvas] whether we're using it as main canvas + */ + + var Renderer = /*#__PURE__*/ function (_p5$Element) { + _inherits(Renderer, _p5$Element); + var _super = _createSuper(Renderer); + function Renderer(elt, pInst, isMainCanvas) { + var _this; + _classCallCheck(this, Renderer); + _this = _super.call(this, elt, pInst); + _this.canvas = elt; + _this._pixelsState = pInst; + if (isMainCanvas) { + _this._isMainCanvas = true; + // for pixel method sharing with pimage + _this._pInst._setProperty('_curElement', _assertThisInitialized(_this)); + _this._pInst._setProperty('canvas', _this.canvas); + _this._pInst._setProperty('width', _this.width); + _this._pInst._setProperty('height', _this.height); + } else { + // hide if offscreen buffer by default + _this.canvas.style.display = 'none'; + _this._styles = [ + ]; // non-main elt styles stored in p5.Renderer + } + _this._clipping = false; + _this._clipInvert = false; + _this._textSize = 12; + _this._textLeading = 15; + _this._textFont = 'sans-serif'; + _this._textStyle = constants.NORMAL; + _this._textAscent = null; + _this._textDescent = null; + _this._textAlign = constants.LEFT; + _this._textBaseline = constants.BASELINE; + _this._textWrap = constants.WORD; + _this._rectMode = constants.CORNER; + _this._ellipseMode = constants.CENTER; + _this._curveTightness = 0; + _this._imageMode = constants.CORNER; + _this._tint = null; + _this._doStroke = true; + _this._doFill = true; + _this._strokeSet = false; + _this._fillSet = false; + _this._leadingSet = false; + _this._pushPopDepth = 0; + return _this; + } // the renderer should return a 'style' object that it wishes to + // store on the push stack. + + _createClass(Renderer, [ + { + key: 'push', + value: function push() { + this._pushPopDepth++; + return { + properties: { + _doStroke: this._doStroke, + _strokeSet: this._strokeSet, + _doFill: this._doFill, + _fillSet: this._fillSet, + _tint: this._tint, + _imageMode: this._imageMode, + _rectMode: this._rectMode, + _ellipseMode: this._ellipseMode, + _textFont: this._textFont, + _textLeading: this._textLeading, + _leadingSet: this._leadingSet, + _textSize: this._textSize, + _textAlign: this._textAlign, + _textBaseline: this._textBaseline, + _textStyle: this._textStyle, + _textWrap: this._textWrap + } + }; + } // a pop() operation is in progress + // the renderer is passed the 'style' object that it returned + // from its push() method. + + }, + { + key: 'pop', + value: function pop(style) { + this._pushPopDepth--; + if (style.properties) { + // copy the style properties back into the renderer + Object.assign(this, style.properties); + } + } + }, + { + key: 'beginClip', + value: function beginClip() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + if (this._clipping) { + throw new Error('It looks like you\'re trying to clip while already in the middle of clipping. Did you forget to endClip()?'); + } + this._clipping = true; + this._clipInvert = options.invert; + } + }, + { + key: 'endClip', + value: function endClip() { + if (!this._clipping) { + throw new Error('It looks like you\'ve called endClip() without beginClip(). Did you forget to call beginClip() first?'); + } + this._clipping = false; + } /** + * Resize our canvas element. + */ + + }, + { + key: 'resize', + value: function resize(w, h) { + this.width = w; + this.height = h; + this.elt.width = w * this._pInst._pixelDensity; + this.elt.height = h * this._pInst._pixelDensity; + this.elt.style.width = ''.concat(w, 'px'); + this.elt.style.height = ''.concat(h, 'px'); + if (this._isMainCanvas) { + this._pInst._setProperty('width', this.width); + this._pInst._setProperty('height', this.height); + } + } + }, + { + key: 'get', + value: function get(x, y, w, h) { + var pixelsState = this._pixelsState; + var pd = pixelsState._pixelDensity; + var canvas = this.canvas; + if (typeof x === 'undefined' && typeof y === 'undefined') { + // get() + x = y = 0; + w = pixelsState.width; + h = pixelsState.height; + } else { + x *= pd; + y *= pd; + if (typeof w === 'undefined' && typeof h === 'undefined') { + // get(x,y) + if (x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) { + return [0, + 0, + 0, + 0]; + } + return this._getPixel(x, y); + } // get(x,y,w,h) + + } + var region = new _main.default.Image(w * pd, h * pd); + region.pixelDensity(pd); + region.canvas.getContext('2d').drawImage(canvas, x, y, w * pd, h * pd, 0, 0, w * pd, h * pd); + return region; + } + }, + { + key: 'textLeading', + value: function textLeading(l) { + if (typeof l === 'number') { + this._setProperty('_leadingSet', true); + this._setProperty('_textLeading', l); + return this._pInst; + } + return this._textLeading; + } + }, + { + key: 'textStyle', + value: function textStyle(s) { + if (s) { + if (s === constants.NORMAL || s === constants.ITALIC || s === constants.BOLD || s === constants.BOLDITALIC) { + this._setProperty('_textStyle', s); + } + return this._applyTextProperties(); + } + return this._textStyle; + } + }, + { + key: 'textAscent', + value: function textAscent() { + if (this._textAscent === null) { + this._updateTextMetrics(); + } + return this._textAscent; + } + }, + { + key: 'textDescent', + value: function textDescent() { + if (this._textDescent === null) { + this._updateTextMetrics(); + } + return this._textDescent; + } + }, + { + key: 'textAlign', + value: function textAlign(h, v) { + if (typeof h !== 'undefined') { + this._setProperty('_textAlign', h); + if (typeof v !== 'undefined') { + this._setProperty('_textBaseline', v); + } + return this._applyTextProperties(); + } else { + return { + horizontal: this._textAlign, + vertical: this._textBaseline + }; + } + } + }, + { + key: 'textWrap', + value: function textWrap(wrapStyle) { + this._setProperty('_textWrap', wrapStyle); + return this._textWrap; + } + }, + { + key: 'text', + value: function text(str, x, y, maxWidth, maxHeight) { + var p = this._pInst; + var textWrapStyle = this._textWrap; + var lines; + var line; + var testLine; + var testWidth; + var words; + var chars; + var shiftedY; + var finalMaxHeight = Number.MAX_VALUE; + // fix for #5785 (top of bounding box) + var finalMinHeight = y; + if (!(this._doFill || this._doStroke)) { + return; + } + if (typeof str === 'undefined') { + return; + } else if (typeof str !== 'string') { + str = str.toString(); + } // Replaces tabs with double-spaces and splits string on any line + // breaks present in the original string + + str = str.replace(/(\t)/g, ' '); + lines = str.split('\n'); + if (typeof maxWidth !== 'undefined') { + if (this._rectMode === constants.CENTER) { + x -= maxWidth / 2; + } + switch (this._textAlign) { + case constants.CENTER: + x += maxWidth / 2; + break; + case constants.RIGHT: + x += maxWidth; + break; + } + if (typeof maxHeight !== 'undefined') { + if (this._rectMode === constants.CENTER) { + y -= maxHeight / 2; + finalMinHeight -= maxHeight / 2; + } + var originalY = y; + var ascent = p.textAscent(); + switch (this._textBaseline) { + case constants.BOTTOM: + shiftedY = y + maxHeight; + y = Math.max(shiftedY, y); + // fix for #5785 (top of bounding box) + finalMinHeight += ascent; + break; + case constants.CENTER: + shiftedY = y + maxHeight / 2; + y = Math.max(shiftedY, y); + // fix for #5785 (top of bounding box) + finalMinHeight += ascent / 2; + break; + } // remember the max-allowed y-position for any line (fix to #928) + + finalMaxHeight = y + maxHeight - ascent; + // fix for #5785 (bottom of bounding box) + if (this._textBaseline === constants.CENTER) { + finalMaxHeight = originalY + maxHeight - ascent / 2; + } + } else { + // no text-height specified, show warning for BOTTOM / CENTER + if (this._textBaseline === constants.BOTTOM || this._textBaseline === constants.CENTER) { + // use rectHeight as an approximation for text height + var rectHeight = p.textSize() * this._textLeading; + finalMinHeight = y - rectHeight / 2; + finalMaxHeight = y + rectHeight / 2; + } + } // Render lines of text according to settings of textWrap + // Splits lines at spaces, for loop adds one word + space + // at a time and tests length with next word added + + if (textWrapStyle === constants.WORD) { + var nlines = [ + ]; + for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) { + line = ''; + words = lines[lineIndex].split(' '); + for (var wordIndex = 0; wordIndex < words.length; wordIndex++) { + testLine = ''.concat(line + words[wordIndex]) + ' '; + testWidth = this.textWidth(testLine); + if (testWidth > maxWidth && line.length > 0) { + nlines.push(line); + line = ''.concat(words[wordIndex]) + ' '; + } else { + line = testLine; + } + } + nlines.push(line); + } + var offset = 0; + if (this._textBaseline === constants.CENTER) { + offset = (nlines.length - 1) * p.textLeading() / 2; + } else if (this._textBaseline === constants.BOTTOM) { + offset = (nlines.length - 1) * p.textLeading(); + } + for (var _lineIndex = 0; _lineIndex < lines.length; _lineIndex++) { + line = ''; + words = lines[_lineIndex].split(' '); + for (var _wordIndex = 0; _wordIndex < words.length; _wordIndex++) { + testLine = ''.concat(line + words[_wordIndex]) + ' '; + testWidth = this.textWidth(testLine); + if (testWidth > maxWidth && line.length > 0) { + this._renderText(p, line.trim(), x, y - offset, finalMaxHeight, finalMinHeight); + line = ''.concat(words[_wordIndex]) + ' '; + y += p.textLeading(); + } else { + line = testLine; + } + } + this._renderText(p, line.trim(), x, y - offset, finalMaxHeight, finalMinHeight); + y += p.textLeading(); + } + } else { + var _nlines = [ + ]; + for (var _lineIndex2 = 0; _lineIndex2 < lines.length; _lineIndex2++) { + line = ''; + chars = lines[_lineIndex2].split(''); + for (var charIndex = 0; charIndex < chars.length; charIndex++) { + testLine = ''.concat(line + chars[charIndex]); + testWidth = this.textWidth(testLine); + if (testWidth <= maxWidth) { + line += chars[charIndex]; + } else if (testWidth > maxWidth && line.length > 0) { + _nlines.push(line); + line = ''.concat(chars[charIndex]); + } + } + } + _nlines.push(line); + var _offset = 0; + if (this._textBaseline === constants.CENTER) { + _offset = (_nlines.length - 1) * p.textLeading() / 2; + } else if (this._textBaseline === constants.BOTTOM) { + _offset = (_nlines.length - 1) * p.textLeading(); + } // Splits lines at characters, for loop adds one char at a time + // and tests length with next char added + + for (var _lineIndex3 = 0; _lineIndex3 < lines.length; _lineIndex3++) { + line = ''; + chars = lines[_lineIndex3].split(''); + for (var _charIndex = 0; _charIndex < chars.length; _charIndex++) { + testLine = ''.concat(line + chars[_charIndex]); + testWidth = this.textWidth(testLine); + if (testWidth <= maxWidth) { + line += chars[_charIndex]; + } else if (testWidth > maxWidth && line.length > 0) { + this._renderText(p, line.trim(), x, y - _offset, finalMaxHeight, finalMinHeight); + y += p.textLeading(); + line = ''.concat(chars[_charIndex]); + } + } + } + this._renderText(p, line.trim(), x, y - _offset, finalMaxHeight, finalMinHeight); + y += p.textLeading(); + } + } else { + // Offset to account for vertically centering multiple lines of text - no + // need to adjust anything for vertical align top or baseline + var _offset2 = 0; + if (this._textBaseline === constants.CENTER) { + _offset2 = (lines.length - 1) * p.textLeading() / 2; + } else if (this._textBaseline === constants.BOTTOM) { + _offset2 = (lines.length - 1) * p.textLeading(); + } // Renders lines of text at any line breaks present in the original string + + for (var i = 0; i < lines.length; i++) { + this._renderText(p, lines[i], x, y - _offset2, finalMaxHeight, finalMinHeight - _offset2); + y += p.textLeading(); + } + } + return p; + } + }, + { + key: '_applyDefaults', + value: function _applyDefaults() { + return this; + } /** + * Helper function to check font type (system or otf) + */ + + }, + { + key: '_isOpenType', + value: function _isOpenType() { + var f = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._textFont; + return _typeof(f) === 'object' && f.font && f.font.supported; + } + }, + { + key: '_updateTextMetrics', + value: function _updateTextMetrics() { + if (this._isOpenType()) { + this._setProperty('_textAscent', this._textFont._textAscent()); + this._setProperty('_textDescent', this._textFont._textDescent()); + return this; + } // Adapted from http://stackoverflow.com/a/25355178 + + var text = document.createElement('span'); + text.style.fontFamily = this._textFont; + text.style.fontSize = ''.concat(this._textSize, 'px'); + text.innerHTML = 'ABCjgq|'; + var block = document.createElement('div'); + block.style.display = 'inline-block'; + block.style.width = '1px'; + block.style.height = '0px'; + var container = document.createElement('div'); + container.appendChild(text); + container.appendChild(block); + container.style.height = '0px'; + container.style.overflow = 'hidden'; + document.body.appendChild(container); + block.style.verticalAlign = 'baseline'; + var blockOffset = calculateOffset(block); + var textOffset = calculateOffset(text); + var ascent = blockOffset[1] - textOffset[1]; + block.style.verticalAlign = 'bottom'; + blockOffset = calculateOffset(block); + textOffset = calculateOffset(text); + var height = blockOffset[1] - textOffset[1]; + var descent = height - ascent; + document.body.removeChild(container); + this._setProperty('_textAscent', ascent); + this._setProperty('_textDescent', descent); + return this; + } + } + ]); + return Renderer; + }(_main.default.Element); + /** + * Helper fxn to measure ascent and descent. + * Adapted from http://stackoverflow.com/a/25355178 + */ + function calculateOffset(object) { + var currentLeft = 0, + currentTop = 0; + if (object.offsetParent) { + do { + currentLeft += object.offsetLeft; + currentTop += object.offsetTop; + } while (object = object.offsetParent); + } else { + currentLeft += object.offsetLeft; + currentTop += object.offsetTop; + } + return [currentLeft, + currentTop]; + } // This caused the test to failed. + + Renderer.prototype.textSize = function (s) { + if (typeof s === 'number') { + this._setProperty('_textSize', s); + if (!this._leadingSet) { + // only use a default value if not previously set (#5181) + this._setProperty('_textLeading', s * constants._DEFAULT_LEADMULT); + } + return this._applyTextProperties(); + } + return this._textSize; + }; + _main.default.Renderer = Renderer; + var _default = _main.default.Renderer; + exports.default = _default; + }, + { + '../core/constants': 291, + './main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.number.constructor': 196, + 'core-js/modules/es.object.assign': 199, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.string.trim': 224, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 307: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.reflect.get'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('./main')); + var constants = _interopRequireWildcard(_dereq_('./constants')); + _dereq_('./p5.Renderer'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } + 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 = _getPrototypeOf(object); + if (object === null) break; + } + return object; + } + 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 _createSuper(Derived) { + function 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; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_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); + } /** + * p5.Renderer2D + * The 2D graphics canvas renderer class. + * extends p5.Renderer + */ + + var styleEmpty = 'rgba(0,0,0,0)'; + // const alphaThreshold = 0.00125; // minimum visible + var Renderer2D = /*#__PURE__*/ function (_p5$Renderer) { + _inherits(Renderer2D, _p5$Renderer); + var _super = _createSuper(Renderer2D); + function Renderer2D(elt, pInst, isMainCanvas) { + var _this; + _classCallCheck(this, Renderer2D); + _this = _super.call(this, elt, pInst, isMainCanvas); + _this.drawingContext = _this.canvas.getContext('2d'); + _this._pInst._setProperty('drawingContext', _this.drawingContext); + return _this; + } + _createClass(Renderer2D, [ + { + key: 'getFilterGraphicsLayer', + value: function getFilterGraphicsLayer() { + // create hidden webgl renderer if it doesn't exist + if (!this.filterGraphicsLayer) { + // the real _pInst is buried when this is a secondary p5.Graphics + var pInst = this._pInst instanceof _main.default.Graphics ? this._pInst._pInst : this._pInst; + // create secondary layer + this.filterGraphicsLayer = new _main.default.Graphics(this.width, this.height, constants.WEBGL, pInst); + } + if (this.filterGraphicsLayer.width !== this.width || this.filterGraphicsLayer.height !== this.height) { + // Resize the graphics layer + this.filterGraphicsLayer.resizeCanvas(this.width, this.height); + } + if (this.filterGraphicsLayer.pixelDensity() !== this._pInst.pixelDensity()) { + this.filterGraphicsLayer.pixelDensity(this._pInst.pixelDensity()); + } + return this.filterGraphicsLayer; + } + }, + { + key: '_applyDefaults', + value: function _applyDefaults() { + this._cachedFillStyle = this._cachedStrokeStyle = undefined; + this._cachedBlendMode = constants.BLEND; + this._setFill(constants._DEFAULT_FILL); + this._setStroke(constants._DEFAULT_STROKE); + this.drawingContext.lineCap = constants.ROUND; + this.drawingContext.font = 'normal 12px sans-serif'; + } + }, + { + key: 'resize', + value: function resize(w, h) { + _get(_getPrototypeOf(Renderer2D.prototype), 'resize', this).call(this, w, h); + this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); + } ////////////////////////////////////////////// + // COLOR | Setting + ////////////////////////////////////////////// + + }, + { + key: 'background', + value: function background() { + this.drawingContext.save(); + this.resetMatrix(); + if ((arguments.length <= 0 ? undefined : arguments[0]) instanceof _main.default.Image) { + if ((arguments.length <= 1 ? undefined : arguments[1]) >= 0) { + // set transparency of background + var img = arguments.length <= 0 ? undefined : arguments[0]; + this.drawingContext.globalAlpha = (arguments.length <= 1 ? undefined : arguments[1]) / 255; + this._pInst.image(img, 0, 0, this.width, this.height); + } else { + this._pInst.image(arguments.length <= 0 ? undefined : arguments[0], 0, 0, this.width, this.height); + } + } else { + var _this$_pInst; + var curFill = this._getFill(); + // create background rect + var color = (_this$_pInst = this._pInst).color.apply(_this$_pInst, arguments); + //accessible Outputs + if (this._pInst._addAccsOutput()) { + this._pInst._accsBackground(color.levels); + } + var newFill = color.toString(); + this._setFill(newFill); + if (this._isErasing) { + this.blendMode(this._cachedBlendMode); + } + this.drawingContext.fillRect(0, 0, this.width, this.height); + // reset fill + this._setFill(curFill); + if (this._isErasing) { + this._pInst.erase(); + } + } + this.drawingContext.restore(); + } + }, + { + key: 'clear', + value: function clear() { + this.drawingContext.save(); + this.resetMatrix(); + this.drawingContext.clearRect(0, 0, this.width, this.height); + this.drawingContext.restore(); + } + }, + { + key: 'fill', + value: function fill() { + var _this$_pInst2; + var color = (_this$_pInst2 = this._pInst).color.apply(_this$_pInst2, arguments); + this._setFill(color.toString()); + //accessible Outputs + if (this._pInst._addAccsOutput()) { + this._pInst._accsCanvasColors('fill', color.levels); + } + } + }, + { + key: 'stroke', + value: function stroke() { + var _this$_pInst3; + var color = (_this$_pInst3 = this._pInst).color.apply(_this$_pInst3, arguments); + this._setStroke(color.toString()); + //accessible Outputs + if (this._pInst._addAccsOutput()) { + this._pInst._accsCanvasColors('stroke', color.levels); + } + } + }, + { + key: 'erase', + value: function erase(opacityFill, opacityStroke) { + if (!this._isErasing) { + // cache the fill style + this._cachedFillStyle = this.drawingContext.fillStyle; + var newFill = this._pInst.color(255, opacityFill).toString(); + this.drawingContext.fillStyle = newFill; + // cache the stroke style + this._cachedStrokeStyle = this.drawingContext.strokeStyle; + var newStroke = this._pInst.color(255, opacityStroke).toString(); + this.drawingContext.strokeStyle = newStroke; + // cache blendMode + var tempBlendMode = this._cachedBlendMode; + this.blendMode(constants.REMOVE); + this._cachedBlendMode = tempBlendMode; + this._isErasing = true; + } + } + }, + { + key: 'noErase', + value: function noErase() { + if (this._isErasing) { + this.drawingContext.fillStyle = this._cachedFillStyle; + this.drawingContext.strokeStyle = this._cachedStrokeStyle; + this.blendMode(this._cachedBlendMode); + this._isErasing = false; + } + } + }, + { + key: 'beginClip', + value: function beginClip() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + _get(_getPrototypeOf(Renderer2D.prototype), 'beginClip', this).call(this, options); + // cache the fill style + this._cachedFillStyle = this.drawingContext.fillStyle; + var newFill = this._pInst.color(255, 0).toString(); + this.drawingContext.fillStyle = newFill; + // cache the stroke style + this._cachedStrokeStyle = this.drawingContext.strokeStyle; + var newStroke = this._pInst.color(255, 0).toString(); + this.drawingContext.strokeStyle = newStroke; + // cache blendMode + var tempBlendMode = this._cachedBlendMode; + this.blendMode(constants.BLEND); + this._cachedBlendMode = tempBlendMode; + // Start a new path. Everything from here on out should become part of this + // one path so that we can clip to the whole thing. + this.drawingContext.beginPath(); + if (this._clipInvert) { + // Slight hack: draw a big rectangle over everything with reverse winding + // order. This is hopefully large enough to cover most things. + this.drawingContext.moveTo( - 2 * this.width, - 2 * this.height); + this.drawingContext.lineTo( - 2 * this.width, 2 * this.height); + this.drawingContext.lineTo(2 * this.width, 2 * this.height); + this.drawingContext.lineTo(2 * this.width, - 2 * this.height); + this.drawingContext.closePath(); + } + } + }, + { + key: 'endClip', + value: function endClip() { + this._doFillStrokeClose(); + this.drawingContext.clip(); + _get(_getPrototypeOf(Renderer2D.prototype), 'endClip', this).call(this); + this.drawingContext.fillStyle = this._cachedFillStyle; + this.drawingContext.strokeStyle = this._cachedStrokeStyle; + this.blendMode(this._cachedBlendMode); + } ////////////////////////////////////////////// + // IMAGE | Loading & Displaying + ////////////////////////////////////////////// + + }, + { + key: 'image', + value: function image(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) { + var cnv; + if (img.gifProperties) { + img._animateGif(this._pInst); + } + try { + if (_main.default.MediaElement && img instanceof _main.default.MediaElement) { + img._ensureCanvas(); + } + if (this._tint && img.canvas) { + cnv = this._getTintedImageCanvas(img); + } + if (!cnv) { + cnv = img.canvas || img.elt; + } + var s = 1; + if (img.width && img.width > 0) { + s = cnv.width / img.width; + } + if (this._isErasing) { + this.blendMode(this._cachedBlendMode); + } + this.drawingContext.drawImage(cnv, s * sx, s * sy, s * sWidth, s * sHeight, dx, dy, dWidth, dHeight); + if (this._isErasing) { + this._pInst.erase(); + } + } catch (e) { + if (e.name !== 'NS_ERROR_NOT_AVAILABLE') { + throw e; + } + } + } + }, + { + key: '_getTintedImageCanvas', + value: function _getTintedImageCanvas(img) { + if (!img.canvas) { + return img; + } + if (!img.tintCanvas) { + // Once an image has been tinted, keep its tint canvas + // around so we don't need to re-incur the cost of + // creating a new one for each tint + img.tintCanvas = document.createElement('canvas'); + } // Keep the size of the tint canvas up-to-date + + if (img.tintCanvas.width !== img.canvas.width) { + img.tintCanvas.width = img.canvas.width; + } + if (img.tintCanvas.height !== img.canvas.height) { + img.tintCanvas.height = img.canvas.height; + } // Goal: multiply the r,g,b,a values of the source by + // the r,g,b,a values of the tint color + + var ctx = img.tintCanvas.getContext('2d'); + ctx.save(); + ctx.clearRect(0, 0, img.canvas.width, img.canvas.height); + if (this._tint[0] < 255 || this._tint[1] < 255 || this._tint[2] < 255) { + // Color tint: we need to use the multiply blend mode to change the colors. + // However, the canvas implementation of this destroys the alpha channel of + // the image. To accommodate, we first get a version of the image with full + // opacity everywhere, tint using multiply, and then use the destination-in + // blend mode to restore the alpha channel again. + // Start with the original image + ctx.drawImage(img.canvas, 0, 0); + // This blend mode makes everything opaque but forces the luma to match + // the original image again + ctx.globalCompositeOperation = 'luminosity'; + ctx.drawImage(img.canvas, 0, 0); + // This blend mode forces the hue and chroma to match the original image. + // After this we should have the original again, but with full opacity. + ctx.globalCompositeOperation = 'color'; + ctx.drawImage(img.canvas, 0, 0); + // Apply color tint + ctx.globalCompositeOperation = 'multiply'; + ctx.fillStyle = 'rgb('.concat(this._tint.slice(0, 3).join(', '), ')'); + ctx.fillRect(0, 0, img.canvas.width, img.canvas.height); + // Replace the alpha channel with the original alpha * the alpha tint + ctx.globalCompositeOperation = 'destination-in'; + ctx.globalAlpha = this._tint[3] / 255; + ctx.drawImage(img.canvas, 0, 0); + } else { + // If we only need to change the alpha, we can skip all the extra work! + ctx.globalAlpha = this._tint[3] / 255; + ctx.drawImage(img.canvas, 0, 0); + } + ctx.restore(); + return img.tintCanvas; + } ////////////////////////////////////////////// + // IMAGE | Pixels + ////////////////////////////////////////////// + + }, + { + key: 'blendMode', + value: function blendMode(mode) { + if (mode === constants.SUBTRACT) { + console.warn('blendMode(SUBTRACT) only works in WEBGL mode.'); + } else if (mode === constants.BLEND || mode === constants.REMOVE || mode === constants.DARKEST || mode === constants.LIGHTEST || mode === constants.DIFFERENCE || mode === constants.MULTIPLY || mode === constants.EXCLUSION || mode === constants.SCREEN || mode === constants.REPLACE || mode === constants.OVERLAY || mode === constants.HARD_LIGHT || mode === constants.SOFT_LIGHT || mode === constants.DODGE || mode === constants.BURN || mode === constants.ADD) { + this._cachedBlendMode = mode; + this.drawingContext.globalCompositeOperation = mode; + } else { + throw new Error('Mode '.concat(mode, ' not recognized.')); + } + } + }, + { + key: 'blend', + value: function blend() { + var currBlend = this.drawingContext.globalCompositeOperation; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + var blendMode = args[args.length - 1]; + var copyArgs = Array.prototype.slice.call(args, 0, args.length - 1); + this.drawingContext.globalCompositeOperation = blendMode; + _main.default.prototype.copy.apply(this, copyArgs); + this.drawingContext.globalCompositeOperation = currBlend; + } // p5.Renderer2D.prototype.get = p5.Renderer.prototype.get; + // .get() is not overridden + // x,y are canvas-relative (pre-scaled by _pixelDensity) + + }, + { + key: '_getPixel', + value: function _getPixel(x, y) { + var imageData, + index; + imageData = this.drawingContext.getImageData(x, y, 1, 1).data; + index = 0; + return [imageData[index + 0], + imageData[index + 1], + imageData[index + 2], + imageData[index + 3]]; + } + }, + { + key: 'loadPixels', + value: function loadPixels() { + var pixelsState = this._pixelsState; // if called by p5.Image + var pd = pixelsState._pixelDensity; + var w = this.width * pd; + var h = this.height * pd; + var imageData = this.drawingContext.getImageData(0, 0, w, h); + // @todo this should actually set pixels per object, so diff buffers can + // have diff pixel arrays. + pixelsState._setProperty('imageData', imageData); + pixelsState._setProperty('pixels', imageData.data); + } + }, + { + key: 'set', + value: function set(x, y, imgOrCol) { + // round down to get integer numbers + x = Math.floor(x); + y = Math.floor(y); + var pixelsState = this._pixelsState; + if (imgOrCol instanceof _main.default.Image) { + this.drawingContext.save(); + this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); + this.drawingContext.scale(pixelsState._pixelDensity, pixelsState._pixelDensity); + this.drawingContext.clearRect(x, y, imgOrCol.width, imgOrCol.height); + this.drawingContext.drawImage(imgOrCol.canvas, x, y); + this.drawingContext.restore(); + } else { + var r = 0, + g = 0, + b = 0, + a = 0; + var idx = 4 * (y * pixelsState._pixelDensity * (this.width * pixelsState._pixelDensity) + x * pixelsState._pixelDensity); + if (!pixelsState.imageData) { + pixelsState.loadPixels(); + } + if (typeof imgOrCol === 'number') { + if (idx < pixelsState.pixels.length) { + r = imgOrCol; + g = imgOrCol; + b = imgOrCol; + a = 255; + //this.updatePixels.call(this); + } + } else if (Array.isArray(imgOrCol)) { + if (imgOrCol.length < 4) { + throw new Error('pixel array must be of the form [R, G, B, A]'); + } + if (idx < pixelsState.pixels.length) { + r = imgOrCol[0]; + g = imgOrCol[1]; + b = imgOrCol[2]; + a = imgOrCol[3]; + //this.updatePixels.call(this); + } + } else if (imgOrCol instanceof _main.default.Color) { + if (idx < pixelsState.pixels.length) { + r = imgOrCol.levels[0]; + g = imgOrCol.levels[1]; + b = imgOrCol.levels[2]; + a = imgOrCol.levels[3]; + //this.updatePixels.call(this); + } + } // loop over pixelDensity * pixelDensity + + for (var i = 0; i < pixelsState._pixelDensity; i++) { + for (var j = 0; j < pixelsState._pixelDensity; j++) { + // loop over + idx = 4 * ((y * pixelsState._pixelDensity + j) * this.width * pixelsState._pixelDensity + (x * pixelsState._pixelDensity + i)); + pixelsState.pixels[idx] = r; + pixelsState.pixels[idx + 1] = g; + pixelsState.pixels[idx + 2] = b; + pixelsState.pixels[idx + 3] = a; + } + } + } + } + }, + { + key: 'updatePixels', + value: function updatePixels(x, y, w, h) { + var pixelsState = this._pixelsState; + var pd = pixelsState._pixelDensity; + if (x === undefined && y === undefined && w === undefined && h === undefined) { + x = 0; + y = 0; + w = this.width; + h = this.height; + } + x *= pd; + y *= pd; + w *= pd; + h *= pd; + if (this.gifProperties) { + this.gifProperties.frames[this.gifProperties.displayIndex].image = pixelsState.imageData; + } + this.drawingContext.putImageData(pixelsState.imageData, x, y, 0, 0, w, h); + } ////////////////////////////////////////////// + // SHAPE | 2D Primitives + ////////////////////////////////////////////// + /** + * Generate a cubic Bezier representing an arc on the unit circle of total + * angle `size` radians, beginning `start` radians above the x-axis. Up to + * four of these curves are combined to make a full arc. + * + * See ecridge.com/bezier.pdf for an explanation of the method. + */ + + }, + { + key: '_acuteArcToBezier', + value: function _acuteArcToBezier(start, size) { + // Evaluate constants. + var alpha = size / 2, + cos_alpha = Math.cos(alpha), + sin_alpha = Math.sin(alpha), + cot_alpha = 1 / Math.tan(alpha), + // This is how far the arc needs to be rotated. + phi = start + alpha, + cos_phi = Math.cos(phi), + sin_phi = Math.sin(phi), + lambda = (4 - cos_alpha) / 3, + mu = sin_alpha + (cos_alpha - lambda) * cot_alpha; + // Return rotated waypoints. + return { + ax: Math.cos(start).toFixed(7), + ay: Math.sin(start).toFixed(7), + bx: (lambda * cos_phi + mu * sin_phi).toFixed(7), + by: (lambda * sin_phi - mu * cos_phi).toFixed(7), + cx: (lambda * cos_phi - mu * sin_phi).toFixed(7), + cy: (lambda * sin_phi + mu * cos_phi).toFixed(7), + dx: Math.cos(start + size).toFixed(7), + dy: Math.sin(start + size).toFixed(7) + }; + } /* + * This function requires that: + * + * 0 <= start < TWO_PI + * + * start <= stop < start + TWO_PI + */ + + }, + { + key: 'arc', + value: function arc(x, y, w, h, start, stop, mode) { + var ctx = this.drawingContext; + var rx = w / 2; + var ry = h / 2; + var epsilon = 0.00001; // Smallest visible angle on displays up to 4K. + var arcToDraw = 0; + var curves = [ + ]; + x += rx; + y += ry; + // Create curves + while (stop - start >= epsilon) { + arcToDraw = Math.min(stop - start, constants.HALF_PI); + curves.push(this._acuteArcToBezier(start, arcToDraw)); + start += arcToDraw; + } // Fill curves + + if (this._doFill) { + if (!this._clipping) ctx.beginPath(); + curves.forEach(function (curve, index) { + if (index === 0) { + ctx.moveTo(x + curve.ax * rx, y + curve.ay * ry); + } /* eslint-disable indent */ + + ctx.bezierCurveTo(x + curve.bx * rx, y + curve.by * ry, x + curve.cx * rx, y + curve.cy * ry, x + curve.dx * rx, y + curve.dy * ry); + /* eslint-enable indent */ + }); + if (mode === constants.PIE || mode == null) { + ctx.lineTo(x, y); + } + ctx.closePath(); + if (!this._clipping) ctx.fill(); + } // Stroke curves + + if (this._doStroke) { + if (!this._clipping) ctx.beginPath(); + curves.forEach(function (curve, index) { + if (index === 0) { + ctx.moveTo(x + curve.ax * rx, y + curve.ay * ry); + } /* eslint-disable indent */ + + ctx.bezierCurveTo(x + curve.bx * rx, y + curve.by * ry, x + curve.cx * rx, y + curve.cy * ry, x + curve.dx * rx, y + curve.dy * ry); + /* eslint-enable indent */ + }); + if (mode === constants.PIE) { + ctx.lineTo(x, y); + ctx.closePath(); + } else if (mode === constants.CHORD) { + ctx.closePath(); + } + if (!this._clipping) ctx.stroke(); + } + return this; + } + }, + { + key: 'ellipse', + value: function ellipse(args) { + var ctx = this.drawingContext; + var doFill = this._doFill, + doStroke = this._doStroke; + var x = parseFloat(args[0]), + y = parseFloat(args[1]), + w = parseFloat(args[2]), + h = parseFloat(args[3]); + if (doFill && !doStroke) { + if (this._getFill() === styleEmpty) { + return this; + } + } else if (!doFill && doStroke) { + if (this._getStroke() === styleEmpty) { + return this; + } + } + var centerX = x + w / 2, + centerY = y + h / 2, + radiusX = w / 2, + radiusY = h / 2; + if (!this._clipping) ctx.beginPath(); + ctx.ellipse(centerX, centerY, radiusX, radiusY, 0, 0, 2 * Math.PI); + if (!this._clipping && doFill) { + ctx.fill(); + } + if (!this._clipping && doStroke) { + ctx.stroke(); + } + } + }, + { + key: 'line', + value: function line(x1, y1, x2, y2) { + var ctx = this.drawingContext; + if (!this._doStroke) { + return this; + } else if (this._getStroke() === styleEmpty) { + return this; + } + if (!this._clipping) ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); + return this; + } + }, + { + key: 'point', + value: function point(x, y) { + var ctx = this.drawingContext; + if (!this._doStroke) { + return this; + } else if (this._getStroke() === styleEmpty) { + return this; + } + var s = this._getStroke(); + var f = this._getFill(); + if (!this._clipping) { + // swapping fill color to stroke and back after for correct point rendering + this._setFill(s); + } + if (!this._clipping) ctx.beginPath(); + ctx.arc(x, y, ctx.lineWidth / 2, 0, constants.TWO_PI, false); + if (!this._clipping) { + ctx.fill(); + this._setFill(f); + } + } + }, + { + key: 'quad', + value: function quad(x1, y1, x2, y2, x3, y3, x4, y4) { + var ctx = this.drawingContext; + var doFill = this._doFill, + doStroke = this._doStroke; + if (doFill && !doStroke) { + if (this._getFill() === styleEmpty) { + return this; + } + } else if (!doFill && doStroke) { + if (this._getStroke() === styleEmpty) { + return this; + } + } + if (!this._clipping) ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.lineTo(x3, y3); + ctx.lineTo(x4, y4); + ctx.closePath(); + if (!this._clipping && doFill) { + ctx.fill(); + } + if (!this._clipping && doStroke) { + ctx.stroke(); + } + return this; + } + }, + { + key: 'rect', + value: function rect(args) { + var x = args[0]; + var y = args[1]; + var w = args[2]; + var h = args[3]; + var tl = args[4]; + var tr = args[5]; + var br = args[6]; + var bl = args[7]; + var ctx = this.drawingContext; + var doFill = this._doFill, + doStroke = this._doStroke; + if (doFill && !doStroke) { + if (this._getFill() === styleEmpty) { + return this; + } + } else if (!doFill && doStroke) { + if (this._getStroke() === styleEmpty) { + return this; + } + } + if (!this._clipping) ctx.beginPath(); + if (typeof tl === 'undefined') { + // No rounded corners + ctx.rect(x, y, w, h); + } else { + // At least one rounded corner + // Set defaults when not specified + if (typeof tr === 'undefined') { + tr = tl; + } + if (typeof br === 'undefined') { + br = tr; + } + if (typeof bl === 'undefined') { + bl = br; + } // corner rounding must always be positive + + var absW = Math.abs(w); + var absH = Math.abs(h); + var hw = absW / 2; + var hh = absH / 2; + // Clip radii + if (absW < 2 * tl) { + tl = hw; + } + if (absH < 2 * tl) { + tl = hh; + } + if (absW < 2 * tr) { + tr = hw; + } + if (absH < 2 * tr) { + tr = hh; + } + if (absW < 2 * br) { + br = hw; + } + if (absH < 2 * br) { + br = hh; + } + if (absW < 2 * bl) { + bl = hw; + } + if (absH < 2 * bl) { + bl = hh; + } // Draw shape + + if (!this._clipping) ctx.beginPath(); + ctx.moveTo(x + tl, y); + ctx.arcTo(x + w, y, x + w, y + h, tr); + ctx.arcTo(x + w, y + h, x, y + h, br); + ctx.arcTo(x, y + h, x, y, bl); + ctx.arcTo(x, y, x + w, y, tl); + ctx.closePath(); + } + if (!this._clipping && this._doFill) { + ctx.fill(); + } + if (!this._clipping && this._doStroke) { + ctx.stroke(); + } + return this; + } + }, + { + key: 'triangle', + value: function triangle(args) { + var ctx = this.drawingContext; + var doFill = this._doFill, + doStroke = this._doStroke; + var x1 = args[0], + y1 = args[1]; + var x2 = args[2], + y2 = args[3]; + var x3 = args[4], + y3 = args[5]; + if (doFill && !doStroke) { + if (this._getFill() === styleEmpty) { + return this; + } + } else if (!doFill && doStroke) { + if (this._getStroke() === styleEmpty) { + return this; + } + } + if (!this._clipping) ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.lineTo(x3, y3); + ctx.closePath(); + if (!this._clipping && doFill) { + ctx.fill(); + } + if (!this._clipping && doStroke) { + ctx.stroke(); + } + } + }, + { + key: 'endShape', + value: function endShape(mode, vertices, isCurve, isBezier, isQuadratic, isContour, shapeKind) { + if (vertices.length === 0) { + return this; + } + if (!this._doStroke && !this._doFill) { + return this; + } + var closeShape = mode === constants.CLOSE; + var v; + if (closeShape && !isContour) { + vertices.push(vertices[0]); + } + var i, + j; + var numVerts = vertices.length; + if (isCurve && shapeKind === null) { + if (numVerts > 3) { + var b = [ + ], + s = 1 - this._curveTightness; + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(vertices[1][0], vertices[1][1]); + for (i = 1; i + 2 < numVerts; i++) { + v = vertices[i]; + b[0] = [ + v[0], + v[1] + ]; + b[1] = [ + v[0] + (s * vertices[i + 1][0] - s * vertices[i - 1][0]) / 6, + v[1] + (s * vertices[i + 1][1] - s * vertices[i - 1][1]) / 6 + ]; + b[2] = [ + vertices[i + 1][0] + (s * vertices[i][0] - s * vertices[i + 2][0]) / 6, + vertices[i + 1][1] + (s * vertices[i][1] - s * vertices[i + 2][1]) / 6 + ]; + b[3] = [ + vertices[i + 1][0], + vertices[i + 1][1] + ]; + this.drawingContext.bezierCurveTo(b[1][0], b[1][1], b[2][0], b[2][1], b[3][0], b[3][1]); + } + if (closeShape) { + this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + } + this._doFillStrokeClose(closeShape); + } + } else if (isBezier && shapeKind === null) { + if (!this._clipping) this.drawingContext.beginPath(); + for (i = 0; i < numVerts; i++) { + if (vertices[i].isVert) { + if (vertices[i].moveTo) { + this.drawingContext.moveTo(vertices[i][0], vertices[i][1]); + } else { + this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); + } + } else { + this.drawingContext.bezierCurveTo(vertices[i][0], vertices[i][1], vertices[i][2], vertices[i][3], vertices[i][4], vertices[i][5]); + } + } + this._doFillStrokeClose(closeShape); + } else if (isQuadratic && shapeKind === null) { + if (!this._clipping) this.drawingContext.beginPath(); + for (i = 0; i < numVerts; i++) { + if (vertices[i].isVert) { + if (vertices[i].moveTo) { + this.drawingContext.moveTo(vertices[i][0], vertices[i][1]); + } else { + this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); + } + } else { + this.drawingContext.quadraticCurveTo(vertices[i][0], vertices[i][1], vertices[i][2], vertices[i][3]); + } + } + this._doFillStrokeClose(closeShape); + } else { + if (shapeKind === constants.POINTS) { + for (i = 0; i < numVerts; i++) { + v = vertices[i]; + if (this._doStroke) { + this._pInst.stroke(v[6]); + } + this._pInst.point(v[0], v[1]); + } + } else if (shapeKind === constants.LINES) { + for (i = 0; i + 1 < numVerts; i += 2) { + v = vertices[i]; + if (this._doStroke) { + this._pInst.stroke(vertices[i + 1][6]); + } + this._pInst.line(v[0], v[1], vertices[i + 1][0], vertices[i + 1][1]); + } + } else if (shapeKind === constants.TRIANGLES) { + for (i = 0; i + 2 < numVerts; i += 3) { + v = vertices[i]; + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(v[0], v[1]); + this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]); + this.drawingContext.closePath(); + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 2][5]); + this.drawingContext.fill(); + } + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 2][6]); + this.drawingContext.stroke(); + } + } + } else if (shapeKind === constants.TRIANGLE_STRIP) { + for (i = 0; i + 1 < numVerts; i++) { + v = vertices[i]; + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(vertices[i + 1][0], vertices[i + 1][1]); + this.drawingContext.lineTo(v[0], v[1]); + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 1][6]); + } + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 1][5]); + } + if (i + 2 < numVerts) { + this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]); + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 2][6]); + } + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 2][5]); + } + } + this._doFillStrokeClose(closeShape); + } + } else if (shapeKind === constants.TRIANGLE_FAN) { + if (numVerts > 2) { + // For performance reasons, try to batch as many of the + // fill and stroke calls as possible. + if (!this._clipping) this.drawingContext.beginPath(); + for (i = 2; i < numVerts; i++) { + v = vertices[i]; + this.drawingContext.moveTo(vertices[0][0], vertices[0][1]); + this.drawingContext.lineTo(vertices[i - 1][0], vertices[i - 1][1]); + this.drawingContext.lineTo(v[0], v[1]); + this.drawingContext.lineTo(vertices[0][0], vertices[0][1]); + // If the next colour is going to be different, stroke / fill now + if (i < numVerts - 1) { + if (this._doFill && v[5] !== vertices[i + 1][5] || this._doStroke && v[6] !== vertices[i + 1][6]) { + if (!this._clipping && this._doFill) { + this._pInst.fill(v[5]); + this.drawingContext.fill(); + this._pInst.fill(vertices[i + 1][5]); + } + if (!this._clipping && this._doStroke) { + this._pInst.stroke(v[6]); + this.drawingContext.stroke(); + this._pInst.stroke(vertices[i + 1][6]); + } + this.drawingContext.closePath(); + if (!this._clipping) this.drawingContext.beginPath(); // Begin the next one + } + } + } + this._doFillStrokeClose(closeShape); + } + } else if (shapeKind === constants.QUADS) { + for (i = 0; i + 3 < numVerts; i += 4) { + v = vertices[i]; + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(v[0], v[1]); + for (j = 1; j < 4; j++) { + this.drawingContext.lineTo(vertices[i + j][0], vertices[i + j][1]); + } + this.drawingContext.lineTo(v[0], v[1]); + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 3][5]); + } + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 3][6]); + } + this._doFillStrokeClose(closeShape); + } + } else if (shapeKind === constants.QUAD_STRIP) { + if (numVerts > 3) { + for (i = 0; i + 1 < numVerts; i += 2) { + v = vertices[i]; + if (!this._clipping) this.drawingContext.beginPath(); + if (i + 3 < numVerts) { + this.drawingContext.moveTo(vertices[i + 2][0], vertices[i + 2][1]); + this.drawingContext.lineTo(v[0], v[1]); + this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + this.drawingContext.lineTo(vertices[i + 3][0], vertices[i + 3][1]); + if (!this._clipping && this._doFill) { + this._pInst.fill(vertices[i + 3][5]); + } + if (!this._clipping && this._doStroke) { + this._pInst.stroke(vertices[i + 3][6]); + } + } else { + this.drawingContext.moveTo(v[0], v[1]); + this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); + } + this._doFillStrokeClose(closeShape); + } + } + } else { + if (!this._clipping) this.drawingContext.beginPath(); + this.drawingContext.moveTo(vertices[0][0], vertices[0][1]); + for (i = 1; i < numVerts; i++) { + v = vertices[i]; + if (v.isVert) { + if (v.moveTo) { + if (closeShape) this.drawingContext.closePath(); + this.drawingContext.moveTo(v[0], v[1]); + } else { + this.drawingContext.lineTo(v[0], v[1]); + } + } + } + this._doFillStrokeClose(closeShape); + } + } + isCurve = false; + isBezier = false; + isQuadratic = false; + isContour = false; + if (closeShape) { + vertices.pop(); + } + return this; + } ////////////////////////////////////////////// + // SHAPE | Attributes + ////////////////////////////////////////////// + + }, + { + key: 'strokeCap', + value: function strokeCap(cap) { + if (cap === constants.ROUND || cap === constants.SQUARE || cap === constants.PROJECT) { + this.drawingContext.lineCap = cap; + } + return this; + } + }, + { + key: 'strokeJoin', + value: function strokeJoin(join) { + if (join === constants.ROUND || join === constants.BEVEL || join === constants.MITER) { + this.drawingContext.lineJoin = join; + } + return this; + } + }, + { + key: 'strokeWeight', + value: function strokeWeight(w) { + if (typeof w === 'undefined' || w === 0) { + // hack because lineWidth 0 doesn't work + this.drawingContext.lineWidth = 0.0001; + } else { + this.drawingContext.lineWidth = w; + } + return this; + } + }, + { + key: '_getFill', + value: function _getFill() { + if (!this._cachedFillStyle) { + this._cachedFillStyle = this.drawingContext.fillStyle; + } + return this._cachedFillStyle; + } + }, + { + key: '_setFill', + value: function _setFill(fillStyle) { + if (fillStyle !== this._cachedFillStyle) { + this.drawingContext.fillStyle = fillStyle; + this._cachedFillStyle = fillStyle; + } + } + }, + { + key: '_getStroke', + value: function _getStroke() { + if (!this._cachedStrokeStyle) { + this._cachedStrokeStyle = this.drawingContext.strokeStyle; + } + return this._cachedStrokeStyle; + } + }, + { + key: '_setStroke', + value: function _setStroke(strokeStyle) { + if (strokeStyle !== this._cachedStrokeStyle) { + this.drawingContext.strokeStyle = strokeStyle; + this._cachedStrokeStyle = strokeStyle; + } + } ////////////////////////////////////////////// + // SHAPE | Curves + ////////////////////////////////////////////// + + }, + { + key: 'bezier', + value: function bezier(x1, y1, x2, y2, x3, y3, x4, y4) { + this._pInst.beginShape(); + this._pInst.vertex(x1, y1); + this._pInst.bezierVertex(x2, y2, x3, y3, x4, y4); + this._pInst.endShape(); + return this; + } + }, + { + key: 'curve', + value: function curve(x1, y1, x2, y2, x3, y3, x4, y4) { + this._pInst.beginShape(); + this._pInst.curveVertex(x1, y1); + this._pInst.curveVertex(x2, y2); + this._pInst.curveVertex(x3, y3); + this._pInst.curveVertex(x4, y4); + this._pInst.endShape(); + return this; + } ////////////////////////////////////////////// + // SHAPE | Vertex + ////////////////////////////////////////////// + + }, + { + key: '_doFillStrokeClose', + value: function _doFillStrokeClose(closeShape) { + if (closeShape) { + this.drawingContext.closePath(); + } + if (!this._clipping && this._doFill) { + this.drawingContext.fill(); + } + if (!this._clipping && this._doStroke) { + this.drawingContext.stroke(); + } + } ////////////////////////////////////////////// + // TRANSFORM + ////////////////////////////////////////////// + + }, + { + key: 'applyMatrix', + value: function applyMatrix(a, b, c, d, e, f) { + this.drawingContext.transform(a, b, c, d, e, f); + } + }, + { + key: 'resetMatrix', + value: function resetMatrix() { + this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); + this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); + return this; + } + }, + { + key: 'rotate', + value: function rotate(rad) { + this.drawingContext.rotate(rad); + } + }, + { + key: 'scale', + value: function scale(x, y) { + this.drawingContext.scale(x, y); + return this; + } + }, + { + key: 'translate', + value: function translate(x, y) { + // support passing a vector as the 1st parameter + if (x instanceof _main.default.Vector) { + y = x.y; + x = x.x; + } + this.drawingContext.translate(x, y); + return this; + } ////////////////////////////////////////////// + // TYPOGRAPHY + // + ////////////////////////////////////////////// + + }, + { + key: '_renderText', + value: function _renderText(p, line, x, y, maxY, minY) { + if (y < minY || y >= maxY) { + return; // don't render lines beyond our minY/maxY bounds (see #5785) + } + p.push(); // fix to #803 + if (!this._isOpenType()) { + // a system/browser font + // no stroke unless specified by user + if (this._doStroke && this._strokeSet) { + this.drawingContext.strokeText(line, x, y); + } + if (!this._clipping && this._doFill) { + // if fill hasn't been set by user, use default text fill + if (!this._fillSet) { + this._setFill(constants._DEFAULT_TEXT_FILL); + } + this.drawingContext.fillText(line, x, y); + } + } else { + // an opentype font, let it handle the rendering + this._textFont._renderPath(line, x, y, { + renderer: this + }); + } + p.pop(); + return p; + } + }, + { + key: 'textWidth', + value: function textWidth(s) { + if (this._isOpenType()) { + return this._textFont._textWidth(s, this._textSize); + } + return this.drawingContext.measureText(s).width; + } + }, + { + key: '_applyTextProperties', + value: function _applyTextProperties() { + var font; + var p = this._pInst; + this._setProperty('_textAscent', null); + this._setProperty('_textDescent', null); + font = this._textFont; + if (this._isOpenType()) { + font = this._textFont.font.familyName; + this._setProperty('_textStyle', this._textFont.font.styleName); + } + var fontNameString = font || 'sans-serif'; + if (/\s/.exec(fontNameString)) { + // If the name includes spaces, surround in quotes + fontNameString = '"'.concat(fontNameString, '"'); + } + this.drawingContext.font = ''.concat(this._textStyle || 'normal', ' ').concat(this._textSize || 12, 'px ').concat(fontNameString); + this.drawingContext.textAlign = this._textAlign; + if (this._textBaseline === constants.CENTER) { + this.drawingContext.textBaseline = constants._CTX_MIDDLE; + } else { + this.drawingContext.textBaseline = this._textBaseline; + } + return p; + } ////////////////////////////////////////////// + // STRUCTURE + ////////////////////////////////////////////// + // a push() operation is in progress. + // the renderer should return a 'style' object that it wishes to + // store on the push stack. + // derived renderers should call the base class' push() method + // to fetch the base style object. + + }, + { + key: 'push', + value: function push() { + this.drawingContext.save(); + // get the base renderer style + return _get(_getPrototypeOf(Renderer2D.prototype), 'push', this).call(this); + } // a pop() operation is in progress + // the renderer is passed the 'style' object that it returned + // from its push() method. + // derived renderers should pass this object to their base + // class' pop method + + }, + { + key: 'pop', + value: function pop(style) { + this.drawingContext.restore(); + // Re-cache the fill / stroke state + this._cachedFillStyle = this.drawingContext.fillStyle; + this._cachedStrokeStyle = this.drawingContext.strokeStyle; + _get(_getPrototypeOf(Renderer2D.prototype), 'pop', this).call(this, style); + } + } + ]); + return Renderer2D; + }(_main.default.Renderer); // Fix test + Renderer2D.prototype.text = function (str, x, y, maxWidth, maxHeight) { + var baselineHacked; + // baselineHacked: (HACK) + // A temporary fix to conform to Processing's implementation + // of BASELINE vertical alignment in a bounding box + if (typeof maxWidth !== 'undefined') { + if (this.drawingContext.textBaseline === constants.BASELINE) { + baselineHacked = true; + this.drawingContext.textBaseline = constants.TOP; + } + } + var p = _main.default.Renderer.prototype.text.apply(this, arguments); + if (baselineHacked) { + this.drawingContext.textBaseline = constants.BASELINE; + } + return p; + }; + _main.default.Renderer2D = Renderer2D; + var _default = _main.default.Renderer2D; + exports.default = _default; + }, + { + './constants': 291, + './main': 303, + './p5.Renderer': 306, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.fill': 173, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.function.name': 191, + 'core-js/modules/es.number.to-fixed': 198, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.reflect.get': 208, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 308: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + var _main = _interopRequireDefault(_dereq_('./main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + _main.default.prototype._promisePreloads = [ + /* Example object + { + target: p5.prototype, // The target object to have the method modified + method: 'loadXAsync', // The name of the preload function to wrap + addCallbacks: true, // Whether to automatically handle the p5 callbacks + legacyPreloadSetup: { // Optional object to generate a legacy-style preload + method: 'loadX', // The name of the legacy preload function to generate + createBaseObject: function() { + return {}; + } // An optional function to create the base object for the legacy preload. + } + } + */ + ]; + _main.default.prototype.registerPromisePreload = function (setup) { + _main.default.prototype._promisePreloads.push(setup); + }; + var initialSetupRan = false; + _main.default.prototype._setupPromisePreloads = function () { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this._promisePreloads[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var preloadSetup = _step.value; + var thisValue = this; + var method = preloadSetup.method, + addCallbacks = preloadSetup.addCallbacks, + legacyPreloadSetup = preloadSetup.legacyPreloadSetup; // Get the target object that the preload gets assigned to by default, + // that is the current object. + var target = preloadSetup.target || this; + var sourceFunction = target[method].bind(target); + // If the target is the p5 prototype, then only set it up on the first run per page + if (target === _main.default.prototype) { + if (initialSetupRan) { + continue; + } + thisValue = null; + sourceFunction = target[method]; + } // Replace the original method with a wrapped version + + target[method] = this._wrapPromisePreload(thisValue, sourceFunction, addCallbacks); + // If a legacy preload is required + if (legacyPreloadSetup) { + // What is the name for this legacy preload + var legacyMethod = legacyPreloadSetup.method; + // Wrap the already wrapped Promise-returning method with the legacy setup + target[legacyMethod] = this._legacyPreloadGenerator(thisValue, legacyPreloadSetup, target[method]); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + initialSetupRan = true; + }; + _main.default.prototype._wrapPromisePreload = function (thisValue, fn, addCallbacks) { + var replacementFunction = function replacementFunction() { + var _this = this; + // Uses the current preload counting mechanism for now. + this._incrementPreload(); + // A variable for the callback function if specified + var callback = null; + // A variable for the errorCallback function if specified + var errorCallback = null; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (addCallbacks) { + // Loop from the end of the args array, pulling up to two functions off of + // the end and putting them in fns + for (var i = args.length - 1; i >= 0 && !errorCallback; i--) { + if (typeof args[i] !== 'function') { + break; + } + errorCallback = callback; + callback = args.pop(); + } + } // Call the underlying function and pass it to Promise.resolve, + // so that even if it didn't return a promise we can still + // act on the result as if it did. + + var promise = Promise.resolve(fn.apply(this, args)); + // Add the optional callbacks + if (callback) { + promise.then(callback); + } + if (errorCallback) { + promise.catch(errorCallback); + } // Decrement the preload counter only if the promise resolved + + promise.then(function () { + return _this._decrementPreload(); + }); + // Return the original promise so that neither callback changes the result. + return promise; + }; + if (thisValue) { + replacementFunction = replacementFunction.bind(thisValue); + } + return replacementFunction; + }; + var objectCreator = function objectCreator() { + return { + }; + }; + _main.default.prototype._legacyPreloadGenerator = function (thisValue, legacyPreloadSetup, fn) { + // Create a function that will generate an object before the preload is + // launched. For example, if the object should be an array or be an instance + // of a specific class. + var baseValueGenerator = legacyPreloadSetup.createBaseObject || objectCreator; + var returnedFunction = function returnedFunction() { + var _this2 = this; + // Our then clause needs to run before setup, so we also increment the preload counter + this._incrementPreload(); + // Generate the return value based on the generator. + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + var returnValue = baseValueGenerator.apply(this, args); + // Run the original wrapper + fn.apply(this, args).then(function (data) { + // Copy each key from the resolved value into returnValue + Object.assign(returnValue, data); + // Decrement the preload counter, to allow setup to continue. + _this2._decrementPreload(); + }); + return returnValue; + }; + if (thisValue) { + returnedFunction = returnedFunction.bind(thisValue); + } + return returnedFunction; + }; + }, + { + './main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.assign': 199, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.promise': 206, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 309: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('./main')); + var constants = _interopRequireWildcard(_dereq_('./constants')); + _dereq_('./p5.Graphics'); + _dereq_('./p5.Renderer2D'); + _dereq_('../webgl/p5.RendererGL'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } /** + * @module Rendering + * @submodule Rendering + * @for p5 + */ + + var defaultId = 'defaultCanvas0'; // this gets set again in createCanvas + var defaultClass = 'p5Canvas'; + /** + * Creates a canvas element on the web page. + * + * `createCanvas()` creates the main drawing canvas for a sketch. It should + * only be called once at the beginning of setup(). + * Calling `createCanvas()` more than once causes unpredictable behavior. + * + * The first two parameters, `width` and `height`, are optional. They set the + * dimensions of the canvas and the values of the + * width and height system + * variables. For example, calling `createCanvas(900, 500)` creates a canvas + * that's 900×500 pixels. By default, `width` and `height` are both 100. + * + * The third parameter is also optional. If either of the constants `P2D` or + * `WEBGL` is passed, as in `createCanvas(900, 500, WEBGL)`, then it will set + * the sketch's rendering mode. If an existing + * HTMLCanvasElement + * is passed, as in `createCanvas(900, 500, myCanvas)`, then it will be used + * by the sketch. + * + * The fourth parameter is also optional. If an existing + * HTMLCanvasElement + * is passed, as in `createCanvas(900, 500, WEBGL, myCanvas)`, then it will be + * used by the sketch. + * + * Note: In WebGL mode, the canvas will use a WebGL2 context if it's supported + * by the browser. Check the webglVersion + * system variable to check what version is being used, or call + * `setAttributes({ version: 1 })` to create a WebGL1 context. + * + * @method createCanvas + * @param {Number} [width] width of the canvas. Defaults to 100. + * @param {Number} [height] width of the canvas. Defaults to 100. + * @param {Constant} [renderer] either P2D or WEBGL. Defaults to `P2D`. + * @param {HTMLCanvasElement} [canvas] existing canvas element that should be used for the sketch. + * @return {p5.Renderer} new `p5.Renderer` that holds the canvas. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw a diagonal line. + * line(0, 0, width, height); + * + * describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 50); + * + * background(200); + * + * // Draw a diagonal line. + * line(0, 0, width, height); + * + * describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); + * } + * + *
        + * + *
        + * + * // Use WebGL mode. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Draw a diagonal line. + * line(-width / 2, -height / 2, width / 2, height / 2); + * + * describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Render object. + * let cnv = createCanvas(50, 50); + * + * // Position the canvas. + * cnv.position(10, 20); + * + * background(200); + * + * // Draw a diagonal line. + * line(0, 0, width, height); + * + * describe('A diagonal line drawn from top-left to bottom-right on a gray background.'); + * } + * + *
        + */ + /** + * @method createCanvas + * @param {Number} [width] + * @param {Number} [height] + * @param {HTMLCanvasElement} [canvas] + * @return {p5.Renderer} + */ + _main.default.prototype.createCanvas = function (w, h, renderer, canvas) { + _main.default._validateParameters('createCanvas', arguments); + //optional: renderer, otherwise defaults to p2d + var r; + if (arguments[2] instanceof HTMLCanvasElement) { + renderer = constants.P2D; + canvas = arguments[2]; + } else { + r = renderer || constants.P2D; + } + var c; + if (canvas) { + c = document.getElementById(defaultId); + if (c) { + c.parentNode.removeChild(c); //replace the existing defaultCanvas + } + c = canvas; + this._defaultGraphicsCreated = false; + } else { + if (r === constants.WEBGL) { + c = document.getElementById(defaultId); + if (c) { + //if defaultCanvas already exists + c.parentNode.removeChild(c); //replace the existing defaultCanvas + var thisRenderer = this._renderer; + this._elements = this._elements.filter(function (e) { + return e !== thisRenderer; + }); + } + c = document.createElement('canvas'); + c.id = defaultId; + c.classList.add(defaultClass); + } else { + if (!this._defaultGraphicsCreated) { + if (canvas) { + c = canvas; + } else { + c = document.createElement('canvas'); + } + var i = 0; + while (document.getElementById('defaultCanvas'.concat(i))) { + i++; + } + defaultId = 'defaultCanvas'.concat(i); + c.id = defaultId; + c.classList.add(defaultClass); + } else { + // resize the default canvas if new one is created + c = this.canvas; + } + } // set to invisible if still in setup (to prevent flashing with manipulate) + + if (!this._setupDone) { + c.dataset.hidden = true; // tag to show later + c.style.visibility = 'hidden'; + } + if (this._userNode) { + // user input node case + this._userNode.appendChild(c); + } else { + //create main element + if (document.getElementsByTagName('main').length === 0) { + var m = document.createElement('main'); + document.body.appendChild(m); + } //append canvas to main + + document.getElementsByTagName('main') [0].appendChild(c); + } + } // Init our graphics renderer + //webgl mode + + if (r === constants.WEBGL) { + this._setProperty('_renderer', new _main.default.RendererGL(c, this, true)); + this._elements.push(this._renderer); + var dimensions = this._renderer._adjustDimensions(w, h); + w = dimensions.adjustedWidth; + h = dimensions.adjustedHeight; + } else { + //P2D mode + if (!this._defaultGraphicsCreated) { + this._setProperty('_renderer', new _main.default.Renderer2D(c, this, true)); + this._defaultGraphicsCreated = true; + this._elements.push(this._renderer); + } + } + this._renderer.resize(w, h); + this._renderer._applyDefaults(); + return this._renderer; + }; + /** + * Resizes the canvas to a given width and height. + * + * `resizeCanvas()` immediately clears the canvas and calls + * redraw(). It's common to call `resizeCanvas()` + * within the body of windowResized() like + * so: + * + * ```js + * function windowResized() { + * resizeCanvas(windowWidth, windowHeight); + * } + * ``` + * + * The first two parameters, `width` and `height`, set the dimensions of the + * canvas. They also the values of the width and + * height system variables. For example, calling + * `resizeCanvas(300, 500)` resizes the canvas to 300×500 pixels, then sets + * width to 300 and + * height 500. + * + * The third parameter, `noRedraw`, is optional. If `true` is passed, as in + * `resizeCanvas(300, 500, true)`, then the canvas will be canvas to 300×500 + * pixels but the redraw() function won't be called + * immediately. By default, redraw() is called + * immediately when `resizeCanvas()` finishes executing. + * + * @method resizeCanvas + * @param {Number} width width of the canvas. + * @param {Number} height height of the canvas. + * @param {Boolean} [noRedraw] whether to delay calling + * redraw(). Defaults + * to `false`. + * + * @example + *
        + * + * // Double-click to resize the canvas. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A white circle drawn on a gray background. The canvas shrinks by half the first time the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw a circle at the center of the canvas. + * circle(width / 2, height / 2, 20); + * } + * + * // Resize the canvas when the user double-clicks. + * function doubleClicked() { + * resizeCanvas(50, 50); + * } + * + *
        + * + *
        + * + * // Resize the web browser to change the canvas size. + * + * function setup() { + * createCanvas(windowWidth, windowHeight); + * + * describe('A white circle drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Draw a circle at the center of the canvas. + * circle(width / 2, height / 2, 20); + * } + * + * // Always resize the canvas to fill the browser window. + * function windowResized() { + * resizeCanvas(windowWidth, windowHeight); + * } + * + *
        + */ + _main.default.prototype.resizeCanvas = function (w, h, noRedraw) { + _main.default._validateParameters('resizeCanvas', arguments); + if (this._renderer) { + // save canvas properties + var props = { + }; + for (var key in this.drawingContext) { + var val = this.drawingContext[key]; + if (_typeof(val) !== 'object' && typeof val !== 'function') { + props[key] = val; + } + } + if (this._renderer instanceof _main.default.RendererGL) { + var dimensions = this._renderer._adjustDimensions(w, h); + w = dimensions.adjustedWidth; + h = dimensions.adjustedHeight; + } + this.width = w; + this.height = h; + // Make sure width and height are updated before the renderer resizes so + // that framebuffers updated from the resize read the correct size + this._renderer.resize(w, h); + // reset canvas properties + for (var savedKey in props) { + try { + this.drawingContext[savedKey] = props[savedKey]; + } catch (err) { + // ignore read-only property errors + } + } + if (!noRedraw) { + this.redraw(); + } + } //accessible Outputs + + if (this._addAccsOutput()) { + this._updateAccsOutput(); + } + }; + /** + * Removes the default canvas. + * + * By default, a 100×100 pixels canvas is created without needing to call + * createCanvas(). `noCanvas()` removes the + * default canvas for sketches that don't need it. + * + * @method noCanvas + * + * @example + *
        + * + * function setup() { + * noCanvas(); + * } + * + *
        + */ + _main.default.prototype.noCanvas = function () { + if (this.canvas) { + this.canvas.parentNode.removeChild(this.canvas); + } + }; + /** + * Creates a p5.Graphics object. + * + * `createGraphics()` creates an offscreen drawing canvas (graphics buffer) + * and returns it as a p5.Graphics object. Drawing + * to a separate graphics buffer can be helpful for performance and for + * organizing code. + * + * The first two parameters, `width` and `height`, are optional. They set the + * dimensions of the p5.Graphics object. For + * example, calling `createGraphics(900, 500)` creates a graphics buffer + * that's 900×500 pixels. + * + * The third parameter is also optional. If either of the constants `P2D` or + * `WEBGL` is passed, as in `createGraphics(900, 500, WEBGL)`, then it will set + * the p5.Graphics object's rendering mode. If an + * existing + * HTMLCanvasElement + * is passed, as in `createGraphics(900, 500, myCanvas)`, then it will be used + * by the graphics buffer. + * + * The fourth parameter is also optional. If an existing + * HTMLCanvasElement + * is passed, as in `createGraphics(900, 500, WEBGL, myCanvas)`, then it will be + * used by the graphics buffer. + * + * Note: In WebGL mode, the p5.Graphics object + * will use a WebGL2 context if it's supported by the browser. Check the + * webglVersion system variable to check what + * version is being used, or call `setAttributes({ version: 1 })` to create a + * WebGL1 context. + * + * @method createGraphics + * @param {Number} width width of the graphics buffer. + * @param {Number} height height of the graphics buffer. + * @param {Constant} [renderer] either P2D or WEBGL. Defaults to P2D. + * @param {HTMLCanvasElement} [canvas] existing canvas element that should be + * used for the graphics buffer.. + * @return {p5.Graphics} new graphics buffer. + * + * @example + *
        + * + * // Double-click to draw the contents of the graphics buffer. + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create the p5.Graphics object. + * pg = createGraphics(50, 50); + * + * // Draw to the graphics buffer. + * pg.background(100); + * pg.circle(pg.width / 2, pg.height / 2, 20); + * + * describe('A gray square. A smaller, darker square with a white circle at its center appears when the user double-clicks.'); + * } + * + * // Display the graphics buffer when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * image(pg, 25, 25); + * } + * } + * + *
        + * + *
        + * + * // Double-click to draw the contents of the graphics buffer. + * + * let pg; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create the p5.Graphics object in WebGL mode. + * pg = createGraphics(50, 50, WEBGL); + * + * // Draw to the graphics buffer. + * pg.background(100); + * pg.lights(); + * pg.noStroke(); + * pg.rotateX(QUARTER_PI); + * pg.rotateY(QUARTER_PI); + * pg.torus(15, 5); + * + * describe('A gray square. A smaller, darker square with a white torus at its center appears when the user double-clicks.'); + * } + * + * // Display the graphics buffer when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * image(pg, 25, 25); + * } + * } + * + *
        + */ + /** + * @method createGraphics + * @param {Number} width + * @param {Number} height + * @param {HTMLCanvasElement} [canvas] + * @return {p5.Graphics} + */ + _main.default.prototype.createGraphics = function (w, h) { + for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } /** + * args[0] is expected to be renderer + * args[1] is expected to be canvas + */ + + if (args[0] instanceof HTMLCanvasElement) { + args[1] = args[0]; + args[0] = constants.P2D; + } + _main.default._validateParameters('createGraphics', arguments); + return new _main.default.Graphics(w, h, args[0], this, args[1]); + }; + /** + * Creates and a new p5.Framebuffer object. + * + * p5.Framebuffer objects are separate drawing + * surfaces that can be used as textures in WebGL mode. They're similar to + * p5.Graphics objects and generally run much + * faster when used as textures. + * + * The parameter, `options`, is optional. An object can be passed to configure + * the p5.Framebuffer object. The available + * properties are: + * + * - `format`: data format of the texture, either `UNSIGNED_BYTE`, `FLOAT`, or `HALF_FLOAT`. Default is `UNSIGNED_BYTE`. + * - `channels`: whether to store `RGB` or `RGBA` color channels. Default is to match the main canvas which is `RGBA`. + * - `depth`: whether to include a depth buffer. Default is `true`. + * - `depthFormat`: data format of depth information, either `UNSIGNED_INT` or `FLOAT`. Default is `FLOAT`. + * - `stencil`: whether to include a stencil buffer for masking. `depth` must be `true` for this feature to work. Defaults to the value of `depth` which is `true`. + * - `antialias`: whether to perform anti-aliasing. If set to `true`, as in `{ antialias: true }`, 2 samples will be used by default. The number of samples can also be set, as in `{ antialias: 4 }`. Default is to match setAttributes() which is `false` (`true` in Safari). + * - `width`: width of the p5.Framebuffer object. Default is to always match the main canvas width. + * - `height`: height of the p5.Framebuffer object. Default is to always match the main canvas height. + * - `density`: pixel density of the p5.Framebuffer object. Default is to always match the main canvas pixel density. + * - `textureFiltering`: how to read values from the p5.Framebuffer object. Either `LINEAR` (nearby pixels will be interpolated) or `NEAREST` (no interpolation). Generally, use `LINEAR` when using the texture as an image and `NEAREST` if reading the texture as data. Default is `LINEAR`. + * + * If the `width`, `height`, or `density` attributes are set, they won't automatically match the main canvas and must be changed manually. + * + * Note: `createFramebuffer()` can only be used in WebGL mode. + * + * @method createFramebuffer + * @param {Object} [options] configuration options. + * @return {p5.Framebuffer} new framebuffer. + * + * @example + *
        + * + * let myBuffer; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * describe('A grid of white toruses rotating against a dark gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Start drawing to the p5.Framebuffer object. + * myBuffer.begin(); + * + * // Clear the drawing surface. + * clear(); + * + * // Turn on the lights. + * lights(); + * + * // Rotate the coordinate system. + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * + * // Style the torus. + * noStroke(); + * + * // Draw the torus. + * torus(20); + * + * // Stop drawing to the p5.Framebuffer object. + * myBuffer.end(); + * + * // Iterate from left to right. + * for (let x = -50; x < 50; x += 25) { + * // Iterate from top to bottom. + * for (let y = -50; y < 50; y += 25) { + * // Draw the p5.Framebuffer object to the canvas. + * image(myBuffer, x, y, 25, 25); + * } + * } + * } + * + *
        + * + *
        + * + * let myBuffer; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create an options object. + * let options = { width: 25, height: 25 }; + * + * // Create a p5.Framebuffer object. + * // Use options for configuration. + * myBuffer = createFramebuffer(options); + * + * describe('A grid of white toruses rotating against a dark gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Start drawing to the p5.Framebuffer object. + * myBuffer.begin(); + * + * // Clear the drawing surface. + * clear(); + * + * // Turn on the lights. + * lights(); + * + * // Rotate the coordinate system. + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * + * // Style the torus. + * noStroke(); + * + * // Draw the torus. + * torus(5, 2.5); + * + * // Stop drawing to the p5.Framebuffer object. + * myBuffer.end(); + * + * // Iterate from left to right. + * for (let x = -50; x < 50; x += 25) { + * // Iterate from top to bottom. + * for (let y = -50; y < 50; y += 25) { + * // Draw the p5.Framebuffer object to the canvas. + * image(myBuffer, x, y); + * } + * } + * } + * + *
        + */ + _main.default.prototype.createFramebuffer = function (options) { + return new _main.default.Framebuffer(this, options); + }; + /** + * Clears the depth buffer in WebGL mode. + * + * `clearDepth()` clears information about how far objects are from the camera + * in 3D space. This information is stored in an object called the + * *depth buffer*. Clearing the depth buffer ensures new objects aren't drawn + * behind old ones. Doing so can be useful for feedback effects in which the + * previous frame serves as the background for the current frame. + * + * The parameter, `depth`, is optional. If a number is passed, as in + * `clearDepth(0.5)`, it determines the range of objects to clear from the + * depth buffer. 0 doesn't clear any depth information, 0.5 clears depth + * information halfway between the near and far clipping planes, and 1 clears + * depth information all the way to the far clipping plane. By default, + * `depth` is 1. + * + * Note: `clearDepth()` can only be used in WebGL mode. + * + * @method clearDepth + * @param {Number} [depth] amount of the depth buffer to clear between 0 + * (none) and 1 (far clipping plane). Defaults to 1. + * + * @example + *
        + * + * let previous; + * let current; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the p5.Framebuffer objects. + * prev = createFramebuffer({ format: FLOAT }); + * current = createFramebuffer({ format: FLOAT }); + * + * describe( + * 'A multicolor box drifts from side to side on a white background. It leaves a trail that fades over time.' + * ); + * } + * + * function draw() { + * // Set the previous p5.Framebuffer to the + * // current one so it can be used as a texture. + * previous = current; + * + * // Start drawing to the current p5.Framebuffer. + * current.begin(); + * + * // Paint the background. + * background(255); + * + * // Draw the previous p5.Framebuffer. + * // Clear the depth buffer so the previous + * // frame doesn't block the current one. + * push(); + * tint(255, 250); + * image(previous, -50, -50); + * clearDepth(); + * pop(); + * + * // Draw the box on top of the previous frame. + * push(); + * let x = 25 * sin(frameCount * 0.01); + * let y = 25 * sin(frameCount * 0.02); + * translate(x, y, 0); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * normalMaterial(); + * box(12); + * pop(); + * + * // Stop drawing to the current p5.Framebuffer. + * current.end(); + * + * // Display the current p5.Framebuffer. + * image(current, -50, -50); + * } + * + *
        + */ + _main.default.prototype.clearDepth = function (depth) { + this._assert3d('clearDepth'); + this._renderer.clearDepth(depth); + }; + /** + * Sets the way colors blend when added to the canvas. + * + * By default, drawing with a solid color paints over the current pixel values + * on the canvas. `blendMode()` offers many options for blending colors. + * + * Shapes, images, and text can be used as sources for drawing to the canvas. + * A source pixel changes the color of the canvas pixel where it's drawn. The + * final color results from blending the source pixel's color with the canvas + * pixel's color. RGB color values from the source and canvas pixels are + * compared, added, subtracted, multiplied, and divided to create different + * effects. Red values with red values, greens with greens, and blues with + * blues. + * + * The parameter, `mode`, sets the blend mode. For example, calling + * `blendMode(ADD)` sets the blend mode to `ADD`. The following blend modes + * are available in both 2D and WebGL mode: + * + * - `BLEND`: color values from the source overwrite the canvas. This is the default mode. + * - `ADD`: color values from the source are added to values from the canvas. + * - `DARKEST`: keeps the darkest color value. + * - `LIGHTEST`: keeps the lightest color value. + * - `EXCLUSION`: similar to `DIFFERENCE` but with less contrast. + * - `MULTIPLY`: color values from the source are multiplied with values from the canvas. The result is always darker. + * - `SCREEN`: all color values are inverted, then multiplied, then inverted again. The result is always lighter. (Opposite of `MULTIPLY`) + * - `REPLACE`: the last source drawn completely replaces the rest of the canvas. + * - `REMOVE`: overlapping pixels are removed by making them completely transparent. + * + * The following blend modes are only available in 2D mode: + * + * - `DIFFERENCE`: color values from the source are subtracted from the values from the canvas. If the difference is a negative number, it's made positive. + * - `OVERLAY`: combines `MULTIPLY` and `SCREEN`. Dark values in the canvas get darker and light values get lighter. + * - `HARD_LIGHT`: combines `MULTIPLY` and `SCREEN`. Dark values in the source get darker and light values get lighter. + * - `SOFT_LIGHT`: a softer version of `HARD_LIGHT`. + * - `DODGE`: lightens light tones and increases contrast. Divides the canvas color values by the inverted color values from the source. + * - `BURN`: darkens dark tones and increases contrast. Divides the source color values by the inverted color values from the canvas, then inverts the result. + * + * The following blend modes are only available in WebGL mode: + * + * - `SUBTRACT`: RGB values from the source are subtracted from the values from the canvas. If the difference is a negative number, it's made positive. Alpha (transparency) values from the source and canvas are added. + * + * @method blendMode + * @param {Constant} mode blend mode to set. + * either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, + * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, + * SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use the default blend mode. + * blendMode(BLEND); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A blue line and a red line form an X on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(ADD); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A faint blue line and a faint red line form an X on a gray background. The area where they overlap is faint magenta.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(DARKEST); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A blue line and a red line form an X on a gray background. The area where they overlap is black.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(LIGHTEST); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A faint blue line and a faint red line form an X on a gray background. The area where they overlap is faint magenta.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(EXCLUSION); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A yellow line and a cyan line form an X on a gray background. The area where they overlap is green.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(MULTIPLY); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A blue line and a red line form an X on a gray background. The area where they overlap is black.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(SCREEN); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A faint blue line and a faint red line form an X on a gray background. The area where they overlap is faint magenta.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(REPLACE); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A diagonal red line.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(REMOVE); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('The silhouette of an X is missing from a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(DIFFERENCE); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A yellow line and a cyan line form an X on a gray background. The area where they overlap is green.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(OVERLAY); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A faint blue line and a faint red line form an X on a gray background. The area where they overlap is bright magenta.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(HARD_LIGHT); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A blue line and a red line form an X on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(SOFT_LIGHT); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A faint blue line and a faint red line form an X on a gray background. The area where they overlap is violet.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(DODGE); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A faint blue line and a faint red line form an X on a gray background. The area where they overlap is faint violet.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(BURN); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A blue line and a red line form an X on a gray background. The area where they overlap is black.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the blend mode. + * blendMode(SUBTRACT); + * + * // Style the lines. + * strokeWeight(30); + * + * // Draw the blue line. + * stroke('blue'); + * line(25, 25, 75, 75); + * + * // Draw the red line. + * stroke('red'); + * line(75, 25, 25, 75); + * + * describe('A yellow line and a turquoise line form an X on a gray background. The area where they overlap is green.'); + * } + * + *
        + */ + _main.default.prototype.blendMode = function (mode) { + _main.default._validateParameters('blendMode', arguments); + if (mode === constants.NORMAL) { + // Warning added 3/26/19, can be deleted in future (1.0 release?) + console.warn('NORMAL has been deprecated for use in blendMode. defaulting to BLEND instead.'); + mode = constants.BLEND; + } + this._renderer.blendMode(mode); + }; + /** + * A system variable that provides direct access to the sketch's + * `<canvas>` element. + * + * The `<canvas>` element provides many specialized features that aren't + * included in the p5.js library. The `drawingContext` system variable + * provides access to these features by exposing the sketch's + * CanvasRenderingContext2D + * object. + * + * @property drawingContext + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the circle using shadows. + * drawingContext.shadowOffsetX = 5; + * drawingContext.shadowOffsetY = -5; + * drawingContext.shadowBlur = 10; + * drawingContext.shadowColor = 'black'; + * + * // Draw the circle. + * circle(50, 50, 40); + * + * describe("A white circle on a gray background. The circle's edges are shadowy."); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background('skyblue'); + * + * // Style the circle using a color gradient. + * let myGradient = drawingContext.createRadialGradient(50, 50, 3, 50, 50, 40); + * myGradient.addColorStop(0, 'yellow'); + * myGradient.addColorStop(0.6, 'orangered'); + * myGradient.addColorStop(1, 'yellow'); + * drawingContext.fillStyle = myGradient; + * drawingContext.strokeStyle = 'rgba(0, 0, 0, 0)'; + * + * // Draw the circle. + * circle(50, 50, 40); + * + * describe('A fiery sun drawn on a light blue background.'); + * } + * + *
        + */ + var _default = _main.default; + exports.default = _default; + }, + { + '../webgl/p5.RendererGL': 360, + './constants': 291, + './main': 303, + './p5.Graphics': 305, + './p5.Renderer2D': 307, + 'core-js/modules/es.array.filter': 174, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 310: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.slice'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../main')); + var constants = _interopRequireWildcard(_dereq_('../constants')); + var _helpers = _interopRequireDefault(_dereq_('../helpers')); + _dereq_('../friendly_errors/fes_core'); + _dereq_('../friendly_errors/file_errors'); + _dereq_('../friendly_errors/validate_params'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } /** + * @module Shape + * @submodule 2D Primitives + * @for p5 + * @requires core + * @requires constants + */ + /** + * This function does 3 things: + * + * 1. Bounds the desired start/stop angles for an arc (in radians) so that: + * + * 0 <= start < TWO_PI ; start <= stop < start + TWO_PI + * + * This means that the arc rendering functions don't have to be concerned + * with what happens if stop is smaller than start, or if the arc 'goes + * round more than once', etc.: they can just start at start and increase + * until stop and the correct arc will be drawn. + * + * 2. Optionally adjusts the angles within each quadrant to counter the naive + * scaling of the underlying ellipse up from the unit circle. Without + * this, the angles become arbitrary when width != height: 45 degrees + * might be drawn at 5 degrees on a 'wide' ellipse, or at 85 degrees on + * a 'tall' ellipse. + * + * 3. Flags up when start and stop correspond to the same place on the + * underlying ellipse. This is useful if you want to do something special + * there (like rendering a whole ellipse instead). + */ + + _main.default.prototype._normalizeArcAngles = function (start, stop, width, height, correctForScaling) { + var epsilon = 0.00001; // Smallest visible angle on displays up to 4K. + var separation; + // The order of the steps is important here: each one builds upon the + // adjustments made in the steps that precede it. + // Constrain both start and stop to [0,TWO_PI). + start = start - constants.TWO_PI * Math.floor(start / constants.TWO_PI); + stop = stop - constants.TWO_PI * Math.floor(stop / constants.TWO_PI); + // Get the angular separation between the requested start and stop points. + // + // Technically this separation only matches what gets drawn if + // correctForScaling is enabled. We could add a more complicated calculation + // for when the scaling is uncorrected (in which case the drawn points could + // end up pushed together or pulled apart quite dramatically relative to what + // was requested), but it would make things more opaque for little practical + // benefit. + // + // (If you do disable correctForScaling and find that correspondToSamePoint + // is set too aggressively, the easiest thing to do is probably to just make + // epsilon smaller...) + separation = Math.min(Math.abs(start - stop), constants.TWO_PI - Math.abs(start - stop)); + // Optionally adjust the angles to counter linear scaling. + if (correctForScaling) { + if (start <= constants.HALF_PI) { + start = Math.atan(width / height * Math.tan(start)); + } else if (start > constants.HALF_PI && start <= 3 * constants.HALF_PI) { + start = Math.atan(width / height * Math.tan(start)) + constants.PI; + } else { + start = Math.atan(width / height * Math.tan(start)) + constants.TWO_PI; + } + if (stop <= constants.HALF_PI) { + stop = Math.atan(width / height * Math.tan(stop)); + } else if (stop > constants.HALF_PI && stop <= 3 * constants.HALF_PI) { + stop = Math.atan(width / height * Math.tan(stop)) + constants.PI; + } else { + stop = Math.atan(width / height * Math.tan(stop)) + constants.TWO_PI; + } + } // Ensure that start <= stop < start + TWO_PI. + + if (start > stop) { + stop += constants.TWO_PI; + } + return { + start: start, + stop: stop, + correspondToSamePoint: separation < epsilon + }; + }; + /** + * Draws an arc. + * + * An arc is a section of an ellipse defined by the `x`, `y`, `w`, and + * `h` parameters. `x` and `y` set the location of the arc's center. `w` and + * `h` set the arc's width and height. See + * ellipse() and + * ellipseMode() for more details. + * + * The fifth and sixth parameters, `start` and `stop`, set the angles + * between which to draw the arc. Arcs are always drawn clockwise from + * `start` to `stop`. Angles are always given in radians. + * + * The seventh parameter, `mode`, is optional. It determines the arc's fill + * style. The fill modes are a semi-circle (`OPEN`), a closed semi-circle + * (`CHORD`), or a closed pie segment (`PIE`). + * + * The eighth parameter, `detail`, is also optional. It determines how many + * vertices are used to draw the arc in WebGL mode. The default value is 25. + * + * @method arc + * @param {Number} x x-coordinate of the arc's ellipse. + * @param {Number} y y-coordinate of the arc's ellipse. + * @param {Number} w width of the arc's ellipse by default. + * @param {Number} h height of the arc's ellipse by default. + * @param {Number} start angle to start the arc, specified in radians. + * @param {Number} stop angle to stop the arc, specified in radians. + * @param {Constant} [mode] optional parameter to determine the way of drawing + * the arc. either CHORD, PIE, or OPEN. + * @param {Integer} [detail] optional parameter for WebGL mode only. This is to + * specify the number of vertices that makes up the + * perimeter of the arc. Default value is 25. Won't + * draw a stroke for a detail of more than 50. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * arc(50, 50, 80, 80, 0, PI + HALF_PI); + * + * describe('A white circle on a gray canvas. The top-right quarter of the circle is missing.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * arc(50, 50, 80, 40, 0, PI + HALF_PI); + * + * describe('A white ellipse on a gray canvas. The top-right quarter of the ellipse is missing.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Bottom-right. + * arc(50, 55, 50, 50, 0, HALF_PI); + * + * noFill(); + * + * // Bottom-left. + * arc(50, 55, 60, 60, HALF_PI, PI); + * + * // Top-left. + * arc(50, 55, 70, 70, PI, PI + QUARTER_PI); + * + * // Top-right. + * arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI); + * + * describe( + * 'A shattered outline of an circle with a quarter of a white circle at the bottom-right.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Default fill mode. + * arc(50, 50, 80, 80, 0, PI + QUARTER_PI); + * + * describe('A white circle with the top-right third missing. The bottom is outlined in black.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // OPEN fill mode. + * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN); + * + * describe( + * 'A white circle missing a section from the top-right. The bottom is outlined in black.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // CHORD fill mode. + * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD); + * + * describe('A white circle with a black outline missing a section from the top-right.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // PIE fill mode. + * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE); + * + * describe('A white circle with a black outline. The top-right third is missing.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // PIE fill mode. + * arc(0, 0, 80, 80, 0, PI + QUARTER_PI, PIE); + * + * describe('A white circle with a black outline. The top-right third is missing.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // PIE fill mode with 5 vertices. + * arc(0, 0, 80, 80, 0, PI + QUARTER_PI, PIE, 5); + * + * describe('A white circle with a black outline. The top-right third is missing.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A yellow circle on a black background. The circle opens and closes its mouth.'); + * } + * + * function draw() { + * background(0); + * + * // Style the arc. + * noStroke(); + * fill(255, 255, 0); + * + * // Update start and stop angles. + * let biteSize = PI / 16; + * let startAngle = biteSize * sin(frameCount * 0.1) + biteSize; + * let endAngle = TWO_PI - startAngle; + * + * // Draw the arc. + * arc(50, 50, 80, 80, startAngle, endAngle, PIE); + * } + * + *
        + */ + _main.default.prototype.arc = function (x, y, w, h, start, stop, mode, detail) { + _main.default._validateParameters('arc', arguments); + // if the current stroke and fill settings wouldn't result in something + // visible, exit immediately + if (!this._renderer._doStroke && !this._renderer._doFill) { + return this; + } + if (start === stop) { + return this; + } + start = this._toRadians(start); + stop = this._toRadians(stop); + // p5 supports negative width and heights for ellipses + w = Math.abs(w); + h = Math.abs(h); + var vals = _helpers.default.modeAdjust(x, y, w, h, this._renderer._ellipseMode); + var angles = this._normalizeArcAngles(start, stop, vals.w, vals.h, true); + if (angles.correspondToSamePoint) { + // If the arc starts and ends at (near enough) the same place, we choose to + // draw an ellipse instead. This is preferable to faking an ellipse (by + // making stop ever-so-slightly less than start + TWO_PI) because the ends + // join up to each other rather than at a vertex at the centre (leaving + // an unwanted spike in the stroke/fill). + this._renderer.ellipse([vals.x, + vals.y, + vals.w, + vals.h, + detail]); + } else { + this._renderer.arc(vals.x, vals.y, vals.w, vals.h, angles.start, // [0, TWO_PI) + angles.stop, // [start, start + TWO_PI) + mode, detail); + //accessible Outputs + if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { + this._accsOutput('arc', [ + vals.x, + vals.y, + vals.w, + vals.h, + angles.start, + angles.stop, + mode + ]); + } + } + return this; + }; + /** + * Draws an ellipse (oval). + * + * An ellipse is a round shape defined by the `x`, `y`, `w`, and + * `h` parameters. `x` and `y` set the location of its center. `w` and + * `h` set its width and height. See + * ellipseMode() for other ways to set + * its position. + * + * If no height is set, the value of width is used for both the width and + * height. If a negative height or width is specified, the absolute value is + * taken. + * + * The fifth parameter, `detail`, is also optional. It determines how many + * vertices are used to draw the ellipse in WebGL mode. The default value is + * 25. + * + * @method ellipse + * @param {Number} x x-coordinate of the center of the ellipse. + * @param {Number} y y-coordinate of the center of the ellipse. + * @param {Number} w width of the ellipse. + * @param {Number} [h] height of the ellipse. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * ellipse(50, 50, 80, 80); + * + * describe('A white circle on a gray canvas.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * ellipse(50, 50, 80); + * + * describe('A white circle on a gray canvas.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * ellipse(50, 50, 80, 40); + * + * describe('A white ellipse on a gray canvas.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * ellipse(0, 0, 80, 40); + * + * describe('A white ellipse on a gray canvas.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Use 6 vertices. + * ellipse(0, 0, 80, 40, 6); + * + * describe('A white hexagon on a gray canvas.'); + * } + * + *
        + */ + /** + * @method ellipse + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + * @param {Integer} [detail] optional parameter for WebGL mode only. This is to + * specify the number of vertices that makes up the + * perimeter of the ellipse. Default value is 25. Won't + * draw a stroke for a detail of more than 50. + */ + _main.default.prototype.ellipse = function (x, y, w, h, detailX) { + _main.default._validateParameters('ellipse', arguments); + return this._renderEllipse.apply(this, arguments); + }; + /** + * Draws a circle. + * + * A circle is a round shape defined by the `x`, `y`, and `d` + * parameters. `x` and `y` set the location of its center. `d` sets its + * width and height (diameter). Every point on the circle's edge is the + * same distance, `d`, from its center. See + * ellipseMode() for other ways to set + * its position. + * + * @method circle + * @param {Number} x x-coordinate of the center of the circle. + * @param {Number} y y-coordinate of the center of the circle. + * @param {Number} d diameter of the circle. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * circle(50, 50, 25); + * + * describe('A white circle with black outline in the middle of a gray canvas.'); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * circle(0, 0, 25); + * + * describe('A white circle with black outline in the middle of a gray canvas.'); + * } + * + *
        + */ + _main.default.prototype.circle = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('circle', args); + var argss = args.slice(0, 2); + argss.push(args[2], args[2]); + return this._renderEllipse.apply(this, _toConsumableArray(argss)); + }; + // internal method for drawing ellipses (without parameter validation) + _main.default.prototype._renderEllipse = function (x, y, w, h, detailX) { + // if the current stroke and fill settings wouldn't result in something + // visible, exit immediately + if (!this._renderer._doStroke && !this._renderer._doFill) { + return this; + } // p5 supports negative width and heights for rects + + if (w < 0) { + w = Math.abs(w); + } + if (typeof h === 'undefined') { + // Duplicate 3rd argument if only 3 given. + h = w; + } else if (h < 0) { + h = Math.abs(h); + } + var vals = _helpers.default.modeAdjust(x, y, w, h, this._renderer._ellipseMode); + this._renderer.ellipse([vals.x, + vals.y, + vals.w, + vals.h, + detailX]); + //accessible Outputs + if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { + this._accsOutput('ellipse', [ + vals.x, + vals.y, + vals.w, + vals.h + ]); + } + return this; + }; + /** + * Draws a straight line between two points. + * + * A line's default width is one pixel. The version of `line()` with four + * parameters draws the line in 2D. To color a line, use the + * stroke() function. To change its width, use the + * strokeWeight() function. A line + * can't be filled, so the fill() function won't + * affect the line's color. + * + * The version of `line()` with six parameters allows the line to be drawn in + * 3D space. Doing so requires adding the `WEBGL` argument to + * createCanvas(). + * + * @method line + * @param {Number} x1 the x-coordinate of the first point. + * @param {Number} y1 the y-coordinate of the first point. + * @param {Number} x2 the x-coordinate of the second point. + * @param {Number} y2 the y-coordinate of the second point. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * line(30, 20, 85, 75); + * + * describe( + * 'A black line on a gray canvas running from top-center to bottom-right.' + * ); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the line. + * stroke('magenta'); + * strokeWeight(5); + * + * line(30, 20, 85, 75); + * + * describe( + * 'A thick, magenta line on a gray canvas running from top-center to bottom-right.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top. + * line(30, 20, 85, 20); + * + * // Right. + * stroke(126); + * line(85, 20, 85, 75); + * + * // Bottom. + * stroke(255); + * line(85, 75, 30, 75); + * + * describe( + * 'Three lines drawn in grayscale on a gray canvas. They form the top, right, and bottom sides of a square.' + * ); + * } + * + *
        + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * line(-20, -30, 35, 25); + * + * describe( + * 'A black line on a gray canvas running from top-center to bottom-right.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A black line connecting two spheres. The scene spins slowly.'); + * } + * + * function draw() { + * background(200); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Draw a line. + * line(0, 0, 0, 30, 20, -10); + * + * // Draw the center sphere. + * sphere(10); + * + * // Translate to the second point. + * translate(30, 20, -10); + * + * // Draw the bottom-right sphere. + * sphere(10); + * } + * + *
        + * + */ + /** + * @method line + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} z1 the z-coordinate of the first point. + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} z2 the z-coordinate of the second point. + * @chainable + */ + _main.default.prototype.line = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('line', args); + if (this._renderer._doStroke) { + var _this$_renderer; + (_this$_renderer = this._renderer).line.apply(_this$_renderer, args); + } //accessible Outputs + + if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { + this._accsOutput('line', args); + } + return this; + }; + /** + * Draws a single point in space. + * + * A point's default width is one pixel. To color a point, use the + * stroke() function. To change its width, use the + * strokeWeight() function. A point + * can't be filled, so the fill() function won't + * affect the point's color. + * + * The version of `point()` with one parameter allows the point's location to + * be set with its x- and y-coordinates, as in `point(10, 20)`. + * + * The version of `point()` with three parameters allows the point to be drawn + * in 3D space with x-, y-, and z-coordinates, as in `point(10, 20, 30)`. + * Doing so requires adding the `WEBGL` argument to + * createCanvas(). + * + * The version of `point()` with one parameter allows the point's location to + * be set with a p5.Vector object. + * + * @method point + * @param {Number} x the x-coordinate. + * @param {Number} y the y-coordinate. + * @param {Number} [z] the z-coordinate (for WebGL mode). + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top-left. + * point(30, 20); + * + * // Top-right. + * point(85, 20); + * + * // Bottom-right. + * point(85, 75); + * + * // Bottom-left. + * point(30, 75); + * + * describe( + * 'Four small, black points drawn on a gray canvas. The points form the corners of a square.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top-left. + * point(30, 20); + * + * // Top-right. + * point(70, 20); + * + * // Style the next points. + * stroke('purple'); + * strokeWeight(10); + * + * // Bottom-right. + * point(70, 80); + * + * // Bottom-left. + * point(30, 80); + * + * describe( + * 'Four points drawn on a gray canvas. Two are black and two are purple. The points form the corners of a square.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top-left. + * let a = createVector(30, 20); + * point(a); + * + * // Top-right. + * let b = createVector(70, 20); + * point(b); + * + * // Bottom-right. + * let c = createVector(70, 80); + * point(c); + * + * // Bottom-left. + * let d = createVector(30, 80); + * point(d); + * + * describe( + * 'Four small, black points drawn on a gray canvas. The points form the corners of a square.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('Two purple points drawn on a gray canvas.'); + * } + * + * function draw() { + * background(200); + * + * // Style the points. + * stroke('purple'); + * strokeWeight(10); + * + * // Top-left. + * point(-20, -30); + * + * // Bottom-right. + * point(20, 30); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('Two purple points drawn on a gray canvas. The scene spins slowly.'); + * } + * + * function draw() { + * background(200); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Style the points. + * stroke('purple'); + * strokeWeight(10); + * + * // Top-left. + * point(-20, -30, 0); + * + * // Bottom-right. + * point(20, 30, -50); + * } + * + *
        + */ + /** + * @method point + * @param {p5.Vector} coordinateVector the coordinate vector. + * @chainable + */ + _main.default.prototype.point = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('point', args); + if (this._renderer._doStroke) { + if (args.length === 1 && args[0] instanceof _main.default.Vector) { + this._renderer.point.call(this._renderer, args[0].x, args[0].y, args[0].z); + } else { + var _this$_renderer2; + (_this$_renderer2 = this._renderer).point.apply(_this$_renderer2, args); + //accessible Outputs + if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { + this._accsOutput('point', args); + } + } + } + return this; + }; + /** + * Draws a quadrilateral (four-sided shape). + * + * Quadrilaterals include rectangles, squares, rhombuses, and trapezoids. The + * first pair of parameters `(x1, y1)` sets the quad's first point. The next + * three pairs of parameters set the coordinates for its next three points + * `(x2, y2)`, `(x3, y3)`, and `(x4, y4)`. Points should be added in either + * clockwise or counter-clockwise order. + * + * The version of `quad()` with twelve parameters allows the quad to be drawn + * in 3D space. Doing so requires adding the `WEBGL` argument to + * createCanvas(). + * + * The thirteenth and fourteenth parameters are optional. In WebGL mode, they + * set the number of segments used to draw the quadrilateral in the x- and + * y-directions. They're both 25 by default. + * + * @method quad + * @param {Number} x1 the x-coordinate of the first point. + * @param {Number} y1 the y-coordinate of the first point. + * @param {Number} x2 the x-coordinate of the second point. + * @param {Number} y2 the y-coordinate of the second point. + * @param {Number} x3 the x-coordinate of the third point. + * @param {Number} y3 the y-coordinate of the third point. + * @param {Number} x4 the x-coordinate of the fourth point. + * @param {Number} y4 the y-coordinate of the fourth point. + * @param {Integer} [detailX] number of segments in the x-direction. + * @param {Integer} [detailY] number of segments in the y-direction. + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * quad(20, 20, 80, 20, 80, 80, 20, 80); + * + * describe('A white square with a black outline drawn on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * quad(20, 30, 80, 30, 80, 70, 20, 70); + * + * describe('A white rectangle with a black outline drawn on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * quad(50, 62, 86, 50, 50, 38, 14, 50); + * + * describe('A white rhombus with a black outline drawn on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * quad(20, 50, 80, 30, 80, 70, 20, 70); + * + * describe('A white trapezoid with a black outline drawn on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * quad(-30, -30, 30, -30, 30, 30, -30, 30); + * + * describe('A white square with a black outline drawn on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A wavy white surface spins around on gray canvas.'); + * } + * + * function draw() { + * background(200); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Draw the quad. + * quad(-30, -30, 0, 30, -30, 0, 30, 30, 20, -30, 30, -20); + * } + * + *
        + */ + /** + * @method quad + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} z1 the z-coordinate of the first point. + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} z2 the z-coordinate of the second point. + * @param {Number} x3 + * @param {Number} y3 + * @param {Number} z3 the z-coordinate of the third point. + * @param {Number} x4 + * @param {Number} y4 + * @param {Number} z4 the z-coordinate of the fourth point. + * @param {Integer} [detailX] + * @param {Integer} [detailY] + * @chainable + */ + _main.default.prototype.quad = function () { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + _main.default._validateParameters('quad', args); + if (this._renderer._doStroke || this._renderer._doFill) { + if (this._renderer.isP3D && args.length < 12) { + // if 3D and we weren't passed 12 args, assume Z is 0 + this._renderer.quad.call(this._renderer, args[0], args[1], 0, args[2], args[3], 0, args[4], args[5], 0, args[6], args[7], 0, args[8], args[9]); + } else { + var _this$_renderer3; + (_this$_renderer3 = this._renderer).quad.apply(_this$_renderer3, args); + //accessibile outputs + if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { + this._accsOutput('quadrilateral', args); + } + } + } + return this; + }; + /** + * Draws a rectangle. + * + * A rectangle is a four-sided shape defined by the `x`, `y`, `w`, and `h` + * parameters. `x` and `y` set the location of its top-left corner. `w` sets + * its width and `h` sets its height. Every angle in the rectangle measures + * 90˚. See rectMode() for other ways to define + * rectangles. + * + * The version of `rect()` with five parameters creates a rounded rectangle. The + * fifth parameter sets the radius for all four corners. + * + * The version of `rect()` with eight parameters also creates a rounded + * rectangle. Each of the last four parameters set the radius of a corner. The + * radii start with the top-left corner and move clockwise around the + * rectangle. If any of these parameters are omitted, they are set to the + * value of the last radius that was set. + * + * @method rect + * @param {Number} x x-coordinate of the rectangle. + * @param {Number} y y-coordinate of the rectangle. + * @param {Number} w width of the rectangle. + * @param {Number} [h] height of the rectangle. + * @param {Number} [tl] optional radius of top-left corner. + * @param {Number} [tr] optional radius of top-right corner. + * @param {Number} [br] optional radius of bottom-right corner. + * @param {Number} [bl] optional radius of bottom-left corner. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * rect(30, 20, 55, 55); + * + * describe('A white square with a black outline on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * rect(30, 20, 55, 40); + * + * describe('A white rectangle with a black outline on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Give all corners a radius of 20. + * rect(30, 20, 55, 50, 20); + * + * describe('A white rectangle with a black outline and round edges on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Give each corner a unique radius. + * rect(30, 20, 55, 50, 20, 15, 10, 5); + * + * describe('A white rectangle with a black outline and round edges of different radii.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * rect(-20, -30, 55, 55); + * + * describe('A white square with a black outline on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white square spins around on gray canvas.'); + * } + * + * function draw() { + * background(200); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Draw the rectangle. + * rect(-20, -30, 55, 55); + * } + * + *
        + */ + /** + * @method rect + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + * @param {Integer} [detailX] number of segments in the x-direction (for WebGL mode). + * @param {Integer} [detailY] number of segments in the y-direction (for WebGL mode). + * @chainable + */ + _main.default.prototype.rect = function () { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + _main.default._validateParameters('rect', args); + return this._renderRect.apply(this, args); + }; + /** + * Draws a square. + * + * A square is a four-sided shape defined by the `x`, `y`, and `s` + * parameters. `x` and `y` set the location of its top-left corner. `s` sets + * its width and height. Every angle in the square measures 90˚ and all its + * sides are the same length. See rectMode() for + * other ways to define squares. + * + * The version of `square()` with four parameters creates a rounded square. + * The fourth parameter sets the radius for all four corners. + * + * The version of `square()` with seven parameters also creates a rounded + * square. Each of the last four parameters set the radius of a corner. The + * radii start with the top-left corner and move clockwise around the + * square. If any of these parameters are omitted, they are set to the + * value of the last radius that was set. + * + * @method square + * @param {Number} x x-coordinate of the square. + * @param {Number} y y-coordinate of the square. + * @param {Number} s side size of the square. + * @param {Number} [tl] optional radius of top-left corner. + * @param {Number} [tr] optional radius of top-right corner. + * @param {Number} [br] optional radius of bottom-right corner. + * @param {Number} [bl] optional radius of bottom-left corner. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * square(30, 20, 55); + * + * describe('A white square with a black outline in on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Give all corners a radius of 20. + * square(30, 20, 55, 20); + * + * describe( + * 'A white square with a black outline and round edges on a gray canvas.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Give each corner a unique radius. + * square(30, 20, 55, 20, 15, 10, 5); + * + * describe('A white square with a black outline and round edges of different radii.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * square(-20, -30, 55); + * + * describe('A white square with a black outline in on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white square spins around on gray canvas.'); + * } + * + * function draw() { + * background(200); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Draw the square. + * square(-20, -30, 55); + * } + * + *
        + */ + _main.default.prototype.square = function (x, y, s, tl, tr, br, bl) { + _main.default._validateParameters('square', arguments); + // duplicate width for height in case of square + return this._renderRect.call(this, x, y, s, s, tl, tr, br, bl); + }; + // internal method to have renderer draw a rectangle + _main.default.prototype._renderRect = function () { + if (this._renderer._doStroke || this._renderer._doFill) { + // duplicate width for height in case only 3 arguments is provided + if (arguments.length === 3) { + arguments[3] = arguments[2]; + } + var vals = _helpers.default.modeAdjust(arguments[0], arguments[1], arguments[2], arguments[3], this._renderer._rectMode); + var args = [ + vals.x, + vals.y, + vals.w, + vals.h + ]; + // append the additional arguments (either cornder radii, or + // segment details) to the argument list + for (var i = 4; i < arguments.length; i++) { + args[i] = arguments[i]; + } + this._renderer.rect(args); + //accessible outputs + if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { + this._accsOutput('rectangle', [ + vals.x, + vals.y, + vals.w, + vals.h + ]); + } + } + return this; + }; + /** + * Draws a triangle. + * + * A triangle is a three-sided shape defined by three points. The + * first two parameters specify the triangle's first point `(x1, y1)`. The + * middle two parameters specify its second point `(x2, y2)`. And the last two + * parameters specify its third point `(x3, y3)`. + * + * @method triangle + * @param {Number} x1 x-coordinate of the first point. + * @param {Number} y1 y-coordinate of the first point. + * @param {Number} x2 x-coordinate of the second point. + * @param {Number} y2 y-coordinate of the second point. + * @param {Number} x3 x-coordinate of the third point. + * @param {Number} y3 y-coordinate of the third point. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * triangle(30, 75, 58, 20, 86, 75); + * + * describe('A white triangle with a black outline on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * triangle(-20, 25, 8, -30, 36, 25); + * + * describe('A white triangle with a black outline on a gray canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white triangle spins around on a gray canvas.'); + * } + * + * function draw() { + * background(200); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Draw the triangle. + * triangle(-20, 25, 8, -30, 36, 25); + * } + * + *
        + */ + _main.default.prototype.triangle = function () { + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + _main.default._validateParameters('triangle', args); + if (this._renderer._doStroke || this._renderer._doFill) { + this._renderer.triangle(args); + } //accessible outputs + + if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { + this._accsOutput('triangle', args); + } + return this; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../constants': 291, + '../friendly_errors/fes_core': 294, + '../friendly_errors/file_errors': 295, + '../friendly_errors/validate_params': 298, + '../helpers': 299, + '../main': 303, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 311: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../main')); + var constants = _interopRequireWildcard(_dereq_('../constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Shape + * @submodule Attributes + * @for p5 + * @requires core + * @requires constants + */ + /** + * Changes where ellipses, circles, and arcs are drawn. + * + * By default, the first two parameters of + * ellipse(), circle(), + * and arc() + * are the x- and y-coordinates of the shape's center. The next parameters set + * the shape's width and height. This is the same as calling + * `ellipseMode(CENTER)`. + * + * `ellipseMode(RADIUS)` also uses the first two parameters to set the x- and + * y-coordinates of the shape's center. The next parameters are half of the + * shapes's width and height. Calling `ellipse(0, 0, 10, 15)` draws a shape + * with a width of 20 and height of 30. + * + * `ellipseMode(CORNER)` uses the first two parameters as the upper-left + * corner of the shape. The next parameters are its width and height. + * + * `ellipseMode(CORNERS)` uses the first two parameters as the location of one + * corner of the ellipse's bounding box. The next parameters are the location + * of the opposite corner. + * + * The argument passed to `ellipseMode()` must be written in ALL CAPS because + * the constants `CENTER`, `RADIUS`, `CORNER`, and `CORNERS` are defined this + * way. JavaScript is a case-sensitive language. + * + * @method ellipseMode + * @param {Constant} mode either CENTER, RADIUS, CORNER, or CORNERS + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // White ellipse. + * ellipseMode(RADIUS); + * fill(255); + * ellipse(50, 50, 30, 30); + * + * // Gray ellipse. + * ellipseMode(CENTER); + * fill(100); + * ellipse(50, 50, 30, 30); + * + * describe('A white circle with a gray circle at its center. Both circles have black outlines.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // White ellipse. + * ellipseMode(CORNER); + * fill(255); + * ellipse(25, 25, 50, 50); + * + * // Gray ellipse. + * ellipseMode(CORNERS); + * fill(100); + * ellipse(25, 25, 50, 50); + * + * describe('A white circle with a gray circle at its top-left corner. Both circles have black outlines.'); + * } + * + *
        + */ + + _main.default.prototype.ellipseMode = function (m) { + _main.default._validateParameters('ellipseMode', arguments); + if (m === constants.CORNER || m === constants.CORNERS || m === constants.RADIUS || m === constants.CENTER) { + this._renderer._ellipseMode = m; + } + return this; + }; + /** + * Draws certain features with jagged (aliased) edges. + * + * smooth() is active by default. In 2D mode, + * `noSmooth()` is helpful for scaling up images without blurring. The + * functions don't affect shapes or fonts. + * + * In WebGL mode, `noSmooth()` causes all shapes to be drawn with jagged + * (aliased) edges. The functions don't affect images or fonts. + * + * @method noSmooth + * @chainable + * + * @example + *
        + * + * let heart; + * + * // Load a pixelated heart image from an image data string. + * function preload() { + * heart = loadImage('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAEZJREFUGFd9jcsNACAIQ9tB2MeR3YdBMBBq8CIXPi2vBICIiOwkOedatllqWO6Y8yOWoyuNf1GZwgmf+RRG2YXr+xVFmA8HZ9Mx/KGPMtcAAAAASUVORK5CYII='); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Antialiased hearts. + * image(heart, 10, 10); + * image(heart, 20, 10, 16, 16); + * image(heart, 40, 10, 32, 32); + * + * // Aliased hearts. + * noSmooth(); + * image(heart, 10, 60); + * image(heart, 20, 60, 16, 16); + * image(heart, 40, 60, 32, 32); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * circle(0, 0, 80); + * + * describe('A white circle on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Disable smoothing. + * noSmooth(); + * + * background(200); + * + * circle(0, 0, 80); + * + * describe('A pixelated white circle on a gray background.'); + * } + * + *
        + */ + _main.default.prototype.noSmooth = function () { + if (!this._renderer.isP3D) { + if ('imageSmoothingEnabled' in this.drawingContext) { + this.drawingContext.imageSmoothingEnabled = false; + } + } else { + this.setAttributes('antialias', false); + } + return this; + }; + /** + * Changes where rectangles and squares are drawn. + * + * By default, the first two parameters of + * rect() and square(), + * are the x- and y-coordinates of the shape's upper left corner. The next parameters set + * the shape's width and height. This is the same as calling + * `rectMode(CORNER)`. + * + * `rectMode(CORNERS)` also uses the first two parameters as the location of + * one of the corners. The next parameters are the location of the opposite + * corner. This mode only works for rect(). + * + * `rectMode(CENTER)` uses the first two parameters as the x- and + * y-coordinates of the shape's center. The next parameters are its width and + * height. + * + * `rectMode(RADIUS)` also uses the first two parameters as the x- and + * y-coordinates of the shape's center. The next parameters are + * half of the shape's width and height. + * + * The argument passed to `rectMode()` must be written in ALL CAPS because the + * constants `CENTER`, `RADIUS`, `CORNER`, and `CORNERS` are defined this way. + * JavaScript is a case-sensitive language. + * + * @method rectMode + * @param {Constant} mode either CORNER, CORNERS, CENTER, or RADIUS + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * rectMode(CORNER); + * fill(255); + * rect(25, 25, 50, 50); + * + * rectMode(CORNERS); + * fill(100); + * rect(25, 25, 50, 50); + * + * describe('A small gray square drawn at the top-left corner of a white square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * rectMode(RADIUS); + * fill(255); + * rect(50, 50, 30, 30); + * + * rectMode(CENTER); + * fill(100); + * rect(50, 50, 30, 30); + * + * describe('A small gray square drawn at the center of a white square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * rectMode(CORNER); + * fill(255); + * square(25, 25, 50); + * + * describe('A white square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * rectMode(RADIUS); + * fill(255); + * square(50, 50, 30); + * + * rectMode(CENTER); + * fill(100); + * square(50, 50, 30); + * + * describe('A small gray square drawn at the center of a white square.'); + * } + * + *
        + */ + _main.default.prototype.rectMode = function (m) { + _main.default._validateParameters('rectMode', arguments); + if (m === constants.CORNER || m === constants.CORNERS || m === constants.RADIUS || m === constants.CENTER) { + this._renderer._rectMode = m; + } + return this; + }; + /** + * Draws certain features with smooth (antialiased) edges. + * + * `smooth()` is active by default. In 2D mode, + * noSmooth() is helpful for scaling up images + * without blurring. The functions don't affect shapes or fonts. + * + * In WebGL mode, noSmooth() causes all shapes to + * be drawn with jagged (aliased) edges. The functions don't affect images or + * fonts. + * + * @method smooth + * @chainable + * + * @example + *
        + * + * let heart; + * + * // Load a pixelated heart image from an image data string. + * function preload() { + * heart = loadImage('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAEZJREFUGFd9jcsNACAIQ9tB2MeR3YdBMBBq8CIXPi2vBICIiOwkOedatllqWO6Y8yOWoyuNf1GZwgmf+RRG2YXr+xVFmA8HZ9Mx/KGPMtcAAAAASUVORK5CYII='); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Antialiased hearts. + * image(heart, 10, 10); + * image(heart, 20, 10, 16, 16); + * image(heart, 40, 10, 32, 32); + * + * // Aliased hearts. + * noSmooth(); + * image(heart, 10, 60); + * image(heart, 20, 60, 16, 16); + * image(heart, 40, 60, 32, 32); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * circle(0, 0, 80); + * + * describe('A white circle on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Disable smoothing. + * noSmooth(); + * + * background(200); + * + * circle(0, 0, 80); + * + * describe('A pixelated white circle on a gray background.'); + * } + * + *
        + */ + _main.default.prototype.smooth = function () { + this.setAttributes('antialias', true); + if (!this._renderer.isP3D) { + if ('imageSmoothingEnabled' in this.drawingContext) { + this.drawingContext.imageSmoothingEnabled = true; + } + } + return this; + }; + /** + * Sets the style for rendering the ends of lines. + * + * The caps for line endings are either rounded (`ROUND`), squared + * (`SQUARE`), or extended (`PROJECT`). The default cap is `ROUND`. + * + * The argument passed to `strokeCap()` must be written in ALL CAPS because + * the constants `ROUND`, `SQUARE`, and `PROJECT` are defined this way. + * JavaScript is a case-sensitive language. + * + * @method strokeCap + * @param {Constant} cap either ROUND, SQUARE, or PROJECT + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * strokeWeight(12); + * + * // Top. + * strokeCap(ROUND); + * line(20, 30, 80, 30); + * + * // Middle. + * strokeCap(SQUARE); + * line(20, 50, 80, 50); + * + * // Bottom. + * strokeCap(PROJECT); + * line(20, 70, 80, 70); + * + * describe( + * 'Three horizontal lines. The top line has rounded ends, the middle line has squared ends, and the bottom line has longer, squared ends.' + * ); + * } + * + *
        + */ + _main.default.prototype.strokeCap = function (cap) { + _main.default._validateParameters('strokeCap', arguments); + if (cap === constants.ROUND || cap === constants.SQUARE || cap === constants.PROJECT) { + this._renderer.strokeCap(cap); + } + return this; + }; + /** + * Sets the style of the joints that connect line segments. + * + * Joints are either mitered (`MITER`), beveled (`BEVEL`), or rounded + * (`ROUND`). The default joint is `MITER` in 2D mode and `ROUND` in WebGL + * mode. + * + * The argument passed to `strokeJoin()` must be written in ALL CAPS because + * the constants `MITER`, `BEVEL`, and `ROUND` are defined this way. + * JavaScript is a case-sensitive language. + * + * @method strokeJoin + * @param {Constant} join either MITER, BEVEL, or ROUND + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the line. + * noFill(); + * strokeWeight(10); + * strokeJoin(MITER); + * + * // Draw the line. + * beginShape(); + * vertex(35, 20); + * vertex(65, 50); + * vertex(35, 80); + * endShape(); + * + * describe('A right-facing arrowhead shape with a pointed tip in center of canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the line. + * noFill(); + * strokeWeight(10); + * strokeJoin(BEVEL); + * + * // Draw the line. + * beginShape(); + * vertex(35, 20); + * vertex(65, 50); + * vertex(35, 80); + * endShape(); + * + * describe('A right-facing arrowhead shape with a flat tip in center of canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the line. + * noFill(); + * strokeWeight(10); + * strokeJoin(ROUND); + * + * // Draw the line. + * beginShape(); + * vertex(35, 20); + * vertex(65, 50); + * vertex(35, 80); + * endShape(); + * + * describe('A right-facing arrowhead shape with a rounded tip in center of canvas.'); + * } + * + *
        + */ + _main.default.prototype.strokeJoin = function (join) { + _main.default._validateParameters('strokeJoin', arguments); + if (join === constants.ROUND || join === constants.BEVEL || join === constants.MITER) { + this._renderer.strokeJoin(join); + } + return this; + }; + /** + * Sets the width of the stroke used for points, lines, and the outlines of + * shapes. + * + * Note: `strokeWeight()` is affected by transformations, especially calls to + * scale(). + * + * @method strokeWeight + * @param {Number} weight the weight of the stroke (in pixels). + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top. + * line(20, 20, 80, 20); + * + * // Middle. + * strokeWeight(4); + * line(20, 40, 80, 40); + * + * // Bottom. + * strokeWeight(10); + * line(20, 70, 80, 70); + * + * describe('Three horizontal black lines. The top line is thin, the middle is medium, and the bottom is thick.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top. + * line(20, 20, 80, 20); + * + * // Scale by a factor of 5. + * scale(5); + * + * // Bottom. Coordinates are adjusted for scaling. + * line(4, 8, 16, 8); + * + * describe('Two horizontal black lines. The top line is thin and the bottom is five times thicker than the top.'); + * } + * + *
        + */ + _main.default.prototype.strokeWeight = function (w) { + _main.default._validateParameters('strokeWeight', arguments); + this._renderer.strokeWeight(w); + return this; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../constants': 291, + '../main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 312: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../main')); + _dereq_('../friendly_errors/fes_core'); + _dereq_('../friendly_errors/file_errors'); + _dereq_('../friendly_errors/validate_params'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Shape + * @submodule Curves + * @for p5 + * @requires core + */ + /** + * Draws a Bézier curve. + * + * Bézier curves can form shapes and curves that slope gently. They're defined + * by two anchor points and two control points. Bézier curves provide more + * control than the spline curves created with the + * curve() function. + * + * The first two parameters, `x1` and `y1`, set the first anchor point. The + * first anchor point is where the curve starts. + * + * The next four parameters, `x2`, `y2`, `x3`, and `y3`, set the two control + * points. The control points "pull" the curve towards them. + * + * The seventh and eighth parameters, `x4` and `y4`, set the last anchor + * point. The last anchor point is where the curve ends. + * + * Bézier curves can also be drawn in 3D using WebGL mode. The 3D version of + * `bezier()` has twelve arguments because each point has x-, y-, + * and z-coordinates. + * + * @method bezier + * @param {Number} x1 x-coordinate of the first anchor point. + * @param {Number} y1 y-coordinate of the first anchor point. + * @param {Number} x2 x-coordinate of the first control point. + * @param {Number} y2 y-coordinate of the first control point. + * @param {Number} x3 x-coordinate of the second control point. + * @param {Number} y3 y-coordinate of the second control point. + * @param {Number} x4 x-coordinate of the second anchor point. + * @param {Number} y4 y-coordinate of the second anchor point. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw the anchor points in black. + * stroke(0); + * strokeWeight(5); + * point(85, 20); + * point(15, 80); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(10, 10); + * point(90, 90); + * + * // Draw a black bezier curve. + * noFill(); + * stroke(0); + * strokeWeight(1); + * bezier(85, 20, 10, 10, 90, 90, 15, 80); + * + * // Draw red lines from the anchor points to the control points. + * stroke(255, 0, 0); + * line(85, 20, 10, 10); + * line(15, 80, 90, 90); + * + * describe( + * 'A gray square with three curves. A black s-curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' + * ); + * } + * + *
        + * + *
        + * + * // Click the mouse near the red dot in the top-left corner + * // and drag to change the curve's shape. + * + * let x2 = 10; + * let y2 = 10; + * let isChanging = false; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with three curves. A black s-curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw the anchor points in black. + * stroke(0); + * strokeWeight(5); + * point(85, 20); + * point(15, 80); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(x2, y2); + * point(90, 90); + * + * // Draw a black bezier curve. + * noFill(); + * stroke(0); + * strokeWeight(1); + * bezier(85, 20, x2, y2, 90, 90, 15, 80); + * + * // Draw red lines from the anchor points to the control points. + * stroke(255, 0, 0); + * line(85, 20, x2, y2); + * line(15, 80, 90, 90); + * } + * + * // Start changing the first control point if the user clicks near it. + * function mousePressed() { + * if (dist(mouseX, mouseY, x2, y2) < 20) { + * isChanging = true; + * } + * } + * + * // Stop changing the first control point when the user releases the mouse. + * function mouseReleased() { + * isChanging = false; + * } + * + * // Update the first control point while the user drags the mouse. + * function mouseDragged() { + * if (isChanging === true) { + * x2 = mouseX; + * y2 = mouseY; + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background('skyblue'); + * + * // Draw the red balloon. + * fill('red'); + * bezier(50, 60, 5, 15, 95, 15, 50, 60); + * + * // Draw the balloon string. + * line(50, 60, 50, 80); + * + * describe('A red balloon in a blue sky.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A red balloon in a blue sky. The balloon rotates slowly, revealing that it is flat.'); + * } + * + * function draw() { + * background('skyblue'); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Draw the red balloon. + * fill('red'); + * bezier(0, 0, 0, -45, -45, 0, 45, -45, 0, 0, 0, 0); + * + * // Draw the balloon string. + * line(0, 0, 0, 0, 20, 0); + * } + * + *
        + */ + /** + * @method bezier + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} z1 z-coordinate of the first anchor point. + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} z2 z-coordinate of the first control point. + * @param {Number} x3 + * @param {Number} y3 + * @param {Number} z3 z-coordinate of the second control point. + * @param {Number} x4 + * @param {Number} y4 + * @param {Number} z4 z-coordinate of the second anchor point. + * @chainable + */ + + _main.default.prototype.bezier = function () { + var _this$_renderer; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('bezier', args); + // if the current stroke and fill settings wouldn't result in something + // visible, exit immediately + if (!this._renderer._doStroke && !this._renderer._doFill) { + return this; + }(_this$_renderer = this._renderer).bezier.apply(_this$_renderer, args); + return this; + }; + /** + * Sets the number of segments used to draw Bézier curves in WebGL mode. + * + * In WebGL mode, smooth shapes are drawn using many flat segments. Adding + * more flat segments makes shapes appear smoother. + * + * The parameter, `detail`, is the number of segments to use while drawing a + * Bézier curve. For example, calling `bezierDetail(5)` will use 5 segments to + * draw curves with the bezier() function. By + * default,`detail` is 20. + * + * Note: `bezierDetail()` has no effect in 2D mode. + * + * @method bezierDetail + * @param {Number} detail number of segments to use. Defaults to 20. + * @chainable + * + * @example + *
        + * + * // Draw the original curve. + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw the anchor points in black. + * stroke(0); + * strokeWeight(5); + * point(85, 20); + * point(15, 80); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(10, 10); + * point(90, 90); + * + * // Draw a black bezier curve. + * noFill(); + * stroke(0); + * strokeWeight(1); + * bezier(85, 20, 10, 10, 90, 90, 15, 80); + * + * // Draw red lines from the anchor points to the control points. + * stroke(255, 0, 0); + * line(85, 20, 10, 10); + * line(15, 80, 90, 90); + * + * describe( + * 'A gray square with three curves. A black s-curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' + * ); + * } + * + *
        + * + *
        + * + * // Draw the curve with less detail. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Set the curveDetail() to 5. + * bezierDetail(5); + * + * // Draw the anchor points in black. + * stroke(0); + * strokeWeight(5); + * point(35, -30, 0); + * point(-35, 30, 0); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(-40, -40, 0); + * point(40, 40, 0); + * + * // Draw a black bezier curve. + * noFill(); + * stroke(0); + * strokeWeight(1); + * bezier(35, -30, 0, -40, -40, 0, 40, 40, 0, -35, 30, 0); + * + * // Draw red lines from the anchor points to the control points. + * stroke(255, 0, 0); + * line(35, -30, -40, -40); + * line(-35, 30, 40, 40); + * + * describe( + * 'A gray square with three curves. A black s-curve is drawn with jagged segments. Two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' + * ); + * } + * + *
        + */ + _main.default.prototype.bezierDetail = function (d) { + _main.default._validateParameters('bezierDetail', arguments); + this._bezierDetail = d; + return this; + }; + /** + * Calculates coordinates along a Bézier curve using interpolation. + * + * `bezierPoint()` calculates coordinates along a Bézier curve using the + * anchor and control points. It expects points in the same order as the + * bezier() function. `bezierPoint()` works one axis + * at a time. Passing the anchor and control points' x-coordinates will + * calculate the x-coordinate of a point on the curve. Passing the anchor and + * control points' y-coordinates will calculate the y-coordinate of a point on + * the curve. + * + * The first parameter, `a`, is the coordinate of the first anchor point. + * + * The second and third parameters, `b` and `c`, are the coordinates of the + * control points. + * + * The fourth parameter, `d`, is the coordinate of the last anchor point. + * + * The fifth parameter, `t`, is the amount to interpolate along the curve. 0 + * is the first anchor point, 1 is the second anchor point, and 0.5 is halfway + * between them. + * + * @method bezierPoint + * @param {Number} a coordinate of first control point. + * @param {Number} b coordinate of first anchor point. + * @param {Number} c coordinate of second anchor point. + * @param {Number} d coordinate of second control point. + * @param {Number} t amount to interpolate between 0 and 1. + * @return {Number} coordinate of the point on the curve. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the coordinates for the curve's anchor and control points. + * let x1 = 85; + * let x2 = 10; + * let x3 = 90; + * let x4 = 15; + * let y1 = 20; + * let y2 = 10; + * let y3 = 90; + * let y4 = 80; + * + * // Style the curve. + * noFill(); + * + * // Draw the curve. + * bezier(x1, y1, x2, y2, x3, y3, x4, y4); + * + * // Draw circles along the curve's path. + * fill(255); + * + * // Top-right. + * let x = bezierPoint(x1, x2, x3, x4, 0); + * let y = bezierPoint(y1, y2, y3, y4, 0); + * circle(x, y, 5); + * + * // Center. + * x = bezierPoint(x1, x2, x3, x4, 0.5); + * y = bezierPoint(y1, y2, y3, y4, 0.5); + * circle(x, y, 5); + * + * // Bottom-left. + * x = bezierPoint(x1, x2, x3, x4, 1); + * y = bezierPoint(y1, y2, y3, y4, 1); + * circle(x, y, 5); + * + * describe('A black s-curve on a gray square. The endpoints and center of the curve are marked with white circles.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A black s-curve on a gray square. A white circle moves back and forth along the curve.'); + * } + * + * function draw() { + * background(200); + * + * // Set the coordinates for the curve's anchor and control points. + * let x1 = 85; + * let x2 = 10; + * let x3 = 90; + * let x4 = 15; + * let y1 = 20; + * let y2 = 10; + * let y3 = 90; + * let y4 = 80; + * + * // Draw the curve. + * noFill(); + * bezier(x1, y1, x2, y2, x3, y3, x4, y4); + * + * // Calculate the circle's coordinates. + * let t = 0.5 * sin(frameCount * 0.01) + 0.5; + * let x = bezierPoint(x1, x2, x3, x4, t); + * let y = bezierPoint(y1, y2, y3, y4, t); + * + * // Draw the circle. + * fill(255); + * circle(x, y, 5); + * } + * + *
        + */ + _main.default.prototype.bezierPoint = function (a, b, c, d, t) { + _main.default._validateParameters('bezierPoint', arguments); + var adjustedT = 1 - t; + return Math.pow(adjustedT, 3) * a + 3 * Math.pow(adjustedT, 2) * t * b + 3 * adjustedT * Math.pow(t, 2) * c + Math.pow(t, 3) * d; + }; + /** + * Calculates coordinates along a line that's tangent to a Bézier curve. + * + * Tangent lines skim the surface of a curve. A tangent line's slope equals + * the curve's slope at the point where it intersects. + * + * `bezierTangent()` calculates coordinates along a tangent line using the + * Bézier curve's anchor and control points. It expects points in the same + * order as the bezier() function. `bezierTangent()` + * works one axis at a time. Passing the anchor and control points' + * x-coordinates will calculate the x-coordinate of a point on the tangent + * line. Passing the anchor and control points' y-coordinates will calculate + * the y-coordinate of a point on the tangent line. + * + * The first parameter, `a`, is the coordinate of the first anchor point. + * + * The second and third parameters, `b` and `c`, are the coordinates of the + * control points. + * + * The fourth parameter, `d`, is the coordinate of the last anchor point. + * + * The fifth parameter, `t`, is the amount to interpolate along the curve. 0 + * is the first anchor point, 1 is the second anchor point, and 0.5 is halfway + * between them. + * + * @method bezierTangent + * @param {Number} a coordinate of first anchor point. + * @param {Number} b coordinate of first control point. + * @param {Number} c coordinate of second control point. + * @param {Number} d coordinate of second anchor point. + * @param {Number} t amount to interpolate between 0 and 1. + * @return {Number} coordinate of a point on the tangent line. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the coordinates for the curve's anchor and control points. + * let x1 = 85; + * let x2 = 10; + * let x3 = 90; + * let x4 = 15; + * let y1 = 20; + * let y2 = 10; + * let y3 = 90; + * let y4 = 80; + * + * // Style the curve. + * noFill(); + * + * // Draw the curve. + * bezier(x1, y1, x2, y2, x3, y3, x4, y4); + * + * // Draw tangents along the curve's path. + * fill(255); + * + * // Top-right circle. + * stroke(0); + * let x = bezierPoint(x1, x2, x3, x4, 0); + * let y = bezierPoint(y1, y2, y3, y4, 0); + * circle(x, y, 5); + * + * // Top-right tangent line. + * // Scale the tangent point to draw a shorter line. + * stroke(255, 0, 0); + * let tx = 0.1 * bezierTangent(x1, x2, x3, x4, 0); + * let ty = 0.1 * bezierTangent(y1, y2, y3, y4, 0); + * line(x + tx, y + ty, x - tx, y - ty); + * + * // Center circle. + * stroke(0); + * x = bezierPoint(x1, x2, x3, x4, 0.5); + * y = bezierPoint(y1, y2, y3, y4, 0.5); + * circle(x, y, 5); + * + * // Center tangent line. + * // Scale the tangent point to draw a shorter line. + * stroke(255, 0, 0); + * tx = 0.1 * bezierTangent(x1, x2, x3, x4, 0.5); + * ty = 0.1 * bezierTangent(y1, y2, y3, y4, 0.5); + * line(x + tx, y + ty, x - tx, y - ty); + * + * // Bottom-left circle. + * stroke(0); + * x = bezierPoint(x1, x2, x3, x4, 1); + * y = bezierPoint(y1, y2, y3, y4, 1); + * circle(x, y, 5); + * + * // Bottom-left tangent. + * // Scale the tangent point to draw a shorter line. + * stroke(255, 0, 0); + * tx = 0.1 * bezierTangent(x1, x2, x3, x4, 1); + * ty = 0.1 * bezierTangent(y1, y2, y3, y4, 1); + * line(x + tx, y + ty, x - tx, y - ty); + * + * describe( + * 'A black s-curve on a gray square. The endpoints and center of the curve are marked with white circles. Red tangent lines extend from the white circles.' + * ); + * } + * + *
        + */ + _main.default.prototype.bezierTangent = function (a, b, c, d, t) { + _main.default._validateParameters('bezierTangent', arguments); + var adjustedT = 1 - t; + return 3 * d * Math.pow(t, 2) - 3 * c * Math.pow(t, 2) + 6 * c * adjustedT * t - 6 * b * adjustedT * t + 3 * b * Math.pow(adjustedT, 2) - 3 * a * Math.pow(adjustedT, 2); + }; + /** + * Draws a curve using a Catmull-Rom spline. + * + * Spline curves can form shapes and curves that slope gently. They’re like + * cables that are attached to a set of points. Splines are defined by two + * anchor points and two control points. + * + * The first two parameters, `x1` and `y1`, set the first control point. This + * point isn’t drawn and can be thought of as the curve’s starting point. + * + * The next four parameters, `x2`, `y2`, `x3`, and `y3`, set the two anchor + * points. The anchor points are the start and end points of the curve’s + * visible segment. + * + * The seventh and eighth parameters, `x4` and `y4`, set the last control + * point. This point isn’t drawn and can be thought of as the curve’s ending + * point. + * + * Spline curves can also be drawn in 3D using WebGL mode. The 3D version of + * `curve()` has twelve arguments because each point has x-, y-, and + * z-coordinates. + * + * @method curve + * @param {Number} x1 x-coordinate of the first control point. + * @param {Number} y1 y-coordinate of the first control point. + * @param {Number} x2 x-coordinate of the first anchor point. + * @param {Number} y2 y-coordinate of the first anchor point. + * @param {Number} x3 x-coordinate of the second anchor point. + * @param {Number} y3 y-coordinate of the second anchor point. + * @param {Number} x4 x-coordinate of the second control point. + * @param {Number} y4 y-coordinate of the second control point. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw a black spline curve. + * noFill(); + * strokeWeight(1); + * stroke(0); + * curve(5, 26, 73, 24, 73, 61, 15, 65); + * + * // Draw red spline curves from the anchor points to the control points. + * stroke(255, 0, 0); + * curve(5, 26, 5, 26, 73, 24, 73, 61); + * curve(73, 24, 73, 61, 15, 65, 15, 65); + * + * // Draw the anchor points in black. + * strokeWeight(5); + * stroke(0); + * point(73, 24); + * point(73, 61); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(5, 26); + * point(15, 65); + * + * describe( + * 'A gray square with a curve drawn in three segments. The curve is a sideways U shape with red segments on top and bottom, and a black segment on the right. The endpoints of all the segments are marked with dots.' + * ); + * } + * + *
        + * + *
        + * + * let x1 = 5; + * let y1 = 26; + * let isChanging = false; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a curve drawn in three segments. The curve is a sideways U shape with red segments on top and bottom, and a black segment on the right. The endpoints of all the segments are marked with dots.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw a black spline curve. + * noFill(); + * strokeWeight(1); + * stroke(0); + * curve(x1, y1, 73, 24, 73, 61, 15, 65); + * + * // Draw red spline curves from the anchor points to the control points. + * stroke(255, 0, 0); + * curve(x1, y1, x1, y1, 73, 24, 73, 61); + * curve(73, 24, 73, 61, 15, 65, 15, 65); + * + * // Draw the anchor points in black. + * strokeWeight(5); + * stroke(0); + * point(73, 24); + * point(73, 61); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(x1, y1); + * point(15, 65); + * } + * + * // Start changing the first control point if the user clicks near it. + * function mousePressed() { + * if (dist(mouseX, mouseY, x1, y1) < 20) { + * isChanging = true; + * } + * } + * + * // Stop changing the first control point when the user releases the mouse. + * function mouseReleased() { + * isChanging = false; + * } + * + * // Update the first control point while the user drags the mouse. + * function mouseDragged() { + * if (isChanging === true) { + * x1 = mouseX; + * y1 = mouseY; + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background('skyblue'); + * + * // Draw the red balloon. + * fill('red'); + * curve(-150, 275, 50, 60, 50, 60, 250, 275); + * + * // Draw the balloon string. + * line(50, 60, 50, 80); + * + * describe('A red balloon in a blue sky.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A red balloon in a blue sky.'); + * } + * + * function draw() { + * background('skyblue'); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Draw the red balloon. + * fill('red'); + * curve(-200, 225, 0, 0, 10, 0, 0, 10, 0, 200, 225, 0); + * + * // Draw the balloon string. + * line(0, 10, 0, 0, 30, 0); + * } + * + *
        + */ + /** + * @method curve + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} z1 z-coordinate of the first control point. + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} z2 z-coordinate of the first anchor point. + * @param {Number} x3 + * @param {Number} y3 + * @param {Number} z3 z-coordinate of the second anchor point. + * @param {Number} x4 + * @param {Number} y4 + * @param {Number} z4 z-coordinate of the second control point. + * @chainable + */ + _main.default.prototype.curve = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('curve', args); + if (this._renderer._doStroke) { + var _this$_renderer2; + (_this$_renderer2 = this._renderer).curve.apply(_this$_renderer2, args); + } + return this; + }; + /** + * Sets the number of segments used to draw spline curves in WebGL mode. + * + * In WebGL mode, smooth shapes are drawn using many flat segments. Adding + * more flat segments makes shapes appear smoother. + * + * The parameter, `detail`, is the number of segments to use while drawing a + * spline curve. For example, calling `curveDetail(5)` will use 5 segments to + * draw curves with the curve() function. By + * default,`detail` is 20. + * + * Note: `curveDetail()` has no effect in 2D mode. + * + * @method curveDetail + * @param {Number} resolution number of segments to use. Defaults to 20. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw a black spline curve. + * noFill(); + * strokeWeight(1); + * stroke(0); + * curve(5, 26, 73, 24, 73, 61, 15, 65); + * + * // Draw red spline curves from the anchor points to the control points. + * stroke(255, 0, 0); + * curve(5, 26, 5, 26, 73, 24, 73, 61); + * curve(73, 24, 73, 61, 15, 65, 15, 65); + * + * // Draw the anchor points in black. + * strokeWeight(5); + * stroke(0); + * point(73, 24); + * point(73, 61); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(5, 26); + * point(15, 65); + * + * describe( + * 'A gray square with a curve drawn in three segments. The curve is a sideways U shape with red segments on top and bottom, and a black segment on the right. The endpoints of all the segments are marked with dots.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Set the curveDetail() to 3. + * curveDetail(3); + * + * // Draw a black spline curve. + * noFill(); + * strokeWeight(1); + * stroke(0); + * curve(-45, -24, 0, 23, -26, 0, 23, 11, 0, -35, 15, 0); + * + * // Draw red spline curves from the anchor points to the control points. + * stroke(255, 0, 0); + * curve(-45, -24, 0, -45, -24, 0, 23, -26, 0, 23, 11, 0); + * curve(23, -26, 0, 23, 11, 0, -35, 15, 0, -35, 15, 0); + * + * // Draw the anchor points in black. + * strokeWeight(5); + * stroke(0); + * point(23, -26); + * point(23, 11); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(-45, -24); + * point(-35, 15); + * + * describe( + * 'A gray square with a jagged curve drawn in three segments. The curve is a sideways U shape with red segments on top and bottom, and a black segment on the right. The endpoints of all the segments are marked with dots.' + * ); + * } + * + *
        + */ + _main.default.prototype.curveDetail = function (d) { + _main.default._validateParameters('curveDetail', arguments); + if (d < 3) { + this._curveDetail = 3; + } else { + this._curveDetail = d; + } + return this; + }; + /** + * Adjusts the way curve() and + * curveVertex() draw. + * + * Spline curves are like cables that are attached to a set of points. + * `curveTightness()` adjusts how tightly the cable is attached to the points. + * + * The parameter, `tightness`, determines how the curve fits to the vertex + * points. By default, `tightness` is set to 0. Setting tightness to 1, + * as in `curveTightness(1)`, connects the curve's points using straight + * lines. Values in the range from –5 to 5 deform curves while leaving them + * recognizable. + * + * @method curveTightness + * @param {Number} amount amount of tightness. + * @chainable + * + * @example + *
        + * + * // Move the mouse left and right to see the curve change. + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A black curve forms a sideways U shape. The curve deforms as the user moves the mouse from left to right'); + * } + * + * function draw() { + * background(200); + * + * // Set the curve's tightness using the mouse. + * let t = map(mouseX, 0, 100, -5, 5, true); + * curveTightness(t); + * + * // Draw the curve. + * noFill(); + * beginShape(); + * curveVertex(10, 26); + * curveVertex(10, 26); + * curveVertex(83, 24); + * curveVertex(83, 61); + * curveVertex(25, 65); + * curveVertex(25, 65); + * endShape(); + * } + * + *
        + */ + _main.default.prototype.curveTightness = function (t) { + _main.default._validateParameters('curveTightness', arguments); + this._renderer._curveTightness = t; + return this; + }; + /** + * Calculates coordinates along a spline curve using interpolation. + * + * `curvePoint()` calculates coordinates along a spline curve using the + * anchor and control points. It expects points in the same order as the + * curve() function. `curvePoint()` works one axis + * at a time. Passing the anchor and control points' x-coordinates will + * calculate the x-coordinate of a point on the curve. Passing the anchor and + * control points' y-coordinates will calculate the y-coordinate of a point on + * the curve. + * + * The first parameter, `a`, is the coordinate of the first control point. + * + * The second and third parameters, `b` and `c`, are the coordinates of the + * anchor points. + * + * The fourth parameter, `d`, is the coordinate of the last control point. + * + * The fifth parameter, `t`, is the amount to interpolate along the curve. 0 + * is the first anchor point, 1 is the second anchor point, and 0.5 is halfway + * between them. + * + * @method curvePoint + * @param {Number} a coordinate of first anchor point. + * @param {Number} b coordinate of first control point. + * @param {Number} c coordinate of second control point. + * @param {Number} d coordinate of second anchor point. + * @param {Number} t amount to interpolate between 0 and 1. + * @return {Number} coordinate of a point on the curve. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the coordinates for the curve's anchor and control points. + * let x1 = 5; + * let y1 = 26; + * let x2 = 73; + * let y2 = 24; + * let x3 = 73; + * let y3 = 61; + * let x4 = 15; + * let y4 = 65; + * + * // Draw the curve. + * noFill(); + * curve(x1, y1, x2, y2, x3, y3, x4, y4); + * + * // Draw circles along the curve's path. + * fill(255); + * + * // Top. + * let x = curvePoint(x1, x2, x3, x4, 0); + * let y = curvePoint(y1, y2, y3, y4, 0); + * circle(x, y, 5); + * + * // Center. + * x = curvePoint(x1, x2, x3, x4, 0.5); + * y = curvePoint(y1, y2, y3, y4, 0.5); + * circle(x, y, 5); + * + * // Bottom. + * x = curvePoint(x1, x2, x3, x4, 1); + * y = curvePoint(y1, y2, y3, y4, 1); + * circle(x, y, 5); + * + * describe('A black curve on a gray square. The endpoints and center of the curve are marked with white circles.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A black curve on a gray square. A white circle moves back and forth along the curve.'); + * } + * + * function draw() { + * background(200); + * + * // Set the coordinates for the curve's anchor and control points. + * let x1 = 5; + * let y1 = 26; + * let x2 = 73; + * let y2 = 24; + * let x3 = 73; + * let y3 = 61; + * let x4 = 15; + * let y4 = 65; + * + * // Draw the curve. + * noFill(); + * curve(x1, y1, x2, y2, x3, y3, x4, y4); + * + * // Calculate the circle's coordinates. + * let t = 0.5 * sin(frameCount * 0.01) + 0.5; + * let x = curvePoint(x1, x2, x3, x4, t); + * let y = curvePoint(y1, y2, y3, y4, t); + * + * // Draw the circle. + * fill(255); + * circle(x, y, 5); + * } + * + *
        + */ + _main.default.prototype.curvePoint = function (a, b, c, d, t) { + _main.default._validateParameters('curvePoint', arguments); + var s = this._renderer._curveTightness, + t3 = t * t * t, + t2 = t * t, + f1 = (s - 1) / 2 * t3 + (1 - s) * t2 + (s - 1) / 2 * t, + f2 = (s + 3) / 2 * t3 + ( - 5 - s) / 2 * t2 + 1, + f3 = ( - 3 - s) / 2 * t3 + (s + 2) * t2 + (1 - s) / 2 * t, + f4 = (1 - s) / 2 * t3 + (s - 1) / 2 * t2; + return a * f1 + b * f2 + c * f3 + d * f4; + }; + /** + * Calculates coordinates along a line that's tangent to a spline curve. + * + * Tangent lines skim the surface of a curve. A tangent line's slope equals + * the curve's slope at the point where it intersects. + * + * `curveTangent()` calculates coordinates along a tangent line using the + * spline curve's anchor and control points. It expects points in the same + * order as the curve() function. `curveTangent()` + * works one axis at a time. Passing the anchor and control points' + * x-coordinates will calculate the x-coordinate of a point on the tangent + * line. Passing the anchor and control points' y-coordinates will calculate + * the y-coordinate of a point on the tangent line. + * + * The first parameter, `a`, is the coordinate of the first control point. + * + * The second and third parameters, `b` and `c`, are the coordinates of the + * anchor points. + * + * The fourth parameter, `d`, is the coordinate of the last control point. + * + * The fifth parameter, `t`, is the amount to interpolate along the curve. 0 + * is the first anchor point, 1 is the second anchor point, and 0.5 is halfway + * between them. + * + * @method curveTangent + * @param {Number} a coordinate of first control point. + * @param {Number} b coordinate of first anchor point. + * @param {Number} c coordinate of second anchor point. + * @param {Number} d coordinate of second control point. + * @param {Number} t amount to interpolate between 0 and 1. + * @return {Number} coordinate of a point on the tangent line. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the coordinates for the curve's anchor and control points. + * let x1 = 5; + * let y1 = 26; + * let x2 = 73; + * let y2 = 24; + * let x3 = 73; + * let y3 = 61; + * let x4 = 15; + * let y4 = 65; + * + * // Draw the curve. + * noFill(); + * curve(x1, y1, x2, y2, x3, y3, x4, y4); + * + * // Draw tangents along the curve's path. + * fill(255); + * + * // Top circle. + * stroke(0); + * let x = curvePoint(x1, x2, x3, x4, 0); + * let y = curvePoint(y1, y2, y3, y4, 0); + * circle(x, y, 5); + * + * // Top tangent line. + * // Scale the tangent point to draw a shorter line. + * stroke(255, 0, 0); + * let tx = 0.2 * curveTangent(x1, x2, x3, x4, 0); + * let ty = 0.2 * curveTangent(y1, y2, y3, y4, 0); + * line(x + tx, y + ty, x - tx, y - ty); + * + * // Center circle. + * stroke(0); + * x = curvePoint(x1, x2, x3, x4, 0.5); + * y = curvePoint(y1, y2, y3, y4, 0.5); + * circle(x, y, 5); + * + * // Center tangent line. + * // Scale the tangent point to draw a shorter line. + * stroke(255, 0, 0); + * tx = 0.2 * curveTangent(x1, x2, x3, x4, 0.5); + * ty = 0.2 * curveTangent(y1, y2, y3, y4, 0.5); + * line(x + tx, y + ty, x - tx, y - ty); + * + * // Bottom circle. + * stroke(0); + * x = curvePoint(x1, x2, x3, x4, 1); + * y = curvePoint(y1, y2, y3, y4, 1); + * circle(x, y, 5); + * + * // Bottom tangent line. + * // Scale the tangent point to draw a shorter line. + * stroke(255, 0, 0); + * tx = 0.2 * curveTangent(x1, x2, x3, x4, 1); + * ty = 0.2 * curveTangent(y1, y2, y3, y4, 1); + * line(x + tx, y + ty, x - tx, y - ty); + * + * describe( + * 'A black curve on a gray square. A white circle moves back and forth along the curve.' + * ); + * } + * + *
        + */ + _main.default.prototype.curveTangent = function (a, b, c, d, t) { + _main.default._validateParameters('curveTangent', arguments); + var s = this._renderer._curveTightness, + tt3 = t * t * 3, + t2 = t * 2, + f1 = (s - 1) / 2 * tt3 + (1 - s) * t2 + (s - 1) / 2, + f2 = (s + 3) / 2 * tt3 + ( - 5 - s) / 2 * t2, + f3 = ( - 3 - s) / 2 * tt3 + (s + 2) * t2 + (1 - s) / 2, + f4 = (1 - s) / 2 * tt3 + (s - 1) / 2 * t2; + return a * f1 + b * f2 + c * f3 + d * f4; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../friendly_errors/fes_core': 294, + '../friendly_errors/file_errors': 295, + '../friendly_errors/validate_params': 298, + '../main': 303 + } + ], + 313: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.slice'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../main')); + var constants = _interopRequireWildcard(_dereq_('../constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Shape + * @submodule Vertex + * @for p5 + * @requires core + * @requires constants + */ + + var shapeKind = null; + var vertices = [ + ]; + var contourVertices = [ + ]; + var isBezier = false; + var isCurve = false; + var isQuadratic = false; + var isContour = false; + var isFirstContour = true; + /** + * Begins creating a hole within a flat shape. + * + * The `beginContour()` and endContour() + * functions allow for creating negative space within custom shapes that are + * flat. `beginContour()` begins adding vertices to a negative space and + * endContour() stops adding them. + * `beginContour()` and endContour() must be + * called between beginShape() and + * endShape(). + * + * Transformations such as translate(), + * rotate(), and scale() + * don't work between `beginContour()` and + * endContour(). It's also not possible to use + * other shapes, such as ellipse() or + * rect(), between `beginContour()` and + * endContour(). + * + * Note: The vertices that define a negative space must "wind" in the opposite + * direction from the outer shape. First, draw vertices for the outer shape + * clockwise order. Then, draw vertices for the negative space in + * counter-clockwise order. + * + * @method beginContour + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * beginShape(); + * + * // Exterior vertices, clockwise winding. + * vertex(10, 10); + * vertex(90, 10); + * vertex(90, 90); + * vertex(10, 90); + * + * // Interior vertices, counter-clockwise winding. + * beginContour(); + * vertex(30, 30); + * vertex(30, 70); + * vertex(70, 70); + * vertex(70, 30); + * endContour(); + * + * // Stop drawing the shape. + * endShape(CLOSE); + * + * describe('A white square with a square hole in its center drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white square with a square hole in its center drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Start drawing the shape. + * beginShape(); + * + * // Exterior vertices, clockwise winding. + * vertex(-40, -40); + * vertex(40, -40); + * vertex(40, 40); + * vertex(-40, 40); + * + * // Interior vertices, counter-clockwise winding. + * beginContour(); + * vertex(-20, -20); + * vertex(-20, 20); + * vertex(20, 20); + * vertex(20, -20); + * endContour(); + * + * // Stop drawing the shape. + * endShape(CLOSE); + * } + * + *
        + */ + _main.default.prototype.beginContour = function () { + if (this._renderer.isP3D) { + this._renderer.beginContour(); + } else { + contourVertices = [ + ]; + isContour = true; + } + return this; + }; + /** + * Begins adding vertices to a custom shape. + * + * The `beginShape()` and endShape() functions + * allow for creating custom shapes in 2D or 3D. `beginShape()` begins adding + * vertices to a custom shape and endShape() stops + * adding them. + * + * The parameter, `kind`, sets the kind of shape to make. By default, any + * irregular polygon can be drawn. The available modes for kind are: + * + * - `POINTS` to draw a series of points. + * - `LINES` to draw a series of unconnected line segments. + * - `TRIANGLES` to draw a series of separate triangles. + * - `TRIANGLE_FAN` to draw a series of connected triangles sharing the first vertex in a fan-like fashion. + * - `TRIANGLE_STRIP` to draw a series of connected triangles in strip fashion. + * - `QUADS` to draw a series of separate quadrilaterals (quads). + * - `QUAD_STRIP` to draw quad strip using adjacent edges to form the next quad. + * - `TESS` to create a filling curve by explicit tessellation (WebGL only). + * + * After calling `beginShape()`, shapes can be built by calling + * vertex(), + * bezierVertex(), + * quadraticVertex(), and/or + * curveVertex(). Calling + * endShape() will stop adding vertices to the + * shape. Each shape will be outlined with the current stroke color and filled + * with the current fill color. + * + * Transformations such as translate(), + * rotate(), and + * scale() don't work between `beginShape()` and + * endShape(). It's also not possible to use + * other shapes, such as ellipse() or + * rect(), between `beginShape()` and + * endShape(). + * + * @method beginShape + * @param {Constant} [kind] either POINTS, LINES, TRIANGLES, TRIANGLE_FAN + * TRIANGLE_STRIP, QUADS, QUAD_STRIP or TESS. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add vertices. + * vertex(30, 20); + * vertex(85, 20); + * vertex(85, 75); + * vertex(30, 75); + * + * // Stop drawing the shape. + * endShape(CLOSE); + * + * describe('A white square on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * // Only draw the vertices (points). + * beginShape(POINTS); + * + * // Add vertices. + * vertex(30, 20); + * vertex(85, 20); + * vertex(85, 75); + * vertex(30, 75); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('Four black dots that form a square are drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * // Only draw lines between alternating pairs of vertices. + * beginShape(LINES); + * + * // Add vertices. + * vertex(30, 20); + * vertex(85, 20); + * vertex(85, 75); + * vertex(30, 75); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('Two horizontal black lines on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the shape. + * noFill(); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add vertices. + * vertex(30, 20); + * vertex(85, 20); + * vertex(85, 75); + * vertex(30, 75); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('Three black lines form a sideways U shape on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the shape. + * noFill(); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add vertices. + * vertex(30, 20); + * vertex(85, 20); + * vertex(85, 75); + * vertex(30, 75); + * + * // Stop drawing the shape. + * // Connect the first and last vertices. + * endShape(CLOSE); + * + * describe('A black outline of a square drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * // Draw a series of triangles. + * beginShape(TRIANGLES); + * + * // Left triangle. + * vertex(30, 75); + * vertex(40, 20); + * vertex(50, 75); + * + * // Right triangle. + * vertex(60, 20); + * vertex(70, 75); + * vertex(80, 20); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('Two white triangles drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * // Draw a series of triangles. + * beginShape(TRIANGLE_STRIP); + * + * // Add vertices. + * vertex(30, 75); + * vertex(40, 20); + * vertex(50, 75); + * vertex(60, 20); + * vertex(70, 75); + * vertex(80, 20); + * vertex(90, 75); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('Five white triangles that are interleaved drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * // Draw a series of triangles that share their first vertex. + * beginShape(TRIANGLE_FAN); + * + * // Add vertices. + * vertex(57.5, 50); + * vertex(57.5, 15); + * vertex(92, 50); + * vertex(57.5, 85); + * vertex(22, 50); + * vertex(57.5, 15); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('Four white triangles form a square are drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * // Draw a series of quadrilaterals. + * beginShape(QUADS); + * + * // Left rectangle. + * vertex(30, 20); + * vertex(30, 75); + * vertex(50, 75); + * vertex(50, 20); + * + * // Right rectangle. + * vertex(65, 20); + * vertex(65, 75); + * vertex(85, 75); + * vertex(85, 20); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('Two white rectangles drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * // Draw a series of quadrilaterals. + * beginShape(QUAD_STRIP); + * + * // Add vertices. + * vertex(30, 20); + * vertex(30, 75); + * vertex(50, 20); + * vertex(50, 75); + * vertex(65, 20); + * vertex(65, 75); + * vertex(85, 20); + * vertex(85, 75); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('Three white rectangles that share edges are drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Start drawing the shape. + * // Draw a series of quadrilaterals. + * beginShape(TESS); + * + * // Add the vertices. + * vertex(-30, -30, 0); + * vertex(30, -30, 0); + * vertex(30, -10, 0); + * vertex(-10, -10, 0); + * vertex(-10, 10, 0); + * vertex(30, 10, 0); + * vertex(30, 30, 0); + * vertex(-30, 30, 0); + * + * // Stop drawing the shape. + * // Connect the first and last vertices. + * endShape(CLOSE); + * + * describe('A blocky C shape drawn in white on a gray background.'); + * } + * + *
        + * + *
        + * + * // Click and drag with the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A blocky C shape drawn in red, blue, and green on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Start drawing the shape. + * // Draw a series of quadrilaterals. + * beginShape(TESS); + * + * // Add the vertices. + * fill('red'); + * stroke('red'); + * vertex(-30, -30, 0); + * vertex(30, -30, 0); + * vertex(30, -10, 0); + * fill('green'); + * stroke('green'); + * vertex(-10, -10, 0); + * vertex(-10, 10, 0); + * vertex(30, 10, 0); + * fill('blue'); + * stroke('blue'); + * vertex(30, 30, 0); + * vertex(-30, 30, 0); + * + * // Stop drawing the shape. + * // Connect the first and last vertices. + * endShape(CLOSE); + * } + * + *
        + */ + _main.default.prototype.beginShape = function (kind) { + _main.default._validateParameters('beginShape', arguments); + if (this._renderer.isP3D) { + var _this$_renderer; + (_this$_renderer = this._renderer).beginShape.apply(_this$_renderer, arguments); + } else { + if (kind === constants.POINTS || kind === constants.LINES || kind === constants.TRIANGLES || kind === constants.TRIANGLE_FAN || kind === constants.TRIANGLE_STRIP || kind === constants.QUADS || kind === constants.QUAD_STRIP) { + shapeKind = kind; + } else { + shapeKind = null; + } + vertices = [ + ]; + contourVertices = [ + ]; + } + return this; + }; + /** + * Adds a Bézier curve segment to a custom shape. + * + * `bezierVertex()` adds a curved segment to custom shapes. The Bézier curves + * it creates are defined like those made by the + * bezier() function. `bezierVertex()` must be + * called between the + * beginShape() and + * endShape() functions. The curved segment uses + * the previous vertex as the first anchor point, so there must be at least + * one call to vertex() before `bezierVertex()` can + * be used. + * + * The first four parameters, `x2`, `y2`, `x3`, and `y3`, set the curve’s two + * control points. The control points "pull" the curve towards them. + * + * The fifth and sixth parameters, `x4`, and `y4`, set the last anchor point. + * The last anchor point is where the curve ends. + * + * Bézier curves can also be drawn in 3D using WebGL mode. The 3D version of + * `bezierVertex()` has eight arguments because each point has x-, y-, and + * z-coordinates. + * + * Note: `bezierVertex()` won’t work when an argument is passed to + * beginShape(). + * + * @method bezierVertex + * @param {Number} x2 x-coordinate of the first control point. + * @param {Number} y2 y-coordinate of the first control point. + * @param {Number} x3 x-coordinate of the second control point. + * @param {Number} y3 y-coordinate of the second control point. + * @param {Number} x4 x-coordinate of the anchor point. + * @param {Number} y4 y-coordinate of the anchor point. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the shape. + * noFill(); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the first anchor point. + * vertex(30, 20); + * + * // Add the Bézier vertex. + * bezierVertex(80, 0, 80, 75, 30, 75); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('A black C curve on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw the anchor points in black. + * stroke(0); + * strokeWeight(5); + * point(30, 20); + * point(30, 75); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(80, 0); + * point(80, 75); + * + * // Style the shape. + * noFill(); + * stroke(0); + * strokeWeight(1); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the first anchor point. + * vertex(30, 20); + * + * // Add the Bézier vertex. + * bezierVertex(80, 0, 80, 75, 30, 75); + * + * // Stop drawing the shape. + * endShape(); + * + * // Draw red lines from the anchor points to the control points. + * stroke(255, 0, 0); + * line(30, 20, 80, 0); + * line(30, 75, 80, 75); + * + * describe( + * 'A gray square with three curves. A black curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' + * ); + * } + * + *
        + * + *
        + * + * // Click the mouse near the red dot in the top-right corner + * // and drag to change the curve's shape. + * + * let x2 = 80; + * let y2 = 0; + * let isChanging = false; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with three curves. A black curve has two straight, red lines that extend from its ends. The endpoints of all the curves are marked with dots.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw the anchor points in black. + * stroke(0); + * strokeWeight(5); + * point(30, 20); + * point(30, 75); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(x2, y2); + * point(80, 75); + * + * // Style the shape. + * noFill(); + * stroke(0); + * strokeWeight(1); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the first anchor point. + * vertex(30, 20); + * + * // Add the Bézier vertex. + * bezierVertex(x2, y2, 80, 75, 30, 75); + * + * // Stop drawing the shape. + * endShape(); + * + * // Draw red lines from the anchor points to the control points. + * stroke(255, 0, 0); + * line(30, 20, x2, y2); + * line(30, 75, 80, 75); + * } + * + * // Start changing the first control point if the user clicks near it. + * function mousePressed() { + * if (dist(mouseX, mouseY, x2, y2) < 20) { + * isChanging = true; + * } + * } + * + * // Stop changing the first control point when the user releases the mouse. + * function mouseReleased() { + * isChanging = false; + * } + * + * // Update the first control point while the user drags the mouse. + * function mouseDragged() { + * if (isChanging === true) { + * x2 = mouseX; + * y2 = mouseY; + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the first anchor point. + * vertex(30, 20); + * + * // Add the Bézier vertices. + * bezierVertex(80, 0, 80, 75, 30, 75); + * bezierVertex(50, 80, 60, 25, 30, 20); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('A crescent moon shape drawn in white on a gray background.'); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A crescent moon shape drawn in white on a blue background. When the user drags the mouse, the scene rotates and a second moon is revealed.'); + * } + * + * function draw() { + * background('midnightblue'); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the moons. + * noStroke(); + * fill('lemonchiffon'); + * + * // Draw the first moon. + * beginShape(); + * vertex(-20, -30, 0); + * bezierVertex(30, -50, 0, 30, 25, 0, -20, 25, 0); + * bezierVertex(0, 30, 0, 10, -25, 0, -20, -30, 0); + * endShape(); + * + * // Draw the second moon. + * beginShape(); + * vertex(-20, -30, -20); + * bezierVertex(30, -50, -20, 30, 25, -20, -20, 25, -20); + * bezierVertex(0, 30, -20, 10, -25, -20, -20, -30, -20); + * endShape(); + * } + * + *
        + */ + /** + * @method bezierVertex + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} z2 z-coordinate of the first control point. + * @param {Number} x3 + * @param {Number} y3 + * @param {Number} z3 z-coordinate of the second control point. + * @param {Number} x4 + * @param {Number} y4 + * @param {Number} z4 z-coordinate of the anchor point. + * @chainable + */ + _main.default.prototype.bezierVertex = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('bezierVertex', args); + if (this._renderer.isP3D) { + var _this$_renderer2; + (_this$_renderer2 = this._renderer).bezierVertex.apply(_this$_renderer2, args); + } else { + if (vertices.length === 0) { + _main.default._friendlyError('vertex() must be used once before calling bezierVertex()', 'bezierVertex'); + } else { + isBezier = true; + var vert = [ + ]; + for (var i = 0; i < args.length; i++) { + vert[i] = args[i]; + } + vert.isVert = false; + if (isContour) { + contourVertices.push(vert); + } else { + vertices.push(vert); + } + } + } + return this; + }; + /** + * Adds a spline curve segment to a custom shape. + * + * `curveVertex()` adds a curved segment to custom shapes. The spline curves + * it creates are defined like those made by the + * curve() function. `curveVertex()` must be called + * between the beginShape() and + * endShape() functions. + * + * Spline curves can form shapes and curves that slope gently. They’re like + * cables that are attached to a set of points. Splines are defined by two + * anchor points and two control points. `curveVertex()` must be called at + * least four times between + * beginShape() and + * endShape() in order to draw a curve: + * + * + * beginShape(); + * + * // Add the first control point. + * curveVertex(84, 91); + * + * // Add the anchor points to draw between. + * curveVertex(68, 19); + * curveVertex(21, 17); + * + * // Add the second control point. + * curveVertex(32, 91); + * + * endShape(); + * + * + * The code snippet above would only draw the curve between the anchor points, + * similar to the curve() function. The segments + * between the control and anchor points can be drawn by calling + * `curveVertex()` with the coordinates of the control points: + * + * + * beginShape(); + * + * // Add the first control point and draw a segment to it. + * curveVertex(84, 91); + * curveVertex(84, 91); + * + * // Add the anchor points to draw between. + * curveVertex(68, 19); + * curveVertex(21, 17); + * + * // Add the second control point. + * curveVertex(32, 91); + * + * // Uncomment the next line to draw the segment to the second control point. + * // curveVertex(32, 91); + * + * endShape(); + * + * + * The first two parameters, `x` and `y`, set the vertex’s location. For + * example, calling `curveVertex(10, 10)` adds a point to the curve at + * `(10, 10)`. + * + * Spline curves can also be drawn in 3D using WebGL mode. The 3D version of + * `curveVertex()` has three arguments because each point has x-, y-, and + * z-coordinates. By default, the vertex’s z-coordinate is set to 0. + * + * Note: `curveVertex()` won’t work when an argument is passed to + * beginShape(). + * + * @method curveVertex + * @param {Number} x x-coordinate of the vertex + * @param {Number} y y-coordinate of the vertex + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the shape. + * noFill(); + * strokeWeight(1); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the first control point. + * curveVertex(32, 91); + * + * // Add the anchor points. + * curveVertex(21, 17); + * curveVertex(68, 19); + * + * // Add the second control point. + * curveVertex(84, 91); + * + * // Stop drawing the shape. + * endShape(); + * + * // Style the anchor and control points. + * strokeWeight(5); + * + * // Draw the anchor points in black. + * stroke(0); + * point(21, 17); + * point(68, 19); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(32, 91); + * point(84, 91); + * + * describe( + * 'A black curve drawn on a gray background. The curve has black dots at its ends. Two red dots appear near the bottom of the canvas.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the shape. + * noFill(); + * strokeWeight(1); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the first control point and draw a segment to it. + * curveVertex(32, 91); + * curveVertex(32, 91); + * + * // Add the anchor points. + * curveVertex(21, 17); + * curveVertex(68, 19); + * + * // Add the second control point. + * curveVertex(84, 91); + * + * // Stop drawing the shape. + * endShape(); + * + * // Style the anchor and control points. + * strokeWeight(5); + * + * // Draw the anchor points in black. + * stroke(0); + * point(21, 17); + * point(68, 19); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(32, 91); + * point(84, 91); + * + * describe( + * 'A black curve drawn on a gray background. The curve passes through one red dot and two black dots. Another red dot appears near the bottom of the canvas.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the shape. + * noFill(); + * strokeWeight(1); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the first control point and draw a segment to it. + * curveVertex(32, 91); + * curveVertex(32, 91); + * + * // Add the anchor points. + * curveVertex(21, 17); + * curveVertex(68, 19); + * + * // Add the second control point and draw a segment to it. + * curveVertex(84, 91); + * curveVertex(84, 91); + * + * // Stop drawing the shape. + * endShape(); + * + * // Style the anchor and control points. + * strokeWeight(5); + * + * // Draw the anchor points in black. + * stroke(0); + * point(21, 17); + * point(68, 19); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(32, 91); + * point(84, 91); + * + * describe( + * 'A black U curve drawn upside down on a gray background. The curve passes from one red dot through two black dots and ends at another red dot.' + * ); + * } + * + *
        + * + *
        + * + * // Click the mouse near the red dot in the bottom-left corner + * // and drag to change the curve's shape. + * + * let x1 = 32; + * let y1 = 91; + * let isChanging = false; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A black U curve drawn upside down on a gray background. The curve passes from one red dot through two black dots and ends at another red dot.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the shape. + * noFill(); + * stroke(0); + * strokeWeight(1); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the first control point and draw a segment to it. + * curveVertex(x1, y1); + * curveVertex(x1, y1); + * + * // Add the anchor points. + * curveVertex(21, 17); + * curveVertex(68, 19); + * + * // Add the second control point and draw a segment to it. + * curveVertex(84, 91); + * curveVertex(84, 91); + * + * // Stop drawing the shape. + * endShape(); + * + * // Style the anchor and control points. + * strokeWeight(5); + * + * // Draw the anchor points in black. + * stroke(0); + * point(21, 17); + * point(68, 19); + * + * // Draw the control points in red. + * stroke(255, 0, 0); + * point(x1, y1); + * point(84, 91); + * } + * + * // Start changing the first control point if the user clicks near it. + * function mousePressed() { + * if (dist(mouseX, mouseY, x1, y1) < 20) { + * isChanging = true; + * } + * } + * + * // Stop changing the first control point when the user releases the mouse. + * function mouseReleased() { + * isChanging = false; + * } + * + * // Update the first control point while the user drags the mouse. + * function mouseDragged() { + * if (isChanging === true) { + * x1 = mouseX; + * y1 = mouseY; + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the first control point and draw a segment to it. + * curveVertex(32, 91); + * curveVertex(32, 91); + * + * // Add the anchor points. + * curveVertex(21, 17); + * curveVertex(68, 19); + * + * // Add the second control point. + * curveVertex(84, 91); + * curveVertex(84, 91); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('A ghost shape drawn in white on a gray background.'); + * } + * + *
        + */ + /** + * @method curveVertex + * @param {Number} x + * @param {Number} y + * @param {Number} [z] z-coordinate of the vertex. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A ghost shape drawn in white on a blue background. When the user drags the mouse, the scene rotates to reveal the outline of a second ghost.'); + * } + * + * function draw() { + * background('midnightblue'); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the first ghost. + * noStroke(); + * fill('ghostwhite'); + * + * beginShape(); + * curveVertex(-28, 41, 0); + * curveVertex(-28, 41, 0); + * curveVertex(-29, -33, 0); + * curveVertex(18, -31, 0); + * curveVertex(34, 41, 0); + * curveVertex(34, 41, 0); + * endShape(); + * + * // Draw the second ghost. + * noFill(); + * stroke('ghostwhite'); + * + * beginShape(); + * curveVertex(-28, 41, -20); + * curveVertex(-28, 41, -20); + * curveVertex(-29, -33, -20); + * curveVertex(18, -31, -20); + * curveVertex(34, 41, -20); + * curveVertex(34, 41, -20); + * endShape(); + * } + * + *
        + */ + _main.default.prototype.curveVertex = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('curveVertex', args); + if (this._renderer.isP3D) { + var _this$_renderer3; + (_this$_renderer3 = this._renderer).curveVertex.apply(_this$_renderer3, args); + } else { + isCurve = true; + this.vertex(args[0], args[1]); + } + return this; + }; + /** + * Stops creating a hole within a flat shape. + * + * The beginContour() and `endContour()` + * functions allow for creating negative space within custom shapes that are + * flat. beginContour() begins adding vertices + * to a negative space and `endContour()` stops adding them. + * beginContour() and `endContour()` must be + * called between beginShape() and + * endShape(). + * + * Transformations such as translate(), + * rotate(), and scale() + * don't work between beginContour() and + * `endContour()`. It's also not possible to use other shapes, such as + * ellipse() or rect(), + * between beginContour() and `endContour()`. + * + * Note: The vertices that define a negative space must "wind" in the opposite + * direction from the outer shape. First, draw vertices for the outer shape + * clockwise order. Then, draw vertices for the negative space in + * counter-clockwise order. + * + * @method endContour + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * beginShape(); + * + * // Exterior vertices, clockwise winding. + * vertex(10, 10); + * vertex(90, 10); + * vertex(90, 90); + * vertex(10, 90); + * + * // Interior vertices, counter-clockwise winding. + * beginContour(); + * vertex(30, 30); + * vertex(30, 70); + * vertex(70, 70); + * vertex(70, 30); + * endContour(); + * + * // Stop drawing the shape. + * endShape(CLOSE); + * + * describe('A white square with a square hole in its center drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white square with a square hole in its center drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Start drawing the shape. + * beginShape(); + * + * // Exterior vertices, clockwise winding. + * vertex(-40, -40); + * vertex(40, -40); + * vertex(40, 40); + * vertex(-40, 40); + * + * // Interior vertices, counter-clockwise winding. + * beginContour(); + * vertex(-20, -20); + * vertex(-20, 20); + * vertex(20, 20); + * vertex(20, -20); + * endContour(); + * + * // Stop drawing the shape. + * endShape(CLOSE); + * } + * + *
        + */ + _main.default.prototype.endContour = function () { + if (this._renderer.isP3D) { + return this; + } + var vert = contourVertices[0].slice(); // copy all data + vert.isVert = contourVertices[0].isVert; + vert.moveTo = false; + contourVertices.push(vert); + // prevent stray lines with multiple contours + if (isFirstContour) { + vertices.push(vertices[0]); + isFirstContour = false; + } + for (var i = 0; i < contourVertices.length; i++) { + vertices.push(contourVertices[i]); + } + return this; + }; + /** + * Begins adding vertices to a custom shape. + * + * The beginShape() and `endShape()` functions + * allow for creating custom shapes in 2D or 3D. + * beginShape() begins adding vertices to a + * custom shape and `endShape()` stops adding them. + * + * The first parameter, `mode`, is optional. By default, the first and last + * vertices of a shape aren't connected. If the constant `CLOSE` is passed, as + * in `endShape(CLOSE)`, then the first and last vertices will be connected. + * + * The second parameter, `count`, is also optional. In WebGL mode, it’s more + * efficient to draw many copies of the same shape using a technique called + * instancing. + * The `count` parameter tells WebGL mode how many copies to draw. For + * example, calling `endShape(CLOSE, 400)` after drawing a custom shape will + * make it efficient to draw 400 copies. This feature requires + * writing a custom shader. + * + * After calling beginShape(), shapes can be + * built by calling vertex(), + * bezierVertex(), + * quadraticVertex(), and/or + * curveVertex(). Calling + * `endShape()` will stop adding vertices to the + * shape. Each shape will be outlined with the current stroke color and filled + * with the current fill color. + * + * Transformations such as translate(), + * rotate(), and + * scale() don't work between + * beginShape() and `endShape()`. It's also not + * possible to use other shapes, such as ellipse() or + * rect(), between + * beginShape() and `endShape()`. + * + * @method endShape + * @param {Constant} [mode] use CLOSE to close the shape + * @param {Integer} [count] number of times you want to draw/instance the shape (for WebGL mode). + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the shapes. + * noFill(); + * + * // Left triangle. + * beginShape(); + * vertex(20, 20); + * vertex(45, 20); + * vertex(45, 80); + * endShape(CLOSE); + * + * // Right triangle. + * beginShape(); + * vertex(50, 20); + * vertex(75, 20); + * vertex(75, 80); + * endShape(); + * + * describe( + * 'Two sets of black lines drawn on a gray background. The three lines on the left form a right triangle. The two lines on the right form a right angle.' + * ); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = `#version 300 es + * + * precision mediump float; + * + * in vec3 aPosition; + * flat out int instanceID; + * + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * void main() { + * + * // Copy the instance ID to the fragment shader. + * instanceID = gl_InstanceID; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * + * // gl_InstanceID represents a numeric value for each instance. + * // Using gl_InstanceID allows us to move each instance separately. + * // Here we move each instance horizontally by ID * 23. + * float xOffset = float(gl_InstanceID) * 23.0; + * + * // Apply the offset to the final position. + * gl_Position = uProjectionMatrix * uModelViewMatrix * (positionVec4 - + * vec4(xOffset, 0.0, 0.0, 0.0)); + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = `#version 300 es + * + * precision mediump float; + * + * out vec4 outColor; + * flat in int instanceID; + * uniform float numInstances; + * + * void main() { + * vec4 red = vec4(1.0, 0.0, 0.0, 1.0); + * vec4 blue = vec4(0.0, 0.0, 1.0, 1.0); + * + * // Normalize the instance ID. + * float normId = float(instanceID) / numInstances; + * + * // Mix between two colors using the normalized instance ID. + * outColor = mix(red, blue, normId); + * } + * `; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * let myShader = createShader(vertSrc, fragSrc); + * + * background(220); + * + * // Compile and apply the p5.Shader. + * shader(myShader); + * + * // Set the numInstances uniform. + * myShader.setUniform('numInstances', 4); + * + * // Translate the origin to help align the drawing. + * translate(25, -10); + * + * // Style the shapes. + * noStroke(); + * + * // Draw the shapes. + * beginShape(); + * vertex(0, 0); + * vertex(0, 20); + * vertex(20, 20); + * vertex(20, 0); + * vertex(0, 0); + * endShape(CLOSE, 4); + * + * describe('A row of four squares. Their colors transition from purple on the left to red on the right'); + * } + * + *
        + */ + _main.default.prototype.endShape = function (mode) { + var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + _main.default._validateParameters('endShape', arguments); + if (count < 1) { + console.log('🌸 p5.js says: You can not have less than one instance'); + count = 1; + } + if (this._renderer.isP3D) { + this._renderer.endShape(mode, isCurve, isBezier, isQuadratic, isContour, shapeKind, count); + } else { + if (count !== 1) { + console.log('🌸 p5.js says: Instancing is only supported in WebGL2 mode'); + } + if (vertices.length === 0) { + return this; + } + if (!this._renderer._doStroke && !this._renderer._doFill) { + return this; + } + var closeShape = mode === constants.CLOSE; + // if the shape is closed, the first element is also the last element + if (closeShape && !isContour) { + vertices.push(vertices[0]); + } + this._renderer.endShape(mode, vertices, isCurve, isBezier, isQuadratic, isContour, shapeKind); + // Reset some settings + isCurve = false; + isBezier = false; + isQuadratic = false; + isContour = false; + isFirstContour = true; + // If the shape is closed, the first element was added as last element. + // We must remove it again to prevent the list of vertices from growing + // over successive calls to endShape(CLOSE) + if (closeShape) { + vertices.pop(); + } + } + return this; + }; + /** + * Adds a quadratic Bézier curve segment to a custom shape. + * + * `quadraticVertex()` adds a curved segment to custom shapes. The Bézier + * curve segments it creates are similar to those made by the + * bezierVertex() function. + * `quadraticVertex()` must be called between the + * beginShape() and + * endShape() functions. The curved segment uses + * the previous vertex as the first anchor point, so there must be at least + * one call to vertex() before `quadraticVertex()` can + * be used. + * + * The first two parameters, `cx` and `cy`, set the curve’s control point. + * The control point "pulls" the curve towards its. + * + * The last two parameters, `x3`, and `y3`, set the last anchor point. The + * last anchor point is where the curve ends. + * + * Bézier curves can also be drawn in 3D using WebGL mode. The 3D version of + * `bezierVertex()` has eight arguments because each point has x-, y-, and + * z-coordinates. + * + * Note: `quadraticVertex()` won’t work when an argument is passed to + * beginShape(). + * + * @method quadraticVertex + * @param {Number} cx x-coordinate of the control point. + * @param {Number} cy y-coordinate of the control point. + * @param {Number} x3 x-coordinate of the anchor point. + * @param {Number} y3 y-coordinate of the anchor point. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the curve. + * noFill(); + * + * // Draw the curve. + * beginShape(); + * vertex(20, 20); + * quadraticVertex(80, 20, 50, 50); + * endShape(); + * + * describe('A black curve drawn on a gray square. The curve starts at the top-left corner and ends at the center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw the curve. + * noFill(); + * beginShape(); + * vertex(20, 20); + * quadraticVertex(80, 20, 50, 50); + * endShape(); + * + * // Draw red lines from the anchor points to the control point. + * stroke(255, 0, 0); + * line(20, 20, 80, 20); + * line(50, 50, 80, 20); + * + * // Draw the anchor points in black. + * strokeWeight(5); + * stroke(0); + * point(20, 20); + * point(50, 50); + * + * // Draw the control point in red. + * stroke(255, 0, 0); + * point(80, 20); + * + * describe('A black curve that starts at the top-left corner and ends at the center. Its anchor and control points are marked with dots. Red lines connect both anchor points to the control point.'); + * } + * + *
        + * + *
        + * + * // Click the mouse near the red dot in the top-right corner + * // and drag to change the curve's shape. + * + * let x2 = 80; + * let y2 = 20; + * let isChanging = false; + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A black curve that starts at the top-left corner and ends at the center. Its anchor and control points are marked with dots. Red lines connect both anchor points to the control point.'); + * } + * + * function draw() { + * background(200); + * + * // Style the curve. + * noFill(); + * strokeWeight(1); + * stroke(0); + * + * // Draw the curve. + * beginShape(); + * vertex(20, 20); + * quadraticVertex(x2, y2, 50, 50); + * endShape(); + * + * // Draw red lines from the anchor points to the control point. + * stroke(255, 0, 0); + * line(20, 20, x2, y2); + * line(50, 50, x2, y2); + * + * // Draw the anchor points in black. + * strokeWeight(5); + * stroke(0); + * point(20, 20); + * point(50, 50); + * + * // Draw the control point in red. + * stroke(255, 0, 0); + * point(x2, y2); + * } + * + * // Start changing the first control point if the user clicks near it. + * function mousePressed() { + * if (dist(mouseX, mouseY, x2, y2) < 20) { + * isChanging = true; + * } + * } + * + * // Stop changing the first control point when the user releases the mouse. + * function mouseReleased() { + * isChanging = false; + * } + * + * // Update the first control point while the user drags the mouse. + * function mouseDragged() { + * if (isChanging === true) { + * x2 = mouseX; + * y2 = mouseY; + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add the curved segments. + * vertex(20, 20); + * quadraticVertex(80, 20, 50, 50); + * quadraticVertex(20, 80, 80, 80); + * + * // Add the straight segments. + * vertex(80, 10); + * vertex(20, 10); + * vertex(20, 20); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('A white puzzle piece drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * // Click the and drag the mouse to view the scene from a different angle. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white puzzle piece on a dark gray background. When the user clicks and drags the scene, the outline of a second puzzle piece is revealed.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the first puzzle piece. + * noStroke(); + * fill(255); + * + * // Draw the first puzzle piece. + * beginShape(); + * vertex(-30, -30, 0); + * quadraticVertex(30, -30, 0, 0, 0, 0); + * quadraticVertex(-30, 30, 0, 30, 30, 0); + * vertex(30, -40, 0); + * vertex(-30, -40, 0); + * vertex(-30, -30, 0); + * endShape(); + * + * // Style the second puzzle piece. + * stroke(255); + * noFill(); + * + * // Draw the second puzzle piece. + * beginShape(); + * vertex(-30, -30, -20); + * quadraticVertex(30, -30, -20, 0, 0, -20); + * quadraticVertex(-30, 30, -20, 30, 30, -20); + * vertex(30, -40, -20); + * vertex(-30, -40, -20); + * vertex(-30, -30, -20); + * endShape(); + * } + * + *
        + */ + /** + * @method quadraticVertex + * @param {Number} cx + * @param {Number} cy + * @param {Number} cz z-coordinate of the control point. + * @param {Number} x3 + * @param {Number} y3 + * @param {Number} z3 z-coordinate of the anchor point. + */ + _main.default.prototype.quadraticVertex = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('quadraticVertex', args); + if (this._renderer.isP3D) { + var _this$_renderer4; + (_this$_renderer4 = this._renderer).quadraticVertex.apply(_this$_renderer4, args); + } else { + //if we're drawing a contour, put the points into an + // array for inside drawing + if (this._contourInited) { + var pt = { + }; + pt.x = args[0]; + pt.y = args[1]; + pt.x3 = args[2]; + pt.y3 = args[3]; + pt.type = constants.QUADRATIC; + this._contourVertices.push(pt); + return this; + } + if (vertices.length > 0) { + isQuadratic = true; + var vert = [ + ]; + for (var i = 0; i < args.length; i++) { + vert[i] = args[i]; + } + vert.isVert = false; + if (isContour) { + contourVertices.push(vert); + } else { + vertices.push(vert); + } + } else { + _main.default._friendlyError('vertex() must be used once before calling quadraticVertex()', 'quadraticVertex'); + } + } + return this; + }; + /** + * Adds a vertex to a custom shape. + * + * `vertex()` sets the coordinates of vertices drawn between the + * beginShape() and + * endShape() functions. + * + * The first two parameters, `x` and `y`, set the x- and y-coordinates of the + * vertex. + * + * The third parameter, `z`, is optional. It sets the z-coordinate of the + * vertex in WebGL mode. By default, `z` is 0. + * + * The fourth and fifth parameters, `u` and `v`, are also optional. They set + * the u- and v-coordinates for the vertex’s texture when used with + * endShape(). By default, `u` and `v` are both 0. + * + * @method vertex + * @param {Number} x x-coordinate of the vertex. + * @param {Number} y y-coordinate of the vertex. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the shape. + * strokeWeight(3); + * + * // Start drawing the shape. + * // Only draw the vertices. + * beginShape(POINTS); + * + * // Add the vertices. + * vertex(30, 20); + * vertex(85, 20); + * vertex(85, 75); + * vertex(30, 75); + * + * // Stop drawing the shape. + * endShape(); + * + * describe('Four black dots that form a square are drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add vertices. + * vertex(30, 20); + * vertex(85, 20); + * vertex(85, 75); + * vertex(30, 75); + * + * // Stop drawing the shape. + * endShape(CLOSE); + * + * describe('A white square on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add vertices. + * vertex(-20, -30, 0); + * vertex(35, -30, 0); + * vertex(35, 25, 0); + * vertex(-20, 25, 0); + * + * // Stop drawing the shape. + * endShape(CLOSE); + * + * describe('A white square on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white square spins around slowly on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Start drawing the shape. + * beginShape(); + * + * // Add vertices. + * vertex(-20, -30, 0); + * vertex(35, -30, 0); + * vertex(35, 25, 0); + * vertex(-20, 25, 0); + * + * // Stop drawing the shape. + * endShape(CLOSE); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load an image to apply as a texture. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A photograph of a ceiling rotates slowly against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Style the shape. + * noStroke(); + * + * // Apply the texture. + * texture(img); + * textureMode(NORMAL); + * + * // Start drawing the shape + * beginShape(); + * + * // Add vertices. + * vertex(-20, -30, 0, 0, 0); + * vertex(35, -30, 0, 1, 0); + * vertex(35, 25, 0, 1, 1); + * vertex(-20, 25, 0, 0, 1); + * + * // Stop drawing the shape. + * endShape(); + * } + * + *
        + */ + /** + * @method vertex + * @param {Number} x + * @param {Number} y + * @param {Number} [z] z-coordinate of the vertex. Defaults to 0. + * @chainable + */ + /** + * @method vertex + * @param {Number} x + * @param {Number} y + * @param {Number} [z] + * @param {Number} [u] u-coordinate of the vertex's texture. Defaults to 0. + * @param {Number} [v] v-coordinate of the vertex's texture. Defaults to 0. + * @chainable + */ + _main.default.prototype.vertex = function (x, y, moveTo, u, v) { + if (this._renderer.isP3D) { + var _this$_renderer5; + (_this$_renderer5 = this._renderer).vertex.apply(_this$_renderer5, arguments); + } else { + var vert = [ + ]; + vert.isVert = true; + vert[0] = x; + vert[1] = y; + vert[2] = 0; + vert[3] = 0; + vert[4] = 0; + vert[5] = this._renderer._getFill(); + vert[6] = this._renderer._getStroke(); + if (moveTo) { + vert.moveTo = moveTo; + } + if (isContour) { + if (contourVertices.length === 0) { + vert.moveTo = true; + } + contourVertices.push(vert); + } else { + vertices.push(vert); + } + } + return this; + }; + /** + * Sets the normal vector for vertices in a custom 3D shape. + * + * 3D shapes created with beginShape() and + * endShape() are made by connecting sets of + * points called vertices. Each vertex added with + * vertex() has a normal vector that points away + * from it. The normal vector controls how light reflects off the shape. + * + * `normal()` can be called two ways with different parameters to define the + * normal vector's components. + * + * The first way to call `normal()` has three parameters, `x`, `y`, and `z`. + * If `Number`s are passed, as in `normal(1, 2, 3)`, they set the x-, y-, and + * z-components of the normal vector. + * + * The second way to call `normal()` has one parameter, `vector`. If a + * p5.Vector object is passed, as in + * `normal(myVector)`, its components will be used to set the normal vector. + * + * `normal()` changes the normal vector of vertices added to a custom shape + * with vertex(). `normal()` must be called between + * the beginShape() and + * endShape() functions, just like + * vertex(). The normal vector set by calling + * `normal()` will affect all following vertices until `normal()` is called + * again: + * + * + * beginShape(); + * + * // Set the vertex normal. + * normal(-0.4, -0.4, 0.8); + * + * // Add a vertex. + * vertex(-30, -30, 0); + * + * // Set the vertex normal. + * normal(0, 0, 1); + * + * // Add vertices. + * vertex(30, -30, 0); + * vertex(30, 30, 0); + * + * // Set the vertex normal. + * normal(0.4, -0.4, 0.8); + * + * // Add a vertex. + * vertex(-30, 30, 0); + * + * endShape(); + * + * + * @method normal + * @param {p5.Vector} vector vertex normal as a p5.Vector object. + * @chainable + * + * @example + *
        + * + * // Click the and drag the mouse to view the scene from a different angle. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'A colorful square on a black background. The square changes color and rotates when the user drags the mouse. Parts of its surface reflect light in different directions.' + * ); + * } + * + * function draw() { + * background(0); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the shape. + * normalMaterial(); + * noStroke(); + * + * // Draw the shape. + * beginShape(); + * vertex(-30, -30, 0); + * vertex(30, -30, 0); + * vertex(30, 30, 0); + * vertex(-30, 30, 0); + * endShape(); + * } + * + *
        + * + *
        + * + * // Click the and drag the mouse to view the scene from a different angle. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'A colorful square on a black background. The square changes color and rotates when the user drags the mouse. Parts of its surface reflect light in different directions.' + * ); + * } + * + * function draw() { + * background(0); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the shape. + * normalMaterial(); + * noStroke(); + * + * // Draw the shape. + * // Use normal() to set vertex normals. + * beginShape(); + * normal(-0.4, -0.4, 0.8); + * vertex(-30, -30, 0); + * + * normal(0, 0, 1); + * vertex(30, -30, 0); + * vertex(30, 30, 0); + * + * normal(0.4, -0.4, 0.8); + * vertex(-30, 30, 0); + * endShape(); + * } + * + *
        + * + *
        + * + * // Click the and drag the mouse to view the scene from a different angle. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'A colorful square on a black background. The square changes color and rotates when the user drags the mouse. Parts of its surface reflect light in different directions.' + * ); + * } + * + * function draw() { + * background(0); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the shape. + * normalMaterial(); + * noStroke(); + * + * // Create p5.Vector objects. + * let n1 = createVector(-0.4, -0.4, 0.8); + * let n2 = createVector(0, 0, 1); + * let n3 = createVector(0.4, -0.4, 0.8); + * + * // Draw the shape. + * // Use normal() to set vertex normals. + * beginShape(); + * normal(n1); + * vertex(-30, -30, 0); + * + * normal(n2); + * vertex(30, -30, 0); + * vertex(30, 30, 0); + * + * normal(n3); + * vertex(-30, 30, 0); + * endShape(); + * } + * + *
        + */ + /** + * @method normal + * @param {Number} x x-component of the vertex normal. + * @param {Number} y y-component of the vertex normal. + * @param {Number} z z-component of the vertex normal. + * @chainable + */ + _main.default.prototype.normal = function (x, y, z) { + var _this$_renderer6; + this._assert3d('normal'); + _main.default._validateParameters('normal', arguments); + (_this$_renderer6 = this._renderer).normal.apply(_this$_renderer6, arguments); + return this; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../constants': 291, + '../main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 314: [ + function (_dereq_, module, exports) { + 'use strict'; + }, + { + } + ], + 315: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.assign'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('./main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Structure + * @submodule Structure + * @for p5 + * @requires core + */ + /** + * Stops the code in draw() from running repeatedly. + * + * By default, draw() tries to run 60 times per + * second. Calling `noLoop()` stops draw() from + * repeating. The draw loop can be restarted by calling + * loop(). draw() can be run + * once by calling redraw(). + * + * The isLooping() function can be used to check + * whether a sketch is looping, as in `isLooping() === true`. + * + * @method noLoop + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Turn off the draw loop. + * noLoop(); + * + * describe('A white half-circle on the left edge of a gray square.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the circle's x-coordinate. + * let x = frameCount; + * + * // Draw the circle. + * // Normally, the circle would move from left to right. + * circle(x, 50, 20); + * } + * + *
        + * + *
        + * + * // Double-click to stop the draw loop. + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(5); + * + * describe('A white circle moves randomly on a gray background. It stops moving when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the circle's coordinates. + * let x = random(0, 100); + * let y = random(0, 100); + * + * // Draw the circle. + * // Normally, the circle would move from left to right. + * circle(x, y, 20); + * } + * + * // Stop the draw loop when the user double-clicks. + * function doubleClicked() { + * noLoop(); + * } + * + *
        + * + *
        + * + * let startButton; + * let stopButton; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create the button elements and place them + * // beneath the canvas. + * startButton = createButton('▶'); + * startButton.position(0, 100); + * startButton.size(50, 20); + * stopButton = createButton('◾'); + * stopButton.position(50, 100); + * stopButton.size(50, 20); + * + * // Set functions to call when the buttons are pressed. + * startButton.mousePressed(loop); + * stopButton.mousePressed(noLoop); + * + * // Slow the frame rate. + * frameRate(5); + * + * describe( + * 'A white circle moves randomly on a gray background. Play and stop buttons are shown beneath the canvas. The circle stops or starts moving when the user presses a button.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Calculate the circle's coordinates. + * let x = random(0, 100); + * let y = random(0, 100); + * + * // Draw the circle. + * // Normally, the circle would move from left to right. + * circle(x, y, 20); + * } + * + *
        + */ + + _main.default.prototype.noLoop = function () { + this._loop = false; + }; + /** + * Resumes the draw loop after noLoop() has been + * called. + * + * By default, draw() tries to run 60 times per + * second. Calling noLoop() stops + * draw() from repeating. The draw loop can be + * restarted by calling `loop()`. + * + * The isLooping() function can be used to check + * whether a sketch is looping, as in `isLooping() === true`. + * + * @method loop + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Turn off the draw loop. + * noLoop(); + * + * describe( + * 'A white half-circle on the left edge of a gray square. The circle starts moving to the right when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Calculate the circle's x-coordinate. + * let x = frameCount; + * + * // Draw the circle. + * circle(x, 50, 20); + * } + * + * // Resume the draw loop when the user double-clicks. + * function doubleClicked() { + * loop(); + * } + * + *
        + * + *
        + * + * let startButton; + * let stopButton; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create the button elements and place them + * // beneath the canvas. + * startButton = createButton('▶'); + * startButton.position(0, 100); + * startButton.size(50, 20); + * stopButton = createButton('◾'); + * stopButton.position(50, 100); + * stopButton.size(50, 20); + * + * // Set functions to call when the buttons are pressed. + * startButton.mousePressed(loop); + * stopButton.mousePressed(noLoop); + * + * // Slow the frame rate. + * frameRate(5); + * + * describe( + * 'A white circle moves randomly on a gray background. Play and stop buttons are shown beneath the canvas. The circle stops or starts moving when the user presses a button.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Calculate the circle's coordinates. + * let x = random(0, 100); + * let y = random(0, 100); + * + * // Draw the circle. + * // Normally, the circle would move from left to right. + * circle(x, y, 20); + * } + * + *
        + */ + _main.default.prototype.loop = function () { + if (!this._loop) { + this._loop = true; + if (this._setupDone) { + this._draw(); + } + } + }; + /** + * Returns `true` if the draw loop is running and `false` if not. + * + * By default, draw() tries to run 60 times per + * second. Calling noLoop() stops + * draw() from repeating. The draw loop can be + * restarted by calling loop(). + * + * The `isLooping()` function can be used to check whether a sketch is + * looping, as in `isLooping() === true`. + * + * @method isLooping + * @returns {boolean} + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white circle drawn against a gray background. When the user double-clicks, the circle stops or resumes following the mouse.'); + * } + * + * function draw() { + * background(200); + * + * // Draw the circle at the mouse's position. + * circle(mouseX, mouseY, 20); + * } + * + * // Toggle the draw loop when the user double-clicks. + * function doubleClicked() { + * if (isLooping() === true) { + * noLoop(); + * } else { + * loop(); + * } + * } + * + *
        + */ + _main.default.prototype.isLooping = function () { + return this._loop; + }; + /** + * Begins a drawing group that contains its own styles and transformations. + * + * By default, styles such as fill() and + * transformations such as rotate() are applied to + * all drawing that follows. The `push()` and pop() + * functions can limit the effect of styles and transformations to a specific + * group of shapes, images, and text. For example, a group of shapes could be + * translated to follow the mouse without affecting the rest of the sketch: + * + * ```js + * // Begin the drawing group. + * push(); + * + * // Translate the origin to the mouse's position. + * translate(mouseX, mouseY); + * + * // Style the face. + * noStroke(); + * fill('green'); + * + * // Draw the face. + * circle(0, 0, 60); + * + * // Style the eyes. + * fill('white'); + * + * // Draw the left eye. + * ellipse(-20, -20, 30, 20); + * + * // Draw the right eye. + * ellipse(20, -20, 30, 20); + * + * // End the drawing group. + * pop(); + * + * // Draw a bug. + * let x = random(0, 100); + * let y = random(0, 100); + * text('🦟', x, y); + * ``` + * + * In the code snippet above, the bug's position isn't affected by + * `translate(mouseX, mouseY)` because that transformation is contained + * between `push()` and pop(). The bug moves around + * the entire canvas as expected. + * + * Note: `push()` and pop() are always called as a + * pair. Both functions are required to begin and end a drawing group. + * + * `push()` and pop() can also be nested to create + * subgroups. For example, the code snippet above could be changed to give + * more detail to the frog’s eyes: + * + * ```js + * // Begin the drawing group. + * push(); + * + * // Translate the origin to the mouse's position. + * translate(mouseX, mouseY); + * + * // Style the face. + * noStroke(); + * fill('green'); + * + * // Draw a face. + * circle(0, 0, 60); + * + * // Style the eyes. + * fill('white'); + * + * // Draw the left eye. + * push(); + * translate(-20, -20); + * ellipse(0, 0, 30, 20); + * fill('black'); + * circle(0, 0, 8); + * pop(); + * + * // Draw the right eye. + * push(); + * translate(20, -20); + * ellipse(0, 0, 30, 20); + * fill('black'); + * circle(0, 0, 8); + * pop(); + * + * // End the drawing group. + * pop(); + * + * // Draw a bug. + * let x = random(0, 100); + * let y = random(0, 100); + * text('🦟', x, y); + * ``` + * + * In this version, the code to draw each eye is contained between its own + * `push()` and pop() functions. Doing so makes it + * easier to add details in the correct part of a drawing. + * + * `push()` and pop() contain the effects of the + * following functions: + * + * - fill() + * - noFill() + * - noStroke() + * - stroke() + * - tint() + * - noTint() + * - strokeWeight() + * - strokeCap() + * - strokeJoin() + * - imageMode() + * - rectMode() + * - ellipseMode() + * - colorMode() + * - textAlign() + * - textFont() + * - textSize() + * - textLeading() + * - applyMatrix() + * - resetMatrix() + * - rotate() + * - scale() + * - shearX() + * - shearY() + * - translate() + * + * In WebGL mode, `push()` and pop() contain the + * effects of a few additional styles: + * + * - setCamera() + * - ambientLight() + * - directionalLight() + * - pointLight() texture() + * - specularMaterial() + * - shininess() + * - normalMaterial() + * - shader() + * + * @method push + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw the left circle. + * circle(25, 50, 20); + * + * // Begin the drawing group. + * push(); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Style the circle. + * strokeWeight(5); + * stroke('royalblue'); + * fill('orange'); + * + * // Draw the circle. + * circle(0, 0, 20); + * + * // End the drawing group. + * pop(); + * + * // Draw the right circle. + * circle(75, 50, 20); + * + * describe( + * 'Three circles drawn in a row on a gray background. The left and right circles are white with thin, black borders. The middle circle is orange with a thick, blue border.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(24); + * + * describe('A mosquito buzzes in front of a green frog. The frog follows the mouse as the user moves.'); + * } + * + * function draw() { + * background(200); + * + * // Begin the drawing group. + * push(); + * + * // Translate the origin to the mouse's position. + * translate(mouseX, mouseY); + * + * // Style the face. + * noStroke(); + * fill('green'); + * + * // Draw a face. + * circle(0, 0, 60); + * + * // Style the eyes. + * fill('white'); + * + * // Draw the left eye. + * push(); + * translate(-20, -20); + * ellipse(0, 0, 30, 20); + * fill('black'); + * circle(0, 0, 8); + * pop(); + * + * // Draw the right eye. + * push(); + * translate(20, -20); + * ellipse(0, 0, 30, 20); + * fill('black'); + * circle(0, 0, 8); + * pop(); + * + * // End the drawing group. + * pop(); + * + * // Draw a bug. + * let x = random(0, 100); + * let y = random(0, 100); + * text('🦟', x, y); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'Two spheres drawn on a gray background. The sphere on the left is red and lit from the front. The sphere on the right is a blue wireframe.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the red sphere. + * push(); + * translate(-25, 0, 0); + * noStroke(); + * directionalLight(255, 0, 0, 0, 0, -1); + * sphere(20); + * pop(); + * + * // Draw the blue sphere. + * push(); + * translate(25, 0, 0); + * strokeWeight(0.3); + * stroke(0, 0, 255); + * noFill(); + * sphere(20); + * pop(); + * } + * + *
        + */ + _main.default.prototype.push = function () { + this._styles.push({ + props: { + _colorMode: this._colorMode + }, + renderer: this._renderer.push() + }); + }; + /** + * Ends a drawing group that contains its own styles and transformations. + * + * By default, styles such as fill() and + * transformations such as rotate() are applied to + * all drawing that follows. The push() and `pop()` + * functions can limit the effect of styles and transformations to a specific + * group of shapes, images, and text. For example, a group of shapes could be + * translated to follow the mouse without affecting the rest of the sketch: + * + * ```js + * // Begin the drawing group. + * push(); + * + * // Translate the origin to the mouse's position. + * translate(mouseX, mouseY); + * + * // Style the face. + * noStroke(); + * fill('green'); + * + * // Draw the face. + * circle(0, 0, 60); + * + * // Style the eyes. + * fill('white'); + * + * // Draw the left eye. + * ellipse(-20, -20, 30, 20); + * + * // Draw the right eye. + * ellipse(20, -20, 30, 20); + * + * // End the drawing group. + * pop(); + * + * // Draw a bug. + * let x = random(0, 100); + * let y = random(0, 100); + * text('🦟', x, y); + * ``` + * + * In the code snippet above, the bug's position isn't affected by + * `translate(mouseX, mouseY)` because that transformation is contained + * between push() and `pop()`. The bug moves around + * the entire canvas as expected. + * + * Note: push() and `pop()` are always called as a + * pair. Both functions are required to begin and end a drawing group. + * + * push() and `pop()` can also be nested to create + * subgroups. For example, the code snippet above could be changed to give + * more detail to the frog’s eyes: + * + * ```js + * // Begin the drawing group. + * push(); + * + * // Translate the origin to the mouse's position. + * translate(mouseX, mouseY); + * + * // Style the face. + * noStroke(); + * fill('green'); + * + * // Draw a face. + * circle(0, 0, 60); + * + * // Style the eyes. + * fill('white'); + * + * // Draw the left eye. + * push(); + * translate(-20, -20); + * ellipse(0, 0, 30, 20); + * fill('black'); + * circle(0, 0, 8); + * pop(); + * + * // Draw the right eye. + * push(); + * translate(20, -20); + * ellipse(0, 0, 30, 20); + * fill('black'); + * circle(0, 0, 8); + * pop(); + * + * // End the drawing group. + * pop(); + * + * // Draw a bug. + * let x = random(0, 100); + * let y = random(0, 100); + * text('🦟', x, y); + * ``` + * + * In this version, the code to draw each eye is contained between its own + * push() and `pop()` functions. Doing so makes it + * easier to add details in the correct part of a drawing. + * + * push() and `pop()` contain the effects of the + * following functions: + * + * - fill() + * - noFill() + * - noStroke() + * - stroke() + * - tint() + * - noTint() + * - strokeWeight() + * - strokeCap() + * - strokeJoin() + * - imageMode() + * - rectMode() + * - ellipseMode() + * - colorMode() + * - textAlign() + * - textFont() + * - textSize() + * - textLeading() + * - applyMatrix() + * - resetMatrix() + * - rotate() + * - scale() + * - shearX() + * - shearY() + * - translate() + * + * In WebGL mode, push() and `pop()` contain the + * effects of a few additional styles: + * + * - setCamera() + * - ambientLight() + * - directionalLight() + * - pointLight() texture() + * - specularMaterial() + * - shininess() + * - normalMaterial() + * - shader() + * + * @method pop + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw the left circle. + * circle(25, 50, 20); + * + * // Begin the drawing group. + * push(); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Style the circle. + * strokeWeight(5); + * stroke('royalblue'); + * fill('orange'); + * + * // Draw the circle. + * circle(0, 0, 20); + * + * // End the drawing group. + * pop(); + * + * // Draw the right circle. + * circle(75, 50, 20); + * + * describe( + * 'Three circles drawn in a row on a gray background. The left and right circles are white with thin, black borders. The middle circle is orange with a thick, blue border.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(24); + * + * describe('A mosquito buzzes in front of a green frog. The frog follows the mouse as the user moves.'); + * } + * + * function draw() { + * background(200); + * + * // Begin the drawing group. + * push(); + * + * // Translate the origin to the mouse's position. + * translate(mouseX, mouseY); + * + * // Style the face. + * noStroke(); + * fill('green'); + * + * // Draw a face. + * circle(0, 0, 60); + * + * // Style the eyes. + * fill('white'); + * + * // Draw the left eye. + * push(); + * translate(-20, -20); + * ellipse(0, 0, 30, 20); + * fill('black'); + * circle(0, 0, 8); + * pop(); + * + * // Draw the right eye. + * push(); + * translate(20, -20); + * ellipse(0, 0, 30, 20); + * fill('black'); + * circle(0, 0, 8); + * pop(); + * + * // End the drawing group. + * pop(); + * + * // Draw a bug. + * let x = random(0, 100); + * let y = random(0, 100); + * text('🦟', x, y); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'Two spheres drawn on a gray background. The sphere on the left is red and lit from the front. The sphere on the right is a blue wireframe.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the red sphere. + * push(); + * translate(-25, 0, 0); + * noStroke(); + * directionalLight(255, 0, 0, 0, 0, -1); + * sphere(20); + * pop(); + * + * // Draw the blue sphere. + * push(); + * translate(25, 0, 0); + * strokeWeight(0.3); + * stroke(0, 0, 255); + * noFill(); + * sphere(20); + * pop(); + * } + * + *
        + */ + _main.default.prototype.pop = function () { + var style = this._styles.pop(); + if (style) { + this._renderer.pop(style.renderer); + Object.assign(this, style.props); + } else { + console.warn('pop() was called without matching push()'); + } + }; + /** + * Runs the code in draw() once. + * + * By default, draw() tries to run 60 times per + * second. Calling noLoop() stops + * draw() from repeating. Calling `redraw()` will + * execute the code in the draw() function a set + * number of times. + * + * The parameter, `n`, is optional. If a number is passed, as in `redraw(5)`, + * then the draw loop will run the given number of times. By default, `n` is + * 1. + * + * @method redraw + * @param {Integer} [n] number of times to run draw(). Defaults to 1. + * + * @example + *
        + * + * // Double-click the canvas to move the circle. + * + * let x = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * // Turn off the draw loop. + * noLoop(); + * + * describe( + * 'A white half-circle on the left edge of a gray square. The circle moves a little to the right when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw the circle. + * circle(x, 50, 20); + * + * // Increment x. + * x += 5; + * } + * + * // Run the draw loop when the user double-clicks. + * function doubleClicked() { + * redraw(); + * } + * + *
        + * + *
        + * + * // Double-click the canvas to move the circle. + * + * let x = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * // Turn off the draw loop. + * noLoop(); + * + * describe( + * 'A white half-circle on the left edge of a gray square. The circle hops to the right when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw the circle. + * circle(x, 50, 20); + * + * // Increment x. + * x += 5; + * } + * + * // Run the draw loop three times when the user double-clicks. + * function doubleClicked() { + * redraw(3); + * } + * + *
        + */ + _main.default.prototype.redraw = function (n) { + if (this._inUserDraw || !this._setupDone) { + return; + } + var numberOfRedraws = parseInt(n); + if (isNaN(numberOfRedraws) || numberOfRedraws < 1) { + numberOfRedraws = 1; + } + var context = this._isGlobal ? window : this; + if (typeof context.draw === 'function') { + if (typeof context.setup === 'undefined') { + context.scale(context._pixelDensity, context._pixelDensity); + } + for (var idxRedraw = 0; idxRedraw < numberOfRedraws; idxRedraw++) { + context.resetMatrix(); + if (this._accessibleOutputs.grid || this._accessibleOutputs.text) { + this._updateAccsOutput(); + } + if (context._renderer.isP3D) { + context._renderer._update(); + } + context._setProperty('frameCount', context.frameCount + 1); + this.callRegisteredHooksFor('pre'); + this._inUserDraw = true; + try { + context.draw(); + } finally { + this._inUserDraw = false; + } + this.callRegisteredHooksFor('post'); + } + } + }; + /** + * Creates a new sketch in "instance" mode. + * + * All p5.js sketches are instances of the `p5` class. Put another way, all + * p5.js sketches are objects with methods including `pInst.setup()`, + * `pInst.draw()`, `pInst.circle()`, and `pInst.fill()`. By default, sketches + * run in "global mode" to hide some of this complexity. + * + * In global mode, a default instance of the `p5` class is created + * automatically. The default `p5` instance searches the web page's source + * code for declarations of system functions such as `setup()`, `draw()`, + * and `mousePressed()`, then attaches those functions to itself as methods. + * Calling a function such as `circle()` in global mode actually calls the + * default `p5` object's `pInst.circle()` method. + * + * It's often helpful to isolate the code within sketches from the rest of the + * code on a web page. Two common use cases are web pages that use other + * JavaScript libraries and web pages with multiple sketches. "Instance mode" + * makes it easy to support both of these scenarios. + * + * Instance mode sketches support the same API as global mode sketches. They + * use a function to bundle, or encapsulate, an entire sketch. The function + * containing the sketch is then passed to the `p5()` constructor. + * + * The first parameter, `sketch`, is a function that contains the sketch. For + * example, the statement `new p5(mySketch)` would create a new instance mode + * sketch from a function named `mySketch`. The function should have one + * parameter, `p`, that's a `p5` object. + * + * The second parameter, `node`, is optional. If a string is passed, as in + * `new p5(mySketch, 'sketch-one')` the new instance mode sketch will become a + * child of the HTML element with the id `sketch-one`. If an HTML element is + * passed, as in `new p5(mySketch, myElement)`, then the new instance mode + * sketch will become a child of the `Element` object called `myElement`. + * + * @method p5 + * @param {Object} sketch function containing the sketch. + * @param {String|HTMLElement} node ID or reference to the HTML element that will contain the sketch. + * + * @example + *
        + * + * // Declare the function containing the sketch. + * function sketch(p) { + * + * // Declare the setup() method. + * p.setup = function () { + * p.createCanvas(100, 100); + * + * p.describe('A white circle drawn on a gray background.'); + * }; + * + * // Declare the draw() method. + * p.draw = function () { + * p.background(200); + * + * // Draw the circle. + * p.circle(50, 50, 20); + * }; + * } + * + * // Initialize the sketch. + * new p5(sketch); + * + *
        + * + *
        + * + * // Declare the function containing the sketch. + * function sketch(p) { + * // Create the sketch's variables within its scope. + * let x = 50; + * let y = 50; + * + * // Declare the setup() method. + * p.setup = function () { + * p.createCanvas(100, 100); + * + * p.describe('A white circle moves randomly on a gray background.'); + * }; + * + * // Declare the draw() method. + * p.draw = function () { + * p.background(200); + * + * // Update x and y. + * x += p.random(-1, 1); + * y += p.random(-1, 1); + * + * // Draw the circle. + * p.circle(x, y, 20); + * }; + * } + * + * // Initialize the sketch. + * new p5(sketch); + * + *
        + * + *
        + * + * // Declare the function containing the sketch. + * function sketch(p) { + * + * // Declare the setup() method. + * p.setup = function () { + * p.createCanvas(100, 100); + * + * p.describe('A white circle drawn on a gray background.'); + * }; + * + * // Declare the draw() method. + * p.draw = function () { + * p.background(200); + * + * // Draw the circle. + * p.circle(50, 50, 20); + * }; + * } + * + * // Select the web page's body element. + * let body = document.querySelector('body'); + * + * // Initialize the sketch and attach it to the web page's body. + * new p5(sketch, body); + * + *
        + * + *
        + * + * // Declare the function containing the sketch. + * function sketch(p) { + * + * // Declare the setup() method. + * p.setup = function () { + * p.createCanvas(100, 100); + * + * p.describe( + * 'A white circle drawn on a gray background. The circle follows the mouse as the user moves.' + * ); + * }; + * + * // Declare the draw() method. + * p.draw = function () { + * p.background(200); + * + * // Draw the circle. + * p.circle(p.mouseX, p.mouseY, 20); + * }; + * } + * + * // Initialize the sketch. + * new p5(sketch); + * + *
        + * + *
        + * + * // Declare the function containing the sketch. + * function sketch(p) { + * + * // Declare the setup() method. + * p.setup = function () { + * p.createCanvas(100, 100); + * + * p.describe( + * 'A white circle drawn on a gray background. The circle follows the mouse as the user moves. The circle becomes black when the user double-clicks.' + * ); + * }; + * + * // Declare the draw() method. + * p.draw = function () { + * p.background(200); + * + * // Draw the circle. + * p.circle(p.mouseX, p.mouseY, 20); + * }; + * + * // Declare the doubleClicked() method. + * p.doubleClicked = function () { + * // Change the fill color when the user double-clicks. + * p.fill(0); + * }; + * } + * + * // Initialize the sketch. + * new p5(sketch); + * + *
        + */ + var _default = _main.default; + exports.default = _default; + }, + { + './main': 303, + 'core-js/modules/es.object.assign': 199 + } + ], + 316: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('./main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } /** + * @module Transform + * @submodule Transform + * @for p5 + * @requires core + * @requires constants + */ + /** + * Applies a transformation matrix to the coordinate system. + * + * Transformations such as + * translate(), + * rotate(), and + * scale() + * use matrix-vector multiplication behind the scenes. A table of numbers, + * called a matrix, encodes each transformation. The values in the matrix + * then multiply each point on the canvas, which is represented by a vector. + * + * `applyMatrix()` allows for many transformations to be applied at once. See + * Wikipedia + * and MDN + * for more details about transformations. + * + * There are two ways to call `applyMatrix()` in two and three dimensions. + * + * In 2D mode, the parameters `a`, `b`, `c`, `d`, `e`, and `f`, correspond to + * elements in the following transformation matrix: + * + * > The transformation matrix used when applyMatrix is called in 2D mode. + * + * The numbers can be passed individually, as in + * `applyMatrix(2, 0, 0, 0, 2, 0)`. They can also be passed in an array, as in + * `applyMatrix([2, 0, 0, 0, 2, 0])`. + * + * In 3D mode, the parameters `a`, `b`, `c`, `d`, `e`, `f`, `g`, `h`, `i`, + * `j`, `k`, `l`, `m`, `n`, `o`, and `p` correspond to elements in the + * following transformation matrix: + * + * The transformation matrix used when applyMatrix is called in 3D mode. + * + * The numbers can be passed individually, as in + * `applyMatrix(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1)`. They can + * also be passed in an array, as in + * `applyMatrix([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1])`. + * + * By default, transformations accumulate. The + * push() and pop() functions + * can be used to isolate transformations within distinct drawing groups. + * + * Note: Transformations are reset at the beginning of the draw loop. Calling + * `applyMatrix()` inside the draw() function won't + * cause shapes to transform continuously. + * + * @method applyMatrix + * @param {Array} arr an array containing the elements of the transformation matrix. Its length should be either 6 (2D) or 16 (3D). + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white circle on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * applyMatrix(1, 0, 0, 1, 50, 50); + * + * // Draw the circle at coordinates (0, 0). + * circle(0, 0, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white circle on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * let m = [1, 0, 0, 1, 50, 50]; + * applyMatrix(m); + * + * // Draw the circle at coordinates (0, 0). + * circle(0, 0, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe("A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right."); + * } + * + * function draw() { + * background(200); + * + * // Rotate the coordinate system 1/8 turn. + * let angle = QUARTER_PI; + * let ca = cos(angle); + * let sa = sin(angle); + * applyMatrix(ca, sa, -sa, ca, 0, 0); + * + * // Draw a rectangle at coordinates (50, 0). + * rect(50, 0, 40, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'Two white squares on a gray background. The larger square appears at the top-center. The smaller square appears at the top-left.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw a square at (30, 20). + * square(30, 20, 40); + * + * // Scale the coordinate system by a factor of 0.5. + * applyMatrix(0.5, 0, 0, 0.5, 0, 0); + * + * // Draw a square at (30, 20). + * // It appears at (15, 10) after scaling. + * square(30, 20, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white quadrilateral on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the shear factor. + * let angle = QUARTER_PI; + * let shearFactor = 1 / tan(HALF_PI - angle); + * + * // Shear the coordinate system along the x-axis. + * applyMatrix(1, 0, shearFactor, 1, 0, 0); + * + * // Draw the square. + * square(0, 0, 50); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube rotates slowly against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system a little more each frame. + * let angle = frameCount * 0.01; + * let ca = cos(angle); + * let sa = sin(angle); + * applyMatrix(ca, 0, sa, 0, 0, 1, 0, 0, -sa, 0, ca, 0, 0, 0, 0, 1); + * + * // Draw a box. + * box(); + * } + * + *
        + */ + /** + * @method applyMatrix + * @param {Number} a an element of the transformation matrix. + * @param {Number} b an element of the transformation matrix. + * @param {Number} c an element of the transformation matrix. + * @param {Number} d an element of the transformation matrix. + * @param {Number} e an element of the transformation matrix. + * @param {Number} f an element of the transformation matrix. + * @chainable + */ + /** + * @method applyMatrix + * @param {Number} a + * @param {Number} b + * @param {Number} c + * @param {Number} d + * @param {Number} e + * @param {Number} f + * @param {Number} g an element of the transformation matrix. + * @param {Number} h an element of the transformation matrix. + * @param {Number} i an element of the transformation matrix. + * @param {Number} j an element of the transformation matrix. + * @param {Number} k an element of the transformation matrix. + * @param {Number} l an element of the transformation matrix. + * @param {Number} m an element of the transformation matrix. + * @param {Number} n an element of the transformation matrix. + * @param {Number} o an element of the transformation matrix. + * @param {Number} p an element of the transformation matrix. + * @chainable + */ + + _main.default.prototype.applyMatrix = function () { + var isTypedArray = (arguments.length <= 0 ? undefined : arguments[0]) instanceof Object.getPrototypeOf(Uint8Array); + if (Array.isArray(arguments.length <= 0 ? undefined : arguments[0]) || isTypedArray) { + var _this$_renderer; + (_this$_renderer = this._renderer).applyMatrix.apply(_this$_renderer, _toConsumableArray(arguments.length <= 0 ? undefined : arguments[0])); + } else { + var _this$_renderer2; + (_this$_renderer2 = this._renderer).applyMatrix.apply(_this$_renderer2, arguments); + } + return this; + }; + /** + * Clears all transformations applied to the coordinate system. + * + * @method resetMatrix + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'Two circles drawn on a gray background. A blue circle is at the top-left and a red circle is at the bottom-right.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw a blue circle at the coordinates (25, 25). + * fill('blue'); + * circle(25, 25, 20); + * + * // Clear all transformations. + * // The origin is now at the top-left corner. + * resetMatrix(); + * + * // Draw a red circle at the coordinates (25, 25). + * fill('red'); + * circle(25, 25, 20); + * } + * + *
        + */ + _main.default.prototype.resetMatrix = function () { + this._renderer.resetMatrix(); + return this; + }; + /** + * Rotates the coordinate system. + * + * By default, the positive x-axis points to the right and the positive y-axis + * points downward. The `rotate()` function changes this orientation by + * rotating the coordinate system about the origin. Everything drawn after + * `rotate()` is called will appear to be rotated. + * + * The first parameter, `angle`, is the amount to rotate. For example, calling + * `rotate(1)` rotates the coordinate system clockwise 1 radian which is + * nearly 57˚. `rotate()` interprets angle values using the current + * angleMode(). + * + * The second parameter, `axis`, is optional. It's used to orient 3D rotations + * in WebGL mode. If a p5.Vector is passed, as in + * `rotate(QUARTER_PI, myVector)`, then the coordinate system will rotate + * `QUARTER_PI` radians about `myVector`. If an array of vector components is + * passed, as in `rotate(QUARTER_PI, [1, 0, 0])`, then the coordinate system + * will rotate `QUARTER_PI` radians about a vector with the components + * `[1, 0, 0]`. + * + * By default, transformations accumulate. For example, calling `rotate(1)` + * twice has the same effect as calling `rotate(2)` once. The + * push() and pop() functions + * can be used to isolate transformations within distinct drawing groups. + * + * Note: Transformations are reset at the beginning of the draw loop. Calling + * `rotate(1)` inside the draw() function won't cause + * shapes to spin. + * + * @method rotate + * @param {Number} angle angle of rotation in the current angleMode(). + * @param {p5.Vector|Number[]} [axis] axis to rotate about in 3D. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * "A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right." + * ); + * } + * + * function draw() { + * background(200); + * + * // Rotate the coordinate system 1/8 turn. + * rotate(QUARTER_PI); + * + * // Draw a rectangle at coordinates (50, 0). + * rect(50, 0, 40, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * "A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right." + * ); + * } + * + * function draw() { + * background(200); + * + * // Rotate the coordinate system 1/16 turn. + * rotate(QUARTER_PI / 2); + * + * // Rotate the coordinate system another 1/16 turn. + * rotate(QUARTER_PI / 2); + * + * // Draw a rectangle at coordinates (50, 0). + * rect(50, 0, 40, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Use degrees. + * angleMode(DEGREES); + * + * describe( + * "A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right." + * ); + * } + * + * function draw() { + * background(200); + * + * // Rotate the coordinate system 1/8 turn. + * rotate(45); + * + * // Draw a rectangle at coordinates (50, 0). + * rect(50, 0, 40, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A white rectangle on a gray background. The rectangle rotates slowly about the top-left corner. It disappears and reappears periodically.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Rotate the coordinate system a little more each frame. + * let angle = frameCount * 0.01; + * rotate(angle); + * + * // Draw a rectangle at coordinates (50, 0). + * rect(50, 0, 40, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe("A cube on a gray background. The cube's front face points to the top-right."); + * } + * + * function draw() { + * background(200); + * + * // Rotate the coordinate system 1/8 turn about + * // the axis [1, 1, 0]. + * let axis = createVector(1, 1, 0); + * rotate(QUARTER_PI, axis); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe("A cube on a gray background. The cube's front face points to the top-right."); + * } + * + * function draw() { + * background(200); + * + * // Rotate the coordinate system 1/8 turn about + * // the axis [1, 1, 0]. + * let axis = [1, 1, 0]; + * rotate(QUARTER_PI, axis); + * + * // Draw a box. + * box(); + * } + * + *
        + */ + _main.default.prototype.rotate = function (angle, axis) { + _main.default._validateParameters('rotate', arguments); + this._renderer.rotate(this._toRadians(angle), axis); + return this; + }; + /** + * Rotates the coordinate system about the x-axis in WebGL mode. + * + * The parameter, `angle`, is the amount to rotate. For example, calling + * `rotateX(1)` rotates the coordinate system about the x-axis by 1 radian. + * `rotateX()` interprets angle values using the current + * angleMode(). + * + * By default, transformations accumulate. For example, calling `rotateX(1)` + * twice has the same effect as calling `rotateX(2)` once. The + * push() and pop() functions + * can be used to isolate transformations within distinct drawing groups. + * + * Note: Transformations are reset at the beginning of the draw loop. Calling + * `rotateX(1)` inside the draw() function won't cause + * shapes to spin. + * + * @method rotateX + * @param {Number} angle angle of rotation in the current angleMode(). + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system 1/8 turn. + * rotateX(QUARTER_PI); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system 1/16 turn. + * rotateX(QUARTER_PI / 2); + * + * // Rotate the coordinate system 1/16 turn. + * rotateX(QUARTER_PI / 2); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Use degrees. + * angleMode(DEGREES); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system 1/8 turn. + * rotateX(45); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube rotates slowly against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system a little more each frame. + * let angle = frameCount * 0.01; + * rotateX(angle); + * + * // Draw a box. + * box(); + * } + * + *
        + */ + _main.default.prototype.rotateX = function (angle) { + this._assert3d('rotateX'); + _main.default._validateParameters('rotateX', arguments); + this._renderer.rotateX(this._toRadians(angle)); + return this; + }; + /** + * Rotates the coordinate system about the y-axis in WebGL mode. + * + * The parameter, `angle`, is the amount to rotate. For example, calling + * `rotateY(1)` rotates the coordinate system about the y-axis by 1 radian. + * `rotateY()` interprets angle values using the current + * angleMode(). + * + * By default, transformations accumulate. For example, calling `rotateY(1)` + * twice has the same effect as calling `rotateY(2)` once. The + * push() and pop() functions + * can be used to isolate transformations within distinct drawing groups. + * + * Note: Transformations are reset at the beginning of the draw loop. Calling + * `rotateY(1)` inside the draw() function won't cause + * shapes to spin. + * + * @method rotateY + * @param {Number} angle angle of rotation in the current angleMode(). + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system 1/8 turn. + * rotateY(QUARTER_PI); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system 1/16 turn. + * rotateY(QUARTER_PI / 2); + * + * // Rotate the coordinate system 1/16 turn. + * rotateY(QUARTER_PI / 2); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Use degrees. + * angleMode(DEGREES); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system 1/8 turn. + * rotateY(45); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube rotates slowly against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system a little more each frame. + * let angle = frameCount * 0.01; + * rotateY(angle); + * + * // Draw a box. + * box(); + * } + * + *
        + */ + _main.default.prototype.rotateY = function (angle) { + this._assert3d('rotateY'); + _main.default._validateParameters('rotateY', arguments); + this._renderer.rotateY(this._toRadians(angle)); + return this; + }; + /** + * Rotates the coordinate system about the z-axis in WebGL mode. + * + * The parameter, `angle`, is the amount to rotate. For example, calling + * `rotateZ(1)` rotates the coordinate system about the z-axis by 1 radian. + * `rotateZ()` interprets angle values using the current + * angleMode(). + * + * By default, transformations accumulate. For example, calling `rotateZ(1)` + * twice has the same effect as calling `rotateZ(2)` once. The + * push() and pop() functions + * can be used to isolate transformations within distinct drawing groups. + * + * Note: Transformations are reset at the beginning of the draw loop. Calling + * `rotateZ(1)` inside the draw() function won't cause + * shapes to spin. + * + * @method rotateZ + * @param {Number} angle angle of rotation in the current angleMode(). + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system 1/8 turn. + * rotateZ(QUARTER_PI); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system 1/16 turn. + * rotateZ(QUARTER_PI / 2); + * + * // Rotate the coordinate system 1/16 turn. + * rotateZ(QUARTER_PI / 2); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Use degrees. + * angleMode(DEGREES); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system 1/8 turn. + * rotateZ(45); + * + * // Draw a box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube rotates slowly against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rotate the coordinate system a little more each frame. + * let angle = frameCount * 0.01; + * rotateZ(angle); + * + * // Draw a box. + * box(); + * } + * + *
        + */ + _main.default.prototype.rotateZ = function (angle) { + this._assert3d('rotateZ'); + _main.default._validateParameters('rotateZ', arguments); + this._renderer.rotateZ(this._toRadians(angle)); + return this; + }; + /** + * Scales the coordinate system. + * + * By default, shapes are drawn at their original scale. A rectangle that's 50 + * pixels wide appears to take up half the width of a 100 pixel-wide canvas. + * The `scale()` function can shrink or stretch the coordinate system so that + * shapes appear at different sizes. There are two ways to call `scale()` with + * parameters that set the scale factor(s). + * + * The first way to call `scale()` uses numbers to set the amount of scaling. + * The first parameter, `s`, sets the amount to scale each axis. For example, + * calling `scale(2)` stretches the x-, y-, and z-axes by a factor of 2. The + * next two parameters, `y` and `z`, are optional. They set the amount to + * scale the y- and z-axes. For example, calling `scale(2, 0.5, 1)` stretches + * the x-axis by a factor of 2, shrinks the y-axis by a factor of 0.5, and + * leaves the z-axis unchanged. + * + * The second way to call `scale()` uses a p5.Vector + * object to set the scale factors. For example, calling `scale(myVector)` + * uses the x-, y-, and z-components of `myVector` to set the amount of + * scaling along the x-, y-, and z-axes. Doing so is the same as calling + * `scale(myVector.x, myVector.y, myVector.z)`. + * + * By default, transformations accumulate. For example, calling `scale(1)` + * twice has the same effect as calling `scale(2)` once. The + * push() and pop() functions + * can be used to isolate transformations within distinct drawing groups. + * + * Note: Transformations are reset at the beginning of the draw loop. Calling + * `scale(2)` inside the draw() function won't cause + * shapes to grow continuously. + * + * @method scale + * @param {Number|p5.Vector|Number[]} s amount to scale along the positive x-axis. + * @param {Number} [y] amount to scale along the positive y-axis. Defaults to `s`. + * @param {Number} [z] amount to scale along the positive z-axis. Defaults to `y`. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'Two white squares on a gray background. The larger square appears at the top-center. The smaller square appears at the top-left.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw a square at (30, 20). + * square(30, 20, 40); + * + * // Scale the coordinate system by a factor of 0.5. + * scale(0.5); + * + * // Draw a square at (30, 20). + * // It appears at (15, 10) after scaling. + * square(30, 20, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A rectangle and a square drawn in white on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Draw a square at (30, 20). + * square(30, 20, 40); + * + * // Scale the coordinate system by factors of + * // 0.5 along the x-axis and + * // 1.3 along the y-axis. + * scale(0.5, 1.3); + * + * // Draw a square at (30, 20). + * // It appears as a rectangle at (15, 26) after scaling. + * square(30, 20, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A rectangle and a square drawn in white on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Draw a square at (30, 20). + * square(30, 20, 40); + * + * // Create a p5.Vector object. + * let v = createVector(0.5, 1.3); + * + * // Scale the coordinate system by factors of + * // 0.5 along the x-axis and + * // 1.3 along the y-axis. + * scale(v); + * + * // Draw a square at (30, 20). + * // It appears as a rectangle at (15, 26) after scaling. + * square(30, 20, 40); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'A red box and a blue box drawn on a gray background. The red box appears embedded in the blue box.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the spheres. + * noStroke(); + * + * // Draw the red sphere. + * fill('red'); + * box(); + * + * // Scale the coordinate system by factors of + * // 0.5 along the x-axis and + * // 1.3 along the y-axis and + * // 2 along the z-axis. + * scale(0.5, 1.3, 2); + * + * // Draw the blue sphere. + * fill('blue'); + * box(); + * } + * + *
        + */ + /** + * @method scale + * @param {p5.Vector|Number[]} scales vector whose components should be used to scale. + * @chainable + */ + _main.default.prototype.scale = function (x, y, z) { + _main.default._validateParameters('scale', arguments); + // Only check for Vector argument type if Vector is available + if (x instanceof _main.default.Vector) { + var v = x; + x = v.x; + y = v.y; + z = v.z; + } else if (Array.isArray(x)) { + var rg = x; + x = rg[0]; + y = rg[1]; + z = rg[2] || 1; + } + if (isNaN(y)) { + y = z = x; + } else if (isNaN(z)) { + z = 1; + } + this._renderer.scale(x, y, z); + return this; + }; + /** + * Shears the x-axis so that shapes appear skewed. + * + * By default, the x- and y-axes are perpendicular. The `shearX()` function + * transforms the coordinate system so that x-coordinates are translated while + * y-coordinates are fixed. + * + * The first parameter, `angle`, is the amount to shear. For example, calling + * `shearX(1)` transforms all x-coordinates using the formula + * `x = x + y * tan(angle)`. `shearX()` interprets angle values using the + * current angleMode(). + * + * By default, transformations accumulate. For example, calling + * `shearX(1)` twice has the same effect as calling `shearX(2)` once. The + * push() and + * pop() functions can be used to isolate + * transformations within distinct drawing groups. + * + * Note: Transformations are reset at the beginning of the draw loop. Calling + * `shearX(1)` inside the draw() function won't + * cause shapes to shear continuously. + * + * @method shearX + * @param {Number} angle angle to shear by in the current angleMode(). + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white quadrilateral on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Shear the coordinate system along the x-axis. + * shearX(QUARTER_PI); + * + * // Draw the square. + * square(0, 0, 50); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Use degrees. + * angleMode(DEGREES); + * + * describe('A white quadrilateral on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Shear the coordinate system along the x-axis. + * shearX(45); + * + * // Draw the square. + * square(0, 0, 50); + * } + * + *
        + */ + _main.default.prototype.shearX = function (angle) { + _main.default._validateParameters('shearX', arguments); + var rad = this._toRadians(angle); + this._renderer.applyMatrix(1, 0, Math.tan(rad), 1, 0, 0); + return this; + }; + /** + * Shears the y-axis so that shapes appear skewed. + * + * By default, the x- and y-axes are perpendicular. The `shearY()` function + * transforms the coordinate system so that y-coordinates are translated while + * x-coordinates are fixed. + * + * The first parameter, `angle`, is the amount to shear. For example, calling + * `shearY(1)` transforms all y-coordinates using the formula + * `y = y + x * tan(angle)`. `shearY()` interprets angle values using the + * current angleMode(). + * + * By default, transformations accumulate. For example, calling + * `shearY(1)` twice has the same effect as calling `shearY(2)` once. The + * push() and + * pop() functions can be used to isolate + * transformations within distinct drawing groups. + * + * Note: Transformations are reset at the beginning of the draw loop. Calling + * `shearY(1)` inside the draw() function won't + * cause shapes to shear continuously. + * + * @method shearY + * @param {Number} angle angle to shear by in the current angleMode(). + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white quadrilateral on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Shear the coordinate system along the x-axis. + * shearY(QUARTER_PI); + * + * // Draw the square. + * square(0, 0, 50); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Use degrees. + * angleMode(DEGREES); + * + * describe('A white quadrilateral on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Shear the coordinate system along the x-axis. + * shearY(45); + * + * // Draw the square. + * square(0, 0, 50); + * } + * + *
        + */ + _main.default.prototype.shearY = function (angle) { + _main.default._validateParameters('shearY', arguments); + var rad = this._toRadians(angle); + this._renderer.applyMatrix(1, Math.tan(rad), 0, 1, 0, 0); + return this; + }; + /** + * Translates the coordinate system. + * + * By default, the origin `(0, 0)` is at the sketch's top-left corner in 2D + * mode and center in WebGL mode. The `translate()` function shifts the origin + * to a different position. Everything drawn after `translate()` is called + * will appear to be shifted. There are two ways to call `translate()` with + * parameters that set the origin's position. + * + * The first way to call `translate()` uses numbers to set the amount of + * translation. The first two parameters, `x` and `y`, set the amount to + * translate along the positive x- and y-axes. For example, calling + * `translate(20, 30)` translates the origin 20 pixels along the x-axis and 30 + * pixels along the y-axis. The third parameter, `z`, is optional. It sets the + * amount to translate along the positive z-axis. For example, calling + * `translate(20, 30, 40)` translates the origin 20 pixels along the x-axis, + * 30 pixels along the y-axis, and 40 pixels along the z-axis. + * + * The second way to call `translate()` uses a + * p5.Vector object to set the amount of + * translation. For example, calling `translate(myVector)` uses the x-, y-, + * and z-components of `myVector` to set the amount to translate along the x-, + * y-, and z-axes. Doing so is the same as calling + * `translate(myVector.x, myVector.y, myVector.z)`. + * + * By default, transformations accumulate. For example, calling + * `translate(10, 0)` twice has the same effect as calling + * `translate(20, 0)` once. The push() and + * pop() functions can be used to isolate + * transformations within distinct drawing groups. + * + * Note: Transformations are reset at the beginning of the draw loop. Calling + * `translate(10, 0)` inside the draw() function won't + * cause shapes to move continuously. + * + * @method translate + * @param {Number} x amount to translate along the positive x-axis. + * @param {Number} y amount to translate along the positive y-axis. + * @param {Number} [z] amount to translate along the positive z-axis. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white circle on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw a circle at coordinates (0, 0). + * circle(0, 0, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'Two circles drawn on a gray background. The blue circle on the right overlaps the red circle at the center.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Draw the red circle. + * fill('red'); + * circle(0, 0, 40); + * + * // Translate the origin to the right. + * translate(25, 0); + * + * // Draw the blue circle. + * fill('blue'); + * circle(0, 0, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white circle moves slowly from left to right on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the x-coordinate. + * let x = frameCount * 0.2; + * + * // Translate the origin. + * translate(x, 50); + * + * // Draw a circle at coordinates (0, 0). + * circle(0, 0, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white circle on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Create a p5.Vector object. + * let v = createVector(50, 50); + * + * // Translate the origin by the vector. + * translate(v); + * + * // Draw a circle at coordinates (0, 0). + * circle(0, 0, 40); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'Two spheres sitting side-by-side on gray background. The sphere at the center is red. The sphere on the right is blue.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Turn on the lights. + * lights(); + * + * // Style the spheres. + * noStroke(); + * + * // Draw the red sphere. + * fill('red'); + * sphere(10); + * + * // Translate the origin to the right. + * translate(30, 0, 0); + * + * // Draw the blue sphere. + * fill('blue'); + * sphere(10); + * } + * + *
        + */ + /** + * @method translate + * @param {p5.Vector} vector vector by which to translate. + * @chainable + */ + _main.default.prototype.translate = function (x, y, z) { + _main.default._validateParameters('translate', arguments); + if (this._renderer.isP3D) { + this._renderer.translate(x, y, z); + } else { + this._renderer.translate(x, y); + } + return this; + }; + var _default = _main.default; + exports.default = _default; + }, + { + './main': 303, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254, + 'core-js/modules/es.typed-array.uint8-array': 257, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 317: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.ends-with'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.ends-with'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } /** + * @module Data + * @submodule LocalStorage + * @requires core + * + * This module defines the p5 methods for working with local storage + */ + /** + * Stores a value in the web browser's local storage. + * + * Web browsers can save small amounts of data using the built-in + * localStorage object. + * Data stored in `localStorage` can be retrieved at any point, even after + * refreshing a page or restarting the browser. Data are stored as key-value + * pairs. + * + * `storeItem()` makes it easy to store values in `localStorage` and + * getItem() makes it easy to retrieve them. + * + * The first parameter, `key`, is the name of the value to be stored as a + * string. + * + * The second parameter, `value`, is the value to be stored. Values can have + * any type. + * + * Note: Sensitive data such as passwords or personal information shouldn't be + * stored in `localStorage`. + * + * @method storeItem + * @for p5 + * @param {String} key name of the value. + * @param {String|Number|Boolean|Object|Array} value value to be stored. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Store the player's name. + * storeItem('name', 'Feist'); + * + * // Store the player's score. + * storeItem('score', 1234); + * + * describe('The text "Feist: 1234" written in black on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Retrieve the name. + * let name = getItem('name'); + * + * // Retrieve the score. + * let score = getItem('score'); + * + * // Display the score. + * text(`${name}: ${score}`, 50, 50); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create an object. + * let p = { x: 50, y: 50 }; + * + * // Store the object. + * storeItem('position', p); + * + * describe('A white circle on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Retrieve the object. + * let p = getItem('position'); + * + * // Draw the circle. + * circle(p.x, p.y, 30); + * } + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Color object. + * let c = color('deeppink'); + * + * // Store the object. + * storeItem('color', c); + * + * describe('A pink circle on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Retrieve the object. + * let c = getItem('color'); + * + * // Style the circle. + * fill(c); + * + * // Draw the circle. + * circle(50, 50, 30); + * } + * + * + */ + + _main.default.prototype.storeItem = function (key, value) { + if (typeof key !== 'string') { + console.log('The argument that you passed to storeItem() - '.concat(key, ' is not a string.')); + } + if (key.endsWith('p5TypeID')) { + console.log('The argument that you passed to storeItem() - '.concat(key, ' must not end with \'p5TypeID\'.')); + } + if (typeof value === 'undefined') { + console.log('You cannot store undefined variables using storeItem().'); + } + var type = _typeof(value); + switch (type) { + case 'number': + case 'boolean': + value = value.toString(); + break; + case 'object': + if (value instanceof _main.default.Color) { + type = 'p5.Color'; + } else if (value instanceof _main.default.Vector) { + type = 'p5.Vector'; + var coord = [ + value.x, + value.y, + value.z + ]; + value = coord; + } + value = JSON.stringify(value); + break; + case 'string': + default: + break; + } + localStorage.setItem(key, value); + var typeKey = ''.concat(key, 'p5TypeID'); + localStorage.setItem(typeKey, type); + }; + /** + * Returns a value in the web browser's local storage. + * + * Web browsers can save small amounts of data using the built-in + * localStorage object. + * Data stored in `localStorage` can be retrieved at any point, even after + * refreshing a page or restarting the browser. Data are stored as key-value + * pairs. + * + * storeItem() makes it easy to store values in + * `localStorage` and `getItem()` makes it easy to retrieve them. + * + * The first parameter, `key`, is the name of the value to be stored as a + * string. + * + * The second parameter, `value`, is the value to be retrieved a string. For + * example, calling `getItem('size')` retrieves the value with the key `size`. + * + * Note: Sensitive data such as passwords or personal information shouldn't be + * stored in `localStorage`. + * + * @method getItem + * @for p5 + * @param {String} key name of the value. + * @return {String|Number|Boolean|Object|Array} stored item. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Store the player's name. + * storeItem('name', 'Feist'); + * + * // Store the player's score. + * storeItem('score', 1234); + * + * describe('The text "Feist: 1234" written in black on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Retrieve the name. + * let name = getItem('name'); + * + * // Retrieve the score. + * let score = getItem('score'); + * + * // Display the score. + * text(`${name}: ${score}`, 50, 50); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create an object. + * let p = { x: 50, y: 50 }; + * + * // Store the object. + * storeItem('position', p); + * + * describe('A white circle on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Retrieve the object. + * let p = getItem('position'); + * + * // Draw the circle. + * circle(p.x, p.y, 30); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Color object. + * let c = color('deeppink'); + * + * // Store the object. + * storeItem('color', c); + * + * describe('A pink circle on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Retrieve the object. + * let c = getItem('color'); + * + * // Style the circle. + * fill(c); + * + * // Draw the circle. + * circle(50, 50, 30); + * } + * + *
        + */ + _main.default.prototype.getItem = function (key) { + var value = localStorage.getItem(key); + var type = localStorage.getItem(''.concat(key, 'p5TypeID')); + if (typeof type === 'undefined') { + console.log('Unable to determine type of item stored under '.concat(key, 'in local storage. Did you save the item with something other than setItem()?')); + } else if (value !== null) { + switch (type) { + case 'number': + value = parseFloat(value); + break; + case 'boolean': + value = value === 'true'; + break; + case 'object': + value = JSON.parse(value); + break; + case 'p5.Color': + value = JSON.parse(value); + value = this.color.apply(this, _toConsumableArray(value.levels)); + break; + case 'p5.Vector': + value = JSON.parse(value); + value = this.createVector.apply(this, _toConsumableArray(value)); + break; + case 'string': + default: + break; + } + } + return value; + }; + /** + * Removes all items in the web browser's local storage. + * + * Web browsers can save small amounts of data using the built-in + * localStorage object. + * Data stored in `localStorage` can be retrieved at any point, even after + * refreshing a page or restarting the browser. Data are stored as key-value + * pairs. Calling `clearStorage()` removes all data from `localStorage`. + * + * Note: Sensitive data such as passwords or personal information shouldn't be + * stored in `localStorage`. + * + * @method clearStorage + * @for p5 + * + * @example + *
        + * + * // Double-click to clear localStorage. + * + * function setup() { + * createCanvas(100, 100); + * + * // Store the player's name. + * storeItem('name', 'Feist'); + * + * // Store the player's score. + * storeItem('score', 1234); + * + * describe( + * 'The text "Feist: 1234" written in black on a gray background. The text "null: null" appears when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Retrieve the name. + * let name = getItem('name'); + * + * // Retrieve the score. + * let score = getItem('score'); + * + * // Display the score. + * text(`${name}: ${score}`, 50, 50); + * } + * + * // Clear localStorage when the user double-clicks. + * function doubleClicked() { + * clearStorage(); + * } + * + *
        + */ + _main.default.prototype.clearStorage = function () { + var _this = this; + var keys = Object.keys(localStorage); + keys.forEach(function (key) { + if (key.endsWith('p5TypeID')) { + _this.removeItem(key.replace('p5TypeID', '')); + } + }); + }; + /** + * Removes an item from the web browser's local storage. + * + * Web browsers can save small amounts of data using the built-in + * localStorage object. + * Data stored in `localStorage` can be retrieved at any point, even after + * refreshing a page or restarting the browser. Data are stored as key-value + * pairs. + * + * storeItem() makes it easy to store values in + * `localStorage` and `removeItem()` makes it easy to delete them. + * + * The parameter, `key`, is the name of the value to remove as a string. For + * example, calling `removeItem('size')` removes the item with the key `size`. + * + * Note: Sensitive data such as passwords or personal information shouldn't be + * stored in `localStorage`. + * + * @method removeItem + * @param {String} key name of the value to remove. + * @for p5 + * + * @example + *
        + * + * // Double-click to remove an item from localStorage. + * + * function setup() { + * createCanvas(100, 100); + * + * // Store the player's name. + * storeItem('name', 'Feist'); + * + * // Store the player's score. + * storeItem('score', 1234); + * + * describe( + * 'The text "Feist: 1234" written in black on a gray background. The text "Feist: null" appears when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Retrieve the name. + * let name = getItem('name'); + * + * // Retrieve the score. + * let score = getItem('score'); + * + * // Display the score. + * text(`${name}: ${score}`, 50, 50); + * } + * + * // Remove the word from localStorage when the user double-clicks. + * function doubleClicked() { + * removeItem('score'); + * } + * + *
        + */ + _main.default.prototype.removeItem = function (key) { + if (typeof key !== 'string') { + console.log('The argument that you passed to removeItem() - '.concat(key, ' is not a string.')); + } + localStorage.removeItem(key); + localStorage.removeItem(''.concat(key, 'p5TypeID')); + }; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.keys': 204, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.ends-with': 213, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.for-each': 260, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 318: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.object.keys'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + 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 _createSuper(Derived) { + function 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; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_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 _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; + } /** + * @module Data + * @submodule Dictionary + * @for p5.TypedDict + * @requires core + * + * This module defines the p5 methods for the p5 Dictionary classes. + * The classes StringDict and NumberDict are for storing and working + * with key-value pairs. + */ + /** + * + * Creates a new instance of p5.StringDict using the key-value pair + * or the object you provide. + * + * @method createStringDict + * @for p5 + * @param {String} key + * @param {String} value + * @return {p5.StringDict} + * + * @example + *
        + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * print(myDictionary.hasKey('p5')); // logs true to console + * + * let anotherDictionary = createStringDict({ happy: 'coding' }); + * print(anotherDictionary.hasKey('happy')); // logs true to console + * } + *
        + */ + /** + * @method createStringDict + * @param {Object} object object + * @return {p5.StringDict} + */ + + _main.default.prototype.createStringDict = function (key, value) { + _main.default._validateParameters('createStringDict', arguments); + return new _main.default.StringDict(key, value); + }; + /** + * + * Creates a new instance of p5.NumberDict using the key-value pair + * or object you provide. + * + * @method createNumberDict + * @for p5 + * @param {Number} key + * @param {Number} value + * @return {p5.NumberDict} + * + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict(100, 42); + * print(myDictionary.hasKey(100)); // logs true to console + * + * let anotherDictionary = createNumberDict({ 200: 84 }); + * print(anotherDictionary.hasKey(200)); // logs true to console + * } + *
        + */ + /** + * @method createNumberDict + * @param {Object} object object + * @return {p5.NumberDict} + */ + _main.default.prototype.createNumberDict = function (key, value) { + _main.default._validateParameters('createNumberDict', arguments); + return new _main.default.NumberDict(key, value); + }; + /** + * + * Base class for all p5.Dictionary types. Specifically + * typed Dictionary classes inherit from this class. + * + * @class p5.TypedDict + * @constructor + */ + _main.default.TypedDict = /*#__PURE__*/ function () { + function TypedDict(key, value) { + _classCallCheck(this, TypedDict); + if (key instanceof Object) { + this.data = key; + } else { + this.data = { + }; + this.data[key] = value; + } + return this; + } /** + * Returns the number of key-value pairs currently stored in the Dictionary. + * + * @method size + * @return {Integer} the number of key-value pairs in the Dictionary + * + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict(1, 10); + * myDictionary.create(2, 20); + * myDictionary.create(3, 30); + * print(myDictionary.size()); // logs 3 to the console + * } + *
        + */ + + _createClass(TypedDict, [ + { + key: 'size', + value: function size() { + return Object.keys(this.data).length; + } /** + * Returns true if the given key exists in the Dictionary, + * otherwise returns false. + * + * @method hasKey + * @param {Number|String} key that you want to look up + * @return {Boolean} whether that key exists in Dictionary + * + * @example + *
        + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * print(myDictionary.hasKey('p5')); // logs true to console + * } + *
        + */ + + }, + { + key: 'hasKey', + value: function hasKey(key) { + return this.data.hasOwnProperty(key); + } /** + * Returns the value stored at the given key. + * + * @method get + * @param {Number|String} the key you want to access + * @return {Number|String} the value stored at that key + * + * @example + *
        + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * let myValue = myDictionary.get('p5'); + * print(myValue === 'js'); // logs true to console + * } + *
        + */ + + }, + { + key: 'get', + value: function get(key) { + if (this.data.hasOwnProperty(key)) { + return this.data[key]; + } else { + console.log(''.concat(key, ' does not exist in this Dictionary')); + } + } /** + * Updates the value associated with the given key in case it already exists + * in the Dictionary. Otherwise a new key-value pair is added. + * + * @method set + * @param {Number|String} key + * @param {Number|String} value + * + * @example + *
        + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * myDictionary.set('p5', 'JS'); + * myDictionary.print(); // logs "key: p5 - value: JS" to console + * } + *
        + */ + + }, + { + key: 'set', + value: function set(key, value) { + if (this._validate(value)) { + this.data[key] = value; + } else { + console.log('Those values dont work for this dictionary type.'); + } + } /** + * private helper function to handle the user passing in objects + * during construction or calls to create() + */ + + }, + { + key: '_addObj', + value: function _addObj(obj) { + for (var key in obj) { + this.set(key, obj[key]); + } + } /** + * Creates a new key-value pair in the Dictionary. + * + * @method create + * @param {Number|String} key + * @param {Number|String} value + * + * @example + *
        + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * myDictionary.create('happy', 'coding'); + * myDictionary.print(); + * // above logs "key: p5 - value: js, key: happy - value: coding" to console + * } + *
        + */ + /** + * @method create + * @param {Object} obj key/value pair + */ + + }, + { + key: 'create', + value: function create(key, value) { + if (key instanceof Object && typeof value === 'undefined') { + this._addObj(key); + } else if (typeof key !== 'undefined') { + this.set(key, value); + } else { + console.log('In order to create a new Dictionary entry you must pass ' + 'an object or a key, value pair'); + } + } /** + * Removes all previously stored key-value pairs from the Dictionary. + * + * @method clear + * @example + *
        + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * print(myDictionary.hasKey('p5')); // prints 'true' + * myDictionary.clear(); + * print(myDictionary.hasKey('p5')); // prints 'false' + * } + * + *
        + */ + + }, + { + key: 'clear', + value: function clear() { + this.data = { + }; + } /** + * Removes the key-value pair stored at the given key from the Dictionary. + * + * @method remove + * @param {Number|String} key for the pair to remove + * + * @example + *
        + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * myDictionary.create('happy', 'coding'); + * myDictionary.print(); + * // above logs "key: p5 - value: js, key: happy - value: coding" to console + * myDictionary.remove('p5'); + * myDictionary.print(); + * // above logs "key: happy value: coding" to console + * } + *
        + */ + + }, + { + key: 'remove', + value: function remove(key) { + if (this.data.hasOwnProperty(key)) { + delete this.data[key]; + } else { + throw new Error(''.concat(key, ' does not exist in this Dictionary')); + } + } /** + * Logs the set of items currently stored in the Dictionary to the console. + * + * @method print + * + * @example + *
        + * + * function setup() { + * let myDictionary = createStringDict('p5', 'js'); + * myDictionary.create('happy', 'coding'); + * myDictionary.print(); + * // above logs "key: p5 - value: js, key: happy - value: coding" to console + * } + * + *
        + */ + + }, + { + key: 'print', + value: function print() { + for (var item in this.data) { + console.log('key:'.concat(item, ' value:').concat(this.data[item])); + } + } /** + * Converts the Dictionary into a CSV file for local download. + * + * @method saveTable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * text('click here to save', 10, 10, 70, 80); + * } + * + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * createStringDict({ + * john: 1940, + * paul: 1942, + * george: 1943, + * ringo: 1940 + * }).saveTable('beatles'); + * } + * } + * + *
        + */ + + }, + { + key: 'saveTable', + value: function saveTable(filename) { + var output = ''; + for (var key in this.data) { + output += ''.concat(key, ',').concat(this.data[key], '\n'); + } + var blob = new Blob([output], { + type: 'text/csv' + }); + _main.default.prototype.downloadFile(blob, filename || 'mycsv', 'csv'); + } /** + * Converts the Dictionary into a JSON file for local download. + * + * @method saveJSON + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * text('click here to save', 10, 10, 70, 80); + * } + * + * function mousePressed() { + * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) { + * createStringDict({ + * john: 1940, + * paul: 1942, + * george: 1943, + * ringo: 1940 + * }).saveJSON('beatles'); + * } + * } + * + *
        + */ + + }, + { + key: 'saveJSON', + value: function saveJSON(filename, opt) { + _main.default.prototype.saveJSON(this.data, filename, opt); + } /** + * private helper function to ensure that the user passed in valid + * values for the Dictionary type + */ + + }, + { + key: '_validate', + value: function _validate(value) { + return true; + } + } + ]); + return TypedDict; + }(); + /** + * + * A simple Dictionary class for Strings. + * + * @class p5.StringDict + * @extends p5.TypedDict + */ + _main.default.StringDict = /*#__PURE__*/ function (_p5$TypedDict) { + _inherits(StringDict, _p5$TypedDict); + var _super = _createSuper(StringDict); + function StringDict() { + _classCallCheck(this, StringDict); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _super.call.apply(_super, [ + this + ].concat(args)); + } + _createClass(StringDict, [ + { + key: '_validate', + value: function _validate(value) { + return typeof value === 'string'; + } + } + ]); + return StringDict; + }(_main.default.TypedDict); + /** + * + * A simple Dictionary class for Numbers. + * + * @class p5.NumberDict + * @constructor + * @extends p5.TypedDict + */ + _main.default.NumberDict = /*#__PURE__*/ function (_p5$TypedDict2) { + _inherits(NumberDict, _p5$TypedDict2); + var _super2 = _createSuper(NumberDict); + function NumberDict() { + _classCallCheck(this, NumberDict); + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + return _super2.call.apply(_super2, [ + this + ].concat(args)); + } /** + * private helper function to ensure that the user passed in valid + * values for the Dictionary type + */ + + _createClass(NumberDict, [ + { + key: '_validate', + value: function _validate(value) { + return typeof value === 'number'; + } /** + * Add the given number to the value currently stored at the given key. + * The sum then replaces the value previously stored in the Dictionary. + * + * @method add + * @param {Number} Key for the value you wish to add to + * @param {Number} Number to add to the value + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict(2, 5); + * myDictionary.add(2, 2); + * print(myDictionary.get(2)); // logs 7 to console. + * } + *
        + * + */ + + }, + { + key: 'add', + value: function add(key, amount) { + if (this.data.hasOwnProperty(key)) { + this.data[key] += amount; + } else { + console.log('The key - '.concat(key, ' does not exist in this dictionary.')); + } + } /** + * Subtract the given number from the value currently stored at the given key. + * The difference then replaces the value previously stored in the Dictionary. + * + * @method sub + * @param {Number} Key for the value you wish to subtract from + * @param {Number} Number to subtract from the value + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict(2, 5); + * myDictionary.sub(2, 2); + * print(myDictionary.get(2)); // logs 3 to console. + * } + *
        + * + */ + + }, + { + key: 'sub', + value: function sub(key, amount) { + this.add(key, - amount); + } /** + * Multiply the given number with the value currently stored at the given key. + * The product then replaces the value previously stored in the Dictionary. + * + * @method mult + * @param {Number} Key for value you wish to multiply + * @param {Number} Amount to multiply the value by + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict(2, 4); + * myDictionary.mult(2, 2); + * print(myDictionary.get(2)); // logs 8 to console. + * } + *
        + * + */ + + }, + { + key: 'mult', + value: function mult(key, amount) { + if (this.data.hasOwnProperty(key)) { + this.data[key] *= amount; + } else { + console.log('The key - '.concat(key, ' does not exist in this dictionary.')); + } + } /** + * Divide the given number with the value currently stored at the given key. + * The quotient then replaces the value previously stored in the Dictionary. + * + * @method div + * @param {Number} Key for value you wish to divide + * @param {Number} Amount to divide the value by + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict(2, 8); + * myDictionary.div(2, 2); + * print(myDictionary.get(2)); // logs 4 to console. + * } + *
        + * + */ + + }, + { + key: 'div', + value: function div(key, amount) { + if (this.data.hasOwnProperty(key)) { + this.data[key] /= amount; + } else { + console.log('The key - '.concat(key, ' does not exist in this dictionary.')); + } + } /** + * private helper function for finding lowest or highest value + * the argument 'flip' is used to flip the comparison arrow + * from 'less than' to 'greater than' + */ + + }, + { + key: '_valueTest', + value: function _valueTest(flip) { + if (Object.keys(this.data).length === 0) { + throw new Error('Unable to search for a minimum or maximum value on an empty NumberDict'); + } else if (Object.keys(this.data).length === 1) { + return this.data[Object.keys(this.data) [0]]; + } else { + var result = this.data[Object.keys(this.data) [0]]; + for (var key in this.data) { + if (this.data[key] * flip < result * flip) { + result = this.data[key]; + } + } + return result; + } + } /** + * Return the lowest number currently stored in the Dictionary. + * + * @method minValue + * @return {Number} + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); + * let lowestValue = myDictionary.minValue(); // value is -10 + * print(lowestValue); + * } + *
        + */ + + }, + { + key: 'minValue', + value: function minValue() { + return this._valueTest(1); + } /** + * Return the highest number currently stored in the Dictionary. + * + * @method maxValue + * @return {Number} + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); + * let highestValue = myDictionary.maxValue(); // value is 3 + * print(highestValue); + * } + *
        + */ + + }, + { + key: 'maxValue', + value: function maxValue() { + return this._valueTest( - 1); + } /** + * private helper function for finding lowest or highest key + * the argument 'flip' is used to flip the comparison arrow + * from 'less than' to 'greater than' + */ + + }, + { + key: '_keyTest', + value: function _keyTest(flip) { + if (Object.keys(this.data).length === 0) { + throw new Error('Unable to use minValue on an empty NumberDict'); + } else if (Object.keys(this.data).length === 1) { + return Object.keys(this.data) [0]; + } else { + var result = Object.keys(this.data) [0]; + for (var i = 1; i < Object.keys(this.data).length; i++) { + if (Object.keys(this.data) [i] * flip < result * flip) { + result = Object.keys(this.data) [i]; + } + } + return result; + } + } /** + * Return the lowest key currently used in the Dictionary. + * + * @method minKey + * @return {Number} + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); + * let lowestKey = myDictionary.minKey(); // value is 1.2 + * print(lowestKey); + * } + *
        + */ + + }, + { + key: 'minKey', + value: function minKey() { + return this._keyTest(1); + } /** + * Return the highest key currently used in the Dictionary. + * + * @method maxKey + * @return {Number} + * @example + *
        + * + * function setup() { + * let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); + * let highestKey = myDictionary.maxKey(); // value is 4 + * print(highestKey); + * } + *
        + */ + + }, + { + key: 'maxKey', + value: function maxKey() { + return this._keyTest( - 1); + } + } + ]); + return NumberDict; + }(_main.default.TypedDict); + var _default = _main.default.TypedDict; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.keys': 204, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 319: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/web.url'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/web.url'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + 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; + } + 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 _createSuper(Derived) { + function 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; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_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 _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } /** + * The web is much more than just canvas and the DOM functionality makes it easy to interact + * with other HTML5 objects, including text, hyperlink, image, input, video, + * audio, and webcam. + * There is a set of creation methods, DOM manipulation methods, and + * an extended p5.Element that supports a range of HTML elements. See the + * + * beyond the canvas tutorial for a full overview of how this addon works. + * + * See tutorial: beyond the canvas + * for more info on how to use this library. + * + * @module DOM + * @submodule DOM + * @for p5 + * @requires p5 + */ + /** + * Searches the page for the first element that matches the given + * CSS selector string. + * + * The selector string can be an ID, class, tag name, or a combination. + * `select()` returns a p5.Element object if it + * finds a match and `null` if not. + * + * The second parameter, `container`, is optional. It specifies a container to + * search within. `container` can be CSS selector string, a + * p5.Element object, or an + * HTMLElement object. + * + * @method select + * @param {String} selectors CSS selector string of element to search for. + * @param {String|p5.Element|HTMLElement} [container] CSS selector string, p5.Element, or + * HTMLElement to search within. + * @return {p5.Element|null} p5.Element containing the element. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * + * // Select the canvas by its tag. + * let cnv = select('canvas'); + * cnv.style('border', '5px deeppink dashed'); + * + * describe('A gray square with a dashed pink border.'); + * } + * + *
        + * + *
        + * + * function setup() { + * let cnv = createCanvas(100, 100); + * + * // Add a class attribute to the canvas. + * cnv.class('pinkborder'); + * + * background(200); + * + * // Select the canvas by its class. + * cnv = select('.pinkborder'); + * + * // Style its border. + * cnv.style('border', '5px deeppink dashed'); + * + * describe('A gray square with a dashed pink border.'); + * } + * + *
        + * + *
        + * + * function setup() { + * let cnv = createCanvas(100, 100); + * + * // Set the canvas' ID. + * cnv.id('mycanvas'); + * + * background(200); + * + * // Select the canvas by its ID. + * cnv = select('#mycanvas'); + * + * // Style its border. + * cnv.style('border', '5px deeppink dashed'); + * + * describe('A gray square with a dashed pink border.'); + * } + * + *
        + */ + + _main.default.prototype.select = function (e, p) { + _main.default._validateParameters('select', arguments); + var container = this._getContainer(p); + var res = container.querySelector(e); + if (res) { + return this._wrapElement(res); + } else { + return null; + } + }; + /** + * Searches the page for all elements that matches the given + * CSS selector string. + * + * The selector string can be an ID, class, tag name, or a combination. + * `selectAll()` returns an array of p5.Element + * objects if it finds any matches and an empty array if none are found. + * + * The second parameter, `container`, is optional. It specifies a container to + * search within. `container` can be CSS selector string, a + * p5.Element object, or an + * HTMLElement object. + * + * @method selectAll + * @param {String} selectors CSS selector string of element to search for. + * @param {String|p5.Element|HTMLElement} [container] CSS selector string, p5.Element, or + * HTMLElement to search within. + * @return {p5.Element[]} array of p5.Elements containing any elements found. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create three buttons. + * createButton('1'); + * createButton('2'); + * createButton('3'); + * + * // Select the buttons by their tag. + * let buttons = selectAll('button'); + * + * // Position the buttons. + * for (let i = 0; i < 3; i += 1) { + * buttons[i].position(0, i * 30); + * } + * + * describe('Three buttons stacked vertically. The buttons are labeled, "1", "2", and "3".'); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create three buttons and position them. + * let b1 = createButton('1'); + * b1.position(0, 0); + * let b2 = createButton('2'); + * b2.position(0, 30); + * let b3 = createButton('3'); + * b3.position(0, 60); + * + * // Add a class attribute to each button. + * b1.class('btn'); + * b2.class('btn btn-pink'); + * b3.class('btn'); + * + * // Select the buttons by their class. + * let buttons = selectAll('.btn'); + * let pinkButtons = selectAll('.btn-pink'); + * + * // Style the selected buttons. + * buttons.forEach(setFont); + * pinkButtons.forEach(setColor); + * + * describe('Three buttons stacked vertically. The buttons are labeled, "1", "2", and "3". Buttons "1" and "3" are gray. Button "2" is pink.'); + * } + * + * // Set a button's font to Comic Sans MS. + * function setFont(btn) { + * btn.style('font-family', 'Comic Sans MS'); + * } + * + * // Set a button's background and font color. + * function setColor(btn) { + * btn.style('background', 'deeppink'); + * btn.style('color', 'white'); + * } + * + *
        + */ + _main.default.prototype.selectAll = function (e, p) { + _main.default._validateParameters('selectAll', arguments); + var arr = [ + ]; + var container = this._getContainer(p); + var res = container.querySelectorAll(e); + if (res) { + for (var j = 0; j < res.length; j++) { + var obj = this._wrapElement(res[j]); + arr.push(obj); + } + } + return arr; + }; + /** + * Helper function for select and selectAll + */ + _main.default.prototype._getContainer = function (p) { + var container = document; + if (typeof p === 'string') { + container = document.querySelector(p) || document; + } else if (p instanceof _main.default.Element) { + container = p.elt; + } else if (p instanceof HTMLElement) { + container = p; + } + return container; + }; + /** + * Helper function for getElement and getElements. + */ + _main.default.prototype._wrapElement = function (elt) { + var children = Array.prototype.slice.call(elt.children); + if (elt.tagName === 'INPUT' && elt.type === 'checkbox') { + var converted = new _main.default.Element(elt, this); + converted.checked = function () { + if (arguments.length === 0) { + return this.elt.checked; + } else if (arguments.length <= 0 ? undefined : arguments[0]) { + this.elt.checked = true; + } else { + this.elt.checked = false; + } + return this; + }; + return converted; + } else if (elt.tagName === 'VIDEO' || elt.tagName === 'AUDIO') { + return new _main.default.MediaElement(elt, this); + } else if (elt.tagName === 'SELECT') { + return this.createSelect(new _main.default.Element(elt, this)); + } else if (children.length > 0 && children.every(function (c) { + return c.tagName === 'INPUT' || c.tagName === 'LABEL'; + })) { + return this.createRadio(new _main.default.Element(elt, this)); + } else { + return new _main.default.Element(elt, this); + } + }; + /** + * Removes all elements created by p5.js, including any event handlers. + * + * There are two exceptions: + * canvas elements created by createCanvas() + * and p5.Render objects created by + * createGraphics(). + * + * @method removeElements + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a paragraph element and place + * // it in the middle of the canvas. + * let p = createP('p5*js'); + * p.position(25, 25); + * + * describe('A gray square with the text "p5*js" written in its center. The text disappears when the mouse is pressed.'); + * } + * + * // Remove all elements when the mouse is pressed. + * function mousePressed() { + * removeElements(); + * } + * + *
        + * + *
        + * + * let slider; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a paragraph element and place + * // it at the top of the canvas. + * let p = createP('p5*js'); + * p.position(25, 25); + * + * // Create a slider element and place it + * // beneath the canvas. + * slider = createSlider(0, 255, 200); + * slider.position(0, 100); + * + * describe('A gray square with the text "p5*js" written in its center and a range slider beneath it. The square changes color when the slider is moved. The text and slider disappear when the square is double-clicked.'); + * } + * + * function draw() { + * // Use the slider value to change the background color. + * let g = slider.value(); + * background(g); + * } + * + * // Remove all elements when the mouse is double-clicked. + * function doubleClicked() { + * removeElements(); + * } + * + *
        + */ + _main.default.prototype.removeElements = function (e) { + _main.default._validateParameters('removeElements', arguments); + // el.remove splices from this._elements, so don't mix iteration with it + var isNotCanvasElement = function isNotCanvasElement(el) { + return !(el.elt instanceof HTMLCanvasElement); + }; + var removeableElements = this._elements.filter(isNotCanvasElement); + removeableElements.map(function (el) { + return el.remove(); + }); + }; + /** + * Calls a function when the element changes. + * + * Calling `myElement.changed(false)` disables the function. + * + * @method changed + * @param {Function|Boolean} fxn function to call when the element changes. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * let dropdown; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a dropdown menu and add a few color options. + * dropdown = createSelect(); + * dropdown.position(0, 0); + * dropdown.option('red'); + * dropdown.option('green'); + * dropdown.option('blue'); + * + * // Call paintBackground() when the color option changes. + * dropdown.changed(paintBackground); + * + * describe('A gray square with a dropdown menu at the top. The square changes color when an option is selected.'); + * } + * + * // Paint the background with the selected color. + * function paintBackground() { + * let c = dropdown.value(); + * background(c); + * } + * + *
        + * + *
        + * + * let checkbox; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a checkbox and place it beneath the canvas. + * checkbox = createCheckbox(' circle'); + * checkbox.position(0, 100); + * + * // Call repaint() when the checkbox changes. + * checkbox.changed(repaint); + * + * describe('A gray square with a checkbox underneath it that says "circle". A white circle appears when the box is checked and disappears otherwise.'); + * } + * + * // Paint the background gray and determine whether to draw a circle. + * function repaint() { + * background(200); + * if (checkbox.checked() === true) { + * circle(50, 50, 30); + * } + * } + * + *
        + */ + _main.default.Element.prototype.changed = function (fxn) { + _main.default.Element._adjustListener('change', fxn, this); + return this; + }; + /** + * Calls a function when the element receives input. + * + * `myElement.input()` is often used to with text inputs and sliders. Calling + * `myElement.input(false)` disables the function. + * + * @method input + * @param {Function|Boolean} fxn function to call when input is detected within + * the element. + * `false` disables the function. + * @chainable + * + * @example + *
        + * + * let slider; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a slider and place it beneath the canvas. + * slider = createSlider(0, 255, 200); + * slider.position(0, 100); + * + * // Call repaint() when the slider changes. + * slider.input(repaint); + * + * describe('A gray square with a range slider underneath it. The background changes shades of gray when the slider is moved.'); + * } + * + * // Paint the background using slider's value. + * function repaint() { + * let g = slider.value(); + * background(g); + * } + * + *
        + * + *
        + * + * let input; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an input and place it beneath the canvas. + * input = createInput(''); + * input.position(0, 100); + * + * // Call repaint() when input is detected. + * input.input(repaint); + * + * describe('A gray square with a text input bar beneath it. Any text written in the input appears in the middle of the square.'); + * } + * + * // Paint the background gray and display the input's value. + * function repaint() { + * background(200); + * let msg = input.value(); + * text(msg, 5, 50); + * } + * + *
        + */ + _main.default.Element.prototype.input = function (fxn) { + _main.default.Element._adjustListener('input', fxn, this); + return this; + }; + /** + * Helpers for create methods. + */ + function addElement(elt, pInst, media) { + var node = pInst._userNode ? pInst._userNode : document.body; + node.appendChild(elt); + var c = media ? new _main.default.MediaElement(elt, pInst) : new _main.default.Element(elt, pInst); + pInst._elements.push(c); + return c; + } /** + * Creates a `<div></div>` element. + * + * `<div></div>` elements are commonly used as containers for + * other elements. + * + * The parameter `html` is optional. It accepts a string that sets the + * inner HTML of the new `<div></div>`. + * + * @method createDiv + * @param {String} [html] inner HTML for the new `<div></div>` element. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a div element and set its position. + * let div = createDiv('p5*js'); + * div.position(25, 35); + * + * describe('A gray square with the text "p5*js" written in its center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an h3 element within the div. + * let div = createDiv('

        p5*js

        '); + * div.position(20, 5); + * + * describe('A gray square with the text "p5*js" written in its center.'); + * } + *
        + *
        + */ + + _main.default.prototype.createDiv = function () { + var html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var elt = document.createElement('div'); + elt.innerHTML = html; + return addElement(elt, this); + }; + /** + * Creates a `<p></p>` element. + * + * `<p></p>` elements are commonly used for paragraph-length text. + * + * The parameter `html` is optional. It accepts a string that sets the + * inner HTML of the new `<p></p>`. + * + * @method createP + * @param {String} [html] inner HTML for the new `<p></p>` element. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a paragraph element and set its position. + * let p = createP('Tell me a story.'); + * p.position(5, 0); + * + * describe('A gray square displaying the text "Tell me a story." written in black.'); + * } + * + *
        + */ + _main.default.prototype.createP = function () { + var html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var elt = document.createElement('p'); + elt.innerHTML = html; + return addElement(elt, this); + }; + /** + * Creates a `<span></span>` element. + * + * `<span></span>` elements are commonly used as containers + * for inline elements. For example, a `<span></span>` + * can hold part of a sentence that's a + * different style. + * + * The parameter `html` is optional. It accepts a string that sets the + * inner HTML of the new `<span></span>`. + * + * @method createSpan + * @param {String} [html] inner HTML for the new `<span></span>` element. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a span element and set its position. + * let span = createSpan('p5*js'); + * span.position(25, 35); + * + * describe('A gray square with the text "p5*js" written in its center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background(200); + * + * // Create a div element as a container. + * let div = createDiv(); + * + * // Place the div at the center. + * div.position(25, 35); + * + * // Create a span element. + * let s1 = createSpan('p5'); + * + * // Create a second span element. + * let s2 = createSpan('*'); + * + * // Set the second span's font color. + * s2.style('color', 'deeppink'); + * + * // Create a third span element. + * let s3 = createSpan('js'); + * + * // Add all the spans to the container div. + * s1.parent(div); + * s2.parent(div); + * s3.parent(div); + * + * describe('A gray square with the text "p5*js" written in black at its center. The asterisk is pink.'); + * } + * + *
        + */ + _main.default.prototype.createSpan = function () { + var html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var elt = document.createElement('span'); + elt.innerHTML = html; + return addElement(elt, this); + }; + /** + * Creates an `<img>` element that can appear outside of the canvas. + * + * The first parameter, `src`, is a string with the path to the image file. + * `src` should be a relative path, as in `'assets/image.png'`, or a URL, as + * in `'https://example.com/image.png'`. + * + * The second parameter, `alt`, is a string with the + * alternate text + * for the image. An empty string `''` can be used for images that aren't displayed. + * + * The third parameter, `crossOrigin`, is optional. It's a string that sets the + * crossOrigin property + * of the image. Use `'anonymous'` or `'use-credentials'` to fetch the image + * with cross-origin access. + * + * The fourth parameter, `callback`, is also optional. It sets a function to + * call after the image loads. The new image is passed to the callback + * function as a p5.Element object. + * + * @method createImg + * @param {String} src relative path or URL for the image. + * @param {String} alt alternate text for the image. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * let img = createImg( + * 'https://p5js.org/assets/img/asterisk-01.png', + * 'The p5.js magenta asterisk.' + * ); + * img.position(0, -10); + * + * describe('A gray square with a magenta asterisk in its center.'); + * } + * + *
        + */ + /** + * @method createImg + * @param {String} src + * @param {String} alt + * @param {String} [crossOrigin] crossOrigin property to use when fetching the image. + * @param {Function} [successCallback] function to call once the image loads. The new image will be passed + * to the function as a p5.Element object. + * @return {p5.Element} new p5.Element object. + */ + _main.default.prototype.createImg = function () { + _main.default._validateParameters('createImg', arguments); + var elt = document.createElement('img'); + var args = arguments; + var self; + if (args.length > 1 && typeof args[1] === 'string') { + elt.alt = args[1]; + } + if (args.length > 2 && typeof args[2] === 'string') { + elt.crossOrigin = args[2]; + } + elt.src = args[0]; + self = addElement(elt, this); + elt.addEventListener('load', function () { + self.width = elt.offsetWidth || elt.width; + self.height = elt.offsetHeight || elt.height; + var last = args[args.length - 1]; + if (typeof last === 'function') last(self); + }); + return self; + }; + /** + * Creates an `<a></a>` element that links to another web page. + * + * The first parmeter, `href`, is a string that sets the URL of the linked + * page. + * + * The second parameter, `html`, is a string that sets the inner HTML of the + * link. It's common to use text, images, or buttons as links. + * + * The third parameter, `target`, is optional. It's a string that tells the + * web browser where to open the link. By default, links open in the current + * browser tab. Passing `'_blank'` will cause the link to open in a new + * browser tab. MDN describes a few + * other options. + * + * @method createA + * @param {String} href URL of linked page. + * @param {String} html inner HTML of link element to display. + * @param {String} [target] target where the new link should open, + * either `'_blank'`, `'_self'`, `'_parent'`, or `'_top'`. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an anchor element that links to p5js.org. + * let a = createA('http://p5js.org/', 'p5*js'); + * a.position(25, 35); + * + * describe('The text "p5*js" written at the center of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background(200); + * + * // Create an anchor tag that links to p5js.org. + * // Open the link in a new tab. + * let a = createA('http://p5js.org/', 'p5*js', '_blank'); + * a.position(25, 35); + * + * describe('The text "p5*js" written at the center of a gray square.'); + * } + * + *
        + */ + _main.default.prototype.createA = function (href, html, target) { + _main.default._validateParameters('createA', arguments); + var elt = document.createElement('a'); + elt.href = href; + elt.innerHTML = html; + if (target) elt.target = target; + return addElement(elt, this); + }; + /** INPUT **/ + /** + * Creates a slider `<input></input>` element. + * + * Range sliders are useful for quickly selecting numbers from a given range. + * + * The first two parameters, `min` and `max`, are numbers that set the + * slider's minimum and maximum. + * + * The third parameter, `value`, is optional. It's a number that sets the + * slider's default value. + * + * The fourth parameter, `step`, is also optional. It's a number that sets the + * spacing between each value in the slider's range. Setting `step` to 0 + * allows the slider to move smoothly from `min` to `max`. + * + * @method createSlider + * @param {Number} min minimum value of the slider. + * @param {Number} max maximum value of the slider. + * @param {Number} [value] default value of the slider. + * @param {Number} [step] size for each step in the slider's range. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * let slider; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a slider and place it at the top of the canvas. + * slider = createSlider(0, 255); + * slider.position(10, 10); + * slider.size(80); + * + * describe('A dark gray square with a range slider at the top. The square changes color when the slider is moved.'); + * } + * + * function draw() { + * // Use the slider as a grayscale value. + * let g = slider.value(); + * background(g); + * } + * + *
        + * + *
        + * + * let slider; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a slider and place it at the top of the canvas. + * // Set its default value to 0. + * slider = createSlider(0, 255, 0); + * slider.position(10, 10); + * slider.size(80); + * + * describe('A black square with a range slider at the top. The square changes color when the slider is moved.'); + * } + * + * function draw() { + * // Use the slider as a grayscale value. + * let g = slider.value(); + * background(g); + * } + * + *
        + * + *
        + * + * let slider; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a slider and place it at the top of the canvas. + * // Set its default value to 0. + * // Set its step size to 50. + * slider = createSlider(0, 255, 0, 50); + * slider.position(10, 10); + * slider.size(80); + * + * describe('A black square with a range slider at the top. The square changes color when the slider is moved.'); + * } + * + * function draw() { + * // Use the slider as a grayscale value. + * let g = slider.value(); + * background(g); + * } + * + *
        + * + *
        + * + * let slider; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a slider and place it at the top of the canvas. + * // Set its default value to 0. + * // Set its step size to 0 so that it moves smoothly. + * slider = createSlider(0, 255, 0, 0); + * slider.position(10, 10); + * slider.size(80); + * + * describe('A black square with a range slider at the top. The square changes color when the slider is moved.'); + * } + * + * function draw() { + * // Use the slider as a grayscale value. + * let g = slider.value(); + * background(g); + * } + * + *
        + */ + _main.default.prototype.createSlider = function (min, max, value, step) { + _main.default._validateParameters('createSlider', arguments); + var elt = document.createElement('input'); + elt.type = 'range'; + elt.min = min; + elt.max = max; + if (step === 0) { + elt.step = 1e-18; // smallest valid step + } else if (step) { + elt.step = step; + } + if (typeof value === 'number') elt.value = value; + return addElement(elt, this); + }; + /** + * Creates a `<button></button>` element. + * + * The first parameter, `label`, is a string that sets the label displayed on + * the button. + * + * The second parameter, `value`, is optional. It's a string that sets the + * button's value. See + * MDN + * for more details. + * + * @method createButton + * @param {String} label label displayed on the button. + * @param {String} [value] value of the button. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a button and place it beneath the canvas. + * let button = createButton('click me'); + * button.position(0, 100); + * + * // Call repaint() when the button is pressed. + * button.mousePressed(repaint); + * + * describe('A gray square with a button that says "click me" beneath it. The square changes color when the button is clicked.'); + * } + * + * // Change the background color. + * function repaint() { + * let g = random(255); + * background(g); + * } + * + *
        + * + *
        + * + * let button; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a button and set its value to 0. + * // Place the button beneath the canvas. + * button = createButton('click me', 'red'); + * button.position(0, 100); + * + * // Call randomColor() when the button is pressed. + * button.mousePressed(randomColor); + * + * describe('A red square with a button that says "click me" beneath it. The square changes color when the button is clicked.'); + * } + * + * function draw() { + * // Use the button's value to set the background color. + * let c = button.value(); + * background(c); + * } + * + * // Set the button's value to a random color. + * function randomColor() { + * let c = random(['red', 'green', 'blue', 'yellow']); + * button.value(c); + * } + * + *
        + */ + _main.default.prototype.createButton = function (label, value) { + _main.default._validateParameters('createButton', arguments); + var elt = document.createElement('button'); + elt.innerHTML = label; + if (value) elt.value = value; + return addElement(elt, this); + }; + /** + * Creates a checkbox `<input></input>` element. + * + * Checkboxes extend the p5.Element class with a + * `checked()` method. Calling `myBox.checked()` returns `true` if it the box + * is checked and `false` if not. + * + * The first parameter, `label`, is optional. It's a string that sets the label + * to display next to the checkbox. + * + * The second parameter, `value`, is also optional. It's a boolean that sets the + * checkbox's value. + * + * @method createCheckbox + * @param {String} [label] label displayed after the checkbox. + * @param {boolean} [value] value of the checkbox. Checked is `true` and unchecked is `false`. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * let checkbox; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a checkbox and place it beneath the canvas. + * checkbox = createCheckbox(); + * checkbox.position(0, 100); + * + * describe('A black square with a checkbox beneath it. The square turns white when the box is checked.'); + * } + * + * function draw() { + * // Use the checkbox to set the background color. + * if (checkbox.checked()) { + * background(255); + * } else { + * background(0); + * } + * } + * + *
        + * + *
        + * + * let checkbox; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a checkbox and place it beneath the canvas. + * // Label the checkbox "white". + * checkbox = createCheckbox(' white'); + * checkbox.position(0, 100); + * + * describe('A black square with a checkbox labeled "white" beneath it. The square turns white when the box is checked.'); + * } + * + * function draw() { + * // Use the checkbox to set the background color. + * if (checkbox.checked()) { + * background(255); + * } else { + * background(0); + * } + * } + * + *
        + * + *
        + * + * let checkbox; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a checkbox and place it beneath the canvas. + * // Label the checkbox "white" and set its value to true. + * checkbox = createCheckbox(' white', true); + * checkbox.position(0, 100); + * + * describe('A white square with a checkbox labeled "white" beneath it. The square turns black when the box is unchecked.'); + * } + * + * function draw() { + * // Use the checkbox to set the background color. + * if (checkbox.checked()) { + * background(255); + * } else { + * background(0); + * } + * } + * + *
        + */ + _main.default.prototype.createCheckbox = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('createCheckbox', args); + // Create a container element + var elt = document.createElement('div'); + // Create checkbox type input element + var checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + // Create label element and wrap it around checkbox + var label = document.createElement('label'); + label.appendChild(checkbox); + // Append label element inside the container + elt.appendChild(label); + //checkbox must be wrapped in p5.Element before label so that label appears after + var self = addElement(elt, this); + self.checked = function () { + var cb = self.elt.firstElementChild.getElementsByTagName('input') [0]; + if (cb) { + if (arguments.length === 0) { + return cb.checked; + } else if (arguments.length <= 0 ? undefined : arguments[0]) { + cb.checked = true; + } else { + cb.checked = false; + } + } + return self; + }; + this.value = function (val) { + self.value = val; + return this; + }; + // Set the span element innerHTML as the label value if passed + if (args[0]) { + self.value(args[0]); + var span = document.createElement('span'); + span.innerHTML = args[0]; + label.appendChild(span); + } // Set the checked value of checkbox if passed + + if (args[1]) { + checkbox.checked = true; + } + return self; + }; + /** + * Creates a dropdown menu `<select></select>` element. + * + * The parameter is optional. If `true` is passed, as in + * `let mySelect = createSelect(true)`, then the dropdown will support + * multiple selections. If an existing `<select></select>` element + * is passed, as in `let mySelect = createSelect(otherSelect)`, the existing + * element will be wrapped in a new p5.Element + * object. + * + * Dropdowns extend the p5.Element class with a few + * helpful methods for managing options: + * - `mySelect.option(name, [value])` adds an option to the menu. The first paremeter, `name`, is a string that sets the option's name and value. The second parameter, `value`, is optional. If provided, it sets the value that corresponds to the key `name`. If an option with `name` already exists, its value is changed to `value`. + * - `mySelect.value()` returns the currently-selected option's value. + * - `mySelect.selected()` returns the currently-selected option. + * - `mySelect.selected(option)` selects the given option by default. + * - `mySelect.disable()` marks the whole dropdown element as disabled. + * - `mySelect.disable(option)` marks a given option as disabled. + * - `mySelect.enable()` marks the whole dropdown element as enabled. + * - `mySelect.enable(option)` marks a given option as enabled. + * + * @method createSelect + * @param {boolean} [multiple] support multiple selections. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * let mySelect; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a dropdown and place it beneath the canvas. + * mySelect = createSelect(); + * mySelect.position(0, 100); + * + * // Add color options. + * mySelect.option('red'); + * mySelect.option('green'); + * mySelect.option('blue'); + * mySelect.option('yellow'); + * + * // Set the selected option to "red". + * mySelect.selected('red'); + * + * describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.'); + * } + * + * function draw() { + * // Use the selected value to paint the background. + * let c = mySelect.selected(); + * background(c); + * } + * + *
        + * + *
        + * + * let mySelect; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a dropdown and place it beneath the canvas. + * mySelect = createSelect(); + * mySelect.position(0, 100); + * + * // Add color options. + * mySelect.option('red'); + * mySelect.option('green'); + * mySelect.option('blue'); + * mySelect.option('yellow'); + * + * // Set the selected option to "red". + * mySelect.selected('red'); + * + * // Disable the "yellow" option. + * mySelect.disable('yellow'); + * + * describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.'); + * } + * + * function draw() { + * // Use the selected value to paint the background. + * let c = mySelect.selected(); + * background(c); + * } + * + *
        + * + *
        + * + * let mySelect; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a dropdown and place it beneath the canvas. + * mySelect = createSelect(); + * mySelect.position(0, 100); + * + * // Add color options with names and values. + * mySelect.option('one', 'red'); + * mySelect.option('two', 'green'); + * mySelect.option('three', 'blue'); + * mySelect.option('four', 'yellow'); + * + * // Set the selected option to "one". + * mySelect.selected('one'); + * + * describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.'); + * } + * + * function draw() { + * // Use the selected value to paint the background. + * let c = mySelect.selected(); + * background(c); + * } + * + *
        + * + *
        + * + * // Hold CTRL to select multiple options on Windows and Linux. + * // Hold CMD to select multiple options on macOS. + * let mySelect; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a dropdown and allow multiple selections. + * // Place it beneath the canvas. + * mySelect = createSelect(true); + * mySelect.position(0, 100); + * + * // Add color options. + * mySelect.option('red'); + * mySelect.option('green'); + * mySelect.option('blue'); + * mySelect.option('yellow'); + * + * describe('A gray square with a dropdown menu beneath it. Colorful circles appear when their color is selected.'); + * } + * + * function draw() { + * background(200); + * + * // Use the selected value(s) to draw circles. + * let colors = mySelect.selected(); + * for (let i = 0; i < colors.length; i += 1) { + * // Calculate the x-coordinate. + * let x = 10 + i * 20; + * + * // Access the color. + * let c = colors[i]; + * + * // Draw the circle. + * fill(c); + * circle(x, 50, 20); + * } + * } + * + *
        + */ + /** + * @method createSelect + * @param {Object} existing select element to wrap, either as a p5.Element or + * a HTMLSelectElement. + * @return {p5.Element} + */ + _main.default.prototype.createSelect = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('createSelect', args); + var self; + var arg = args[0]; + if (arg instanceof _main.default.Element && arg.elt instanceof HTMLSelectElement) { + // If given argument is p5.Element of select type + self = arg; + this.elt = arg.elt; + } else if (arg instanceof HTMLSelectElement) { + self = addElement(arg, this); + this.elt = arg; + } else { + var elt = document.createElement('select'); + if (arg && typeof arg === 'boolean') { + elt.setAttribute('multiple', 'true'); + } + self = addElement(elt, this); + this.elt = elt; + } + self.option = function (name, value) { + var index; + // if no name is passed, return + if (name === undefined) { + return; + } //see if there is already an option with this name + + for (var i = 0; i < this.elt.length; i += 1) { + if (this.elt[i].textContent === name) { + index = i; + break; + } + } //if there is an option with this name we will modify it + + if (index !== undefined) { + //if the user passed in false then delete that option + if (value === false) { + this.elt.remove(index); + } else { + // Update the option at index with the value + this.elt[index].value = value; + } + } else { + //if it doesn't exist create it + var opt = document.createElement('option'); + opt.textContent = name; + opt.value = value === undefined ? name : value; + this.elt.appendChild(opt); + this._pInst._elements.push(opt); + } + }; + self.selected = function (value) { + // Update selected status of option + if (value !== undefined) { + for (var i = 0; i < this.elt.length; i += 1) { + if (this.elt[i].value.toString() === value.toString()) { + this.elt.selectedIndex = i; + } + } + return this; + } else { + if (this.elt.getAttribute('multiple')) { + var arr = [ + ]; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.elt.selectedOptions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var selectedOption = _step.value; + arr.push(selectedOption.value); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + return arr; + } else { + return this.elt.value; + } + } + }; + self.disable = function (value) { + if (typeof value === 'string') { + for (var i = 0; i < this.elt.length; i++) { + if (this.elt[i].value.toString() === value) { + this.elt[i].disabled = true; + this.elt[i].selected = false; + } + } + } else { + this.elt.disabled = true; + } + return this; + }; + self.enable = function (value) { + if (typeof value === 'string') { + for (var i = 0; i < this.elt.length; i++) { + if (this.elt[i].value.toString() === value) { + this.elt[i].disabled = false; + this.elt[i].selected = false; + } + } + } else { + this.elt.disabled = false; + for (var _i = 0; _i < this.elt.length; _i++) { + this.elt[_i].disabled = false; + this.elt[_i].selected = false; + } + } + return this; + }; + return self; + }; + /** + * Creates a radio button element. + * + * The parameter is optional. If a string is passed, as in + * `let myRadio = createSelect('food')`, then each radio option will + * have `"food"` as its `name` parameter: `<input name="food"></input>`. + * If an existing `<div></div>` or `<span></span>` + * element is passed, as in `let myRadio = createSelect(container)`, it will + * become the radio button's parent element. + * + * Radio buttons extend the p5.Element class with a few + * helpful methods for managing options: + * - `myRadio.option(value, [label])` adds an option to the menu. The first paremeter, `value`, is a string that sets the option's value and label. The second parameter, `label`, is optional. If provided, it sets the label displayed for the `value`. If an option with `value` already exists, its label is changed and its value is returned. + * - `myRadio.value()` returns the currently-selected option's value. + * - `myRadio.selected()` returns the currently-selected option. + * - `myRadio.selected(value)` selects the given option and returns it as an `HTMLInputElement`. + * - `myRadio.disable(shouldDisable)` enables the entire radio button if `true` is passed and disables it if `false` is passed. + * + * @method createRadio + * @param {Object} [containerElement] container HTML Element, either a `<div></div>` + * or `<span></span>`. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * let myRadio; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a radio button element and place it + * // in the top-left corner. + * myRadio = createRadio(); + * myRadio.position(0, 0); + * myRadio.size(60); + * + * // Add a few color options. + * myRadio.option('red'); + * myRadio.option('yellow'); + * myRadio.option('blue'); + * + * // Choose a default option. + * myRadio.selected('yellow'); + * + * describe('A yellow square with three color options listed, "red", "yellow", and "blue". The square changes color when the user selects a new option.'); + * } + * + * function draw() { + * // Set the background color using the radio button. + * let g = myRadio.value(); + * background(g); + * } + * + *
        + * + *
        + * + * let myRadio; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a radio button element and place it + * // in the top-left corner. + * myRadio = createRadio(); + * myRadio.position(0, 0); + * myRadio.size(50); + * + * // Add a few color options. + * // Color values are labeled with + * // emotions they evoke. + * myRadio.option('red', 'love'); + * myRadio.option('yellow', 'joy'); + * myRadio.option('blue', 'trust'); + * + * // Choose a default option. + * myRadio.selected('yellow'); + * + * describe('A yellow square with three options listed, "love", "joy", and "trust". The square changes color when the user selects a new option.'); + * } + * + * function draw() { + * // Set the background color using the radio button. + * let c = myRadio.value(); + * background(c); + * } + * + *
        + * + *
        + * + * let myRadio; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a radio button element and place it + * // in the top-left corner. + * myRadio = createRadio(); + * myRadio.position(0, 0); + * myRadio.size(50); + * + * // Add a few color options. + * myRadio.option('red'); + * myRadio.option('yellow'); + * myRadio.option('blue'); + * + * // Choose a default option. + * myRadio.selected('yellow'); + * + * // Create a button and place it beneath the canvas. + * let btn = createButton('disable'); + * btn.position(0, 100); + * + * // Call disableRadio() when btn is pressed. + * btn.mousePressed(disableRadio); + * + * describe('A yellow square with three options listed, "red", "yellow", and "blue". The square changes color when the user selects a new option. A "disable" button beneath the canvas disables the color options when pressed.'); + * } + * + * function draw() { + * // Set the background color using the radio button. + * let c = myRadio.value(); + * background(c); + * } + * + * // Disable myRadio. + * function disableRadio() { + * myRadio.disable(true); + * } + * + *
        + */ + /** + * @method createRadio + * @param {String} [name] name parameter assigned to each option's `<input></input>` element. + * @return {p5.Element} new p5.Element object. + */ + /** + * @method createRadio + * @return {p5.Element} new p5.Element object. + */ + _main.default.prototype.createRadio = function () { + // Creates a div, adds each option as an individual input inside it. + // If already given with a containerEl, will search for all input[radio] + // it, create a p5.Element out of it, add options to it and return the p5.Element. + var self; + var radioElement; + var name; + var arg0 = arguments.length <= 0 ? undefined : arguments[0]; + if (arg0 instanceof _main.default.Element && (arg0.elt instanceof HTMLDivElement || arg0.elt instanceof HTMLSpanElement)) { + // If given argument is p5.Element of div/span type + self = arg0; + this.elt = arg0.elt; + } else if ( // If existing radio Element is provided as argument 0 + arg0 instanceof HTMLDivElement || arg0 instanceof HTMLSpanElement) { + self = addElement(arg0, this); + this.elt = arg0; + radioElement = arg0; + if (typeof (arguments.length <= 1 ? undefined : arguments[1]) === 'string') name = arguments.length <= 1 ? undefined : arguments[1]; + } else { + if (typeof arg0 === 'string') name = arg0; + radioElement = document.createElement('div'); + self = addElement(radioElement, this); + this.elt = radioElement; + } + self._name = name || 'radioOption'; + // setup member functions + var isRadioInput = function isRadioInput(el) { + return el instanceof HTMLInputElement && el.type === 'radio'; + }; + var isLabelElement = function isLabelElement(el) { + return el instanceof HTMLLabelElement; + }; + var isSpanElement = function isSpanElement(el) { + return el instanceof HTMLSpanElement; + }; + self._getOptionsArray = function () { + return Array.from(this.elt.children).filter(function (el) { + return isRadioInput(el) || isLabelElement(el) && isRadioInput(el.firstElementChild); + }).map(function (el) { + return isRadioInput(el) ? el : el.firstElementChild; + }); + }; + self.option = function (value, label) { + // return an option with this value, create if not exists. + var optionEl; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = self._getOptionsArray() [Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var option = _step2.value; + if (option.value === value) { + optionEl = option; + break; + } + } // Create a new option, add it to radioElement and return it. + + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + if (optionEl === undefined) { + optionEl = document.createElement('input'); + optionEl.setAttribute('type', 'radio'); + optionEl.setAttribute('value', value); + } + optionEl.setAttribute('name', self._name); + // Check if label element exists, else create it + var labelElement; + if (!isLabelElement(optionEl.parentElement)) { + labelElement = document.createElement('label'); + labelElement.insertAdjacentElement('afterbegin', optionEl); + } else { + labelElement = optionEl.parentElement; + } // Check if span element exists, else create it + + var spanElement; + if (!isSpanElement(labelElement.lastElementChild)) { + spanElement = document.createElement('span'); + optionEl.insertAdjacentElement('afterend', spanElement); + } else { + spanElement = labelElement.lastElementChild; + } // Set the innerHTML of span element as the label text + + spanElement.innerHTML = label === undefined ? value : label; + // Append the label element, which includes option element and + // span element to the radio container element + this.elt.appendChild(labelElement); + return optionEl; + }; + self.remove = function (value) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = self._getOptionsArray() [Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var optionEl = _step3.value; + if (optionEl.value === value) { + if (isLabelElement(optionEl.parentElement)) { + // Remove parent label which also removes children elements + optionEl.parentElement.remove(); + } else { + // Remove the option input if parent label does not exist + optionEl.remove(); + } + return; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + }; + self.value = function () { + var result = ''; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + try { + for (var _iterator4 = self._getOptionsArray() [Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var option = _step4.value; + if (option.checked) { + result = option.value; + break; + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + return result; + }; + self.selected = function (value) { + var result = null; + if (value === undefined) { + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + try { + for (var _iterator5 = self._getOptionsArray() [Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var option = _step5.value; + if (option.checked) { + result = option; + break; + } + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + } else { + // forEach loop to uncheck all radio buttons before + // setting any one as checked. + self._getOptionsArray().forEach(function (option) { + option.checked = false; + option.removeAttribute('checked'); + }); + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + try { + for (var _iterator6 = self._getOptionsArray() [Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var _option = _step6.value; + if (_option.value === value) { + _option.setAttribute('checked', true); + _option.checked = true; + result = _option; + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + return result; + }; + self.disable = function () { + var shouldDisable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + try { + for (var _iterator7 = self._getOptionsArray() [Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var radioInput = _step7.value; + radioInput.setAttribute('disabled', shouldDisable); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + }; + return self; + }; + /** + * Creates a color picker element. + * + * The parameter, `value`, is optional. If a color string or + * p5.Color object is passed, it will set the default + * color. + * + * Color pickers extend the p5.Element class with a + * couple of helpful methods for managing colors: + * - `myPicker.value()` returns the current color as a hex string in the format `'#rrggbb'`. + * - `myPicker.color()` returns the current color as a p5.Color object. + * + * @method createColorPicker + * @param {String|p5.Color} [value] default color as a CSS color string. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * let myPicker; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a color picker and set its position. + * myPicker = createColorPicker('deeppink'); + * myPicker.position(0, 100); + * + * describe('A pink square with a color picker beneath it. The square changes color when the user picks a new color.'); + * } + * + * function draw() { + * // Use the color picker to paint the background. + * let c = myPicker.color(); + * background(c); + * } + * + *
        + * + *
        + * + * let myPicker; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a color picker and set its position. + * myPicker = createColorPicker('deeppink'); + * myPicker.position(0, 100); + * + * describe('A number with the format "#rrggbb" is displayed on a pink canvas. The background color and number change when the user picks a new color.'); + * } + * + * function draw() { + * // Use the color picker to paint the background. + * let c = myPicker.value(); + * background(c); + * + * // Display the current color as a hex string. + * text(c, 25, 55); + * } + * + *
        + */ + _main.default.prototype.createColorPicker = function (value) { + _main.default._validateParameters('createColorPicker', arguments); + var elt = document.createElement('input'); + var self; + elt.type = 'color'; + if (value) { + if (value instanceof _main.default.Color) { + elt.value = value.toString('#rrggbb'); + } else { + _main.default.prototype._colorMode = 'rgb'; + _main.default.prototype._colorMaxes = { + rgb: [ + 255, + 255, + 255, + 255 + ], + hsb: [ + 360, + 100, + 100, + 1 + ], + hsl: [ + 360, + 100, + 100, + 1 + ] + }; + elt.value = _main.default.prototype.color(value).toString('#rrggbb'); + } + } else { + elt.value = '#000000'; + } + self = addElement(elt, this); + // Method to return a p5.Color object for the given color. + self.color = function () { + if (value) { + if (value.mode) { + _main.default.prototype._colorMode = value.mode; + } + if (value.maxes) { + _main.default.prototype._colorMaxes = value.maxes; + } + } + return _main.default.prototype.color(this.elt.value); + }; + return self; + }; + /** + * Creates a text `<input></input>` element. + * + * Call `myInput.size()` to set the length of the text box. + * + * The first parameter, `value`, is optional. It's a string that sets the + * input's default value. The input is blank by default. + * + * The second parameter, `type`, is also optional. It's a string that + * specifies the type of text being input. See MDN for a full + * list of options. + * The default is `'text'`. + * + * @method createInput + * @param {String} [value] default value of the input box. Defaults to an empty string `''`. + * @param {String} [type] type of input. Defaults to `'text'`. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * let myInput; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create an input element and place it + * // beneath the canvas. + * myInput = createInput(); + * myInput.position(0, 100); + * + * describe('A gray square with a text box beneath it. The text in the square changes when the user types something new in the input bar.'); + * } + * + * function draw() { + * background(200); + * + * // Use the input to display a message. + * let msg = myInput.value(); + * text(msg, 25, 55); + * } + * + *
        + * + *
        + * + * let myInput; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create an input element and place it + * // beneath the canvas. Set its default + * // text to "hello!". + * myInput = createInput('hello!'); + * myInput.position(0, 100); + * + * describe('The text "hello!" written at the center of a gray square. A text box beneath the square also says "hello!". The text in the square changes when the user types something new in the input bar.'); + * } + * + * function draw() { + * background(200); + * + * // Use the input to display a message. + * let msg = myInput.value(); + * text(msg, 25, 55); + * } + * + *
        + */ + /** + * @method createInput + * @param {String} [value] + * @return {p5.Element} + */ + _main.default.prototype.createInput = function () { + var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'text'; + _main.default._validateParameters('createInput', arguments); + var elt = document.createElement('input'); + elt.setAttribute('value', value); + elt.setAttribute('type', type); + return addElement(elt, this); + }; + /** + * Creates an `<input></input>` element of type `'file'`. + * + * `createFileInput()` allows users to select local files for use in a sketch. + * It returns a p5.File object. + * + * The first parameter, `callback`, is a function that's called when the file + * loads. The callback function should have one parameter, `file`, that's a + * p5.File object. + * + * The second parameter, `multiple`, is optional. It's a boolean value that + * allows loading multiple files if set to `true`. If `true`, `callback` + * will be called once per file. + * + * @method createFileInput + * @param {Function} callback function to call once the file loads. + * @param {Boolean} [multiple] allow multiple files to be selected. + * @return {p5.File} new p5.File object. + * + * @example + *
        + * + * // Use the file input to select an image to + * // load and display. + * let input; + * let img; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a file input and place it beneath + * // the canvas. + * input = createFileInput(handleImage); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.'); + * } + * + * function draw() { + * background(200); + * + * // Draw the image if loaded. + * if (img) { + * image(img, 0, 0, width, height); + * } + * } + * + * // Create an image if the file is an image. + * function handleImage(file) { + * if (file.type === 'image') { + * img = createImg(file.data, ''); + * img.hide(); + * } else { + * img = null; + * } + * } + * + *
        + * + *
        + * + * // Use the file input to select multiple images + * // to load and display. + * let input; + * let images = []; + * + * function setup() { + * // Create a file input and place it beneath + * // the canvas. Allow it to load multiple files. + * input = createFileInput(handleImage, true); + * input.position(0, 100); + * } + * + * function draw() { + * background(200); + * + * // Draw the images if loaded. Each image + * // is drawn 20 pixels lower than the + * // previous image. + * for (let i = 0; i < images.length; i += 1) { + * // Calculate the y-coordinate. + * let y = i * 20; + * + * // Draw the image. + * image(img, 0, y, 100, 100); + * } + * + * describe('A gray square with a file input beneath it. If the user selects multiple image files to load, they are displayed on the square.'); + * } + * + * // Create an image if the file is an image, + * // then add it to the images array. + * function handleImage(file) { + * if (file.type === 'image') { + * let img = createImg(file.data, ''); + * img.hide(); + * images.push(img); + * } + * } + * + *
        + */ + _main.default.prototype.createFileInput = function (callback) { + var multiple = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + _main.default._validateParameters('createFileInput', arguments); + var handleFileSelect = function handleFileSelect(event) { + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + try { + for (var _iterator8 = event.target.files[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var file = _step8.value; + _main.default.File._load(file, callback); + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + }; + // If File API's are not supported, throw Error + if (!(window.File && window.FileReader && window.FileList && window.Blob)) { + console.log('The File APIs are not fully supported in this browser. Cannot create element.'); + return; + } + var fileInput = document.createElement('input'); + fileInput.setAttribute('type', 'file'); + if (multiple) fileInput.setAttribute('multiple', true); + fileInput.addEventListener('change', handleFileSelect, false); + return addElement(fileInput, this); + }; + /** VIDEO STUFF **/ + // Helps perform similar tasks for media element methods. + function createMedia(pInst, type, src, callback) { + var elt = document.createElement(type); + // Create source elements from given sources + src = src || ''; + if (typeof src === 'string') { + src = [ + src + ]; + } + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + try { + for (var _iterator9 = src[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var mediaSource = _step9.value; + var sourceEl = document.createElement('source'); + sourceEl.setAttribute('src', mediaSource); + elt.appendChild(sourceEl); + } // If callback is provided, attach to element + + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + if (typeof callback === 'function') { + var callbackHandler = function callbackHandler() { + callback(); + elt.removeEventListener('canplaythrough', callbackHandler); + }; + elt.addEventListener('canplaythrough', callbackHandler); + } + var mediaEl = addElement(elt, pInst, true); + mediaEl.loadedmetadata = false; + // set width and height onload metadata + elt.addEventListener('loadedmetadata', function () { + mediaEl.width = elt.videoWidth; + mediaEl.height = elt.videoHeight; + // set elt width and height if not set + if (mediaEl.elt.width === 0) mediaEl.elt.width = elt.videoWidth; + if (mediaEl.elt.height === 0) mediaEl.elt.height = elt.videoHeight; + if (mediaEl.presetPlaybackRate) { + mediaEl.elt.playbackRate = mediaEl.presetPlaybackRate; + delete mediaEl.presetPlaybackRate; + } + mediaEl.loadedmetadata = true; + }); + return mediaEl; + } /** + * Creates a `<video>` element for simple audio/video playback. + * + * `createVideo()` returns a new + * p5.MediaElement object. Videos are shown by + * default. They can be hidden by calling `video.hide()` and drawn to the + * canvas using image(). + * + * The first parameter, `src`, is the path the video. If a single string is + * passed, as in `'assets/topsecret.mp4'`, a single video is loaded. An array + * of strings can be used to load the same video in different formats. For + * example, `['assets/topsecret.mp4', 'assets/topsecret.ogv', 'assets/topsecret.webm']`. + * This is useful for ensuring that the video can play across different browsers with + * different capabilities. See + * MDN + * for more information about supported formats. + * + * The second parameter, `callback`, is optional. It's a function to call once + * the video is ready to play. + * + * @method createVideo + * @param {String|String[]} src path to a video file, or an array of paths for + * supporting different browsers. + * @param {Function} [callback] function to call once the video is ready to play. + * @return {p5.MediaElement} new p5.MediaElement object. + * + * @example + *
        + * + * function setup() { + * noCanvas(); + * + * // Load a video and add it to the page. + * // Note: this may not work in some browsers. + * let video = createVideo('assets/small.mp4'); + * + * // Show the default video controls. + * video.showControls(); + * + * describe('A video of a toy robot with playback controls beneath it.'); + * } + * + *
        + * + *
        + * + * function setup() { + * noCanvas(); + * + * // Load a video and add it to the page. + * // Provide an array options for different file formats. + * let video = createVideo( + * ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'] + * ); + * + * // Show the default video controls. + * video.showControls(); + * + * describe('A video of a toy robot with playback controls beneath it.'); + * } + * + *
        + * + *
        + * + * let video; + * + * function setup() { + * noCanvas(); + * + * // Load a video and add it to the page. + * // Provide an array options for different file formats. + * // Call mute() once the video loads. + * video = createVideo( + * ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'], + * muteVideo + * ); + * + * // Show the default video controls. + * video.showControls(); + * + * describe('A video of a toy robot with playback controls beneath it.'); + * } + * + * // Mute the video once it loads. + * function muteVideo() { + * video.volume(0); + * } + * + *
        + */ + + _main.default.prototype.createVideo = function (src, callback) { + _main.default._validateParameters('createVideo', arguments); + return createMedia(this, 'video', src, callback); + }; + /** AUDIO STUFF **/ + /** + * Creates a hidden `<audio>` element for simple audio playback. + * + * `createAudio()` returns a new + * p5.MediaElement object. + * + * The first parameter, `src`, is the path the video. If a single string is + * passed, as in `'assets/video.mp4'`, a single video is loaded. An array + * of strings can be used to load the same video in different formats. For + * example, `['assets/video.mp4', 'assets/video.ogv', 'assets/video.webm']`. + * This is useful for ensuring that the video can play across different + * browsers with different capabilities. See + * MDN + * for more information about supported formats. + * + * The second parameter, `callback`, is optional. It's a function to call once + * the audio is ready to play. + * + * @method createAudio + * @param {String|String[]} [src] path to an audio file, or an array of paths + * for supporting different browsers. + * @param {Function} [callback] function to call once the audio is ready to play. + * @return {p5.MediaElement} new p5.MediaElement object. + * + * @example + *
        + * + * function setup() { + * noCanvas(); + * + * // Load the audio. + * let beat = createAudio('assets/beat.mp3'); + * + * // Show the default audio controls. + * beat.showControls(); + * + * describe('An audio beat plays when the user double-clicks the square.'); + * } + * + *
        + */ + _main.default.prototype.createAudio = function (src, callback) { + _main.default._validateParameters('createAudio', arguments); + return createMedia(this, 'audio', src, callback); + }; + /** CAMERA STUFF **/ + _main.default.prototype.VIDEO = 'video'; + _main.default.prototype.AUDIO = 'audio'; + // from: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia + // Older browsers might not implement mediaDevices at all, so we set an empty object first + if (navigator.mediaDevices === undefined) { + navigator.mediaDevices = { + }; + } // Some browsers partially implement mediaDevices. We can't just assign an object + // with getUserMedia as it would overwrite existing properties. + // Here, we will just add the getUserMedia property if it's missing. + + if (navigator.mediaDevices.getUserMedia === undefined) { + navigator.mediaDevices.getUserMedia = function (constraints) { + // First get ahold of the legacy getUserMedia, if present + var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; + // Some browsers just don't implement it - return a rejected promise with an error + // to keep a consistent interface + if (!getUserMedia) { + return Promise.reject(new Error('getUserMedia is not implemented in this browser')); + } // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise + + return new Promise(function (resolve, reject) { + getUserMedia.call(navigator, constraints, resolve, reject); + }); + }; + } /** + * Creates a `<video>` element that "captures" the audio/video stream from + * the webcam and microphone. + * + * `createCapture()` returns a new + * p5.MediaElement object. Videos are shown by + * default. They can be hidden by calling `capture.hide()` and drawn to the + * canvas using image(). + * + * The first parameter, `type`, is optional. It sets the type of capture to + * use. By default, `createCapture()` captures both audio and video. If `VIDEO` + * is passed, as in `createCapture(VIDEO)`, only video will be captured. + * If `AUDIO` is passed, as in `createCapture(AUDIO)`, only audio will be + * captured. A constraints object can also be passed to customize the stream. + * See the + * W3C documentation for possible properties. Different browsers support different + * properties. + * + * The 'flipped' property is an optional property which can be set to `{flipped:true}` + * to mirror the video output.If it is true then it means that video will be mirrored + * or flipped and if nothing is mentioned then by default it will be `false`. + * + * The second parameter,`callback`, is optional. It's a function to call once + * the capture is ready for use. The callback function should have one + * parameter, `stream`, that's a + * MediaStream object. + * + * Note: `createCapture()` only works when running a sketch locally or using HTTPS. Learn more + * here + * and here. + * + * @method createCapture + * @param {String|Constant|Object} [type] type of capture, either AUDIO or VIDEO, + * or a constraints object. Both video and audio + * audio streams are captured by default. + * @param {Object} [flipped] flip the capturing video and mirror the output with `{flipped:true}`. By + * default it is false. + * @param {Function} [callback] function to call once the stream + * has loaded. + * @return {p5.MediaElement} new p5.MediaElement object. + * + * @example + *
        + * + * function setup() { + * noCanvas(); + * + * // Create the video capture. + * createCapture(VIDEO); + * + * describe('A video stream from the webcam.'); + * } + * + *
        + * + *
        + * + * let capture; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create the video capture and hide the element. + * capture = createCapture(VIDEO); + * capture.hide(); + * + * describe('A video stream from the webcam with inverted colors.'); + * } + * + * function draw() { + * // Draw the video capture within the canvas. + * image(capture, 0, 0, width, width * capture.height / capture.width); + * + * // Invert the colors in the stream. + * filter(INVERT); + * } + * + *
        + *
        + * + * let capture; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create the video capture with mirrored output. + * capture = createCapture(VIDEO,{ flipped:true }); + * capture.size(100,100); + * + * describe('A video stream from the webcam with flipped or mirrored output.'); + * } + * + * + *
        + * + *
        + * + * function setup() { + * createCanvas(480, 120); + * + * // Create a constraints object. + * let constraints = { + * video: { + * mandatory: { + * minWidth: 1280, + * minHeight: 720 + * }, + * optional: [{ maxFrameRate: 10 }] + * }, + * audio: false + * }; + * + * // Create the video capture. + * createCapture(constraints); + * + * describe('A video stream from the webcam.'); + * } + * + *
        + */ + + _main.default.prototype.createCapture = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('createCapture', args); + // return if getUserMedia is not supported by the browser + if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) { + throw new DOMException('getUserMedia not supported in this browser'); + } + var useVideo = true; + var useAudio = true; + var constraints; + var callback; + var flipped = false; + for (var _i2 = 0, _args = args; _i2 < _args.length; _i2++) { + var arg = _args[_i2]; + if (arg === _main.default.prototype.VIDEO) useAudio = false; + else if (arg === _main.default.prototype.AUDIO) useVideo = false; + else if (_typeof(arg) === 'object') { + if (arg.flipped !== undefined) { + flipped = arg.flipped; + delete arg.flipped; + } + constraints = Object.assign({ + }, constraints, arg); + } else if (typeof arg === 'function') { + callback = arg; + } + } + var videoConstraints = { + video: useVideo, + audio: useAudio + }; + constraints = Object.assign({ + }, videoConstraints, constraints); + var domElement = document.createElement('video'); + // required to work in iOS 11 & up: + domElement.setAttribute('playsinline', ''); + navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { + try { + if ('srcObject' in domElement) { + domElement.srcObject = stream; + } else { + domElement.src = window.URL.createObjectURL(stream); + } + } catch (err) { + domElement.src = stream; + } + }).catch(function (e) { + if (e.name === 'NotFoundError') _main.default._friendlyError('No webcam found on this device', 'createCapture'); + if (e.name === 'NotAllowedError') _main.default._friendlyError('Access to the camera was denied', 'createCapture'); + console.error(e); + }); + var videoEl = addElement(domElement, this, true); + videoEl.loadedmetadata = false; + // set width and height onload metadata + domElement.addEventListener('loadedmetadata', function () { + domElement.play(); + if (domElement.width) { + videoEl.width = domElement.width; + videoEl.height = domElement.height; + if (flipped) { + videoEl.elt.style.transform = 'scaleX(-1)'; + } + } else { + videoEl.width = videoEl.elt.width = domElement.videoWidth; + videoEl.height = videoEl.elt.height = domElement.videoHeight; + } + videoEl.loadedmetadata = true; + if (callback) callback(domElement.srcObject); + }); + videoEl.flipped = flipped; + return videoEl; + }; + /** + * Creates a new p5.Element object. + * + * The first parameter, `tag`, is a string an HTML tag such as `'h5'`. + * + * The second parameter, `content`, is optional. It's a string that sets the + * HTML content to insert into the new element. New elements have no content + * by default. + * + * @method createElement + * @param {String} tag tag for the new element. + * @param {String} [content] HTML content to insert into the element. + * @return {p5.Element} new p5.Element object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an h5 element with nothing in it. + * createElement('h5'); + * + * describe('A gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an h5 element with the content "p5*js". + * let h5 = createElement('h5', 'p5*js'); + * + * // Set the element's style and position. + * h5.style('color', 'deeppink'); + * h5.position(30, 15); + * + * describe('The text "p5*js" written in pink in the middle of a gray square.'); + * } + * + *
        + */ + _main.default.prototype.createElement = function (tag, content) { + _main.default._validateParameters('createElement', arguments); + var elt = document.createElement(tag); + if (typeof content !== 'undefined') { + elt.innerHTML = content; + } + return addElement(elt, this); + }; + // ============================================================================= + // p5.Element additions + // ============================================================================= + /** + * + * Adds a class to the element. + * + * @for p5.Element + * @method addClass + * @param {String} class name of class to add. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a div element. + * let div = createDiv('div'); + * + * // Add a class to the div. + * div.addClass('myClass'); + * + * describe('A gray square.'); + * } + * + *
        + */ + _main.default.Element.prototype.addClass = function (c) { + if (this.elt.className) { + if (!this.hasClass(c)) { + this.elt.className = this.elt.className + ' ' + c; + } + } else { + this.elt.className = c; + } + return this; + }; + /** + * Removes a class from the element. + * + * @method removeClass + * @param {String} class name of class to remove. + * @chainable + * + * @example + *
        + * + * // In this example, a class is set when the div is created + * // and removed when mouse is pressed. This could link up + * // with a CSS style rule to toggle style properties. + * + * let div; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a div element. + * div = createDiv('div'); + * + * // Add a class to the div. + * div.addClass('myClass'); + * + * describe('A gray square.'); + * } + * + * // Remove 'myClass' from the div when the user presses the mouse. + * function mousePressed() { + * div.removeClass('myClass'); + * } + * + *
        + */ + _main.default.Element.prototype.removeClass = function (c) { + // Note: Removing a class that does not exist does NOT throw an error in classList.remove method + this.elt.classList.remove(c); + return this; + }; + /** + * Checks if a class is already applied to element. + * + * @method hasClass + * @returns {boolean} a boolean value if element has specified class. + * @param c {String} name of class to check. + * + * @example + *
        + * + * let div; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a div element. + * div = createDiv('div'); + * + * // Add the class 'show' to the div. + * div.addClass('show'); + * + * describe('A gray square.'); + * } + * + * // Toggle the class 'show' when the mouse is pressed. + * function mousePressed() { + * if (div.hasClass('show')) { + * div.addClass('show'); + * } else { + * div.removeClass('show'); + * } + * } + * + *
        + */ + _main.default.Element.prototype.hasClass = function (c) { + return this.elt.classList.contains(c); + }; + /** + * Toggles whether a class is applied to the element. + * + * @method toggleClass + * @param c {String} class name to toggle. + * @chainable + * + * @example + *
        + * + * let div; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a div element. + * div = createDiv('div'); + * + * // Add the 'show' class to the div. + * div.addClass('show'); + * + * describe('A gray square.'); + * } + * + * // Toggle the 'show' class when the mouse is pressed. + * function mousePressed() { + * div.toggleClass('show'); + * } + * + *
        + */ + _main.default.Element.prototype.toggleClass = function (c) { + // classList also has a toggle() method, but we cannot use that yet as support is unclear. + // See https://github.com/processing/p5.js/issues/3631 + // this.elt.classList.toggle(c); + if (this.elt.classList.contains(c)) { + this.elt.classList.remove(c); + } else { + this.elt.classList.add(c); + } + return this; + }; + /** + * Attaches the element as a child of another element. + * + * `myElement.child()` accepts either a string ID, DOM node, or + * p5.Element. For example, + * `myElement.child(otherElement)`. If no argument is provided, an array of + * children DOM nodes is returned. + * + * @method child + * @returns {Node[]} an array of child nodes. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create the div elements. + * let div0 = createDiv('Parent'); + * let div1 = createDiv('Child'); + * + * // Make div1 the child of div0 + * // using the p5.Element. + * div0.child(div1); + * + * describe('A gray square with the words "Parent" and "Child" written beneath it.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create the div elements. + * let div0 = createDiv('Parent'); + * let div1 = createDiv('Child'); + * + * // Give div1 an ID. + * div1.id('apples'); + * + * // Make div1 the child of div0 + * // using its ID. + * div0.child('apples'); + * + * describe('A gray square with the words "Parent" and "Child" written beneath it.'); + * } + * + *
        + * + *
        + * + * // This example assumes there is a div already on the page + * // with id "myChildDiv". + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create the div elements. + * let div0 = createDiv('Parent'); + * + * // Select the child element by its ID. + * let elt = document.getElementById('myChildDiv'); + * + * // Make div1 the child of div0 + * // using its HTMLElement object. + * div0.child(elt); + * + * describe('A gray square with the words "Parent" and "Child" written beneath it.'); + * } + * + *
        + */ + /** + * @method child + * @param {String|p5.Element} [child] the ID, DOM node, or p5.Element + * to add to the current element + * @chainable + */ + _main.default.Element.prototype.child = function (childNode) { + if (typeof childNode === 'undefined') { + return this.elt.childNodes; + } + if (typeof childNode === 'string') { + if (childNode[0] === '#') { + childNode = childNode.substring(1); + } + childNode = document.getElementById(childNode); + } else if (childNode instanceof _main.default.Element) { + childNode = childNode.elt; + } + if (childNode instanceof HTMLElement) { + this.elt.appendChild(childNode); + } + return this; + }; + /** + * Centers the element either vertically, horizontally, or both. + * + * `center()` will center the element relative to its parent or according to + * the page's body if the element has no parent. + * + * If no argument is passed, as in `myElement.center()` the element is aligned + * both vertically and horizontally. + * + * @method center + * @param {String} [align] passing 'vertical', 'horizontal' aligns element accordingly + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create the div element and style it. + * let div = createDiv(''); + * div.size(10, 10); + * div.style('background-color', 'orange'); + * + * // Center the div relative to the page's body. + * div.center(); + * + * describe('A gray square and an orange rectangle. The rectangle is at the center of the page.'); + * } + * + *
        + */ + _main.default.Element.prototype.center = function (align) { + var style = this.elt.style.display; + var hidden = this.elt.style.display === 'none'; + var parentHidden = this.parent().style.display === 'none'; + var pos = { + x: this.elt.offsetLeft, + y: this.elt.offsetTop + }; + if (hidden) this.show(); + if (parentHidden) this.parent().show(); + this.elt.style.display = 'block'; + this.position(0, 0); + var wOffset = Math.abs(this.parent().offsetWidth - this.elt.offsetWidth); + var hOffset = Math.abs(this.parent().offsetHeight - this.elt.offsetHeight); + if (align === 'both' || align === undefined) { + this.position(wOffset / 2 + this.parent().offsetLeft, hOffset / 2 + this.parent().offsetTop); + } else if (align === 'horizontal') { + this.position(wOffset / 2 + this.parent().offsetLeft, pos.y); + } else if (align === 'vertical') { + this.position(pos.x, hOffset / 2 + this.parent().offsetTop); + } + this.style('display', style); + if (hidden) this.hide(); + if (parentHidden) this.parent().hide(); + return this; + }; + /** + * Sets the inner HTML of the element, replacing any existing HTML. + * + * The second parameter, `append`, is optional. If `true` is passed, as in + * `myElement.html('hi', true)`, the HTML is appended instead of replacing + * existing HTML. + * + * If no arguments are passed, as in `myElement.html()`, the element's inner + * HTML is returned. + * + * @for p5.Element + * @method html + * @returns {String} the inner HTML of the element + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create the div element and set its size. + * let div = createDiv(''); + * div.size(100, 100); + * + * // Set the inner HTML to "hi". + * div.html('hi'); + * + * describe('A gray square with the word "hi" written beneath it.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create the div element and set its size. + * let div = createDiv('Hello '); + * div.size(100, 100); + * + * // Append "World" to the div's HTML. + * div.html('World', true); + * + * describe('A gray square with the text "Hello World" written beneath it.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create the div element. + * let div = createDiv('Hello'); + * + * // Prints "Hello" to the console. + * print(div.html()); + * + * describe('A gray square with the word "Hello!" written beneath it.'); + * } + * + *
        + */ + /** + * @method html + * @param {String} [html] the HTML to be placed inside the element + * @param {boolean} [append] whether to append HTML to existing + * @chainable + */ + _main.default.Element.prototype.html = function () { + if (arguments.length === 0) { + return this.elt.innerHTML; + } else if (arguments.length <= 1 ? undefined : arguments[1]) { + this.elt.insertAdjacentHTML('beforeend', arguments.length <= 0 ? undefined : arguments[0]); + return this; + } else { + this.elt.innerHTML = arguments.length <= 0 ? undefined : arguments[0]; + return this; + } + }; + /** + * Sets the element's position. + * + * The first two parameters, `x` and `y`, set the element's position relative + * to the top-left corner of the web page. + * + * The third parameter, `positionType`, is optional. It sets the element's + * positioning scheme. + * `positionType` is a string that can be either `'static'`, `'fixed'`, + * `'relative'`, `'sticky'`, `'initial'`, or `'inherit'`. + * + * If no arguments passed, as in `myElement.position()`, the method returns + * the element's position in an object, as in `{ x: 0, y: 0 }`. + * + * @method position + * @returns {Object} object of form `{ x: 0, y: 0 }` containing the element's position. + * + * @example + *
        + * + * function setup() { + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Positions the canvas 50px to the right and 100px + * // below the top-left corner of the window. + * cnv.position(50, 100); + * + * describe('A gray square that is 50 pixels to the right and 100 pixels down from the top-left corner of the web page.'); + * } + * + *
        + * + *
        + * + * function setup() { + * let cnv = createCanvas(100, 100); + * + * background(200); + * + * // Positions the canvas at the top-left corner + * // of the window with a 'fixed' position type. + * cnv.position(0, 0, 'fixed'); + * + * describe('A gray square in the top-left corner of the web page.'); + * } + * + *
        + */ + /** + * @method position + * @param {Number} [x] x-position relative to top-left of window (optional) + * @param {Number} [y] y-position relative to top-left of window (optional) + * @param {String} [positionType] it can be static, fixed, relative, sticky, initial or inherit (optional) + * @chainable + */ + _main.default.Element.prototype.position = function () { + if (arguments.length === 0) { + return { + x: this.elt.offsetLeft, + y: this.elt.offsetTop + }; + } else { + var positionType = 'absolute'; + if ((arguments.length <= 2 ? undefined : arguments[2]) === 'static' || (arguments.length <= 2 ? undefined : arguments[2]) === 'fixed' || (arguments.length <= 2 ? undefined : arguments[2]) === 'relative' || (arguments.length <= 2 ? undefined : arguments[2]) === 'sticky' || (arguments.length <= 2 ? undefined : arguments[2]) === 'initial' || (arguments.length <= 2 ? undefined : arguments[2]) === 'inherit') { + positionType = arguments.length <= 2 ? undefined : arguments[2]; + } + this.elt.style.position = positionType; + this.elt.style.left = (arguments.length <= 0 ? undefined : arguments[0]) + 'px'; + this.elt.style.top = (arguments.length <= 1 ? undefined : arguments[1]) + 'px'; + this.x = arguments.length <= 0 ? undefined : arguments[0]; + this.y = arguments.length <= 1 ? undefined : arguments[1]; + return this; + } + }; + /* Helper method called by p5.Element.style() */ + _main.default.Element.prototype._translate = function () { + this.elt.style.position = 'absolute'; + // save out initial non-translate transform styling + var transform = ''; + if (this.elt.style.transform) { + transform = this.elt.style.transform.replace(/translate3d\(.*\)/g, ''); + transform = transform.replace(/translate[X-Z]?\(.*\)/g, ''); + } + if (arguments.length === 2) { + this.elt.style.transform = 'translate(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'px, ' + (arguments.length <= 1 ? undefined : arguments[1]) + 'px)'; + } else if (arguments.length > 2) { + this.elt.style.transform = 'translate3d(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'px,' + (arguments.length <= 1 ? undefined : arguments[1]) + 'px,' + (arguments.length <= 2 ? undefined : arguments[2]) + 'px)'; + if (arguments.length === 3) { + this.elt.parentElement.style.perspective = '1000px'; + } else { + this.elt.parentElement.style.perspective = (arguments.length <= 3 ? undefined : arguments[3]) + 'px'; + } + } // add any extra transform styling back on end + + this.elt.style.transform += transform; + return this; + }; + /* Helper method called by p5.Element.style() */ + _main.default.Element.prototype._rotate = function () { + // save out initial non-rotate transform styling + var transform = ''; + if (this.elt.style.transform) { + transform = this.elt.style.transform.replace(/rotate3d\(.*\)/g, ''); + transform = transform.replace(/rotate[X-Z]?\(.*\)/g, ''); + } + if (arguments.length === 1) { + this.elt.style.transform = 'rotate(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'deg)'; + } else if (arguments.length === 2) { + this.elt.style.transform = 'rotate(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'deg, ' + (arguments.length <= 1 ? undefined : arguments[1]) + 'deg)'; + } else if (arguments.length === 3) { + this.elt.style.transform = 'rotateX(' + (arguments.length <= 0 ? undefined : arguments[0]) + 'deg)'; + this.elt.style.transform += 'rotateY(' + (arguments.length <= 1 ? undefined : arguments[1]) + 'deg)'; + this.elt.style.transform += 'rotateZ(' + (arguments.length <= 2 ? undefined : arguments[2]) + 'deg)'; + } // add remaining transform back on + + this.elt.style.transform += transform; + return this; + }; + /** + * Applies a style to the element by adding a + * CSS declaration. + * + * The first parameter, `property`, is a string. If the name of a style + * property is passed, as in `myElement.style('color')`, the method returns + * the current value as a string or `null` if it hasn't been set. If a + * `property:style` string is passed, as in + * `myElement.style('color:deeppink')`, the method sets the style `property` + * to `value`. + * + * The second parameter, `value`, is optional. It sets the property's value. + * `value` can be a string, as in + * `myElement.style('color', 'deeppink')`, or a + * p5.Color object, as in + * `myElement.style('color', myColor)`. + * + * @method style + * @param {String} property style property to set. + * @returns {String} value of the property. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a paragraph element and set its font color to "deeppink". + * let p = createP('p5*js'); + * p.position(25, 20); + * p.style('color', 'deeppink'); + * + * describe('The text p5*js written in pink on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let c = color('deeppink'); + * + * // Create a paragraph element and set its font color using a p5.Color object. + * let p = createP('p5*js'); + * p.position(25, 20); + * p.style('color', c); + * + * describe('The text p5*js written in pink on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a paragraph element and set its font color to "deeppink" + * // using property:value syntax. + * let p = createP('p5*js'); + * p.position(25, 20); + * p.style('color:deeppink'); + * + * describe('The text p5*js written in pink on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an empty paragraph element and set its font color to "deeppink". + * let p = createP(); + * p.position(5, 5); + * p.style('color', 'deeppink'); + * + * // Get the element's color as an RGB color string. + * let c = p.style('color'); + * + * // Set the element's inner HTML using the RGB color string. + * p.html(c); + * + * describe('The text "rgb(255, 20, 147)" written in pink on a gray background.'); + * } + * + *
        + */ + /** + * @method style + * @param {String} property + * @param {String|p5.Color} value value to assign to the property. + * @return {String} value of the property. + * @chainable + */ + _main.default.Element.prototype.style = function (prop, val) { + var self = this; + if (val instanceof _main.default.Color) { + val = 'rgba(' + val.levels[0] + ',' + val.levels[1] + ',' + val.levels[2] + ',' + val.levels[3] / 255 + ')'; + } + if (typeof val === 'undefined') { + if (prop.indexOf(':') === - 1) { + // no value set, so assume requesting a value + var styles = window.getComputedStyle(self.elt); + var style = styles.getPropertyValue(prop); + return style; + } else { + // value set using `:` in a single line string + var attrs = prop.split(';'); + for (var i = 0; i < attrs.length; i++) { + var parts = attrs[i].split(':'); + if (parts[0] && parts[1]) { + this.elt.style[parts[0].trim()] = parts[1].trim(); + } + } + } + } else { + // input provided as key,val pair + this.elt.style[prop] = val; + if (prop === 'width' || prop === 'height' || prop === 'left' || prop === 'top') { + var _styles = window.getComputedStyle(self.elt); + var styleVal = _styles.getPropertyValue(prop); + var numVal = styleVal.replace(/[^\d.]/g, ''); + this[prop] = Math.round(parseFloat(numVal, 10)); + } + } + return this; + }; + /** + * Adds an + * attribute + * to the element. + * + * This method is useful for advanced tasks. Most commonly-used attributes, + * such as `id`, can be set with their dedicated methods. For example, + * `nextButton.id('next')` sets an element's `id` attribute. Calling + * `nextButton.attribute('id', 'next')` has the same effect. + * + * The first parameter, `attr`, is the attribute's name as a string. Calling + * `myElement.attribute('align')` returns the attribute's current value as a + * string or `null` if it hasn't been set. + * + * The second parameter, `value`, is optional. It's a string used to set the + * attribute's value. For example, calling + * `myElement.attribute('align', 'center')` sets the element's horizontal + * alignment to `center`. + * + * @method attribute + * @return {String} value of the attribute. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a container div element and place it at the top-left corner. + * let container = createDiv(); + * container.position(0, 0); + * + * // Create a paragraph element and place it within the container. + * // Set its horizontal alignment to "left". + * let p1 = createP('hi'); + * p1.parent(container); + * p1.attribute('align', 'left'); + * + * // Create a paragraph element and place it within the container. + * // Set its horizontal alignment to "center". + * let p2 = createP('hi'); + * p2.parent(container); + * p2.attribute('align', 'center'); + * + * // Create a paragraph element and place it within the container. + * // Set its horizontal alignment to "right". + * let p3 = createP('hi'); + * p3.parent(container); + * p3.attribute('align', 'right'); + * + * describe('A gray square with the text "hi" written on three separate lines, each placed further to the right.'); + * } + * + *
        + */ + /** + * @method attribute + * @param {String} attr attribute to set. + * @param {String} value value to assign to the attribute. + * @chainable + */ + _main.default.Element.prototype.attribute = function (attr, value) { + //handling for checkboxes and radios to ensure options get + //attributes not divs + if (this.elt.firstChild != null && (this.elt.firstChild.type === 'checkbox' || this.elt.firstChild.type === 'radio')) { + if (typeof value === 'undefined') { + return this.elt.firstChild.getAttribute(attr); + } else { + for (var i = 0; i < this.elt.childNodes.length; i++) { + this.elt.childNodes[i].setAttribute(attr, value); + } + } + } else if (typeof value === 'undefined') { + return this.elt.getAttribute(attr); + } else { + this.elt.setAttribute(attr, value); + return this; + } + }; + /** + * Removes an attribute from the element. + * + * The parameter `attr` is the attribute's name as a string. For example, + * calling `myElement.removeAttribute('align')` removes its `align` + * attribute if it's been set. + * + * @method removeAttribute + * @param {String} attr attribute to remove. + * @chainable + * + * @example + *
        + * + * let p; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a paragraph element and place it in the center of the canvas. + * // Set its "align" attribute to "center". + * p = createP('hi'); + * p.position(0, 20); + * p.attribute('align', 'center'); + * + * describe('The text "hi" written in black at the center of a gray square. The text moves to the left edge when double-clicked.'); + * } + * + * // Remove the 'align' attribute when the user double-clicks the paragraph. + * function doubleClicked() { + * p.removeAttribute('align'); + * } + * + *
        + */ + _main.default.Element.prototype.removeAttribute = function (attr) { + if (this.elt.firstChild != null && (this.elt.firstChild.type === 'checkbox' || this.elt.firstChild.type === 'radio')) { + for (var i = 0; i < this.elt.childNodes.length; i++) { + this.elt.childNodes[i].removeAttribute(attr); + } + } + this.elt.removeAttribute(attr); + return this; + }; + /** + * Returns or sets the element's value. + * + * Calling `myElement.value()` returns the element's current value. + * + * The parameter, `value`, is an optional number or string. If provided, + * as in `myElement.value(123)`, it's used to set the element's value. + * + * @method value + * @return {String|Number} value of the element. + * + * @example + *
        + * + * let input; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a text input and place it beneath the canvas. + * // Set its default value to "hello". + * input = createInput('hello'); + * input.position(0, 100); + * + * describe('The text from an input box is displayed on a gray square.'); + * } + * + * function draw() { + * background(200); + * + * // Use the input's value to display a message. + * let msg = input.value(); + * text(msg, 0, 55); + * } + * + *
        + * + *
        + * + * let input; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a text input and place it beneath the canvas. + * // Set its default value to "hello". + * input = createInput('hello'); + * input.position(0, 100); + * + * describe('The text from an input box is displayed on a gray square. The text resets to "hello" when the user double-clicks the square.'); + * } + * + * function draw() { + * background(200); + * + * // Use the input's value to display a message. + * let msg = input.value(); + * text(msg, 0, 55); + * } + * + * // Reset the input's value. + * function doubleClicked() { + * input.value('hello'); + * } + * + *
        + */ + /** + * @method value + * @param {String|Number} value + * @chainable + */ + _main.default.Element.prototype.value = function () { + if (arguments.length > 0) { + this.elt.value = arguments.length <= 0 ? undefined : arguments[0]; + return this; + } else { + if (this.elt.type === 'range') { + return parseFloat(this.elt.value); + } else return this.elt.value; + } + }; + /** + * Shows the current element. + * + * @method show + * @chainable + * + * @example + *
        + * + * let p; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a paragraph element and hide it. + * p = createP('p5*js'); + * p.position(10, 10); + * p.hide(); + * + * describe('A gray square. The text "p5*js" appears when the user double-clicks the square.'); + * } + * + * // Show the paragraph when the user double-clicks. + * function doubleClicked() { + * p.show(); + * } + * + *
        + */ + _main.default.Element.prototype.show = function () { + this.elt.style.display = 'block'; + return this; + }; + /** + * Hides the current element. + * + * @method hide + * @chainable + * + * @example + * let p; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a paragraph element. + * p = createP('p5*js'); + * p.position(10, 10); + * + * describe('The text "p5*js" at the center of a gray square. The text disappears when the user double-clicks the square.'); + * } + * + * // Hide the paragraph when the user double-clicks. + * function doubleClicked() { + * p.hide(); + * } + * + * + */ + _main.default.Element.prototype.hide = function () { + this.elt.style.display = 'none'; + return this; + }; + /** + * Sets the element's width and height. + * + * Calling `myElement.size()` without an argument returns the element's size + * as an object with the properties `width` and `height`. For example, + * `{ width: 20, height: 10 }`. + * + * The first parameter, `width`, is optional. It's a number used to set the + * element's width. Calling `myElement.size(10)` + * + * The second parameter, 'height`, is also optional. It's a + * number used to set the element's height. For example, calling + * `myElement.size(20, 10)` sets the element's width to 20 pixels and height + * to 10 pixels. + * + * The constant `AUTO` can be used to adjust one dimension at a time while + * maintaining the aspect ratio, which is `width / height`. For example, + * consider an element that's 200 pixels wide and 100 pixels tall. Calling + * `myElement.size(20, AUTO)` sets the width to 20 pixels and height to 10 + * pixels. + * + * Note: In the case of elements that need to load data, such as images, wait + * to call `myElement.size()` until after the data loads. + * + * @method size + * @return {Object} width and height of the element in an object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a pink div element and place it at the top-left corner. + * let div = createDiv(); + * div.position(10, 10); + * div.style('background-color', 'deeppink'); + * + * // Set the div's width to 80 pixels and height to 20 pixels. + * div.size(80, 20); + * + * describe('A gray square with a pink rectangle near its top.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a pink div element and place it at the top-left corner. + * let div = createDiv(); + * div.position(10, 10); + * div.style('background-color', 'deeppink'); + * + * // Set the div's width to 80 pixels and height to 40 pixels. + * div.size(80, 40); + * + * // Get the div's size as an object. + * let s = div.size(); + * + * // Display the div's dimensions. + * div.html(`${s.width} x ${s.height}`); + * + * describe('A gray square with a pink rectangle near its top. The text "80 x 40" is written within the rectangle.'); + * } + * + *
        + * + *
        + * + * let img1; + * let img2; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Load an image of an astronaut on the moon + * // and place it at the top-left of the canvas. + * img1 = createImg( + * 'assets/moonwalk.jpg', + * 'An astronaut walking on the moon', + * '' + * ); + * img1.position(0, 0); + * + * // Load an image of an astronaut on the moon + * // and place it at the top-left of the canvas. + * // Resize the image once it's loaded. + * img2 = createImg( + * 'assets/moonwalk.jpg', + * 'An astronaut walking on the moon', + * '', + * resizeImage + * ); + * img2.position(0, 0); + * + * describe('A gray square two copies of a space image at the top-left. The copy in front is smaller.'); + * } + * + * // Resize img2 and keep its aspect ratio. + * function resizeImage() { + * img2.size(50, AUTO); + * } + * + *
        + */ + /** + * @method size + * @param {Number|Constant} [w] width of the element, either AUTO, or a number. + * @param {Number|Constant} [h] height of the element, either AUTO, or a number. + * @chainable + */ + _main.default.Element.prototype.size = function (w, h) { + if (arguments.length === 0) { + return { + width: this.elt.offsetWidth, + height: this.elt.offsetHeight + }; + } else { + var aW = w; + var aH = h; + var AUTO = _main.default.prototype.AUTO; + if (aW !== AUTO || aH !== AUTO) { + if (aW === AUTO) { + aW = h * this.width / this.height; + } else if (aH === AUTO) { + aH = w * this.height / this.width; + } // set diff for cnv vs normal div + + if (this.elt instanceof HTMLCanvasElement) { + var j = { + }; + var k = this.elt.getContext('2d'); + var prop; + for (prop in k) { + j[prop] = k[prop]; + } + this.elt.setAttribute('width', aW * this._pInst._pixelDensity); + this.elt.setAttribute('height', aH * this._pInst._pixelDensity); + this.elt.style.width = aW + 'px'; + this.elt.style.height = aH + 'px'; + this._pInst.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); + for (prop in j) { + this.elt.getContext('2d') [prop] = j[prop]; + } + } else { + this.elt.style.width = aW + 'px'; + this.elt.style.height = aH + 'px'; + this.elt.width = aW; + this.elt.height = aH; + } + this.width = aW; + this.height = aH; + if (this._pInst && this._pInst._curElement) { + // main canvas associated with p5 instance + if (this._pInst._curElement.elt === this.elt) { + this._pInst._setProperty('width', aW); + this._pInst._setProperty('height', aH); + } + } + } + return this; + } + }; + /** + * Removes the element, stops all audio/video streams, and removes all + * callback functions. + * + * @method remove + * + * @example + *
        + * + * let p; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a paragraph element. + * p = createP('p5*js'); + * p.position(10, 10); + * + * describe('The text "p5*js" written at the center of a gray square. '); + * } + * + * // Remove the paragraph when the user double-clicks. + * function doubleClicked() { + * p.remove(); + * } + * + *
        + */ + _main.default.Element.prototype.remove = function () { + // stop all audios/videos and detach all devices like microphone/camera etc + // used as input/output for audios/videos. + if (this instanceof _main.default.MediaElement) { + this.stop(); + var sources = this.elt.srcObject; + if (sources !== null) { + var tracks = sources.getTracks(); + tracks.forEach(function (track) { + track.stop(); + }); + } + } // delete the reference in this._pInst._elements + + var index = this._pInst._elements.indexOf(this); + if (index !== - 1) { + this._pInst._elements.splice(index, 1); + } // deregister events + + for (var ev in this._events) { + this.elt.removeEventListener(ev, this._events[ev]); + } + if (this.elt && this.elt.parentNode) { + this.elt.parentNode.removeChild(this.elt); + } + }; + /** + * Calls a function when the user drops a file on the element. + * + * The first parameter, `callback`, is a function to call once the file loads. + * The callback function should have one parameter, `file`, that's a + * p5.File object. If the user drops multiple files on + * the element, `callback`, is called once for each file. + * + * The second parameter, `fxn`, is a function to call when the browser detects + * one or more dropped files. The callback function should have one + * parameter, `event`, that's a + * DragEvent. + * + * @method drop + * @param {Function} callback called when a file loads. Called once for each file dropped. + * @param {Function} [fxn] called once when any files are dropped. + * @chainable + * + * @example + *
        + * + * // Drop an image on the canvas to view + * // this example. + * let img; + * + * function setup() { + * let c = createCanvas(100, 100); + * + * background(200); + * + * // Call handleFile() when a file that's dropped on the canvas has loaded. + * c.drop(handleFile); + * + * describe('A gray square. When the user drops an image on the square, it is displayed.'); + * } + * + * // Remove the existing image and display the new one. + * function handleFile(file) { + * // Remove the current image, if any. + * if (img) { + * img.remove(); + * } + * + * // Create an element with the + * // dropped file. + * img = createImg(file.data, ''); + * img.hide(); + * + * // Draw the image. + * image(img, 0, 0, width, height); + * } + * + *
        + * + *
        + * + * // Drop an image on the canvas to view + * // this example. + * let img; + * let msg; + * + * function setup() { + * let c = createCanvas(100, 100); + * + * background(200); + * + * // Call functions when the user drops a file on the canvas + * // and when the file loads. + * c.drop(handleFile, handleDrop); + * + * describe('A gray square. When the user drops an image on the square, it is displayed. The id attribute of canvas element is also displayed.'); + * } + * + * // Display the image when it loads. + * function handleFile(file) { + * // Remove the current image, if any. + * if (img) { + * img.remove(); + * } + * + * // Create an img element with the dropped file. + * img = createImg(file.data, ''); + * img.hide(); + * + * // Draw the image. + * image(img, 0, 0, width, height); + * } + * + * // Display the file's name when it loads. + * function handleDrop(event) { + * // Remove current paragraph, if any. + * if (msg) { + * msg.remove(); + * } + * + * // Use event to get the drop target's id. + * let id = event.target.id; + * + * // Write the canvas' id beneath it. + * msg = createP(id); + * msg.position(0, 100); + * + * // Set the font color randomly for each drop. + * let c = random(['red', 'green', 'blue']); + * msg.style('color', c); + * msg.style('font-size', '12px'); + * } + * + *
        + */ + _main.default.Element.prototype.drop = function (callback, fxn) { + // Is the file stuff supported? + if (window.File && window.FileReader && window.FileList && window.Blob) { + if (!this._dragDisabled) { + this._dragDisabled = true; + var preventDefault = function preventDefault(evt) { + evt.preventDefault(); + }; + // If you want to be able to drop you've got to turn off + // a lot of default behavior. + // avoid `attachListener` here, since it overrides other handlers. + this.elt.addEventListener('dragover', preventDefault); + // If this is a drag area we need to turn off the default behavior + this.elt.addEventListener('dragleave', preventDefault); + } // Deal with the files + + _main.default.Element._attachListener('drop', function (evt) { + evt.preventDefault(); + // Call the second argument as a callback that receives the raw drop event + if (typeof fxn === 'function') { + fxn.call(this, evt); + } // A FileList + + var files = evt.dataTransfer.files; + // Load each one and trigger the callback + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + try { + for (var _iterator10 = files[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var f = _step10.value; + _main.default.File._load(f, callback); + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + }, this); + } else { + console.log('The File APIs are not fully supported in this browser.'); + } + return this; + }; + /** + * Makes the element draggable. + * + * The parameter, `elmnt`, is optional. If another + * p5.Element object is passed, as in + * `myElement.draggable(otherElement)`, the other element will become draggable. + * + * @method draggable + * @param {p5.Element} [elmnt] another p5.Element. + * @chainable + * + * @example + *
        + * + * let stickyNote; + * let textInput; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a div element and style it. + * stickyNote = createDiv('Note'); + * stickyNote.position(5, 5); + * stickyNote.size(80, 20); + * stickyNote.style('font-size', '16px'); + * stickyNote.style('font-family', 'Comic Sans MS'); + * stickyNote.style('background', 'orchid'); + * stickyNote.style('padding', '5px'); + * + * // Make the note draggable. + * stickyNote.draggable(); + * + * // Create a panel div and style it. + * let panel = createDiv(''); + * panel.position(5, 40); + * panel.size(80, 50); + * panel.style('background', 'orchid'); + * panel.style('font-size', '16px'); + * panel.style('padding', '5px'); + * panel.style('text-align', 'center'); + * + * // Make the panel draggable. + * panel.draggable(); + * + * // Create a text input and style it. + * textInput = createInput('Note'); + * textInput.size(70); + * + * // Add the input to the panel. + * textInput.parent(panel); + * + * // Call handleInput() when text is input. + * textInput.input(handleInput); + * + * describe( + * 'A gray square with two purple rectangles that move when dragged. The top rectangle displays the text that is typed into the bottom rectangle.' + * ); + * } + * + * // Update stickyNote's HTML when text is input. + * function handleInput() { + * stickyNote.html(textInput.value()); + * } + * + *
        + */ + _main.default.Element.prototype.draggable = function (elmMove) { + var isTouch = ('ontouchstart' in window); + var x = 0, + y = 0, + px = 0, + py = 0, + elmDrag, + dragMouseDownEvt = isTouch ? 'touchstart' : 'mousedown', + closeDragElementEvt = isTouch ? 'touchend' : 'mouseup', + elementDragEvt = isTouch ? 'touchmove' : 'mousemove'; + if (elmMove === undefined) { + elmMove = this.elt; + elmDrag = elmMove; + } else if (elmMove !== this.elt && elmMove.elt !== this.elt) { + elmMove = elmMove.elt; + elmDrag = this.elt; + } + elmDrag.addEventListener(dragMouseDownEvt, dragMouseDown, false); + elmDrag.style.cursor = 'move'; + function dragMouseDown(e) { + e = e || window.event; + if (isTouch) { + var touches = e.changedTouches; + px = parseInt(touches[0].clientX); + py = parseInt(touches[0].clientY); + } else { + px = parseInt(e.clientX); + py = parseInt(e.clientY); + } + document.addEventListener(closeDragElementEvt, closeDragElement, false); + document.addEventListener(elementDragEvt, elementDrag, false); + return false; + } + function elementDrag(e) { + e = e || window.event; + if (isTouch) { + var touches = e.changedTouches; + x = px - parseInt(touches[0].clientX); + y = py - parseInt(touches[0].clientY); + px = parseInt(touches[0].clientX); + py = parseInt(touches[0].clientY); + } else { + x = px - parseInt(e.clientX); + y = py - parseInt(e.clientY); + px = parseInt(e.clientX); + py = parseInt(e.clientY); + } + elmMove.style.left = elmMove.offsetLeft - x + 'px'; + elmMove.style.top = elmMove.offsetTop - y + 'px'; + } + function closeDragElement() { + document.removeEventListener(closeDragElementEvt, closeDragElement, false); + document.removeEventListener(elementDragEvt, elementDrag, false); + } + return this; + }; + /*** SCHEDULE EVENTS ***/ + // Cue inspired by JavaScript setTimeout, and the + // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org + // eslint-disable-next-line no-unused-vars + var Cue = function Cue(callback, time, id, val) { + _classCallCheck(this, Cue); + this.callback = callback; + this.time = time; + this.id = id; + this.val = val; + }; // ============================================================================= + // p5.MediaElement additions + // ============================================================================= + /** + * A class to handle audio and video. + * + * `p5.MediaElement` extends p5.Element with + * methods to handle audio and video. `p5.MediaElement` objects are created by + * calling createVideo, + * createAudio, and + * createCapture. + * + * @class p5.MediaElement + * @constructor + * @param {String} elt DOM node that is wrapped + * @extends p5.Element + * + * @example + *
        + * + * let capture; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createCapture(). + * capture = createCapture(VIDEO); + * capture.hide(); + * + * describe('A webcam feed with inverted colors.'); + * } + * + * function draw() { + * // Display the video stream and invert the colors. + * image(capture, 0, 0, width, width * capture.height / capture.width); + * filter(INVERT); + * } + * + *
        + */ + var MediaElement = /*#__PURE__*/ function (_p5$Element) { + _inherits(MediaElement, _p5$Element); + var _super = _createSuper(MediaElement); + function MediaElement(elt, pInst) { + var _this; + _classCallCheck(this, MediaElement); + _this = _super.call(this, elt, pInst); + var self = _assertThisInitialized(_this); + _this.elt.crossOrigin = 'anonymous'; + _this._prevTime = 0; + _this._cueIDCounter = 0; + _this._cues = [ + ]; + _this.pixels = [ + ]; + _this._pixelsState = _assertThisInitialized(_this); + _this._pixelDensity = 1; + _this._modified = false; + // Media has an internal canvas that is used when drawing it to the main + // canvas. It will need to be updated each frame as the video itself plays. + // We don't want to update it every time we draw, however, in case the user + // has used load/updatePixels. To handle this, we record the frame drawn to + // the internal canvas so we only update it if the frame has changed. + _this._frameOnCanvas = - 1; + /** + * Path to the media element's source as a string. + * + * @property src + * @return {String} src + * + * @example + *
        + * + * let beat; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "https://p5js.org/reference/assets/beat.mp3" written in black on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * textWrap(CHAR); + * text(beat.src, 10, 10, 80, 80); + * } + * + *
        + */ + Object.defineProperty(self, 'src', { + get: function get() { + var firstChildSrc = self.elt.children[0].src; + var srcVal = self.elt.src === window.location.href ? '' : self.elt.src; + var ret = firstChildSrc === window.location.href ? srcVal : firstChildSrc; + return ret; + }, + set: function set(newValue) { + for (var i = 0; i < self.elt.children.length; i++) { + self.elt.removeChild(self.elt.children[i]); + } + var source = document.createElement('source'); + source.src = newValue; + elt.appendChild(source); + self.elt.src = newValue; + self.modified = true; + } + }); + // private _onended callback, set by the method: onended(callback) + self._onended = function () { + }; + self.elt.onended = function () { + self._onended(self); + }; + return _this; + } /** + * Plays audio or video from a media element. + * + * @method play + * @chainable + * + * @example + *
        + * + * let beat; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display a message. + * text('Click to play', 50, 50); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to play" written in black on a gray background. A beat plays when the user clicks the square.'); + * } + * + * // Play the beat when the user presses the mouse. + * function mousePressed() { + * beat.play(); + * } + * + *
        + */ + + _createClass(MediaElement, [ + { + key: 'play', + value: function play() { + var _this2 = this; + if (this.elt.currentTime === this.elt.duration) { + this.elt.currentTime = 0; + } + var promise; + if (this.elt.readyState > 1) { + promise = this.elt.play(); + } else { + // in Chrome, playback cannot resume after being stopped and must reload + this.elt.load(); + promise = this.elt.play(); + } + if (promise && promise.catch) { + promise.catch(function (e) { + // if it's an autoplay failure error + if (e.name === 'NotAllowedError') { + if (typeof IS_MINIFIED === 'undefined') { + _main.default._friendlyAutoplayError(_this2.src); + } else { + console.error(e); + } + } else { + // any other kind of error + console.error('Media play method encountered an unexpected error', e); + } + }); + } + return this; + } /** + * Stops a media element and sets its current time to 0. + * + * Calling `media.play()` will restart playing audio/video from the beginning. + * + * @method stop + * @chainable + * + * @example + *
        + * + * let beat; + * let isStopped = true; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to start" written in black on a gray background. The beat starts or stops when the user presses the mouse.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display different instructions based on playback. + * if (isStopped === true) { + * text('Click to start', 50, 50); + * } else { + * text('Click to stop', 50, 50); + * } + * } + * + * // Adjust playback when the user presses the mouse. + * function mousePressed() { + * if (isStopped === true) { + * // If the beat is stopped, play it. + * beat.play(); + * isStopped = false; + * } else { + * // If the beat is playing, stop it. + * beat.stop(); + * isStopped = true; + * } + * } + * + *
        + */ + + }, + { + key: 'stop', + value: function stop() { + this.elt.pause(); + this.elt.currentTime = 0; + return this; + } /** + * Pauses a media element. + * + * Calling `media.play()` will resume playing audio/video from the moment it paused. + * + * @method pause + * @chainable + * + * @example + *
        + * + * let beat; + * let isPaused = true; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to play" written in black on a gray background. The beat plays or pauses when the user clicks the square.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display different instructions based on playback. + * if (isPaused === true) { + * text('Click to play', 50, 50); + * } else { + * text('Click to pause', 50, 50); + * } + * } + * + * // Adjust playback when the user presses the mouse. + * function mousePressed() { + * if (isPaused === true) { + * // If the beat is paused, + * // play it. + * beat.play(); + * isPaused = false; + * } else { + * // If the beat is playing, + * // pause it. + * beat.pause(); + * isPaused = true; + * } + * } + * + *
        + */ + + }, + { + key: 'pause', + value: function pause() { + this.elt.pause(); + return this; + } /** + * Plays the audio/video repeatedly in a loop. + * + * @method loop + * @chainable + * + * @example + *
        + * + * let beat; + * let isLooping = false; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to loop" written in black on a gray background. A beat plays repeatedly in a loop when the user clicks. The beat stops when the user clicks again.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display different instructions based on playback. + * if (isLooping === true) { + * text('Click to stop', 50, 50); + * } else { + * text('Click to loop', 50, 50); + * } + * } + * + * // Adjust playback when the user presses the mouse. + * function mousePressed() { + * if (isLooping === true) { + * // If the beat is looping, stop it. + * beat.stop(); + * isLooping = false; + * } else { + * // If the beat is stopped, loop it. + * beat.loop(); + * isLooping = true; + * } + * } + * + *
        + */ + + }, + { + key: 'loop', + value: function loop() { + this.elt.setAttribute('loop', true); + this.play(); + return this; + } /** + * Stops the audio/video from playing in a loop. + * + * The media will stop when it finishes playing. + * + * @method noLoop + * @chainable + * + * @example + *
        + * + * let beat; + * let isPlaying = false; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * describe('The text "Click to play" written in black on a gray background. A beat plays when the user clicks. The beat stops when the user clicks again.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display different instructions based on playback. + * if (isPlaying === true) { + * text('Click to stop', 50, 50); + * } else { + * text('Click to play', 50, 50); + * } + * } + * + * // Adjust playback when the user presses the mouse. + * function mousePressed() { + * if (isPlaying === true) { + * // If the beat is playing, stop it. + * beat.stop(); + * isPlaying = false; + * } else { + * // If the beat is stopped, play it. + * beat.play(); + * isPlaying = true; + * } + * } + * + *
        + */ + + }, + { + key: 'noLoop', + value: function noLoop() { + this.elt.removeAttribute('loop'); + return this; + } /** + * Sets up logic to check that autoplay succeeded. + * + * @method setupAutoplayFailDetection + * @private + */ + + }, + { + key: '_setupAutoplayFailDetection', + value: function _setupAutoplayFailDetection() { + var _this3 = this; + var timeout = setTimeout(function () { + if (typeof IS_MINIFIED === 'undefined') { + _main.default._friendlyAutoplayError(_this3.src); + } else { + console.error(e); + } + }, 500); + this.elt.addEventListener('play', function () { + return clearTimeout(timeout); + }, { + passive: true, + once: true + }); + } /** + * Sets the audio/video to play once it's loaded. + * + * The parameter, `shouldAutoplay`, is optional. Calling + * `media.autoplay()` without an argument causes the media to play + * automatically. If `true` is passed, as in `media.autoplay(true)`, the + * media will automatically play. If `false` is passed, as in + * `media.autoPlay(false)`, it won't play automatically. + * + * @method autoplay + * @param {Boolean} [shouldAutoplay] whether the element should autoplay. + * @chainable + * + * @example + *
        + * + * let video; + * + * function setup() { + * noCanvas(); + * + * // Call handleVideo() once the video loads. + * video = createVideo('assets/fingers.mov', handleVideo); + * + * describe('A video of fingers walking on a treadmill.'); + * } + * + * // Set the video's size and play it. + * function handleVideo() { + * video.size(100, 100); + * video.autoplay(); + * } + * + *
        + * + *
        + * + * function setup() { + * noCanvas(); + * + * // Load a video, but don't play it automatically. + * let video = createVideo('assets/fingers.mov', handleVideo); + * + * // Play the video when the user clicks on it. + * video.mousePressed(handlePress); + * + * describe('An image of fingers on a treadmill. They start walking when the user double-clicks on them.'); + * } + * + *
        + * + * // Set the video's size and playback mode. + * function handleVideo() { + * video.size(100, 100); + * video.autoplay(false); + * } + * + * // Play the video. + * function handleClick() { + * video.play(); + * } + */ + + }, + { + key: 'autoplay', + value: function autoplay(val) { + var _this4 = this; + var oldVal = this.elt.getAttribute('autoplay'); + this.elt.setAttribute('autoplay', val); + // if we turned on autoplay + if (val && !oldVal) { + // bind method to this scope + var setupAutoplayFailDetection = function setupAutoplayFailDetection() { + return _this4._setupAutoplayFailDetection(); + }; + // if media is ready to play, schedule check now + if (this.elt.readyState === 4) { + setupAutoplayFailDetection(); + } else { + // otherwise, schedule check whenever it is ready + this.elt.addEventListener('canplay', setupAutoplayFailDetection, { + passive: true, + once: true + }); + } + } + return this; + } /** + * Sets the audio/video volume. + * + * Calling `media.volume()` without an argument returns the current volume + * as a number in the range 0 (off) to 1 (maximum). + * + * The parameter, `val`, is optional. It's a number that sets the volume + * from 0 (off) to 1 (maximum). For example, calling `media.volume(0.5)` + * sets the volume to half of its maximum. + * + * @method volume + * @return {Number} current volume. + * + * @example + *
        + * + * let dragon; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "Volume: V" on a gray square with media controls beneath it. The number "V" oscillates between 0 and 1 as the music plays.'); + * } + * + * function draw() { + * background(200); + * + * // Produce a number between 0 and 1. + * let n = 0.5 * sin(frameCount * 0.01) + 0.5; + * + * // Use n to set the volume. + * dragon.volume(n); + * + * // Get the current volume and display it. + * let v = dragon.volume(); + * + * // Round v to 1 decimal place for display. + * v = round(v, 1); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the volume. + * text(`Volume: ${v}`, 50, 50); + * } + * + *
        + */ + /** + * @method volume + * @param {Number} val volume between 0.0 and 1.0. + * @chainable + */ + + }, + { + key: 'volume', + value: function volume(val) { + if (typeof val === 'undefined') { + return this.elt.volume; + } else { + this.elt.volume = val; + } + } /** + * Sets the audio/video playback speed. + * + * The parameter, `val`, is optional. It's a number that sets the playback + * speed. 1 plays the media at normal speed, 0.5 plays it at half speed, 2 + * plays it at double speed, and so on. -1 plays the media at normal speed + * in reverse. + * + * Calling `media.speed()` returns the current speed as a number. + * + * Note: Not all browsers support backward playback. Even if they do, + * playback might not be smooth. + * + * @method speed + * @return {Number} current playback speed. + * + * @example + *
        + * + * let dragon; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "Speed: S" on a gray square with media controls beneath it. The number "S" oscillates between 0 and 1 as the music plays.'); + * } + * + * function draw() { + * background(200); + * + * // Produce a number between 0 and 2. + * let n = sin(frameCount * 0.01) + 1; + * + * // Use n to set the playback speed. + * dragon.speed(n); + * + * // Get the current speed and display it. + * let s = dragon.speed(); + * + * // Round s to 1 decimal place for display. + * s = round(s, 1); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the speed. + * text(`Speed: ${s}`, 50, 50); + * } + * + */ + /** + * @method speed + * @param {Number} speed speed multiplier for playback. + * @chainable + */ + + }, + { + key: 'speed', + value: function speed(val) { + if (typeof val === 'undefined') { + return this.presetPlaybackRate || this.elt.playbackRate; + } else { + if (this.loadedmetadata) { + this.elt.playbackRate = val; + } else { + this.presetPlaybackRate = val; + } + } + } /** + * Sets the media element's playback time. + * + * The parameter, `time`, is optional. It's a number that specifies the + * time, in seconds, to jump to when playback begins. + * + * Calling `media.time()` without an argument returns the number of seconds + * the audio/video has played. + * + * Note: Time resets to 0 when looping media restarts. + * + * @method time + * @return {Number} current time (in seconds). + * + * @example + *
        + * + * let dragon; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "S seconds" on a gray square with media controls beneath it. The number "S" increases as the song plays.'); + * } + * + * function draw() { + * background(200); + * + * // Get the current playback time. + * let s = dragon.time(); + * + * // Round s to 1 decimal place for display. + * s = round(s, 1); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the playback time. + * text(`${s} seconds`, 50, 50); + * } + * + *
        + * + *
        + * + * let dragon; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * + * // Show the default media controls. + * dragon.showControls(); + * + * // Jump to 2 seconds to start. + * dragon.time(2); + * + * describe('The text "S seconds" on a gray square with media controls beneath it. The number "S" increases as the song plays.'); + * } + * + * function draw() { + * background(200); + * + * // Get the current playback time. + * let s = dragon.time(); + * + * // Round s to 1 decimal place for display. + * s = round(s, 1); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the playback time. + * text(`${s} seconds`, 50, 50); + * } + * + *
        + */ + /** + * @method time + * @param {Number} time time to jump to (in seconds). + * @chainable + */ + + }, + { + key: 'time', + value: function time(val) { + if (typeof val === 'undefined') { + return this.elt.currentTime; + } else { + this.elt.currentTime = val; + return this; + } + } /** + * Returns the audio/video's duration in seconds. + * + * @method duration + * @return {Number} duration (in seconds). + * + * @example + *
        + * + * let dragon; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "S seconds left" on a gray square with media controls beneath it. The number "S" decreases as the song plays.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the time remaining. + * let s = dragon.duration() - dragon.time(); + * + * // Round s to 1 decimal place for display. + * s = round(s, 1); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the time remaining. + * text(`${s} seconds left`, 50, 50); + * } + * + *
        + */ + + }, + { + key: 'duration', + value: function duration() { + return this.elt.duration; + } + }, + { + key: '_ensureCanvas', + value: function _ensureCanvas() { + if (!this.canvas) { + this.canvas = document.createElement('canvas'); + this.drawingContext = this.canvas.getContext('2d'); + this.setModified(true); + } // Don't update the canvas again if we have already updated the canvas with + // the current frame + + var needsRedraw = this._frameOnCanvas !== this._pInst.frameCount; + if (this.loadedmetadata && needsRedraw) { + // wait for metadata for w/h + if (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.clearRect(0, 0, this.canvas.width, this.canvas.height); + if (this.flipped === true) { + this.drawingContext.save(); + this.drawingContext.scale( - 1, 1); + this.drawingContext.translate( - this.canvas.width, 0); + } + this.drawingContext.drawImage(this.elt, 0, 0, this.canvas.width, this.canvas.height); + if (this.flipped === true) { + this.drawingContext.restore(); + } + this.setModified(true); + this._frameOnCanvas = this._pInst.frameCount; + } + } + }, + { + key: 'loadPixels', + value: function loadPixels() { + this._ensureCanvas(); + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + return _main.default.Renderer2D.prototype.loadPixels.apply(this, args); + } + }, + { + key: 'updatePixels', + value: function updatePixels(x, y, w, h) { + if (this.loadedmetadata) { + // wait for metadata + this._ensureCanvas(); + _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); + } + this.setModified(true); + return this; + } + }, + { + key: 'get', + value: function get() { + this._ensureCanvas(); + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + return _main.default.Renderer2D.prototype.get.apply(this, args); + } + }, + { + key: '_getPixel', + value: function _getPixel() { + this.loadPixels(); + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + return _main.default.Renderer2D.prototype._getPixel.apply(this, args); + } + }, + { + key: 'set', + value: function set(x, y, imgOrCol) { + if (this.loadedmetadata) { + // wait for metadata + this._ensureCanvas(); + _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol); + this.setModified(true); + } + } + }, + { + key: 'copy', + value: function copy() { + this._ensureCanvas(); + for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { + args[_key7] = arguments[_key7]; + } + _main.default.prototype.copy.apply(this, args); + } + }, + { + key: 'mask', + value: function mask() { + this.loadPixels(); + this.setModified(true); + for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { + args[_key8] = arguments[_key8]; + } + _main.default.Image.prototype.mask.apply(this, args); + } /** + * helper method for web GL mode to figure out if the element + * has been modified and might need to be re-uploaded to texture + * memory between frames. + * @method isModified + * @private + * @return {boolean} a boolean indicating whether or not the + * image has been updated or modified since last texture upload. + */ + + }, + { + key: 'isModified', + value: function isModified() { + return this._modified; + } /** + * helper method for web GL mode to indicate that an element has been + * changed or unchanged since last upload. gl texture upload will + * set this value to false after uploading the texture; or might set + * it to true if metadata has become available but there is no actual + * texture data available yet.. + * @method setModified + * @param {boolean} val sets whether or not the element has been + * modified. + * @private + */ + + }, + { + key: 'setModified', + value: function setModified(value) { + this._modified = value; + } /** + * Calls a function when the audio/video reaches the end of its playback. + * + * The element is passed as an argument to the callback function. + * + * Note: The function won't be called if the media is looping. + * + * @method onended + * @param {Function} callback function to call when playback ends. + * The `p5.MediaElement` is passed as + * the argument. + * @chainable + * + * @example + *
        + * + * let beat; + * let isPlaying = false; + * let isDone = false; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * beat = createAudio('assets/beat.mp3'); + * + * // Call handleEnd() when the beat finishes. + * beat.onended(handleEnd); + * + * describe('The text "Click to play" written in black on a gray square. A beat plays when the user clicks. The text "Done!" appears when the beat finishes playing.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display different messages based on playback. + * if (isDone === true) { + * text('Done!', 50, 50); + * } else if (isPlaying === false) { + * text('Click to play', 50, 50); + * } else { + * text('Playing...', 50, 50); + * } + * } + * + * // Play the beat when the user presses the mouse. + * function mousePressed() { + * if (isPlaying === false) { + * isPlaying = true; + * beat.play(); + * } + * } + * + * // Set isDone when playback ends. + * function handleEnd() { + * isDone = false; + * } + * + *
        + */ + + }, + { + key: 'onended', + value: function onended(callback) { + this._onended = callback; + return this; + } /*** CONNECT TO WEB AUDIO API / p5.sound.js ***/ + /** + * Sends the element's audio to an output. + * + * The parameter, `audioNode`, can be an `AudioNode` or an object from the + * `p5.sound` library. + * + * If no element is provided, as in `myElement.connect()`, the element + * connects to the main output. All connections are removed by the + * `.disconnect()` method. + * + * Note: This method is meant to be used with the p5.sound.js addon library. + * + * @method connect + * @param {AudioNode|Object} audioNode AudioNode from the Web Audio API, + * or an object from the p5.sound library + */ + + }, + { + key: 'connect', + value: function connect(obj) { + var audioContext, + mainOutput; + // if p5.sound exists, same audio context + if (typeof _main.default.prototype.getAudioContext === 'function') { + audioContext = _main.default.prototype.getAudioContext(); + mainOutput = _main.default.soundOut.input; + } else { + try { + audioContext = obj.context; + mainOutput = audioContext.destination; + } catch (e) { + throw 'connect() is meant to be used with Web Audio API or p5.sound.js'; + } + } // create a Web Audio MediaElementAudioSourceNode if none already exists + + if (!this.audioSourceNode) { + this.audioSourceNode = audioContext.createMediaElementSource(this.elt); + // connect to main output when this method is first called + this.audioSourceNode.connect(mainOutput); + } // connect to object if provided + + if (obj) { + if (obj.input) { + this.audioSourceNode.connect(obj.input); + } else { + this.audioSourceNode.connect(obj); + } + } else { + // otherwise connect to main output of p5.sound / AudioContext + this.audioSourceNode.connect(mainOutput); + } + } /** + * Disconnect all Web Audio routing, including to the main output. + * + * This is useful if you want to re-route the output through audio effects, + * for example. + * + * @method disconnect + */ + + }, + { + key: 'disconnect', + value: function disconnect() { + if (this.audioSourceNode) { + this.audioSourceNode.disconnect(); + } else { + throw 'nothing to disconnect'; + } + } /*** SHOW / HIDE CONTROLS ***/ + /** + * Show the default + * HTMLMediaElement + * controls. + * + * Note: The controls vary between web browsers. + * + * @method showControls + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background('cornflowerblue'); + * + * // Style the text. + * textAlign(CENTER); + * textSize(50); + * + * // Display a dragon. + * text('🐉', 50, 50); + * + * // Create a p5.MediaElement using createAudio(). + * let dragon = createAudio('assets/lucky_dragons.mp3'); + * + * // Show the default media controls. + * dragon.showControls(); + * + * describe('A dragon emoji, 🐉, drawn in the center of a blue square. A song plays in the background. Audio controls are displayed beneath the canvas.'); + * } + * + *
        + */ + + }, + { + key: 'showControls', + value: function showControls() { + // must set style for the element to show on the page + this.elt.style['text-align'] = 'inherit'; + this.elt.controls = true; + } /** + * Hide the default + * HTMLMediaElement + * controls. + * + * @method hideControls + * + * @example + *
        + * + * let dragon; + * let isHidden = false; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * dragon = createAudio('assets/lucky_dragons.mp3'); + * + * // Show the default media controls. + * dragon.showControls(); + * + * describe('The text "Double-click to hide controls" written in the middle of a gray square. A song plays in the background. Audio controls are displayed beneath the canvas. The controls appear/disappear when the user double-clicks the square.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * + * // Display a different message when controls are hidden or shown. + * if (isHidden === true) { + * text('Double-click to show controls', 10, 20, 80, 80); + * } else { + * text('Double-click to hide controls', 10, 20, 80, 80); + * } + * } + * + * // Show/hide controls based on a double-click. + * function doubleClicked() { + * if (isHidden === true) { + * dragon.showControls(); + * isHidden = false; + * } else { + * dragon.hideControls(); + * isHidden = true; + * } + * } + * + *
        + */ + + }, + { + key: 'hideControls', + value: function hideControls() { + this.elt.controls = false; + } /** + * Schedules a function to call when the audio/video reaches a specific time + * during its playback. + * + * The first parameter, `time`, is the time, in seconds, when the function + * should run. This value is passed to `callback` as its first argument. + * + * The second parameter, `callback`, is the function to call at the specified + * cue time. + * + * The third parameter, `value`, is optional and can be any type of value. + * `value` is passed to `callback`. + * + * Calling `media.addCue()` returns an ID as a string. This is useful for + * removing the cue later. + * + * @method addCue + * @param {Number} time cue time to run the callback function. + * @param {Function} callback function to call at the cue time. + * @param {Object} [value] object to pass as the argument to + * `callback`. + * @return {Number} id ID of this cue, + * useful for `media.removeCue(id)`. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * let beat = createAudio('assets/beat.mp3'); + * + * // Play the beat in a loop. + * beat.loop(); + * + * // Schedule a few events. + * beat.addCue(0, changeBackground, 'red'); + * beat.addCue(2, changeBackground, 'deeppink'); + * beat.addCue(4, changeBackground, 'orchid'); + * beat.addCue(6, changeBackground, 'lavender'); + * + * describe('A red square with a beat playing in the background. Its color changes every 2 seconds while the audio plays.'); + * } + * + * // Change the background color. + * function changeBackground(c) { + * background(c); + * } + * + *
        + */ + + }, + { + key: 'addCue', + value: function addCue(time, callback, val) { + var id = this._cueIDCounter++; + var cue = new Cue(callback, time, id, val); + this._cues.push(cue); + if (!this.elt.ontimeupdate) { + this.elt.ontimeupdate = this._onTimeUpdate.bind(this); + } + return id; + } /** + * Removes a callback based on its ID. + * + * @method removeCue + * @param {Number} id ID of the cue, created by `media.addCue()`. + * + * @example + *
        + * + * let lavenderID; + * let isRemoved = false; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.MediaElement using createAudio(). + * let beat = createAudio('assets/beat.mp3'); + * + * // Play the beat in a loop. + * beat.loop(); + * + * // Schedule a few events. + * beat.addCue(0, changeBackground, 'red'); + * beat.addCue(2, changeBackground, 'deeppink'); + * beat.addCue(4, changeBackground, 'orchid'); + * + * // Record the ID of the "lavender" callback. + * lavenderID = beat.addCue(6, changeBackground, 'lavender'); + * + * describe('The text "Double-click to remove lavender." written on a red square. The color changes every 2 seconds while the audio plays. The lavender option is removed when the user double-clicks the square.'); + * } + * + * function draw() { + * background(200); + * + * // Display different instructions based on the available callbacks. + * if (isRemoved === false) { + * text('Double-click to remove lavender.', 10, 10, 80, 80); + * } else { + * text('No more lavender.', 10, 10, 80, 80); + * } + * } + * + * // Change the background color. + * function changeBackground(c) { + * background(c); + * } + * + * // Remove the lavender color-change cue when the user double-clicks. + * function doubleClicked() { + * if (isRemoved === false) { + * beat.removeCue(lavenderID); + * isRemoved = true; + * } + * } + * + *
        + */ + + }, + { + key: 'removeCue', + value: function removeCue(id) { + for (var i = 0; i < this._cues.length; i++) { + if (this._cues[i].id === id) { + console.log(id); + this._cues.splice(i, 1); + } + } + if (this._cues.length === 0) { + this.elt.ontimeupdate = null; + } + } /** + * Removes all functions scheduled with `media.addCue()`. + * + * @method clearCues + * + * @example + *
        + * + * let isChanging = true; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.MediaElement using createAudio(). + * let beat = createAudio('assets/beat.mp3'); + * + * // Play the beat in a loop. + * beat.loop(); + * + * // Schedule a few events. + * beat.addCue(0, changeBackground, 'red'); + * beat.addCue(2, changeBackground, 'deeppink'); + * beat.addCue(4, changeBackground, 'orchid'); + * beat.addCue(6, changeBackground, 'lavender'); + * + * describe('The text "Double-click to stop changing." written on a square. The color changes every 2 seconds while the audio plays. The color stops changing when the user double-clicks the square.'); + * } + * + * function draw() { + * background(200); + * + * // Display different instructions based on the available callbacks. + * if (isChanging === true) { + * text('Double-click to stop changing.', 10, 10, 80, 80); + * } else { + * text('No more changes.', 10, 10, 80, 80); + * } + * } + * + * // Change the background color. + * function changeBackground(c) { + * background(c); + * } + * + * // Remove cued functions and stop changing colors when the user + * // double-clicks. + * function doubleClicked() { + * if (isChanging === true) { + * beat.clearCues(); + * isChanging = false; + * } + * } + * + *
        + */ + + }, + { + key: 'clearCues', + value: function clearCues() { + this._cues = [ + ]; + this.elt.ontimeupdate = null; + } // private method that checks for cues to be fired if events + // have been scheduled using addCue(callback, time). + + }, + { + key: '_onTimeUpdate', + value: function _onTimeUpdate() { + var playbackTime = this.time(); + for (var i = 0; i < this._cues.length; i++) { + var callbackTime = this._cues[i].time; + var val = this._cues[i].val; + if (this._prevTime < callbackTime && callbackTime <= playbackTime) { + // pass the scheduled callbackTime as parameter to the callback + this._cues[i].callback(val); + } + } + this._prevTime = playbackTime; + } + } + ]); + return MediaElement; + }(_main.default.Element); + _main.default.MediaElement = MediaElement; + /** + * A class to describe a file. + * + * `p5.File` objects are used by + * myElement.drop() and + * created by + * createFileInput. + * + * @class p5.File + * @constructor + * @param {File} file wrapped file. + * + * @example + *
        + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a file input and place it beneath the canvas. + * // Call displayInfo() when the file loads. + * let input = createFileInput(displayInfo); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.'); + * } + * + * // Display the p5.File's info once it loads. + * function displayInfo(file) { + * background(200); + * + * // Display the p5.File's name. + * text(file.name, 10, 10, 80, 40); + * + * // Display the p5.File's type and subtype. + * text(`${file.type}/${file.subtype}`, 10, 70); + * + * // Display the p5.File's size in bytes. + * text(file.size, 10, 90); + * } + * + *
        + * + *
        + * + * // Use the file input to select an image to + * // load and display. + * let img; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a file input and place it beneath the canvas. + * // Call handleImage() when the file image loads. + * let input = createFileInput(handleImage); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.'); + * } + * + * function draw() { + * background(200); + * + * // Draw the image if it's ready. + * if (img) { + * image(img, 0, 0, width, height); + * } + * } + * + * // Use the p5.File's data once it loads. + * function handleImage(file) { + * // Check the p5.File's type. + * if (file.type === 'image') { + * // Create an image using using the p5.File's data. + * img = createImg(file.data, ''); + * + * // Hide the image element so it doesn't appear twice. + * img.hide(); + * } else { + * img = null; + * } + * } + * + *
        + */ + var File = /*#__PURE__*/ function () { + function File(file, pInst) { + _classCallCheck(this, File); + /** + * Underlying + * File + * object. All `File` properties and methods are accessible. + * + * @property file + * + * @example + *
        + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a file input and place it beneath the canvas. + * // Call displayInfo() when the file loads. + * let input = createFileInput(displayInfo); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.'); + * } + * + * // Use the p5.File once it loads. + * function displayInfo(file) { + * background(200); + * + * // Display the p5.File's name. + * text(file.name, 10, 10, 80, 40); + * + * // Display the p5.File's type and subtype. + * text(`${file.type}/${file.subtype}`, 10, 70); + * + * // Display the p5.File's size in bytes. + * text(file.size, 10, 90); + * } + * + *
        + */ + this.file = file; + this._pInst = pInst; + // Splitting out the file type into two components + // This makes determining if image or text etc simpler + var typeList = file.type.split('/'); + /** + * The file + * MIME type + * as a string. + * + * For example, `'image'` and `'text'` are both MIME types. + * + * @property type + * + * @example + *
        + * + * // Use the file input to load a file and display its info. + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a file input and place it beneath the canvas. + * // Call displayType() when the file loads. + * let input = createFileInput(displayType); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its type is written in black.'); + * } + * + * // Display the p5.File's type once it loads. + * function displayType(file) { + * background(200); + * + * // Display the p5.File's type. + * text(`This is file's type is: ${file.type}`, 10, 10, 80, 80); + * } + * + *
        + */ + this.type = typeList[0]; + /** + * The file subtype as a string. + * + * For example, a file with an `'image'` + * MIME type + * may have a subtype such as ``png`` or ``jpeg``. + * + * @property subtype + * + * @example + *
        + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a file input and place it beneath the canvas. + * // Call displaySubtype() when the file loads. + * let input = createFileInput(displaySubtype); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its subtype is written in black.'); + * } + * + * // Display the p5.File's type once it loads. + * function displaySubtype(file) { + * background(200); + * + * // Display the p5.File's subtype. + * text(`This is file's subtype is: ${file.subtype}`, 10, 10, 80, 80); + * } + * + *
        + */ + this.subtype = typeList[1]; + /** + * The file name as a string. + * + * @property name + * + * @example + *
        + * + * // Use the file input to load a + * // file and display its info. + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a file input and place it beneath the canvas. + * // Call displayName() when the file loads. + * let input = createFileInput(displayName); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its name is written in black.'); + * } + * + * // Display the p5.File's name once it loads. + * function displayName(file) { + * background(200); + * + * // Display the p5.File's name. + * text(`This is file's name is: ${file.name}`, 10, 10, 80, 80); + * } + * + *
        + */ + this.name = file.name; + /** + * The number of bytes in the file. + * + * @property size + * + * @example + *
        + * + * // Use the file input to load a file and display its info. + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a file input and place it beneath the canvas. + * // Call displaySize() when the file loads. + * let input = createFileInput(displaySize); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its size in bytes is written in black.'); + * } + * + * // Display the p5.File's size in bytes once it loads. + * function displaySize(file) { + * background(200); + * + * // Display the p5.File's size. + * text(`This is file has ${file.size} bytes.`, 10, 10, 80, 80); + * } + * + *
        + */ + this.size = file.size; + /** + * A string containing the file's data. + * + * Data can be either image data, text contents, or a parsed object in the + * case of JSON and p5.XML objects. + * + * @property data + * + * @example + *
        + * + * // Use the file input to load a file and display its info. + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a file input and place it beneath the canvas. + * // Call displayData() when the file loads. + * let input = createFileInput(displayData); + * input.position(0, 100); + * + * describe('A gray square with a file input beneath it. If the user loads a file, its data is written in black.'); + * } + * + * // Display the p5.File's data once it loads. + * function displayData(file) { + * background(200); + * + * // Display the p5.File's data, which looks like a random string of characters. + * text(file.data, 10, 10, 80, 80); + * } + * + *
        + */ + this.data = undefined; + } + _createClass(File, null, [ + { + key: '_createLoader', + value: function _createLoader(theFile, callback) { + var reader = new FileReader(); + reader.onload = function (e) { + var p5file = new _main.default.File(theFile); + if (p5file.file.type === 'application/json') { + // Parse JSON and store the result in data + p5file.data = JSON.parse(e.target.result); + } else if (p5file.file.type === 'text/xml') { + // Parse XML, wrap it in p5.XML and store the result in data + var parser = new DOMParser(); + var xml = parser.parseFromString(e.target.result, 'text/xml'); + p5file.data = new _main.default.XML(xml.documentElement); + } else { + p5file.data = e.target.result; + } + callback(p5file); + }; + return reader; + } + }, + { + key: '_load', + value: function _load(f, callback) { + // Text or data? + // This should likely be improved + if (/^text\//.test(f.type) || f.type === 'application/json') { + _main.default.File._createLoader(f, callback).readAsText(f); + } else if (!/^(video|audio)\//.test(f.type)) { + _main.default.File._createLoader(f, callback).readAsDataURL(f); + } else { + var file = new _main.default.File(f); + file.data = URL.createObjectURL(f); + callback(file); + } + } + } + ]); + return File; + }(); + _main.default.File = File; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.every': 172, + 'core-js/modules/es.array.filter': 174, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.splice': 188, + 'core-js/modules/es.function.name': 191, + 'core-js/modules/es.object.assign': 199, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.promise': 206, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.string.trim': 224, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.for-each': 260, + 'core-js/modules/web.dom-collections.iterator': 261, + 'core-js/modules/web.url': 263 + } + ], + 320: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Events + * @submodule Acceleration + * @for p5 + * @requires core + * @main Events + */ + /** + * The system variable deviceOrientation always contains the orientation of + * the device. The value of this variable will either be set 'landscape' + * or 'portrait'. If no data is available it will be set to 'undefined'. + * either LANDSCAPE or PORTRAIT. + * + * @property {Constant} deviceOrientation + * @readOnly + */ + + _main.default.prototype.deviceOrientation = window.innerWidth / window.innerHeight > 1 ? 'landscape' : 'portrait'; + /** + * The system variable accelerationX always contains the acceleration of the + * device along the x axis. Value is represented as meters per second squared. + * + * @property {Number} accelerationX + * @readOnly + * @example + *
        + * + * // Move a touchscreen device to register + * // acceleration changes. + * function draw() { + * background(220, 50); + * fill('magenta'); + * ellipse(width / 2, height / 2, accelerationX); + * describe('Magnitude of device acceleration is displayed as ellipse size.'); + * } + * + *
        + */ + _main.default.prototype.accelerationX = 0; + /** + * The system variable accelerationY always contains the acceleration of the + * device along the y axis. Value is represented as meters per second squared. + * + * @property {Number} accelerationY + * @readOnly + * @example + *
        + * + * // Move a touchscreen device to register + * // acceleration changes. + * function draw() { + * background(220, 50); + * fill('magenta'); + * ellipse(width / 2, height / 2, accelerationY); + * describe('Magnitude of device acceleration is displayed as ellipse size'); + * } + * + *
        + */ + _main.default.prototype.accelerationY = 0; + /** + * The system variable accelerationZ always contains the acceleration of the + * device along the z axis. Value is represented as meters per second squared. + * + * @property {Number} accelerationZ + * @readOnly + * + * @example + *
        + * + * // Move a touchscreen device to register + * // acceleration changes. + * function draw() { + * background(220, 50); + * fill('magenta'); + * ellipse(width / 2, height / 2, accelerationZ); + * describe('Magnitude of device acceleration is displayed as ellipse size'); + * } + * + *
        + */ + _main.default.prototype.accelerationZ = 0; + /** + * The system variable pAccelerationX always contains the acceleration of the + * device along the x axis in the frame previous to the current frame. Value + * is represented as meters per second squared. + * + * @property {Number} pAccelerationX + * @readOnly + */ + _main.default.prototype.pAccelerationX = 0; + /** + * The system variable pAccelerationY always contains the acceleration of the + * device along the y axis in the frame previous to the current frame. Value + * is represented as meters per second squared. + * + * @property {Number} pAccelerationY + * @readOnly + */ + _main.default.prototype.pAccelerationY = 0; + /** + * The system variable pAccelerationZ always contains the acceleration of the + * device along the z axis in the frame previous to the current frame. Value + * is represented as meters per second squared. + * + * @property {Number} pAccelerationZ + * @readOnly + */ + _main.default.prototype.pAccelerationZ = 0; + /** + * _updatePAccelerations updates the pAcceleration values + * + * @private + */ + _main.default.prototype._updatePAccelerations = function () { + this._setProperty('pAccelerationX', this.accelerationX); + this._setProperty('pAccelerationY', this.accelerationY); + this._setProperty('pAccelerationZ', this.accelerationZ); + }; + /** + * The system variable rotationX always contains the rotation of the + * device along the x axis. If the sketch + * angleMode() is set to DEGREES, the value will be -180 to 180. If + * it is set to RADIANS, the value will be -PI to PI. + * + * Note: The order the rotations are called is important, ie. if used + * together, it must be called in the order Z-X-Y or there might be + * unexpected behaviour. + * + * @property {Number} rotationX + * @readOnly + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(200); + * //rotateZ(radians(rotationZ)); + * rotateX(radians(rotationX)); + * //rotateY(radians(rotationY)); + * box(200, 200, 200); + * describe(`red horizontal line right, green vertical line bottom. + * black background.`); + * } + * + *
        + */ + _main.default.prototype.rotationX = 0; + /** + * The system variable rotationY always contains the rotation of the + * device along the y axis. If the sketch + * angleMode() is set to DEGREES, the value will be -90 to 90. If + * it is set to RADIANS, the value will be -PI/2 to PI/2. + * + * Note: The order the rotations are called is important, ie. if used + * together, it must be called in the order Z-X-Y or there might be + * unexpected behaviour. + * + * @property {Number} rotationY + * @readOnly + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(200); + * //rotateZ(radians(rotationZ)); + * //rotateX(radians(rotationX)); + * rotateY(radians(rotationY)); + * box(200, 200, 200); + * describe(`red horizontal line right, green vertical line bottom. + * black background.`); + * } + * + *
        + */ + _main.default.prototype.rotationY = 0; + /** + * The system variable rotationZ always contains the rotation of the + * device along the z axis. If the sketch + * angleMode() is set to DEGREES, the value will be 0 to 360. If + * it is set to RADIANS, the value will be 0 to 2*PI. + * + * Unlike rotationX and rotationY, this variable is available for devices + * with a built-in compass only. + * + * Note: The order the rotations are called is important, ie. if used + * together, it must be called in the order Z-X-Y or there might be + * unexpected behaviour. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(200); + * rotateZ(radians(rotationZ)); + * //rotateX(radians(rotationX)); + * //rotateY(radians(rotationY)); + * box(200, 200, 200); + * describe(`red horizontal line right, green vertical line bottom. + * black background.`); + * } + * + *
        + * + * @property {Number} rotationZ + * @readOnly + */ + _main.default.prototype.rotationZ = 0; + /** + * The system variable pRotationX always contains the rotation of the + * device along the x axis in the frame previous to the current frame. + * If the sketch angleMode() is set to DEGREES, + * the value will be -180 to 180. If it is set to RADIANS, the value will + * be -PI to PI. + * + * pRotationX can also be used with rotationX to determine the rotate + * direction of the device along the X-axis. + * @example + *
        + * + * // A simple if statement looking at whether + * // rotationX - pRotationX < 0 is true or not will be + * // sufficient for determining the rotate direction + * // in most cases. + * + * // Some extra logic is needed to account for cases where + * // the angles wrap around. + * let rotateDirection = 'clockwise'; + * + * // Simple range conversion to make things simpler. + * // This is not absolutely necessary but the logic + * // will be different in that case. + * + * let rX = rotationX + 180; + * let pRX = pRotationX + 180; + * + * if ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) { + * rotateDirection = 'clockwise'; + * } else if (rX - pRX < 0 || rX - pRX > 270) { + * rotateDirection = 'counter-clockwise'; + * } + * + * print(rotateDirection); + * describe('no image to display.'); + * + *
        + * + * @property {Number} pRotationX + * @readOnly + */ + _main.default.prototype.pRotationX = 0; + /** + * The system variable pRotationY always contains the rotation of the + * device along the y axis in the frame previous to the current frame. + * If the sketch angleMode() is set to DEGREES, + * the value will be -90 to 90. If it is set to RADIANS, the value will + * be -PI/2 to PI/2. + * + * pRotationY can also be used with rotationY to determine the rotate + * direction of the device along the Y-axis. + * @example + *
        + * + * // A simple if statement looking at whether + * // rotationY - pRotationY < 0 is true or not will be + * // sufficient for determining the rotate direction + * // in most cases. + * + * // Some extra logic is needed to account for cases where + * // the angles wrap around. + * let rotateDirection = 'clockwise'; + * + * // Simple range conversion to make things simpler. + * // This is not absolutely necessary but the logic + * // will be different in that case. + * + * let rY = rotationY + 180; + * let pRY = pRotationY + 180; + * + * if ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) { + * rotateDirection = 'clockwise'; + * } else if (rY - pRY < 0 || rY - pRY > 270) { + * rotateDirection = 'counter-clockwise'; + * } + * print(rotateDirection); + * describe('no image to display.'); + * + *
        + * + * @property {Number} pRotationY + * @readOnly + */ + _main.default.prototype.pRotationY = 0; + /** + * The system variable pRotationZ always contains the rotation of the + * device along the z axis in the frame previous to the current frame. + * If the sketch angleMode() is set to DEGREES, + * the value will be 0 to 360. If it is set to RADIANS, the value will + * be 0 to 2*PI. + * + * pRotationZ can also be used with rotationZ to determine the rotate + * direction of the device along the Z-axis. + * @example + *
        + * + * // A simple if statement looking at whether + * // rotationZ - pRotationZ < 0 is true or not will be + * // sufficient for determining the rotate direction + * // in most cases. + * + * // Some extra logic is needed to account for cases where + * // the angles wrap around. + * let rotateDirection = 'clockwise'; + * + * if ( + * (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) || + * rotationZ - pRotationZ < -270 + * ) { + * rotateDirection = 'clockwise'; + * } else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) { + * rotateDirection = 'counter-clockwise'; + * } + * print(rotateDirection); + * describe('no image to display.'); + * + *
        + * + * @property {Number} pRotationZ + * @readOnly + */ + _main.default.prototype.pRotationZ = 0; + var startAngleX = 0; + var startAngleY = 0; + var startAngleZ = 0; + var rotateDirectionX = 'clockwise'; + var rotateDirectionY = 'clockwise'; + var rotateDirectionZ = 'clockwise'; + _main.default.prototype.pRotateDirectionX = undefined; + _main.default.prototype.pRotateDirectionY = undefined; + _main.default.prototype.pRotateDirectionZ = undefined; + _main.default.prototype._updatePRotations = function () { + this._setProperty('pRotationX', this.rotationX); + this._setProperty('pRotationY', this.rotationY); + this._setProperty('pRotationZ', this.rotationZ); + }; + /** + * When a device is rotated, the axis that triggers the deviceTurned() + * method is stored in the turnAxis variable. The turnAxis variable is only defined within + * the scope of deviceTurned(). + * @property {String} turnAxis + * @readOnly + * @example + *
        + * + * // Run this example on a mobile device + * // Rotate the device by 90 degrees in the + * // X-axis to change the value. + * + * let value = 0; + * function draw() { + * fill(value); + * rect(25, 25, 50, 50); + * describe(`50-by-50 black rect in center of canvas. + * turns white on mobile when device turns`); + * describe(`50-by-50 black rect in center of canvas. + * turns white on mobile when x-axis turns`); + * } + * function deviceTurned() { + * if (turnAxis === 'X') { + * if (value === 0) { + * value = 255; + * } else if (value === 255) { + * value = 0; + * } + * } + * } + * + *
        + */ + _main.default.prototype.turnAxis = undefined; + var move_threshold = 0.5; + var shake_threshold = 30; + /** + * The setMoveThreshold() function is used to set the movement threshold for + * the deviceMoved() function. The default threshold is set to 0.5. + * + * @method setMoveThreshold + * @param {number} value The threshold value + * @example + *
        + * + * // Run this example on a mobile device + * // You will need to move the device incrementally further + * // the closer the square's color gets to white in order to change the value. + * + * let value = 0; + * let threshold = 0.5; + * function setup() { + * setMoveThreshold(threshold); + * } + * function draw() { + * fill(value); + * rect(25, 25, 50, 50); + * describe(`50-by-50 black rect in center of canvas. + * turns white on mobile when device moves`); + * } + * function deviceMoved() { + * value = value + 5; + * threshold = threshold + 0.1; + * if (value > 255) { + * value = 0; + * threshold = 30; + * } + * setMoveThreshold(threshold); + * } + * + *
        + */ + _main.default.prototype.setMoveThreshold = function (val) { + _main.default._validateParameters('setMoveThreshold', arguments); + move_threshold = val; + }; + /** + * The setShakeThreshold() function is used to set the movement threshold for + * the deviceShaken() function. The default threshold is set to 30. + * + * @method setShakeThreshold + * @param {number} value The threshold value + * @example + *
        + * + * // Run this example on a mobile device + * // You will need to shake the device more firmly + * // the closer the box's fill gets to white in order to change the value. + * + * let value = 0; + * let threshold = 30; + * function setup() { + * setShakeThreshold(threshold); + * } + * function draw() { + * fill(value); + * rect(25, 25, 50, 50); + * describe(`50-by-50 black rect in center of canvas. + * turns white on mobile when device is being shaked`); + * } + * function deviceMoved() { + * value = value + 5; + * threshold = threshold + 5; + * if (value > 255) { + * value = 0; + * threshold = 30; + * } + * setShakeThreshold(threshold); + * } + * + *
        + */ + _main.default.prototype.setShakeThreshold = function (val) { + _main.default._validateParameters('setShakeThreshold', arguments); + shake_threshold = val; + }; + /** + * The deviceMoved() function is called when the device is moved by more than + * the threshold value along X, Y or Z axis. The default threshold is set to 0.5. + * The threshold value can be changed using setMoveThreshold(). + * + * @method deviceMoved + * @example + *
        + * + * // Run this example on a mobile device + * // Move the device around + * // to change the value. + * + * let value = 0; + * function draw() { + * fill(value); + * rect(25, 25, 50, 50); + * describe(`50-by-50 black rect in center of canvas. + * turns white on mobile when device moves`); + * } + * function deviceMoved() { + * value = value + 5; + * if (value > 255) { + * value = 0; + * } + * } + * + *
        + */ + /** + * The deviceTurned() function is called when the device rotates by + * more than 90 degrees continuously. + * + * The axis that triggers the deviceTurned() method is stored in the turnAxis + * variable. The deviceTurned() method can be locked to trigger on any axis: + * X, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'. + * + * @method deviceTurned + * @example + *
        + * + * // Run this example on a mobile device + * // Rotate the device by 90 degrees + * // to change the value. + * + * let value = 0; + * function draw() { + * fill(value); + * rect(25, 25, 50, 50); + * describe(`50-by-50 black rect in center of canvas. + * turns white on mobile when device turns`); + * } + * function deviceTurned() { + * if (value === 0) { + * value = 255; + * } else if (value === 255) { + * value = 0; + * } + * } + * + *
        + *
        + * + * // Run this example on a mobile device + * // Rotate the device by 90 degrees in the + * // X-axis to change the value. + * + * let value = 0; + * function draw() { + * fill(value); + * rect(25, 25, 50, 50); + * describe(`50-by-50 black rect in center of canvas. + * turns white on mobile when x-axis turns`); + * } + * function deviceTurned() { + * if (turnAxis === 'X') { + * if (value === 0) { + * value = 255; + * } else if (value === 255) { + * value = 0; + * } + * } + * } + * + *
        + */ + /** + * The deviceShaken() function is called when the device total acceleration + * changes of accelerationX and accelerationY values is more than + * the threshold value. The default threshold is set to 30. + * The threshold value can be changed using setShakeThreshold(). + * + * @method deviceShaken + * @example + *
        + * + * // Run this example on a mobile device + * // Shake the device to change the value. + * + * let value = 0; + * function draw() { + * fill(value); + * rect(25, 25, 50, 50); + * describe(`50-by-50 black rect in center of canvas. + * turns white on mobile when device shakes`); + * } + * function deviceShaken() { + * value = value + 5; + * if (value > 255) { + * value = 0; + * } + * } + * + *
        + */ + _main.default.prototype._ondeviceorientation = function (e) { + this._updatePRotations(); + // Convert from degrees into current angle mode + this._setProperty('rotationX', this._fromDegrees(e.beta)); + this._setProperty('rotationY', this._fromDegrees(e.gamma)); + this._setProperty('rotationZ', this._fromDegrees(e.alpha)); + this._handleMotion(); + }; + _main.default.prototype._ondevicemotion = function (e) { + this._updatePAccelerations(); + this._setProperty('accelerationX', e.acceleration.x * 2); + this._setProperty('accelerationY', e.acceleration.y * 2); + this._setProperty('accelerationZ', e.acceleration.z * 2); + this._handleMotion(); + }; + _main.default.prototype._handleMotion = function () { + if (window.orientation === 90 || window.orientation === - 90) { + this._setProperty('deviceOrientation', 'landscape'); + } else if (window.orientation === 0) { + this._setProperty('deviceOrientation', 'portrait'); + } else if (window.orientation === undefined) { + this._setProperty('deviceOrientation', 'undefined'); + } + var context = this._isGlobal ? window : this; + if (typeof context.deviceMoved === 'function') { + if (Math.abs(this.accelerationX - this.pAccelerationX) > move_threshold || Math.abs(this.accelerationY - this.pAccelerationY) > move_threshold || Math.abs(this.accelerationZ - this.pAccelerationZ) > move_threshold) { + context.deviceMoved(); + } + } + if (typeof context.deviceTurned === 'function') { + // The angles given by rotationX etc is from range [-180 to 180]. + // The following will convert them to [0 to 360] for ease of calculation + // of cases when the angles wrapped around. + // _startAngleX will be converted back at the end and updated. + // Rotations are converted to degrees and all calculations are done in degrees + var wRX = this._toDegrees(this.rotationX) + 180; + var wPRX = this._toDegrees(this.pRotationX) + 180; + var wSAX = startAngleX + 180; + if (wRX - wPRX > 0 && wRX - wPRX < 270 || wRX - wPRX < - 270) { + rotateDirectionX = 'clockwise'; + } else if (wRX - wPRX < 0 || wRX - wPRX > 270) { + rotateDirectionX = 'counter-clockwise'; + } + if (rotateDirectionX !== this.pRotateDirectionX) { + wSAX = wRX; + } + if (Math.abs(wRX - wSAX) > 90 && Math.abs(wRX - wSAX) < 270) { + wSAX = wRX; + this._setProperty('turnAxis', 'X'); + context.deviceTurned(); + } + this.pRotateDirectionX = rotateDirectionX; + startAngleX = wSAX - 180; + // Y-axis is identical to X-axis except for changing some names. + var wRY = this._toDegrees(this.rotationY) + 180; + var wPRY = this._toDegrees(this.pRotationY) + 180; + var wSAY = startAngleY + 180; + if (wRY - wPRY > 0 && wRY - wPRY < 270 || wRY - wPRY < - 270) { + rotateDirectionY = 'clockwise'; + } else if (wRY - wPRY < 0 || wRY - this.pRotationY > 270) { + rotateDirectionY = 'counter-clockwise'; + } + if (rotateDirectionY !== this.pRotateDirectionY) { + wSAY = wRY; + } + if (Math.abs(wRY - wSAY) > 90 && Math.abs(wRY - wSAY) < 270) { + wSAY = wRY; + this._setProperty('turnAxis', 'Y'); + context.deviceTurned(); + } + this.pRotateDirectionY = rotateDirectionY; + startAngleY = wSAY - 180; + // Z-axis is already in the range 0 to 360 + // so no conversion is needed. + var rotZ = this._toDegrees(this.rotationZ); + var pRotZ = this._toDegrees(this.pRotationZ); + if (rotZ - pRotZ > 0 && rotZ - pRotZ < 270 || rotZ - pRotZ < - 270) { + rotateDirectionZ = 'clockwise'; + } else if (rotZ - pRotZ < 0 || rotZ - pRotZ > 270) { + rotateDirectionZ = 'counter-clockwise'; + } + if (rotateDirectionZ !== this.pRotateDirectionZ) { + startAngleZ = rotZ; + } + if (Math.abs(rotZ - startAngleZ) > 90 && Math.abs(rotZ - startAngleZ) < 270) { + startAngleZ = rotZ; + this._setProperty('turnAxis', 'Z'); + context.deviceTurned(); + } + this.pRotateDirectionZ = rotateDirectionZ; + this._setProperty('turnAxis', undefined); + } + if (typeof context.deviceShaken === 'function') { + var accelerationChangeX; + var accelerationChangeY; + // Add accelerationChangeZ if acceleration change on Z is needed + if (this.pAccelerationX !== null) { + accelerationChangeX = Math.abs(this.accelerationX - this.pAccelerationX); + accelerationChangeY = Math.abs(this.accelerationY - this.pAccelerationY); + } + if (accelerationChangeX + accelerationChangeY > shake_threshold) { + context.deviceShaken(); + } + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303 + } + ], + 321: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Events + * @submodule Keyboard + * @for p5 + * @requires core + */ + /** + * A `Boolean` system variable that's `true` if any key is currently pressed + * and `false` if not. + * + * @property {Boolean} keyIsPressed + * @readOnly + * + * @example + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a white square at its center. The white square turns black when the user presses a key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * if (keyIsPressed === true) { + * fill(0); + * } else { + * fill(255); + * } + * + * // Draw the square. + * square(25, 25, 50); + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a white square at its center. The white square turns black when the user presses a key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * if (keyIsPressed) { + * fill(0); + * } else { + * fill(255); + * } + * + * // Draw the square. + * square(25, 25, 50); + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with the word "false" at its center. The word switches to "true" when the user presses a key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the value of keyIsPressed. + * text(keyIsPressed, 50, 50); + * } + * + *
        + */ + + _main.default.prototype.isKeyPressed = false; + _main.default.prototype.keyIsPressed = false; // khan + /** + * A `String` system variable that contains the value of the last key typed. + * + * The key variable is helpful for checking whether an + * ASCII + * key has been typed. For example, the expression `key === "a"` evaluates to + * `true` if the `a` key was typed and `false` if not. `key` doesn’t update + * for special keys such as `LEFT_ARROW` and `ENTER`. Use keyCode instead for + * special keys. The keyIsDown() function should + * be used to check for multiple different key presses at the same time. + * + * @property {String} key + * @readOnly + * + * @example + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square. The last key pressed is displayed at the center.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the last key pressed. + * text(key, 50, 50); + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let x = 50; + * let y = 50; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe( + * 'A gray square with a black circle at its center. The circle moves when the user presses the keys "w", "a", "s", or "d". It leaves a trail as it moves.' + * ); + * } + * + * function draw() { + * // Update x and y if a key is pressed. + * if (keyIsPressed === true) { + * if (key === 'w') { + * y -= 1; + * } else if (key === 's') { + * y += 1; + * } else if (key === 'a') { + * x -= 1; + * } else if (key === 'd') { + * x += 1; + * } + * } + * + * // Style the circle. + * fill(0); + * + * // Draw the circle at (x, y). + * circle(x, y, 5); + * } + * + *
        + */ + _main.default.prototype.key = ''; + /** + * A `Number` system variable that contains the code of the last key typed. + * + * All keys have a `keyCode`. For example, the `a` key has the `keyCode` 65. + * The `keyCode` variable is helpful for checking whether a special key has + * been typed. For example, the following conditional checks whether the enter + * key has been typed: + * + * + * if (keyCode === 13) { + * // Code to run if the enter key was pressed. + * } + * + * + * The same code can be written more clearly using the system variable `ENTER` + * which has a value of 13: + * + * + * if (keyCode === ENTER) { + * // Code to run if the enter key was pressed. + * } + * + * + * The system variables `BACKSPACE`, `DELETE`, `ENTER`, `RETURN`, `TAB`, + * `ESCAPE`, `SHIFT`, `CONTROL`, `OPTION`, `ALT`, `UP_ARROW`, `DOWN_ARROW`, + * `LEFT_ARROW`, and `RIGHT_ARROW` are all helpful shorthands the key codes of + * special keys. Key codes can be found on websites such as + * keycode.info. + * + * @property {Integer} keyCode + * @readOnly + * + * @example + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square. The last key pressed and its code are displayed at the center.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the last key pressed and its code. + * text(`${key} : ${keyCode}`, 50, 50); + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let x = 50; + * let y = 50; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe( + * 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.' + * ); + * } + * + * function draw() { + * // Update x and y if an arrow key is pressed. + * if (keyIsPressed === true) { + * if (keyCode === UP_ARROW) { + * y -= 1; + * } else if (keyCode === DOWN_ARROW) { + * y += 1; + * } else if (keyCode === LEFT_ARROW) { + * x -= 1; + * } else if (keyCode === RIGHT_ARROW) { + * x += 1; + * } + * } + * + * // Style the circle. + * fill(0); + * + * // Draw the circle at (x, y). + * circle(x, y, 5); + * } + * + *
        + */ + _main.default.prototype.keyCode = 0; + /** + * A function that's called once when any key is pressed. + * + * Declaring the function `keyPressed()` sets a code block to run once + * automatically when the user presses any key: + * + * + * function keyPressed() { + * // Code to run. + * } + * + * + * The key and keyCode + * variables will be updated with the most recently typed value when + * `keyPressed()` is called by p5.js: + * + * + * function keyPressed() { + * if (key === 'c') { + * // Code to run. + * } + * + * if (keyCode === ENTER) { + * // Code to run. + * } + * } + * + * + * The parameter, `event`, is optional. `keyPressed()` is always passed a + * KeyboardEvent + * object with properties that describe the key press event: + * + * + * function keyPressed(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * Browsers may have default behaviors attached to various key events. For + * example, some browsers may jump to the bottom of a web page when the + * `SPACE` key is pressed. To prevent any default behavior for this event, add + * `return false;` to the end of the function. + * + * @method keyPressed + * @param {KeyboardEvent} [event] optional `KeyboardEvent` callback argument. + * + * @example + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square changes color when the user presses a key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Toggle the background color when the user presses a key. + * function keyPressed() { + * if (value === 0) { + * value = 255; + * } else { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a white square at its center. The inner square turns black when the user presses the "b" key. It turns white when the user presses the "a" key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Reassign value when the user presses the 'a' or 'b' key. + * function keyPressed() { + * if (key === 'a') { + * value = 255; + * } else if (key === 'b') { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square turns white when the user presses the left arrow key. It turns black when the user presses the right arrow key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Toggle the background color when the user presses an arrow key. + * function keyPressed() { + * if (keyCode === LEFT_ARROW) { + * value = 255; + * } else if (keyCode === RIGHT_ARROW) { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + */ + _main.default.prototype._onkeydown = function (e) { + if (this._downKeys[e.which]) { + // prevent multiple firings + return; + } + this._setProperty('isKeyPressed', true); + this._setProperty('keyIsPressed', true); + this._setProperty('keyCode', e.which); + this._downKeys[e.which] = true; + this._setProperty('key', e.key || String.fromCharCode(e.which) || e.which); + var context = this._isGlobal ? window : this; + if (typeof context.keyPressed === 'function' && !e.charCode) { + var executeDefault = context.keyPressed(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + }; + /** + * A function that's called once when any key is released. + * + * Declaring the function `keyReleased()` sets a code block to run once + * automatically when the user releases any key: + * + * + * function keyReleased() { + * // Code to run. + * } + * + * + * The key and keyCode + * variables will be updated with the most recently released value when + * `keyReleased()` is called by p5.js: + * + * + * function keyReleased() { + * if (key === 'c') { + * // Code to run. + * } + * + * if (keyCode === ENTER) { + * // Code to run. + * } + * } + * + * + * The parameter, `event`, is optional. `keyReleased()` is always passed a + * KeyboardEvent + * object with properties that describe the key press event: + * + * + * function keyReleased(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * Browsers may have default behaviors attached to various key events. To + * prevent any default behavior for this event, add `return false;` to the end + * of the function. + * + * @method keyReleased + * @param {KeyboardEvent} [event] optional `KeyboardEvent` callback argument. + * + * @example + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square changes color when the user releases a key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Toggle value when the user releases a key. + * function keyReleased() { + * if (value === 0) { + * value = 255; + * } else { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square becomes white when the user releases the "w" key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Set value to 255 the user releases the 'w' key. + * function keyReleased() { + * if (key === 'w') { + * value = 255; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square turns white when the user presses and releases the left arrow key. It turns black when the user presses and releases the right arrow key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Toggle the background color when the user releases an arrow key. + * function keyReleased() { + * if (keyCode === LEFT_ARROW) { + * value = 255; + * } else if (keyCode === RIGHT_ARROW) { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + */ + _main.default.prototype._onkeyup = function (e) { + this._downKeys[e.which] = false; + if (!this._areDownKeys()) { + this._setProperty('isKeyPressed', false); + this._setProperty('keyIsPressed', false); + } + this._setProperty('_lastKeyCodeTyped', null); + this._setProperty('key', e.key || String.fromCharCode(e.which) || e.which); + this._setProperty('keyCode', e.which); + var context = this._isGlobal ? window : this; + if (typeof context.keyReleased === 'function') { + var executeDefault = context.keyReleased(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + }; + /** + * A function that's called once when keys with printable characters are pressed. + * + * Declaring the function `keyTyped()` sets a code block to run once + * automatically when the user presses any key with a printable character such + * as `a` or 1. Modifier keys such as `SHIFT`, `CONTROL`, and the arrow keys + * will be ignored: + * + * + * function keyTyped() { + * // Code to run. + * } + * + * + * The key and keyCode + * variables will be updated with the most recently released value when + * `keyTyped()` is called by p5.js: + * + * + * function keyTyped() { + * // Check for the "c" character using key. + * if (key === 'c') { + * // Code to run. + * } + * + * // Check for "c" using keyCode. + * if (keyCode === 67) { + * // Code to run. + * } + * } + * + * + * The parameter, `event`, is optional. `keyTyped()` is always passed a + * KeyboardEvent + * object with properties that describe the key press event: + * + * + * function keyReleased(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * Note: Use the keyPressed() function and + * keyCode system variable to respond to modifier + * keys such as `ALT`. + * + * Browsers may have default behaviors attached to various key events. To + * prevent any default behavior for this event, add `return false;` to the end + * of the function. + * + * @method keyTyped + * @param {KeyboardEvent} [event] optional `KeyboardEvent` callback argument. + * + * @example + *
        + * + * // Click on the canvas to begin detecting key presses. + * // Note: Pressing special keys such as SPACE have no effect. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a white square at its center. The inner square changes color when the user presses a key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Toggle the square's color when the user types a printable key. + * function keyTyped() { + * if (value === 0) { + * value = 255; + * } else { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a white square at its center. The inner square turns black when the user types the "b" key. It turns white when the user types the "a" key.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Reassign value when the user types the 'a' or 'b' key. + * function keyTyped() { + * if (key === 'a') { + * value = 255; + * } else if (key === 'b') { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + */ + _main.default.prototype._onkeypress = function (e) { + if (e.which === this._lastKeyCodeTyped) { + // prevent multiple firings + return; + } + this._setProperty('_lastKeyCodeTyped', e.which); // track last keyCode + this._setProperty('key', e.key || String.fromCharCode(e.which) || e.which); + var context = this._isGlobal ? window : this; + if (typeof context.keyTyped === 'function') { + var executeDefault = context.keyTyped(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + }; + /** + * The onblur function is called when the user is no longer focused + * on the p5 element. Because the keyup events will not fire if the user is + * not focused on the element we must assume all keys currently down have + * been released. + */ + _main.default.prototype._onblur = function (e) { + this._downKeys = { + }; + }; + /** + * Returns `true` if the key it’s checking is pressed and `false` if not. + * + * `keyIsDown()` is helpful when checking for multiple different key presses. + * For example, `keyIsDown()` can be used to check if both `LEFT_ARROW` and + * `UP_ARROW` are pressed: + * + * + * if (keyIsDown(LEFT_ARROW) && keyIsDown(UP_ARROW)) { + * // Move diagonally. + * } + * + * + * `keyIsDown()` can check for key presses using + * keyCode values, as in `keyIsDown(37)` or + * `keyIsDown(LEFT_ARROW)`. Key codes can be found on websites such as + * keycode.info. + * + * @method keyIsDown + * @param {Number} code key to check. + * @return {Boolean} whether the key is down or not. + * + * @example + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let x = 50; + * let y = 50; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe( + * 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.' + * ); + * } + * + * function draw() { + * // Update x and y if an arrow key is pressed. + * if (keyIsDown(LEFT_ARROW) === true) { + * x -= 1; + * } + * + * if (keyIsDown(RIGHT_ARROW) === true) { + * x += 1; + * } + * + * if (keyIsDown(UP_ARROW) === true) { + * y -= 1; + * } + * + * if (keyIsDown(DOWN_ARROW) === true) { + * y += 1; + * } + * + * // Style the circle. + * fill(0); + * + * // Draw the circle. + * circle(x, y, 5); + * } + * + *
        + * + *
        + * + * // Click on the canvas to begin detecting key presses. + * + * let x = 50; + * let y = 50; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe( + * 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.' + * ); + * } + * + * function draw() { + * // Update x and y if an arrow key is pressed. + * if (keyIsDown(37) === true) { + * x -= 1; + * } + * + * if (keyIsDown(39) === true) { + * x += 1; + * } + * + * if (keyIsDown(38) === true) { + * y -= 1; + * } + * + * if (keyIsDown(40) === true) { + * y += 1; + * } + * + * // Style the circle. + * fill(0); + * + * // Draw the circle. + * circle(x, y, 5); + * } + * + *
        + */ + _main.default.prototype.keyIsDown = function (code) { + _main.default._validateParameters('keyIsDown', arguments); + return this._downKeys[code] || false; + }; + /** + * The _areDownKeys function returns a boolean true if any keys pressed + * and a false if no keys are currently pressed. + + * Helps avoid instances where multiple keys are pressed simultaneously and + * releasing a single key will then switch the + * keyIsPressed property to true. + * @private +**/ + _main.default.prototype._areDownKeys = function () { + for (var key in this._downKeys) { + if (this._downKeys.hasOwnProperty(key) && this._downKeys[key] === true) { + return true; + } + } + return false; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303 + } + ], + 322: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Events + * @submodule Mouse + * @for p5 + * @requires core + * @requires constants + */ + /** + * A `Number` system variable that tracks the mouse's horizontal movement. + * + * `movedX` tracks how many pixels the mouse moves left or right between + * frames. `movedX` will have a negative value if the mouse moves left between + * frames and a positive value if it moves right. `movedX` can be calculated + * as `mouseX - pmouseX`. + * + * Note: `movedX` continues updating even when + * requestPointerLock() is active. + * + * @property {Number} movedX + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square. The text ">>" appears when the user moves the mouse to the right. The text "<<" appears when the user moves the mouse to the left.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display >> when movedX is positive and + * // << when it's negative. + * if (movedX > 0) { + * text('>>', 50, 50); + * } else if (movedX < 0) { + * text('<<', 50, 50); + * } + * } + * + *
        + */ + + _main.default.prototype.movedX = 0; + /** + * A `Number` system variable that tracks the mouse's vertical movement. + * + * `movedY` tracks how many pixels the mouse moves up or down between + * frames. `movedY` will have a negative value if the mouse moves up between + * frames and a positive value if it moves down. `movedY` can be calculated + * as `mouseY - pmouseY`. + * + * Note: `movedY` continues updating even when + * requestPointerLock() is active. + * + * @property {Number} movedY + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square. The text "▲" appears when the user moves the mouse upward. The text "▼" appears when the user moves the mouse downward.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display ▼ when movedY is positive and + * // ▲ when it's negative. + * if (movedY > 0) { + * text('▼', 50, 50); + * } else if (movedY < 0) { + * text('▲', 50, 50); + * } + * } + * + *
        + */ + _main.default.prototype.movedY = 0; + /* + * This is a flag which is false until the first time + * we receive a mouse event. The pmouseX and pmouseY + * values will match the mouseX and mouseY values until + * this interaction takes place. + */ + _main.default.prototype._hasMouseInteracted = false; + /** + * A `Number` system variable that tracks the mouse's horizontal position. + * + * In 2D mode, `mouseX` keeps track of the mouse's position relative to the + * top-left corner of the canvas. For example, if the mouse is 50 pixels from + * the left edge of the canvas, then `mouseX` will be 50. + * + * In WebGL mode, `mouseX` keeps track of the mouse's position relative to the + * center of the canvas. For example, if the mouse is 50 pixels to the right + * of the canvas' center, then `mouseX` will be 50. + * + * If touch is used instead of the mouse, then `mouseX` will hold the + * x-coordinate of the most recent touch point. + * + * @property {Number} mouseX + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe("A vertical black line moves left and right following the mouse's x-position."); + * } + * + * function draw() { + * background(200); + * + * // Draw a vertical line that follows the mouse's x-coordinate. + * line(mouseX, 0, mouseX, 100); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe("A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse."); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the mouse's coordinates. + * text(`x: ${mouseX} y: ${mouseY}`, 50, 50); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe("A vertical black line moves left and right following the mouse's x-position."); + * } + * + * function draw() { + * background(200); + * + * // Adjust coordinates for WebGL mode. + * // The origin (0, 0) is at the center of the canvas. + * let mx = mouseX - 50; + * + * // Draw the line. + * line(mx, -50, mx, 50); + * } + * + *
        + * + *
        + * + * let font; + * + * // Load a font for WebGL mode. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * "A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse." + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the mouse's coordinates. + * text(`x: ${mouseX} y: ${mouseY}`, 0, 0); + * } + * + *
        + */ + _main.default.prototype.mouseX = 0; + /** + * A `Number` system variable that tracks the mouse's vertical position. + * + * In 2D mode, `mouseY` keeps track of the mouse's position relative to the + * top-left corner of the canvas. For example, if the mouse is 50 pixels from + * the top edge of the canvas, then `mouseY` will be 50. + * + * In WebGL mode, `mouseY` keeps track of the mouse's position relative to the + * center of the canvas. For example, if the mouse is 50 pixels below the + * canvas' center, then `mouseY` will be 50. + * + * If touch is used instead of the mouse, then `mouseY` will hold the + * y-coordinate of the most recent touch point. + * + * @property {Number} mouseY + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe("A horizontal black line moves up and down following the mouse's y-position."); + * } + * + * function draw() { + * background(200); + * + * // Draw a horizontal line that follows the mouse's y-coordinate. + * line(0, mouseY, 0, mouseY); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe("A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse."); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the mouse's coordinates. + * text(`x: ${mouseX} y: ${mouseY}`, 50, 50); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe("A horizontal black line moves up and down following the mouse's y-position."); + * } + * + * function draw() { + * background(200); + * + * // Adjust coordinates for WebGL mode. + * // The origin (0, 0) is at the center of the canvas. + * let my = mouseY - 50; + * + * // Draw the line. + * line(-50, my, 50, my); + * } + * + *
        + * + *
        + * + * let font; + * + * // Load a font for WebGL mode. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * "A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse." + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the mouse's coordinates. + * text(`x: ${mouseX} y: ${mouseY}`, 0, 0); + * } + * + *
        + */ + _main.default.prototype.mouseY = 0; + /** + * A `Number` system variable that tracks the mouse's previous horizontal + * position. + * + * In 2D mode, `pmouseX` keeps track of the mouse's position relative to the + * top-left corner of the canvas. Its value is + * mouseX from the previous frame. For example, if + * the mouse was 50 pixels from the left edge of the canvas during the last + * frame, then `pmouseX` will be 50. + * + * In WebGL mode, `pmouseX` keeps track of the mouse's position relative to the + * center of the canvas. For example, if the mouse was 50 pixels to the right + * of the canvas' center during the last frame, then `pmouseX` will be 50. + * + * If touch is used instead of the mouse, then `pmouseX` will hold the + * x-coordinate of the last touch point. + * + * Note: `pmouseX` is reset to the current mouseX + * value at the start of each touch event. + * + * @property {Number} pmouseX + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(10); + * + * describe('A line follows the mouse as it moves. The line grows longer with faster movements.'); + * } + * + * function draw() { + * background(200); + * + * line(pmouseX, pmouseY, mouseX, mouseY); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A line follows the mouse as it moves. The line grows longer with faster movements.'); + * } + * + * function draw() { + * background(200); + * + * // Adjust coordinates for WebGL mode. + * // The origin (0, 0) is at the center of the canvas. + * let pmx = pmouseX - 50; + * let pmy = pmouseY - 50; + * let mx = mouseX - 50; + * let my = mouseY - 50; + * + * // Draw the line. + * line(pmx, pmy, mx, my); + * } + * + *
        + */ + _main.default.prototype.pmouseX = 0; + /** + * A `Number` system variable that tracks the mouse's previous vertical + * position. + * + * In 2D mode, `pmouseY` keeps track of the mouse's position relative to the + * top-left corner of the canvas. Its value is + * mouseY from the previous frame. For example, if + * the mouse was 50 pixels from the top edge of the canvas during the last + * frame, then `pmouseY` will be 50. + * + * In WebGL mode, `pmouseY` keeps track of the mouse's position relative to the + * center of the canvas. For example, if the mouse was 50 pixels below the + * canvas' center during the last frame, then `pmouseY` will be 50. + * + * If touch is used instead of the mouse, then `pmouseY` will hold the + * y-coordinate of the last touch point. + * + * Note: `pmouseY` is reset to the current mouseY + * value at the start of each touch event. + * + * @property {Number} pmouseY + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(10); + * + * describe('A line follows the mouse as it moves. The line grows longer with faster movements.'); + * } + * + * function draw() { + * background(200); + * + * line(pmouseX, pmouseY, mouseX, mouseY); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A line follows the mouse as it moves. The line grows longer with faster movements.'); + * } + * + * function draw() { + * background(200); + * + * // Adjust coordinates for WebGL mode. + * // The origin (0, 0) is at the center of the canvas. + * let pmx = pmouseX - 50; + * let pmy = pmouseY - 50; + * let mx = mouseX - 50; + * let my = mouseY - 50; + * + * // Draw the line. + * line(pmx, pmy, mx, my); + * } + * + *
        + */ + _main.default.prototype.pmouseY = 0; + /** + * A `Number` variable that tracks the mouse's horizontal position within the + * browser. + * + * `winMouseX` keeps track of the mouse's position relative to the top-left + * corner of the browser window. For example, if the mouse is 50 pixels from + * the left edge of the browser, then `winMouseX` will be 50. + * + * On a touchscreen device, `winMouseX` will hold the x-coordinate of the most + * recent touch point. + * + * Note: Use mouseX to track the mouse’s + * x-coordinate within the canvas. + * + * @property {Number} winMouseX + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe("A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse."); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the mouse's coordinates within the browser window. + * text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50); + * } + * + *
        + */ + _main.default.prototype.winMouseX = 0; + /** + * A `Number` variable that tracks the mouse's vertical position within the + * browser. + * + * `winMouseY` keeps track of the mouse's position relative to the top-left + * corner of the browser window. For example, if the mouse is 50 pixels from + * the top edge of the browser, then `winMouseY` will be 50. + * + * On a touchscreen device, `winMouseY` will hold the y-coordinate of the most + * recent touch point. + * + * Note: Use mouseY to track the mouse’s + * y-coordinate within the canvas. + * + * @property {Number} winMouseY + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe("A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse."); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the mouse's coordinates within the browser window. + * text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50); + * } + * + *
        + */ + _main.default.prototype.winMouseY = 0; + /** + * A `Number` variable that tracks the mouse's previous horizontal position + * within the browser. + * + * `pwinMouseX` keeps track of the mouse's position relative to the top-left + * corner of the browser window. Its value is + * winMouseX from the previous frame. For + * example, if the mouse was 50 pixels from + * the left edge of the browser during the last frame, then `pwinMouseX` will + * be 50. + * + * On a touchscreen device, `pwinMouseX` will hold the x-coordinate of the most + * recent touch point. `pwinMouseX` is reset to the current + * winMouseX value at the start of each touch + * event. + * + * Note: Use pmouseX to track the mouse’s previous + * x-coordinate within the canvas. + * + * @property {Number} pwinMouseX + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(10); + * + * describe('A gray square. A white circle at its center grows larger when the mouse moves horizontally.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the circle's diameter. + * let d = winMouseX - pwinMouseX; + * + * // Draw the circle. + * circle(50, 50, d); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create the canvas and set its position. + * let cnv = createCanvas(100, 100); + * cnv.position(20, 20); + * + * describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display pwinMouseX. + * text(pwinMouseX, 50, 50); + * } + * + *
        + */ + _main.default.prototype.pwinMouseX = 0; + /** + * A `Number` variable that tracks the mouse's previous vertical position + * within the browser. + * + * `pwinMouseY` keeps track of the mouse's position relative to the top-left + * corner of the browser window. Its value is + * winMouseY from the previous frame. For + * example, if the mouse was 50 pixels from + * the top edge of the browser during the last frame, then `pwinMouseY` will + * be 50. + * + * On a touchscreen device, `pwinMouseY` will hold the y-coordinate of the most + * recent touch point. `pwinMouseY` is reset to the current + * winMouseY value at the start of each touch + * event. + * + * Note: Use pmouseY to track the mouse’s previous + * y-coordinate within the canvas. + * + * @property {Number} pwinMouseY + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(10); + * + * describe('A gray square. A white circle at its center grows larger when the mouse moves vertically.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the circle's diameter. + * let d = winMouseY - pwinMouseY; + * + * // Draw the circle. + * circle(50, 50, d); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create the canvas and set its position. + * let cnv = createCanvas(100, 100); + * cnv.position(20, 20); + * + * describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.'); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display pwinMouseY. + * text(pwinMouseY, 50, 50); + * } + * + *
        + */ + _main.default.prototype.pwinMouseY = 0; + /** + * A String system variable that contains the value of the last mouse button + * pressed. + * + * The `mouseButton` variable is either `LEFT`, `RIGHT`, or `CENTER`, + * depending on which button was pressed last. + * + * Note: Different browsers may track `mouseButton` differently. See + * MDN + * for more information. + * + * @property {Constant} mouseButton + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with black text at its center. The text changes from 0 to either "left" or "right" when the user clicks a mouse button.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the mouse button. + * text(mouseButton, 50, 50); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * "A gray square. Different shapes appear at its center depending on the mouse button that's clicked." + * ); + * } + * + * function draw() { + * background(200); + * + * if (mouseIsPressed === true) { + * if (mouseButton === LEFT) { + * circle(50, 50, 50); + * } + * if (mouseButton === RIGHT) { + * square(25, 25, 50); + * } + * if (mouseButton === CENTER) { + * triangle(23, 75, 50, 20, 78, 75); + * } + * } + * } + * + *
        + */ + _main.default.prototype.mouseButton = 0; + /** + * A `Boolean` system variable that's `true` if the mouse is pressed and + * `false` if not. + * + * @property {Boolean} mouseIsPressed + * @readOnly + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with the word "false" at its center. The word changes to "true" when the user presses a mouse button.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the mouseIsPressed variable. + * text(mouseIsPressed, 25, 50); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a white square at its center. The inner square turns black when the user presses the mouse.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * if (mouseIsPressed === true) { + * fill(0); + * } else { + * fill(255); + * } + * + * // Draw the square. + * square(25, 25, 50); + * } + * + *
        + */ + _main.default.prototype.mouseIsPressed = false; + _main.default.prototype._updateNextMouseCoords = function (e) { + if (this._curElement !== null && (!e.touches || e.touches.length > 0)) { + var mousePos = getMousePos(this._curElement.elt, this.width, this.height, e); + this._setProperty('movedX', e.movementX); + this._setProperty('movedY', e.movementY); + this._setProperty('mouseX', mousePos.x); + this._setProperty('mouseY', mousePos.y); + this._setProperty('winMouseX', mousePos.winX); + this._setProperty('winMouseY', mousePos.winY); + } + if (!this._hasMouseInteracted) { + // For first draw, make previous and next equal + this._updateMouseCoords(); + this._setProperty('_hasMouseInteracted', true); + } + }; + _main.default.prototype._updateMouseCoords = function () { + this._setProperty('pmouseX', this.mouseX); + this._setProperty('pmouseY', this.mouseY); + this._setProperty('pwinMouseX', this.winMouseX); + this._setProperty('pwinMouseY', this.winMouseY); + this._setProperty('_pmouseWheelDeltaY', this._mouseWheelDeltaY); + }; + function getMousePos(canvas, w, h, evt) { + if (evt && !evt.clientX) { + // use touches if touch and not mouse + if (evt.touches) { + evt = evt.touches[0]; + } else if (evt.changedTouches) { + evt = evt.changedTouches[0]; + } + } + var rect = canvas.getBoundingClientRect(); + var sx = canvas.scrollWidth / w || 1; + var sy = canvas.scrollHeight / h || 1; + return { + x: (evt.clientX - rect.left) / sx, + y: (evt.clientY - rect.top) / sy, + winX: evt.clientX, + winY: evt.clientY, + id: evt.identifier + }; + } + _main.default.prototype._setMouseButton = function (e) { + if (e.button === 1) { + this._setProperty('mouseButton', constants.CENTER); + } else if (e.button === 2) { + this._setProperty('mouseButton', constants.RIGHT); + } else { + this._setProperty('mouseButton', constants.LEFT); + } + }; + /** + * A function that's called when the mouse moves. + * + * Declaring the function `mouseMoved()` sets a code block to run + * automatically when the user moves the mouse without clicking any mouse + * buttons: + * + * + * function mouseMoved() { + * // Code to run. + * } + * + * + * The mouse system variables, such as mouseX and + * mouseY, will be updated with their most recent + * value when `mouseMoved()` is called by p5.js: + * + * + * function mouseMoved() { + * if (mouseX < 50) { + * // Code to run if the mouse is on the left. + * } + * + * if (mouseY > 50) { + * // Code to run if the mouse is near the bottom. + * } + * } + * + * + * The parameter, `event`, is optional. `mouseMoved()` is always passed a + * MouseEvent + * object with properties that describe the mouse move event: + * + * + * function mouseMoved(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * Browsers may have default behaviors attached to various mouse events. For + * example, some browsers highlight text when the user moves the mouse while + * pressing a mouse button. To prevent any default behavior for this event, + * add `return false;` to the end of the function. + * + * @method mouseMoved + * @param {MouseEvent} [event] optional `MouseEvent` argument. + * + * @example + *
        + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square becomes lighter as the mouse moves.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * function mouseMoved() { + * // Update the grayscale value. + * value += 5; + * + * // Reset the grayscale value. + * if (value > 255) { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + */ + /** + * A function that's called when the mouse moves while a button is pressed. + * + * Declaring the function `mouseDragged()` sets a code block to run + * automatically when the user clicks and drags the mouse: + * + * + * function mouseDragged() { + * // Code to run. + * } + * + * + * The mouse system variables, such as mouseX and + * mouseY, will be updated with their most recent + * value when `mouseDragged()` is called by p5.js: + * + * + * function mouseDragged() { + * if (mouseX < 50) { + * // Code to run if the mouse is on the left. + * } + * + * if (mouseY > 50) { + * // Code to run if the mouse is near the bottom. + * } + * } + * + * + * The parameter, `event`, is optional. `mouseDragged()` is always passed a + * MouseEvent + * object with properties that describe the mouse drag event: + * + * + * function mouseDragged(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * On touchscreen devices, `mouseDragged()` will run when a user moves a touch + * point if touchMoved() isn’t declared. If + * touchMoved() is declared, then + * touchMoved() will run when a user moves a + * touch point and `mouseDragged()` won’t. + * + * Browsers may have default behaviors attached to various mouse events. For + * example, some browsers highlight text when the user moves the mouse while + * pressing a mouse button. To prevent any default behavior for this event, + * add `return false;` to the end of the function. + * + * @method mouseDragged + * @param {MouseEvent} [event] optional `MouseEvent` argument. + * + * @example + *
        + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square becomes lighter as the user drags the mouse.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * function mouseDragged() { + * // Update the grayscale value. + * value += 5; + * + * // Reset the grayscale value. + * if (value > 255) { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + */ + _main.default.prototype._onmousemove = function (e) { + var context = this._isGlobal ? window : this; + var executeDefault; + this._updateNextMouseCoords(e); + if (!this.mouseIsPressed) { + if (typeof context.mouseMoved === 'function') { + executeDefault = context.mouseMoved(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + } else { + if (typeof context.mouseDragged === 'function') { + executeDefault = context.mouseDragged(e); + if (executeDefault === false) { + e.preventDefault(); + } + } else if (typeof context.touchMoved === 'function') { + executeDefault = context.touchMoved(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + } + }; + /** + * A function that's called once when a mouse button is pressed. + * + * Declaring the function `mousePressed()` sets a code block to run + * automatically when the user presses a mouse button: + * + * + * function mousePressed() { + * // Code to run. + * } + * + * + * The mouse system variables, such as mouseX and + * mouseY, will be updated with their most recent + * value when `mousePressed()` is called by p5.js: + * + * + * function mousePressed() { + * if (mouseX < 50) { + * // Code to run if the mouse is on the left. + * } + * + * if (mouseY > 50) { + * // Code to run if the mouse is near the bottom. + * } + * } + * + * + * The parameter, `event`, is optional. `mousePressed()` is always passed a + * MouseEvent + * object with properties that describe the mouse press event: + * + * + * function mousePressed(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * On touchscreen devices, `mousePressed()` will run when a user’s touch + * begins if touchStarted() isn’t declared. If + * touchStarted() is declared, then + * touchStarted() will run when a user’s touch + * begins and `mousePressed()` won’t. + * + * Browsers may have default behaviors attached to various mouse events. For + * example, some browsers highlight text when the user moves the mouse while + * pressing a mouse button. To prevent any default behavior for this event, + * add `return false;` to the end of the function. + * + * Note: `mousePressed()`, mouseReleased(), + * and mouseClicked() are all related. + * `mousePressed()` runs as soon as the user clicks the mouse. + * mouseReleased() runs as soon as the user + * releases the mouse click. mouseClicked() + * runs immediately after mouseReleased(). + * + * @method mousePressed + * @param {MouseEvent} [event] optional `MouseEvent` argument. + * + * @example + *
        + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square becomes lighter when the user presses a mouse button.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * function mousePressed() { + * // Update the grayscale value. + * value += 5; + * + * // Reset the grayscale value. + * if (value > 255) { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Style the circle. + * fill('orange'); + * stroke('royalblue'); + * strokeWeight(10); + * + * describe( + * 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.' + * ); + * } + * + * function draw() { + * background(220); + * + * // Draw the circle. + * circle(50, 50, 20); + * } + * + * // Set the stroke color and weight as soon as the user clicks. + * function mousePressed() { + * stroke('deeppink'); + * strokeWeight(3); + * } + * + * // Set the stroke and fill colors as soon as the user releases + * // the mouse. + * function mouseReleased() { + * stroke('royalblue'); + * + * // This is never visible because fill() is called + * // in mouseClicked() which runs immediately after + * // mouseReleased(); + * fill('limegreen'); + * } + * + * // Set the fill color and stroke weight after + * // mousePressed() and mouseReleased() are called. + * function mouseClicked() { + * fill('orange'); + * strokeWeight(10); + * } + * + *
        + */ + _main.default.prototype._onmousedown = function (e) { + var context = this._isGlobal ? window : this; + var executeDefault; + this._setProperty('mouseIsPressed', true); + this._setMouseButton(e); + this._updateNextMouseCoords(e); + // _ontouchstart triggers first and sets this.touchstart + if (this.touchstart) { + return; + } + if (typeof context.mousePressed === 'function') { + executeDefault = context.mousePressed(e); + if (executeDefault === false) { + e.preventDefault(); + } + } else if (typeof context.touchStarted === 'function') { + executeDefault = context.touchStarted(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + this.touchstart = false; + }; + /** + * A function that's called once when a mouse button is released. + * + * Declaring the function `mouseReleased()` sets a code block to run + * automatically when the user releases a mouse button after having pressed + * it: + * + * + * function mouseReleased() { + * // Code to run. + * } + * + * + * The mouse system variables, such as mouseX and + * mouseY, will be updated with their most recent + * value when `mouseReleased()` is called by p5.js: + * + * + * function mouseReleased() { + * if (mouseX < 50) { + * // Code to run if the mouse is on the left. + * } + * + * if (mouseY > 50) { + * // Code to run if the mouse is near the bottom. + * } + * } + * + * + * The parameter, `event`, is optional. `mouseReleased()` is always passed a + * MouseEvent + * object with properties that describe the mouse release event: + * + * + * function mouseReleased(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * On touchscreen devices, `mouseReleased()` will run when a user’s touch + * ends if touchEnded() isn’t declared. If + * touchEnded() is declared, then + * touchEnded() will run when a user’s touch + * ends and `mouseReleased()` won’t. + * + * Browsers may have default behaviors attached to various mouse events. For + * example, some browsers highlight text when the user moves the mouse while + * pressing a mouse button. To prevent any default behavior for this event, + * add `return false;` to the end of the function. + * + * Note: mousePressed(), `mouseReleased()`, + * and mouseClicked() are all related. + * mousePressed() runs as soon as the user + * clicks the mouse. `mouseReleased()` runs as soon as the user releases the + * mouse click. mouseClicked() runs + * immediately after `mouseReleased()`. + * + * @method mouseReleased + * @param {MouseEvent} [event] optional `MouseEvent` argument. + * + * @example + *
        + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square becomes lighter when the user presses and releases a mouse button.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * function mouseReleased() { + * // Update the grayscale value. + * value += 5; + * + * // Reset the grayscale value. + * if (value > 255) { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Style the circle. + * fill('orange'); + * stroke('royalblue'); + * strokeWeight(10); + * + * describe( + * 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.' + * ); + * } + * + * function draw() { + * background(220); + * + * // Draw the circle. + * circle(50, 50, 20); + * } + * + * // Set the stroke color and weight as soon as the user clicks. + * function mousePressed() { + * stroke('deeppink'); + * strokeWeight(3); + * } + * + * // Set the stroke and fill colors as soon as the user releases + * // the mouse. + * function mouseReleased() { + * stroke('royalblue'); + * + * // This is never visible because fill() is called + * // in mouseClicked() which runs immediately after + * // mouseReleased(); + * fill('limegreen'); + * } + * + * // Set the fill color and stroke weight after + * // mousePressed() and mouseReleased() are called. + * function mouseClicked() { + * fill('orange'); + * strokeWeight(10); + * } + * + *
        + */ + _main.default.prototype._onmouseup = function (e) { + var context = this._isGlobal ? window : this; + var executeDefault; + this._setProperty('mouseIsPressed', false); + // _ontouchend triggers first and sets this.touchend + if (this.touchend) { + return; + } + if (typeof context.mouseReleased === 'function') { + executeDefault = context.mouseReleased(e); + if (executeDefault === false) { + e.preventDefault(); + } + } else if (typeof context.touchEnded === 'function') { + executeDefault = context.touchEnded(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + this.touchend = false; + }; + _main.default.prototype._ondragend = _main.default.prototype._onmouseup; + _main.default.prototype._ondragover = _main.default.prototype._onmousemove; + /** + * A function that's called once after a mouse button is pressed and released. + * + * Declaring the function `mouseClicked()` sets a code block to run + * automatically when the user releases a mouse button after having pressed + * it: + * + * + * function mouseClicked() { + * // Code to run. + * } + * + * + * The mouse system variables, such as mouseX and + * mouseY, will be updated with their most recent + * value when `mouseClicked()` is called by p5.js: + * + * + * function mouseClicked() { + * if (mouseX < 50) { + * // Code to run if the mouse is on the left. + * } + * + * if (mouseY > 50) { + * // Code to run if the mouse is near the bottom. + * } + * } + * + * + * The parameter, `event`, is optional. `mouseClicked()` is always passed a + * MouseEvent + * object with properties that describe the mouse click event: + * + * + * function mouseClicked(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * On touchscreen devices, `mouseClicked()` will run when a user’s touch + * ends if touchEnded() isn’t declared. If + * touchEnded() is declared, then + * touchEnded() will run when a user’s touch + * ends and `mouseClicked()` won’t. + * + * Browsers may have default behaviors attached to various mouse events. For + * example, some browsers highlight text when the user moves the mouse while + * pressing a mouse button. To prevent any default behavior for this event, + * add `return false;` to the end of the function. + * + * Note: mousePressed(), + * mouseReleased(), + * and `mouseClicked()` are all related. + * mousePressed() runs as soon as the user + * clicks the mouse. mouseReleased() runs as + * soon as the user releases the mouse click. `mouseClicked()` runs + * immediately after mouseReleased(). + * + * @method mouseClicked + * @param {MouseEvent} [event] optional `MouseEvent` argument. + * + * @example + *
        + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square changes color when the user presses and releases a mouse button.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Toggle the square's color when the user clicks. + * function mouseClicked() { + * if (value === 0) { + * value = 255; + * } else { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Style the circle. + * fill('orange'); + * stroke('royalblue'); + * strokeWeight(10); + * + * describe( + * 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.' + * ); + * } + * + * function draw() { + * background(220); + * + * // Draw the circle. + * circle(50, 50, 20); + * } + * + * // Set the stroke color and weight as soon as the user clicks. + * function mousePressed() { + * stroke('deeppink'); + * strokeWeight(3); + * } + * + * // Set the stroke and fill colors as soon as the user releases + * // the mouse. + * function mouseReleased() { + * stroke('royalblue'); + * + * // This is never visible because fill() is called + * // in mouseClicked() which runs immediately after + * // mouseReleased(); + * fill('limegreen'); + * } + * + * // Set the fill color and stroke weight after + * // mousePressed() and mouseReleased() are called. + * function mouseClicked() { + * fill('orange'); + * strokeWeight(10); + * } + * + *
        + */ + _main.default.prototype._onclick = function (e) { + var context = this._isGlobal ? window : this; + if (typeof context.mouseClicked === 'function') { + var executeDefault = context.mouseClicked(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + }; + /** + * A function that's called once when a mouse button is clicked twice quickly. + * + * Declaring the function `doubleClicked()` sets a code block to run + * automatically when the user presses and releases the mouse button twice + * quickly: + * + * + * function doubleClicked() { + * // Code to run. + * } + * + * + * The mouse system variables, such as mouseX and + * mouseY, will be updated with their most recent + * value when `doubleClicked()` is called by p5.js: + * + * + * function doubleClicked() { + * if (mouseX < 50) { + * // Code to run if the mouse is on the left. + * } + * + * if (mouseY > 50) { + * // Code to run if the mouse is near the bottom. + * } + * } + * + * + * The parameter, `event`, is optional. `doubleClicked()` is always passed a + * MouseEvent + * object with properties that describe the double-click event: + * + * + * function doubleClicked(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * On touchscreen devices, code placed in `doubleClicked()` will run after two + * touches that occur within a short time. + * + * Browsers may have default behaviors attached to various mouse events. For + * example, some browsers highlight text when the user moves the mouse while + * pressing a mouse button. To prevent any default behavior for this event, + * add `return false;` to the end of the function. + * + * @method doubleClicked + * @param {MouseEvent} [event] optional `MouseEvent` argument. + * + * @example + *
        + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square changes color when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Toggle the square's color when the user double-clicks. + * function doubleClicked() { + * if (value === 0) { + * value = 255; + * } else { + * value = 0; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black circle at its center. When the user double-clicks on the circle, it changes color to white.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the circle. + * fill(value); + * + * // Draw the circle. + * circle(50, 50, 80); + * } + * + * // Reassign value to 255 when the user double-clicks on the circle. + * function doubleClicked() { + * if (dist(50, 50, mouseX, mouseY) < 40) { + * value = 255; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + */ + _main.default.prototype._ondblclick = function (e) { + var context = this._isGlobal ? window : this; + if (typeof context.doubleClicked === 'function') { + var executeDefault = context.doubleClicked(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + }; + /** + * For use with WebGL orbitControl. + * @property {Number} _mouseWheelDeltaY + * @readOnly + * @private + */ + _main.default.prototype._mouseWheelDeltaY = 0; + /** + * For use with WebGL orbitControl. + * @property {Number} _pmouseWheelDeltaY + * @readOnly + * @private + */ + _main.default.prototype._pmouseWheelDeltaY = 0; + /** + * A function that's called once when the mouse wheel moves. + * + * Declaring the function `mouseWheel()` sets a code block to run + * automatically when the user scrolls with the mouse wheel: + * + * + * function mouseWheel() { + * // Code to run. + * } + * + * + * The mouse system variables, such as mouseX and + * mouseY, will be updated with their most recent + * value when `mouseWheel()` is called by p5.js: + * + * + * function mouseWheel() { + * if (mouseX < 50) { + * // Code to run if the mouse is on the left. + * } + * + * if (mouseY > 50) { + * // Code to run if the mouse is near the bottom. + * } + * } + * + * + * The parameter, `event`, is optional. `mouseWheel()` is always passed a + * MouseEvent + * object with properties that describe the mouse scroll event: + * + * + * function mouseWheel(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * The `event` object has many properties including `delta`, a `Number` + * containing the distance that the user scrolled. For example, `event.delta` + * might have the value 5 when the user scrolls up. `event.delta` is positive + * if the user scrolls up and negative if they scroll down. The signs are + * opposite on macOS with "natural" scrolling enabled. + * + * Browsers may have default behaviors attached to various mouse events. For + * example, some browsers highlight text when the user moves the mouse while + * pressing a mouse button. To prevent any default behavior for this event, + * add `return false;` to the end of the function. + * + * Note: On Safari, `mouseWheel()` may only work as expected if + * `return false;` is added at the end of the function. + * + * @method mouseWheel + * @param {WheelEvent} [event] optional `WheelEvent` argument. + * + * @example + *
        + * + * let circleSize = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square. A white circle at its center grows up when the user scrolls the mouse wheel.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw the circle + * circle(circleSize, 50, 50); + * } + * + * // Increment circleSize when the user scrolls the mouse wheel. + * function mouseWheel() { + * circleSize += 1; + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + * + *
        + * + * let direction = ''; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square. An arrow at its center points up when the user scrolls up. The arrow points down when the user scrolls down.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Draw an arrow that points where + * // the mouse last scrolled. + * text(direction, 50, 50); + * } + * + * // Change direction when the user scrolls the mouse wheel. + * function mouseWheel(event) { + * if (event.delta > 0) { + * direction = '▲'; + * } else { + * direction = '▼'; + * } + * // Uncomment to prevent any default behavior. + * // return false; + * } + * + *
        + */ + _main.default.prototype._onwheel = function (e) { + var context = this._isGlobal ? window : this; + this._setProperty('_mouseWheelDeltaY', e.deltaY); + if (typeof context.mouseWheel === 'function') { + e.delta = e.deltaY; + var executeDefault = context.mouseWheel(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + }; + /** + * Locks the mouse pointer to its current position and makes it invisible. + * + * `requestPointerLock()` allows the mouse to move forever without leaving the + * screen. Calling `requestPointerLock()` locks the values of + * mouseX, mouseY, + * pmouseX, and pmouseY. + * movedX and movedY + * continue updating and can be used to get the distance the mouse moved since + * the last frame was drawn. Calling + * exitPointerLock() resumes updating the + * mouse system variables. + * + * Note: Most browsers require an input, such as a click, before calling + * `requestPointerLock()`. It’s recommended to call `requestPointerLock()` in + * an event function such as doubleClicked(). + * + * @method requestPointerLock + * + * @example + *
        + * + * let score = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with the text "Score: X" at its center. The score increases when the user moves the mouse upward. It decreases when the user moves the mouse downward.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Update the score. + * score -= movedY; + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the score. + * text(`Score: ${score}`, 50, 50); + * } + * + * // Lock the pointer when the user double-clicks. + * function doubleClicked() { + * requestPointerLock(); + * } + * + *
        + */ + _main.default.prototype.requestPointerLock = function () { + // pointer lock object forking for cross browser + var canvas = this._curElement.elt; + canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock; + if (!canvas.requestPointerLock) { + console.log('requestPointerLock is not implemented in this browser'); + return false; + } + canvas.requestPointerLock(); + return true; + }; + /** + * Exits a pointer lock started with + * requestPointerLock. + * + * Calling `requestPointerLock()` locks the values of + * mouseX, mouseY, + * pmouseX, and pmouseY. + * Calling `exitPointerLock()` resumes updating the mouse system variables. + * + * Note: Most browsers require an input, such as a click, before calling + * `requestPointerLock()`. It’s recommended to call `requestPointerLock()` in + * an event function such as doubleClicked(). + * + * @method exitPointerLock + * + * @example + *
        + * + * let isLocked = false; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a word at its center. The word changes between "Unlocked" and "Locked" when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Tell the user whether the pointer is locked. + * if (isLocked === true) { + * text('Locked', 50, 50); + * } else { + * text('Unlocked', 50, 50); + * } + * } + * + * // Toggle the pointer lock when the user double-clicks. + * function doubleClicked() { + * if (isLocked === true) { + * exitPointerLock(); + * isLocked = false; + * } else { + * requestPointerLock(); + * isLocked = true; + * } + * } + * + *
        + */ + _main.default.prototype.exitPointerLock = function () { + document.exitPointerLock(); + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 323: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Events + * @submodule Touch + * @for p5 + * @requires core + */ + /** + * An `Array` of all the current touch points on a touchscreen device. + * + * The `touches` array is empty by default. When the user touches their + * screen, a new touch point is tracked and added to the array. Touch points + * are `Objects` with the following properties: + * + * + * // Iterate over the touches array. + * for (let touch of touches) { + * // x-coordinate relative to the top-left + * // corner of the canvas. + * console.log(touch.x); + * + * // y-coordinate relative to the top-left + * // corner of the canvas. + * console.log(touch.y); + * + * // x-coordinate relative to the top-left + * // corner of the browser. + * console.log(touch.winX); + * + * // y-coordinate relative to the top-left + * // corner of the browser. + * console.log(touch.winY); + * + * // ID number + * console.log(touch.id); + * } + * + * + * @property {Object[]} touches + * @readOnly + * + * @example + *
        + * + * // On a touchscreen device, touch the canvas using one or more fingers + * // at the same time. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square. White circles appear where the user touches the square.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw a circle at each touch point. + * for (let touch of touches) { + * circle(touch.x, touch.y, 40); + * } + * } + * + *
        + * + *
        + * + * // On a touchscreen device, touch the canvas using one or more fingers + * // at the same time. + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square. Labels appear where the user touches the square, displaying the coordinates.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw a label above each touch point. + * for (let touch of touches) { + * text(`${touch.x}, ${touch.y}`, touch.x, touch.y - 40); + * } + * } + * + *
        + */ + + _main.default.prototype.touches = [ + ]; + _main.default.prototype._updateTouchCoords = function (e) { + if (this._curElement !== null) { + var touches = [ + ]; + for (var i = 0; i < e.touches.length; i++) { + touches[i] = getTouchInfo(this._curElement.elt, this.width, this.height, e, i); + } + this._setProperty('touches', touches); + } + }; + function getTouchInfo(canvas, w, h, e) { + var i = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var rect = canvas.getBoundingClientRect(); + var sx = canvas.scrollWidth / w || 1; + var sy = canvas.scrollHeight / h || 1; + var touch = e.touches[i] || e.changedTouches[i]; + return { + x: (touch.clientX - rect.left) / sx, + y: (touch.clientY - rect.top) / sy, + winX: touch.clientX, + winY: touch.clientY, + id: touch.identifier + }; + } /** + * A function that's called once each time the user touches the screen. + * + * Declaring a function called `touchStarted()` sets a code block to run + * automatically each time the user begins touching a touchscreen device: + * + * + * function touchStarted() { + * // Code to run. + * } + * + * + * The touches array will be updated with the most + * recent touch points when `touchStarted()` is called by p5.js: + * + * + * function touchStarted() { + * // Paint over the background. + * background(200); + * + * // Mark each touch point once with a circle. + * for (let touch of touches) { + * circle(touch.x, touch.y, 40); + * } + * } + * + * + * The parameter, event, is optional. `touchStarted()` will be passed a + * TouchEvent + * object with properties that describe the touch event: + * + * + * function touchStarted(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * On touchscreen devices, mousePressed() will + * run when a user’s touch starts if `touchStarted()` isn’t declared. If + * `touchStarted()` is declared, then `touchStarted()` will run when a user’s + * touch starts and mousePressed() won’t. + * + * Note: `touchStarted()`, touchEnded(), and + * touchMoved() are all related. + * `touchStarted()` runs as soon as the user touches a touchscreen device. + * touchEnded() runs as soon as the user ends a + * touch. touchMoved() runs repeatedly as the + * user moves any touch points. + * + * @method touchStarted + * @param {TouchEvent} [event] optional `TouchEvent` argument. + * + * @example + *
        + * + * // On a touchscreen device, touch the canvas using one or more fingers + * // at the same time. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square switches color between black and white each time the user touches the screen.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Toggle colors with each touch. + * function touchStarted() { + * if (value === 0) { + * value = 255; + * } else { + * value = 0; + * } + * } + * + *
        + * + *
        + * + * // On a touchscreen device, touch the canvas using one or more fingers + * // at the same time. + * + * let bgColor = 50; + * let fillColor = 255; + * let borderWidth = 0.5; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.' + * ); + * } + * + * function draw() { + * background(bgColor); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * fill(0); + * noStroke(); + * + * // Display the number of touch points. + * text(touches.length, 50, 20); + * + * // Style the touch points. + * fill(fillColor); + * stroke(0); + * strokeWeight(borderWidth); + * + * // Display the touch points as circles. + * for (let touch of touches) { + * circle(touch.x, touch.y, 40); + * } + * } + * + * // Set the background color to a random grayscale value. + * function touchStarted() { + * bgColor = random(80, 255); + * } + * + * // Set the fill color to a random grayscale value. + * function touchEnded() { + * fillColor = random(0, 255); + * } + * + * // Set the stroke weight. + * function touchMoved() { + * // Increment the border width. + * borderWidth += 0.1; + * + * // Reset the border width once it's too thick. + * if (borderWidth > 20) { + * borderWidth = 0.5; + * } + * } + * + *
        + */ + + _main.default.prototype._ontouchstart = function (e) { + var context = this._isGlobal ? window : this; + var executeDefault; + this._setProperty('mouseIsPressed', true); + this._updateTouchCoords(e); + this._updateNextMouseCoords(e); + this._updateMouseCoords(); // reset pmouseXY at the start of each touch event + if (typeof context.touchStarted === 'function') { + executeDefault = context.touchStarted(e); + if (executeDefault === false) { + e.preventDefault(); + } + this.touchstart = true; + } + }; + /** + * A function that's called when the user touches the screen and moves. + * + * Declaring the function `touchMoved()` sets a code block to run + * automatically when the user touches a touchscreen device and moves: + * + * + * function touchMoved() { + * // Code to run. + * } + * + * + * The touches array will be updated with the most + * recent touch points when `touchMoved()` is called by p5.js: + * + * + * function touchMoved() { + * // Paint over the background. + * background(200); + * + * // Mark each touch point while the user moves. + * for (let touch of touches) { + * circle(touch.x, touch.y, 40); + * } + * } + * + * + * The parameter, event, is optional. `touchMoved()` will be passed a + * TouchEvent + * object with properties that describe the touch event: + * + * + * function touchMoved(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * On touchscreen devices, mouseDragged() will + * run when the user’s touch points move if `touchMoved()` isn’t declared. If + * `touchMoved()` is declared, then `touchMoved()` will run when a user’s + * touch points move and mouseDragged() won’t. + * + * Note: touchStarted(), + * touchEnded(), and + * `touchMoved()` are all related. + * touchStarted() runs as soon as the user + * touches a touchscreen device. touchEnded() + * runs as soon as the user ends a touch. `touchMoved()` runs repeatedly as + * the user moves any touch points. + * + * @method touchMoved + * @param {TouchEvent} [event] optional TouchEvent argument. + * + * @example + *
        + * + * // On a touchscreen device, touch the canvas using one or more fingers + * // at the same time. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square becomes lighter when the user touches the screen and moves.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * function touchMoved() { + * // Update the grayscale value. + * value += 5; + * + * // Reset the grayscale value. + * if (value > 255) { + * value = 0; + * } + * } + * + *
        + * + *
        + * + * // On a touchscreen device, touch the canvas using one or more fingers + * // at the same time. + * + * let bgColor = 50; + * let fillColor = 255; + * let borderWidth = 0.5; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.' + * ); + * } + * + * function draw() { + * background(bgColor); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * fill(0); + * noStroke(); + * + * // Display the number of touch points. + * text(touches.length, 50, 20); + * + * // Style the touch points. + * fill(fillColor); + * stroke(0); + * strokeWeight(borderWidth); + * + * // Display the touch points as circles. + * for (let touch of touches) { + * circle(touch.x, touch.y, 40); + * } + * } + * + * // Set the background color to a random grayscale value. + * function touchStarted() { + * bgColor = random(80, 255); + * } + * + * // Set the fill color to a random grayscale value. + * function touchEnded() { + * fillColor = random(0, 255); + * } + * + * // Set the stroke weight. + * function touchMoved() { + * // Increment the border width. + * borderWidth += 0.1; + * + * // Reset the border width once it's too thick. + * if (borderWidth > 20) { + * borderWidth = 0.5; + * } + * } + * + *
        + */ + _main.default.prototype._ontouchmove = function (e) { + var context = this._isGlobal ? window : this; + var executeDefault; + this._updateTouchCoords(e); + this._updateNextMouseCoords(e); + if (typeof context.touchMoved === 'function') { + executeDefault = context.touchMoved(e); + if (executeDefault === false) { + e.preventDefault(); + } + } else if (typeof context.mouseDragged === 'function') { + executeDefault = context.mouseDragged(e); + if (executeDefault === false) { + e.preventDefault(); + } + } + }; + /** + * A function that's called once each time a screen touch ends. + * + * Declaring the function `touchEnded()` sets a code block to run + * automatically when the user stops touching a touchscreen device: + * + * + * function touchEnded() { + * // Code to run. + * } + * + * + * The touches array will be updated with the most + * recent touch points when `touchEnded()` is called by p5.js: + * + * + * function touchEnded() { + * // Paint over the background. + * background(200); + * + * // Mark each remaining touch point when the user stops + * // a touch. + * for (let touch of touches) { + * circle(touch.x, touch.y, 40); + * } + * } + * + * + * The parameter, event, is optional. `touchEnded()` will be passed a + * TouchEvent + * object with properties that describe the touch event: + * + * + * function touchEnded(event) { + * // Code to run that uses the event. + * console.log(event); + * } + * + * + * On touchscreen devices, mouseReleased() will + * run when the user’s touch ends if `touchEnded()` isn’t declared. If + * `touchEnded()` is declared, then `touchEnded()` will run when a user’s + * touch ends and mouseReleased() won’t. + * + * Note: touchStarted(), + * `touchEnded()`, and touchMoved() are all + * related. touchStarted() runs as soon as the + * user touches a touchscreen device. `touchEnded()` runs as soon as the user + * ends a touch. touchMoved() runs repeatedly as + * the user moves any touch points. + * + * @method touchEnded + * @param {TouchEvent} [event] optional `TouchEvent` argument. + * + * @example + *
        + * + * // On a touchscreen device, touch the canvas using one or more fingers + * // at the same time. + * + * let value = 0; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with a black square at its center. The inner square switches color between black and white each time the user stops touching the screen.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the square. + * fill(value); + * + * // Draw the square. + * square(25, 25, 50); + * } + * + * // Toggle colors when a touch ends. + * function touchEnded() { + * if (value === 0) { + * value = 255; + * } else { + * value = 0; + * } + * } + * + *
        + * + *
        + * + * // On a touchscreen device, touch the canvas using one or more fingers + * // at the same time. + * + * let bgColor = 50; + * let fillColor = 255; + * let borderWidth = 0.5; + * + * function setup() { + * createCanvas(100, 100); + * + * describe( + * 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.' + * ); + * } + * + * function draw() { + * background(bgColor); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * fill(0); + * noStroke(); + * + * // Display the number of touch points. + * text(touches.length, 50, 20); + * + * // Style the touch points. + * fill(fillColor); + * stroke(0); + * strokeWeight(borderWidth); + * + * // Display the touch points as circles. + * for (let touch of touches) { + * circle(touch.x, touch.y, 40); + * } + * } + * + * // Set the background color to a random grayscale value. + * function touchStarted() { + * bgColor = random(80, 255); + * } + * + * // Set the fill color to a random grayscale value. + * function touchEnded() { + * fillColor = random(0, 255); + * } + * + * // Set the stroke weight. + * function touchMoved() { + * // Increment the border width. + * borderWidth += 0.1; + * + * // Reset the border width once it's too thick. + * if (borderWidth > 20) { + * borderWidth = 0.5; + * } + * } + * + *
        + */ + _main.default.prototype._ontouchend = function (e) { + this._setProperty('mouseIsPressed', false); + this._updateTouchCoords(e); + this._updateNextMouseCoords(e); + var context = this._isGlobal ? window : this; + var executeDefault; + if (typeof context.touchEnded === 'function') { + executeDefault = context.touchEnded(e); + if (executeDefault === false) { + e.preventDefault(); + } + this.touchend = true; + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303 + } + ], + 324: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.int32-array'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.int32-array'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + /** + * This module defines the filters for use with image buffers. + * + * This module is basically a collection of functions stored in an object + * as opposed to modules. The functions are destructive, modifying + * the passed in canvas rather than creating a copy. + * + * Generally speaking users of this module will use the Filters.apply method + * on a canvas to create an effect. + * + * A number of functions are borrowed/adapted from + * http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ + * or the java processing implementation. + */ + var Filters = { + /* + * Helper functions + */ + /** + * Returns the pixel buffer for a canvas. + * + * @private + * + * @param {Canvas|ImageData} canvas the canvas to get pixels from + * @return {Uint8ClampedArray} a one-dimensional array containing + * the data in the RGBA order, with integer + * values between 0 and 255. + */ + _toPixels: function _toPixels(canvas) { + // Return pixel data if 'canvas' is an ImageData object. + if (canvas instanceof ImageData) { + return canvas.data; + } else { + // Check 2D context support. + if (canvas.getContext('2d')) { + // Retrieve pixel data. + return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data; + } else if (canvas.getContext('webgl')) { + //Check WebGL context support + var gl = canvas.getContext('webgl'); + // Calculate the size of pixel data + // (4 bytes per pixel - one byte for each RGBA channel). + var len = gl.drawingBufferWidth * gl.drawingBufferHeight * 4; + var data = new Uint8Array(len); + // Use gl.readPixels to fetch pixel data from the WebGL + // canvas, storing it in the data array as UNSIGNED_BYTE integers. + gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, data); + return data; + } + } + }, + /** + * Returns a 32-bit number containing ARGB data at the ith pixel in the + * 1D array containing pixels data. + * + * @private + * + * @param {Uint8ClampedArray} data array returned by _toPixels() + * @param {Integer} i index of a 1D Image Array + * @return {Integer} 32-bit integer value representing + * ARGB value. + */ + _getARGB: function _getARGB(data, i) { + // Determine the starting position in the 'data' array for the 'i'-th pixel. + var offset = i * 4; + return ( // Combining the extracted components using bitwise OR operations to form the final ARGB value. + data[offset + 3] << 24 & 4278190080 | //Extract alpha component + data[offset] << 16 & 16711680 | //Extract Red component + data[offset + 1] << 8 & 65280 | //Extract green component + data[offset + 2] & 255 //Extract blue component + ); + }, + /** + * Modifies pixels RGBA values to values contained in the data object. + * + * @private + * + * @param {Uint8ClampedArray} pixels array returned by _toPixels() + * @param {Int32Array} data source 1D array where each value + * represents ARGB values + */ + _setPixels: function _setPixels(pixels, data) { + var offset = 0; + for (var i = 0, al = pixels.length; i < al; i++) { + offset = i * 4; + pixels[offset + 0] = (data[i] & 16711680) >>> 16; + pixels[offset + 1] = (data[i] & 65280) >>> 8; + pixels[offset + 2] = data[i] & 255; + pixels[offset + 3] = (data[i] & 4278190080) >>> 24; + } + }, + /** + * Returns the ImageData object for a canvas. + * https://developer.mozilla.org/en-US/docs/Web/API/ImageData + * + * @private + * + * @param {Canvas|ImageData} canvas canvas to get image data from + * @return {ImageData} Holder of pixel data (and width and + * height) for a canvas + */ + _toImageData: function _toImageData(canvas) { + if (canvas instanceof ImageData) { + return canvas; + } else { + return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height); + } + }, + /** + * Returns a blank ImageData object. + * + * @private + * + * @param {Integer} width + * @param {Integer} height + * @return {ImageData} + */ + _createImageData: function _createImageData(width, height) { + Filters._tmpCanvas = document.createElement('canvas'); + Filters._tmpCtx = Filters._tmpCanvas.getContext('2d'); + return this._tmpCtx.createImageData(width, height); + }, + /** + * Applys a filter function to a canvas. + * + * The difference between this and the actual filter functions defined below + * is that the filter functions generally modify the pixel buffer but do + * not actually put that data back to the canvas (where it would actually + * update what is visible). By contrast this method does make the changes + * actually visible in the canvas. + * + * The apply method is the method that callers of this module would generally + * use. It has been separated from the actual filters to support an advanced + * use case of creating a filter chain that executes without actually updating + * the canvas in between everystep. + * + * @private + * @param {HTMLCanvasElement} canvas The input canvas to apply the filter on. + * @param {function(ImageData,Object)} func The filter function to apply to the canvas's pixel data. + * @param {Object} filterParam An optional parameter to pass to the filter function. + */ + apply: function apply(canvas, func, filterParam) { + var pixelsState = canvas.getContext('2d'); + var imageData = pixelsState.getImageData(0, 0, canvas.width, canvas.height); + //Filters can either return a new ImageData object, or just modify + //the one they received. + var newImageData = func(imageData, filterParam); + //If new ImageData is returned, replace the canvas's pixel data with it. + if (newImageData instanceof ImageData) { + pixelsState.putImageData(newImageData, 0, 0, 0, 0, canvas.width, canvas.height); + } else { + //Restore the original pixel. + pixelsState.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height); + } + }, + /* + * Filters + */ + /** + * Converts the image to black and white pixels depending if they are above or + * below the threshold defined by the level parameter. The parameter must be + * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. + * + * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ + * + * @private + * @param {Canvas} canvas Canvas to apply thershold filter on. + * @param {Float} level Threshold level (0-1). + */ + threshold: function threshold(canvas) { + var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.5; + var pixels = Filters._toPixels(canvas); + // Calculate threshold value on a (0-255) scale. + var thresh = Math.floor(level * 255); + for (var i = 0; i < pixels.length; i += 4) { + var r = pixels[i]; + var g = pixels[i + 1]; + var b = pixels[i + 2]; + // CIE luminance for RGB + var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; + var val = void 0; + if (gray >= thresh) { + val = 255; + } else { + val = 0; + } + pixels[i] = pixels[i + 1] = pixels[i + 2] = val; //set pixel to val. + } + }, + /** + * Converts any colors in the image to grayscale equivalents. + * No parameter is used. + * + * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ + * + * @private + * @param {Canvas} canvas Canvas to apply gray filter on. + */ + gray: function gray(canvas) { + var pixels = Filters._toPixels(canvas); + for (var i = 0; i < pixels.length; i += 4) { + var r = pixels[i]; + var g = pixels[i + 1]; + var b = pixels[i + 2]; + // CIE luminance for RGB + var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; + pixels[i] = pixels[i + 1] = pixels[i + 2] = gray; // set pixel to gray. + } + }, + /** + * Sets the alpha channel to entirely opaque. No parameter is used. + * + * @private + * @param {Canvas} canvas + */ + opaque: function opaque(canvas) { + var pixels = Filters._toPixels(canvas); + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 3] = 255; + } + return pixels; + }, + /** + * Sets each pixel to its inverse value. No parameter is used. + * @private + * @param {Canvas} canvas + */ + invert: function invert(canvas) { + var pixels = Filters._toPixels(canvas); + for (var i = 0; i < pixels.length; i += 4) { + pixels[i] = 255 - pixels[i]; + pixels[i + 1] = 255 - pixels[i + 1]; + pixels[i + 2] = 255 - pixels[i + 2]; + } + }, + /** + * Limits each channel of the image to the number of colors specified as + * the parameter. The parameter can be set to values between 2 and 255, but + * results are most noticeable in the lower ranges. + * + * Adapted from java based processing implementation + * + * @private + * @param {Canvas} canvas + * @param {Integer} level + */ + posterize: function posterize(canvas) { + var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4; + var pixels = Filters._toPixels(canvas); + if (level < 2 || level > 255) { + throw new Error('Level must be greater than 2 and less than 255 for posterize'); + } + var levels1 = level - 1; + for (var i = 0; i < pixels.length; i += 4) { + var rlevel = pixels[i]; + var glevel = pixels[i + 1]; + var blevel = pixels[i + 2]; + // New pixel value by posterizing each color. + pixels[i] = (rlevel * level >> 8) * 255 / levels1; + pixels[i + 1] = (glevel * level >> 8) * 255 / levels1; + pixels[i + 2] = (blevel * level >> 8) * 255 / levels1; + } + }, + /** + * Increases the bright areas in an image. + * @private + * @param {Canvas} canvas + */ + dilate: function dilate(canvas) { + var pixels = Filters._toPixels(canvas); + var currIdx = 0; + var maxIdx = pixels.length ? pixels.length / 4 : 0; + var out = new Int32Array(maxIdx); + var currRowIdx, + maxRowIdx, + colOrig, + colOut, + currLum; + var idxRight, + idxLeft, + idxUp, + idxDown; + var colRight, + colLeft, + colUp, + colDown; + var lumRight, + lumLeft, + lumUp, + lumDown; + // Iterates through rows of pixels. + while (currIdx < maxIdx) { + currRowIdx = currIdx; + maxRowIdx = currIdx + canvas.width; + // Iterates through pixels within the current row. + while (currIdx < maxRowIdx) { + // Get original color of current pixel. + colOrig = colOut = Filters._getARGB(pixels, currIdx); + idxLeft = currIdx - 1; + idxRight = currIdx + 1; + idxUp = currIdx - canvas.width; + idxDown = currIdx + canvas.width; + // Adjust the indices to avoid going out of bounds. + if (idxLeft < currRowIdx) { + idxLeft = currIdx; + } + if (idxRight >= maxRowIdx) { + idxRight = currIdx; + } + if (idxUp < 0) { + idxUp = 0; + } + if (idxDown >= maxIdx) { + idxDown = currIdx; + } + colUp = Filters._getARGB(pixels, idxUp); + colLeft = Filters._getARGB(pixels, idxLeft); + colDown = Filters._getARGB(pixels, idxDown); + colRight = Filters._getARGB(pixels, idxRight); + // Compute luminance + currLum = 77 * (colOrig >> 16 & 255) + 151 * (colOrig >> 8 & 255) + 28 * (colOrig & 255); + lumLeft = 77 * (colLeft >> 16 & 255) + 151 * (colLeft >> 8 & 255) + 28 * (colLeft & 255); + lumRight = 77 * (colRight >> 16 & 255) + 151 * (colRight >> 8 & 255) + 28 * (colRight & 255); + lumUp = 77 * (colUp >> 16 & 255) + 151 * (colUp >> 8 & 255) + 28 * (colUp & 255); + lumDown = 77 * (colDown >> 16 & 255) + 151 * (colDown >> 8 & 255) + 28 * (colDown & 255); + // Update the output color based on the highest luminance value + if (lumLeft > currLum) { + colOut = colLeft; + currLum = lumLeft; + } + if (lumRight > currLum) { + colOut = colRight; + currLum = lumRight; + } + if (lumUp > currLum) { + colOut = colUp; + currLum = lumUp; + } + if (lumDown > currLum) { + colOut = colDown; + currLum = lumDown; + } // Store the updated color. + + out[currIdx++] = colOut; + } + } + Filters._setPixels(pixels, out); + }, + /** + * Reduces the bright areas in an image. + * Similar to `dilate()`, but updates the output color based on the lowest luminance value. + * @private + * @param {Canvas} canvas + */ + erode: function erode(canvas) { + var pixels = Filters._toPixels(canvas); + var currIdx = 0; + var maxIdx = pixels.length ? pixels.length / 4 : 0; + var out = new Int32Array(maxIdx); + var currRowIdx, + maxRowIdx, + colOrig, + colOut, + currLum; + var idxRight, + idxLeft, + idxUp, + idxDown; + var colRight, + colLeft, + colUp, + colDown; + var lumRight, + lumLeft, + lumUp, + lumDown; + while (currIdx < maxIdx) { + currRowIdx = currIdx; + maxRowIdx = currIdx + canvas.width; + while (currIdx < maxRowIdx) { + colOrig = colOut = Filters._getARGB(pixels, currIdx); + idxLeft = currIdx - 1; + idxRight = currIdx + 1; + idxUp = currIdx - canvas.width; + idxDown = currIdx + canvas.width; + if (idxLeft < currRowIdx) { + idxLeft = currIdx; + } + if (idxRight >= maxRowIdx) { + idxRight = currIdx; + } + if (idxUp < 0) { + idxUp = 0; + } + if (idxDown >= maxIdx) { + idxDown = currIdx; + } + colUp = Filters._getARGB(pixels, idxUp); + colLeft = Filters._getARGB(pixels, idxLeft); + colDown = Filters._getARGB(pixels, idxDown); + colRight = Filters._getARGB(pixels, idxRight); + //compute luminance + currLum = 77 * (colOrig >> 16 & 255) + 151 * (colOrig >> 8 & 255) + 28 * (colOrig & 255); + lumLeft = 77 * (colLeft >> 16 & 255) + 151 * (colLeft >> 8 & 255) + 28 * (colLeft & 255); + lumRight = 77 * (colRight >> 16 & 255) + 151 * (colRight >> 8 & 255) + 28 * (colRight & 255); + lumUp = 77 * (colUp >> 16 & 255) + 151 * (colUp >> 8 & 255) + 28 * (colUp & 255); + lumDown = 77 * (colDown >> 16 & 255) + 151 * (colDown >> 8 & 255) + 28 * (colDown & 255); + if (lumLeft < currLum) { + colOut = colLeft; + currLum = lumLeft; + } + if (lumRight < currLum) { + colOut = colRight; + currLum = lumRight; + } + if (lumUp < currLum) { + colOut = colUp; + currLum = lumUp; + } + if (lumDown < currLum) { + colOut = colDown; + currLum = lumDown; + } // Store the updated color. + + out[currIdx++] = colOut; + } + } + Filters._setPixels(pixels, out); + }, + blur: function blur(canvas, radius) { + blurARGB(canvas, radius); + } + }; + // BLUR + // Internal kernel stuff for the gaussian blur filter. + var blurRadius; + var blurKernelSize; + var blurKernel; + var blurMult; + /* + * Port of https://github.com/processing/processing/blob/ + * main/core/src/processing/core/PImage.java#L1250 + * + * Optimized code for building the blur kernel. + * further optimized blur code (approx. 15% for radius=20) + * bigger speed gains for larger radii (~30%) + * added support for various image types (ALPHA, RGB, ARGB) + * [toxi 050728] + */ + function buildBlurKernel(r) { + var radius = r * 3.5 | 0; + radius = radius < 1 ? 1 : radius < 248 ? radius : 248; + if (blurRadius !== radius) { + blurRadius = radius; + // Calculating the size of the blur kernel + blurKernelSize = 1 + blurRadius << 1; + blurKernel = new Int32Array(blurKernelSize); + blurMult = new Array(blurKernelSize); + for (var l = 0; l < blurKernelSize; l++) { + blurMult[l] = new Int32Array(256); + } + var bk, + bki; + var bm, + bmi; + // Generating blur kernel values. + for (var i = 1, radiusi = radius - 1; i < radius; i++) { + blurKernel[radius + i] = blurKernel[radiusi] = bki = radiusi * radiusi; + bm = blurMult[radius + i]; + bmi = blurMult[radiusi--]; + for (var j = 0; j < 256; j++) { + bm[j] = bmi[j] = bki * j; + } + } + bk = blurKernel[radius] = radius * radius; + bm = blurMult[radius]; + for (var k = 0; k < 256; k++) { + bm[k] = bk * k; + } + } + } // Port of https://github.com/processing/processing/blob/ + // main/core/src/processing/core/PImage.java#L1433 + + function blurARGB(canvas, radius) { + // Get pixel data. + var pixels = Filters._toPixels(canvas); + var width = canvas.width; + var height = canvas.height; + var numPackedPixels = width * height; + var argb = new Int32Array(numPackedPixels); + for (var j = 0; j < numPackedPixels; j++) { + argb[j] = Filters._getARGB(pixels, j); + } + var sum, + cr, + cg, + cb, + ca; + var read, + ri, + ym, + ymi, + bk0; + var a2 = new Int32Array(numPackedPixels); + var r2 = new Int32Array(numPackedPixels); + var g2 = new Int32Array(numPackedPixels); + var b2 = new Int32Array(numPackedPixels); + var yi = 0; + buildBlurKernel(radius); + var x, + y, + i; + var bm; + // Horizontal pass. + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + cb = cg = cr = ca = sum = 0; + read = x - blurRadius; + // Handle edge cases. + if (read < 0) { + bk0 = - read; + read = 0; + } else { + if (read >= width) { + break; + } + bk0 = 0; + } + for (i = bk0; i < blurKernelSize; i++) { + if (read >= width) { + break; + } + var c = argb[read + yi]; + bm = blurMult[i]; + ca += bm[(c & - 16777216) >>> 24]; + cr += bm[(c & 16711680) >> 16]; + cg += bm[(c & 65280) >> 8]; + cb += bm[c & 255]; + sum += blurKernel[i]; + read++; + } + ri = yi + x; + a2[ri] = ca / sum; + r2[ri] = cr / sum; + g2[ri] = cg / sum; + b2[ri] = cb / sum; + } + yi += width; + } + yi = 0; + ym = - blurRadius; + ymi = ym * width; + // Vertical pass. + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + cb = cg = cr = ca = sum = 0; + // Handle edge cases. + if (ym < 0) { + bk0 = ri = - ym; + read = x; + } else { + if (ym >= height) { + break; + } + bk0 = 0; + ri = ym; + read = x + ymi; + } + for (i = bk0; i < blurKernelSize; i++) { + if (ri >= height) { + break; + } + bm = blurMult[i]; + ca += bm[a2[read]]; + cr += bm[r2[read]]; + cg += bm[g2[read]]; + cb += bm[b2[read]]; + sum += blurKernel[i]; + ri++; + read += width; + } // Set final ARGB value + + argb[x + yi] = ca / sum << 24 | cr / sum << 16 | cg / sum << 8 | cb / sum; + } + yi += width; + ymi += width; + ym++; + } + Filters._setPixels(pixels, argb); + } + var _default = Filters; + exports.default = _default; + }, + { + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.int32-array': 240, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254, + 'core-js/modules/es.typed-array.uint8-array': 257 + } + ], + 325: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var _omggif = _interopRequireDefault(_dereq_('omggif')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } /** + * @module Image + * @submodule Image + * @for p5 + * @requires core + */ + /** + * This module defines the p5 methods for the p5.Image class + * for drawing images to the main display canvas. + */ + /** + * Creates a new p5.Image object. + * + * `createImage()` uses the `width` and `height` parameters to set the new + * p5.Image object's dimensions in pixels. The new + * p5.Image can be modified by updating its + * pixels array or by calling its + * get() and + * set() methods. The + * loadPixels() method must be called + * before reading or modifying pixel values. The + * updatePixels() method must be called + * for updates to take effect. + * + * Note: The new p5.Image object is transparent by + * default. + * + * @method createImage + * @param {Integer} width width in pixels. + * @param {Integer} height height in pixels. + * @return {p5.Image} new p5.Image object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the image's pixels into memory. + * img.loadPixels(); + * + * // Set all the image's pixels to black. + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * img.set(x, y, 0); + * } + * } + * + * // Update the image's pixel values. + * img.updatePixels(); + * + * // Draw the image. + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the image's pixels into memory. + * img.loadPixels(); + * + * // Create a color gradient. + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * // Calculate the transparency. + * let a = map(x, 0, img.width, 0, 255); + * + * // Create a p5.Color object. + * let c = color(0, a); + * + * // Set the pixel's color. + * img.set(x, y, c); + * } + * } + * + * // Update the image's pixels. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A square with a horizontal color gradient that transitions from gray to black.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the pixels into memory. + * img.loadPixels(); + * // Get the current pixel density. + * let d = pixelDensity(); + * + * // Calculate the pixel that is halfway through the image's pixel array. + * let halfImage = 4 * (d * img.width) * (d * img.height / 2); + * + * // Set half of the image's pixels to black. + * for (let i = 0; i < halfImage; i += 4) { + * // Red. + * img.pixels[i] = 0; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; + * } + * + * // Update the image's pixels. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * } + * + *
        + */ + + _main.default.prototype.createImage = function (width, height) { + _main.default._validateParameters('createImage', arguments); + return new _main.default.Image(width, height); + }; + /** + * Saves the current canvas as an image. + * + * By default, `saveCanvas()` saves the canvas as a PNG image called + * `untitled.png`. + * + * The first parameter, `filename`, is optional. It's a string that sets the + * file's name. If a file extension is included, as in + * `saveCanvas('drawing.png')`, then the image will be saved using that + * format. + * + * The second parameter, `extension`, is also optional. It sets the files format. + * Either `'png'` or `'jpg'` can be used. For example, `saveCanvas('drawing', 'jpg')` + * saves the canvas to a file called `drawing.jpg`. + * + * Note: The browser will either save the file immediately or prompt the user + * with a dialogue window. + * + * @method saveCanvas + * @param {p5.Framebuffer|p5.Element|HTMLCanvasElement} selectedCanvas reference to a + * specific HTML5 canvas element. + * @param {String} [filename] file name. Defaults to 'untitled'. + * @param {String} [extension] file extension, either 'jpg' or 'png'. Defaults to 'png'. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * background(255); + * + * // Save the canvas to 'untitled.png'. + * saveCanvas(); + * + * describe('A white square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(255); + * + * // Save the canvas to 'myCanvas.jpg'. + * saveCanvas('myCanvas.jpg'); + * + * describe('A white square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(255); + * + * // Save the canvas to 'myCanvas.jpg'. + * saveCanvas('myCanvas', 'jpg'); + * + * describe('A white square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * let cnv = createCanvas(100, 100); + * + * background(255); + * + * // Save the canvas to 'untitled.png'. + * saveCanvas(cnv); + * + * describe('A white square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * let cnv = createCanvas(100, 100); + * + * background(255); + * + * // Save the canvas to 'myCanvas.jpg'. + * saveCanvas(cnv, 'myCanvas.jpg'); + * + * describe('A white square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * let cnv = createCanvas(100, 100); + * + * background(255); + * + * // Save the canvas to 'myCanvas.jpg'. + * saveCanvas(cnv, 'myCanvas', 'jpg'); + * + * describe('A white square.'); + * } + * + *
        + */ + /** + * @method saveCanvas + * @param {String} [filename] + * @param {String} [extension] + */ + _main.default.prototype.saveCanvas = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('saveCanvas', args); + // copy arguments to array + var htmlCanvas, + filename, + extension, + temporaryGraphics; + if (args[0] instanceof HTMLCanvasElement) { + htmlCanvas = args[0]; + args.shift(); + } else if (args[0] instanceof _main.default.Element) { + htmlCanvas = args[0].elt; + args.shift(); + } else if (args[0] instanceof _main.default.Framebuffer) { + var framebuffer = args[0]; + temporaryGraphics = this.createGraphics(framebuffer.width, framebuffer.height); + temporaryGraphics.pixelDensity(pixelDensity()); + framebuffer.loadPixels(); + temporaryGraphics.loadPixels(); + temporaryGraphics.pixels.set(framebuffer.pixels); + temporaryGraphics.updatePixels(); + htmlCanvas = temporaryGraphics.elt; + args.shift(); + } else { + htmlCanvas = this._curElement && this._curElement.elt; + } + if (args.length >= 1) { + filename = args[0]; + } + if (args.length >= 2) { + extension = args[1]; + } + extension = extension || _main.default.prototype._checkFileExtension(filename, extension) [1] || 'png'; + var mimeType; + switch (extension) { + default: + //case 'png': + mimeType = 'image/png'; + break; + case 'jpeg': + case 'jpg': + mimeType = 'image/jpeg'; + break; + } + htmlCanvas.toBlob(function (blob) { + _main.default.prototype.downloadFile(blob, filename, extension); + if (temporaryGraphics) temporaryGraphics.remove(); + }, mimeType); + }; + // this is the old saveGif, left here for compatibility purposes + // the only place I found it being used was on image/p5.Image.js, on the + // save function. that has been changed to use this function. + _main.default.prototype.encodeAndDownloadGif = function (pImg, filename) { + var props = pImg.gifProperties; + //convert loopLimit back into Netscape Block formatting + var loopLimit = props.loopLimit; + if (loopLimit === 1) { + loopLimit = null; + } else if (loopLimit === null) { + loopLimit = 0; + } + var buffer = new Uint8Array(pImg.width * pImg.height * props.numFrames); + var allFramesPixelColors = [ + ]; + // Used to determine the occurrence of unique palettes and the frames + // which use them + var paletteFreqsAndFrames = { + }; + // Pass 1: + //loop over frames and get the frequency of each palette + for (var i = 0; i < props.numFrames; i++) { + var paletteSet = new Set(); + var data = props.frames[i].image.data; + var dataLength = data.length; + // The color for each pixel in this frame ( for easier lookup later ) + var pixelColors = new Uint32Array(pImg.width * pImg.height); + for (var j = 0, k = 0; j < dataLength; j += 4, k++) { + var r = data[j + 0]; + var g = data[j + 1]; + var b = data[j + 2]; + var color = r << 16 | g << 8 | b << 0; + paletteSet.add(color); + // What color does this pixel have in this frame ? + pixelColors[k] = color; + } // A way to put use the entire palette as an object key + + var paletteStr = _toConsumableArray(paletteSet).sort().toString(); + if (paletteFreqsAndFrames[paletteStr] === undefined) { + paletteFreqsAndFrames[paletteStr] = { + freq: 1, + frames: [ + i + ] + }; + } else { + paletteFreqsAndFrames[paletteStr].freq += 1; + paletteFreqsAndFrames[paletteStr].frames.push(i); + } + allFramesPixelColors.push(pixelColors); + } + var framesUsingGlobalPalette = [ + ]; + // Now to build the global palette + // Sort all the unique palettes in descending order of their occurrence + var palettesSortedByFreq = Object.keys(paletteFreqsAndFrames).sort(function (a, b) { + return paletteFreqsAndFrames[b].freq - paletteFreqsAndFrames[a].freq; + }); + // The initial global palette is the one with the most occurrence + var globalPalette = palettesSortedByFreq[0].split(',').map(function (a) { + return parseInt(a); + }); + framesUsingGlobalPalette = framesUsingGlobalPalette.concat(paletteFreqsAndFrames[globalPalette].frames); + var globalPaletteSet = new Set(globalPalette); + // Build a more complete global palette + // Iterate over the remaining palettes in the order of + // their occurrence and see if the colors in this palette which are + // not in the global palette can be added there, while keeping the length + // of the global palette <= 256 + for (var _i = 1; _i < palettesSortedByFreq.length; _i++) { + var palette = palettesSortedByFreq[_i].split(',').map(function (a) { + return parseInt(a); + }); + var difference = palette.filter(function (x) { + return !globalPaletteSet.has(x); + }); + if (globalPalette.length + difference.length <= 256) { + for (var _j = 0; _j < difference.length; _j++) { + globalPalette.push(difference[_j]); + globalPaletteSet.add(difference[_j]); + } // All frames using this palette now use the global palette + + framesUsingGlobalPalette = framesUsingGlobalPalette.concat(paletteFreqsAndFrames[palettesSortedByFreq[_i]].frames); + } + } + framesUsingGlobalPalette = new Set(framesUsingGlobalPalette); + // Build a lookup table of the index of each color in the global palette + // Maps a color to its index + var globalIndicesLookup = { + }; + for (var _i2 = 0; _i2 < globalPalette.length; _i2++) { + if (!globalIndicesLookup[globalPalette[_i2]]) { + globalIndicesLookup[globalPalette[_i2]] = _i2; + } + } // force palette to be power of 2 + + var powof2 = 1; + while (powof2 < globalPalette.length) { + powof2 <<= 1; + } + globalPalette.length = powof2; + // global opts + var opts = { + loop: loopLimit, + palette: new Uint32Array(globalPalette) + }; + var gifWriter = new _omggif.default.GifWriter(buffer, pImg.width, pImg.height, opts); + var previousFrame = { + }; + // Pass 2 + // Determine if the frame needs a local palette + // Also apply transparency optimization. This function will often blow up + // the size of a GIF if not for transparency. If a pixel in one frame has + // the same color in the previous frame, that pixel can be marked as + // transparent. We decide one particular color as transparent and make all + // transparent pixels take this color. This helps in later in compression. + var _loop = function _loop(_i3) { + var localPaletteRequired = !framesUsingGlobalPalette.has(_i3); + var palette = localPaletteRequired ? [ + ] : globalPalette; + var pixelPaletteIndex = new Uint8Array(pImg.width * pImg.height); + // Lookup table mapping color to its indices + var colorIndicesLookup = { + }; + // All the colors that cannot be marked transparent in this frame + var cannotBeTransparent = new Set(); + allFramesPixelColors[_i3].forEach(function (color, k) { + if (localPaletteRequired) { + if (colorIndicesLookup[color] === undefined) { + colorIndicesLookup[color] = palette.length; + palette.push(color); + } + pixelPaletteIndex[k] = colorIndicesLookup[color]; + } else { + pixelPaletteIndex[k] = globalIndicesLookup[color]; + } + if (_i3 > 0) { + // If even one pixel of this color has changed in this frame + // from the previous frame, we cannot mark it as transparent + if (allFramesPixelColors[_i3 - 1][k] !== color) { + cannotBeTransparent.add(color); + } + } + }); + var frameOpts = { + }; + // Transparency optimization + var canBeTransparent = palette.filter(function (a) { + return !cannotBeTransparent.has(a); + }); + if (canBeTransparent.length > 0) { + // Select a color to mark as transparent + var transparent = canBeTransparent[0]; + var transparentIndex = localPaletteRequired ? colorIndicesLookup[transparent] : globalIndicesLookup[transparent]; + if (_i3 > 0) { + for (var _k = 0; _k < allFramesPixelColors[_i3].length; _k++) { + // If this pixel in this frame has the same color in previous frame + if (allFramesPixelColors[_i3 - 1][_k] === allFramesPixelColors[_i3][_k]) { + pixelPaletteIndex[_k] = transparentIndex; + } + } + frameOpts.transparent = transparentIndex; + // If this frame has any transparency, do not dispose the previous frame + previousFrame.frameOpts.disposal = 1; + } + } + frameOpts.delay = props.frames[_i3].delay / 10; // Move timing back into GIF formatting + if (localPaletteRequired) { + // force palette to be power of 2 + var _powof = 1; + while (_powof < palette.length) { + _powof <<= 1; + } + palette.length = _powof; + frameOpts.palette = new Uint32Array(palette); + } + if (_i3 > 0) { + // add the frame that came before the current one + gifWriter.addFrame(0, 0, pImg.width, pImg.height, previousFrame.pixelPaletteIndex, previousFrame.frameOpts); + } // previous frame object should now have details of this frame + + previousFrame = { + pixelPaletteIndex: pixelPaletteIndex, + frameOpts: frameOpts + }; + }; + for (var _i3 = 0; _i3 < props.numFrames; _i3++) { + _loop(_i3); + } + previousFrame.frameOpts.disposal = 1; + // add the last frame + gifWriter.addFrame(0, 0, pImg.width, pImg.height, previousFrame.pixelPaletteIndex, previousFrame.frameOpts); + var extension = 'gif'; + var blob = new Blob([buffer.slice(0, gifWriter.end())], { + type: 'image/gif' + }); + _main.default.prototype.downloadFile(blob, filename, extension); + }; + /** + * Captures a sequence of frames from the canvas that can be saved as images. + * + * `saveFrames()` creates an array of frame objects. Each frame is stored as + * an object with its file type, file name, and image data as a string. For + * example, the first saved frame might have the following properties: + * + * `{ ext: 'png', filenmame: 'frame0', imageData: 'data:image/octet-stream;base64, abc123' }`. + * + * The first parameter, `filename`, sets the prefix for the file names. For + * example, setting the prefix to `'frame'` would generate the image files + * `frame0.png`, `frame1.png`, and so on. + * + * The second parameter, `extension`, sets the file type to either `'png'` or + * `'jpg'`. + * + * The third parameter, `duration`, sets the duration to record in seconds. + * The maximum duration is 15 seconds. + * + * The fourth parameter, `framerate`, sets the number of frames to record per + * second. The maximum frame rate value is 22. Limits are placed on `duration` + * and `framerate` to avoid using too much memory. Recording large canvases + * can easily crash sketches or even web browsers. + * + * The fifth parameter, `callback`, is optional. If a function is passed, + * image files won't be saved by default. The callback function can be used + * to process an array containing the data for each captured frame. The array + * of image data contains a sequence of objects with three properties for each + * frame: `imageData`, `filename`, and `extension`. + * + * Note: Frames are downloaded as individual image files by default. + * + * @method saveFrames + * @param {String} filename prefix of file name. + * @param {String} extension file extension, either 'jpg' or 'png'. + * @param {Number} duration duration in seconds to record. This parameter will be constrained to be less or equal to 15. + * @param {Number} framerate number of frames to save per second. This parameter will be constrained to be less or equal to 22. + * @param {function(Array)} [callback] callback function that will be executed + to handle the image data. This function + should accept an array as argument. The + array will contain the specified number of + frames of objects. Each object has three + properties: `imageData`, `filename`, and `extension`. + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A square repeatedly changes color from blue to pink.'); + * } + * + * function draw() { + * let r = frameCount % 255; + * let g = 50; + * let b = 100; + * background(r, g, b); + * } + * + * // Save the frames when the user presses the 's' key. + * function keyPressed() { + * if (key === 's') { + * saveFrames('frame', 'png', 1, 5); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A square repeatedly changes color from blue to pink.'); + * } + * + * function draw() { + * let r = frameCount % 255; + * let g = 50; + * let b = 100; + * background(r, g, b); + * } + * + * // Print 5 frames when the user presses the mouse. + * function mousePressed() { + * saveFrames('frame', 'png', 1, 5, printFrames); + * } + * + * // Prints an array of objects containing raw image data, filenames, and extensions. + * function printFrames(frames) { + * for (let frame of frames) { + * print(frame); + * } + * } + * + *
        + */ + _main.default.prototype.saveFrames = function (fName, ext, _duration, _fps, callback) { + _main.default._validateParameters('saveFrames', arguments); + var duration = _duration || 3; + duration = _main.default.prototype.constrain(duration, 0, 15); + duration = duration * 1000; + var fps = _fps || 15; + fps = _main.default.prototype.constrain(fps, 0, 22); + var count = 0; + var makeFrame = _main.default.prototype._makeFrame; + var cnv = this._curElement.elt; + var frames = [ + ]; + var frameFactory = setInterval(function () { + frames.push(makeFrame(fName + count, ext, cnv)); + count++; + }, 1000 / fps); + setTimeout(function () { + clearInterval(frameFactory); + if (callback) { + callback(frames); + } else { + for (var _i4 = 0, _frames = frames; _i4 < _frames.length; _i4++) { + var f = _frames[_i4]; + _main.default.prototype.downloadFile(f.imageData, f.filename, f.ext); + } + } + frames = [ + ]; // clear frames + }, duration + 0.01); + }; + _main.default.prototype._makeFrame = function (filename, extension, _cnv) { + var cnv; + if (this) { + cnv = this._curElement.elt; + } else { + cnv = _cnv; + } + var mimeType; + if (!extension) { + extension = 'png'; + mimeType = 'image/png'; + } else { + switch (extension.toLowerCase()) { + case 'png': + mimeType = 'image/png'; + break; + case 'jpeg': + mimeType = 'image/jpeg'; + break; + case 'jpg': + mimeType = 'image/jpeg'; + break; + default: + mimeType = 'image/png'; + break; + } + } + var downloadMime = 'image/octet-stream'; + var imageData = cnv.toDataURL(mimeType); + imageData = imageData.replace(mimeType, downloadMime); + var thisFrame = { + }; + thisFrame.imageData = imageData; + thisFrame.filename = filename; + thisFrame.ext = extension; + return thisFrame; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.filter': 174, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.object.keys': 204, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.set': 212, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254, + 'core-js/modules/es.typed-array.uint32-array': 256, + 'core-js/modules/es.typed-array.uint8-array': 257, + 'core-js/modules/web.dom-collections.for-each': 260, + 'core-js/modules/web.dom-collections.iterator': 261, + 'omggif': 275 + } + ], + 326: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.copy-within'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint8-clamped-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.copy-within'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint8-clamped-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + _dereq_('regenerator-runtime/runtime'); + var _main = _interopRequireDefault(_dereq_('../core/main')); + var _helpers = _interopRequireDefault(_dereq_('../core/helpers')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + var _omggif = _interopRequireDefault(_dereq_('omggif')); + var _gifenc = _dereq_('gifenc'); + _dereq_('../core/friendly_errors/validate_params'); + _dereq_('../core/friendly_errors/file_errors'); + _dereq_('../core/friendly_errors/fes_core'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value); + } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err); + } + _next(undefined); + }); + }; + } /** + * @module Image + * @submodule Loading & Displaying + * @for p5 + * @requires core + */ + /** + * Loads an image to create a p5.Image object. + * + * `loadImage()` interprets the first parameter one of three ways. If the path + * to an image file is provided, `loadImage()` will load it. Paths to local + * files should be relative, such as `'assets/thundercat.jpg'`. URLs such as + * `'https://example.com/thundercat.jpg'` may be blocked due to browser + * security. Raw image data can also be passed as a base64 encoded image in + * the form `'data:image/png;base64,arandomsequenceofcharacters'`. + * + * The second parameter is optional. If a function is passed, it will be + * called once the image has loaded. The callback function can optionally use + * the new p5.Image object. + * + * The third parameter is also optional. If a function is passed, it will be + * called if the image fails to load. The callback function can optionally use + * the event error. + * + * Images can take time to load. Calling `loadImage()` in + * preload() ensures images load before they're + * used in setup() or draw(). + * + * @method loadImage + * @param {String} path path of the image to be loaded or base64 encoded image. + * @param {function(p5.Image)} [successCallback] function called with + * p5.Image once it + * loads. + * @param {function(Event)} [failureCallback] function called with event + * error if the image fails to load. + * @return {p5.Image} the p5.Image object. + * + * @example + *
        + * + * let img; + * + * // Load the image and create a p5.Image object. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Draw the image. + * image(img, 0, 0); + * + * describe('Image of the underside of a white umbrella and a gridded ceiling.'); + * } + * + *
        + * + *
        + * + * function setup() { + * // Call handleImage() once the image loads. + * loadImage('assets/laDefense.jpg', handleImage); + * + * describe('Image of the underside of a white umbrella and a gridded ceiling.'); + * } + * + * // Display the image. + * function handleImage(img) { + * image(img, 0, 0); + * } + * + *
        + * + *
        + * + * function setup() { + * // Call handleImage() once the image loads or + * // call handleError() if an error occurs. + * loadImage('assets/laDefense.jpg', handleImage, handleError); + * } + * + * // Display the image. + * function handleImage(img) { + * image(img, 0, 0); + * + * describe('Image of the underside of a white umbrella and a gridded ceiling.'); + * } + * + * // Log the error. + * function handleError(event) { + * console.error('Oops!', event); + * } + * + *
        + */ + + _main.default.prototype.loadImage = function (path, successCallback, failureCallback) { + _main.default._validateParameters('loadImage', arguments); + var pImg = new _main.default.Image(1, 1, this); + var self = this; + var req = new Request(path, { + method: 'GET', + mode: 'cors' + }); + fetch(path, req).then(function (response) { + // GIF section + var contentType = response.headers.get('content-type'); + if (contentType === null) { + console.warn('The image you loaded does not have a Content-Type header. If you are using the online editor consider reuploading the asset.'); + } + if (contentType && contentType.includes('image/gif')) { + response.arrayBuffer().then(function (arrayBuffer) { + if (arrayBuffer) { + var byteArray = new Uint8Array(arrayBuffer); + _createGif(byteArray, pImg, successCallback, failureCallback, function (pImg) { + self._decrementPreload(); + }.bind(self)); + } + }, function (e) { + if (typeof failureCallback === 'function') { + failureCallback(e); + self._decrementPreload(); + } else { + console.error(e); + } + }); + } else { + // Non-GIF Section + var img = new Image(); + img.onload = function () { + pImg.width = pImg.canvas.width = img.width; + pImg.height = pImg.canvas.height = img.height; + // Draw the image into the backing canvas of the p5.Image + pImg.drawingContext.drawImage(img, 0, 0); + pImg.modified = true; + if (typeof successCallback === 'function') { + successCallback(pImg); + } + self._decrementPreload(); + }; + img.onerror = function (e) { + _main.default._friendlyFileLoadError(0, img.src); + if (typeof failureCallback === 'function') { + failureCallback(e); + self._decrementPreload(); + } else { + console.error(e); + } + }; + // Set crossOrigin in case image is served with CORS headers. + // This will let us draw to the canvas without tainting it. + // See https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image + // When using data-uris the file will be loaded locally + // so we don't need to worry about crossOrigin with base64 file types. + if (path.indexOf('data:image/') !== 0) { + img.crossOrigin = 'Anonymous'; + } // start loading the image + + img.src = path; + } + pImg.modified = true; + }).catch(function (e) { + _main.default._friendlyFileLoadError(0, path); + if (typeof failureCallback === 'function') { + failureCallback(e); + self._decrementPreload(); + } else { + console.error(e); + } + }); + return pImg; + }; + /** + * Generates a gif from a sketch and saves it to a file. + * + * `saveGif()` may be called in setup() or at any + * point while a sketch is running. + * + * The first parameter, `fileName`, sets the gif's file name. + * + * The second parameter, `duration`, sets the gif's duration in seconds. + * + * The third parameter, `options`, is optional. If an object is passed, + * `saveGif()` will use its properties to customize the gif. `saveGif()` + * recognizes the properties `delay`, `units`, `silent`, + * `notificationDuration`, and `notificationID`. + * + * @method saveGif + * @param {String} filename file name of gif. + * @param {Number} duration duration in seconds to capture from the sketch. + * @param {Object} [options] an object that can contain five more properties: + * `delay`, a Number specifying how much time to wait before recording; + * `units`, a String that can be either 'seconds' or 'frames'. By default it's 'seconds’; + * `silent`, a Boolean that defines presence of progress notifications. By default it’s `false`; + * `notificationDuration`, a Number that defines how long in seconds the final notification + * will live. By default it's `0`, meaning the notification will never be removed; + * `notificationID`, a String that specifies the id of the notification's DOM element. By default it’s `'progressBar’`. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.'); + * } + * + * function draw() { + * background(200); + * + * // Style the circle. + * let c = frameCount % 255; + * fill(c); + * + * // Display the circle. + * circle(50, 50, 25); + * } + * + * // Save a 5-second gif when the user presses the 's' key. + * function keyPressed() { + * if (key === 's') { + * saveGif('mySketch', 5); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.'); + * } + * + * function draw() { + * background(200); + * + * // Style the circle. + * let c = frameCount % 255; + * fill(c); + * + * // Display the circle. + * circle(50, 50, 25); + * } + * + * // Save a 5-second gif when the user presses the 's' key. + * // Wait 1 second after the key press before recording. + * function keyPressed() { + * if (key === 's') { + * saveGif('mySketch', 5, { delay: 1 }); + * } + * } + * + *
        + */ + _main.default.prototype.saveGif = /*#__PURE__*/ function () { + var _ref = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(fileName, duration) { + var options, + delay, + units, + silent, + notificationDuration, + notificationID, + _frameRate, + gifFrameDelay, + nFrames, + nFramesDelay, + totalNumberOfFrames, + frameIterator, + lastPixelDensity, + frames, + p, + pixels, + gl, + data, + gif, + globalPalette, + paletteCache, + getIndexedFrame, + transparentIndex, + prevIndexedFrame, + i, + indexedFrame, + originalIndexedFrame, + _i, + buffer, + extension, + blob, + _args = arguments; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + options = _args.length > 2 && _args[2] !== undefined ? _args[2] : { + delay: 0, + units: 'seconds', + silent: false, + notificationDuration: 0, + notificationID: 'progressBar' + }; + if (!(typeof fileName !== 'string')) { + _context.next = 3; + break; + } + throw TypeError('fileName parameter must be a string'); + case 3: + if (!(typeof duration !== 'number')) { + _context.next = 5; + break; + } + throw TypeError('Duration parameter must be a number'); + case 5: + // extract variables for more comfortable use + delay = options && options.delay || 0; // in seconds + units = options && options.units || 'seconds'; // either 'seconds' or 'frames' + silent = options && options.silent || false; + notificationDuration = options && options.notificationDuration || 0; + notificationID = options && options.notificationID || 'progressBar'; // if arguments in the options object are not correct, cancel operation + if (!(typeof delay !== 'number')) { + _context.next = 12; + break; + } + throw TypeError('Delay parameter must be a number'); + case 12: + if (!(units !== 'seconds' && units !== 'frames')) { + _context.next = 14; + break; + } + throw TypeError('Units parameter must be either "frames" or "seconds"'); + case 14: + if (!(typeof silent !== 'boolean')) { + _context.next = 16; + break; + } + throw TypeError('Silent parameter must be a boolean'); + case 16: + if (!(typeof notificationDuration !== 'number')) { + _context.next = 18; + break; + } + throw TypeError('Notification duration parameter must be a number'); + case 18: + if (!(typeof notificationID !== 'string')) { + _context.next = 20; + break; + } + throw TypeError('Notification ID parameter must be a string'); + case 20: + this._recording = true; + // get the project's framerate + _frameRate = this._targetFrameRate; // if it is undefined or some non useful value, assume it's 60 + if (_frameRate === Infinity || _frameRate === undefined || _frameRate === 0) { + _frameRate = 60; + } // calculate frame delay based on frameRate + // this delay has nothing to do with the + // delay in options, but rather is the delay + // we have to specify to the gif encoder between frames. + + gifFrameDelay = 1 / _frameRate * 1000; // constrain it to be always greater than 20, + // otherwise it won't work in some browsers and systems + // reference: https://stackoverflow.com/questions/64473278/gif-frame-duration-seems-slower-than-expected + gifFrameDelay = gifFrameDelay < 20 ? 20 : gifFrameDelay; + // check the mode we are in and how many frames + // that duration translates to + nFrames = units === 'seconds' ? duration * _frameRate : duration; + nFramesDelay = units === 'seconds' ? delay * _frameRate : delay; + totalNumberOfFrames = nFrames + nFramesDelay; // initialize variables for the frames processing + frameIterator = nFramesDelay; + this.frameCount = frameIterator; + lastPixelDensity = this._pixelDensity; + this.pixelDensity(1); + // We first take every frame that we are going to use for the animation + frames = [ + ]; + if (document.getElementById(notificationID) !== null) document.getElementById(notificationID).remove(); + if (!silent) { + p = this.createP(''); + p.id(notificationID); + p.style('font-size', '16px'); + p.style('font-family', 'Montserrat'); + p.style('background-color', '#ffffffa0'); + p.style('padding', '8px'); + p.style('border-radius', '10px'); + p.position(0, 0); + } + if (this._renderer instanceof _main.default.RendererGL) { + // if we have a WEBGL context, initialize the pixels array + // and the gl context to use them inside the loop + gl = this.drawingContext; + pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + } // stop the loop since we are going to manually redraw + + this.noLoop(); + // Defer execution until the rest of the call stack finishes, allowing the + // rest of `setup` to be called (and, importantly, canvases hidden in setup + // to be unhidden.) + // + // Waiting on this empty promise means we'll continue as soon as setup + // finishes without waiting for another frame. + _context.next = 39; + return Promise.resolve(); + case 39: + if (!(frameIterator < totalNumberOfFrames)) { + _context.next = 50; + break; + } /* + we draw the next frame. this is important, since + busy sketches or low end devices might take longer + to render some frames. So we just wait for the frame + to be drawn and immediately save it to a buffer and continue + */ + + this.redraw(); + // depending on the context we'll extract the pixels one way + // or another + data = undefined; + if (this._renderer instanceof _main.default.RendererGL) { + pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + data = _flipPixels(pixels, this.width, this.height); + } else { + data = this.drawingContext.getImageData(0, 0, this.width, this.height).data; + } + frames.push(data); + frameIterator++; + if (!silent) { + p.html('Saved frame ' + frames.length.toString() + ' out of ' + nFrames.toString()); + } + _context.next = 48; + return new Promise(function (resolve) { + return setTimeout(resolve, 0); + }); + case 48: + _context.next = 39; + break; + case 50: + if (!silent) p.html('Frames processed, generating color palette...'); + this.loop(); + this.pixelDensity(lastPixelDensity); + // create the gif encoder and the colorspace format + gif = (0, _gifenc.GIFEncoder) (); // calculate the global palette for this set of frames + globalPalette = _generateGlobalPalette(frames); // Rather than using applyPalette() from the gifenc library, we use our + // own function to map frame pixels to a palette color. This way, we can + // cache palette color mappings between frames for extra performance, and + // use our own caching mechanism to avoid flickering colors from cache + // key collisions. + paletteCache = { + }; + getIndexedFrame = function getIndexedFrame(frame) { + var length = frame.length / 4; + var index = new Uint8Array(length); + for (var i = 0; i < length; i++) { + var key = frame[i * 4] << 24 | frame[i * 4 + 1] << 16 | frame[i * 4 + 2] << 8 | frame[i * 4 + 3]; + if (paletteCache[key] === undefined) { + paletteCache[key] = (0, _gifenc.nearestColorIndex) (globalPalette, frame.slice(i * 4, (i + 1) * 4)); + } + index[i] = paletteCache[key]; + } + return index; + }; // the way we designed the palette means we always take the last index for transparency + transparentIndex = globalPalette.length - 1; // we are going to iterate the frames in pairs, n-1 and n + prevIndexedFrame = [ + ]; + i = 0; + case 60: + if (!(i < frames.length)) { + _context.next = 71; + break; + } //const indexedFrame = applyPalette(frames[i], globalPaletteWithoutAlpha, 'rgba565'); + + indexedFrame = getIndexedFrame(frames[i]); // Make a copy of the palette-applied frame before editing the original + // to use transparent pixels + originalIndexedFrame = indexedFrame.slice(); + if (i === 0) { + gif.writeFrame(indexedFrame, this.width, this.height, { + palette: globalPalette, + delay: gifFrameDelay, + dispose: 1 + }); + } else { + // Matching pixels between frames can be set to full transparency, + // allowing the previous frame's pixels to show through. We only do + // this for pixels that get mapped to the same quantized color so that + // the resulting image would be the same. + for (_i = 0; _i < indexedFrame.length; _i++) { + if (indexedFrame[_i] === prevIndexedFrame[_i]) { + indexedFrame[_i] = transparentIndex; + } + } // Write frame into the encoder + + gif.writeFrame(indexedFrame, this.width, this.height, { + delay: gifFrameDelay, + transparent: true, + transparentIndex: transparentIndex, + dispose: 1 + }); + } + prevIndexedFrame = originalIndexedFrame; + if (!silent) { + p.html('Rendered frame ' + i.toString() + ' out of ' + nFrames.toString()); + } // this just makes the process asynchronous, preventing + // that the encoding locks up the browser + + _context.next = 68; + return new Promise(function (resolve) { + return setTimeout(resolve, 0); + }); + case 68: + i++; + _context.next = 60; + break; + case 71: + gif.finish(); + // Get a direct typed array view into the buffer to avoid copying it + buffer = gif.bytesView(); + extension = 'gif'; + blob = new Blob([buffer], { + type: 'image/gif' + }); + frames = [ + ]; + this._recording = false; + this.loop(); + if (!silent) { + p.html('Done. Downloading your gif!🌸'); + if (notificationDuration > 0) setTimeout(function () { + return p.remove(); + }, notificationDuration * 1000); + } + _main.default.prototype.downloadFile(blob, fileName, extension); + case 80: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + function _flipPixels(pixels, width, height) { + // extracting the pixels using readPixels returns + // an upside down image. we have to flip it back + // first. this solution is proposed by gman on + // this stack overflow answer: + // https://stackoverflow.com/questions/41969562/how-can-i-flip-the-result-of-webglrenderingcontext-readpixels + var halfHeight = parseInt(height / 2); + var bytesPerRow = width * 4; + // make a temp buffer to hold one row + var temp = new Uint8Array(width * 4); + for (var y = 0; y < halfHeight; ++y) { + var topOffset = y * bytesPerRow; + var bottomOffset = (height - y - 1) * bytesPerRow; + // make copy of a row on the top half + temp.set(pixels.subarray(topOffset, topOffset + bytesPerRow)); + // copy a row from the bottom half to the top + pixels.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow); + // copy the copy of the top half row to the bottom half + pixels.set(temp, bottomOffset); + } + return pixels; + } + function _generateGlobalPalette(frames) { + // make an array the size of every possible color in every possible frame + // that is: width * height * frames. + var allColors = new Uint8Array(frames.length * frames[0].length); + // put every frame one after the other in sequence. + // this array will hold absolutely every pixel from the animation. + // the set function on the Uint8Array works super fast tho! + for (var f = 0; f < frames.length; f++) { + allColors.set(frames[f], f * frames[0].length); + } // quantize this massive array into 256 colors and return it! + + var colorPalette = (0, _gifenc.quantize) (allColors, 256, { + format: 'rgba4444', + oneBitAlpha: true + }); + // when generating the palette, we have to leave space for 1 of the + // indices to be a random color that does not appear anywhere in our + // animation to use for transparency purposes. So, if the palette is full + // (has 256 colors), we overwrite the last one with a random, fully transparent + // color. Otherwise, we just push a new color into the palette the same way. + // this guarantees that when using the transparency index, there are no matches + // between some colors of the animation and the "holes" we want to dig on them, + // which would cause pieces of some frames to be transparent and thus look glitchy. + if (colorPalette.length === 256) { + colorPalette[colorPalette.length - 1] = [ + Math.random() * 255, + Math.random() * 255, + Math.random() * 255, + 0 + ]; + } else { + colorPalette.push([Math.random() * 255, + Math.random() * 255, + Math.random() * 255, + 0]); + } + return colorPalette; + } /** + * Helper function for loading GIF-based images + */ + + function _createGif(arrayBuffer, pImg, successCallback, failureCallback, finishCallback) { + var gifReader = new _omggif.default.GifReader(arrayBuffer); + pImg.width = pImg.canvas.width = gifReader.width; + pImg.height = pImg.canvas.height = gifReader.height; + var frames = [ + ]; + var numFrames = gifReader.numFrames(); + var framePixels = new Uint8ClampedArray(pImg.width * pImg.height * 4); + var loadGIFFrameIntoImage = function loadGIFFrameIntoImage(frameNum, gifReader) { + try { + gifReader.decodeAndBlitFrameRGBA(frameNum, framePixels); + } catch (e) { + _main.default._friendlyFileLoadError(8, pImg.src); + if (typeof failureCallback === 'function') { + failureCallback(e); + } else { + console.error(e); + } + } + }; + for (var j = 0; j < numFrames; j++) { + var frameInfo = gifReader.frameInfo(j); + var prevFrameData = pImg.drawingContext.getImageData(0, 0, pImg.width, pImg.height); + framePixels = prevFrameData.data.slice(); + loadGIFFrameIntoImage(j, gifReader); + var imageData = new ImageData(framePixels, pImg.width, pImg.height); + pImg.drawingContext.putImageData(imageData, 0, 0); + var frameDelay = frameInfo.delay; + // To maintain the default of 10FPS when frameInfo.delay equals to 0 + if (frameDelay === 0) { + frameDelay = 10; + } + frames.push({ + image: pImg.drawingContext.getImageData(0, 0, pImg.width, pImg.height), + delay: frameDelay * 10 //GIF stores delay in one-hundredth of a second, shift to ms + }); + // Some GIFs are encoded so that they expect the previous frame + // to be under the current frame. This can occur at a sub-frame level + // + // Values : 0 - No disposal specified. The decoder is + // not required to take any action. + // 1 - Do not dispose. The graphic is to be left + // in place. + // 2 - Restore to background color. The area used by the + // graphic must be restored to the background color. + // 3 - Restore to previous. The decoder is required to + // restore the area overwritten by the graphic with + // what was there prior to rendering the graphic. + // 4-7 - To be defined. + if (frameInfo.disposal === 2) { + // Restore background color + pImg.drawingContext.clearRect(frameInfo.x, frameInfo.y, frameInfo.width, frameInfo.height); + } else if (frameInfo.disposal === 3) { + // Restore previous + pImg.drawingContext.putImageData(prevFrameData, 0, 0, frameInfo.x, frameInfo.y, frameInfo.width, frameInfo.height); + } + } //Uses Netscape block encoding + //to repeat forever, this will be 0 + //to repeat just once, this will be null + //to repeat N times (1 1) { + pImg.gifProperties = { + displayIndex: 0, + loopLimit: loopLimit, + loopCount: 0, + frames: frames, + numFrames: numFrames, + playing: true, + timeDisplayed: 0, + lastChangeTime: 0 + }; + } + if (typeof successCallback === 'function') { + successCallback(pImg); + } + finishCallback(); + } /** + * @private + * @param {Constant} xAlign either LEFT, RIGHT or CENTER + * @param {Constant} yAlign either TOP, BOTTOM or CENTER + * @param {Number} dx + * @param {Number} dy + * @param {Number} dw + * @param {Number} dh + * @param {Number} sw + * @param {Number} sh + * @returns {Object} + */ + + function _imageContain(xAlign, yAlign, dx, dy, dw, dh, sw, sh) { + var r = Math.max(sw / dw, sh / dh); + var adjusted_dw = sw / r, + adjusted_dh = sh / r; + var x = dx; + var y = dy; + if (xAlign === constants.CENTER) { + x += (dw - adjusted_dw) / 2; + } else if (xAlign === constants.RIGHT) { + x += dw - adjusted_dw; + } + if (yAlign === constants.CENTER) { + y += (dh - adjusted_dh) / 2; + } else if (yAlign === constants.BOTTOM) { + y += dh - adjusted_dh; + } + return { + x: x, + y: y, + w: adjusted_dw, + h: adjusted_dh + }; + } /** + * @private + * @param {Constant} xAlign either LEFT, RIGHT or CENTER + * @param {Constant} yAlign either TOP, BOTTOM or CENTER + * @param {Number} dw + * @param {Number} dh + * @param {Number} sx + * @param {Number} sy + * @param {Number} sw + * @param {Number} sh + * @returns {Object} + */ + + function _imageCover(xAlign, yAlign, dw, dh, sx, sy, sw, sh) { + var r = Math.max(dw / sw, dh / sh); + var adjusted_sw = dw / r, + adjusted_sh = dh / r; + var x = sx; + var y = sy; + if (xAlign === constants.CENTER) { + x += (sw - adjusted_sw) / 2; + } else if (xAlign === constants.RIGHT) { + x += sw - adjusted_sw; + } + if (yAlign === constants.CENTER) { + y += (sh - adjusted_sh) / 2; + } else if (yAlign === constants.BOTTOM) { + y += sh - adjusted_sh; + } + return { + x: x, + y: y, + w: adjusted_sw, + h: adjusted_sh + }; + } /** + * @private + * @param {Constant} [fit] either CONTAIN or COVER + * @param {Constant} xAlign either LEFT, RIGHT or CENTER + * @param {Constant} yAlign either TOP, BOTTOM or CENTER + * @param {Number} dx + * @param {Number} dy + * @param {Number} dw + * @param {Number} dh + * @param {Number} sx + * @param {Number} sy + * @param {Number} sw + * @param {Number} sh + * @returns {Object} + */ + + function _imageFit(fit, xAlign, yAlign, dx, dy, dw, dh, sx, sy, sw, sh) { + if (fit === constants.COVER) { + var _imageCover2 = _imageCover(xAlign, yAlign, dw, dh, sx, sy, sw, sh), + x = _imageCover2.x, + y = _imageCover2.y, + w = _imageCover2.w, + h = _imageCover2.h; + sx = x; + sy = y; + sw = w; + sh = h; + } + if (fit === constants.CONTAIN) { + var _imageContain2 = _imageContain(xAlign, yAlign, dx, dy, dw, dh, sw, sh), + _x3 = _imageContain2.x, + _y = _imageContain2.y, + _w = _imageContain2.w, + _h = _imageContain2.h; + dx = _x3; + dy = _y; + dw = _w; + dh = _h; + } + return { + sx: sx, + sy: sy, + sw: sw, + sh: sh, + dx: dx, + dy: dy, + dw: dw, + dh: dh + }; + } /** + * Validates clipping params. Per drawImage spec sWidth and sHight cannot be + * negative or greater than image intrinsic width and height + * @private + * @param {Number} sVal + * @param {Number} iVal + * @returns {Number} + * @private + */ + + function _sAssign(sVal, iVal) { + if (sVal > 0 && sVal < iVal) { + return sVal; + } else { + return iVal; + } + } /** + * Draws an image to the canvas. + * + * The first parameter, `img`, is the source image to be drawn. `img` can be + * any of the following objects: + * - p5.Image + * - p5.Element + * - p5.Texture + * - p5.Framebuffer + * - p5.FramebufferTexture + * + * The second and third parameters, `dx` and `dy`, set the coordinates of the + * destination image's top left corner. See + * imageMode() for other ways to position images. + * + * Here's a diagram that explains how optional parameters work in `image()`: + * + * + * + * The fourth and fifth parameters, `dw` and `dh`, are optional. They set the + * the width and height to draw the destination image. By default, `image()` + * draws the full source image at its original size. + * + * The sixth and seventh parameters, `sx` and `sy`, are also optional. + * These coordinates define the top left corner of a subsection to draw from + * the source image. + * + * The eighth and ninth parameters, `sw` and `sh`, are also optional. + * They define the width and height of a subsection to draw from the source + * image. By default, `image()` draws the full subsection that begins at + * `(sx, sy)` and extends to the edges of the source image. + * + * The ninth parameter, `fit`, is also optional. It enables a subsection of + * the source image to be drawn without affecting its aspect ratio. If + * `CONTAIN` is passed, the full subsection will appear within the destination + * rectangle. If `COVER` is passed, the subsection will completely cover the + * destination rectangle. This may have the effect of zooming into the + * subsection. + * + * The tenth and eleventh paremeters, `xAlign` and `yAlign`, are also + * optional. They determine how to align the fitted subsection. `xAlign` can + * be set to either `LEFT`, `RIGHT`, or `CENTER`. `yAlign` can be set to + * either `TOP`, `BOTTOM`, or `CENTER`. By default, both `xAlign` and `yAlign` + * are set to `CENTER`. + * + * @method image + * @param {p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture} img image to display. + * @param {Number} x x-coordinate of the top-left corner of the image. + * @param {Number} y y-coordinate of the top-left corner of the image. + * @param {Number} [width] width to draw the image. + * @param {Number} [height] height to draw the image. + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Draw the image. + * image(img, 0, 0); + * + * describe('An image of the underside of a white umbrella with a gridded ceiling above.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Draw the image. + * image(img, 10, 10); + * + * describe('An image of the underside of a white umbrella with a gridded ceiling above. The image has dark gray borders on its left and top.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Draw the image 50x50. + * image(img, 0, 0, 50, 50); + * + * describe('An image of the underside of a white umbrella with a gridded ceiling above. The image is drawn in the top left corner of a dark gray square.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Draw the center of the image. + * image(img, 25, 25, 50, 50, 25, 25, 50, 50); + * + * describe('An image of a gridded ceiling drawn in the center of a dark gray square.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/moonwalk.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Draw the image and scale it to fit within the canvas. + * image(img, 0, 0, width, height, 0, 0, img.width, img.height, CONTAIN); + * + * describe('An image of an astronaut on the moon. The top and bottom borders of the image are dark gray.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * // Image is 50 x 50 pixels. + * img = loadImage('assets/laDefense50.png'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Draw the image and scale it to cover the canvas. + * image(img, 0, 0, width, height, 0, 0, img.width, img.height, COVER); + * + * describe('A pixelated image of the underside of a white umbrella with a gridded ceiling above.'); + * } + * + *
        + */ + /** + * @method image + * @param {p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture} img + * @param {Number} dx the x-coordinate of the destination + * rectangle in which to draw the source image + * @param {Number} dy the y-coordinate of the destination + * rectangle in which to draw the source image + * @param {Number} dWidth the width of the destination rectangle + * @param {Number} dHeight the height of the destination rectangle + * @param {Number} sx the x-coordinate of the subsection of the source + * image to draw into the destination rectangle + * @param {Number} sy the y-coordinate of the subsection of the source + * image to draw into the destination rectangle + * @param {Number} [sWidth] the width of the subsection of the + * source image to draw into the destination + * rectangle + * @param {Number} [sHeight] the height of the subsection of the + * source image to draw into the destination rectangle + * @param {Constant} [fit] either CONTAIN or COVER + * @param {Constant} [xAlign] either LEFT, RIGHT or CENTER default is CENTER + * @param {Constant} [yAlign] either TOP, BOTTOM or CENTER default is CENTER + */ + + _main.default.prototype.image = function (img, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight, fit, xAlign, yAlign) { + // set defaults per spec: https://goo.gl/3ykfOq + _main.default._validateParameters('image', arguments); + var defW = img.width; + var defH = img.height; + yAlign = yAlign || constants.CENTER; + xAlign = xAlign || constants.CENTER; + if (img.elt) { + defW = defW !== undefined ? defW : img.elt.width; + defH = defH !== undefined ? defH : img.elt.height; + } + if (img.elt && img.elt.videoWidth && !img.canvas) { + // video no canvas + defW = defW !== undefined ? defW : img.elt.videoWidth; + defH = defH !== undefined ? defH : img.elt.videoHeight; + } + var _dx = dx; + var _dy = dy; + var _dw = dWidth || defW; + var _dh = dHeight || defH; + var _sx = sx || 0; + var _sy = sy || 0; + var _sw = sWidth !== undefined ? sWidth : defW; + var _sh = sHeight !== undefined ? sHeight : defH; + _sw = _sAssign(_sw, defW); + _sh = _sAssign(_sh, defH); + // This part needs cleanup and unit tests + // see issues https://github.com/processing/p5.js/issues/1741 + // and https://github.com/processing/p5.js/issues/1673 + var pd = 1; + if (img.elt && !img.canvas && img.elt.style.width) { + //if img is video and img.elt.size() has been used and + //no width passed to image() + if (img.elt.videoWidth && !dWidth) { + pd = img.elt.videoWidth; + } else { + //all other cases + pd = img.elt.width; + } + pd /= parseInt(img.elt.style.width, 10); + } + _sx *= pd; + _sy *= pd; + _sh *= pd; + _sw *= pd; + var vals = _helpers.default.modeAdjust(_dx, _dy, _dw, _dh, this._renderer._imageMode); + vals = _imageFit(fit, xAlign, yAlign, vals.x, vals.y, vals.w, vals.h, _sx, _sy, _sw, _sh); + // tint the image if there is a tint + this._renderer.image(img, vals.sx, vals.sy, vals.sw, vals.sh, vals.dx, vals.dy, vals.dw, vals.dh); + }; + /** + * Tints images using a color. + * + * The version of `tint()` with one parameter interprets it one of four ways. + * If the parameter is a number, it's interpreted as a grayscale value. If the + * parameter is a string, it's interpreted as a CSS color string. An array of + * `[R, G, B, A]` values or a p5.Color object can + * also be used to set the tint color. + * + * The version of `tint()` with two parameters uses the first one as a + * grayscale value and the second as an alpha value. For example, calling + * `tint(255, 128)` will make an image 50% transparent. + * + * The version of `tint()` with three parameters interprets them as RGB or + * HSB values, depending on the current + * colorMode(). The optional fourth parameter + * sets the alpha value. For example, `tint(255, 0, 0, 100)` will give images + * a red tint and make them transparent. + * + * @method tint + * @param {Number} v1 red or hue value. + * @param {Number} v2 green or saturation value. + * @param {Number} v3 blue or brightness. + * @param {Number} [alpha] + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Left image. + * image(img, 0, 0); + * + * // Right image. + * // Tint with a CSS color string. + * tint('red'); + * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Left image. + * image(img, 0, 0); + * + * // Right image. + * // Tint with RGB values. + * tint(255, 0, 0); + * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Left. + * image(img, 0, 0); + * + * // Right. + * // Tint with RGBA values. + * tint(255, 0, 0, 100); + * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a transparent red tint.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Left. + * image(img, 0, 0); + * + * // Right. + * // Tint with grayscale and alpha values. + * tint(255, 180); + * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the right is transparent.'); + * } + * + *
        + */ + /** + * @method tint + * @param {String} value CSS color string. + */ + /** + * @method tint + * @param {Number} gray grayscale value. + * @param {Number} [alpha] + */ + /** + * @method tint + * @param {Number[]} values array containing the red, green, blue & + * alpha components of the color. + */ + /** + * @method tint + * @param {p5.Color} color the tint color + */ + _main.default.prototype.tint = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('tint', args); + var c = this.color.apply(this, args); + this._renderer._tint = c.levels; + }; + /** + * Removes the current tint set by tint(). + * + * `noTint()` restores images to their original colors. + * + * @method noTint + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Left. + * // Tint with a CSS color string. + * tint('red'); + * image(img, 0, 0); + * + * // Right. + * // Remove the tint. + * noTint(); + * image(img, 50, 0); + * + * describe('Two images of an umbrella and a ceiling side-by-side. The image on the left has a red tint.'); + * } + * + *
        + */ + _main.default.prototype.noTint = function () { + this._renderer._tint = null; + }; + /** + * Apply the current tint color to the input image, return the resulting + * canvas. + * + * @private + * @param {p5.Image} The image to be tinted + * @return {canvas} The resulting tinted canvas + */ + _main.default.prototype._getTintedImageCanvas = _main.default.Renderer2D.prototype._getTintedImageCanvas; + /** + * Changes the location from which images are drawn when + * image() is called. + * + * By default, the first + * two parameters of image() are the x- and + * y-coordinates of the image's upper-left corner. The next parameters are + * its width and height. This is the same as calling `imageMode(CORNER)`. + * + * `imageMode(CORNERS)` also uses the first two parameters of + * image() as the x- and y-coordinates of the image's + * top-left corner. The third and fourth parameters are the coordinates of its + * bottom-right corner. + * + * `imageMode(CENTER)` uses the first two parameters of + * image() as the x- and y-coordinates of the image's + * center. The next parameters are its width and height. + * + * @method imageMode + * @param {Constant} mode either CORNER, CORNERS, or CENTER. + * + * @example + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use CORNER mode. + * imageMode(CORNER); + * + * // Display the image. + * image(img, 10, 10, 50, 50); + * + * describe('A square image of a brick wall is drawn at the top left of a gray square.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use CORNERS mode. + * imageMode(CORNERS); + * + * // Display the image. + * image(img, 10, 10, 90, 40); + * + * describe('An image of a brick wall is drawn on a gray square. The image is squeezed into a small rectangular area.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use CENTER mode. + * imageMode(CENTER); + * + * // Display the image. + * image(img, 50, 50, 80, 80); + * + * describe('A square image of a brick wall is drawn on a gray square.'); + * } + * + *
        + */ + _main.default.prototype.imageMode = function (m) { + _main.default._validateParameters('imageMode', arguments); + if (m === constants.CORNER || m === constants.CORNERS || m === constants.CENTER) { + this._renderer._imageMode = m; + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/friendly_errors/fes_core': 294, + '../core/friendly_errors/file_errors': 295, + '../core/friendly_errors/validate_params': 298, + '../core/helpers': 299, + '../core/main': 303, + 'core-js/modules/es.array.copy-within': 171, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.promise': 206, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254, + 'core-js/modules/es.typed-array.uint8-array': 257, + 'core-js/modules/es.typed-array.uint8-clamped-array': 258, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261, + 'gifenc': 268, + 'omggif': 275, + 'regenerator-runtime/runtime': 279 + } + ], + 327: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var _filters = _interopRequireDefault(_dereq_('./filters')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * @module Image + * @submodule Image + * @requires core + * @requires constants + * @requires filters + */ + /** + * This module defines the p5.Image class and P5 methods for + * drawing images to the main display canvas. + */ + /* + * Class methods + */ + /** + * A class to describe an image. + * + * Images are rectangular grids of pixels that can be displayed and modified. + * + * Existing images can be loaded by calling + * loadImage(). Blank images can be created by + * calling createImage(). `p5.Image` objects + * have methods for common tasks such as applying filters and modifying + * pixel values. + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('An image of a brick wall.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the GRAY filter. + * img.filter(GRAY); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('A grayscale image of a brick wall.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the image's pixels. + * img.loadPixels(); + * + * // Set the pixels to black. + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * img.set(x, y, 0); + * } + * } + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * } + * + *
        + * + * @class p5.Image + * @constructor + * @param {Number} width + * @param {Number} height + */ + + _main.default.Image = /*#__PURE__*/ function () { + function _class(width, height) { + _classCallCheck(this, _class); + /** + * The image's width in pixels. + * + * @type {Number} + * @property {Number} width + * @name width + * @readOnly + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Calculate the center coordinates. + * let x = img.width / 2; + * let y = img.height / 2; + * + * // Draw a circle at the image's center. + * circle(x, y, 20); + * + * describe('An image of a mountain landscape with a white circle drawn in the middle.'); + * } + * + *
        + */ + this.width = width; + /** + * The image's height in pixels. + * + * @type {Number} + * @property height + * @name height + * @readOnly + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Calculate the center coordinates. + * let x = img.width / 2; + * let y = img.height / 2; + * + * // Draw a circle at the image's center. + * circle(x, y, 20); + * + * describe('An image of a mountain landscape with a white circle drawn in the middle.'); + * } + * + *
        + */ + this.height = height; + this.canvas = document.createElement('canvas'); + this.canvas.width = this.width; + this.canvas.height = this.height; + this.drawingContext = this.canvas.getContext('2d'); + this._pixelsState = this; + this._pixelDensity = 1; + //Object for working with GIFs, defaults to null + this.gifProperties = null; + //For WebGL Texturing only: used to determine whether to reupload texture to GPU + this._modified = false; + /** + * An array containing the color of each pixel in the image. + * + * Colors are stored as numbers representing red, green, blue, and alpha + * (RGBA) values. `img.pixels` is a one-dimensional array for performance + * reasons. + * + * Each pixel occupies four elements in the pixels array, one for each + * RGBA value. For example, the pixel at coordinates (0, 0) stores its + * RGBA values at `img.pixels[0]`, `img.pixels[1]`, `img.pixels[2]`, + * and `img.pixels[3]`, respectively. The next pixel at coordinates (1, 0) + * stores its RGBA values at `img.pixels[4]`, `img.pixels[5]`, + * `img.pixels[6]`, and `img.pixels[7]`. And so on. The `img.pixels` array + * for a 100×100 p5.Image object has + * 100 × 100 × 4 = 40,000 elements. + * + * Accessing the RGBA values for a pixel in the image requires a little + * math as shown in the examples below. The + * img.loadPixels() + * method must be called before accessing the `img.pixels` array. The + * img.updatePixels() method must be + * called after any changes are made. + * + * @property {Number[]} pixels + * @name pixels + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the image's pixels. + * img.loadPixels(); + * + * for (let i = 0; i < img.pixels.length; i += 4) { + * // Red. + * img.pixels[i] = 0; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; + * } + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the image's pixels. + * img.loadPixels(); + * + * // Set the pixels to red. + * for (let i = 0; i < img.pixels.length; i += 4) { + * // Red. + * img.pixels[i] = 255; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; + * } + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A red square drawn in the middle of a gray square.'); + * } + * + *
        + */ + this.pixels = [ + ]; + } /** + * Gets or sets the pixel density for high pixel density displays. + * + * By default, the density will be set to 1. + * + * Call this method with no arguments to get the default density, or pass + * in a number to set the density. If a non-positive number is provided, + * it defaults to 1. + * + * @method pixelDensity + * @param {Number} [density] A scaling factor for the number of pixels per + * side + * @returns {Number} The current density if called without arguments, or the instance for chaining if setting density. + */ + + _createClass(_class, [ + { + key: 'pixelDensity', + value: function pixelDensity(density) { + if (typeof density !== 'undefined') { + // Setter: set the density and handle resize + if (density <= 0) { + var errorObj = { + type: 'INVALID_VALUE', + format: { + types: [ + 'Number' + ] + }, + position: 1 + }; + _main.default._friendlyParamError(errorObj, 'pixelDensity'); + // Default to 1 in case of an invalid value + density = 1; + } + this._pixelDensity = density; + // Adjust canvas dimensions based on pixel density + this.width /= density; + this.height /= density; + return this; // Return the image instance for chaining if needed + } else { + // Getter: return the default density + return this._pixelDensity; + } + } /** + * Helper function for animating GIF-based images with time + */ + + }, + { + key: '_animateGif', + value: function _animateGif(pInst) { + var props = this.gifProperties; + var curTime = pInst._lastRealFrameTime || window.performance.now(); + if (props.lastChangeTime === 0) { + props.lastChangeTime = curTime; + } + if (props.playing) { + props.timeDisplayed = curTime - props.lastChangeTime; + var curDelay = props.frames[props.displayIndex].delay; + if (props.timeDisplayed >= curDelay) { + //GIF is bound to 'realtime' so can skip frames + var skips = Math.floor(props.timeDisplayed / curDelay); + props.timeDisplayed = 0; + props.lastChangeTime = curTime; + props.displayIndex += skips; + props.loopCount = Math.floor(props.displayIndex / props.numFrames); + if (props.loopLimit !== null && props.loopCount >= props.loopLimit) { + props.playing = false; + } else { + var ind = props.displayIndex % props.numFrames; + this.drawingContext.putImageData(props.frames[ind].image, 0, 0); + props.displayIndex = ind; + this.setModified(true); + } + } + } + } /** + * Helper fxn for sharing pixel methods + */ + + }, + { + key: '_setProperty', + value: function _setProperty(prop, value) { + this[prop] = value; + this.setModified(true); + } /** + * Loads the current value of each pixel in the image into the `img.pixels` + * array. + * + * `img.loadPixels()` must be called before reading or modifying pixel + * values. + * + * @method loadPixels + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the image's pixels. + * img.loadPixels(); + * + * // Set the pixels to black. + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * img.set(x, y, 0); + * } + * } + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the image's pixels. + * img.loadPixels(); + * + * for (let i = 0; i < img.pixels.length; i += 4) { + * // Red. + * img.pixels[i] = 0; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; + * } + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * } + * + *
        + */ + + }, + { + key: 'loadPixels', + value: function loadPixels() { + _main.default.Renderer2D.prototype.loadPixels.call(this); + this.setModified(true); + } /** + * Updates the canvas with the RGBA values in the + * img.pixels array. + * + * `img.updatePixels()` only needs to be called after changing values in + * the img.pixels array. Such changes can be + * made directly after calling + * img.loadPixels() or by calling + * img.set(). + * + * The optional parameters `x`, `y`, `width`, and `height` define a + * subsection of the image to update. Doing so can improve performance in + * some cases. + * + * If the image was loaded from a GIF, then calling `img.updatePixels()` + * will update the pixels in current frame. + * + * @method updatePixels + * @param {Integer} x x-coordinate of the upper-left corner + * of the subsection to update. + * @param {Integer} y y-coordinate of the upper-left corner + * of the subsection to update. + * @param {Integer} w width of the subsection to update. + * @param {Integer} h height of the subsection to update. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the image's pixels. + * img.loadPixels(); + * + * // Set the pixels to black. + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * img.set(x, y, 0); + * } + * } + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Load the image's pixels. + * img.loadPixels(); + * + * // Set the pixels to black. + * for (let i = 0; i < img.pixels.length; i += 4) { + * // Red. + * img.pixels[i] = 0; + * // Green. + * img.pixels[i + 1] = 0; + * // Blue. + * img.pixels[i + 2] = 0; + * // Alpha. + * img.pixels[i + 3] = 255; + * } + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A black square drawn in the middle of a gray square.'); + * } + * + *
        + */ + /** + * @method updatePixels + */ + + }, + { + key: 'updatePixels', + value: function updatePixels(x, y, w, h) { + _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); + this.setModified(true); + } /** + * Gets a pixel or a region of pixels from the image. + * + * `img.get()` is easy to use but it's not as fast as + * img.pixels. Use + * img.pixels to read many pixel values. + * + * The version of `img.get()` with no parameters returns the entire image. + * + * The version of `img.get()` with two parameters, as in `img.get(10, 20)`, + * interprets them as coordinates. It returns an array with the + * `[R, G, B, A]` values of the pixel at the given point. + * + * The version of `img.get()` with four parameters, as in + * `img,get(10, 20, 50, 90)`, interprets them as + * coordinates and dimensions. The first two parameters are the coordinates + * of the upper-left corner of the subsection. The last two parameters are + * the width and height of the subsection. It returns a subsection of the + * canvas in a new p5.Image object. + * + * Use `img.get()` instead of get() to work directly + * with images. + * + * @method get + * @param {Number} x x-coordinate of the pixel. + * @param {Number} y y-coordinate of the pixel. + * @param {Number} w width of the subsection to be returned. + * @param {Number} h height of the subsection to be returned. + * @return {p5.Image} subsection as a p5.Image object. + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Display the image. + * image(img, 0, 0); + * + * // Copy the image. + * let img2 = get(); + * + * // Display the copied image on the right. + * image(img2, 50, 0); + * + * describe('Two identical mountain landscapes shown side-by-side.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Get a pixel's color. + * let c = img.get(50, 90); + * + * // Style the square using the pixel's color. + * fill(c); + * noStroke(); + * + * // Draw the square. + * square(25, 25, 50); + * + * describe('A mountain landscape with an olive green square in its center.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Copy half of the image. + * let img2 = img.get(0, 0, img.width / 2, img.height / 2); + * + * // Display half of the image. + * image(img2, 50, 50); + * + * describe('A mountain landscape drawn on top of another mountain landscape.'); + * } + * + *
        + */ + /** + * @method get + * @return {p5.Image} whole p5.Image + */ + /** + * @method get + * @param {Number} x + * @param {Number} y + * @return {Number[]} color of the pixel at (x, y) in array format `[R, G, B, A]`. + */ + + }, + { + key: 'get', + value: function get(x, y, w, h) { + _main.default._validateParameters('p5.Image.get', arguments); + return _main.default.Renderer2D.prototype.get.apply(this, arguments); + } + }, + { + key: '_getPixel', + value: function _getPixel() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _main.default.Renderer2D.prototype._getPixel.apply(this, args); + } /** + * Sets the color of one or more pixels within an image. + * + * `img.set()` is easy to use but it's not as fast as + * img.pixels. Use + * img.pixels to set many pixel values. + * + * `img.set()` interprets the first two parameters as x- and y-coordinates. It + * interprets the last parameter as a grayscale value, a `[R, G, B, A]` pixel + * array, a p5.Color object, or another + * p5.Image object. + * + * img.updatePixels() must be called + * after using `img.set()` for changes to appear. + * + * @method set + * @param {Number} x x-coordinate of the pixel. + * @param {Number} y y-coordinate of the pixel. + * @param {Number|Number[]|Object} a grayscale value | pixel array | + * p5.Color object | + * p5.Image to copy. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(100, 100); + * + * // Set four pixels to black. + * img.set(30, 20, 0); + * img.set(85, 20, 0); + * img.set(85, 75, 0); + * img.set(30, 75, 0); + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('Four black dots arranged in a square drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(100, 100); + * + * // Create a p5.Color object. + * let black = color(0); + * + * // Set four pixels to black. + * img.set(30, 20, black); + * img.set(85, 20, black); + * img.set(85, 75, black); + * img.set(30, 75, black); + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('Four black dots arranged in a square drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Image object. + * let img = createImage(66, 66); + * + * // Draw a color gradient. + * for (let x = 0; x < img.width; x += 1) { + * for (let y = 0; y < img.height; y += 1) { + * let c = map(x, 0, img.width, 0, 255); + * img.set(x, y, c); + * } + * } + * + * // Update the image. + * img.updatePixels(); + * + * // Display the image. + * image(img, 17, 17); + * + * describe('A square with a horiztonal color gradient from black to white drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Image object. + * let img2 = createImage(100, 100); + * + * // Set the blank image's pixels using the landscape. + * img2.set(0, 0, img); + * + * // Display the second image. + * image(img2, 0, 0); + * + * describe('An image of a mountain landscape.'); + * } + * + *
        + */ + + }, + { + key: 'set', + value: function set(x, y, imgOrCol) { + _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol); + this.setModified(true); + } /** + * Resizes the image to a given width and height. + * + * The image's original aspect ratio can be kept by passing 0 for either + * `width` or `height`. For example, calling `img.resize(50, 0)` on an image + * that was 500 × 300 pixels will resize it to 50 × 30 pixels. + * + * @method resize + * @param {Number} width resized image width. + * @param {Number} height resized image height. + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Resize the image. + * img.resize(50, 100); + * + * // Display the resized image. + * image(img, 0, 0); + * + * describe('Two images of a mountain landscape. One copy of the image is squeezed horizontally.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Resize the image, keeping the aspect ratio. + * img.resize(0, 30); + * + * // Display the resized image. + * image(img, 0, 0); + * + * describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Resize the image, keeping the aspect ratio. + * img.resize(60, 0); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('Two images of a mountain landscape. The small copy of the image covers the top-left corner of the larger image.'); + * } + * + *
        + */ + + }, + { + key: 'resize', + value: function resize(width, height) { + // Copy contents to a temporary canvas, resize the original + // and then copy back. + // + // There is a faster approach that involves just one copy and swapping the + // this.canvas reference. We could switch to that approach if (as i think + // is the case) there an expectation that the user would not hold a + // reference to the backing canvas of a p5.Image. But since we do not + // enforce that at the moment, I am leaving in the slower, but safer + // implementation. + // auto-resize + if (width === 0 && height === 0) { + width = this.canvas.width; + height = this.canvas.height; + } else if (width === 0) { + width = this.canvas.width * height / this.canvas.height; + } else if (height === 0) { + height = this.canvas.height * width / this.canvas.width; + } + width = Math.floor(width); + height = Math.floor(height); + var tempCanvas = document.createElement('canvas'); + tempCanvas.width = width; + tempCanvas.height = height; + if (this.gifProperties) { + var props = this.gifProperties; + //adapted from github.com/LinusU/resize-image-data + var nearestNeighbor = function nearestNeighbor(src, dst) { + var pos = 0; + for (var y = 0; y < dst.height; y++) { + for (var x = 0; x < dst.width; x++) { + var srcX = Math.floor(x * src.width / dst.width); + var srcY = Math.floor(y * src.height / dst.height); + var srcPos = (srcY * src.width + srcX) * 4; + dst.data[pos++] = src.data[srcPos++]; // R + dst.data[pos++] = src.data[srcPos++]; // G + dst.data[pos++] = src.data[srcPos++]; // B + dst.data[pos++] = src.data[srcPos++]; // A + } + } + }; + for (var i = 0; i < props.numFrames; i++) { + var resizedImageData = this.drawingContext.createImageData(width, height); + nearestNeighbor(props.frames[i].image, resizedImageData); + props.frames[i].image = resizedImageData; + } + } + tempCanvas.getContext('2d').drawImage(this.canvas, 0, 0, this.canvas.width, this.canvas.height, 0, 0, tempCanvas.width, tempCanvas.height); + // Resize the original canvas, which will clear its contents + this.canvas.width = this.width = width; + this.canvas.height = this.height = height; + //Copy the image back + this.drawingContext.drawImage(tempCanvas, 0, 0, width, height, 0, 0, width, height); + if (this.pixels.length > 0) { + this.loadPixels(); + } + this.setModified(true); + } /** + * Copies pixels from a source image to this image. + * + * The first parameter, `srcImage`, is an optional + * p5.Image object to copy. If a source image isn't + * passed, then `img.copy()` can copy a region of this image to another + * region. + * + * The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region + * to copy from the source image. `(sx, sy)` is the top-left corner of the + * region. `sw` and `sh` are the region's width and height. + * + * The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region + * of this image to copy into. `(dx, dy)` is the top-left corner of the + * region. `dw` and `dh` are the region's width and height. + * + * Calling `img.copy()` will scale pixels from the source region if it isn't + * the same size as the destination region. + * + * @method copy + * @param {p5.Image|p5.Element} srcImage source image. + * @param {Integer} sx x-coordinate of the source's upper-left corner. + * @param {Integer} sy y-coordinate of the source's upper-left corner. + * @param {Integer} sw source image width. + * @param {Integer} sh source image height. + * @param {Integer} dx x-coordinate of the destination's upper-left corner. + * @param {Integer} dy y-coordinate of the destination's upper-left corner. + * @param {Integer} dw destination image width. + * @param {Integer} dh destination image height. + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Copy one region of the image to another. + * img.copy(7, 22, 10, 10, 35, 25, 50, 50); + * + * // Display the image. + * image(img, 0, 0); + * + * // Outline the copied region. + * stroke(255); + * noFill(); + * square(7, 22, 10); + * + * describe('An image of a mountain landscape. A square region is outlined in white. A larger square contains a pixelated view of the outlined region.'); + * } + * + *
        + * + *
        + * + * let mountains; + * let bricks; + * + * // Load the images. + * function preload() { + * mountains = loadImage('assets/rockies.jpg'); + * bricks = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Calculate the center of the bricks image. + * let x = bricks.width / 2; + * let y = bricks.height / 2; + * + * // Copy the bricks to the mountains image. + * mountains.copy(bricks, 0, 0, x, y, 0, 0, x, y); + * + * // Display the mountains image. + * image(mountains, 0, 0); + * + * describe('An image of a brick wall drawn at the top-left of an image of a mountain landscape.'); + * } + * + *
        + */ + /** + * @method copy + * @param {Integer} sx + * @param {Integer} sy + * @param {Integer} sw + * @param {Integer} sh + * @param {Integer} dx + * @param {Integer} dy + * @param {Integer} dw + * @param {Integer} dh + */ + + }, + { + key: 'copy', + value: function copy() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default.prototype.copy.apply(this, args); + } /** + * Masks part of the image with another. + * + * `img.mask()` uses another p5.Image object's + * alpha channel as the alpha channel for this image. Masks are cumulative + * and can't be removed once applied. If the mask has a different + * pixel density from this image, the mask will be scaled. + * + * @method mask + * @param {p5.Image} srcImage source image. + * + * @example + *
        + * + * let photo; + * let maskImage; + * + * // Load the images. + * function preload() { + * photo = loadImage('assets/rockies.jpg'); + * maskImage = loadImage('assets/mask2.png'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the mask. + * photo.mask(maskImage); + * + * // Display the image. + * image(photo, 0, 0); + * + * describe('An image of a mountain landscape. The right side of the image has a faded patch of white.'); + * } + * + *
        + */ + // TODO: - Accept an array of alpha values. + + }, + { + key: 'mask', + value: function mask(p5Image) { + if (p5Image === undefined) { + p5Image = this; + } + var currBlend = this.drawingContext.globalCompositeOperation; + var imgScaleFactor = this._pixelDensity; + var maskScaleFactor = 1; + if (p5Image instanceof _main.default.Renderer) { + maskScaleFactor = p5Image._pInst._pixelDensity; + } + var copyArgs = [ + p5Image, + 0, + 0, + maskScaleFactor * p5Image.width, + maskScaleFactor * p5Image.height, + 0, + 0, + imgScaleFactor * this.width, + imgScaleFactor * this.height + ]; + this.drawingContext.globalCompositeOperation = 'destination-in'; + if (this.gifProperties) { + for (var i = 0; i < this.gifProperties.frames.length; i++) { + this.drawingContext.putImageData(this.gifProperties.frames[i].image, 0, 0); + this.copy.apply(this, copyArgs); + this.gifProperties.frames[i].image = this.drawingContext.getImageData(0, 0, imgScaleFactor * this.width, imgScaleFactor * this.height); + } + this.drawingContext.putImageData(this.gifProperties.frames[this.gifProperties.displayIndex].image, 0, 0); + } else { + this.copy.apply(this, copyArgs); + } + this.drawingContext.globalCompositeOperation = currBlend; + this.setModified(true); + } /** + * Applies an image filter to the image. + * + * The preset options are: + * + * `INVERT` + * Inverts the colors in the image. No parameter is used. + * + * `GRAY` + * Converts the image to grayscale. No parameter is used. + * + * `THRESHOLD` + * Converts the image to black and white. Pixels with a grayscale value + * above a given threshold are converted to white. The rest are converted to + * black. The threshold must be between 0.0 (black) and 1.0 (white). If no + * value is specified, 0.5 is used. + * + * `OPAQUE` + * Sets the alpha channel to be entirely opaque. No parameter is used. + * + * `POSTERIZE` + * Limits the number of colors in the image. Each color channel is limited to + * the number of colors specified. Values between 2 and 255 are valid, but + * results are most noticeable with lower values. The default value is 4. + * + * `BLUR` + * Blurs the image. The level of blurring is specified by a blur radius. Larger + * values increase the blur. The default value is 4. A gaussian blur is used + * in `P2D` mode. A box blur is used in `WEBGL` mode. + * + * `ERODE` + * Reduces the light areas. No parameter is used. + * + * `DILATE` + * Increases the light areas. No parameter is used. + * + * @method filter + * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT, + * POSTERIZE, ERODE, DILATE or BLUR. + * @param {Number} [filterParam] parameter unique to each filter. + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the INVERT filter. + * img.filter(INVERT); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('A blue brick wall.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the GRAY filter. + * img.filter(GRAY); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('A brick wall drawn in grayscale.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the THRESHOLD filter. + * img.filter(THRESHOLD); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('A brick wall drawn in black and white.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the OPAQUE filter. + * img.filter(OPAQUE); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('A red brick wall.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the POSTERIZE filter. + * img.filter(POSTERIZE, 3); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('An image of a red brick wall drawn with a limited color palette.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the BLUR filter. + * img.filter(BLUR, 3); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('A blurry image of a red brick wall.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the DILATE filter. + * img.filter(DILATE); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('A red brick wall with bright lines between each brick.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Apply the ERODE filter. + * img.filter(ERODE); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('A red brick wall with faint lines between each brick.'); + * } + * + *
        + */ + + }, + { + key: 'filter', + value: function filter(operation, value) { + _filters.default.apply(this.canvas, _filters.default[operation], value); + this.setModified(true); + } /** + * Copies a region of pixels from another image into this one. + * + * The first parameter, `srcImage`, is the + * p5.Image object to blend. + * + * The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region + * to blend from the source image. `(sx, sy)` is the top-left corner of the + * region. `sw` and `sh` are the regions width and height. + * + * The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region + * of the canvas to blend into. `(dx, dy)` is the top-left corner of the + * region. `dw` and `dh` are the regions width and height. + * + * The tenth parameter, `blendMode`, sets the effect used to blend the images' + * colors. The options are `BLEND`, `DARKEST`, `LIGHTEST`, `DIFFERENCE`, + * `MULTIPLY`, `EXCLUSION`, `SCREEN`, `REPLACE`, `OVERLAY`, `HARD_LIGHT`, + * `SOFT_LIGHT`, `DODGE`, `BURN`, `ADD`, or `NORMAL`. + * + * @method blend + * @param {p5.Image} srcImage source image + * @param {Integer} sx x-coordinate of the source's upper-left corner. + * @param {Integer} sy y-coordinate of the source's upper-left corner. + * @param {Integer} sw source image width. + * @param {Integer} sh source image height. + * @param {Integer} dx x-coordinate of the destination's upper-left corner. + * @param {Integer} dy y-coordinate of the destination's upper-left corner. + * @param {Integer} dw destination image width. + * @param {Integer} dh destination image height. + * @param {Constant} blendMode the blend mode. either + * BLEND, DARKEST, LIGHTEST, DIFFERENCE, + * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, + * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. + * + * Available blend modes are: normal | multiply | screen | overlay | + * darken | lighten | color-dodge | color-burn | hard-light | + * soft-light | difference | exclusion | hue | saturation | + * color | luminosity + * + * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ + * + * @example + *
        + * + * let mountains; + * let bricks; + * + * // Load the images. + * function preload() { + * mountains = loadImage('assets/rockies.jpg'); + * bricks = loadImage('assets/bricks_third.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Blend the bricks image into the mountains. + * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD); + * + * // Display the mountains image. + * image(mountains, 0, 0); + * + * // Display the bricks image. + * image(bricks, 0, 0); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.'); + * } + * + *
        + * + *
        + * + * let mountains; + * let bricks; + * + * // Load the images. + * function preload() { + * mountains = loadImage('assets/rockies.jpg'); + * bricks = loadImage('assets/bricks_third.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Blend the bricks image into the mountains. + * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST); + * + * // Display the mountains image. + * image(mountains, 0, 0); + * + * // Display the bricks image. + * image(bricks, 0, 0); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.'); + * } + * + *
        + * + *
        + * + * let mountains; + * let bricks; + * + * // Load the images. + * function preload() { + * mountains = loadImage('assets/rockies.jpg'); + * bricks = loadImage('assets/bricks_third.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Blend the bricks image into the mountains. + * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST); + * + * // Display the mountains image. + * image(mountains, 0, 0); + * + * // Display the bricks image. + * image(bricks, 0, 0); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears washed out on the right of the image.'); + * } + * + *
        + */ + /** + * @method blend + * @param {Integer} sx + * @param {Integer} sy + * @param {Integer} sw + * @param {Integer} sh + * @param {Integer} dx + * @param {Integer} dy + * @param {Integer} dw + * @param {Integer} dh + * @param {Constant} blendMode + */ + + }, + { + key: 'blend', + value: function blend() { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('p5.Image.blend', arguments); + _main.default.prototype.blend.apply(this, args); + this.setModified(true); + } /** + * helper method for web GL mode to indicate that an image has been + * changed or unchanged since last upload. gl texture upload will + * set this value to false after uploading the texture. + * @method setModified + * @param {boolean} val sets whether or not the image has been + * modified. + * @private + */ + + }, + { + key: 'setModified', + value: function setModified(val) { + this._modified = val; //enforce boolean? + } /** + * helper method for web GL mode to figure out if the image + * has been modified and might need to be re-uploaded to texture + * memory between frames. + * @method isModified + * @private + * @return {boolean} a boolean indicating whether or not the + * image has been updated or modified since last texture upload. + */ + + }, + { + key: 'isModified', + value: function isModified() { + return this._modified; + } /** + * Saves the image to a file. + * + * By default, `img.save()` saves the image as a PNG image called + * `untitled.png`. + * + * The first parameter, `filename`, is optional. It's a string that sets the + * file's name. If a file extension is included, as in + * `img.save('drawing.png')`, then the image will be saved using that + * format. + * + * The second parameter, `extension`, is also optional. It sets the files format. + * Either `'png'` or `'jpg'` can be used. For example, `img.save('drawing', 'jpg')` + * saves the canvas to a file called `drawing.jpg`. + * + * Note: The browser will either save the file immediately or prompt the user + * with a dialogue window. + * + * The image will only be downloaded as an animated GIF if it was loaded + * from a GIF file. See saveGif() to create new + * GIFs. + * + * @method save + * @param {String} filename filename. Defaults to 'untitled'. + * @param {String} [extension] file extension, either 'png' or 'jpg'. + * Defaults to 'png'. + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * describe('An image of a mountain landscape. The image is downloaded when the user presses the "s", "j", or "p" key.'); + * } + * + * // Save the image with different options when the user presses a key. + * function keyPressed() { + * if (key === 's') { + * img.save(); + * } else if (key === 'j') { + * img.save('rockies.jpg'); + * } else if (key === 'p') { + * img.save('rockies', 'png'); + * } + * } + * + *
        + */ + + }, + { + key: 'save', + value: function save(filename, extension) { + if (this.gifProperties) { + _main.default.prototype.encodeAndDownloadGif(this, filename); + } else { + _main.default.prototype.saveCanvas(this.canvas, filename, extension); + } + } // GIF Section + /** + * Restarts an animated GIF at its first frame. + * + * @method reset + * + * @example + *
        + * + * let gif; + * + * // Load the image. + * function preload() { + * gif = loadImage('assets/arnott-wallace-wink-loop-once.gif'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A cartoon face winks once and then freezes. Clicking resets the face and makes it wink again.'); + * } + * + * function draw() { + * background(255); + * + * // Display the image. + * image(gif, 0, 0); + * } + * + * // Reset the GIF when the user presses the mouse. + * function mousePressed() { + * gif.reset(); + * } + * + *
        + */ + + }, + { + key: 'reset', + value: function reset() { + if (this.gifProperties) { + var props = this.gifProperties; + props.playing = true; + props.timeSinceStart = 0; + props.timeDisplayed = 0; + props.lastChangeTime = 0; + props.loopCount = 0; + props.displayIndex = 0; + this.drawingContext.putImageData(props.frames[0].image, 0, 0); + } + } /** + * Gets the index of the current frame in an animated GIF. + * + * @method getCurrentFrame + * @return {Number} index of the GIF's current frame. + * + * @example + *
        + * + * let gif; + * + * // Load the image. + * function preload() { + * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A cartoon eye repeatedly looks around, then outwards. A number displayed in the bottom-left corner increases from 0 to 124, then repeats.'); + * } + * + * function draw() { + * // Get the index of the current GIF frame. + * let index = gif.getCurrentFrame(); + * + * // Display the image. + * image(gif, 0, 0); + * + * // Display the current frame. + * text(index, 10, 90); + * } + * + *
        + */ + + }, + { + key: 'getCurrentFrame', + value: function getCurrentFrame() { + if (this.gifProperties) { + var props = this.gifProperties; + return props.displayIndex % props.numFrames; + } + } /** + * Sets the current frame in an animated GIF. + * + * @method setFrame + * @param {Number} index index of the frame to display. + * + * @example + *
        + * + * let gif; + * let frameSlider; + * + * // Load the image. + * function preload() { + * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Get the index of the last frame. + * let maxFrame = gif.numFrames() - 1; + * + * // Create a slider to control which frame is drawn. + * frameSlider = createSlider(0, maxFrame); + * frameSlider.position(10, 80); + * frameSlider.size(80); + * + * describe('A cartoon eye looks around when a slider is moved.'); + * } + * + * function draw() { + * // Get the slider's value. + * let index = frameSlider.value(); + * + * // Set the GIF's frame. + * gif.setFrame(index); + * + * // Display the image. + * image(gif, 0, 0); + * } + * + *
        + */ + + }, + { + key: 'setFrame', + value: function setFrame(index) { + if (this.gifProperties) { + var props = this.gifProperties; + if (index < props.numFrames && index >= 0) { + props.timeDisplayed = 0; + props.lastChangeTime = 0; + props.displayIndex = index; + this.drawingContext.putImageData(props.frames[index].image, 0, 0); + } else { + console.log('Cannot set GIF to a frame number that is higher than total number of frames or below zero.'); + } + } + } /** + * Returns the number of frames in an animated GIF. + * + * @method numFrames + * @return {Number} number of frames in the GIF. + * + * @example + *
        + * + * let gif; + * + * // Load the image. + * function preload() { + * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A cartoon eye looks around. The text "n / 125" is shown at the bottom of the canvas.'); + * } + * + * function draw() { + * // Display the image. + * image(gif, 0, 0); + * + * // Display the current state of playback. + * let total = gif.numFrames(); + * let index = gif.getCurrentFrame(); + * text(`${index} / ${total}`, 30, 90); + * } + * + *
        + */ + + }, + { + key: 'numFrames', + value: function numFrames() { + if (this.gifProperties) { + return this.gifProperties.numFrames; + } + } /** + * Plays an animated GIF that was paused with + * img.pause(). + * + * @method play + * + * @example + *
        + * + * let gif; + * + * // Load the image. + * function preload() { + * gif = loadImage('assets/nancy-liang-wind-loop-forever.gif'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.'); + * } + * + * function draw() { + * background(255); + * image(gif, 0, 0); + * } + * + * // Pause the GIF when the user presses the mouse. + * function mousePressed() { + * gif.pause(); + * } + * + * // Play the GIF when the user releases the mouse. + * function mouseReleased() { + * gif.play(); + * } + * + *
        + */ + + }, + { + key: 'play', + value: function play() { + if (this.gifProperties) { + this.gifProperties.playing = true; + } + } /** + * Pauses an animated GIF. + * + * The GIF can be resumed by calling + * img.play(). + * + * @method pause + * + * @example + *
        + * + * let gif; + * + * // Load the image. + * function preload() { + * gif = loadImage('assets/nancy-liang-wind-loop-forever.gif'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A drawing of a child with hair blowing in the wind. The animation freezes when clicked and resumes when released.'); + * } + * + * function draw() { + * background(255); + * + * // Display the image. + * image(gif, 0, 0); + * } + * + * // Pause the GIF when the user presses the mouse. + * function mousePressed() { + * gif.pause(); + * } + * + * // Play the GIF when the user presses the mouse. + * function mouseReleased() { + * gif.play(); + * } + * + *
        + */ + + }, + { + key: 'pause', + value: function pause() { + if (this.gifProperties) { + this.gifProperties.playing = false; + } + } /** + * Changes the delay between frames in an animated GIF. + * + * The first parameter, `delay`, is the length of the delay in milliseconds. + * + * The second parameter, `index`, is optional. If provided, only the frame + * at `index` will have its delay modified. All other frames will keep + * their default delay. + * + * @method delay + * @param {Number} d delay in milliseconds between switching frames. + * @param {Number} [index] index of the frame that will have its delay modified. + * + * @example + *
        + * + * let gifFast; + * let gifSlow; + * + * // Load the images. + * function preload() { + * gifFast = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * gifSlow = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Resize the images. + * gifFast.resize(50, 50); + * gifSlow.resize(50, 50); + * + * // Set the delay lengths. + * gifFast.delay(10); + * gifSlow.delay(100); + * + * describe('Two animated eyes looking around. The eye on the left moves faster than the eye on the right.'); + * } + * + * function draw() { + * // Display the images. + * image(gifFast, 0, 0); + * image(gifSlow, 50, 0); + * } + * + *
        + * + *
        + * + * let gif; + * + * // Load the image. + * function preload() { + * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Set the delay of frame 67. + * gif.delay(3000, 67); + * + * describe('An animated eye looking around. It pauses for three seconds while it looks down.'); + * } + * + * function draw() { + * // Display the image. + * image(gif, 0, 0); + * } + * + *
        + */ + + }, + { + key: 'delay', + value: function delay(d, index) { + if (this.gifProperties) { + var props = this.gifProperties; + if (index < props.numFrames && index >= 0) { + props.frames[index].delay = d; + } else { + // change all frames + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = props.frames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var frame = _step.value; + frame.delay = d; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + } + } + ]); + return _class; + }(); + var _default = _main.default.Image; + exports.default = _default; + }, + { + '../core/main': 303, + './filters': 324, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 328: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.filter'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var _filters = _interopRequireDefault(_dereq_('./filters')); + _dereq_('../color/p5.Color'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Image + * @submodule Pixels + * @for p5 + * @requires core + */ + /** + * An array containing the color of each pixel on the canvas. + * + * Colors are stored as numbers representing red, green, blue, and alpha + * (RGBA) values. `pixels` is a one-dimensional array for performance reasons. + * + * Each pixel occupies four elements in the `pixels` array, one for each RGBA + * value. For example, the pixel at coordinates (0, 0) stores its RGBA values + * at `pixels[0]`, `pixels[1]`, `pixels[2]`, and `pixels[3]`, respectively. + * The next pixel at coordinates (1, 0) stores its RGBA values at `pixels[4]`, + * `pixels[5]`, `pixels[6]`, and `pixels[7]`. And so on. The `pixels` array + * for a 100×100 canvas has 100 × 100 × 4 = 40,000 elements. + * + * Some displays use several smaller pixels to set the color at a single + * point. The pixelDensity() function returns + * the pixel density of the canvas. High density displays often have a + * pixelDensity() of 2. On such a display, the + * `pixels` array for a 100×100 canvas has 200 × 200 × 4 = + * 160,000 elements. + * + * Accessing the RGBA values for a point on the canvas requires a little math + * as shown below. The loadPixels() function + * must be called before accessing the `pixels` array. The + * updatePixels() function must be called + * after any changes are made. + * + * @property {Number[]} pixels + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Load the pixels array. + * loadPixels(); + * + * // Set the dot's coordinates. + * let x = 50; + * let y = 50; + * + * // Get the pixel density. + * let d = pixelDensity(); + * + * // Set the pixel(s) at the center of the canvas black. + * for (let i = 0; i < d; i += 1) { + * for (let j = 0; j < d; j += 1) { + * let index = 4 * ((y * d + j) * width * d + (x * d + i)); + * // Red. + * pixels[index] = 0; + * // Green. + * pixels[index + 1] = 0; + * // Blue. + * pixels[index + 2] = 0; + * // Alpha. + * pixels[index + 3] = 255; + * } + * } + * + * // Update the canvas. + * updatePixels(); + * + * describe('A black dot in the middle of a gray rectangle.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Load the pixels array. + * loadPixels(); + * + * // Get the pixel density. + * let d = pixelDensity(); + * + * // Calculate the halfway index in the pixels array. + * let halfImage = 4 * (d * width) * (d * height / 2); + * + * // Make the top half of the canvas red. + * for (let i = 0; i < halfImage; i += 4) { + * // Red. + * pixels[i] = 255; + * // Green. + * pixels[i + 1] = 0; + * // Blue. + * pixels[i + 2] = 0; + * // Alpha. + * pixels[i + 3] = 255; + * } + * + * // Update the canvas. + * updatePixels(); + * + * describe('A red rectangle drawn above a gray rectangle.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Create a p5.Color object. + * let pink = color(255, 102, 204); + * + * // Load the pixels array. + * loadPixels(); + * + * // Get the pixel density. + * let d = pixelDensity(); + * + * // Calculate the halfway index in the pixels array. + * let halfImage = 4 * (d * width) * (d * height / 2); + * + * // Make the top half of the canvas red. + * for (let i = 0; i < halfImage; i += 4) { + * pixels[i] = red(pink); + * pixels[i + 1] = green(pink); + * pixels[i + 2] = blue(pink); + * pixels[i + 3] = alpha(pink); + * } + * + * // Update the canvas. + * updatePixels(); + * + * describe('A pink rectangle drawn above a gray rectangle.'); + * } + * + *
        + */ + + _main.default.prototype.pixels = [ + ]; + /** + * Copies a region of pixels from one image to another. + * + * The first parameter, `srcImage`, is the + * p5.Image object to blend. + * + * The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region + * to blend from the source image. `(sx, sy)` is the top-left corner of the + * region. `sw` and `sh` are the regions width and height. + * + * The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region + * of the canvas to blend into. `(dx, dy)` is the top-left corner of the + * region. `dw` and `dh` are the regions width and height. + * + * The tenth parameter, `blendMode`, sets the effect used to blend the images' + * colors. The options are `BLEND`, `DARKEST`, `LIGHTEST`, `DIFFERENCE`, + * `MULTIPLY`, `EXCLUSION`, `SCREEN`, `REPLACE`, `OVERLAY`, `HARD_LIGHT`, + * `SOFT_LIGHT`, `DODGE`, `BURN`, `ADD`, or `NORMAL` + * + * @method blend + * @param {p5.Image} srcImage source image. + * @param {Integer} sx x-coordinate of the source's upper-left corner. + * @param {Integer} sy y-coordinate of the source's upper-left corner. + * @param {Integer} sw source image width. + * @param {Integer} sh source image height. + * @param {Integer} dx x-coordinate of the destination's upper-left corner. + * @param {Integer} dy y-coordinate of the destination's upper-left corner. + * @param {Integer} dw destination image width. + * @param {Integer} dh destination image height. + * @param {Constant} blendMode the blend mode. either + * BLEND, DARKEST, LIGHTEST, DIFFERENCE, + * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, + * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. + * + * @example + *
        + * + * let img0; + * let img1; + * + * // Load the images. + * function preload() { + * img0 = loadImage('assets/rockies.jpg'); + * img1 = loadImage('assets/bricks_third.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Use the mountains as the background. + * background(img0); + * + * // Display the bricks. + * image(img1, 0, 0); + * + * // Display the bricks faded into the landscape. + * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.'); + * } + * + *
        + * + *
        + * + * let img0; + * let img1; + * + * // Load the images. + * function preload() { + * img0 = loadImage('assets/rockies.jpg'); + * img1 = loadImage('assets/bricks_third.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Use the mountains as the background. + * background(img0); + * + * // Display the bricks. + * image(img1, 0, 0); + * + * // Display the bricks partially transparent. + * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.'); + * } + * + *
        + * + *
        + * + * let img0; + * let img1; + * + * // Load the images. + * function preload() { + * img0 = loadImage('assets/rockies.jpg'); + * img1 = loadImage('assets/bricks_third.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Use the mountains as the background. + * background(img0); + * + * // Display the bricks. + * image(img1, 0, 0); + * + * // Display the bricks washed out into the landscape. + * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD); + * + * describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears washed out on the right of the image.'); + * } + * + *
        + */ + /** + * @method blend + * @param {Integer} sx + * @param {Integer} sy + * @param {Integer} sw + * @param {Integer} sh + * @param {Integer} dx + * @param {Integer} dy + * @param {Integer} dw + * @param {Integer} dh + * @param {Constant} blendMode + */ + _main.default.prototype.blend = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('blend', args); + if (this._renderer) { + var _this$_renderer; + (_this$_renderer = this._renderer).blend.apply(_this$_renderer, args); + } else { + _main.default.Renderer2D.prototype.blend.apply(this, args); + } + }; + /** + * Copies pixels from a source image to a region of the canvas. + * + * The first parameter, `srcImage`, is the + * p5.Image object to blend. The source image can be + * the canvas itself or a + * p5.Image object. `copy()` will scale pixels from + * the source region if it isn't the same size as the destination region. + * + * The next four parameters, `sx`, `sy`, `sw`, and `sh` determine the region + * to copy from the source image. `(sx, sy)` is the top-left corner of the + * region. `sw` and `sh` are the region's width and height. + * + * The next four parameters, `dx`, `dy`, `dw`, and `dh` determine the region + * of the canvas to copy into. `(dx, dy)` is the top-left corner of the + * region. `dw` and `dh` are the region's width and height. + * + * @method copy + * @param {p5.Image|p5.Element} srcImage source image. + * @param {Integer} sx x-coordinate of the source's upper-left corner. + * @param {Integer} sy y-coordinate of the source's upper-left corner. + * @param {Integer} sw source image width. + * @param {Integer} sh source image height. + * @param {Integer} dx x-coordinate of the destination's upper-left corner. + * @param {Integer} dy y-coordinate of the destination's upper-left corner. + * @param {Integer} dw destination image width. + * @param {Integer} dh destination image height. + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Use the mountains as the background. + * background(img); + * + * // Copy a region of pixels to another spot. + * copy(img, 7, 22, 10, 10, 35, 25, 50, 50); + * + * // Outline the copied region. + * stroke(255); + * noFill(); + * square(7, 22, 10); + * + * describe('An image of a mountain landscape. A square region is outlined in white. A larger square contains a pixelated view of the outlined region.'); + * } + * + *
        + */ + /** + * @method copy + * @param {Integer} sx + * @param {Integer} sy + * @param {Integer} sw + * @param {Integer} sh + * @param {Integer} dx + * @param {Integer} dy + * @param {Integer} dw + * @param {Integer} dh + */ + _main.default.prototype.copy = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('copy', args); + var srcImage, + sx, + sy, + sw, + sh, + dx, + dy, + dw, + dh; + if (args.length === 9) { + srcImage = args[0]; + sx = args[1]; + sy = args[2]; + sw = args[3]; + sh = args[4]; + dx = args[5]; + dy = args[6]; + dw = args[7]; + dh = args[8]; + } else if (args.length === 8) { + srcImage = this; + sx = args[0]; + sy = args[1]; + sw = args[2]; + sh = args[3]; + dx = args[4]; + dy = args[5]; + dw = args[6]; + dh = args[7]; + } else { + throw new Error('Signature not supported'); + } + _main.default.prototype._copyHelper(this, srcImage, sx, sy, sw, sh, dx, dy, dw, dh); + }; + _main.default.prototype._copyHelper = function (dstImage, srcImage, sx, sy, sw, sh, dx, dy, dw, dh) { + var s = srcImage.canvas.width / srcImage.width; + // adjust coord system for 3D when renderer + // ie top-left = -width/2, -height/2 + var sxMod = 0; + var syMod = 0; + if (srcImage._renderer && srcImage._renderer.isP3D) { + sxMod = srcImage.width / 2; + syMod = srcImage.height / 2; + } + if (dstImage._renderer && dstImage._renderer.isP3D) { + dstImage.push(); + dstImage.resetMatrix(); + dstImage.noLights(); + dstImage.blendMode(dstImage.BLEND); + dstImage.imageMode(dstImage.CORNER); + _main.default.RendererGL.prototype.image.call(dstImage._renderer, srcImage, sx + sxMod, sy + syMod, sw, sh, dx, dy, dw, dh); + dstImage.pop(); + } else { + dstImage.drawingContext.drawImage(srcImage.canvas, s * (sx + sxMod), s * (sy + syMod), s * sw, s * sh, dx, dy, dw, dh); + } + }; + /** + * Applies an image filter to the canvas. + * + * The preset options are: + * + * `INVERT` + * Inverts the colors in the image. No parameter is used. + * + * `GRAY` + * Converts the image to grayscale. No parameter is used. + * + * `THRESHOLD` + * Converts the image to black and white. Pixels with a grayscale value + * above a given threshold are converted to white. The rest are converted to + * black. The threshold must be between 0.0 (black) and 1.0 (white). If no + * value is specified, 0.5 is used. + * + * `OPAQUE` + * Sets the alpha channel to entirely opaque. No parameter is used. + * + * `POSTERIZE` + * Limits the number of colors in the image. Each color channel is limited to + * the number of colors specified. Values between 2 and 255 are valid, but + * results are most noticeable with lower values. The default value is 4. + * + * `BLUR` + * Blurs the image. The level of blurring is specified by a blur radius. Larger + * values increase the blur. The default value is 4. A gaussian blur is used + * in `P2D` mode. A box blur is used in `WEBGL` mode. + * + * `ERODE` + * Reduces the light areas. No parameter is used. + * + * `DILATE` + * Increases the light areas. No parameter is used. + * + * `filter()` uses WebGL in the background by default because it's faster. + * This can be disabled in `P2D` mode by adding a `false` argument, as in + * `filter(BLUR, false)`. This may be useful to keep computation off the GPU + * or to work around a lack of WebGL support. + * + * In WebgL mode, `filter()` can also use custom shaders. See + * createFilterShader() for more + * information. + * + * + * @method filter + * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT, + * POSTERIZE, BLUR, ERODE, DILATE or BLUR. + * @param {Number} [filterParam] parameter unique to each filter. + * @param {Boolean} [useWebGL] flag to control whether to use fast + * WebGL filters (GPU) or original image + * filters (CPU); defaults to `true`. + * + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Apply the INVERT filter. + * filter(INVERT); + * + * describe('A blue brick wall.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Apply the GRAY filter. + * filter(GRAY); + * + * describe('A brick wall drawn in grayscale.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Apply the THRESHOLD filter. + * filter(THRESHOLD); + * + * describe('A brick wall drawn in black and white.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Apply the OPAQUE filter. + * filter(OPAQUE); + * + * describe('A red brick wall.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Apply the POSTERIZE filter. + * filter(POSTERIZE, 3); + * + * describe('An image of a red brick wall drawn with limited color palette.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Apply the BLUR filter. + * filter(BLUR, 3); + * + * describe('A blurry image of a red brick wall.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Apply the DILATE filter. + * filter(DILATE); + * + * describe('A red brick wall with bright lines between each brick.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Apply the ERODE filter. + * filter(ERODE); + * + * describe('A red brick wall with faint lines between each brick.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Apply the BLUR filter. + * // Don't use WebGL. + * filter(BLUR, 3, false); + * + * describe('A blurry image of a red brick wall.'); + * } + * + *
        + */ + /** + * @method getFilterGraphicsLayer + * @private + * @returns {p5.Graphics} + */ + _main.default.prototype.getFilterGraphicsLayer = function () { + return this._renderer.getFilterGraphicsLayer(); + }; + /** + * @method filter + * @param {Constant} filterType + * @param {Boolean} [useWebGL] + */ + /** + * @method filter + * @param {p5.Shader} shaderFilter shader that's been loaded, with the + * frag shader using a `tex0` uniform. + */ + _main.default.prototype.filter = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('filter', args); + var _parseFilterArgs = parseFilterArgs.apply(void 0, args), + shader = _parseFilterArgs.shader, + operation = _parseFilterArgs.operation, + value = _parseFilterArgs.value, + useWebGL = _parseFilterArgs.useWebGL; // when passed a shader, use it directly + if (this._renderer.isP3D && shader) { + _main.default.RendererGL.prototype.filter.call(this._renderer, shader); + return; + } // when opting out of webgl, use old pixels method + + if (!useWebGL && !this._renderer.isP3D) { + if (this.canvas !== undefined) { + _filters.default.apply(this.canvas, _filters.default[operation], value); + } else { + _filters.default.apply(this.elt, _filters.default[operation], value); + } + return; + } + if (!useWebGL && this._renderer.isP3D) { + console.warn('filter() with useWebGL=false is not supported in WEBGL'); + } // when this is a webgl renderer, apply constant shader filter + + if (this._renderer.isP3D) { + _main.default.RendererGL.prototype.filter.call(this._renderer, operation, value); + } // when this is P2D renderer, create/use hidden webgl renderer + else { + var filterGraphicsLayer = this.getFilterGraphicsLayer(); + // copy p2d canvas contents to secondary webgl renderer + // dest + filterGraphicsLayer.copy( // src + this._renderer, // src coods + 0, 0, this.width, this.height, // dest coords + - this.width / 2, - this.height / 2, this.width, this.height); + //clearing the main canvas + this._renderer.clear(); + this._renderer.resetMatrix(); + // filter it with shaders + filterGraphicsLayer.filter.apply(filterGraphicsLayer, args); + // copy secondary webgl renderer back to original p2d canvas + this.copy( // src + filterGraphicsLayer._renderer, // src coods + 0, 0, this.width, this.height, // dest coords + 0, 0, this.width, this.height); + filterGraphicsLayer.clear(); // prevent feedback effects on p2d canvas + } + }; + function parseFilterArgs() { + var _ref; + // args could be: + // - operation, value, [useWebGL] + // - operation, [useWebGL] + // - shader + var result = { + shader: undefined, + operation: undefined, + value: undefined, + useWebGL: true + }; + if ((arguments.length <= 0 ? undefined : arguments[0]) instanceof _main.default.Shader) { + result.shader = arguments.length <= 0 ? undefined : arguments[0]; + return result; + } else { + result.operation = arguments.length <= 0 ? undefined : arguments[0]; + } + if (arguments.length > 1 && typeof (arguments.length <= 1 ? undefined : arguments[1]) === 'number') { + result.value = arguments.length <= 1 ? undefined : arguments[1]; + } + if ((_ref = arguments.length - 1, _ref < 0 || arguments.length <= _ref ? undefined : arguments[_ref]) === false) { + result.useWebGL = false; + } + return result; + } /** + * Gets a pixel or a region of pixels from the canvas. + * + * `get()` is easy to use but it's not as fast as + * pixels. Use pixels + * to read many pixel values. + * + * The version of `get()` with no parameters returns the entire canvas. + * + * The version of `get()` with two parameters interprets them as + * coordinates. It returns an array with the `[R, G, B, A]` values of the + * pixel at the given point. + * + * The version of `get()` with four parameters interprets them as coordinates + * and dimensions. It returns a subsection of the canvas as a + * p5.Image object. The first two parameters are the + * coordinates for the upper-left corner of the subsection. The last two + * parameters are the width and height of the subsection. + * + * Use p5.Image.get() to work directly with + * p5.Image objects. + * + * @method get + * @param {Number} x x-coordinate of the pixel. + * @param {Number} y y-coordinate of the pixel. + * @param {Number} w width of the subsection to be returned. + * @param {Number} h height of the subsection to be returned. + * @return {p5.Image} subsection as a p5.Image object. + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Get the entire canvas. + * let c = get(); + * + * // Display half the canvas. + * image(c, 50, 0); + * + * describe('Two identical mountain landscapes shown side-by-side.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Get the color of a pixel. + * let c = get(50, 90); + * + * // Style the square with the pixel's color. + * fill(c); + * noStroke(); + * + * // Display the square. + * square(25, 25, 50); + * + * describe('A mountain landscape with an olive green square in its center.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0); + * + * // Get a region of the image. + * let c = get(0, 0, 50, 50); + * + * // Display the region. + * image(c, 50, 50); + * + * describe('A mountain landscape drawn on top of another mountain landscape.'); + * } + * + *
        + */ + /** + * @method get + * @return {p5.Image} whole canvas as a p5.Image. + */ + /** + * @method get + * @param {Number} x + * @param {Number} y + * @return {Number[]} color of the pixel at (x, y) in array format `[R, G, B, A]`. + */ + + _main.default.prototype.get = function (x, y, w, h) { + var _this$_renderer2; + _main.default._validateParameters('get', arguments); + return (_this$_renderer2 = this._renderer).get.apply(_this$_renderer2, arguments); + }; + /** + * Loads the current value of each pixel on the canvas into the + * pixels array. + * + * `loadPixels()` must be called before reading from or writing to + * pixels. + * + * @method loadPixels + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0, 100, 100); + * + * // Get the pixel density. + * let d = pixelDensity(); + * + * // Calculate the halfway index in the pixels array. + * let halfImage = 4 * (d * width) * (d * height / 2); + * + * // Load the pixels array. + * loadPixels(); + * + * // Copy the top half of the canvas to the bottom. + * for (let i = 0; i < halfImage; i += 1) { + * pixels[i + halfImage] = pixels[i]; + * } + * + * // Update the canvas. + * updatePixels(); + * + * describe('Two identical images of mountain landscapes, one on top of the other.'); + * } + * + *
        + */ + _main.default.prototype.loadPixels = function () { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + _main.default._validateParameters('loadPixels', args); + this._renderer.loadPixels(); + }; + /** + * Sets the color of a pixel or draws an image to the canvas. + * + * `set()` is easy to use but it's not as fast as + * pixels. Use pixels + * to set many pixel values. + * + * `set()` interprets the first two parameters as x- and y-coordinates. It + * interprets the last parameter as a grayscale value, a `[R, G, B, A]` pixel + * array, a p5.Color object, or a + * p5.Image object. If an image is passed, the first + * two parameters set the coordinates for the image's upper-left corner, + * regardless of the current imageMode(). + * + * updatePixels() must be called after using + * `set()` for changes to appear. + * + * @method set + * @param {Number} x x-coordinate of the pixel. + * @param {Number} y y-coordinate of the pixel. + * @param {Number|Number[]|Object} c grayscale value | pixel array | + * p5.Color object | p5.Image to copy. + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set four pixels to black. + * set(30, 20, 0); + * set(85, 20, 0); + * set(85, 75, 0); + * set(30, 75, 0); + * + * // Update the canvas. + * updatePixels(); + * + * describe('Four black dots arranged in a square drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object. + * let black = color(0); + * + * // Set four pixels to black. + * set(30, 20, black); + * set(85, 20, black); + * set(85, 75, black); + * set(30, 75, black); + * + * // Update the canvas. + * updatePixels(); + * + * describe('Four black dots arranged in a square drawn on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(255); + * + * // Draw a horizontal color gradient. + * for (let x = 0; x < 100; x += 1) { + * for (let y = 0; y < 100; y += 1) { + * // Calculate the grayscale value. + * let c = map(x, 0, 100, 0, 255); + * + * // Set the pixel using the grayscale value. + * set(x, y, c); + * } + * } + * + * // Update the canvas. + * updatePixels(); + * + * describe('A horiztonal color gradient from black to white.'); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Use the image to set all pixels. + * set(0, 0, img); + * + * // Update the canvas. + * updatePixels(); + * + * describe('An image of a mountain landscape.'); + * } + * + *
        + */ + _main.default.prototype.set = function (x, y, imgOrCol) { + this._renderer.set(x, y, imgOrCol); + }; + /** + * Updates the canvas with the RGBA values in the + * pixels array. + * + * `updatePixels()` only needs to be called after changing values in the + * pixels array. Such changes can be made directly + * after calling loadPixels() or by calling + * set(). + * + * @method updatePixels + * @param {Number} [x] x-coordinate of the upper-left corner of region + * to update. + * @param {Number} [y] y-coordinate of the upper-left corner of region + * to update. + * @param {Number} [w] width of region to update. + * @param {Number} [h] height of region to update. + * @example + *
        + * + * let img; + * + * // Load the image. + * function preload() { + * img = loadImage('assets/rockies.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Display the image. + * image(img, 0, 0, 100, 100); + * + * // Get the pixel density. + * let d = pixelDensity(); + * + * // Calculate the halfway index in the pixels array. + * let halfImage = 4 * (d * width) * (d * height / 2); + * + * // Load the pixels array. + * loadPixels(); + * + * // Copy the top half of the canvas to the bottom. + * for (let i = 0; i < halfImage; i += 1) { + * pixels[i + halfImage] = pixels[i]; + * } + * + * // Update the canvas. + * updatePixels(); + * + * describe('Two identical images of mountain landscapes, one on top of the other.'); + * } + * + *
        + */ + _main.default.prototype.updatePixels = function (x, y, w, h) { + _main.default._validateParameters('updatePixels', arguments); + // graceful fail - if loadPixels() or set() has not been called, pixel + // array will be empty, ignore call to updatePixels() + if (this.pixels.length === 0) { + return; + } + this._renderer.updatePixels(x, y, w, h); + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../color/p5.Color': 289, + '../core/main': 303, + './filters': 324, + 'core-js/modules/es.array.filter': 174 + } + ], + 329: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.from-entries'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/web.url'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.from-entries'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/web.url'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + _dereq_('whatwg-fetch'); + _dereq_('es6-promise/auto'); + var _fetchJsonp = _interopRequireDefault(_dereq_('fetch-jsonp')); + var _fileSaver = _interopRequireDefault(_dereq_('file-saver')); + _dereq_('../core/friendly_errors/validate_params'); + _dereq_('../core/friendly_errors/file_errors'); + _dereq_('../core/friendly_errors/fes_core'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } /** + * @module IO + * @submodule Input + * @for p5 + * @requires core + */ + /** + * Loads a JSON file to create an `Object`. + * + * JavaScript Object Notation + * (JSON) + * is a standard format for sending data between applications. The format is + * based on JavaScript objects which have keys and values. JSON files store + * data in an object with strings as keys. Values can be strings, numbers, + * Booleans, arrays, `null`, or other objects. + * + * The first parameter, `path`, is always a string with the path to the file. + * Paths to local files should be relative, as in + * `loadJSON('assets/data.json')`. URLs such as + * `'https://example.com/data.json'` may be blocked due to browser security. + * + * The second parameter, `successCallback`, is optional. If a function is + * passed, as in `loadJSON('assets/data.json', handleData)`, then the + * `handleData()` function will be called once the data loads. The object + * created from the JSON data will be passed to `handleData()` as its only argument. + * + * The third parameter, `failureCallback`, is also optional. If a function is + * passed, as in `loadJSON('assets/data.json', handleData, handleFailure)`, + * then the `handleFailure()` function will be called if an error occurs while + * loading. The `Error` object will be passed to `handleFailure()` as its only + * argument. + * + * Note: Data can take time to load. Calling `loadJSON()` within + * preload() ensures data loads before it's used in + * setup() or draw(). + * + * @method loadJSON + * @param {String} path path of the JSON file to be loaded. + * @param {function} [successCallback] function to call once the data is loaded. Will be passed the object. + * @param {function} [errorCallback] function to call if the data fails to load. Will be passed an `Error` event object. + * @return {Object} object containing the loaded data. + * + * @example + * + *
        + * + * let myData; + * + * // Load the JSON and create an object. + * function preload() { + * myData = loadJSON('assets/data.json'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the circle. + * fill(myData.color); + * noStroke(); + * + * // Draw the circle. + * circle(myData.x, myData.y, myData.d); + * + * describe('A pink circle on a gray background.'); + * } + * + *
        + * + *
        + * + * let myData; + * + * // Load the JSON and create an object. + * function preload() { + * myData = loadJSON('assets/data.json'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Color object and make it transparent. + * let c = color(myData.color); + * c.setAlpha(80); + * + * // Style the circles. + * fill(c); + * noStroke(); + * + * // Iterate over the myData.bubbles array. + * for (let b of myData.bubbles) { + * // Draw a circle for each bubble. + * circle(b.x, b.y, b.d); + * } + * + * describe('Several pink bubbles floating in a blue sky.'); + * } + * + *
        + * + *
        + * + * let myData; + * + * // Load the GeoJSON and create an object. + * function preload() { + * myData = loadJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get data about the most recent earthquake. + * let quake = myData.features[0].properties; + * + * // Draw a circle based on the earthquake's magnitude. + * circle(50, 50, quake.mag * 10); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(11); + * + * // Display the earthquake's location. + * text(quake.place, 5, 80, 100); + * + * describe(`A white circle on a gray background. The text "${quake.place}" is written beneath the circle.`); + * } + * + *
        + * + *
        + * + * let bigQuake; + * + * // Load the GeoJSON and preprocess it. + * function preload() { + * loadJSON( + * 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson', + * handleData + * ); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw a circle based on the earthquake's magnitude. + * circle(50, 50, bigQuake.mag * 10); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(11); + * + * // Display the earthquake's location. + * text(bigQuake.place, 5, 80, 100); + * + * describe(`A white circle on a gray background. The text "${bigQuake.place}" is written beneath the circle.`); + * } + * + * // Find the biggest recent earthquake. + * function handleData(data) { + * let maxMag = 0; + * // Iterate over the earthquakes array. + * for (let quake of data.features) { + * // Reassign bigQuake if a larger + * // magnitude quake is found. + * if (quake.properties.mag > maxMag) { + * bigQuake = quake.properties; + * } + * } + * } + * + *
        + * + *
        + * + * let bigQuake; + * + * // Load the GeoJSON and preprocess it. + * function preload() { + * loadJSON( + * 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson', + * handleData, + * handleError + * ); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw a circle based on the earthquake's magnitude. + * circle(50, 50, bigQuake.mag * 10); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(11); + * + * // Display the earthquake's location. + * text(bigQuake.place, 5, 80, 100); + * + * describe(`A white circle on a gray background. The text "${bigQuake.place}" is written beneath the circle.`); + * } + * + * // Find the biggest recent earthquake. + * function handleData(data) { + * let maxMag = 0; + * // Iterate over the earthquakes array. + * for (let quake of data.features) { + * // Reassign bigQuake if a larger + * // magnitude quake is found. + * if (quake.properties.mag > maxMag) { + * bigQuake = quake.properties; + * } + * } + * } + * + * // Log any errors to the console. + * function handleError(error) { + * console.log('Oops!', error); + * } + * + *
        + */ + + _main.default.prototype.loadJSON = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('loadJSON', args); + var path = args[0]; + var callback; + var errorCallback; + var options; + var ret = { + }; // object needed for preload + var t = 'json'; + // check for explicit data type argument + for (var i = 1; i < args.length; i++) { + var arg = args[i]; + if (typeof arg === 'string') { + if (arg === 'jsonp' || arg === 'json') { + t = arg; + } + } else if (typeof arg === 'function') { + if (!callback) { + callback = arg; + } else { + errorCallback = arg; + } + } else if (_typeof(arg) === 'object' && (arg.hasOwnProperty('jsonpCallback') || arg.hasOwnProperty('jsonpCallbackFunction'))) { + t = 'jsonp'; + options = arg; + } + } + var self = this; + this.httpDo(path, 'GET', options, t, function (resp) { + for (var k in resp) { + ret[k] = resp[k]; + } + if (typeof callback !== 'undefined') { + callback(resp); + } + self._decrementPreload(); + }, function (err) { + // Error handling + _main.default._friendlyFileLoadError(5, path); + if (errorCallback) { + errorCallback(err); + } else { + throw err; + } + }); + return ret; + }; + /** + * Loads a text file to create an `Array`. + * + * The first parameter, `path`, is always a string with the path to the file. + * Paths to local files should be relative, as in + * `loadStrings('assets/data.txt')`. URLs such as + * `'https://example.com/data.txt'` may be blocked due to browser security. + * + * The second parameter, `successCallback`, is optional. If a function is + * passed, as in `loadStrings('assets/data.txt', handleData)`, then the + * `handleData()` function will be called once the data loads. The array + * created from the text data will be passed to `handleData()` as its only + * argument. + * + * The third parameter, `failureCallback`, is also optional. If a function is + * passed, as in `loadStrings('assets/data.txt', handleData, handleFailure)`, + * then the `handleFailure()` function will be called if an error occurs while + * loading. The `Error` object will be passed to `handleFailure()` as its only + * argument. + * + * Note: Data can take time to load. Calling `loadStrings()` within + * preload() ensures data loads before it's used in + * setup() or draw(). + * + * @method loadStrings + * @param {String} path path of the text file to be loaded. + * @param {function} [successCallback] function to call once the data is + * loaded. Will be passed the array. + * @param {function} [errorCallback] function to call if the data fails to + * load. Will be passed an `Error` event + * object. + * @return {String[]} new array containing the loaded text. + * + * @example + * + *
        + * + * let myData; + * + * // Load the text and create an array. + * function preload() { + * myData = loadStrings('assets/test.txt'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Select a random line from the text. + * let phrase = random(myData); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display the text. + * text(phrase, 10, 50, 90); + * + * describe(`The text "${phrase}" written in black on a gray background.`); + * } + * + *
        + * + *
        + * + * let lastLine; + * + * // Load the text and preprocess it. + * function preload() { + * loadStrings('assets/test.txt', handleData); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display the text. + * text(lastLine, 10, 50, 90); + * + * describe('The text "I talk like an orange" written in black on a gray background.'); + * } + * + * // Select the last line from the text. + * function handleData(data) { + * lastLine = data[data.length - 1]; + * } + * + *
        + * + *
        + * + * let lastLine; + * + * // Load the text and preprocess it. + * function preload() { + * loadStrings('assets/test.txt', handleData, handleError); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display the text. + * text(lastLine, 10, 50, 90); + * + * describe('The text "I talk like an orange" written in black on a gray background.'); + * } + * + * // Select the last line from the text. + * function handleData(data) { + * lastLine = data[data.length - 1]; + * } + * + * // Log any errors to the console. + * function handleError(error) { + * console.error('Oops!', error); + * } + * + *
        + */ + _main.default.prototype.loadStrings = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('loadStrings', args); + var ret = [ + ]; + var callback, + errorCallback; + for (var i = 1; i < args.length; i++) { + var arg = args[i]; + if (typeof arg === 'function') { + if (typeof callback === 'undefined') { + callback = arg; + } else if (typeof errorCallback === 'undefined') { + errorCallback = arg; + } + } + } + var self = this; + _main.default.prototype.httpDo.call(this, args[0], 'GET', 'text', function (data) { + // split lines handling mac/windows/linux endings + var lines = data.replace(/\r\n/g, '\r').replace(/\n/g, '\r').split(/\r/); + // safe insert approach which will not blow up stack when inserting + // >100k lines, but still be faster than iterating line-by-line. based on + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#Examples + var QUANTUM = 32768; + for (var _i = 0, len = lines.length; _i < len; _i += QUANTUM) { + Array.prototype.push.apply(ret, lines.slice(_i, Math.min(_i + QUANTUM, len))); + } + if (typeof callback !== 'undefined') { + callback(ret); + } + self._decrementPreload(); + }, function (err) { + // Error handling + _main.default._friendlyFileLoadError(3, arguments[0]); + if (errorCallback) { + errorCallback(err); + } else { + throw err; + } + }); + return ret; + }; + /** + * Reads the contents of a file or URL and creates a p5.Table object with + * its values. If a file is specified, it must be located in the sketch's + * "data" folder. The filename parameter can also be a URL to a file found + * online. By default, the file is assumed to be comma-separated (in CSV + * format). Table only looks for a header row if the 'header' option is + * included. + * + * This method is asynchronous, meaning it may not finish before the next + * line in your sketch is executed. Calling loadTable() inside preload() + * guarantees to complete the operation before setup() and draw() are called. + * Outside of preload(), you may supply a callback function to handle the + * object: + * + * All files loaded and saved use UTF-8 encoding. This method is suitable for fetching files up to size of 64MB. + * @method loadTable + * @param {String} filename name of the file or URL to load + * @param {String} [extension] parse the table by comma-separated values "csv", semicolon-separated + * values "ssv", or tab-separated values "tsv" + * @param {String} [header] "header" to indicate table has header row + * @param {function} [callback] function to be executed after + * loadTable() completes. On success, the + * Table object is passed in as the + * first argument. + * @param {function} [errorCallback] function to be executed if + * there is an error, response is passed + * in as first argument + * @return {Object} Table object containing data + * + * @example + *
        + * + * // Given the following CSV file called "mammals.csv" + * // located in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * //the file can be remote + * //table = loadTable("http://p5js.org/reference/assets/mammals.csv", + * // "csv", "header"); + * } + * + * function setup() { + * //count the columns + * print(table.getRowCount() + ' total rows in table'); + * print(table.getColumnCount() + ' total columns in table'); + * + * print(table.getColumn('name')); + * //["Goat", "Leopard", "Zebra"] + * + * //cycle through the table + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) { + * print(table.getString(r, c)); + * } + * describe(`randomly generated text from a file, + * for example "i smell like butter"`); + * } + * + *
        + */ + _main.default.prototype.loadTable = function (path) { + // p5._validateParameters('loadTable', arguments); + var callback; + var errorCallback; + var options = [ + ]; + var header = false; + var ext = path.substring(path.lastIndexOf('.') + 1, path.length); + var sep; + if (ext === 'csv') { + sep = ','; + } else if (ext === 'ssv') { + sep = ';'; + } else if (ext === 'tsv') { + sep = '\t'; + } + for (var i = 1; i < arguments.length; i++) { + if (typeof arguments[i] === 'function') { + if (typeof callback === 'undefined') { + callback = arguments[i]; + } else if (typeof errorCallback === 'undefined') { + errorCallback = arguments[i]; + } + } else if (typeof arguments[i] === 'string') { + options.push(arguments[i]); + if (arguments[i] === 'header') { + header = true; + } + if (arguments[i] === 'csv') { + sep = ','; + } else if (arguments[i] === 'ssv') { + sep = ';'; + } else if (arguments[i] === 'tsv') { + sep = '\t'; + } + } + } + var t = new _main.default.Table(); + var self = this; + this.httpDo(path, 'GET', 'table', function (resp) { + var state = { + }; + // define constants + var PRE_TOKEN = 0, + MID_TOKEN = 1, + POST_TOKEN = 2, + POST_RECORD = 4; + var QUOTE = '"', + CR = '\r', + LF = '\n'; + var records = [ + ]; + var offset = 0; + var currentRecord = null; + var currentChar; + var tokenBegin = function tokenBegin() { + state.currentState = PRE_TOKEN; + state.token = ''; + }; + var tokenEnd = function tokenEnd() { + currentRecord.push(state.token); + tokenBegin(); + }; + var recordBegin = function recordBegin() { + state.escaped = false; + currentRecord = [ + ]; + tokenBegin(); + }; + var recordEnd = function recordEnd() { + state.currentState = POST_RECORD; + records.push(currentRecord); + currentRecord = null; + }; + for (; ; ) { + currentChar = resp[offset++]; + // EOF + if (currentChar == null) { + if (state.escaped) { + throw new Error('Unclosed quote in file.'); + } + if (currentRecord) { + tokenEnd(); + recordEnd(); + break; + } + } + if (currentRecord === null) { + recordBegin(); + } // Handle opening quote + + if (state.currentState === PRE_TOKEN) { + if (currentChar === QUOTE) { + state.escaped = true; + state.currentState = MID_TOKEN; + continue; + } + state.currentState = MID_TOKEN; + } // mid-token and escaped, look for sequences and end quote + + if (state.currentState === MID_TOKEN && state.escaped) { + if (currentChar === QUOTE) { + if (resp[offset] === QUOTE) { + state.token += QUOTE; + offset++; + } else { + state.escaped = false; + state.currentState = POST_TOKEN; + } + } else if (currentChar === CR) { + continue; + } else { + state.token += currentChar; + } + continue; + } // fall-through: mid-token or post-token, not escaped + + if (currentChar === CR) { + if (resp[offset] === LF) { + offset++; + } + tokenEnd(); + recordEnd(); + } else if (currentChar === LF) { + tokenEnd(); + recordEnd(); + } else if (currentChar === sep) { + tokenEnd(); + } else if (state.currentState === MID_TOKEN) { + state.token += currentChar; + } + } // set up column names + + if (header) { + t.columns = records.shift(); + } else { + for (var _i2 = 0; _i2 < records[0].length; _i2++) { + t.columns[_i2] = 'null'; + } + } + var row; + for (var _i3 = 0; _i3 < records.length; _i3++) { + //Handles row of 'undefined' at end of some CSVs + if (records[_i3].length === 1) { + if (records[_i3][0] === 'undefined' || records[_i3][0] === '') { + continue; + } + } + row = new _main.default.TableRow(); + row.arr = records[_i3]; + row.obj = makeObject(records[_i3], t.columns); + t.addRow(row); + } + if (typeof callback === 'function') { + callback(t); + } + self._decrementPreload(); + }, function (err) { + // Error handling + _main.default._friendlyFileLoadError(2, path); + if (errorCallback) { + errorCallback(err); + } else { + console.error(err); + } + }); + return t; + }; + // helper function to turn a row into a JSON object + function makeObject(row, headers) { + headers = headers || [ + ]; + if (typeof headers === 'undefined') { + for (var j = 0; j < row.length; j++) { + headers[j.toString()] = j; + } + } + return Object.fromEntries(headers.map(function (key, i) { + return [key, + row[i]]; + })); + } /** + * Loads an XML file to create a p5.XML object. + * + * Extensible Markup Language + * (XML) + * is a standard format for sending data between applications. Like HTML, the + * XML format is based on tags and attributes, as in + * `<time units="s">1234</time>`. + * + * The first parameter, `path`, is always a string with the path to the file. + * Paths to local files should be relative, as in + * `loadXML('assets/data.xml')`. URLs such as `'https://example.com/data.xml'` + * may be blocked due to browser security. + * + * The second parameter, `successCallback`, is optional. If a function is + * passed, as in `loadXML('assets/data.xml', handleData)`, then the + * `handleData()` function will be called once the data loads. The + * p5.XML object created from the data will be passed + * to `handleData()` as its only argument. + * + * The third parameter, `failureCallback`, is also optional. If a function is + * passed, as in `loadXML('assets/data.xml', handleData, handleFailure)`, then + * the `handleFailure()` function will be called if an error occurs while + * loading. The `Error` object will be passed to `handleFailure()` as its only + * argument. + * + * Note: Data can take time to load. Calling `loadXML()` within + * preload() ensures data loads before it's used in + * setup() or draw(). + * + * @method loadXML + * @param {String} path path of the XML file to be loaded. + * @param {function} [successCallback] function to call once the data is + * loaded. Will be passed the + * p5.XML object. + * @param {function} [errorCallback] function to call if the data fails to + * load. Will be passed an `Error` event + * object. + * @return {p5.XML} XML data loaded into a p5.XML + * object. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get an array with all mammal tags. + * let mammals = myXML.getChildren('mammal'); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Iterate over the mammals array. + * for (let i = 0; i < mammals.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Get the mammal's common name. + * let name = mammals[i].getContent(); + * + * // Display the mammal's name. + * text(name, 20, y); + * } + * + * describe( + * 'The words "Goat", "Leopard", and "Zebra" written on three separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + * + *
        + * + * let lastMammal; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * loadXML('assets/animals.xml', handleData); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(16); + * + * // Display the content of the last mammal element. + * text(lastMammal, 50, 50); + * + * describe('The word "Zebra" written in black on a gray background.'); + * } + * + * // Get the content of the last mammal element. + * function handleData(data) { + * // Get an array with all mammal elements. + * let mammals = data.getChildren('mammal'); + * + * // Get the content of the last mammal. + * lastMammal = mammals[mammals.length - 1].getContent(); + * } + * + *
        + * + *
        + * + * let lastMammal; + * + * // Load the XML and preprocess it. + * function preload() { + * loadXML('assets/animals.xml', handleData, handleError); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(16); + * + * // Display the content of the last mammal element. + * text(lastMammal, 50, 50); + * + * describe('The word "Zebra" written in black on a gray background.'); + * } + * + * // Get the content of the last mammal element. + * function handleData(data) { + * // Get an array with all mammal elements. + * let mammals = data.getChildren('mammal'); + * + * // Get the content of the last mammal. + * lastMammal = mammals[mammals.length - 1].getContent(); + * } + * + * // Log any errors to the console. + * function handleError(error) { + * console.error('Oops!', error); + * } + * + *
        + */ + + _main.default.prototype.loadXML = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + var ret = new _main.default.XML(); + var callback, + errorCallback; + for (var i = 1; i < args.length; i++) { + var arg = args[i]; + if (typeof arg === 'function') { + if (typeof callback === 'undefined') { + callback = arg; + } else if (typeof errorCallback === 'undefined') { + errorCallback = arg; + } + } + } + var self = this; + this.httpDo(args[0], 'GET', 'xml', function (xml) { + for (var key in xml) { + ret[key] = xml[key]; + } + if (typeof callback !== 'undefined') { + callback(ret); + } + self._decrementPreload(); + }, function (err) { + // Error handling + _main.default._friendlyFileLoadError(1, arguments[0]); + if (errorCallback) { + errorCallback(err); + } else { + throw err; + } + }); + return ret; + }; + /** + * This method is suitable for fetching files up to size of 64MB. + * @method loadBytes + * @param {string} file name of the file or URL to load + * @param {function} [callback] function to be executed after loadBytes() + * completes + * @param {function} [errorCallback] function to be executed if there + * is an error + * @returns {Object} an object whose 'bytes' property will be the loaded buffer + * + * @example + *
        + * let data; + * + * function preload() { + * data = loadBytes('assets/mammals.xml'); + * } + * + * function setup() { + * for (let i = 0; i < 5; i++) { + * console.log(data.bytes[i].toString(16)); + * } + * describe('no image displayed'); + * } + *
        + */ + _main.default.prototype.loadBytes = function (file, callback, errorCallback) { + var ret = { + }; + var self = this; + this.httpDo(file, 'GET', 'arrayBuffer', function (arrayBuffer) { + ret.bytes = new Uint8Array(arrayBuffer); + if (typeof callback === 'function') { + callback(ret); + } + self._decrementPreload(); + }, function (err) { + // Error handling + _main.default._friendlyFileLoadError(6, file); + if (errorCallback) { + errorCallback(err); + } else { + throw err; + } + }); + return ret; + }; + /** + * Method for executing an HTTP GET request. If data type is not specified, + * p5 will try to guess based on the URL, defaulting to text. This is equivalent to + * calling httpDo(path, 'GET'). The 'binary' datatype will return + * a Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer + * which can be used to initialize typed arrays (such as Uint8Array). + * + * @method httpGet + * @param {String} path name of the file or url to load + * @param {String} [datatype] "json", "jsonp", "binary", "arrayBuffer", + * "xml", or "text" + * @param {Object|Boolean} [data] param data passed sent with request + * @param {function} [callback] function to be executed after + * httpGet() completes, data is passed in + * as first argument + * @param {function} [errorCallback] function to be executed if + * there is an error, response is passed + * in as first argument + * @return {Promise} A promise that resolves with the data when the operation + * completes successfully or rejects with the error after + * one occurs. + * @example + *
        + * // Examples use USGS Earthquake API: + * // https://earthquake.usgs.gov/fdsnws/event/1/#methods + * let earthquakes; + * function preload() { + * // Get the most recent earthquake in the database + * let url = + 'https://earthquake.usgs.gov/fdsnws/event/1/query?' + + * 'format=geojson&limit=1&orderby=time'; + * httpGet(url, 'jsonp', false, function(response) { + * // when the HTTP request completes, populate the variable that holds the + * // earthquake data used in the visualization. + * earthquakes = response; + * }); + * } + * + * function draw() { + * if (!earthquakes) { + * // Wait until the earthquake data has loaded before drawing. + * return; + * } + * background(200); + * // Get the magnitude and name of the earthquake out of the loaded JSON + * let earthquakeMag = earthquakes.features[0].properties.mag; + * let earthquakeName = earthquakes.features[0].properties.place; + * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); + * textAlign(CENTER); + * text(earthquakeName, 0, height - 30, width, 30); + * noLoop(); + * } + *
        + */ + /** + * @method httpGet + * @param {String} path + * @param {Object|Boolean} data + * @param {function} [callback] + * @param {function} [errorCallback] + * @return {Promise} + */ + /** + * @method httpGet + * @param {String} path + * @param {function} callback + * @param {function} [errorCallback] + * @return {Promise} + */ + _main.default.prototype.httpGet = function () { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + _main.default._validateParameters('httpGet', args); + args.splice(1, 0, 'GET'); + return _main.default.prototype.httpDo.apply(this, args); + }; + /** + * Method for executing an HTTP POST request. If data type is not specified, + * p5 will try to guess based on the URL, defaulting to text. This is equivalent to + * calling httpDo(path, 'POST'). + * + * @method httpPost + * @param {String} path name of the file or url to load + * @param {String} [datatype] "json", "jsonp", "xml", or "text". + * If omitted, httpPost() will guess. + * @param {Object|Boolean} [data] param data passed sent with request + * @param {function} [callback] function to be executed after + * httpPost() completes, data is passed in + * as first argument + * @param {function} [errorCallback] function to be executed if + * there is an error, response is passed + * in as first argument + * @return {Promise} A promise that resolves with the data when the operation + * completes successfully or rejects with the error after + * one occurs. + * + * @example + *
        + * + * // Examples use jsonplaceholder.typicode.com for a Mock Data API + * + * let url = 'https://jsonplaceholder.typicode.com/posts'; + * let postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is very cool.' }; + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * } + * + * function mousePressed() { + * httpPost(url, 'json', postData, function(result) { + * strokeWeight(2); + * text(result.body, mouseX, mouseY); + * }); + * } + * + *
        + * + *
        + * let url = 'ttps://invalidURL'; // A bad URL that will cause errors + * let postData = { title: 'p5 Clicked!', body: 'p5.js is very cool.' }; + * + * function setup() { + * createCanvas(100, 100); + * background(200); + * } + * + * function mousePressed() { + * httpPost( + * url, + * 'json', + * postData, + * function(result) { + * // ... won't be called + * }, + * function(error) { + * strokeWeight(2); + * text(error.toString(), mouseX, mouseY); + * } + * ); + * } + *
        + */ + /** + * @method httpPost + * @param {String} path + * @param {Object|Boolean} data + * @param {function} [callback] + * @param {function} [errorCallback] + * @return {Promise} + */ + /** + * @method httpPost + * @param {String} path + * @param {function} callback + * @param {function} [errorCallback] + * @return {Promise} + */ + _main.default.prototype.httpPost = function () { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + _main.default._validateParameters('httpPost', args); + args.splice(1, 0, 'POST'); + return _main.default.prototype.httpDo.apply(this, args); + }; + /** + * Method for executing an HTTP request. If data type is not specified, + * p5 will try to guess based on the URL, defaulting to text.

        + * For more advanced use, you may also pass in the path as the first argument + * and a object as the second argument, the signature follows the one specified + * in the Fetch API specification. + * This method is suitable for fetching files up to size of 64MB when "GET" is used. + * + * @method httpDo + * @param {String} path name of the file or url to load + * @param {String} [method] either "GET", "POST", or "PUT", + * defaults to "GET" + * @param {String} [datatype] "json", "jsonp", "xml", or "text" + * @param {Object} [data] param data passed sent with request + * @param {function} [callback] function to be executed after + * httpGet() completes, data is passed in + * as first argument + * @param {function} [errorCallback] function to be executed if + * there is an error, response is passed + * in as first argument + * @return {Promise} A promise that resolves with the data when the operation + * completes successfully or rejects with the error after + * one occurs. + * + * @example + *
        + * + * // Examples use USGS Earthquake API: + * // https://earthquake.usgs.gov/fdsnws/event/1/#methods + * + * // displays an animation of all USGS earthquakes + * let earthquakes; + * let eqFeatureIndex = 0; + * + * function preload() { + * let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson'; + * httpDo( + * url, + * { + * method: 'GET', + * // Other Request options, like special headers for apis + * headers: { authorization: 'Bearer secretKey' } + * }, + * function(res) { + * earthquakes = res; + * } + * ); + * } + * + * function draw() { + * // wait until the data is loaded + * if (!earthquakes || !earthquakes.features[eqFeatureIndex]) { + * return; + * } + * clear(); + * + * let feature = earthquakes.features[eqFeatureIndex]; + * let mag = feature.properties.mag; + * let rad = mag / 11 * ((width + height) / 2); + * fill(255, 0, 0, 100); + * ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad); + * + * if (eqFeatureIndex >= earthquakes.features.length) { + * eqFeatureIndex = 0; + * } else { + * eqFeatureIndex += 1; + * } + * } + * + *
        + */ + /** + * @method httpDo + * @param {String} path + * @param {Object} options Request object options as documented in the + * "fetch" API + * reference + * @param {function} [callback] + * @param {function} [errorCallback] + * @return {Promise} + */ + _main.default.prototype.httpDo = function () { + var type; + var callback; + var errorCallback; + var request; + var promise; + var jsonpOptions = { + }; + var cbCount = 0; + var contentType = 'text/plain'; + // Trim the callbacks off the end to get an idea of how many arguments are passed + for (var i = arguments.length - 1; i > 0; i--) { + if (typeof (i < 0 || arguments.length <= i ? undefined : arguments[i]) === 'function') { + cbCount++; + } else { + break; + } + } // The number of arguments minus callbacks + + var argsCount = arguments.length - cbCount; + var path = arguments.length <= 0 ? undefined : arguments[0]; + if (argsCount === 2 && typeof path === 'string' && _typeof(arguments.length <= 1 ? undefined : arguments[1]) === 'object') { + // Intended for more advanced use, pass in Request parameters directly + request = new Request(path, arguments.length <= 1 ? undefined : arguments[1]); + callback = arguments.length <= 2 ? undefined : arguments[2]; + errorCallback = arguments.length <= 3 ? undefined : arguments[3]; + } else { + // Provided with arguments + var method = 'GET'; + var data; + for (var j = 1; j < arguments.length; j++) { + var a = j < 0 || arguments.length <= j ? undefined : arguments[j]; + if (typeof a === 'string') { + if (a === 'GET' || a === 'POST' || a === 'PUT' || a === 'DELETE') { + method = a; + } else if (a === 'json' || a === 'jsonp' || a === 'binary' || a === 'arrayBuffer' || a === 'xml' || a === 'text' || a === 'table') { + type = a; + } else { + data = a; + } + } else if (typeof a === 'number') { + data = a.toString(); + } else if (_typeof(a) === 'object') { + if (a.hasOwnProperty('jsonpCallback') || a.hasOwnProperty('jsonpCallbackFunction')) { + for (var attr in a) { + jsonpOptions[attr] = a[attr]; + } + } else if (a instanceof _main.default.XML) { + data = a.serialize(); + contentType = 'application/xml'; + } else { + data = JSON.stringify(a); + contentType = 'application/json'; + } + } else if (typeof a === 'function') { + if (!callback) { + callback = a; + } else { + errorCallback = a; + } + } + } + var headers = method === 'GET' ? new Headers() : new Headers({ + 'Content-Type': contentType + }); + request = new Request(path, { + method: method, + mode: 'cors', + body: data, + headers: headers + }); + } // do some sort of smart type checking + + if (!type) { + if (path.includes('json')) { + type = 'json'; + } else if (path.includes('xml')) { + type = 'xml'; + } else { + type = 'text'; + } + } + if (type === 'jsonp') { + promise = (0, _fetchJsonp.default) (path, jsonpOptions); + } else { + promise = fetch(request); + } + promise = promise.then(function (res) { + if (!res.ok) { + var err = new Error(res.body); + err.status = res.status; + err.ok = false; + throw err; + } else { + var fileSize = 0; + if (type !== 'jsonp') { + fileSize = res.headers.get('content-length'); + } + if (fileSize && fileSize > 64000000) { + _main.default._friendlyFileLoadError(7, path); + } + switch (type) { + case 'json': + case 'jsonp': + return res.json(); + case 'binary': + return res.blob(); + case 'arrayBuffer': + return res.arrayBuffer(); + case 'xml': + return res.text().then(function (text) { + var parser = new DOMParser(); + var xml = parser.parseFromString(text, 'text/xml'); + return new _main.default.XML(xml.documentElement); + }); + default: + return res.text(); + } + } + }); + promise.then(callback || function () { + }); + promise.catch(errorCallback || console.error); + return promise; + }; + /** + * @module IO + * @submodule Output + * @for p5 + */ + window.URL = window.URL || window.webkitURL; + // private array of p5.PrintWriter objects + _main.default.prototype._pWriters = [ + ]; + /** + * Creates a new p5.PrintWriter object. + * + * p5.PrintWriter objects provide a way to + * save a sequence of text data, called the *print stream*, to the user's + * computer. They're low-level objects that enable precise control of text + * output. Functions such as + * saveStrings() and + * saveJSON() are easier to use for simple file + * saving. + * + * The first parameter, `filename`, is the name of the file to be written. If + * a string is passed, as in `createWriter('words.txt')`, a new + * p5.PrintWriter object will be created that + * writes to a file named `words.txt`. + * + * The second parameter, `extension`, is optional. If a string is passed, as + * in `createWriter('words', 'csv')`, the first parameter will be interpreted + * as the file name and the second parameter as the extension. + * + * @method createWriter + * @param {String} name name of the file to create. + * @param {String} [extension] format to use for the file. + * @return {p5.PrintWriter} stream for writing data. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * // Create a p5.PrintWriter object. + * let myWriter = createWriter('xo.txt'); + * + * // Add some lines to the print stream. + * myWriter.print('XOO'); + * myWriter.print('OXO'); + * myWriter.print('OOX'); + * + * // Save the file and close the print stream. + * myWriter.close(); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * // Create a p5.PrintWriter object. + * // Use the file format .csv. + * let myWriter = createWriter('mauna_loa_co2', 'csv'); + * + * // Add some lines to the print stream. + * myWriter.print('date,ppm_co2'); + * myWriter.print('1960-01-01,316.43'); + * myWriter.print('1970-01-01,325.06'); + * myWriter.print('1980-01-01,337.9'); + * myWriter.print('1990-01-01,353.86'); + * myWriter.print('2000-01-01,369.45'); + * myWriter.print('2020-01-01,413.61'); + * + * // Save the file and close the print stream. + * myWriter.close(); + * } + * } + * + *
        + */ + _main.default.prototype.createWriter = function (name, extension) { + var newPW; + // check that it doesn't already exist + for (var i in _main.default.prototype._pWriters) { + if (_main.default.prototype._pWriters[i].name === name) { + // if a p5.PrintWriter w/ this name already exists... + // return p5.prototype._pWriters[i]; // return it w/ contents intact. + // or, could return a new, empty one with a unique name: + newPW = new _main.default.PrintWriter(name + this.millis(), extension); + _main.default.prototype._pWriters.push(newPW); + return newPW; + } + } + newPW = new _main.default.PrintWriter(name, extension); + _main.default.prototype._pWriters.push(newPW); + return newPW; + }; + /** + * A class to describe a print stream. + * + * Each `p5.PrintWriter` object provides a way to save a sequence of text + * data, called the *print stream*, to the user's computer. It's a low-level + * object that enables precise control of text output. Functions such as + * saveStrings() and + * saveJSON() are easier to use for simple file + * saving. + * + * Note: createWriter() is the recommended way + * to make an instance of this class. + * + * @class p5.PrintWriter + * @param {String} filename name of the file to create. + * @param {String} [extension] format to use for the file. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * // Create a p5.PrintWriter object. + * let myWriter = createWriter('xo.txt'); + * + * // Add some lines to the print stream. + * myWriter.print('XOO'); + * myWriter.print('OXO'); + * myWriter.print('OOX'); + * + * // Save the file and close the print stream. + * myWriter.close(); + * } + * + *
        + */ + _main.default.PrintWriter = function (filename, extension) { + var self = this; + this.name = filename; + this.content = ''; + /** + * Writes data to the print stream without adding new lines. + * + * The parameter, `data`, is the data to write. `data` can be a number or + * string, as in `myWriter.write('hi')`, or an array of numbers and strings, + * as in `myWriter.write([1, 2, 3])`. A comma will be inserted between array + * array elements when they're added to the print stream. + * + * @method write + * @param {String|Number|Array} data data to be written as a string, number, + * or array of strings and numbers. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * // Create a p5.PrintWriter object. + * let myWriter = createWriter('numbers.txt'); + * + * // Add some data to the print stream. + * myWriter.write('1,2,3,'); + * myWriter.write(['4', '5', '6']); + * + * // Save the file and close the print stream. + * myWriter.close(); + * } + * + *
        + */ + this.write = function (data) { + this.content += data; + }; + /** + * Writes data to the print stream with new lines added. + * + * The parameter, `data`, is the data to write. `data` can be a number or + * string, as in `myWriter.print('hi')`, or an array of numbers and strings, + * as in `myWriter.print([1, 2, 3])`. A comma will be inserted between array + * array elements when they're added to the print stream. + * + * @method print + * @param {String|Number|Array} data data to be written as a string, number, + * or array of strings and numbers. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * // Create a p5.PrintWriter object. + * let myWriter = createWriter('numbers.txt'); + * + * // Add some data to the print stream. + * myWriter.print('1,2,3,'); + * myWriter.print(['4', '5', '6']); + * + * // Save the file and close the print stream. + * myWriter.close(); + * } + * + *
        + */ + this.print = function (data) { + this.content += ''.concat(data, '\n'); + }; + /** + * Clears all data from the print stream. + * + * @method clear + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * // Create a p5.PrintWriter object. + * let myWriter = createWriter('numbers.txt'); + * + * // Add some data to the print stream. + * myWriter.print('Hello p5*js!'); + * + * // Clear the print stream. + * myWriter.clear(); + * + * // Save the file and close the print stream. + * myWriter.close(); + * } + * + *
        + */ + this.clear = function () { + this.content = ''; + }; + /** + * Saves the file and closes the print stream. + * + * @method close + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * // Create a p5.PrintWriter object. + * let myWriter = createWriter('cat.txt'); + * + * // Add some data to the print stream. + * // ASCII art courtesy Wikipedia: + * // https://en.wikipedia.org/wiki/ASCII_art + * myWriter.print(' (\\_/) '); + * myWriter.print("(='.'=)"); + * myWriter.print('(")_(")'); + * + * // Save the file and close the print stream. + * myWriter.close(); + * } + * + *
        + */ + this.close = function () { + // convert String to Array for the writeFile Blob + var arr = [ + ]; + arr.push(this.content); + _main.default.prototype.writeFile(arr, filename, extension); + // remove from _pWriters array and delete self + for (var i in _main.default.prototype._pWriters) { + if (_main.default.prototype._pWriters[i].name === this.name) { + // remove from _pWriters array + _main.default.prototype._pWriters.splice(i, 1); + } + } + self.clear(); + self = { + }; + }; + }; + /** + * @module IO + * @submodule Output + * @for p5 + */ + // object, filename, options --> saveJSON, saveStrings, + // filename, [extension] [canvas] --> saveImage + /** + * Saves a given element(image, text, json, csv, wav, or html) to the client's + * computer. The first parameter can be a pointer to element we want to save. + * The element can be one of p5.Element,an Array of + * Strings, an Array of JSON, a JSON object, a p5.Table + * , a p5.Image, or a p5.SoundFile (requires + * p5.sound). The second parameter is a filename (including extension).The + * third parameter is for options specific to this type of object. This method + * will save a file that fits the given parameters. + * If it is called without specifying an element, by default it will save the + * whole canvas as an image file. You can optionally specify a filename as + * the first parameter in such a case. + * **Note that it is not recommended to + * call this method within draw, as it will open a new save dialog on every + * render.** + * + * @method save + * @param {Object|String} [objectOrFilename] If filename is provided, will + * save canvas as an image with + * either png or jpg extension + * depending on the filename. + * If object is provided, will + * save depending on the object + * and filename (see examples + * above). + * @param {String} [filename] If an object is provided as the first + * parameter, then the second parameter + * indicates the filename, + * and should include an appropriate + * file extension (see examples above). + * @param {Boolean|String} [options] Additional options depend on + * filetype. For example, when saving JSON, + * true indicates that the + * output will be optimized for filesize, + * rather than readability. + * + * @example + *
        + * // Saves the canvas as an image + * cnv = createCanvas(300, 300); + * save(cnv, 'myCanvas.jpg'); + * + * // Saves the canvas as an image by default + * save('myCanvas.jpg'); + * describe('An example for saving a canvas as an image.'); + *
        + * + *
        + * // Saves p5.Image as an image + * img = createImage(10, 10); + * save(img, 'myImage.png'); + * describe('An example for saving a p5.Image element as an image.'); + *
        + * + *
        + * // Saves p5.Renderer object as an image + * obj = createGraphics(100, 100); + * save(obj, 'myObject.png'); + * describe('An example for saving a p5.Renderer element.'); + *
        + * + *
        + * let myTable = new p5.Table(); + * // Saves table as html file + * save(myTable, 'myTable.html'); + * + * // Comma Separated Values + * save(myTable, 'myTable.csv'); + * + * // Tab Separated Values + * save(myTable, 'myTable.tsv'); + * + * describe(`An example showing how to save a table in formats of + * HTML, CSV and TSV.`); + *
        + * + *
        + * let myJSON = { a: 1, b: true }; + * + * // Saves pretty JSON + * save(myJSON, 'my.json'); + * + * // Optimizes JSON filesize + * save(myJSON, 'my.json', true); + * + * describe('An example for saving JSON to a txt file with some extra arguments.'); + *
        + * + *
        + * // Saves array of strings to text file with line breaks after each item + * let arrayOfStrings = ['a', 'b']; + * save(arrayOfStrings, 'my.txt'); + * describe(`An example for saving an array of strings to text file + * with line breaks.`); + *
        + */ + _main.default.prototype.save = function (object, _filename, _options) { + // parse the arguments and figure out which things we are saving + var args = arguments; + // ================================================= + // OPTION 1: saveCanvas... + // if no arguments are provided, save canvas + var cnv = this._curElement ? this._curElement.elt : this.elt; + if (args.length === 0) { + _main.default.prototype.saveCanvas(cnv); + return; + } else if (args[0] instanceof _main.default.Renderer || args[0] instanceof _main.default.Graphics) { + // otherwise, parse the arguments + // if first param is a p5Graphics, then saveCanvas + _main.default.prototype.saveCanvas(args[0].elt, args[1], args[2]); + return; + } else if (args.length === 1 && typeof args[0] === 'string') { + // if 1st param is String and only one arg, assume it is canvas filename + _main.default.prototype.saveCanvas(cnv, args[0]); + } else { + // ================================================= + // OPTION 2: extension clarifies saveStrings vs. saveJSON + var extension = _checkFileExtension(args[1], args[2]) [1]; + switch (extension) { + case 'json': + _main.default.prototype.saveJSON(args[0], args[1], args[2]); + return; + case 'txt': + _main.default.prototype.saveStrings(args[0], args[1], args[2]); + return; + // ================================================= + // OPTION 3: decide based on object... + default: + if (args[0] instanceof Array) { + _main.default.prototype.saveStrings(args[0], args[1], args[2]); + } else if (args[0] instanceof _main.default.Table) { + _main.default.prototype.saveTable(args[0], args[1], args[2]); + } else if (args[0] instanceof _main.default.Image) { + _main.default.prototype.saveCanvas(args[0].canvas, args[1]); + } else if (args[0] instanceof _main.default.SoundFile) { + _main.default.prototype.saveSound(args[0], args[1], args[2], args[3]); + } + } + } + }; + /** + * Saves an `Object` or `Array` to a JSON file. + * + * JavaScript Object Notation + * (JSON) + * is a standard format for sending data between applications. The format is + * based on JavaScript objects which have keys and values. JSON files store + * data in an object with strings as keys. Values can be strings, numbers, + * Booleans, arrays, `null`, or other objects. + * + * The first parameter, `json`, is the data to save. The data can be an array, + * as in `[1, 2, 3]`, or an object, as in + * `{ x: 50, y: 50, color: 'deeppink' }`. + * + * The second parameter, `filename`, is a string that sets the file's name. + * For example, calling `saveJSON([1, 2, 3], 'data.json')` saves the array + * `[1, 2, 3]` to a file called `data.json` on the user's computer. + * + * The third parameter, `optimize`, is optional. If `true` is passed, as in + * `saveJSON([1, 2, 3], 'data.json', true)`, then all unneeded whitespace will + * be removed to reduce the file size. + * + * Note: The browser will either save the file immediately or prompt the user + * with a dialogue window. + * + * @method saveJSON + * @param {Array|Object} json data to save. + * @param {String} filename name of the file to be saved. + * @param {Boolean} [optimize] whether to trim unneeded whitespace. Defaults + * to `true`. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * // Create an array. + * let data = [1, 2, 3]; + * + * // Save the JSON file. + * saveJSON(data, 'numbers.json'); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * // Create an object. + * let data = { x: mouseX, y: mouseY }; + * + * // Save the JSON file. + * saveJSON(data, 'state.json'); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * // Create an object. + * let data = { x: mouseX, y: mouseY }; + * + * // Save the JSON file and reduce its size. + * saveJSON(data, 'state.json', true); + * } + * } + * + *
        + */ + _main.default.prototype.saveJSON = function (json, filename, opt) { + _main.default._validateParameters('saveJSON', arguments); + var stringify; + if (opt) { + stringify = JSON.stringify(json); + } else { + stringify = JSON.stringify(json, undefined, 2); + } + this.saveStrings(stringify.split('\n'), filename, 'json'); + }; + _main.default.prototype.saveJSONObject = _main.default.prototype.saveJSON; + _main.default.prototype.saveJSONArray = _main.default.prototype.saveJSON; + /** + * Saves an `Array` of `String`s to a file, one per line. + * + * The first parameter, `list`, is an array with the strings to save. + * + * The second parameter, `filename`, is a string that sets the file's name. + * For example, calling `saveStrings(['0', '01', '011'], 'data.txt')` saves + * the array `['0', '01', '011']` to a file called `data.txt` on the user's + * computer. + * + * The third parameter, `extension`, is optional. If a string is passed, as in + * `saveStrings(['0', '01', '0`1'], 'data', 'txt')`, the second parameter will + * be interpreted as the file name and the third parameter as the extension. + * + * The fourth parameter, `isCRLF`, is also optional, If `true` is passed, as + * in `saveStrings(['0', '01', '011'], 'data', 'txt', true)`, then two + * characters, `\r\n` , will be added to the end of each string to create new + * lines in the saved file. `\r` is a carriage return (CR) and `\n` is a line + * feed (LF). By default, only `\n` (line feed) is added to each string in + * order to create new lines. + * + * Note: The browser will either save the file immediately or prompt the user + * with a dialogue window. + * + * @method saveStrings + * @param {String[]} list data to save. + * @param {String} filename name of file to be saved. + * @param {String} [extension] format to use for the file. + * @param {Boolean} [isCRLF] whether to add `\r\n` to the end of each + * string. Defaults to `false`. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * // Create an array. + * let data = ['0', '01', '011']; + * + * // Save the text file. + * saveStrings(data, 'data.txt'); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * // Create an array. + * // ASCII art courtesy Wikipedia: + * // https://en.wikipedia.org/wiki/ASCII_art + * let data = [' (\\_/) ', "(='.'=)", '(")_(")']; + * + * // Save the text file. + * saveStrings(data, 'cat', 'txt'); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { + * // Create an array. + * // +--+ + * // / /| + * // +--+ + + * // | |/ + * // +--+ + * let data = [' +--+', ' / /|', '+--+ +', '| |/', '+--+']; + * + * // Save the text file. + * // Use CRLF for line endings. + * saveStrings(data, 'box', 'txt', true); + * } + * } + * + *
        + */ + _main.default.prototype.saveStrings = function (list, filename, extension, isCRLF) { + _main.default._validateParameters('saveStrings', arguments); + var ext = extension || 'txt'; + var pWriter = this.createWriter(filename, ext); + for (var i = 0; i < list.length; i++) { + isCRLF ? pWriter.write(list[i] + '\r\n') : pWriter.write(list[i] + '\n'); + } + pWriter.close(); + pWriter.clear(); + }; + // ======= + // HELPERS + // ======= + function escapeHelper(content) { + return content.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); + } /** + * Writes the contents of a Table object to a file. Defaults to a + * text file with comma-separated-values ('csv') but can also + * use tab separation ('tsv'), or generate an HTML table ('html'). + * The file saving process and location of the saved file will + * vary between web browsers. + * + * @method saveTable + * @param {p5.Table} Table the Table object to save to a file + * @param {String} filename the filename to which the Table should be saved + * @param {String} [options] can be one of "tsv", "csv", or "html" + * @example + *
        + * let table; + * + * function setup() { + * table = new p5.Table(); + * + * table.addColumn('id'); + * table.addColumn('species'); + * table.addColumn('name'); + * + * let newRow = table.addRow(); + * newRow.setNum('id', table.getRowCount() - 1); + * newRow.setString('species', 'Panthera leo'); + * newRow.setString('name', 'Lion'); + * + * // To save, un-comment next line then click 'run' + * // saveTable(table, 'new.csv'); + * + * describe('no image displayed'); + * } + * + * // Saves the following to a file called 'new.csv': + * // id,species,name + * // 0,Panthera leo,Lion + *
        + */ + + _main.default.prototype.saveTable = function (table, filename, options) { + _main.default._validateParameters('saveTable', arguments); + var ext; + if (options === undefined) { + ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length); + } else { + ext = options; + } + var pWriter = this.createWriter(filename, ext); + var header = table.columns; + var sep = ','; // default to CSV + if (ext === 'tsv') { + sep = '\t'; + } + if (ext !== 'html') { + // make header if it has values + if (header[0] !== '0') { + for (var h = 0; h < header.length; h++) { + if (h < header.length - 1) { + pWriter.write(header[h] + sep); + } else { + pWriter.write(header[h]); + } + } + pWriter.write('\n'); + } // make rows + + for (var i = 0; i < table.rows.length; i++) { + var j = void 0; + for (j = 0; j < table.rows[i].arr.length; j++) { + if (j < table.rows[i].arr.length - 1) { + //double quotes should be inserted in csv only if contains comma separated single value + if (ext === 'csv' && String(table.rows[i].arr[j]).includes(',')) { + pWriter.write('"' + table.rows[i].arr[j] + '"' + sep); + } else { + pWriter.write(table.rows[i].arr[j] + sep); + } + } else { + //double quotes should be inserted in csv only if contains comma separated single value + if (ext === 'csv' && String(table.rows[i].arr[j]).includes(',')) { + pWriter.write('"' + table.rows[i].arr[j] + '"'); + } else { + pWriter.write(table.rows[i].arr[j]); + } + } + } + pWriter.write('\n'); + } + } else { + // otherwise, make HTML + pWriter.print(''); + pWriter.print(''); + var str = ' '); + pWriter.print(''); + pWriter.print(' '); + // make header if it has values + if (header[0] !== '0') { + pWriter.print(' '); + for (var k = 0; k < header.length; k++) { + var e = escapeHelper(header[k]); + pWriter.print(' '); + } + pWriter.print(' '); + } // make rows + + for (var row = 0; row < table.rows.length; row++) { + pWriter.print(' '); + for (var col = 0; col < table.columns.length; col++) { + var entry = table.rows[row].getString(col); + var htmlEntry = escapeHelper(entry); + pWriter.print(' '); + } + pWriter.print(' '); + } + pWriter.print('
        '.concat(e)); + pWriter.print('
        '.concat(htmlEntry)); + pWriter.print('
        '); + pWriter.print(''); + pWriter.print(''); + } // close and clear the pWriter + + pWriter.close(); + pWriter.clear(); + }; // end saveTable() + /** + * Generate a blob of file data as a url to prepare for download. + * Accepts an array of data, a filename, and an extension (optional). + * This is a private function because it does not do any formatting, + * but it is used by saveStrings, saveJSON, saveTable etc. + * + * @param {Array} dataToDownload + * @param {String} filename + * @param {String} [extension] + * @private + */ + _main.default.prototype.writeFile = function (dataToDownload, filename, extension) { + var type = 'application/octet-stream'; + if (_main.default.prototype._isSafari()) { + type = 'text/plain'; + } + var blob = new Blob(dataToDownload, { + type: type + }); + _main.default.prototype.downloadFile(blob, filename, extension); + }; + /** + * Forces download. Accepts a url to filedata/blob, a filename, + * and an extension (optional). + * This is a private function because it does not do any formatting, + * but it is used by saveStrings, saveJSON, saveTable etc. + * + * @method downloadFile + * @private + * @param {String|Blob} data either an href generated by createObjectURL, + * or a Blob object containing the data + * @param {String} [filename] + * @param {String} [extension] + */ + _main.default.prototype.downloadFile = function (data, fName, extension) { + var fx = _checkFileExtension(fName, extension); + var filename = fx[0]; + if (data instanceof Blob) { + _fileSaver.default.saveAs(data, filename); + return; + } + var a = document.createElement('a'); + a.href = data; + a.download = filename; + // Firefox requires the link to be added to the DOM before click() + a.onclick = function (e) { + destroyClickedElement(e); + e.stopPropagation(); + }; + a.style.display = 'none'; + document.body.appendChild(a); + // Safari will open this file in the same page as a confusing Blob. + if (_main.default.prototype._isSafari()) { + var aText = 'Hello, Safari user! To download this file...\n'; + aText += '1. Go to File --> Save As.\n'; + aText += '2. Choose "Page Source" as the Format.\n'; + aText += '3. Name it with this extension: ."'.concat(fx[1], '"'); + alert(aText); + } + a.click(); + }; + /** + * Returns a file extension, or another string + * if the provided parameter has no extension. + * + * @param {String} filename + * @param {String} [extension] + * @return {String[]} [fileName, fileExtension] + * + * @private + */ + function _checkFileExtension(filename, extension) { + if (!extension || extension === true || extension === 'true') { + extension = ''; + } + if (!filename) { + filename = 'untitled'; + } + var ext = ''; + // make sure the file will have a name, see if filename needs extension + if (filename && filename.includes('.')) { + ext = filename.split('.').pop(); + } // append extension if it doesn't exist + + if (extension) { + if (ext !== extension) { + ext = extension; + filename = ''.concat(filename, '.').concat(ext); + } + } + return [filename, + ext]; + } + _main.default.prototype._checkFileExtension = _checkFileExtension; + /** + * Returns true if the browser is Safari, false if not. + * Safari makes trouble for downloading files. + * + * @return {Boolean} [description] + * @private + */ + _main.default.prototype._isSafari = function () { + return window.HTMLElement.toString().includes('Constructor'); + }; + /** + * Helper function, a callback for download that deletes + * an invisible anchor element from the DOM once the file + * has been automatically downloaded. + * + * @private + */ + function destroyClickedElement(event) { + document.body.removeChild(event.target); + } + var _default = _main.default; + exports.default = _default; + }, + { + '../core/friendly_errors/fes_core': 294, + '../core/friendly_errors/file_errors': 295, + '../core/friendly_errors/validate_params': 298, + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.last-index-of': 184, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.splice': 188, + 'core-js/modules/es.function.name': 191, + 'core-js/modules/es.object.from-entries': 200, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.promise': 206, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254, + 'core-js/modules/es.typed-array.uint8-array': 257, + 'core-js/modules/web.dom-collections.iterator': 261, + 'core-js/modules/web.url': 263, + 'es6-promise/auto': 264, + 'fetch-jsonp': 266, + 'file-saver': 267, + 'whatwg-fetch': 280 + } + ], + 330: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.replace'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * @module IO + * @submodule Table + * @requires core + */ + /** + * Table Options + * Generic class for handling tabular data, typically from a + * CSV, TSV, or other sort of spreadsheet file. + * CSV files are + * + * comma separated values, often with the data in quotes. TSV + * files use tabs as separators, and usually don't bother with the + * quotes. + * File names should end with .csv if they're comma separated. + * A rough "spec" for CSV can be found + * here. + * To load files, use the loadTable method. + * To save tables to your computer, use the save method + * or the saveTable method. + * + * Possible options include: + *
          + *
        • csv - parse the table as comma-separated values + *
        • tsv - parse the table as tab-separated values + *
        • header - this table has a header (title) row + *
        + */ + /** + * Table objects store data with multiple rows and columns, much + * like in a traditional spreadsheet. Tables can be generated from + * scratch, dynamically, or using data from an existing file. + * + * @class p5.Table + * @constructor + * @param {p5.TableRow[]} [rows] An array of p5.TableRow objects + */ + + _main.default.Table = /*#__PURE__*/ function () { + /** + * An array containing the names of the columns in the table, if the "header" the table is + * loaded with the "header" parameter. + * @type {String[]} + * @property columns + * @name columns + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //print the column names + * for (let c = 0; c < table.getColumnCount(); c++) { + * print('column ' + c + ' is named ' + table.columns[c]); + * } + * } + * + *
        + */ + function _class() { + var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [ + ]; + _classCallCheck(this, _class); + this.columns = [ + ]; + /** + * An array containing the p5.TableRow objects that make up the + * rows of the table. The same result as calling getRows() + * @type {p5.TableRow[]} + * @property rows + * @name rows + */ + this.rows = rows; + } /** + * Use addRow() to add a new row of data to a p5.Table object. By default, + * an empty row is created. Typically, you would store a reference to + * the new row in a TableRow object (see newRow in the example above), + * and then set individual values using set(). + * + * If a p5.TableRow object is included as a parameter, then that row is + * duplicated and added to the table. + * + * @method addRow + * @param {p5.TableRow} [row] row to be added to the table + * @return {p5.TableRow} the row that was added + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //add a row + * let newRow = table.addRow(); + * newRow.setString('id', table.getRowCount() - 1); + * newRow.setString('species', 'Canis Lupus'); + * newRow.setString('name', 'Wolf'); + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
        + */ + + _createClass(_class, [ + { + key: 'addRow', + value: function addRow(row) { + // make sure it is a valid TableRow + var r = row || new _main.default.TableRow(); + if (typeof r.arr === 'undefined' || typeof r.obj === 'undefined') { + //r = new p5.prototype.TableRow(r); + throw new Error('invalid TableRow: '.concat(r)); + } + r.table = this; + this.rows.push(r); + return r; + } /** + * Removes a row from the table object. + * + * @method removeRow + * @param {Integer} id ID number of the row to remove + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //remove the first row + * table.removeRow(0); + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'removeRow', + value: function removeRow(id) { + this.rows[id].table = null; // remove reference to table + var chunk = this.rows.splice(id + 1, this.rows.length); + this.rows.pop(); + this.rows = this.rows.concat(chunk); + } /** + * Returns a reference to the specified p5.TableRow. The reference + * can then be used to get and set values of the selected row. + * + * @method getRow + * @param {Integer} rowID ID number of the row to get + * @return {p5.TableRow} p5.TableRow object + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let row = table.getRow(1); + * //print it column by column + * //note: a row is an object, not an array + * for (let c = 0; c < table.getColumnCount(); c++) { + * print(row.getString(c)); + * } + * + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'getRow', + value: function getRow(r) { + return this.rows[r]; + } /** + * Gets all rows from the table. Returns an array of p5.TableRows. + * + * @method getRows + * @return {p5.TableRow[]} Array of p5.TableRows + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * + * //warning: rows is an array of objects + * for (let r = 0; r < rows.length; r++) { + * rows[r].set('name', 'Unicorn'); + * } + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'getRows', + value: function getRows() { + return this.rows; + } /** + * Finds the first row in the Table that contains the value + * provided, and returns a reference to that row. Even if + * multiple rows are possible matches, only the first matching + * row is returned. The column to search may be specified by + * either its ID or title. + * + * @method findRow + * @param {String} value The value to match + * @param {Integer|String} column ID number or title of the + * column to search + * @return {p5.TableRow} + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //find the animal named zebra + * let row = table.findRow('Zebra', 'name'); + * //find the corresponding species + * print(row.getString('species')); + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'findRow', + value: function findRow(value, column) { + // try the Object + if (typeof column === 'string') { + for (var i = 0; i < this.rows.length; i++) { + if (this.rows[i].obj[column] === value) { + return this.rows[i]; + } + } + } else { + // try the Array + for (var j = 0; j < this.rows.length; j++) { + if (this.rows[j].arr[column] === value) { + return this.rows[j]; + } + } + } // otherwise... + + return null; + } /** + * Finds the rows in the Table that contain the value + * provided, and returns references to those rows. Returns an + * Array, so for must be used to iterate through all the rows, + * as shown in the example above. The column to search may be + * specified by either its ID or title. + * + * @method findRows + * @param {String} value The value to match + * @param {Integer|String} column ID number or title of the + * column to search + * @return {p5.TableRow[]} An Array of TableRow objects + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //add another goat + * let newRow = table.addRow(); + * newRow.setString('id', table.getRowCount() - 1); + * newRow.setString('species', 'Scape Goat'); + * newRow.setString('name', 'Goat'); + * + * //find the rows containing animals named Goat + * let rows = table.findRows('Goat', 'name'); + * print(rows.length + ' Goats found'); + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'findRows', + value: function findRows(value, column) { + var ret = [ + ]; + if (typeof column === 'string') { + for (var i = 0; i < this.rows.length; i++) { + if (this.rows[i].obj[column] === value) { + ret.push(this.rows[i]); + } + } + } else { + // try the Array + for (var j = 0; j < this.rows.length; j++) { + if (this.rows[j].arr[column] === value) { + ret.push(this.rows[j]); + } + } + } + return ret; + } /** + * Finds the first row in the Table that matches the regular + * expression provided, and returns a reference to that row. + * Even if multiple rows are possible matches, only the first + * matching row is returned. The column to search may be + * specified by either its ID or title. + * + * @method matchRow + * @param {String|RegExp} regexp The regular expression to match + * @param {String|Integer} column The column ID (number) or + * title (string) + * @return {p5.TableRow} TableRow object + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //Search using specified regex on a given column, return TableRow object + * let mammal = table.matchRow(new RegExp('ant'), 1); + * print(mammal.getString(1)); + * //Output "Panthera pardus" + * } + * + *
        + */ + + }, + { + key: 'matchRow', + value: function matchRow(regexp, column) { + if (typeof column === 'number') { + for (var j = 0; j < this.rows.length; j++) { + if (this.rows[j].arr[column].match(regexp)) { + return this.rows[j]; + } + } + } else { + for (var i = 0; i < this.rows.length; i++) { + if (this.rows[i].obj[column].match(regexp)) { + return this.rows[i]; + } + } + } + return null; + } /** + * Finds the rows in the Table that match the regular expression provided, + * and returns references to those rows. Returns an array, so for must be + * used to iterate through all the rows, as shown in the example. The + * column to search may be specified by either its ID or title. + * + * @method matchRows + * @param {String} regexp The regular expression to match + * @param {String|Integer} [column] The column ID (number) or + * title (string) + * @return {p5.TableRow[]} An Array of TableRow objects + * @example + *
        + * + * let table; + * + * function setup() { + * table = new p5.Table(); + * + * table.addColumn('name'); + * table.addColumn('type'); + * + * let newRow = table.addRow(); + * newRow.setString('name', 'Lion'); + * newRow.setString('type', 'Mammal'); + * + * newRow = table.addRow(); + * newRow.setString('name', 'Snake'); + * newRow.setString('type', 'Reptile'); + * + * newRow = table.addRow(); + * newRow.setString('name', 'Mosquito'); + * newRow.setString('type', 'Insect'); + * + * newRow = table.addRow(); + * newRow.setString('name', 'Lizard'); + * newRow.setString('type', 'Reptile'); + * + * let rows = table.matchRows('R.*', 'type'); + * for (let i = 0; i < rows.length; i++) { + * print(rows[i].getString('name') + ': ' + rows[i].getString('type')); + * } + * } + * // Sketch prints: + * // Snake: Reptile + * // Lizard: Reptile + * + *
        + */ + + }, + { + key: 'matchRows', + value: function matchRows(regexp, column) { + var ret = [ + ]; + if (typeof column === 'number') { + for (var j = 0; j < this.rows.length; j++) { + if (this.rows[j].arr[column].match(regexp)) { + ret.push(this.rows[j]); + } + } + } else { + for (var i = 0; i < this.rows.length; i++) { + if (this.rows[i].obj[column].match(regexp)) { + ret.push(this.rows[i]); + } + } + } + return ret; + } /** + * Retrieves all values in the specified column, and returns them + * as an array. The column may be specified by either its ID or title. + * + * @method getColumn + * @param {String|Number} column String or Number of the column to return + * @return {Array} Array of column values + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //getColumn returns an array that can be printed directly + * print(table.getColumn('species')); + * //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"] + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'getColumn', + value: function getColumn(value) { + var ret = [ + ]; + if (typeof value === 'string') { + for (var i = 0; i < this.rows.length; i++) { + ret.push(this.rows[i].obj[value]); + } + } else { + for (var j = 0; j < this.rows.length; j++) { + ret.push(this.rows[j].arr[value]); + } + } + return ret; + } /** + * Removes all rows from a Table. While all rows are removed, + * columns and column titles are maintained. + * + * @method clearRows + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.clearRows(); + * print(table.getRowCount() + ' total rows in table'); + * print(table.getColumnCount() + ' total columns in table'); + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'clearRows', + value: function clearRows() { + delete this.rows; + this.rows = [ + ]; + } /** + * Use addColumn() to add a new column to a Table object. + * Typically, you will want to specify a title, so the column + * may be easily referenced later by name. (If no title is + * specified, the new column's title will be null.) + * + * @method addColumn + * @param {String} [title] title of the given column + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.addColumn('carnivore'); + * table.set(0, 'carnivore', 'no'); + * table.set(1, 'carnivore', 'yes'); + * table.set(2, 'carnivore', 'no'); + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'addColumn', + value: function addColumn(title) { + var t = title || null; + this.columns.push(t); + } /** + * Returns the total number of columns in a Table. + * + * @method getColumnCount + * @return {Integer} Number of columns in this table + * @example + *
        + * + * // given the cvs file "blobs.csv" in /assets directory + * // ID, Name, Flavor, Shape, Color + * // Blob1, Blobby, Sweet, Blob, Pink + * // Blob2, Saddy, Savory, Blob, Blue + * + * let table; + * + * function preload() { + * table = loadTable('assets/blobs.csv'); + * } + * + * function setup() { + * createCanvas(200, 100); + * textAlign(CENTER); + * background(255); + * } + * + * function draw() { + * let numOfColumn = table.getColumnCount(); + * text('There are ' + numOfColumn + ' columns in the table.', 100, 50); + * } + * + *
        + */ + + }, + { + key: 'getColumnCount', + value: function getColumnCount() { + return this.columns.length; + } /** + * Returns the total number of rows in a Table. + * + * @method getRowCount + * @return {Integer} Number of rows in this table + * @example + *
        + * + * // given the cvs file "blobs.csv" in /assets directory + * // + * // ID, Name, Flavor, Shape, Color + * // Blob1, Blobby, Sweet, Blob, Pink + * // Blob2, Saddy, Savory, Blob, Blue + * + * let table; + * + * function preload() { + * table = loadTable('assets/blobs.csv'); + * } + * + * function setup() { + * createCanvas(200, 100); + * textAlign(CENTER); + * background(255); + * } + * + * function draw() { + * text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50); + * } + * + *
        + */ + + }, + { + key: 'getRowCount', + value: function getRowCount() { + return this.rows.length; + } /** + * Removes any of the specified characters (or "tokens"). + * + * If no column is specified, then the values in all columns and + * rows are processed. A specific column may be referenced by + * either its ID or title. + * + * @method removeTokens + * @param {String} chars String listing characters to be removed + * @param {String|Integer} [column] Column ID (number) + * or name (string) + * + * @example + *
        + * function setup() { + * let table = new p5.Table(); + * + * table.addColumn('name'); + * table.addColumn('type'); + * + * let newRow = table.addRow(); + * newRow.setString('name', ' $Lion ,'); + * newRow.setString('type', ',,,Mammal'); + * + * newRow = table.addRow(); + * newRow.setString('name', '$Snake '); + * newRow.setString('type', ',,,Reptile'); + * + * table.removeTokens(',$ '); + * print(table.getArray()); + * } + * + * // prints: + * // 0 "Lion" "Mamal" + * // 1 "Snake" "Reptile" + *
        + */ + + }, + { + key: 'removeTokens', + value: function removeTokens(chars, column) { + var escape = function escape(s) { + return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); + }; + var charArray = [ + ]; + for (var i = 0; i < chars.length; i++) { + charArray.push(escape(chars.charAt(i))); + } + var regex = new RegExp(charArray.join('|'), 'g'); + if (typeof column === 'undefined') { + for (var c = 0; c < this.columns.length; c++) { + for (var d = 0; d < this.rows.length; d++) { + var s = this.rows[d].arr[c]; + s = s.replace(regex, ''); + this.rows[d].arr[c] = s; + this.rows[d].obj[this.columns[c]] = s; + } + } + } else if (typeof column === 'string') { + for (var j = 0; j < this.rows.length; j++) { + var val = this.rows[j].obj[column]; + val = val.replace(regex, ''); + this.rows[j].obj[column] = val; + var pos = this.columns.indexOf(column); + this.rows[j].arr[pos] = val; + } + } else { + for (var k = 0; k < this.rows.length; k++) { + var str = this.rows[k].arr[column]; + str = str.replace(regex, ''); + this.rows[k].arr[column] = str; + this.rows[k].obj[this.columns[column]] = str; + } + } + } /** + * Trims leading and trailing whitespace, such as spaces and tabs, + * from String table values. If no column is specified, then the + * values in all columns and rows are trimmed. A specific column + * may be referenced by either its ID or title. + * + * @method trim + * @param {String|Integer} [column] Column ID (number) + * or name (string) + * @example + *
        + * function setup() { + * let table = new p5.Table(); + * + * table.addColumn('name'); + * table.addColumn('type'); + * + * let newRow = table.addRow(); + * newRow.setString('name', ' Lion ,'); + * newRow.setString('type', ' Mammal '); + * + * newRow = table.addRow(); + * newRow.setString('name', ' Snake '); + * newRow.setString('type', ' Reptile '); + * + * table.trim(); + * print(table.getArray()); + * } + * + * // prints: + * // 0 "Lion" "Mamal" + * // 1 "Snake" "Reptile" + *
        + */ + + }, + { + key: 'trim', + value: function trim(column) { + var regex = new RegExp(' ', 'g'); + if (typeof column === 'undefined') { + for (var c = 0; c < this.columns.length; c++) { + for (var d = 0; d < this.rows.length; d++) { + var s = this.rows[d].arr[c]; + s = s.replace(regex, ''); + this.rows[d].arr[c] = s; + this.rows[d].obj[this.columns[c]] = s; + } + } + } else if (typeof column === 'string') { + for (var j = 0; j < this.rows.length; j++) { + var val = this.rows[j].obj[column]; + val = val.replace(regex, ''); + this.rows[j].obj[column] = val; + var pos = this.columns.indexOf(column); + this.rows[j].arr[pos] = val; + } + } else { + for (var k = 0; k < this.rows.length; k++) { + var str = this.rows[k].arr[column]; + str = str.replace(regex, ''); + this.rows[k].arr[column] = str; + this.rows[k].obj[this.columns[column]] = str; + } + } + } /** + * Use removeColumn() to remove an existing column from a Table + * object. The column to be removed may be identified by either + * its title (a String) or its index value (an int). + * removeColumn(0) would remove the first column, removeColumn(1) + * would remove the second column, and so on. + * + * @method removeColumn + * @param {String|Integer} column columnName (string) or ID (number) + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.removeColumn('id'); + * print(table.getColumnCount()); + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'removeColumn', + value: function removeColumn(c) { + var cString; + var cNumber; + if (typeof c === 'string') { + // find the position of c in the columns + cString = c; + cNumber = this.columns.indexOf(c); + } else { + cNumber = c; + cString = this.columns[c]; + } + var chunk = this.columns.splice(cNumber + 1, this.columns.length); + this.columns.pop(); + this.columns = this.columns.concat(chunk); + for (var i = 0; i < this.rows.length; i++) { + var tempR = this.rows[i].arr; + var chip = tempR.splice(cNumber + 1, tempR.length); + tempR.pop(); + this.rows[i].arr = tempR.concat(chip); + delete this.rows[i].obj[cString]; + } + } /** + * Stores a value in the Table's specified row and column. + * The row is specified by its ID, while the column may be specified + * by either its ID or title. + * + * @method set + * @param {Integer} row row ID + * @param {String|Integer} column column ID (Number) + * or title (String) + * @param {String|Number} value value to assign + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.set(0, 'species', 'Canis Lupus'); + * table.set(0, 'name', 'Wolf'); + * + * //print the results + * for (let r = 0; r < table.getRowCount(); r++) + * for (let c = 0; c < table.getColumnCount(); c++) + * print(table.getString(r, c)); + * + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'set', + value: function set(row, column, value) { + this.rows[row].set(column, value); + } /** + * Stores a Float value in the Table's specified row and column. + * The row is specified by its ID, while the column may be specified + * by either its ID or title. + * + * @method setNum + * @param {Integer} row row ID + * @param {String|Integer} column column ID (Number) + * or title (String) + * @param {Number} value value to assign + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * table.setNum(1, 'id', 1); + * + * print(table.getColumn(0)); + * //["0", 1, "2"] + * + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'setNum', + value: function setNum(row, column, value) { + this.rows[row].setNum(column, value); + } /** + * Stores a String value in the Table's specified row and column. + * The row is specified by its ID, while the column may be specified + * by either its ID or title. + * + * @method setString + * @param {Integer} row row ID + * @param {String|Integer} column column ID (Number) + * or title (String) + * @param {String} value value to assign + * @example + *
        + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * //add a row + * let newRow = table.addRow(); + * newRow.setString('id', table.getRowCount() - 1); + * newRow.setString('species', 'Canis Lupus'); + * newRow.setString('name', 'Wolf'); + * + * print(table.getArray()); + * + * describe('no image displayed'); + * } + *
        + */ + + }, + { + key: 'setString', + value: function setString(row, column, value) { + this.rows[row].setString(column, value); + } /** + * Retrieves a value from the Table's specified row and column. + * The row is specified by its ID, while the column may be specified by + * either its ID or title. + * + * @method get + * @param {Integer} row row ID + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {String|Number} + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * print(table.get(0, 1)); + * //Capra hircus + * print(table.get(0, 'species')); + * //Capra hircus + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'get', + value: function get(row, column) { + return this.rows[row].get(column); + } /** + * Retrieves a Float value from the Table's specified row and column. + * The row is specified by its ID, while the column may be specified by + * either its ID or title. + * + * @method getNum + * @param {Integer} row row ID + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {Number} + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * print(table.getNum(1, 0) + 100); + * //id 1 + 100 = 101 + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'getNum', + value: function getNum(row, column) { + return this.rows[row].getNum(column); + } /** + * Retrieves a String value from the Table's specified row and column. + * The row is specified by its ID, while the column may be specified by + * either its ID or title. + * + * @method getString + * @param {Integer} row row ID + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {String} + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * // table is comma separated value "CSV" + * // and has specifiying header for column labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * print(table.getString(0, 0)); // 0 + * print(table.getString(0, 1)); // Capra hircus + * print(table.getString(0, 2)); // Goat + * print(table.getString(1, 0)); // 1 + * print(table.getString(1, 1)); // Panthera pardus + * print(table.getString(1, 2)); // Leopard + * print(table.getString(2, 0)); // 2 + * print(table.getString(2, 1)); // Equus zebra + * print(table.getString(2, 2)); // Zebra + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'getString', + value: function getString(row, column) { + return this.rows[row].getString(column); + } /** + * Retrieves all table data and returns as an object. If a column name is + * passed in, each row object will be stored with that attribute as its + * title. + * + * @method getObject + * @param {String} [headerColumn] Name of the column which should be used to + * title each row object (optional) + * @return {Object} + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let tableObject = table.getObject(); + * + * print(tableObject); + * //outputs an object + * + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'getObject', + value: function getObject(headerColumn) { + var tableObject = { + }; + var obj, + cPos, + index; + for (var i = 0; i < this.rows.length; i++) { + obj = this.rows[i].obj; + if (typeof headerColumn === 'string') { + cPos = this.columns.indexOf(headerColumn); // index of columnID + if (cPos >= 0) { + index = obj[headerColumn]; + tableObject[index] = obj; + } else { + throw new Error('This table has no column named "'.concat(headerColumn, '"')); + } + } else { + tableObject[i] = this.rows[i].obj; + } + } + return tableObject; + } /** + * Retrieves all table data and returns it as a multidimensional array. + * + * @method getArray + * @return {Array} + * + * @example + *
        + * + * // Given the CSV file "mammals.csv" + * // in the project's "assets" folder + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leoperd + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * // table is comma separated value "CSV" + * // and has specifiying header for column labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let tableArray = table.getArray(); + * for (let i = 0; i < tableArray.length; i++) { + * print(tableArray[i]); + * } + * describe('no image displayed'); + * } + * + *
        + */ + + }, + { + key: 'getArray', + value: function getArray() { + var tableArray = [ + ]; + for (var i = 0; i < this.rows.length; i++) { + tableArray.push(this.rows[i].arr); + } + return tableArray; + } + } + ]); + return _class; + }(); + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.splice': 188, + 'core-js/modules/es.regexp.constructor': 209, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.match': 216, + 'core-js/modules/es.string.replace': 219 + } + ], + 331: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.from-entries'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.from-entries'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * @module IO + * @submodule Table + * @requires core + */ + /** + * A TableRow object represents a single row of data values, + * stored in columns, from a table. + * + * A Table Row contains both an ordered array, and an unordered + * JSON object. + * + * @class p5.TableRow + * @constructor + * @param {String} [str] optional: populate the row with a + * string of values, separated by the + * separator + * @param {String} [separator] comma separated values (csv) by default + */ + + _main.default.TableRow = /*#__PURE__*/ function () { + function _class(str, separator) { + _classCallCheck(this, _class); + var arr = [ + ]; + if (str) { + separator = separator || ','; + arr = str.split(separator); + } + this.arr = arr; + this.obj = Object.fromEntries(arr.entries()); + this.table = null; + } /** + * Stores a value in the TableRow's specified column. + * The column may be specified by either its ID or title. + * + * @method set + * @param {String|Integer} column Column ID (Number) + * or Title (String) + * @param {String|Number} value The value to be stored + * + * @example + *
        + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { + * rows[r].set('name', 'Unicorn'); + * } + * + * //print the results + * print(table.getArray()); + * + * describe('no image displayed'); + * } + *
        + */ + + _createClass(_class, [ + { + key: 'set', + value: function set(column, value) { + // if typeof column is string, use .obj + if (typeof column === 'string') { + var cPos = this.table.columns.indexOf(column); // index of columnID + if (cPos >= 0) { + this.obj[column] = value; + this.arr[cPos] = value; + } else { + throw new Error('This table has no column named "'.concat(column, '"')); + } + } else { + // if typeof column is number, use .arr + if (column < this.table.columns.length) { + this.arr[column] = value; + var cTitle = this.table.columns[column]; + this.obj[cTitle] = value; + } else { + throw new Error('Column #'.concat(column, ' is out of the range of this table')); + } + } + } /** + * Stores a Float value in the TableRow's specified column. + * The column may be specified by either its ID or title. + * + * @method setNum + * @param {String|Integer} column Column ID (Number) + * or Title (String) + * @param {Number|String} value The value to be stored + * as a Float + * @example + *
        + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { + * rows[r].setNum('id', r + 10); + * } + * + * print(table.getArray()); + * + * describe('no image displayed'); + * } + *
        + */ + + }, + { + key: 'setNum', + value: function setNum(column, value) { + var floatVal = parseFloat(value); + this.set(column, floatVal); + } /** + * Stores a String value in the TableRow's specified column. + * The column may be specified by either its ID or title. + * + * @method setString + * @param {String|Integer} column Column ID (Number) + * or Title (String) + * @param {String|Number|Boolean|Object} value The value to be stored + * as a String + * @example + *
        + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { + * let name = rows[r].getString('name'); + * rows[r].setString('name', 'A ' + name + ' named George'); + * } + * + * print(table.getArray()); + * + * describe('no image displayed'); + * } + *
        + */ + + }, + { + key: 'setString', + value: function setString(column, value) { + var stringVal = value.toString(); + this.set(column, stringVal); + } /** + * Retrieves a value from the TableRow's specified column. + * The column may be specified by either its ID or title. + * + * @method get + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {String|Number} + * + * @example + *
        + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let names = []; + * let rows = table.getRows(); + * for (let r = 0; r < rows.length; r++) { + * names.push(rows[r].get('name')); + * } + * + * print(names); + * + * describe('no image displayed'); + * } + *
        + */ + + }, + { + key: 'get', + value: function get(column) { + if (typeof column === 'string') { + return this.obj[column]; + } else { + return this.arr[column]; + } + } /** + * Retrieves a Float value from the TableRow's specified + * column. The column may be specified by either its ID or + * title. + * + * @method getNum + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {Number} Float Floating point number + * @example + *
        + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * let minId = Infinity; + * let maxId = -Infinity; + * for (let r = 0; r < rows.length; r++) { + * let id = rows[r].getNum('id'); + * minId = min(minId, id); + * maxId = min(maxId, id); + * } + * print('minimum id = ' + minId + ', maximum id = ' + maxId); + * describe('no image displayed'); + * } + *
        + */ + + }, + { + key: 'getNum', + value: function getNum(column) { + var ret; + if (typeof column === 'string') { + ret = parseFloat(this.obj[column]); + } else { + ret = parseFloat(this.arr[column]); + } + if (ret.toString() === 'NaN') { + throw 'Error: '.concat(this.obj[column], ' is NaN (Not a Number)'); + } + return ret; + } /** + * Retrieves an String value from the TableRow's specified + * column. The column may be specified by either its ID or + * title. + * + * @method getString + * @param {String|Integer} column columnName (string) or + * ID (number) + * @return {String} String + * @example + *
        + * // Given the CSV file "mammals.csv" in the project's "assets" folder: + * // + * // id,species,name + * // 0,Capra hircus,Goat + * // 1,Panthera pardus,Leopard + * // 2,Equus zebra,Zebra + * + * let table; + * + * function preload() { + * //my table is comma separated value "csv" + * //and has a header specifying the columns labels + * table = loadTable('assets/mammals.csv', 'csv', 'header'); + * } + * + * function setup() { + * let rows = table.getRows(); + * let longest = ''; + * for (let r = 0; r < rows.length; r++) { + * let species = rows[r].getString('species'); + * if (longest.length < species.length) { + * longest = species; + * } + * } + * + * print('longest: ' + longest); + * + * describe('no image displayed'); + * } + *
        + */ + + }, + { + key: 'getString', + value: function getString(column) { + if (typeof column === 'string') { + return this.obj[column].toString(); + } else { + return this.arr[column].toString(); + } + } + } + ]); + return _class; + }(); + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.from-entries': 200, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 332: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * @module IO + * @submodule Input + * @requires core + */ + /** + * A class to describe an XML object. + * + * Each `p5.XML` object provides an easy way to interact with XML data. + * Extensible Markup Language + * (XML) + * is a standard format for sending data between applications. Like HTML, the + * XML format is based on tags and attributes, as in + * `<time units="s">1234</time>`. + * + * Note: Use loadXML() to load external XML files. + * + * @class p5.XML + * @constructor + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get an array with all mammal tags. + * let mammals = myXML.getChildren('mammal'); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Iterate over the mammals array. + * for (let i = 0; i < mammals.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Get the mammal's common name. + * let name = mammals[i].getContent(); + * + * // Display the mammal's name. + * text(name, 20, y); + * } + * + * describe( + * 'The words "Goat", "Leopard", and "Zebra" written on three separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + */ + + _main.default.XML = /*#__PURE__*/ function () { + function _class(DOM) { + _classCallCheck(this, _class); + if (!DOM) { + var xmlDoc = document.implementation.createDocument(null, 'doc'); + this.DOM = xmlDoc.createElement('root'); + } else { + this.DOM = DOM; + } + } /** + * Returns the element's parent element as a new p5.XML + * object. + * + * @method getParent + * @return {p5.XML} parent element. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get an array with all mammal elements. + * let mammals = myXML.getChildren('mammal'); + * + * // Get the first mammal element. + * let firstMammal = mammals[0]; + * + * // Get the parent element. + * let parent = firstMammal.getParent(); + * + * // Get the parent element's name. + * let name = parent.getName(); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the parent element's name. + * text(name, 50, 50); + * + * describe('The word "animals" written in black on a gray background.'); + * } + * + *
        + */ + + _createClass(_class, [ + { + key: 'getParent', + value: function getParent() { + return new _main.default.XML(this.DOM.parentElement); + } /** + * Returns the element's name as a `String`. + * + * An XML element's name is given by its tag. For example, the element + * `<language>JavaScript</language>` has the name `language`. + * + * @method getName + * @return {String} name of the element. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get an array with all mammal elements. + * let mammals = myXML.getChildren('mammal'); + * + * // Get the first mammal element. + * let firstMammal = mammals[0]; + * + * // Get the mammal element's name. + * let name = firstMammal.getName(); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the element's name. + * text(name, 50, 50); + * + * describe('The word "mammal" written in black on a gray background.'); + * } + * +
        + */ + + }, + { + key: 'getName', + value: function getName() { + return this.DOM.tagName; + } /** + * Sets the element's tag name. + * + * An XML element's name is given by its tag. For example, the element + * `<language>JavaScript</language>` has the name `language`. + * + * The parameter, `name`, is the element's new name as a string. For example, + * calling `myXML.setName('planet')` will make the element's new tag name + * `<planet></planet>`. + * + * @method setName + * @param {String} name new tag name of the element. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the element's original name. + * let oldName = myXML.getName(); + * + * // Set the element's name. + * myXML.setName('monsters'); + * + * // Get the element's new name. + * let newName = myXML.getName(); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the element's names. + * text(oldName, 50, 33); + * text(newName, 50, 67); + * + * describe( + * 'The words "animals" and "monsters" written on separate lines. The text is black on a gray background.' + * ); + * } + *
        + */ + + }, + { + key: 'setName', + value: function setName(name) { + var content = this.DOM.innerHTML; + var attributes = this.DOM.attributes; + var xmlDoc = document.implementation.createDocument(null, 'default'); + var newDOM = xmlDoc.createElement(name); + newDOM.innerHTML = content; + for (var i = 0; i < attributes.length; i++) { + newDOM.setAttribute(attributes[i].nodeName, attributes[i].nodeValue); + } + this.DOM = newDOM; + } /** + * Returns `true` if the element has child elements and `false` if not. + * + * @method hasChildren + * @return {boolean} whether the element has children. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Check whether the element has child elements. + * let isParent = myXML.hasChildren(); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Style the text. + * if (isParent === true) { + * text('Parent', 50, 50); + * } else { + * text('Not Parent', 50, 50); + * } + * + * describe('The word "Parent" written in black on a gray background.'); + * } + * + *
        + */ + + }, + { + key: 'hasChildren', + value: function hasChildren() { + return this.DOM.children.length > 0; + } /** + * Returns an array with the names of the element's child elements as + * `String`s. + * + * @method listChildren + * @return {String[]} names of the child elements. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the names of the element's children as an array. + * let children = myXML.listChildren(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Iterate over the array. + * for (let i = 0; i < children.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Display the child element's name. + * text(children[i], 10, y); + * } + * + * describe( + * 'The words "mammal", "mammal", "mammal", and "reptile" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + */ + + }, + { + key: 'listChildren', + value: function listChildren() { + var arr = [ + ]; + for (var i = 0; i < this.DOM.childNodes.length; i++) { + arr.push(this.DOM.childNodes[i].nodeName); + } + return arr; + } /** + * Returns an array with the element's child elements as new + * p5.XML objects. + * + * The parameter, `name`, is optional. If a string is passed, as in + * `myXML.getChildren('cat')`, then the method will only return child elements + * with the tag `<cat>`. + * + * @method getChildren + * @param {String} [name] name of the elements to return. + * @return {p5.XML[]} child elements. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get an array of the child elements. + * let children = myXML.getChildren(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Iterate over the array. + * for (let i = 0; i < children.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 20; + * + * // Get the child element's content. + * let content = children[i].getContent(); + * + * // Display the child element's content. + * text(content, 10, y); + * } + * + * describe( + * 'The words "Goat", "Leopard", "Zebra", and "Turtle" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + * + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get an array of the child elements + * // that are mammals. + * let children = myXML.getChildren('mammal'); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Iterate over the array. + * for (let i = 0; i < children.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 20; + * + * // Get the child element's content. + * let content = children[i].getContent(); + * + * // Display the child element's content. + * text(content, 10, y); + * } + * + * describe( + * 'The words "Goat", "Leopard", and "Zebra" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + */ + + }, + { + key: 'getChildren', + value: function getChildren(param) { + if (param) { + return elementsToP5XML(this.DOM.getElementsByTagName(param)); + } else { + return elementsToP5XML(this.DOM.children); + } + } /** + * Returns the first matching child element as a new + * p5.XML object. + * + * The parameter, `name`, is optional. If a string is passed, as in + * `myXML.getChild('cat')`, then the first child element with the tag + * `<cat>` will be returned. If a number is passed, as in + * `myXML.getChild(1)`, then the child element at that index will be returned. + * + * @method getChild + * @param {String|Integer} name element name or index. + * @return {p5.XML} child element. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first child element that is a mammal. + * let goat = myXML.getChild('mammal'); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Get the child element's content. + * let content = goat.getContent(); + * + * // Display the child element's content. + * text(content, 50, 50); + * + * describe('The word "Goat" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the child element at index 1. + * let leopard = myXML.getChild(1); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Get the child element's content. + * let content = leopard.getContent(); + * + * // Display the child element's content. + * text(content, 50, 50); + * + * describe('The word "Leopard" written in black on a gray background.'); + * } + * + *
        + */ + + }, + { + key: 'getChild', + value: function getChild(param) { + if (typeof param === 'string') { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.DOM.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var child = _step.value; + if (child.tagName === param) return new _main.default.XML(child); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else { + return new _main.default.XML(this.DOM.children[param]); + } + } /** + * Adds a new child element and returns a reference to it. + * + * The parameter, `child`, is the p5.XML object to add + * as a child element. For example, calling `myXML.addChild(otherXML)` inserts + * `otherXML` as a child element of `myXML`. + * + * @method addChild + * @param {p5.XML} child child element to add. + * @return {p5.XML} added child element. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a new p5.XML object. + * let newAnimal = new p5.XML(); + * + * // Set its properties. + * newAnimal.setName('hydrozoa'); + * newAnimal.setAttribute('id', 4); + * newAnimal.setAttribute('species', 'Physalia physalis'); + * newAnimal.setContent('Bluebottle'); + * + * // Add the child element. + * myXML.addChild(newAnimal); + * + * // Get the first child element that is a hydrozoa. + * let blueBottle = myXML.getChild('hydrozoa'); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Get the child element's content. + * let content = blueBottle.getContent(); + * + * // Display the child element's content. + * text(content, 50, 50); + * + * describe('The word "Bluebottle" written in black on a gray background.'); + * } + * + *
        + */ + + }, + { + key: 'addChild', + value: function addChild(node) { + if (node instanceof _main.default.XML) { + this.DOM.appendChild(node.DOM); + } else { + // PEND + } + } /** + * Removes the first matching child element. + * + * The parameter, `name`, is the child element to remove. If a string is + * passed, as in `myXML.removeChild('cat')`, then the first child element + * with the tag `<cat>` will be removed. If a number is passed, as in + * `myXML.removeChild(1)`, then the child element at that index will be + * removed. + * + * @method removeChild + * @param {String|Integer} name name or index of the child element to remove. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Remove the first mammal element. + * myXML.removeChild('mammal'); + * + * // Get an array of child elements. + * let children = myXML.getChildren(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Iterate over the array. + * for (let i = 0; i < children.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Get the child element's content. + * let content = children[i].getContent(); + * + * // Display the child element's content. + * text(content, 10, y); + * } + * + * describe( + * 'The words "Leopard", "Zebra", and "Turtle" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + * + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Remove the element at index 2. + * myXML.removeChild(2); + * + * // Get an array of child elements. + * let children = myXML.getChildren(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Iterate over the array. + * for (let i = 0; i < children.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Get the child element's content. + * let content = children[i].getContent(); + * + * // Display the child element's content. + * text(content, 10, y); + * } + * + * describe( + * 'The words "Goat", "Leopard", and "Turtle" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + */ + + }, + { + key: 'removeChild', + value: function removeChild(param) { + var ind = - 1; + if (typeof param === 'string') { + for (var i = 0; i < this.DOM.children.length; i++) { + if (this.DOM.children[i].tagName === param) { + ind = i; + break; + } + } + } else { + ind = param; + } + if (ind !== - 1) { + this.DOM.removeChild(this.DOM.children[ind]); + } + } /** + * Returns the number of attributes the element has. + * + * @method getAttributeCount + * @return {Integer} number of attributes. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first child element. + * let first = myXML.getChild(0); + * + * // Get the number of attributes. + * let numAttributes = first.getAttributeCount(); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the number of attributes. + * text(numAttributes, 50, 50); + * + * describe('The number "2" written in black on a gray background.'); + * } + * + *
        + */ + + }, + { + key: 'getAttributeCount', + value: function getAttributeCount() { + return this.DOM.attributes.length; + } /** + * Returns an `Array` with the names of the element's attributes. + * + * Note: Use + * myXML.getString() or + * myXML.getNum() to return an attribute's value. + * + * @method listAttributes + * @return {String[]} attribute names. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first child element. + * let first = myXML.getChild(0); + * + * // Get the number of attributes. + * let attributes = first.listAttributes(); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the element's attributes. + * text(attributes, 50, 50); + * + * describe('The text "id,species" written in black on a gray background.'); + * } + * + *
        + */ + + }, + { + key: 'listAttributes', + value: function listAttributes() { + var arr = [ + ]; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = this.DOM.attributes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var attribute = _step2.value; + arr.push(attribute.nodeName); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + return arr; + } /** + * Returns `true` if the element has a given attribute and `false` if not. + * + * The parameter, `name`, is a string with the name of the attribute being + * checked. + * + * Note: Use + * myXML.getString() or + * myXML.getNum() to return an attribute's value. + * + * @method hasAttribute + * @param {String} name name of the attribute to be checked. + * @return {boolean} whether the element has the attribute. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first mammal child element. + * let mammal = myXML.getChild('mammal'); + * + * // Check whether the element has an + * // species attribute. + * let hasSpecies = mammal.hasAttribute('species'); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display whether the element has a species attribute. + * if (hasSpecies === true) { + * text('Species', 50, 50); + * } else { + * text('No species', 50, 50); + * } + * + * describe('The text "Species" written in black on a gray background.'); + * } + * + *
        + */ + + }, + { + key: 'hasAttribute', + value: function hasAttribute(name) { + var obj = { + }; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = this.DOM.attributes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var attribute = _step3.value; + obj[attribute.nodeName] = attribute.nodeValue; + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + return obj[name] ? true : false; + } /** + * Return an attribute's value as a `Number`. + * + * The first parameter, `name`, is a string with the name of the attribute + * being checked. For example, calling `myXML.getNum('id')` returns the + * element's `id` attribute as a number. + * + * The second parameter, `defaultValue`, is optional. If a number is passed, + * as in `myXML.getNum('id', -1)`, it will be returned if the attribute + * doesn't exist or can't be converted to a number. + * + * Note: Use + * myXML.getString() or + * myXML.getNum() to return an attribute's value. + * + * @method getNum + * @param {String} name name of the attribute to be checked. + * @param {Number} [defaultValue] value to return if the attribute doesn't exist. + * @return {Number} attribute value as a number. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first reptile child element. + * let reptile = myXML.getChild('reptile'); + * + * // Get the reptile's content. + * let content = reptile.getContent(); + * + * // Get the reptile's ID. + * let id = reptile.getNum('id'); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the ID attribute. + * text(`${content} is ${id + 1}th`, 5, 50, 90); + * + * describe(`The text "${content} is ${id + 1}th" written in black on a gray background.`); + * } + * + *
        + * + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first reptile child element. + * let reptile = myXML.getChild('reptile'); + * + * // Get the reptile's content. + * let content = reptile.getContent(); + * + * // Get the reptile's size. + * let weight = reptile.getNum('weight', 135); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the ID attribute. + * text(`${content} is ${weight}kg`, 5, 50, 90); + * + * describe( + * `The text "${content} is ${weight}kg" written in black on a gray background.` + * ); + * } + * + *
        + */ + + }, + { + key: 'getNum', + value: function getNum(name, defaultValue) { + var obj = { + }; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + try { + for (var _iterator4 = this.DOM.attributes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var attribute = _step4.value; + obj[attribute.nodeName] = attribute.nodeValue; + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + return Number(obj[name]) || defaultValue || 0; + } /** + * Return an attribute's value as a string. + * + * The first parameter, `name`, is a string with the name of the attribute + * being checked. For example, calling `myXML.getString('color')` returns the + * element's `id` attribute as a string. + * + * The second parameter, `defaultValue`, is optional. If a string is passed, + * as in `myXML.getString('color', 'deeppink')`, it will be returned if the + * attribute doesn't exist. + * + * Note: Use + * myXML.getString() or + * myXML.getNum() to return an attribute's value. + * + * @method getString + * @param {String} name name of the attribute to be checked. + * @param {Number} [defaultValue] value to return if the attribute doesn't exist. + * @return {String} attribute value as a string. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first reptile child element. + * let reptile = myXML.getChild('reptile'); + * + * // Get the reptile's content. + * let content = reptile.getContent(); + * + * // Get the reptile's species. + * let species = reptile.getString('species'); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the species attribute. + * text(`${content}: ${species}`, 5, 50, 90); + * + * describe(`The text "${content}: ${species}" written in black on a gray background.`); + * } + * + *
        + * + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first reptile child element. + * let reptile = myXML.getChild('reptile'); + * + * // Get the reptile's content. + * let content = reptile.getContent(); + * + * // Get the reptile's color. + * let attribute = reptile.getString('color', 'green'); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * fill(attribute); + * + * // Display the element's content. + * text(content, 50, 50); + * + * describe(`The text "${content}" written in green on a gray background.`); + * } + * + *
        + */ + + }, + { + key: 'getString', + value: function getString(name, defaultValue) { + var obj = { + }; + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + try { + for (var _iterator5 = this.DOM.attributes[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var attribute = _step5.value; + obj[attribute.nodeName] = attribute.nodeValue; + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + return obj[name] ? String(obj[name]) : defaultValue || null; + } /** + * Sets an attribute to a given value. + * + * The first parameter, `name`, is a string with the name of the attribute + * being set. + * + * The second parameter, `value`, is the attribute's new value. For example, + * calling `myXML.setAttribute('id', 123)` sets the `id` attribute to the + * value 123. + * + * @method setAttribute + * @param {String} name name of the attribute to be set. + * @param {Number|String|Boolean} value attribute's new value. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first reptile child element. + * let reptile = myXML.getChild('reptile'); + * + * // Set the reptile's color. + * reptile.setAttribute('color', 'green'); + * + * // Get the reptile's content. + * let content = reptile.getContent(); + * + * // Get the reptile's color. + * let attribute = reptile.getString('color'); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the element's content. + * text(`${content} is ${attribute}`, 5, 50, 90); + * + * describe( + * `The text "${content} is ${attribute}" written in green on a gray background.` + * ); + * } + * + *
        + */ + + }, + { + key: 'setAttribute', + value: function setAttribute(name, value) { + this.DOM.setAttribute(name, value); + } /** + * Returns the element's content as a `String`. + * + * The parameter, `defaultValue`, is optional. If a string is passed, as in + * `myXML.getContent('???')`, it will be returned if the element has no + * content. + * + * @method getContent + * @param {String} [defaultValue] value to return if the element has no + * content. + * @return {String} element's content as a string. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first reptile child element. + * let reptile = myXML.getChild('reptile'); + * + * // Get the reptile's content. + * let content = reptile.getContent(); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the element's content. + * text(content, 5, 50, 90); + * + * describe(`The text "${content}" written in green on a gray background.`); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.XML object. + * let blankSpace = new p5.XML(); + * + * // Get the element's content and use a default value. + * let content = blankSpace.getContent('Your name'); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the element's content. + * text(content, 5, 50, 90); + * + * describe(`The text "${content}" written in green on a gray background.`); + * } + * + *
        + */ + + }, + { + key: 'getContent', + value: function getContent(defaultValue) { + var str; + str = this.DOM.textContent; + str = str.replace(/\s\s+/g, ','); + return str || defaultValue || null; + } /** + * Sets the element's content. + * + * An element's content is the text between its tags. For example, the element + * `<language>JavaScript</language>` has the content `JavaScript`. + * + * The parameter, `content`, is a string with the element's new content. + * + * @method setContent + * @param {String} content new content for the element. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the first reptile child element. + * let reptile = myXML.getChild('reptile'); + * + * // Get the reptile's original content. + * let oldContent = reptile.getContent(); + * + * // Set the reptile's content. + * reptile.setContent('Loggerhead'); + * + * // Get the reptile's new content. + * let newContent = reptile.getContent(); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(14); + * + * // Display the element's old and new content. + * text(`${oldContent}: ${newContent}`, 5, 50, 90); + * + * describe( + * `The text "${oldContent}: ${newContent}" written in green on a gray background.` + * ); + * } + * + *
        + */ + + }, + { + key: 'setContent', + value: function setContent(content) { + if (!this.DOM.children.length) { + this.DOM.textContent = content; + } + } /** + * Returns the element as a `String`. + * + * `myXML.serialize()` is useful for sending the element over the network or + * saving it to a file. + * + * @method serialize + * @return {String} element as a string. + * + * @example + *
        + * + * let myXML; + * + * // Load the XML and create a p5.XML object. + * function preload() { + * myXML = loadXML('assets/animals.xml'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Display instructions. + * text('Double-click to save', 5, 50, 90); + * + * describe('The text "Double-click to save" written in black on a gray background.'); + * } + * + * // Save the file when the user double-clicks. + * function doubleClicked() { + * // Create a p5.PrintWriter object. + * // Use the file format .xml. + * let myWriter = createWriter('animals', 'xml'); + * + * // Serialize the XML data to a string. + * let data = myXML.serialize(); + * + * // Write the data to the print stream. + * myWriter.write(data); + * + * // Save the file and close the print stream. + * myWriter.close(); + * } + * + *
        + */ + + }, + { + key: 'serialize', + value: function serialize() { + var xmlSerializer = new XMLSerializer(); + return xmlSerializer.serializeToString(this.DOM); + } + } + ]); + return _class; + }(); + function elementsToP5XML(elements) { + var arr = [ + ]; + for (var i = 0; i < elements.length; i++) { + arr.push(new _main.default.XML(elements[i])); + } + return arr; + } + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.number.constructor': 196, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 333: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.string.includes'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } /** + * @module Math + * @submodule Calculation + * @for p5 + * @requires core + */ + /** + * Calculates the absolute value of a number. + * + * A number's absolute value is its distance from zero on the number line. + * -5 and 5 are both five units away from zero, so calling `abs(-5)` and + * `abs(5)` both return 5. The absolute value of a number is always positive. + * + * @method abs + * @param {Number} n number to compute. + * @return {Number} absolute value of given number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A gray square with a vertical black line that divides it in half. A white rectangle gets taller when the user moves the mouse away from the line.'); + * } + * + * function draw() { + * background(200); + * + * // Divide the canvas. + * line(50, 0, 50, 100); + * + * // Calculate the mouse's distance from the middle. + * let h = abs(mouseX - 50); + * + * // Draw a rectangle based on the mouse's distance + * // from the middle. + * rect(0, 100 - h, 100, h); + * } + * + *
        + */ + + _main.default.prototype.abs = Math.abs; + /** + * Calculates the closest integer value that is greater than or equal to a + * number. + * + * For example, calling `ceil(9.03)` and `ceil(9.97)` both return the value + * 10. + * + * @method ceil + * @param {Number} n number to round up. + * @return {Integer} rounded up number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use RGB color with values from 0 to 1. + * colorMode(RGB, 1); + * + * noStroke(); + * + * // Draw the left rectangle. + * let r = 0.3; + * fill(r, 0, 0); + * rect(0, 0, 50, 100); + * + * // Round r up to 1. + * r = ceil(r); + * + * // Draw the right rectangle. + * fill(r, 0, 0); + * rect(50, 0, 50, 100); + * + * describe('Two rectangles. The one on the left is dark red and the one on the right is bright red.'); + * } + * + *
        + */ + _main.default.prototype.ceil = Math.ceil; + /** + * Constrains a number between a minimum and maximum value. + * + * @method constrain + * @param {Number} n number to constrain. + * @param {Number} low minimum limit. + * @param {Number} high maximum limit. + * @return {Number} constrained number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A black dot drawn on a gray square follows the mouse from left to right. Its movement is constrained to the middle third of the square.'); + * } + * + * function draw() { + * background(200); + * + * let x = constrain(mouseX, 33, 67); + * let y = 50; + * + * strokeWeight(5); + * point(x, y); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Two vertical lines. Two circles move horizontally with the mouse. One circle stops at the vertical lines.'); + * } + * + * function draw() { + * background(200); + * + * // Set boundaries and draw them. + * let leftWall = 25; + * let rightWall = 75; + * line(leftWall, 0, leftWall, 100); + * line(rightWall, 0, rightWall, 100); + * + * // Draw a circle that follows the mouse freely. + * fill(255); + * circle(mouseX, 33, 9); + * + * // Draw a circle that's constrained. + * let xc = constrain(mouseX, leftWall, rightWall); + * fill(0); + * circle(xc, 67, 9); + * } + * + *
        + */ + _main.default.prototype.constrain = function (n, low, high) { + _main.default._validateParameters('constrain', arguments); + return Math.max(Math.min(n, high), low); + }; + /** + * Calculates the distance between two points. + * + * The version of `dist()` with four parameters calculates distance in two + * dimensions. + * + * The version of `dist()` with six parameters calculates distance in three + * dimensions. + * + * Use p5.Vector.dist() to calculate the + * distance between two p5.Vector objects. + * + * @method dist + * @param {Number} x1 x-coordinate of the first point. + * @param {Number} y1 y-coordinate of the first point. + * @param {Number} x2 x-coordinate of the second point. + * @param {Number} y2 y-coordinate of the second point. + * @return {Number} distance between the two points. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the coordinates. + * let x1 = 10; + * let y1 = 50; + * let x2 = 90; + * let y2 = 50; + * + * // Draw the points and a line connecting them. + * line(x1, y1, x2, y2); + * strokeWeight(5); + * point(x1, y1); + * point(x2, y2); + * + * // Calculate the distance. + * let d = dist(x1, y1, x2, y2); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the distance. + * text(d, 43, 40); + * + * describe('Two dots connected by a horizontal line. The number 80 is written above the center of the line.'); + * } + * + *
        + */ + /** + * @method dist + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} z1 z-coordinate of the first point. + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} z2 z-coordinate of the second point. + * @return {Number} distance between the two points. + */ + _main.default.prototype.dist = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('dist', args); + if (args.length === 4) { + //2D + return Math.hypot(args[2] - args[0], args[3] - args[1]); + } else if (args.length === 6) { + //3D + return Math.hypot(args[3] - args[0], args[4] - args[1], args[5] - args[2]); + } + }; + /** + * Calculates the value of Euler's number e (2.71828...) raised to the power + * of a number. + * + * @method exp + * @param {Number} n exponent to raise. + * @return {Number} e^n + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top-left. + * let d = exp(1); + * circle(10, 10, d); + * + * // Left-center. + * d = exp(2); + * circle(20, 20, d); + * + * // Right-center. + * d = exp(3); + * circle(40, 40, d); + * + * // Bottom-right. + * d = exp(4); + * circle(80, 80, d); + * + * describe('A series of circles that grow exponentially from top left to bottom right.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A series of black dots that grow exponentially from left to right.'); + * } + * + * function draw() { + * // Invert the y-axis. + * scale(1, -1); + * translate(0, -100); + * + * // Calculate the coordinates. + * let x = frameCount; + * let y = 0.005 * exp(x * 0.1); + * + * // Draw a point. + * point(x, y); + * } + * + *
        + */ + _main.default.prototype.exp = Math.exp; + /** + * Calculates the closest integer value that is less than or equal to the + * value of a number. + * + * @method floor + * @param {Number} n number to round down. + * @return {Integer} rounded down number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Use RGB color with values from 0 to 1. + * colorMode(RGB, 1); + * + * noStroke(); + * + * // Draw the left rectangle. + * let r = 0.8; + * fill(r, 0, 0); + * rect(0, 0, 50, 100); + * + * // Round r down to 0. + * r = floor(r); + * + * // Draw the right rectangle. + * fill(r, 0, 0); + * rect(50, 0, 50, 100); + * + * describe('Two rectangles. The one on the left is bright red and the one on the right is black.'); + * } + * + *
        + */ + _main.default.prototype.floor = Math.floor; + /** + * Calculates a number between two numbers at a specific increment. + * + * The `amt` parameter is the amount to interpolate between the two numbers. + * 0.0 is equal to the first number, 0.1 is very near the first number, 0.5 is + * half-way in between, and 1.0 is equal to the second number. The `lerp()` + * function is convenient for creating motion along a straight path and for + * drawing dotted lines. + * + * If the value of `amt` is less than 0 or more than 1, `lerp()` will return a + * number outside of the original interval. For example, calling + * `lerp(0, 10, 1.5)` will return 15. + * + * @method lerp + * @param {Number} start first value. + * @param {Number} stop second value. + * @param {Number} amt number. + * @return {Number} lerped value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Declare variables for coordinates. + * let a = 20; + * let b = 80; + * let c = lerp(a, b, 0.2); + * let d = lerp(a, b, 0.5); + * let e = lerp(a, b, 0.8); + * + * strokeWeight(5); + * + * // Draw the original points in black. + * stroke(0); + * point(a, 50); + * point(b, 50); + * + * // Draw the lerped points in gray. + * stroke(100); + * point(c, 50); + * point(d, 50); + * point(e, 50); + * + * describe('Five points in a horizontal line. The outer points are black and the inner points are gray.'); + * } + * + *
        + * + *
        + * + * let x = 50; + * let y = 50; + * let targetX = 50; + * let targetY = 50; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A white circle at the center of a gray canvas. The circle moves to where the user clicks, then moves smoothly back to the center.'); + * } + * + * function draw() { + * background(220); + * + * // Move x and y toward the target. + * x = lerp(x, targetX, 0.05); + * y = lerp(y, targetY, 0.05); + * + * // Draw the circle. + * circle(x, y, 20); + * } + * + * // Set x and y when the user clicks the mouse. + * function mouseClicked() { + * x = mouseX; + * y = mouseY; + * } + * + *
        + */ + _main.default.prototype.lerp = function (start, stop, amt) { + _main.default._validateParameters('lerp', arguments); + return amt * (stop - start) + start; + }; + /** + * Calculates the natural logarithm (the base-e logarithm) of a number. + * + * `log()` expects the `n` parameter to be a value greater than 0 because + * the natural logarithm is defined that way. + * + * @method log + * @param {Number} n number greater than 0. + * @return {Number} natural logarithm of n. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top-left. + * let d = log(50); + * circle(33, 33, d); + * + * // Bottom-right. + * d = log(500000000); + * circle(67, 67, d); + * + * describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is about five times larger.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A series of black dots that get higher slowly from left to right.'); + * } + * + * function draw() { + * // Invert the y-axis. + * scale(1, -1); + * translate(0, -100); + * + * // Calculate coordinates. + * let x = frameCount; + * let y = 15 * log(x); + * + * // Draw a point. + * point(x, y); + * } + * + *
        + */ + _main.default.prototype.log = Math.log; + /** + * Calculates the magnitude, or length, of a vector. + * + * A vector can be thought of in different ways. In one view, a vector is a + * point in space. The vector's components, `x` and `y`, are the point's + * coordinates `(x, y)`. A vector's magnitude is the distance from the origin + * `(0, 0)` to `(x, y)`. `mag(x, y)` is a shortcut for calling + * `dist(0, 0, x, y)`. + * + * A vector can also be thought of as an arrow pointing in space. This view is + * helpful for programming motion. See p5.Vector for + * more details. + * + * Use p5.Vector.mag() to calculate the + * magnitude of a p5.Vector object. + * + * @method mag + * @param {Number} x first component. + * @param {Number} y second component. + * @return {Number} magnitude of vector. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the vector's components. + * let x = 30; + * let y = 40; + * + * // Calculate the magnitude. + * let m = mag(x, y); + * + * // Style the text. + * textSize(16); + * + * // Display the vector and its magnitude. + * line(0, 0, x, y); + * text(m, x, y); + * + * describe('A diagonal line is drawn from the top left of the canvas. The number 50 is written at the end of the line.'); + * } + * + *
        + */ + _main.default.prototype.mag = function (x, y) { + _main.default._validateParameters('mag', arguments); + return Math.hypot(x, y); + }; + /** + * Re-maps a number from one range to another. + * + * For example, calling `map(2, 0, 10, 0, 100)` returns 20. The first three + * arguments set the original value to 2 and the original range from 0 to 10. + * The last two arguments set the target range from 0 to 100. 20's position + * in the target range [0, 100] is proportional to 2's position in the + * original range [0, 10]. + * + * The sixth parameter, `withinBounds`, is optional. By default, `map()` can + * return values outside of the target range. For example, + * `map(11, 0, 10, 0, 100)` returns 110. Passing `true` as the sixth parameter + * constrains the remapped value to the target range. For example, + * `map(11, 0, 10, 0, 100, true)` returns 100. + * + * @method map + * @param {Number} value the value to be remapped. + * @param {Number} start1 lower bound of the value's current range. + * @param {Number} stop1 upper bound of the value's current range. + * @param {Number} start2 lower bound of the value's target range. + * @param {Number} stop2 upper bound of the value's target range. + * @param {Boolean} [withinBounds] constrain the value to the newly mapped range. + * @return {Number} remapped number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Two horizontal lines. The top line grows horizontally as the mouse moves to the right. The bottom line also grows horizontally but is scaled to stay on the left half of the canvas.'); + * } + * + * function draw() { + * background(200); + * + * // Draw the top line. + * line(0, 25, mouseX, 25); + * + * // Remap mouseX from [0, 100] to [0, 50]. + * let x = map(mouseX, 0, 100, 0, 50); + * + * // Draw the bottom line. + * line(0, 75, x, 75); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A circle changes color from black to white as the mouse moves from left to right.'); + * } + * + * function draw() { + * background(200); + * + * // Remap mouseX from [0, 100] to [0, 255] + * let c = map(mouseX, 0, 100, 0, 255); + * + * // Style the circle. + * fill(c); + * + * // Draw the circle. + * circle(50, 50, 20); + * } + * + *
        + */ + _main.default.prototype.map = function (n, start1, stop1, start2, stop2, withinBounds) { + _main.default._validateParameters('map', arguments); + var newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2; + if (!withinBounds) { + return newval; + } + if (start2 < stop2) { + return this.constrain(newval, start2, stop2); + } else { + return this.constrain(newval, stop2, start2); + } + }; + /** + * Returns the largest value in a sequence of numbers. + * + * The version of `max()` with one parameter interprets it as an array of + * numbers and returns the largest number. + * + * The version of `max()` with two or more parameters interprets them as + * individual numbers and returns the largest number. + * + * @method max + * @param {Number} n0 first number to compare. + * @param {Number} n1 second number to compare. + * @return {Number} maximum number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Calculate the maximum of 10, 5, and 20. + * let m = max(10, 5, 20); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the max. + * text(m, 50, 50); + * + * describe('The number 20 written in the middle of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of numbers. + * let numbers = [10, 5, 20]; + * + * // Calculate the maximum of the array. + * let m = max(numbers); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the max. + * text(m, 50, 50); + * + * describe('The number 20 written in the middle of a gray square.'); + * } + * + *
        + */ + /** + * @method max + * @param {Number[]} nums numbers to compare. + * @return {Number} + */ + _main.default.prototype.max = function () { + var findMax = function findMax(arr) { + return Math.max.apply(Math, _toConsumableArray(arr)); + }; + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + if (Array.isArray(args[0])) { + return findMax(args[0]); + } else { + return findMax(args); + } + }; + /** + * Returns the smallest value in a sequence of numbers. + * + * The version of `min()` with one parameter interprets it as an array of + * numbers and returns the smallest number. + * + * The version of `min()` with two or more parameters interprets them as + * individual numbers and returns the smallest number. + * + * @method min + * @param {Number} n0 first number to compare. + * @param {Number} n1 second number to compare. + * @return {Number} minimum number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Calculate the minimum of 10, 5, and 20. + * let m = min(10, 5, 20); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the min. + * text(m, 50, 50); + * + * describe('The number 5 written in the middle of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of numbers. + * let numbers = [10, 5, 20]; + * + * // Calculate the minimum of the array. + * let m = min(numbers); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the min. + * text(m, 50, 50); + * + * describe('The number 5 written in the middle of a gray square.'); + * } + * + *
        + */ + /** + * @method min + * @param {Number[]} nums numbers to compare. + * @return {Number} + */ + _main.default.prototype.min = function () { + var findMin = function findMin(arr) { + return Math.min.apply(Math, _toConsumableArray(arr)); + }; + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + if (Array.isArray(args[0])) { + return findMin(args[0]); + } else { + return findMin(args); + } + }; + /** + * Maps a number from one range to a value between 0 and 1. + * + * For example, `norm(2, 0, 10)` returns 0.2. 2's position in the original + * range [0, 10] is proportional to 0.2's position in the range [0, 1]. This + * is the same as calling `map(2, 0, 10, 0, 1)`. + * + * Numbers outside of the original range are not constrained between 0 and 1. + * Out-of-range values are often intentional and useful. + * + * @method norm + * @param {Number} value incoming value to be normalized. + * @param {Number} start lower bound of the value's current range. + * @param {Number} stop upper bound of the value's current range. + * @return {Number} normalized number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Use RGB color with values from 0 to 1. + * colorMode(RGB, 1); + * + * describe('A square changes color from black to red as the mouse moves from left to right.'); + * } + * + * function draw() { + * // Calculate the redValue. + * let redValue = norm(mouseX, 0, 100); + * + * // Paint the background. + * background(redValue, 0, 0); + * } + * + *
        + */ + _main.default.prototype.norm = function (n, start, stop) { + _main.default._validateParameters('norm', arguments); + return this.map(n, start, stop, 0, 1); + }; + /** + * Calculates exponential expressions such as 23. + * + * For example, `pow(2, 3)` evaluates the expression + * 2 × 2 × 2. `pow(2, -3)` evaluates 1 ÷ + * (2 × 2 × 2). + * + * @method pow + * @param {Number} n base of the exponential expression. + * @param {Number} e power by which to raise the base. + * @return {Number} n^e. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the base of the exponent. + * let base = 3; + * + * // Top-left. + * let d = pow(base, 1); + * circle(10, 10, d); + * + * // Left-center. + * d = pow(base, 2); + * circle(20, 20, d); + * + * // Right-center. + * d = pow(base, 3); + * circle(40, 40, d); + * + * // Bottom-right. + * d = pow(base, 4); + * circle(80, 80, d); + * + * describe('A series of circles that grow exponentially from top left to bottom right.'); + * } + * + *
        + */ + _main.default.prototype.pow = Math.pow; + /** + * Calculates the integer closest to a number. + * + * For example, `round(133.8)` returns the value 134. + * + * The second parameter, `decimals`, is optional. It sets the number of + * decimal places to use when rounding. For example, `round(12.34, 1)` returns + * 12.3. `decimals` is 0 by default. + * + * @method round + * @param {Number} n number to round. + * @param {Number} [decimals] number of decimal places to round to, default is 0. + * @return {Integer} rounded number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Round a number. + * let x = round(4.2); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the rounded number. + * text(x, 50, 50); + * + * describe('The number 4 written in middle of the canvas.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Round a number to 2 decimal places. + * let x = round(12.782383, 2); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the rounded number. + * text(x, 50, 50); + * + * describe('The number 12.78 written in middle of canvas.'); + * } + * + *
        + */ + _main.default.prototype.round = function (n, decimals) { + if (!decimals) { + return Math.round(n); + } + var multiplier = Math.pow(10, decimals); + return Math.round(n * multiplier) / multiplier; + }; + /** + * Calculates the square of a number. + * + * Squaring a number means multiplying the number by itself. For example, + * `sq(3)` evaluates 3 × 3 which is 9. `sq(-3)` evaluates -3 × -3 + * which is also 9. Multiplying two negative numbers produces a positive + * number. The value returned by `sq()` is always positive. + * + * @method sq + * @param {Number} n number to square. + * @return {Number} squared number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top-left. + * let d = sq(3); + * circle(33, 33, d); + * + * // Bottom-right. + * d = sq(6); + * circle(67, 67, d); + * + * describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is four times larger.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A series of black dots that get higher quickly from left to right.'); + * } + * + * function draw() { + * // Invert the y-axis. + * scale(1, -1); + * translate(0, -100); + * + * // Calculate the coordinates. + * let x = frameCount; + * let y = 0.01 * sq(x); + * + * // Draw the point. + * point(x, y); + * } + * + *
        + */ + _main.default.prototype.sq = function (n) { + return n * n; + }; + /** + * Calculates the square root of a number. + * + * A number's square root can be multiplied by itself to produce the original + * number. For example, `sqrt(9)` returns 3 because 3 × 3 = 9. `sqrt()` + * always returns a positive value. `sqrt()` doesn't work with negative arguments + * such as `sqrt(-9)`. + * + * @method sqrt + * @param {Number} n non-negative number to square root. + * @return {Number} square root of number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top-left. + * let d = sqrt(16); + * circle(33, 33, d); + * + * // Bottom-right. + * d = sqrt(1600); + * circle(67, 67, d); + * + * describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is ten times larger.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A series of black dots that get higher slowly from left to right.'); + * } + * + * function draw() { + * // Invert the y-axis. + * scale(1, -1); + * translate(0, -100); + * + * // Calculate the coordinates. + * let x = frameCount; + * let y = 5 * sqrt(x); + * + * // Draw the point. + * point(x, y); + * } + * + *
        + */ + _main.default.prototype.sqrt = Math.sqrt; + /** + * Calculates the fractional part of a number. + * + * A number's fractional part includes its decimal values. For example, + * `fract(12.34)` returns 0.34. + * + * @method fract + * @param {Number} n number whose fractional part will be found. + * @returns {Number} fractional part of n. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Original number. + * let n = 56.78; + * text(n, 50, 33); + * + * // Fractional part. + * let f = fract(n); + * text(f, 50, 67); + * + * describe('The number 56.78 written above the number 0.78.'); + * } + * + *
        + */ + _main.default.prototype.fract = function (toConvert) { + _main.default._validateParameters('fract', arguments); + var sign = 0; + var num = Number(toConvert); + if (isNaN(num) || Math.abs(num) === Infinity) { + return num; + } else if (num < 0) { + num = - num; + sign = 1; + } + if (String(num).includes('.') && !String(num).includes('e')) { + var toFract = String(num); + toFract = Number('0' + toFract.slice(toFract.indexOf('.'))); + return Math.abs(sign - toFract); + } else if (num < 1) { + return Math.abs(sign - num); + } else { + return 0; + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.math.hypot': 193, + 'core-js/modules/es.number.constructor': 196, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 334: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.slice'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function 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; + } + } + function _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); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } /** + * @module Math + * @submodule Vector + * @for p5 + * @requires core + */ + /** + * Creates a new p5.Vector object. + * + * A vector can be thought of in different ways. In one view, a vector is like + * an arrow pointing in space. Vectors have both magnitude (length) and + * direction. This view is helpful for programming motion. + * + * A vector's components determine its magnitude and direction. For example, + * calling `createVector(3, 4)` creates a new + * p5.Vector object with an x-component of 3 and a + * y-component of 4. From the origin, this vector's tip is 3 units to the + * right and 4 units down. + * + * p5.Vector objects are often used to program + * motion because they simplify the math. For example, a moving ball has a + * position and a velocity. Position describes where the ball is in space. The + * ball's position vector extends from the origin to the ball's center. + * Velocity describes the ball's speed and the direction it's moving. If the + * ball is moving straight up, its velocity vector points straight up. Adding + * the ball's velocity vector to its position vector moves it, as in + * `pos.add(vel)`. Vector math relies on methods inside the + * p5.Vector class. + * + * @method createVector + * @param {Number} [x] x component of the vector. + * @param {Number} [y] y component of the vector. + * @param {Number} [z] z component of the vector. + * @return {p5.Vector} new p5.Vector object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create p5.Vector objects. + * let p1 = createVector(25, 25); + * let p2 = createVector(50, 50); + * let p3 = createVector(75, 75); + * + * // Draw the dots. + * strokeWeight(5); + * point(p1); + * point(p2); + * point(p3); + * + * describe('Three black dots form a diagonal line from top left to bottom right.'); + * } + * + *
        + * + *
        + * + * let pos; + * let vel; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create p5.Vector objects. + * pos = createVector(50, 100); + * vel = createVector(0, -1); + * + * describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.'); + * } + * + * function draw() { + * background(200); + * + * // Add velocity to position. + * pos.add(vel); + * + * // If the dot reaches the top of the canvas, + * // restart from the bottom. + * if (pos.y < 0) { + * pos.y = 100; + * } + * + * // Draw the dot. + * strokeWeight(5); + * point(pos); + * } + * + *
        + */ + + _main.default.prototype.createVector = function (x, y, z) { + if (this instanceof _main.default) { + return _construct(_main.default.Vector, [ + this._fromRadians.bind(this), + this._toRadians.bind(this) + ].concat(Array.prototype.slice.call(arguments))); + } else { + return new _main.default.Vector(x, y, z); + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.regexp.to-string': 211 + } + ], + 335: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } ////////////////////////////////////////////////////////////// + // http://mrl.nyu.edu/~perlin/noise/ + // Adapting from PApplet.java + // which was adapted from toxi + // which was adapted from the german demo group farbrausch + // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip + // someday we might consider using "improved noise" + // http://mrl.nyu.edu/~perlin/paper445.pdf + // See: https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/ + // blob/main/introduction/Noise1D/noise.js + /** + * @module Math + * @submodule Noise + * @for p5 + * @requires core + */ + + var PERLIN_YWRAPB = 4; + var PERLIN_YWRAP = 1 << PERLIN_YWRAPB; + var PERLIN_ZWRAPB = 8; + var PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB; + var PERLIN_SIZE = 4095; + var perlin_octaves = 4; // default to medium smooth + var perlin_amp_falloff = 0.5; // 50% reduction/octave + var scaled_cosine = function scaled_cosine(i) { + return 0.5 * (1 - Math.cos(i * Math.PI)); + }; + var perlin; // will be initialized lazily by noise() or noiseSeed() + /** + * Returns random numbers that can be tuned to feel organic. + * + * Values returned by random() and + * randomGaussian() can change by large + * amounts between function calls. By contrast, values returned by `noise()` + * can be made "smooth". Calls to `noise()` with similar inputs will produce + * similar outputs. `noise()` is used to create textures, motion, shapes, + * terrains, and so on. Ken Perlin invented `noise()` while animating the + * original Tron film in the 1980s. + * + * `noise()` always returns values between 0 and 1. It returns the same value + * for a given input while a sketch is running. `noise()` produces different + * results each time a sketch runs. The + * noiseSeed() function can be used to generate + * the same sequence of Perlin noise values each time a sketch runs. + * + * The character of the noise can be adjusted in two ways. The first way is to + * scale the inputs. `noise()` interprets inputs as coordinates. The sequence + * of noise values will be smoother when the input coordinates are closer. The + * second way is to use the noiseDetail() + * function. + * + * The version of `noise()` with one parameter computes noise values in one + * dimension. This dimension can be thought of as space, as in `noise(x)`, or + * time, as in `noise(t)`. + * + * The version of `noise()` with two parameters computes noise values in two + * dimensions. These dimensions can be thought of as space, as in + * `noise(x, y)`, or space and time, as in `noise(x, t)`. + * + * The version of `noise()` with three parameters computes noise values in + * three dimensions. These dimensions can be thought of as space, as in + * `noise(x, y, z)`, or space and time, as in `noise(x, y, t)`. + * + * @method noise + * @param {Number} x x-coordinate in noise space. + * @param {Number} [y] y-coordinate in noise space. + * @param {Number} [z] z-coordinate in noise space. + * @return {Number} Perlin noise value at specified coordinates. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A black dot moves randomly on a gray square.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the coordinates. + * let x = 100 * noise(0.005 * frameCount); + * let y = 100 * noise(0.005 * frameCount + 10000); + * + * // Draw the point. + * strokeWeight(5); + * point(x, y); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A black dot moves randomly on a gray square.'); + * } + * + * function draw() { + * background(200); + * + * // Set the noise level and scale. + * let noiseLevel = 100; + * let noiseScale = 0.005; + * + * // Scale the input coordinate. + * let nt = noiseScale * frameCount; + * + * // Compute the noise values. + * let x = noiseLevel * noise(nt); + * let y = noiseLevel * noise(nt + 10000); + * + * // Draw the point. + * strokeWeight(5); + * point(x, y); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A hilly terrain drawn in gray against a black sky.'); + * } + * + * function draw() { + * // Set the noise level and scale. + * let noiseLevel = 100; + * let noiseScale = 0.02; + * + * // Scale the input coordinate. + * let x = frameCount; + * let nx = noiseScale * x; + * + * // Compute the noise value. + * let y = noiseLevel * noise(nx); + * + * // Draw the line. + * line(x, 0, x, y); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A calm sea drawn in gray against a black sky.'); + * } + * + * function draw() { + * background(200); + * + * // Set the noise level and scale. + * let noiseLevel = 100; + * let noiseScale = 0.002; + * + * // Iterate from left to right. + * for (let x = 0; x < 100; x += 1) { + * // Scale the input coordinates. + * let nx = noiseScale * x; + * let nt = noiseScale * frameCount; + * + * // Compute the noise value. + * let y = noiseLevel * noise(nx, nt); + * + * // Draw the line. + * line(x, 0, x, y); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the noise level and scale. + * let noiseLevel = 255; + * let noiseScale = 0.01; + * + * // Iterate from top to bottom. + * for (let y = 0; y < 100; y += 1) { + * // Iterate from left to right. + * for (let x = 0; x < 100; x += 1) { + * // Scale the input coordinates. + * let nx = noiseScale * x; + * let ny = noiseScale * y; + * + * // Compute the noise value. + * let c = noiseLevel * noise(nx, ny); + * + * // Draw the point. + * stroke(c); + * point(x, y); + * } + * } + * + * describe('A gray cloudy pattern.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A gray cloudy pattern that changes.'); + * } + * + * function draw() { + * // Set the noise level and scale. + * let noiseLevel = 255; + * let noiseScale = 0.009; + * + * // Iterate from top to bottom. + * for (let y = 0; y < 100; y += 1) { + * // Iterate from left to right. + * for (let x = 0; x < width; x += 1) { + * // Scale the input coordinates. + * let nx = noiseScale * x; + * let ny = noiseScale * y; + * let nt = noiseScale * frameCount; + * + * // Compute the noise value. + * let c = noiseLevel * noise(nx, ny, nt); + * + * // Draw the point. + * stroke(c); + * point(x, y); + * } + * } + * } + * + *
        + */ + _main.default.prototype.noise = function (x) { + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var z = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + if (perlin == null) { + perlin = new Array(PERLIN_SIZE + 1); + for (var i = 0; i < PERLIN_SIZE + 1; i++) { + perlin[i] = Math.random(); + } + } + if (x < 0) { + x = - x; + } + if (y < 0) { + y = - y; + } + if (z < 0) { + z = - z; + } + var xi = Math.floor(x), + yi = Math.floor(y), + zi = Math.floor(z); + var xf = x - xi; + var yf = y - yi; + var zf = z - zi; + var rxf, + ryf; + var r = 0; + var ampl = 0.5; + var n1, + n2, + n3; + for (var o = 0; o < perlin_octaves; o++) { + var of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); + rxf = scaled_cosine(xf); + ryf = scaled_cosine(yf); + n1 = perlin[of & PERLIN_SIZE]; + n1 += rxf * (perlin[of + 1 & PERLIN_SIZE] - n1); + n2 = perlin[of + PERLIN_YWRAP & PERLIN_SIZE]; + n2 += rxf * (perlin[of + PERLIN_YWRAP + 1 & PERLIN_SIZE] - n2); + n1 += ryf * (n2 - n1); + of += PERLIN_ZWRAP; + n2 = perlin[of & PERLIN_SIZE]; + n2 += rxf * (perlin[of + 1 & PERLIN_SIZE] - n2); + n3 = perlin[of + PERLIN_YWRAP & PERLIN_SIZE]; + n3 += rxf * (perlin[of + PERLIN_YWRAP + 1 & PERLIN_SIZE] - n3); + n2 += ryf * (n3 - n2); + n1 += scaled_cosine(zf) * (n2 - n1); + r += n1 * ampl; + ampl *= perlin_amp_falloff; + xi <<= 1; + xf *= 2; + yi <<= 1; + yf *= 2; + zi <<= 1; + zf *= 2; + if (xf >= 1) { + xi++; + xf--; + } + if (yf >= 1) { + yi++; + yf--; + } + if (zf >= 1) { + zi++; + zf--; + } + } + return r; + }; + /** + * Adjusts the character of the noise produced by the + * noise() function. + * + * Perlin noise values are created by adding layers of noise together. The + * noise layers, called octaves, are similar to harmonics in music. Lower + * octaves contribute more to the output signal. They define the overall + * intensity of the noise. Higher octaves create finer-grained details. + * + * By default, noise values are created by combining four octaves. Each higher + * octave contributes half as much (50% less) compared to its predecessor. + * `noiseDetail()` changes the number of octaves and the falloff amount. For + * example, calling `noiseDetail(6, 0.25)` ensures that + * noise() will use six octaves. Each higher octave + * will contribute 25% as much (75% less) compared to its predecessor. Falloff + * values between 0 and 1 are valid. However, falloff values greater than 0.5 + * might result in noise values greater than 1. + * + * @method noiseDetail + * @param {Number} lod number of octaves to be used by the noise. + * @param {Number} falloff falloff factor for each octave. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Set the noise level and scale. + * let noiseLevel = 255; + * let noiseScale = 0.02; + * + * // Iterate from top to bottom. + * for (let y = 0; y < 100; y += 1) { + * // Iterate from left to right. + * for (let x = 0; x < 50; x += 1) { + * // Scale the input coordinates. + * let nx = noiseScale * x; + * let ny = noiseScale * y; + * + * // Compute the noise value with six octaves + * // and a low falloff factor. + * noiseDetail(6, 0.25); + * let c = noiseLevel * noise(nx, ny); + * + * // Draw the left side. + * stroke(c); + * point(x, y); + * + * // Compute the noise value with four octaves + * // and a high falloff factor. + * noiseDetail(4, 0.5); + * c = noiseLevel * noise(nx, ny); + * + * // Draw the right side. + * stroke(c); + * point(x + 50, y); + * } + * } + * + * describe('Two gray cloudy patterns. The pattern on the right is cloudier than the pattern on the left.'); + * } + * + *
        + */ + _main.default.prototype.noiseDetail = function (lod, falloff) { + if (lod > 0) { + perlin_octaves = lod; + } + if (falloff > 0) { + perlin_amp_falloff = falloff; + } + }; + /** + * Sets the seed value for the noise() function. + * + * By default, noise() produces different results + * each time a sketch is run. Calling `noiseSeed()` with a constant argument, + * such as `noiseSeed(99)`, makes noise() produce the + * same results each time a sketch is run. + * + * @method noiseSeed + * @param {Number} seed seed value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Set the noise seed for consistent results. + * noiseSeed(99); + * + * describe('A black rectangle that grows randomly, first to the right and then to the left.'); + * } + * + * function draw() { + * // Set the noise level and scale. + * let noiseLevel = 100; + * let noiseScale = 0.005; + * + * // Scale the input coordinate. + * let nt = noiseScale * frameCount; + * + * // Compute the noise value. + * let x = noiseLevel * noise(nt); + * + * // Draw the line. + * line(x, 0, x, height); + * } + * + *
        + */ + _main.default.prototype.noiseSeed = function (seed) { + // Linear Congruential Generator + // Variant of a Lehman Generator + var lcg = function () { + // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes + // m is basically chosen to be large (as it is the max period) + // and for its relationships to a and c + var m = 4294967296; + // a - 1 should be divisible by m's prime factors + var a = 1664525; + // c and m should be co-prime + var c = 1013904223; + var seed, + z; + return { + setSeed: function setSeed(val) { + // pick a random seed if val is undefined or null + // the >>> 0 casts the seed to an unsigned 32-bit integer + z = seed = (val == null ? Math.random() * m : val) >>> 0; + }, + getSeed: function getSeed() { + return seed; + }, + rand: function rand() { + // define the recurrence relationship + z = (a * z + c) % m; + // return a float in [0, 1) + // if z = m then z / m = 0 therefore (z % m) / m < 1 always + return z / m; + } + }; + }(); + lcg.setSeed(seed); + perlin = new Array(PERLIN_SIZE + 1); + for (var i = 0; i < PERLIN_SIZE + 1; i++) { + perlin[i] = lcg.rand(); + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303 + } + ], + 336: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.number.is-finite'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.number.is-finite'); + _dereq_('core-js/modules/es.string.sub'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * @module Math + * @submodule Vector + * @requires constants + */ + /** + * A class to describe a two or three-dimensional vector. + * + * A vector can be thought of in different ways. In one view, a vector is like + * an arrow pointing in space. Vectors have both magnitude (length) and + * direction. + * + * `p5.Vector` objects are often used to program motion because they simplify + * the math. For example, a moving ball has a position and a velocity. + * Position describes where the ball is in space. The ball's position vector + * extends from the origin to the ball's center. Velocity describes the ball's + * speed and the direction it's moving. If the ball is moving straight up, its + * velocity vector points straight up. Adding the ball's velocity vector to + * its position vector moves it, as in `pos.add(vel)`. Vector math relies on + * methods inside the `p5.Vector` class. + * + * Note: createVector() is the recommended way + * to make an instance of this class. + * + * @class p5.Vector + * @constructor + * @param {Number} [x] x component of the vector. + * @param {Number} [y] y component of the vector. + * @param {Number} [z] z component of the vector. + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create p5.Vector objects. + * let p1 = createVector(25, 25); + * let p2 = createVector(75, 75); + * + * // Style the points. + * strokeWeight(5); + * + * // Draw the first point using a p5.Vector. + * point(p1); + * + * // Draw the second point using a p5.Vector's components. + * point(p2.x, p2.y); + * + * describe('Two black dots on a gray square, one at the top left and the other at the bottom right.'); + * } + * + *
        + * + *
        + * + * let pos; + * let vel; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create p5.Vector objects. + * pos = createVector(50, 100); + * vel = createVector(0, -1); + * + * describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.'); + * } + * + * function draw() { + * background(200); + * + * // Add velocity to position. + * pos.add(vel); + * + * // If the dot reaches the top of the canvas, + * // restart from the bottom. + * if (pos.y < 0) { + * pos.y = 100; + * } + * + * // Draw the dot. + * strokeWeight(5); + * point(pos); + * } + * + *
        + */ + + _main.default.Vector = /*#__PURE__*/ function () { + // This is how it comes in with createVector() + // This check if the first argument is a function + function _class() { + _classCallCheck(this, _class); + var x, + y, + z; + if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'function') { + this.isPInst = true; + this._fromRadians = arguments.length <= 0 ? undefined : arguments[0]; + this._toRadians = arguments.length <= 1 ? undefined : arguments[1]; + x = (arguments.length <= 2 ? undefined : arguments[2]) || 0; + y = (arguments.length <= 3 ? undefined : arguments[3]) || 0; + z = (arguments.length <= 4 ? undefined : arguments[4]) || 0; + // This is what we'll get with new p5.Vector() + } else { + x = (arguments.length <= 0 ? undefined : arguments[0]) || 0; + y = (arguments.length <= 1 ? undefined : arguments[1]) || 0; + z = (arguments.length <= 2 ? undefined : arguments[2]) || 0; + } /** + * The x component of the vector + * @type {Number} + * @property x + * @name x + */ + + this.x = x; + /** + * The y component of the vector + * @type {Number} + * @property y + * @name y + */ + this.y = y; + /** + * The z component of the vector + * @type {Number} + * @property z + * @name z + */ + this.z = z; + } /** + * Returns a string representation of a vector. + * + * Calling `toString()` is useful for printing vectors to the console while + * debugging. + * + * @method toString + * @return {String} string representation of the vector. + * + * @example + *
        + * + * function setup() { + * let v = createVector(20, 30); + * + * // Prints 'p5.Vector Object : [20, 30, 0]'. + * print(v.toString()); + * } + * + *
        + */ + + _createClass(_class, [ + { + key: 'toString', + value: function toString() { + return 'p5.Vector Object : ['.concat(this.x, ', ').concat(this.y, ', ').concat(this.z, ']'); + } /** + * Sets the vector's `x`, `y`, and `z` components. + * + * `set()` can use separate numbers, as in `v.set(1, 2, 3)`, a + * p5.Vector object, as in `v.set(v2)`, or an + * array of numbers, as in `v.set([1, 2, 3])`. + * + * If a value isn't provided for a component, it will be set to 0. For + * example, `v.set(4, 5)` sets `v.x` to 4, `v.y` to 5, and `v.z` to 0. + * Calling `set()` with no arguments, as in `v.set()`, sets all the vector's + * components to 0. + * + * @method set + * @param {Number} [x] x component of the vector. + * @param {Number} [y] y component of the vector. + * @param {Number} [z] z component of the vector. + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Top left. + * let pos = createVector(25, 25); + * point(pos); + * + * // Top right. + * // set() with numbers. + * pos.set(75, 25); + * point(pos); + * + * // Bottom right. + * // set() with a p5.Vector. + * let p2 = createVector(75, 75); + * pos.set(p2); + * point(pos); + * + * // Bottom left. + * // set() with an array. + * let arr = [25, 75]; + * pos.set(arr); + * point(pos); + * + * describe('Four black dots arranged in a square on a gray background.'); + * } + * + *
        + */ + /** + * @method set + * @param {p5.Vector|Number[]} value vector to set. + * @chainable + */ + + }, + { + key: 'set', + value: function set(x, y, z) { + if (x instanceof _main.default.Vector) { + this.x = x.x || 0; + this.y = x.y || 0; + this.z = x.z || 0; + return this; + } + if (Array.isArray(x)) { + this.x = x[0] || 0; + this.y = x[1] || 0; + this.z = x[2] || 0; + return this; + } + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + return this; + } /** + * Returns a copy of the p5.Vector object. + * + * @method copy + * @return {p5.Vector} copy of the p5.Vector object. + * + * @example + *
        + * + * function setup() { + * createCanvas(100 ,100); + * + * background(200); + * + * // Create a p5.Vector object. + * let pos = createVector(50, 50); + * + * // Make a copy. + * let pc = pos.copy(); + * + * // Draw the point. + * strokeWeight(5); + * point(pc); + * + * describe('A black point drawn in the middle of a gray square.'); + * } + * + *
        + */ + + }, + { + key: 'copy', + value: function copy() { + if (this.isPInst) { + return new _main.default.Vector(this._fromRadians, this._toRadians, this.x, this.y, this.z); + } else { + return new _main.default.Vector(this.x, this.y, this.z); + } + } /** + * Adds to a vector's `x`, `y`, and `z` components. + * + * `add()` can use separate numbers, as in `v.add(1, 2, 3)`, + * another p5.Vector object, as in `v.add(v2)`, or + * an array of numbers, as in `v.add([1, 2, 3])`. + * + * If a value isn't provided for a component, it won't change. For + * example, `v.add(4, 5)` adds 4 to `v.x`, 5 to `v.y`, and 0 to `v.z`. + * Calling `add()` with no arguments, as in `v.add()`, has no effect. + * + * The static version of `add()`, as in `p5.Vector.add(v2, v1)`, returns a new + * p5.Vector object and doesn't change the + * originals. + * + * @method add + * @param {Number} x x component of the vector to be added. + * @param {Number} [y] y component of the vector to be added. + * @param {Number} [z] z component of the vector to be added. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Top left. + * let pos = createVector(25, 25); + * point(pos); + * + * // Top right. + * // Add numbers. + * pos.add(50, 0); + * point(pos); + * + * // Bottom right. + * // Add a p5.Vector. + * let p2 = createVector(0, 50); + * pos.add(p2); + * point(pos); + * + * // Bottom left. + * // Add an array. + * let arr = [-50, 0]; + * pos.add(arr); + * point(pos); + * + * describe('Four black dots arranged in a square on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top left. + * let p1 = createVector(25, 25); + * + * // Center. + * let p2 = createVector(50, 50); + * + * // Bottom right. + * // Add p1 and p2. + * let p3 = p5.Vector.add(p1, p2); + * + * // Draw the points. + * strokeWeight(5); + * point(p1); + * point(p2); + * point(p3); + * + * describe('Three black dots in a diagonal line from top left to bottom right.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Three arrows drawn on a gray square. A red arrow extends from the top left corner to the center. A blue arrow extends from the tip of the red arrow. A purple arrow extends from the origin to the tip of the blue arrow.'); + * } + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * + * // Draw the red arrow. + * let v1 = createVector(50, 50); + * drawArrow(origin, v1, 'red'); + * + * // Draw the blue arrow. + * let v2 = createVector(-30, 20); + * drawArrow(v1, v2, 'blue'); + * + * // Purple arrow. + * let v3 = p5.Vector.add(v1, v2); + * drawArrow(origin, v3, 'purple'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + /** + * @method add + * @param {p5.Vector|Number[]} value The vector to add + * @chainable + */ + + }, + { + key: 'add', + value: function add(x, y, z) { + if (x instanceof _main.default.Vector) { + this.x += x.x || 0; + this.y += x.y || 0; + this.z += x.z || 0; + return this; + } + if (Array.isArray(x)) { + this.x += x[0] || 0; + this.y += x[1] || 0; + this.z += x[2] || 0; + return this; + } + this.x += x || 0; + this.y += y || 0; + this.z += z || 0; + return this; + } /** + * @private + * @chainable + */ + + }, + { + key: 'calculateRemainder2D', + value: function calculateRemainder2D(xComponent, yComponent) { + if (xComponent !== 0) { + this.x = this.x % xComponent; + } + if (yComponent !== 0) { + this.y = this.y % yComponent; + } + return this; + } /** + * @private + * @chainable + */ + + }, + { + key: 'calculateRemainder3D', + value: function calculateRemainder3D(xComponent, yComponent, zComponent) { + if (xComponent !== 0) { + this.x = this.x % xComponent; + } + if (yComponent !== 0) { + this.y = this.y % yComponent; + } + if (zComponent !== 0) { + this.z = this.z % zComponent; + } + return this; + } /** + * Performs modulo (remainder) division with a vector's `x`, `y`, and `z` + * components. + * + * `rem()` can use separate numbers, as in `v.rem(1, 2, 3)`, + * another p5.Vector object, as in `v.rem(v2)`, or + * an array of numbers, as in `v.rem([1, 2, 3])`. + * + * If only one value is provided, as in `v.rem(2)`, then all the components + * will be set to their values modulo 2. If two values are provided, as in + * `v.rem(2, 3)`, then `v.z` won't change. Calling `rem()` with no + * arguments, as in `v.rem()`, has no effect. + * + * The static version of `rem()`, as in `p5.Vector.rem(v2, v1)`, returns a + * new p5.Vector object and doesn't change the + * originals. + * + * @method rem + * @param {Number} x x component of divisor vector. + * @param {Number} y y component of divisor vector. + * @param {Number} z z component of divisor vector. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(3, 4, 5); + * + * // Divide numbers. + * v.rem(2); + * + * // Prints 'p5.Vector Object : [1, 0, 1]'. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(3, 4, 5); + * + * // Divide numbers. + * v.rem(2, 3); + * + * // Prints 'p5.Vector Object : [1, 1, 5]'. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(3, 4, 5); + * + * // Divide numbers. + * v.rem(2, 3, 4); + * + * // Prints 'p5.Vector Object : [1, 1, 1]'. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v1 = createVector(3, 4, 5); + * let v2 = createVector(2, 3, 4); + * + * // Divide a p5.Vector. + * v1.rem(v2); + * + * // Prints 'p5.Vector Object : [1, 1, 1]'. + * print(v1.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(3, 4, 5); + * + * // Divide an array. + * let arr = [2, 3, 4]; + * v.rem(arr); + * + * // Prints 'p5.Vector Object : [1, 1, 1]'. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v1 = createVector(3, 4, 5); + * let v2 = createVector(2, 3, 4); + * + * // Divide without modifying the original vectors. + * let v3 = p5.Vector.rem(v1, v2); + * + * // Prints 'p5.Vector Object : [1, 1, 1]'. + * print(v3.toString()); + * } + * + *
        + */ + /** + * @method rem + * @param {p5.Vector | Number[]} value divisor vector. + * @chainable + */ + + }, + { + key: 'rem', + value: function rem() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + var x = args[0], + y = args[1], + z = args[2]; + if (x instanceof _main.default.Vector) { + if ([x.x, + x.y, + x.z].every(Number.isFinite)) { + var xComponent = parseFloat(x.x); + var yComponent = parseFloat(x.y); + var zComponent = parseFloat(x.z); + return this.calculateRemainder3D(xComponent, yComponent, zComponent); + } + } else if (Array.isArray(x)) { + if (x.every(Number.isFinite)) { + if (x.length === 2) { + return this.calculateRemainder2D(x[0], x[1]); + } + if (x.length === 3) { + return this.calculateRemainder3D(x[0], x[1], x[2]); + } + } + } else if (args.length === 1) { + if (Number.isFinite(x) && x !== 0) { + this.x = this.x % x; + this.y = this.y % x; + this.z = this.z % x; + return this; + } + } else if (args.length === 2) { + if (args.every(Number.isFinite)) { + return this.calculateRemainder2D(x, y); + } + } else if (args.length === 3) { + if (args.every(Number.isFinite)) { + return this.calculateRemainder3D(x, y, z); + } + } + } /** + * Subtracts from a vector's `x`, `y`, and `z` components. + * + * `sub()` can use separate numbers, as in `v.sub(1, 2, 3)`, another + * p5.Vector object, as in `v.sub(v2)`, or an array + * of numbers, as in `v.sub([1, 2, 3])`. + * + * If a value isn't provided for a component, it won't change. For + * example, `v.sub(4, 5)` subtracts 4 from `v.x`, 5 from `v.y`, and 0 from `v.z`. + * Calling `sub()` with no arguments, as in `v.sub()`, has no effect. + * + * The static version of `sub()`, as in `p5.Vector.sub(v2, v1)`, returns a new + * p5.Vector object and doesn't change the + * originals. + * + * @method sub + * @param {Number} x x component of the vector to subtract. + * @param {Number} [y] y component of the vector to subtract. + * @param {Number} [z] z component of the vector to subtract. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Bottom right. + * let pos = createVector(75, 75); + * point(pos); + * + * // Top right. + * // Subtract numbers. + * pos.sub(0, 50); + * point(pos); + * + * // Top left. + * // Subtract a p5.Vector. + * let p2 = createVector(50, 0); + * pos.sub(p2); + * point(pos); + * + * // Bottom left. + * // Subtract an array. + * let arr = [0, -50]; + * pos.sub(arr); + * point(pos); + * + * describe('Four black dots arranged in a square on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create p5.Vector objects. + * let p1 = createVector(75, 75); + * let p2 = createVector(50, 50); + * + * // Subtract with modifying the original vectors. + * let p3 = p5.Vector.sub(p1, p2); + * + * // Draw the points. + * strokeWeight(5); + * point(p1); + * point(p2); + * point(p3); + * + * describe('Three black dots in a diagonal line from top left to bottom right.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Three arrows drawn on a gray square. A red and a blue arrow extend from the top left. A purple arrow extends from the tip of the red arrow to the tip of the blue arrow.'); + * } + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * + * // Draw the red arrow. + * let v1 = createVector(50, 50); + * drawArrow(origin, v1, 'red'); + * + * // Draw the blue arrow. + * let v2 = createVector(20, 70); + * drawArrow(origin, v2, 'blue'); + * + * // Purple arrow. + * let v3 = p5.Vector.sub(v2, v1); + * drawArrow(v1, v3, 'purple'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + /** + * @method sub + * @param {p5.Vector|Number[]} value the vector to subtract + * @chainable + */ + + }, + { + key: 'sub', + value: function sub(x, y, z) { + if (x instanceof _main.default.Vector) { + this.x -= x.x || 0; + this.y -= x.y || 0; + this.z -= x.z || 0; + return this; + } + if (Array.isArray(x)) { + this.x -= x[0] || 0; + this.y -= x[1] || 0; + this.z -= x[2] || 0; + return this; + } + this.x -= x || 0; + this.y -= y || 0; + this.z -= z || 0; + return this; + } /** + * Multiplies a vector's `x`, `y`, and `z` components. + * + * `mult()` can use separate numbers, as in `v.mult(1, 2, 3)`, another + * p5.Vector object, as in `v.mult(v2)`, or an array + * of numbers, as in `v.mult([1, 2, 3])`. + * + * If only one value is provided, as in `v.mult(2)`, then all the components + * will be multiplied by 2. If a value isn't provided for a component, it + * won't change. For example, `v.mult(4, 5)` multiplies `v.x` by, `v.y` by 5, + * and `v.z` by 1. Calling `mult()` with no arguments, as in `v.mult()`, has + * no effect. + * + * The static version of `mult()`, as in `p5.Vector.mult(v, 2)`, returns a new + * p5.Vector object and doesn't change the + * originals. + * + * @method mult + * @param {Number} n The number to multiply with the vector + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Top-left. + * let p = createVector(25, 25); + * point(p); + * + * // Center. + * // Multiply all components by 2. + * p.mult(2); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * strokeWeight(5); + * + * // Top-left. + * let p = createVector(25, 25); + * point(p); + * + * // Bottom-right. + * // Multiply p.x * 2 and p.y * 3 + * p.mult(2, 3); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Top-left. + * let p = createVector(25, 25); + * point(p); + * + * // Bottom-right. + * // Multiply p.x * 2 and p.y * 3 + * let arr = [2, 3]; + * p.mult(arr); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Top-left. + * let p = createVector(25, 25); + * point(p); + * + * // Bottom-right. + * // Multiply p.x * p2.x and p.y * p2.y + * let p2 = createVector(2, 3); + * p.mult(p2); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Top-left. + * let p = createVector(25, 25); + * point(p); + * + * // Bottom-right. + * // Create a new p5.Vector with + * // p3.x = p.x * p2.x + * // p3.y = p.y * p2.y + * let p2 = createVector(2, 3); + * let p3 = p5.Vector.mult(p, p2); + * point(p3); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Two arrows extending from the top left corner. The blue arrow is twice the length of the red arrow.'); + * } + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * + * // Draw the red arrow. + * let v1 = createVector(25, 25); + * drawArrow(origin, v1, 'red'); + * + * // Draw the blue arrow. + * let v2 = p5.Vector.mult(v1, 2); + * drawArrow(origin, v2, 'blue'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + /** + * @method mult + * @param {Number} x number to multiply with the x component of the vector. + * @param {Number} y number to multiply with the y component of the vector. + * @param {Number} [z] number to multiply with the z component of the vector. + * @chainable + */ + /** + * @method mult + * @param {Number[]} arr array to multiply with the components of the vector. + * @chainable + */ + /** + * @method mult + * @param {p5.Vector} v vector to multiply with the components of the original vector. + * @chainable + */ + + }, + { + key: 'mult', + value: function mult() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + var x = args[0], + y = args[1], + z = args[2]; + if (x instanceof _main.default.Vector) { + // new p5.Vector will check that values are valid upon construction but it's possible + // that someone could change the value of a component after creation, which is why we still + // perform this check + if (Number.isFinite(x.x) && Number.isFinite(x.y) && Number.isFinite(x.z) && typeof x.x === 'number' && typeof x.y === 'number' && typeof x.z === 'number') { + this.x *= x.x; + this.y *= x.y; + this.z *= x.z; + } else { + console.warn('p5.Vector.prototype.mult:', 'x contains components that are either undefined or not finite numbers'); + } + return this; + } + if (Array.isArray(x)) { + if (x.every(function (element) { + return Number.isFinite(element); + }) && x.every(function (element) { + return typeof element === 'number'; + })) { + if (x.length === 1) { + this.x *= x[0]; + this.y *= x[0]; + this.z *= x[0]; + } else if (x.length === 2) { + this.x *= x[0]; + this.y *= x[1]; + } else if (x.length === 3) { + this.x *= x[0]; + this.y *= x[1]; + this.z *= x[2]; + } + } else { + console.warn('p5.Vector.prototype.mult:', 'x contains elements that are either undefined or not finite numbers'); + } + return this; + } + var vectorComponents = args; + if (vectorComponents.every(function (element) { + return Number.isFinite(element); + }) && vectorComponents.every(function (element) { + return typeof element === 'number'; + })) { + if (args.length === 1) { + this.x *= x; + this.y *= x; + this.z *= x; + } + if (args.length === 2) { + this.x *= x; + this.y *= y; + } + if (args.length === 3) { + this.x *= x; + this.y *= y; + this.z *= z; + } + } else { + console.warn('p5.Vector.prototype.mult:', 'x, y, or z arguments are either undefined or not a finite number'); + } + return this; + } /** + * Divides a vector's `x`, `y`, and `z` components. + * + * `div()` can use separate numbers, as in `v.div(1, 2, 3)`, another + * p5.Vector object, as in `v.div(v2)`, or an array + * of numbers, as in `v.div([1, 2, 3])`. + * + * If only one value is provided, as in `v.div(2)`, then all the components + * will be divided by 2. If a value isn't provided for a component, it + * won't change. For example, `v.div(4, 5)` divides `v.x` by, `v.y` by 5, + * and `v.z` by 1. Calling `div()` with no arguments, as in `v.div()`, has + * no effect. + * + * The static version of `div()`, as in `p5.Vector.div(v, 2)`, returns a new + * p5.Vector object and doesn't change the + * originals. + * + * @method div + * @param {number} n The number to divide the vector by + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Center. + * let p = createVector(50, 50); + * point(p); + * + * // Top-left. + * // Divide p.x / 2 and p.y / 2 + * p.div(2); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Bottom-right. + * let p = createVector(50, 75); + * point(p); + * + * // Top-left. + * // Divide p.x / 2 and p.y / 3 + * p.div(2, 3); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Bottom-right. + * let p = createVector(50, 75); + * point(p); + * + * // Top-left. + * // Divide p.x / 2 and p.y / 3 + * let arr = [2, 3]; + * p.div(arr); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Bottom-right. + * let p = createVector(50, 75); + * point(p); + * + * // Top-left. + * // Divide p.x / 2 and p.y / 3 + * let p2 = createVector(2, 3); + * p.div(p2); + * point(p); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the points. + * strokeWeight(5); + * + * // Bottom-right. + * let p = createVector(50, 75); + * point(p); + * + * // Top-left. + * // Create a new p5.Vector with + * // p3.x = p.x / p2.x + * // p3.y = p.y / p2.y + * let p2 = createVector(2, 3); + * let p3 = p5.Vector.div(p, p2); + * point(p3); + * + * describe('Two black dots drawn on a gray square. One dot is in the top left corner and the other is in the bottom center.'); + * } + * + *
        + * + *
        + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * + * // Draw the red arrow. + * let v1 = createVector(50, 50); + * drawArrow(origin, v1, 'red'); + * + * // Draw the blue arrow. + * let v2 = p5.Vector.div(v1, 2); + * drawArrow(origin, v2, 'blue'); + * + * describe('Two arrows extending from the top left corner. The blue arrow is half the length of the red arrow.'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + /** + * @method div + * @param {Number} x number to divide with the x component of the vector. + * @param {Number} y number to divide with the y component of the vector. + * @param {Number} [z] number to divide with the z component of the vector. + * @chainable + */ + /** + * @method div + * @param {Number[]} arr array to divide the components of the vector by. + * @chainable + */ + /** + * @method div + * @param {p5.Vector} v vector to divide the components of the original vector by. + * @chainable + */ + + }, + { + key: 'div', + value: function div() { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + var x = args[0], + y = args[1], + z = args[2]; + if (x instanceof _main.default.Vector) { + // new p5.Vector will check that values are valid upon construction but it's possible + // that someone could change the value of a component after creation, which is why we still + // perform this check + if (Number.isFinite(x.x) && Number.isFinite(x.y) && Number.isFinite(x.z) && typeof x.x === 'number' && typeof x.y === 'number' && typeof x.z === 'number') { + var isLikely2D = x.z === 0 && this.z === 0; + if (x.x === 0 || x.y === 0 || !isLikely2D && x.z === 0) { + console.warn('p5.Vector.prototype.div:', 'divide by 0'); + return this; + } + this.x /= x.x; + this.y /= x.y; + if (!isLikely2D) { + this.z /= x.z; + } + } else { + console.warn('p5.Vector.prototype.div:', 'x contains components that are either undefined or not finite numbers'); + } + return this; + } + if (Array.isArray(x)) { + if (x.every(Number.isFinite) && x.every(function (element) { + return typeof element === 'number'; + })) { + if (x.some(function (element) { + return element === 0; + })) { + console.warn('p5.Vector.prototype.div:', 'divide by 0'); + return this; + } + if (x.length === 1) { + this.x /= x[0]; + this.y /= x[0]; + this.z /= x[0]; + } else if (x.length === 2) { + this.x /= x[0]; + this.y /= x[1]; + } else if (x.length === 3) { + this.x /= x[0]; + this.y /= x[1]; + this.z /= x[2]; + } + } else { + console.warn('p5.Vector.prototype.div:', 'x contains components that are either undefined or not finite numbers'); + } + return this; + } + if (args.every(Number.isFinite) && args.every(function (element) { + return typeof element === 'number'; + })) { + if (args.some(function (element) { + return element === 0; + })) { + console.warn('p5.Vector.prototype.div:', 'divide by 0'); + return this; + } + if (args.length === 1) { + this.x /= x; + this.y /= x; + this.z /= x; + } + if (args.length === 2) { + this.x /= x; + this.y /= y; + } + if (args.length === 3) { + this.x /= x; + this.y /= y; + this.z /= z; + } + } else { + console.warn('p5.Vector.prototype.div:', 'x, y, or z arguments are either undefined or not a finite number'); + } + return this; + } /** + * Calculates the magnitude (length) of the vector. + * + * Use mag() to calculate the magnitude of a 2D vector + * using components as in `mag(x, y)`. + * + * @method mag + * @return {Number} magnitude of the vector. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Vector object. + * let p = createVector(30, 40); + * + * // Draw a line from the origin. + * line(0, 0, p.x, p.y); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the vector's magnitude. + * let m = p.mag(); + * text(m, p.x, p.y); + * + * describe('A diagonal black line extends from the top left corner of a gray square. The number 50 is written at the end of the line.'); + * } + * + *
        + */ + + }, + { + key: 'mag', + value: function mag() { + return Math.sqrt(this.magSq()); + } /** + * Calculates the magnitude (length) of the vector squared. + * + * @method magSq + * @return {number} squared magnitude of the vector. + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Vector object. + * let p = createVector(30, 40); + * + * // Draw a line from the origin. + * line(0, 0, p.x, p.y); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * + * // Display the vector's magnitude squared. + * let m = p.magSq(); + * text(m, p.x, p.y); + * + * describe('A diagonal black line extends from the top left corner of a gray square. The number 2500 is written at the end of the line.'); + * } + * + *
        + */ + + }, + { + key: 'magSq', + value: function magSq() { + var x = this.x; + var y = this.y; + var z = this.z; + return x * x + y * y + z * z; + } /** + * Calculates the dot product of two vectors. + * + * The dot product is a number that describes the overlap between two vectors. + * Visually, the dot product can be thought of as the "shadow" one vector + * casts on another. The dot product's magnitude is largest when two vectors + * point in the same or opposite directions. Its magnitude is 0 when two + * vectors form a right angle. + * + * The version of `dot()` with one parameter interprets it as another + * p5.Vector object. + * + * The version of `dot()` with multiple parameters interprets them as the + * `x`, `y`, and `z` components of another vector. + * + * The static version of `dot()`, as in `p5.Vector.dot(v1, v2)`, is the same + * as calling `v1.dot(v2)`. + * + * @method dot + * @param {Number} x x component of the vector. + * @param {Number} [y] y component of the vector. + * @param {Number} [z] z component of the vector. + * @return {Number} dot product. + * + * @example + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v1 = createVector(3, 4); + * let v2 = createVector(3, 0); + * + * // Calculate the dot product. + * let dp = v1.dot(v2); + * + * // Prints "9" to the console. + * print(dp); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v1 = createVector(1, 0); + * let v2 = createVector(0, 1); + * + * // Calculate the dot product. + * let dp = p5.Vector.dot(v1, v2); + * + * // Prints "0" to the console. + * print(dp); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Two arrows drawn on a gray square. A black arrow points to the right and a red arrow follows the mouse. The text "v1 • v2 = something" changes as the mouse moves.'); + * } + * + * function draw() { + * background(200); + * + * // Center. + * let v0 = createVector(50, 50); + * + * // Draw the black arrow. + * let v1 = createVector(30, 0); + * drawArrow(v0, v1, 'black'); + * + * // Draw the red arrow. + * let v2 = createVector(mouseX - 50, mouseY - 50); + * drawArrow(v0, v2, 'red'); + * + * // Display the dot product. + * let dp = v2.dot(v1); + * text(`v2 • v1 = ${dp}`, 10, 20); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + /** + * @method dot + * @param {p5.Vector} v p5.Vector to be dotted. + * @return {Number} + */ + + }, + { + key: 'dot', + value: function dot(x, y, z) { + if (x instanceof _main.default.Vector) { + return this.dot(x.x, x.y, x.z); + } + return this.x * (x || 0) + this.y * (y || 0) + this.z * (z || 0); + } /** + * Calculates the cross product of two vectors. + * + * The cross product is a vector that points straight out of the plane created + * by two vectors. The cross product's magnitude is the area of the parallelogram + * formed by the original two vectors. + * + * The static version of `cross()`, as in `p5.Vector.cross(v1, v2)`, is the same + * as calling `v1.cross(v2)`. + * + * @method cross + * @param {p5.Vector} v p5.Vector to be crossed. + * @return {p5.Vector} cross product as a p5.Vector. + * + * @example + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v1 = createVector(1, 0); + * let v2 = createVector(3, 4); + * + * // Calculate the cross product. + * let cp = v1.cross(v2); + * + * // Prints "p5.Vector Object : [0, 0, 4]" to the console. + * print(cp.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v1 = createVector(1, 0); + * let v2 = createVector(3, 4); + * + * // Calculate the cross product. + * let cp = p5.Vector.cross(v1, v2); + * + * // Prints "p5.Vector Object : [0, 0, 4]" to the console. + * print(cp.toString()); + * } + * + *
        + */ + + }, + { + key: 'cross', + value: function cross(v) { + var x = this.y * v.z - this.z * v.y; + var y = this.z * v.x - this.x * v.z; + var z = this.x * v.y - this.y * v.x; + if (this.isPInst) { + return new _main.default.Vector(this._fromRadians, this._toRadians, x, y, z); + } else { + return new _main.default.Vector(x, y, z); + } + } /** + * Calculates the distance between two points represented by vectors. + * + * A point's coordinates can be represented by the components of a vector + * that extends from the origin to the point. + * + * The static version of `dist()`, as in `p5.Vector.dist(v1, v2)`, is the same + * as calling `v1.dist(v2)`. + * + * Use dist() to calculate the distance between points + * using coordinates as in `dist(x1, y1, x2, y2)`. + * + * @method dist + * @param {p5.Vector} v x, y, and z coordinates of a p5.Vector. + * @return {Number} distance. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create p5.Vector objects. + * let v1 = createVector(1, 0); + * let v2 = createVector(0, 1); + * + * // Calculate the distance between them. + * let d = v1.dist(v2); + * + * // Prints "1.414..." to the console. + * print(d); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create p5.Vector objects. + * let v1 = createVector(1, 0); + * let v2 = createVector(0, 1); + * + * // Calculate the distance between them. + * let d = p5.Vector.dist(v1, v2); + * + * // Prints "1.414..." to the console. + * print(d); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Three arrows drawn on a gray square. A red and a blue arrow extend from the top left. A purple arrow extends from the tip of the red arrow to the tip of the blue arrow. The number 36 is written in black near the purple arrow.'); + * } + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * + * // Draw the red arrow. + * let v1 = createVector(50, 50); + * drawArrow(origin, v1, 'red'); + * + * // Draw the blue arrow. + * let v2 = createVector(20, 70); + * drawArrow(origin, v2, 'blue'); + * + * // Purple arrow. + * let v3 = p5.Vector.sub(v2, v1); + * drawArrow(v1, v3, 'purple'); + * + * // Style the text. + * textAlign(CENTER); + * + * // Display the magnitude. + * let m = floor(v3.mag()); + * text(m, 50, 75); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'dist', + value: function dist(v) { + return v.copy().sub(this).mag(); + } /** + * Scales the components of a p5.Vector object so + * that its magnitude is 1. + * + * The static version of `normalize()`, as in `p5.Vector.normalize(v)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method normalize + * @return {p5.Vector} normalized p5.Vector. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Vector. + * let v = createVector(10, 20, 2); + * + * // Normalize. + * v.normalize(); + * + * // Prints "p5.Vector Object : [0.445..., 0.890..., 0.089...]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a p5.Vector. + * let v0 = createVector(10, 20, 2); + * + * // Create a normalized copy. + * let v1 = p5.Vector.normalize(v0); + * + * // Prints "p5.Vector Object : [10, 20, 2]" to the console. + * print(v0.toString()); + * // Prints "p5.Vector Object : [0.445..., 0.890..., 0.089...]" to the console. + * print(v1.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe("A red and blue arrow extend from the center of a circle. Both arrows follow the mouse, but the blue arrow's length is fixed to the circle's radius."); + * } + * + * function draw() { + * background(240); + * + * // Vector to the center. + * let v0 = createVector(50, 50); + * + * // Vector from the center to the mouse. + * let v1 = createVector(mouseX - 50, mouseY - 50); + * + * // Circle's radius. + * let r = 25; + * + * // Draw the red arrow. + * drawArrow(v0, v1, 'red'); + * + * // Draw the blue arrow. + * v1.normalize(); + * drawArrow(v0, v1.mult(r), 'blue'); + * + * // Draw the circle. + * noFill(); + * circle(50, 50, r * 2); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'normalize', + value: function normalize() { + var len = this.mag(); + // here we multiply by the reciprocal instead of calling 'div()' + // since div duplicates this zero check. + if (len !== 0) this.mult(1 / len); + return this; + } /** + * Limits a vector's magnitude to a maximum value. + * + * The static version of `limit()`, as in `p5.Vector.limit(v, 5)`, returns a + * new p5.Vector object and doesn't change the + * original. + * + * @method limit + * @param {Number} max maximum magnitude for the vector. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(10, 20, 2); + * + * // Limit its magnitude. + * v.limit(5); + * + * // Prints "p5.Vector Object : [2.227..., 4.454..., 0.445...]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v0 = createVector(10, 20, 2); + * + * // Create a copy an limit its magintude. + * let v1 = p5.Vector.limit(v0, 5); + * + * // Prints "p5.Vector Object : [2.227..., 4.454..., 0.445...]" to the console. + * print(v1.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe("A red and blue arrow extend from the center of a circle. Both arrows follow the mouse, but the blue arrow never crosses the circle's edge."); + * } + * function draw() { + * background(240); + * + * // Vector to the center. + * let v0 = createVector(50, 50); + * + * // Vector from the center to the mouse. + * let v1 = createVector(mouseX - 50, mouseY - 50); + * + * // Circle's radius. + * let r = 25; + * + * // Draw the red arrow. + * drawArrow(v0, v1, 'red'); + * + * // Draw the blue arrow. + * drawArrow(v0, v1.limit(r), 'blue'); + * + * // Draw the circle. + * noFill(); + * circle(50, 50, r * 2); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'limit', + value: function limit(max) { + var mSq = this.magSq(); + if (mSq > max * max) { + this.div(Math.sqrt(mSq)) //normalize it + .mult(max); + } + return this; + } /** + * Sets a vector's magnitude to a given value. + * + * The static version of `setMag()`, as in `p5.Vector.setMag(v, 10)`, returns + * a new p5.Vector object and doesn't change the + * original. + * + * @method setMag + * @param {number} len new length for this vector. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(3, 4, 0); + * + * // Prints "5" to the console. + * print(v.mag()); + * + * // Set its magnitude to 10. + * v.setMag(10); + * + * // Prints "p5.Vector Object : [6, 8, 0]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v0 = createVector(3, 4, 0); + * + * // Create a copy with a magnitude of 10. + * let v1 = p5.Vector.setMag(v0, 10); + * + * // Prints "5" to the console. + * print(v0.mag()); + * + * // Prints "p5.Vector Object : [6, 8, 0]" to the console. + * print(v1.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Two arrows extend from the top left corner of a square toward its center. The red arrow reaches the center and the blue arrow only extends part of the way.'); + * } + * + * function draw() { + * background(240); + * + * let origin = createVector(0, 0); + * let v = createVector(50, 50); + * + * // Draw the red arrow. + * drawArrow(origin, v, 'red'); + * + * // Set v's magnitude to 30. + * v.setMag(30); + * + * // Draw the blue arrow. + * drawArrow(origin, v, 'blue'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'setMag', + value: function setMag(n) { + return this.normalize().mult(n); + } /** + * Calculates the angle a 2D vector makes with the positive x-axis. + * + * By convention, the positive x-axis has an angle of 0. Angles increase in + * the clockwise direction. + * + * If the vector was created with + * createVector(), `heading()` returns angles + * in the units of the current angleMode(). + * + * The static version of `heading()`, as in `p5.Vector.heading(v)`, works the + * same way. + * + * @method heading + * @return {Number} angle of rotation. + * + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(1, 1); + * + * // Prints "0.785..." to the console. + * print(v.heading()); + * + * // Use degrees. + * angleMode(DEGREES); + * + * // Prints "45" to the console. + * print(v.heading()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(1, 1); + * + * // Prints "0.785..." to the console. + * print(p5.Vector.heading(v)); + * + * // Use degrees. + * angleMode(DEGREES); + * + * // Prints "45" to the console. + * print(p5.Vector.heading(v)); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A black arrow extends from the top left of a square to its center. The text "Radians: 0.79" and "Degrees: 45" is written near the tip of the arrow.'); + * } + * + * function draw() { + * background(200); + * + * let origin = createVector(0, 0); + * let v = createVector(50, 50); + * + * // Draw the black arrow. + * drawArrow(origin, v, 'black'); + * + * // Use radians. + * angleMode(RADIANS); + * + * // Display the heading in radians. + * let h = round(v.heading(), 2); + * text(`Radians: ${h}`, 20, 70); + * + * // Use degrees. + * angleMode(DEGREES); + * + * // Display the heading in degrees. + * h = v.heading(); + * text(`Degrees: ${h}`, 20, 85); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'heading', + value: function heading() { + var h = Math.atan2(this.y, this.x); + if (this.isPInst) return this._fromRadians(h); + return h; + } /** + * Rotates a 2D vector to a specific angle without changing its magnitude. + * + * By convention, the positive x-axis has an angle of 0. Angles increase in + * the clockwise direction. + * + * If the vector was created with + * createVector(), `setHeading()` uses + * the units of the current angleMode(). + * + * @method setHeading + * @param {number} angle angle of rotation. + * @chainable + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(0, 1); + * + * // Prints "1.570..." to the console. + * print(v.heading()); + * + * // Point to the left. + * v.setHeading(PI); + * + * // Prints "3.141..." to the console. + * print(v.heading()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Use degrees. + * angleMode(DEGREES); + * + * // Create a p5.Vector object. + * let v = createVector(0, 1); + * + * // Prints "90" to the console. + * print(v.heading()); + * + * // Point to the left. + * v.setHeading(180); + * + * // Prints "180" to the console. + * print(v.heading()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Two arrows extend from the center of a gray square. The red arrow points to the right and the blue arrow points down.'); + * } + * + * function draw() { + * background(200); + * + * // Create p5.Vector objects. + * let v0 = createVector(50, 50); + * let v1 = createVector(30, 0); + * + * // Draw the red arrow. + * drawArrow(v0, v1, 'red'); + * + * // Point down. + * v1.setHeading(HALF_PI); + * + * // Draw the blue arrow. + * drawArrow(v0, v1, 'blue'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'setHeading', + value: function setHeading(a) { + if (this.isPInst) a = this._toRadians(a); + var m = this.mag(); + this.x = m * Math.cos(a); + this.y = m * Math.sin(a); + return this; + } /** + * Rotates a 2D vector by an angle without changing its magnitude. + * + * By convention, the positive x-axis has an angle of 0. Angles increase in + * the clockwise direction. + * + * If the vector was created with + * createVector(), `rotate()` uses + * the units of the current angleMode(). + * + * The static version of `rotate()`, as in `p5.Vector.rotate(v, PI)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method rotate + * @param {number} angle angle of rotation. + * @chainable + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(1, 0); + * + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v.toString()); + * + * // Rotate a quarter turn. + * v.rotate(HALF_PI); + * + * // Prints "p5.Vector Object : [0, 1, 0]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Use degrees. + * angleMode(DEGREES); + * + * // Create a p5.Vector object. + * let v = createVector(1, 0); + * + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v.toString()); + * + * // Rotate a quarter turn. + * v.rotate(90); + * + * // Prints "p5.Vector Object : [0, 1, 0]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v0 = createVector(1, 0); + * + * // Create a rotated copy. + * let v1 = p5.Vector.rotate(v0, HALF_PI); + * + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v0.toString()); + * // Prints "p5.Vector Object : [0, 1, 0]" to the console. + * print(v1.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Use degrees. + * angleMode(DEGREES); + * + * // Create a p5.Vector object. + * let v0 = createVector(1, 0); + * + * // Create a rotated copy. + * let v1 = p5.Vector.rotate(v0, 90); + * + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v0.toString()); + * + * // Prints "p5.Vector Object : [0, 1, 0]" to the console. + * print(v1.toString()); + * } + * + *
        + * + *
        + * + * let v0; + * let v1; + * + * function setup() { + * createCanvas(100, 100); + * + * // Create p5.Vector objects. + * v0 = createVector(50, 50); + * v1 = createVector(30, 0); + * + * describe('A black arrow extends from the center of a gray square. The arrow rotates clockwise.'); + * } + * + * function draw() { + * background(240); + * + * // Rotate v1. + * v1.rotate(0.01); + * + * // Draw the black arrow. + * drawArrow(v0, v1, 'black'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'rotate', + value: function rotate(a) { + var newHeading = this.heading() + a; + if (this.isPInst) newHeading = this._toRadians(newHeading); + var mag = this.mag(); + this.x = Math.cos(newHeading) * mag; + this.y = Math.sin(newHeading) * mag; + return this; + } /** + * Calculates the angle between two vectors. + * + * The angles returned are signed, which means that + * `v1.angleBetween(v2) === -v2.angleBetween(v1)`. + * + * If the vector was created with + * createVector(), `angleBetween()` returns + * angles in the units of the current + * angleMode(). + * + * @method angleBetween + * @param {p5.Vector} value x, y, and z components of a p5.Vector. + * @return {Number} angle between the vectors. + * @example + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v0 = createVector(1, 0); + * let v1 = createVector(0, 1); + * + * // Prints "1.570..." to the console. + * print(v0.angleBetween(v1)); + * + * // Prints "-1.570..." to the console. + * print(v1.angleBetween(v0)); + * } + * + *
        + * + *
        + * + * function setup() { + * // Use degrees. + * angleMode(DEGREES); + * // Create p5.Vector objects. + * let v0 = createVector(1, 0); + * let v1 = createVector(0, 1); + * + * // Prints "90" to the console. + * print(v0.angleBetween(v1)); + * + * // Prints "-90" to the console. + * print(v1.angleBetween(v0)); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v0 = createVector(1, 0); + * let v1 = createVector(0, 1); + * + * // Prints "1.570..." to the console. + * print(p5.Vector.angleBetween(v0, v1)); + * + * // Prints "-1.570..." to the console. + * print(p5.Vector.angleBetween(v1, v0)); + * } + * + *
        + * + *
        + * + * function setup() { + * // Use degrees. + * angleMode(DEGREES); + * + * // Create p5.Vector objects. + * let v0 = createVector(1, 0); + * let v1 = createVector(0, 1); + * + * // Prints "90" to the console. + * print(p5.Vector.angleBetween(v0, v1)); + * + * // Prints "-90" to the console. + * print(p5.Vector.angleBetween(v1, v0)); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Two arrows extend from the center of a gray square. A red arrow points to the right and a blue arrow points down. The text "Radians: 1.57" and "Degrees: 90" is written above the arrows.'); + * } + * function draw() { + * background(200); + * + * // Create p5.Vector objects. + * let v0 = createVector(50, 50); + * let v1 = createVector(30, 0); + * let v2 = createVector(0, 30); + * + * // Draw the red arrow. + * drawArrow(v0, v1, 'red'); + * + * // Draw the blue arrow. + * drawArrow(v0, v2, 'blue'); + * + * // Use radians. + * angleMode(RADIANS); + * + * // Display the angle in radians. + * let angle = round(v1.angleBetween(v2), 2); + * text(`Radians: ${angle}`, 20, 20); + * + * // Use degrees. + * angleMode(DEGREES); + * + * // Display the angle in degrees. + * angle = round(v1.angleBetween(v2), 2); + * text(`Degrees: ${angle}`, 20, 35); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'angleBetween', + value: function angleBetween(v) { + var magSqMult = this.magSq() * v.magSq(); + // Returns NaN if either vector is the zero vector. + if (magSqMult === 0) { + return NaN; + } + var u = this.cross(v); + // The dot product computes the cos value, and the cross product computes + // the sin value. Find the angle based on them. In addition, in the case of + // 2D vectors, a sign is added according to the direction of the vector. + var angle = Math.atan2(u.mag(), this.dot(v)) * Math.sign(u.z || 1); + if (this.isPInst) { + angle = this._fromRadians(angle); + } + return angle; + } /** + * Calculates new `x`, `y`, and `z` components that are proportionally the + * same distance between two vectors. + * + * The `amt` parameter is the amount to interpolate between the old vector and + * the new vector. 0.0 keeps all components equal to the old vector's, 0.5 is + * halfway between, and 1.0 sets all components equal to the new vector's. + * + * The static version of `lerp()`, as in `p5.Vector.lerp(v0, v1, 0.5)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method lerp + * @param {Number} x x component. + * @param {Number} y y component. + * @param {Number} z z component. + * @param {Number} amt amount of interpolation between 0.0 (old vector) + * and 1.0 (new vector). 0.5 is halfway between. + * @chainable + * + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v0 = createVector(1, 1, 1); + * let v1 = createVector(3, 3, 3); + * + * // Interpolate. + * v0.lerp(v1, 0.5); + * + * // Prints "p5.Vector Object : [2, 2, 2]" to the console. + * print(v0.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(1, 1, 1); + * + * // Interpolate. + * v.lerp(3, 3, 3, 0.5); + * + * // Prints "p5.Vector Object : [2, 2, 2]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v0 = createVector(1, 1, 1); + * let v1 = createVector(3, 3, 3); + * + * // Interpolate. + * let v2 = p5.Vector.lerp(v0, v1, 0.5); + * + * // Prints "p5.Vector Object : [2, 2, 2]" to the console. + * print(v2.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Three arrows extend from the center of a gray square. A red arrow points to the right, a blue arrow points down, and a purple arrow points to the bottom right.'); + * } + * function draw() { + * background(200); + * + * // Create p5.Vector objects. + * let v0 = createVector(50, 50); + * let v1 = createVector(30, 0); + * let v2 = createVector(0, 30); + * + * // Interpolate. + * let v3 = p5.Vector.lerp(v1, v2, 0.5); + * + * // Draw the red arrow. + * drawArrow(v0, v1, 'red'); + * + * // Draw the blue arrow. + * drawArrow(v0, v2, 'blue'); + * + * // Draw the purple arrow. + * drawArrow(v0, v3, 'purple'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + /** + * @method lerp + * @param {p5.Vector} v p5.Vector to lerp toward. + * @param {Number} amt + * @chainable + */ + + }, + { + key: 'lerp', + value: function lerp(x, y, z, amt) { + if (x instanceof _main.default.Vector) { + return this.lerp(x.x, x.y, x.z, y); + } + this.x += (x - this.x) * amt || 0; + this.y += (y - this.y) * amt || 0; + this.z += (z - this.z) * amt || 0; + return this; + } /** + * Calculates a new heading and magnitude that are between two vectors. + * + * The `amt` parameter is the amount to interpolate between the old vector and + * the new vector. 0.0 keeps the heading and magnitude equal to the old + * vector's, 0.5 sets them halfway between, and 1.0 sets the heading and + * magnitude equal to the new vector's. + * + * `slerp()` differs from lerp() because + * it interpolates magnitude. Calling `v0.slerp(v1, 0.5)` sets `v0`'s + * magnitude to a value halfway between its original magnitude and `v1`'s. + * Calling `v0.lerp(v1, 0.5)` makes no such guarantee. + * + * The static version of `slerp()`, as in `p5.Vector.slerp(v0, v1, 0.5)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method slerp + * @param {p5.Vector} v p5.Vector to slerp toward. + * @param {Number} amt amount of interpolation between 0.0 (old vector) + * and 1.0 (new vector). 0.5 is halfway between. + * @return {p5.Vector} + * + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v0 = createVector(3, 0); + * + * // Prints "3" to the console. + * print(v0.mag()); + * + * // Prints "0" to the console. + * print(v0.heading()); + * + * // Create a p5.Vector object. + * let v1 = createVector(0, 1); + * + * // Prints "1" to the console. + * print(v1.mag()); + * + * // Prints "1.570..." to the console. + * print(v1.heading()); + * + * // Interpolate halfway between v0 and v1. + * v0.slerp(v1, 0.5); + * + * // Prints "2" to the console. + * print(v0.mag()); + * + * // Prints "0.785..." to the console. + * print(v0.heading()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v0 = createVector(3, 0); + * + * // Prints "3" to the console. + * print(v0.mag()); + * + * // Prints "0" to the console. + * print(v0.heading()); + * + * // Create a p5.Vector object. + * let v1 = createVector(0, 1); + * + * // Prints "1" to the console. + * print(v1.mag()); + * + * // Prints "1.570..." to the console. + * print(v1.heading()); + * + * // Create a p5.Vector that's halfway between v0 and v1. + * let v3 = p5.Vector.slerp(v0, v1, 0.5); + * + * // Prints "2" to the console. + * print(v3.mag()); + * + * // Prints "0.785..." to the console. + * print(v3.heading()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Three arrows extend from the center of a gray square. A red arrow points to the right, a blue arrow points to the left, and a purple arrow points down.'); + * } + * + * function draw() { + * background(200); + * + * // Create p5.Vector objects. + * let v0 = createVector(50, 50); + * let v1 = createVector(20, 0); + * let v2 = createVector(-40, 0); + * + * // Create a p5.Vector that's halfway between v1 and v2. + * let v3 = p5.Vector.slerp(v1, v2, 0.5); + * + * // Draw the red arrow. + * drawArrow(v0, v1, 'red'); + * + * // Draw the blue arrow. + * drawArrow(v0, v2, 'blue'); + * + * // Draw the purple arrow. + * drawArrow(v0, v3, 'purple'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'slerp', + value: function slerp(v, amt) { + // edge cases. + if (amt === 0) { + return this; + } + if (amt === 1) { + return this.set(v); + } // calculate magnitudes + + var selfMag = this.mag(); + var vMag = v.mag(); + var magmag = selfMag * vMag; + // if either is a zero vector, linearly interpolate by these vectors + if (magmag === 0) { + this.mult(1 - amt).add(v.x * amt, v.y * amt, v.z * amt); + return this; + } // the cross product of 'this' and 'v' is the axis of rotation + + var axis = this.cross(v); + var axisMag = axis.mag(); + // Calculates the angle between 'this' and 'v' + var theta = Math.atan2(axisMag, this.dot(v)); + // However, if the norm of axis is 0, normalization cannot be performed, + // so we will divide the cases + if (axisMag > 0) { + axis.x /= axisMag; + axis.y /= axisMag; + axis.z /= axisMag; + } else if (theta < Math.PI * 0.5) { + // if the norm is 0 and the angle is less than PI/2, + // the angle is very close to 0, so do linear interpolation. + this.mult(1 - amt).add(v.x * amt, v.y * amt, v.z * amt); + return this; + } else { + // If the norm is 0 and the angle is more than PI/2, the angle is + // very close to PI. + // In this case v can be regarded as '-this', so take any vector + // that is orthogonal to 'this' and use that as the axis. + if (this.z === 0 && v.z === 0) { + // if both this and v are 2D vectors, use (0,0,1) + // this makes the result also a 2D vector. + axis.set(0, 0, 1); + } else if (this.x !== 0) { + // if the x components is not 0, use (y, -x, 0) + axis.set(this.y, - this.x, 0).normalize(); + } else { + // if the x components is 0, use (1,0,0) + axis.set(1, 0, 0); + } + } // Since 'axis' is a unit vector, ey is a vector of the same length as 'this'. + + var ey = axis.cross(this); + // interpolate the length with 'this' and 'v'. + var lerpedMagFactor = 1 - amt + amt * vMag / selfMag; + // imagine a situation where 'axis', 'this', and 'ey' are pointing + // along the z, x, and y axes, respectively. + // rotates 'this' around 'axis' by amt * theta towards 'ey'. + var cosMultiplier = lerpedMagFactor * Math.cos(amt * theta); + var sinMultiplier = lerpedMagFactor * Math.sin(amt * theta); + // then, calculate 'result'. + this.x = this.x * cosMultiplier + ey.x * sinMultiplier; + this.y = this.y * cosMultiplier + ey.y * sinMultiplier; + this.z = this.z * cosMultiplier + ey.z * sinMultiplier; + return this; + } /** + * Reflects a vector about a line in 2D or a plane in 3D. + * + * The orientation of the line or plane is described by a normal vector that + * points away from the shape. + * + * The static version of `reflect()`, as in `p5.Vector.reflect(v, n)`, + * returns a new p5.Vector object and doesn't change + * the original. + * + * @method reflect + * @param {p5.Vector} surfaceNormal p5.Vector + * to reflect about. + * @chainable + * @example + *
        + * + * function setup() { + * // Create a normal vector. + * let n = createVector(0, 1); + * // Create a vector to reflect. + * let v = createVector(4, 6); + * + * // Reflect v about n. + * v.reflect(n); + * + * // Prints "p5.Vector Object : [4, -6, 0]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a normal vector. + * let n = createVector(0, 1); + * + * // Create a vector to reflect. + * let v0 = createVector(4, 6); + * + * // Create a reflected vector. + * let v1 = p5.Vector.reflect(v0, n); + * + * // Prints "p5.Vector Object : [4, -6, 0]" to the console. + * print(v1.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('Three arrows extend from the center of a gray square with a vertical line down its middle. A black arrow points to the right, a blue arrow points to the bottom left, and a red arrow points to the bottom right.'); + * } + * function draw() { + * background(200); + * + * // Draw a vertical line. + * line(50, 0, 50, 100); + * + * // Create a normal vector. + * let n = createVector(1, 0); + * + * // Center. + * let v0 = createVector(50, 50); + * + * // Create a vector to reflect. + * let v1 = createVector(30, 40); + * + * // Create a reflected vector. + * let v2 = p5.Vector.reflect(v1, n); + * + * // Scale the normal vector for drawing. + * n.setMag(30); + * + * // Draw the black arrow. + * drawArrow(v0, n, 'black'); + * + * // Draw the red arrow. + * drawArrow(v0, v1, 'red'); + * + * // Draw the blue arrow. + * drawArrow(v0, v2, 'blue'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'reflect', + value: function reflect(surfaceNormal) { + surfaceNormal.normalize(); + return this.sub(surfaceNormal.mult(2 * this.dot(surfaceNormal))); + } /** + * Returns the vector's components as an array of numbers. + * + * @method array + * @return {Number[]} array with the vector's components. + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = createVector(20, 30); + * + * // Prints "[20, 30, 0]" to the console. + * print(v.array()); + * } + * + *
        + */ + + }, + { + key: 'array', + value: function array() { + return [this.x || 0, + this.y || 0, + this.z || 0]; + } /** + * Checks whether all the vector's components are equal to another vector's. + * + * `equals()` returns `true` if the vector's components are all the same as another + * vector's and `false` if not. + * + * The version of `equals()` with one parameter interprets it as another + * p5.Vector object. + * + * The version of `equals()` with multiple parameters interprets them as the + * components of another vector. Any missing parameters are assigned the value + * 0. + * + * The static version of `equals()`, as in `p5.Vector.equals(v0, v1)`, + * interprets both parameters as p5.Vector objects. + * + * @method equals + * @param {Number} [x] x component of the vector. + * @param {Number} [y] y component of the vector. + * @param {Number} [z] z component of the vector. + * @return {Boolean} whether the vectors are equal. + * @example + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v0 = createVector(10, 20, 30); + * let v1 = createVector(10, 20, 30); + * let v2 = createVector(0, 0, 0); + * + * // Prints "true" to the console. + * print(v0.equals(v1)); + * + * // Prints "false" to the console. + * print(v0.equals(v2)); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v0 = createVector(5, 10, 20); + * let v1 = createVector(5, 10, 20); + * let v2 = createVector(13, 10, 19); + * + * // Prints "true" to the console. + * print(v0.equals(v1.x, v1.y, v1.z)); + * + * // Prints "false" to the console. + * print(v0.equals(v2.x, v2.y, v2.z)); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create p5.Vector objects. + * let v0 = createVector(10, 20, 30); + * let v1 = createVector(10, 20, 30); + * let v2 = createVector(0, 0, 0); + * + * // Prints "true" to the console. + * print(p5.Vector.equals(v0, v1)); + * + * // Prints "false" to the console. + * print(p5.Vector.equals(v0, v2)); + * } + * + *
        + */ + /** + * @method equals + * @param {p5.Vector|Array} value vector to compare. + * @return {Boolean} + */ + + }, + { + key: 'equals', + value: function equals(x, y, z) { + var a, + b, + c; + if (x instanceof _main.default.Vector) { + a = x.x || 0; + b = x.y || 0; + c = x.z || 0; + } else if (Array.isArray(x)) { + a = x[0] || 0; + b = x[1] || 0; + c = x[2] || 0; + } else { + a = x || 0; + b = y || 0; + c = z || 0; + } + return this.x === a && this.y === b && this.z === c; + } // Static Methods + /** + * Creates a new 2D vector from an angle. + * + * @method fromAngle + * @static + * @param {Number} angle desired angle, in radians. Unaffected by angleMode(). + * @param {Number} [length] length of the new vector (defaults to 1). + * @return {p5.Vector} new p5.Vector object. + * + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = p5.Vector.fromAngle(0); + * + * // Prints "p5.Vector Object : [1, 0, 0]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = p5.Vector.fromAngle(0, 30); + * + * // Prints "p5.Vector Object : [30, 0, 0]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A black arrow extends from the center of a gray square. It points to the right.'); + * } + * function draw() { + * background(200); + * + * // Create a p5.Vector to the center. + * let v0 = createVector(50, 50); + * + * // Create a p5.Vector with an angle 0 and magnitude 30. + * let v1 = p5.Vector.fromAngle(0, 30); + * + * // Draw the black arrow. + * drawArrow(v0, v1, 'black'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + } + ], [ + { + key: 'fromAngle', + value: function fromAngle(angle) { + var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + return new _main.default.Vector(length * Math.cos(angle), length * Math.sin(angle), 0); + } /** + * Creates a new 3D vector from a pair of ISO spherical angles. + * + * @method fromAngles + * @static + * @param {Number} theta polar angle in radians (zero is up). + * @param {Number} phi azimuthal angle in radians + * (zero is out of the screen). + * @param {Number} [length] length of the new vector (defaults to 1). + * @return {p5.Vector} new p5.Vector object. + * + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = p5.Vector.fromAngles(0, 0); + * + * // Prints "p5.Vector Object : [0, -1, 0]" to the console. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A light shines on a pink sphere as it orbits.'); + * } + * + * function draw() { + * background(0); + * + * // Calculate the ISO angles. + * let theta = frameCount * 0.05; + * let phi = 0; + * + * // Create a p5.Vector object. + * let v = p5.Vector.fromAngles(theta, phi, 100); + * + * // Create a point light using the p5.Vector. + * let c = color('deeppink'); + * pointLight(c, v); + * + * // Style the sphere. + * fill(255); + * noStroke(); + * + * // Draw the sphere. + * sphere(35); + * } + * + *
        + */ + + }, + { + key: 'fromAngles', + value: function fromAngles(theta, phi) { + var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var cosPhi = Math.cos(phi); + var sinPhi = Math.sin(phi); + var cosTheta = Math.cos(theta); + var sinTheta = Math.sin(theta); + return new _main.default.Vector(length * sinTheta * sinPhi, - length * cosTheta, length * sinTheta * cosPhi); + } /** + * Creates a new 2D unit vector with a random heading. + * + * @method random2D + * @static + * @return {p5.Vector} new p5.Vector object. + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = p5.Vector.random2D(); + * + * // Prints "p5.Vector Object : [x, y, 0]" to the console + * // where x and y are small random numbers. + * print(v.toString()); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(1); + * + * describe('A black arrow in extends from the center of a gray square. It changes direction once per second.'); + * } + * + * function draw() { + * background(200); + * + * // Create a p5.Vector to the center. + * let v0 = createVector(50, 50); + * + * // Create a random p5.Vector. + * let v1 = p5.Vector.random2D(); + * + * // Scale v1 for drawing. + * v1.mult(30); + * + * // Draw the black arrow. + * drawArrow(v0, v1, 'black'); + * } + * + * // Draws an arrow between two vectors. + * function drawArrow(base, vec, myColor) { + * push(); + * stroke(myColor); + * strokeWeight(3); + * fill(myColor); + * translate(base.x, base.y); + * line(0, 0, vec.x, vec.y); + * rotate(vec.heading()); + * let arrowSize = 7; + * translate(vec.mag() - arrowSize, 0); + * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); + * pop(); + * } + * + *
        + */ + + }, + { + key: 'random2D', + value: function random2D() { + return this.fromAngle(Math.random() * constants.TWO_PI); + } /** + * Creates a new 3D unit vector with a random heading. + * + * @method random3D + * @static + * @return {p5.Vector} new p5.Vector object. + * @example + *
        + * + * function setup() { + * // Create a p5.Vector object. + * let v = p5.Vector.random3D(); + * + * // Prints "p5.Vector Object : [x, y, z]" to the console + * // where x, y, and z are small random numbers. + * print(v.toString()); + * } + * + *
        + */ + + }, + { + key: 'random3D', + value: function random3D() { + var angle = Math.random() * constants.TWO_PI; + var vz = Math.random() * 2 - 1; + var vzBase = Math.sqrt(1 - vz * vz); + var vx = vzBase * Math.cos(angle); + var vy = vzBase * Math.sin(angle); + return new _main.default.Vector(vx, vy, vz); + } // Returns a copy of a vector. + /** + * @method copy + * @static + * @param {p5.Vector} v the p5.Vector to create a copy of + * @return {p5.Vector} the copy of the p5.Vector object + */ + + }, + { + key: 'copy', + value: function copy(v) { + return v.copy(v); + } // Adds two vectors together and returns a new one. + /** + * @method add + * @static + * @param {p5.Vector} v1 A p5.Vector to add + * @param {p5.Vector} v2 A p5.Vector to add + * @param {p5.Vector} [target] vector to receive the result. + * @return {p5.Vector} resulting p5.Vector. + */ + + }, + { + key: 'add', + value: function add() { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + var v1 = args[0], + v2 = args[1], + target = args[2]; + if (!target) { + target = v1.copy(); + if (args.length === 3) { + _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.add'); + } + } else { + target.set(v1); + } + target.add(v2); + return target; + } // Returns a vector remainder when it is divided by another vector + /** + * @method rem + * @static + * @param {p5.Vector} v1 The dividend p5.Vector + * @param {p5.Vector} v2 The divisor p5.Vector + */ + /** + * @method rem + * @static + * @param {p5.Vector} v1 + * @param {p5.Vector} v2 + * @return {p5.Vector} The resulting p5.Vector + */ + + }, + { + key: 'rem', + value: function rem(v1, v2) { + if (v1 instanceof _main.default.Vector && v2 instanceof _main.default.Vector) { + var target = v1.copy(); + target.rem(v2); + return target; + } + } /* + * Subtracts one p5.Vector from another and returns a new one. The second + * vector (`v2`) is subtracted from the first (`v1`), resulting in `v1-v2`. + */ + /** + * @method sub + * @static + * @param {p5.Vector} v1 A p5.Vector to subtract from + * @param {p5.Vector} v2 A p5.Vector to subtract + * @param {p5.Vector} [target] vector to receive the result. + * @return {p5.Vector} The resulting p5.Vector + */ + + }, + { + key: 'sub', + value: function sub() { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + var v1 = args[0], + v2 = args[1], + target = args[2]; + if (!target) { + target = v1.copy(); + if (args.length === 3) { + _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.sub'); + } + } else { + target.set(v1); + } + target.sub(v2); + return target; + } /** + * Multiplies a vector by a scalar and returns a new vector. + */ + /** + * @method mult + * @static + * @param {Number} x + * @param {Number} y + * @param {Number} [z] + * @return {p5.Vector} resulting new p5.Vector. + */ + /** + * @method mult + * @static + * @param {p5.Vector} v + * @param {Number} n + * @param {p5.Vector} [target] vector to receive the result. + * @return {p5.Vector} The resulting new p5.Vector + */ + /** + * @method mult + * @static + * @param {p5.Vector} v0 + * @param {p5.Vector} v1 + * @param {p5.Vector} [target] + * @return {p5.Vector} The resulting new p5.Vector + */ + /** + * @method mult + * @static + * @param {p5.Vector} v0 + * @param {Number[]} arr + * @param {p5.Vector} [target] + * @return {p5.Vector} The resulting new p5.Vector + */ + + }, + { + key: 'mult', + value: function mult() { + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + var v = args[0], + n = args[1], + target = args[2]; + if (!target) { + target = v.copy(); + if (args.length === 3) { + _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.mult'); + } + } else { + target.set(v); + } + target.mult(n); + return target; + } /** + * Rotates the vector (only 2D vectors) by the given angle; magnitude remains the same. Returns a new vector. + */ + /** + * @method rotate + * @static + * @param {p5.Vector} v + * @param {Number} angle + * @param {p5.Vector} [target] The vector to receive the result + * @return {p5.Vector} The resulting new p5.Vector + */ + + }, + { + key: 'rotate', + value: function rotate() { + for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { + args[_key7] = arguments[_key7]; + } + var v = args[0], + a = args[1], + target = args[2]; + if (args.length === 2) { + target = v.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.rotate'); + } + target.set(v); + } + target.rotate(a); + return target; + } /** + * Divides a vector by a scalar and returns a new vector. + */ + /** + * @method div + * @static + * @param {Number} x + * @param {Number} y + * @param {Number} [z] + * @return {p5.Vector} The resulting new p5.Vector + */ + /** + * @method div + * @static + * @param {p5.Vector} v + * @param {Number} n + * @param {p5.Vector} [target] The vector to receive the result + * @return {p5.Vector} The resulting new p5.Vector + */ + /** + * @method div + * @static + * @param {p5.Vector} v0 + * @param {p5.Vector} v1 + * @param {p5.Vector} [target] + * @return {p5.Vector} The resulting new p5.Vector + */ + /** + * @method div + * @static + * @param {p5.Vector} v0 + * @param {Number[]} arr + * @param {p5.Vector} [target] + * @return {p5.Vector} The resulting new p5.Vector + */ + + }, + { + key: 'div', + value: function div() { + for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { + args[_key8] = arguments[_key8]; + } + var v = args[0], + n = args[1], + target = args[2]; + if (!target) { + target = v.copy(); + if (args.length === 3) { + _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.div'); + } + } else { + target.set(v); + } + target.div(n); + return target; + } /** + * Calculates the dot product of two vectors. + */ + /** + * @method dot + * @static + * @param {p5.Vector} v1 first p5.Vector. + * @param {p5.Vector} v2 second p5.Vector. + * @return {Number} dot product. + */ + + }, + { + key: 'dot', + value: function dot(v1, v2) { + return v1.dot(v2); + } /** + * Calculates the cross product of two vectors. + */ + /** + * @method cross + * @static + * @param {p5.Vector} v1 first p5.Vector. + * @param {p5.Vector} v2 second p5.Vector. + * @return {Number} cross product. + */ + + }, + { + key: 'cross', + value: function cross(v1, v2) { + return v1.cross(v2); + } /** + * Calculates the Euclidean distance between two points (considering a + * point as a vector object). + */ + /** + * @method dist + * @static + * @param {p5.Vector} v1 The first p5.Vector + * @param {p5.Vector} v2 The second p5.Vector + * @return {Number} The distance + */ + + }, + { + key: 'dist', + value: function dist(v1, v2) { + return v1.dist(v2); + } /** + * Linear interpolate a vector to another vector and return the result as a + * new vector. + */ + /** + * @method lerp + * @static + * @param {p5.Vector} v1 + * @param {p5.Vector} v2 + * @param {Number} amt + * @param {p5.Vector} [target] The vector to receive the result + * @return {p5.Vector} The lerped value + */ + + }, + { + key: 'lerp', + value: function lerp() { + for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { + args[_key9] = arguments[_key9]; + } + var v1 = args[0], + v2 = args[1], + amt = args[2], + target = args[3]; + if (!target) { + target = v1.copy(); + if (args.length === 4) { + _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.lerp'); + } + } else { + target.set(v1); + } + target.lerp(v2, amt); + return target; + } /** + * Performs spherical linear interpolation with the other vector + * and returns the resulting vector. + * This works in both 3D and 2D. As for 2D, the result of slerping + * between 2D vectors is always a 2D vector. + */ + /** + * @method slerp + * @static + * @param {p5.Vector} v1 old vector. + * @param {p5.Vector} v2 new vector. + * @param {Number} amt + * @param {p5.Vector} [target] vector to receive the result. + * @return {p5.Vector} slerped vector between v1 and v2 + */ + + }, + { + key: 'slerp', + value: function slerp() { + for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { + args[_key10] = arguments[_key10]; + } + var v1 = args[0], + v2 = args[1], + amt = args[2], + target = args[3]; + if (!target) { + target = v1.copy(); + if (args.length === 4) { + _main.default._friendlyError('The target parameter is undefined, it should be of type p5.Vector', 'p5.Vector.slerp'); + } + } else { + target.set(v1); + } + target.slerp(v2, amt); + return target; + } /** + * Calculates the magnitude (length) of the vector and returns the result as + * a float (this is simply the equation `sqrt(x*x + y*y + z*z)`.) + */ + /** + * @method mag + * @static + * @param {p5.Vector} vecT The vector to return the magnitude of + * @return {Number} The magnitude of vecT + */ + + }, + { + key: 'mag', + value: function mag(vecT) { + return vecT.mag(); + } /** + * Calculates the squared magnitude of the vector and returns the result + * as a float (this is simply the equation (x\*x + y\*y + z\*z).) + * Faster if the real length is not required in the + * case of comparing vectors, etc. + */ + /** + * @method magSq + * @static + * @param {p5.Vector} vecT the vector to return the squared magnitude of + * @return {Number} the squared magnitude of vecT + */ + + }, + { + key: 'magSq', + value: function magSq(vecT) { + return vecT.magSq(); + } /** + * Normalize the vector to length 1 (make it a unit vector). + */ + /** + * @method normalize + * @static + * @param {p5.Vector} v The vector to normalize + * @param {p5.Vector} [target] The vector to receive the result + * @return {p5.Vector} The vector v, normalized to a length of 1 + */ + + }, + { + key: 'normalize', + value: function normalize() { + for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) { + args[_key11] = arguments[_key11]; + } + var v = args[0], + target = args[1]; + if (args.length < 2) { + target = v.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.normalize'); + } + target.set(v); + } + return target.normalize(); + } /** + * Limit the magnitude of the vector to the value used for the max + * parameter. + */ + /** + * @method limit + * @static + * @param {p5.Vector} v the vector to limit + * @param {Number} max + * @param {p5.Vector} [target] the vector to receive the result (Optional) + * @return {p5.Vector} v with a magnitude limited to max + */ + + }, + { + key: 'limit', + value: function limit() { + for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) { + args[_key12] = arguments[_key12]; + } + var v = args[0], + max = args[1], + target = args[2]; + if (args.length < 3) { + target = v.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.limit'); + } + target.set(v); + } + return target.limit(max); + } /** + * Set the magnitude of the vector to the value used for the len + * parameter. + */ + /** + * @method setMag + * @static + * @param {p5.Vector} v the vector to set the magnitude of + * @param {number} len + * @param {p5.Vector} [target] the vector to receive the result (Optional) + * @return {p5.Vector} v with a magnitude set to len + */ + + }, + { + key: 'setMag', + value: function setMag() { + for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) { + args[_key13] = arguments[_key13]; + } + var v = args[0], + len = args[1], + target = args[2]; + if (args.length < 3) { + target = v.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.setMag'); + } + target.set(v); + } + return target.setMag(len); + } /** + * Calculate the angle of rotation for this vector (only 2D vectors). + * p5.Vectors created using createVector() + * will take the current angleMode into + * consideration, and give the angle in radians or degrees accordingly. + */ + /** + * @method heading + * @static + * @param {p5.Vector} v the vector to find the angle of + * @return {Number} the angle of rotation + */ + + }, + { + key: 'heading', + value: function heading(v) { + return v.heading(); + } /** + * Calculates and returns the angle between two vectors. This function will take + * the angleMode on v1 into consideration, and + * give the angle in radians or degrees accordingly. + */ + /** + * @method angleBetween + * @static + * @param {p5.Vector} v1 the first vector. + * @param {p5.Vector} v2 the second vector. + * @return {Number} angle between the two vectors. + */ + + }, + { + key: 'angleBetween', + value: function angleBetween(v1, v2) { + return v1.angleBetween(v2); + } /** + * Reflect a vector about a normal to a line in 2D, or about a normal to a + * plane in 3D. + */ + /** + * @method reflect + * @static + * @param {p5.Vector} incidentVector vector to be reflected. + * @param {p5.Vector} surfaceNormal + * @param {p5.Vector} [target] vector to receive the result. + * @return {p5.Vector} the reflected vector + */ + + }, + { + key: 'reflect', + value: function reflect() { + for (var _len14 = arguments.length, args = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) { + args[_key14] = arguments[_key14]; + } + var incidentVector = args[0], + surfaceNormal = args[1], + target = args[2]; + if (args.length < 3) { + target = incidentVector.copy(); + } else { + if (!(target instanceof _main.default.Vector)) { + _main.default._friendlyError('The target parameter should be of type p5.Vector', 'p5.Vector.reflect'); + } + target.set(incidentVector); + } + return target.reflect(surfaceNormal); + } /** + * Return a representation of this vector as a float array. This is only + * for temporary use. If used in any other fashion, the contents should be + * copied by using the p5.Vector.copy() + * method to copy into your own vector. + */ + /** + * @method array + * @static + * @param {p5.Vector} v the vector to convert to an array + * @return {Number[]} an Array with the 3 values + */ + + }, + { + key: 'array', + value: function array(v) { + return v.array(); + } /** + * Equality check against a p5.Vector + */ + /** + * @method equals + * @static + * @param {p5.Vector|Array} v1 the first vector to compare + * @param {p5.Vector|Array} v2 the second vector to compare + * @return {Boolean} + */ + + }, + { + key: 'equals', + value: function equals(v1, v2) { + var v; + if (v1 instanceof _main.default.Vector) { + v = v1; + } else if (Array.isArray(v1)) { + v = new _main.default.Vector().set(v1); + } else { + _main.default._friendlyError('The v1 parameter should be of type Array or p5.Vector', 'p5.Vector.equals'); + } + return v.equals(v2); + } + } + ]); + return _class; + }(); + var _default = _main.default.Vector; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.every': 172, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.some': 187, + 'core-js/modules/es.math.sign': 195, + 'core-js/modules/es.number.constructor': 196, + 'core-js/modules/es.number.is-finite': 197, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.sub': 223, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 337: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Math + * @submodule Random + * @for p5 + * @requires core + */ + // variables used for random number generators + + var randomStateProp = '_lcg_random_state'; + // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes + // m is basically chosen to be large (as it is the max period) + // and for its relationships to a and c + var m = 4294967296; + // a - 1 should be divisible by m's prime factors + var a = 1664525; + // c and m should be co-prime + var c = 1013904223; + var y2 = 0; + // Linear Congruential Generator that stores its state at instance[stateProperty] + _main.default.prototype._lcg = function (stateProperty) { + // define the recurrence relationship + this[stateProperty] = (a * this[stateProperty] + c) % m; + // return a float in [0, 1) + // we've just used % m, so / m is always < 1 + return this[stateProperty] / m; + }; + _main.default.prototype._lcgSetSeed = function (stateProperty, val) { + // pick a random seed if val is undefined or null + // the >>> 0 casts the seed to an unsigned 32-bit integer + this[stateProperty] = (val == null ? Math.random() * m : val) >>> 0; + }; + /** + * Sets the seed value for the random() and + * randomGaussian() functions. + * + * By default, random() and + * randomGaussian() produce different + * results each time a sketch is run. Calling `randomSeed()` with a constant + * argument, such as `randomSeed(99)`, makes these functions produce the same + * results each time a sketch is run. + * + * @method randomSeed + * @param {Number} seed seed value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get random coordinates. + * let x = random(0, 100); + * let y = random(0, 100); + * + * // Draw the white circle. + * circle(x, y, 10); + * + * // Set a random seed for consistency. + * randomSeed(99); + * + * // Get random coordinates. + * x = random(0, 100); + * y = random(0, 100); + * + * // Draw the black circle. + * fill(0); + * circle(x, y, 10); + * + * describe('A white circle appears at a random position. A black circle appears at (27.4, 25.8).'); + * } + * + *
        + */ + _main.default.prototype.randomSeed = function (seed) { + this._lcgSetSeed(randomStateProp, seed); + this._gaussian_previous = false; + }; + /** + * Returns a random number or a random element from an array. + * + * `random()` follows uniform distribution, which means that all outcomes are + * equally likely. When `random()` is used to generate numbers, all + * numbers in the output range are equally likely to be returned. When + * `random()` is used to select elements from an array, all elements are + * equally likely to be chosen. + * + * By default, `random()` produces different results each time a sketch runs. + * The randomSeed() function can be used to + * generate the same sequence of numbers or choices each time a sketch runs. + * + * The version of `random()` with no parameters returns a random number from 0 + * up to but not including 1. + * + * The version of `random()` with one parameter works one of two ways. If the + * argument passed is a number, `random()` returns a random number from 0 up + * to but not including the number. For example, calling `random(5)` returns + * values between 0 and 5. If the argument passed is an array, `random()` + * returns a random element from that array. For example, calling + * `random(['🦁', '🐯', '🐻'])` returns either a lion, tiger, or bear emoji. + * + * The version of `random()` with two parameters returns a random number from + * a given range. The arguments passed set the range's lower and upper bounds. + * For example, calling `random(-5, 10.2)` returns values from -5 up to but + * not including 10.2. + * + * @method random + * @param {Number} [min] lower bound (inclusive). + * @param {Number} [max] upper bound (exclusive). + * @return {Number} random number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get random coordinates between 0 and 100. + * let x = random(0, 100); + * let y = random(0, 100); + * + * // Draw a point. + * strokeWeight(5); + * point(x, y); + * + * describe('A black dot appears in a random position on a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get random coordinates between 0 and 100. + * let x = random(100); + * let y = random(100); + * + * // Draw the point. + * strokeWeight(5); + * point(x, y); + * + * describe('A black dot appears in a random position on a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of emoji strings. + * let animals = ['🦁', '🐯', '🐻']; + * + * // Choose a random element from the array. + * let choice = random(animals); + * + * // Style the text. + * textAlign(CENTER); + * textSize(20); + * + * // Display the emoji. + * text(choice, 50, 50); + * + * describe('An animal face is displayed at random. Either a lion, tiger, or bear.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(5); + * + * describe('A black dot moves around randomly on a gray square.'); + * } + * + * function draw() { + * background(200); + * + * // Get random coordinates between 0 and 100. + * let x = random(100); + * let y = random(100); + * + * // Draw the point. + * strokeWeight(5); + * point(x, y); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Slow the frame rate. + * frameRate(5); + * + * describe('A black dot moves around randomly in the middle of a gray square.'); + * } + * + * function draw() { + * background(200); + * + * // Get random coordinates between 45 and 55. + * let x = random(45, 55); + * let y = random(45, 55); + * + * // Draw the point. + * strokeWeight(5); + * point(x, y); + * } + * + *
        + * + *
        + * + * let x = 50; + * let y = 50; + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A black dot moves around randomly leaving a trail.'); + * } + * + * function draw() { + * // Update x and y randomly. + * x += random(-1, 1); + * y += random(-1, 1); + * + * // Draw the point. + * point(x, y); + * } + * + *
        + */ + /** + * @method random + * @param {Array} choices array to choose from. + * @return {*} random element from the array. + * @example + */ + _main.default.prototype.random = function (min, max) { + _main.default._validateParameters('random', arguments); + var rand; + if (this[randomStateProp] != null) { + rand = this._lcg(randomStateProp); + } else { + rand = Math.random(); + } + if (typeof min === 'undefined') { + return rand; + } else if (typeof max === 'undefined') { + if (Array.isArray(min)) { + return min[Math.floor(rand * min.length)]; + } else { + return rand * min; + } + } else { + if (min > max) { + var tmp = min; + min = max; + max = tmp; + } + return rand * (max - min) + min; + } + }; + /** + * Returns a random number fitting a Gaussian, or normal, distribution. + * + * Normal distributions look like bell curves when plotted. Values from a + * normal distribution cluster around a central value called the mean. The + * cluster's standard deviation describes its spread. + * + * By default, `randomGaussian()` produces different results each time a + * sketch runs. The randomSeed() function can be + * used to generate the same sequence of numbers each time a sketch runs. + * + * There's no minimum or maximum value that `randomGaussian()` might return. + * Values far from the mean are very unlikely and values near the mean are + * very likely. + * + * The version of `randomGaussian()` with no parameters returns values with a + * mean of 0 and standard deviation of 1. + * + * The version of `randomGaussian()` with one parameter interprets the + * argument passed as the mean. The standard deviation is 1. + * + * The version of `randomGaussian()` with two parameters interprets the first + * argument passed as the mean and the second as the standard deviation. + * + * @method randomGaussian + * @param {Number} [mean] mean. + * @param {Number} [sd] standard deviation. + * @return {Number} random number. + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('Three horizontal black lines are filled in randomly. The top line spans entire canvas. The middle line is very short. The bottom line spans two-thirds of the canvas.'); + * } + * + * function draw() { + * // Style the circles. + * noStroke(); + * fill(0, 10); + * + * // Uniform distribution between 0 and 100. + * let x = random(100); + * let y = 25; + * circle(x, y, 5); + * + * // Gaussian distribution with a mean of 50 and sd of 1. + * x = randomGaussian(50); + * y = 50; + * circle(x, y, 5); + * + * // Gaussian distribution with a mean of 50 and sd of 10. + * x = randomGaussian(50, 10); + * y = 75; + * circle(x, y, 5); + * } + * + *
        + */ + _main.default.prototype.randomGaussian = function (mean) { + var sd = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + var y1, + x1, + x2, + w; + if (this._gaussian_previous) { + y1 = y2; + this._gaussian_previous = false; + } else { + do { + x1 = this.random(2) - 1; + x2 = this.random(2) - 1; + w = x1 * x1 + x2 * x2; + } while (w >= 1); + w = Math.sqrt( - 2 * Math.log(w) / w); + y1 = x1 * w; + y2 = x2 * w; + this._gaussian_previous = true; + } + var m = mean || 0; + return y1 * sd + m; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303 + } + ], + 338: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Math + * @submodule Trigonometry + * @for p5 + * @requires core + * @requires constants + */ + /* + * all DEGREES/RADIANS conversion should be done in the p5 instance + * if possible, using the p5._toRadians(), p5._fromRadians() methods. + */ + + _main.default.prototype._angleMode = constants.RADIANS; + /** + * Calculates the arc cosine of a number. + * + * `acos()` is the inverse of cos(). It expects + * arguments in the range -1 to 1. By default, `acos()` returns values in the + * range 0 to π (about 3.14). If the + * angleMode() is `DEGREES`, then values are + * returned in the range 0 to 180. + * + * @method acos + * @param {Number} value value whose arc cosine is to be returned. + * @return {Number} arc cosine of the given value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Calculate cos() and acos() values. + * let a = PI; + * let c = cos(a); + * let ac = acos(c); + * + * // Display the values. + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(c, 3)}`, 35, 50); + * text(`${round(ac, 3)}`, 35, 75); + * + * describe('The numbers 3.142, -1, and 3.142 written on separate rows.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Calculate cos() and acos() values. + * let a = PI + QUARTER_PI; + * let c = cos(a); + * let ac = acos(c); + * + * // Display the values. + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(c, 3)}`, 35, 50); + * text(`${round(ac, 3)}`, 35, 75); + * + * describe('The numbers 3.927, -0.707, and 2.356 written on separate rows.'); + * } + * + *
        + */ + _main.default.prototype.acos = function (ratio) { + return this._fromRadians(Math.acos(ratio)); + }; + /** + * Calculates the arc sine of a number. + * + * `asin()` is the inverse of sin(). It expects input + * values in the range of -1 to 1. By default, `asin()` returns values in the + * range -π ÷ 2 (about -1.57) to π ÷ 2 (about 1.57). If + * the angleMode() is `DEGREES` then values are + * returned in the range -90 to 90. + * + * @method asin + * @param {Number} value value whose arc sine is to be returned. + * @return {Number} arc sine of the given value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Calculate sin() and asin() values. + * let a = PI / 3; + * let s = sin(a); + * let as = asin(s); + * + * // Display the values. + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(s, 3)}`, 35, 50); + * text(`${round(as, 3)}`, 35, 75); + * + * describe('The numbers 1.047, 0.866, and 1.047 written on separate rows.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Calculate sin() and asin() values. + * let a = PI + PI / 3; + * let s = sin(a); + * let as = asin(s); + * + * // Display the values. + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(s, 3)}`, 35, 50); + * text(`${round(as, 3)}`, 35, 75); + * + * describe('The numbers 4.189, -0.866, and -1.047 written on separate rows.'); + * } + * + *
        + */ + _main.default.prototype.asin = function (ratio) { + return this._fromRadians(Math.asin(ratio)); + }; + /** + * Calculates the arc tangent of a number. + * + * `atan()` is the inverse of tan(). It expects input + * values in the range of -Infinity to Infinity. By default, `atan()` returns + * values in the range -π ÷ 2 (about -1.57) to π ÷ 2 + * (about 1.57). If the angleMode() is `DEGREES` + * then values are returned in the range -90 to 90. + * + * @method atan + * @param {Number} value value whose arc tangent is to be returned. + * @return {Number} arc tangent of the given value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Calculate tan() and atan() values. + * let a = PI / 3; + * let t = tan(a); + * let at = atan(t); + * + * // Display the values. + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(t, 3)}`, 35, 50); + * text(`${round(at, 3)}`, 35, 75); + * + * describe('The numbers 1.047, 1.732, and 1.047 written on separate rows.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Calculate tan() and atan() values. + * let a = PI + PI / 3; + * let t = tan(a); + * let at = atan(t); + * + * // Display the values. + * text(`${round(a, 3)}`, 35, 25); + * text(`${round(t, 3)}`, 35, 50); + * text(`${round(at, 3)}`, 35, 75); + * + * describe('The numbers 4.189, 1.732, and 1.047 written on separate rows.'); + * } + * + *
        + */ + _main.default.prototype.atan = function (ratio) { + return this._fromRadians(Math.atan(ratio)); + }; + /** + * Calculates the angle formed by a point, the origin, and the positive + * x-axis. + * + * `atan2()` is most often used for orienting geometry to the mouse's + * position, as in `atan2(mouseY, mouseX)`. The first parameter is the point's + * y-coordinate and the second parameter is its x-coordinate. + * + * By default, `atan2()` returns values in the range + * -π (about -3.14) to π (3.14). If the + * angleMode() is `DEGREES`, then values are + * returned in the range -180 to 180. + * + * @method atan2 + * @param {Number} y y-coordinate of the point. + * @param {Number} x x-coordinate of the point. + * @return {Number} arc tangent of the given point. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A rectangle at the top-left of the canvas rotates with mouse movements.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the angle between the mouse + * // and the origin. + * let a = atan2(mouseY, mouseX); + * + * // Rotate. + * rotate(a); + * + * // Draw the shape. + * rect(0, 0, 60, 10); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A rectangle at the center of the canvas rotates with mouse movements.'); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin to the center. + * translate(50, 50); + * + * // Get the mouse's coordinates relative to the origin. + * let x = mouseX - 50; + * let y = mouseY - 50; + * + * // Calculate the angle between the mouse and the origin. + * let a = atan2(y, x); + * + * // Rotate. + * rotate(a); + * + * // Draw the shape. + * rect(-30, -5, 60, 10); + * } + * + *
        + */ + _main.default.prototype.atan2 = function (y, x) { + return this._fromRadians(Math.atan2(y, x)); + }; + /** + * Calculates the cosine of an angle. + * + * `cos()` is useful for many geometric tasks in creative coding. The values + * returned oscillate between -1 and 1 as the input angle increases. `cos()` + * takes into account the current angleMode(). + * + * @method cos + * @param {Number} angle the angle. + * @return {Number} cosine of the angle. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white ball on a string oscillates left and right.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the coordinates. + * let x = 30 * cos(frameCount * 0.05) + 50; + * let y = 50; + * + * // Draw the oscillator. + * line(50, y, x, y); + * circle(x, y, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A series of black dots form a wave pattern.'); + * } + * + * function draw() { + * // Calculate the coordinates. + * let x = frameCount; + * let y = 30 * cos(x * 0.1) + 50; + * + * // Draw the point. + * point(x, y); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A series of black dots form an infinity symbol.'); + * } + * + * function draw() { + * // Calculate the coordinates. + * let x = 30 * cos(frameCount * 0.1) + 50; + * let y = 10 * sin(frameCount * 0.2) + 50; + * + * // Draw the point. + * point(x, y); + * } + * + *
        + */ + _main.default.prototype.cos = function (angle) { + return Math.cos(this._toRadians(angle)); + }; + /** + * Calculates the sine of an angle. + * + * `sin()` is useful for many geometric tasks in creative coding. The values + * returned oscillate between -1 and 1 as the input angle increases. `sin()` + * takes into account the current angleMode(). + * + * @method sin + * @param {Number} angle the angle. + * @return {Number} sine of the angle. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white ball on a string oscillates up and down.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the coordinates. + * let x = 50; + * let y = 30 * sin(frameCount * 0.05) + 50; + * + * // Draw the oscillator. + * line(50, y, x, y); + * circle(x, y, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A series of black dots form a wave pattern.'); + * } + * + * function draw() { + * // Calculate the coordinates. + * let x = frameCount; + * let y = 30 * sin(x * 0.1) + 50; + * + * // Draw the point. + * point(x, y); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A series of black dots form an infinity symbol.'); + * } + * + * function draw() { + * // Calculate the coordinates. + * let x = 30 * cos(frameCount * 0.1) + 50; + * let y = 10 * sin(frameCount * 0.2) + 50; + * + * // Draw the point. + * point(x, y); + * } + * + *
        + */ + _main.default.prototype.sin = function (angle) { + return Math.sin(this._toRadians(angle)); + }; + /** + * Calculates the tangent of an angle. + * + * `tan()` is useful for many geometric tasks in creative coding. The values + * returned range from -Infinity to Infinity and repeat periodically as the + * input angle increases. `tan()` takes into account the current + * angleMode(). + * + * @method tan + * @param {Number} angle the angle. + * @return {Number} tangent of the angle. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * describe('A series of identical curves drawn with black dots. Each curve starts from the top of the canvas, continues down at a slight angle, flattens out at the middle of the canvas, then continues to the bottom.'); + * } + * + * function draw() { + * // Calculate the coordinates. + * let x = frameCount; + * let y = 5 * tan(x * 0.1) + 50; + * + * // Draw the point. + * point(x, y); + * } + * + *
        + */ + _main.default.prototype.tan = function (angle) { + return Math.tan(this._toRadians(angle)); + }; + /** + * Converts an angle measured in radians to its value in degrees. + * + * Degrees and radians are both units for measuring angles. There are 360˚ in + * one full rotation. A full rotation is 2 × π (about 6.28) radians. + * + * The same angle can be expressed in with either unit. For example, 90° is a + * quarter of a full rotation. The same angle is 2 × π ÷ 4 + * (about 1.57) radians. + * + * @method degrees + * @param {Number} radians radians value to convert to degrees. + * @return {Number} converted angle. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Calculate the angle conversion. + * let rad = QUARTER_PI; + * let deg = degrees(rad); + * + * // Display the conversion. + * text(`${round(rad, 2)} rad = ${deg}˚`, 10, 50); + * + * describe('The text "0.79 rad = 45˚".'); + * } + * + *
        + */ + _main.default.prototype.degrees = function (angle) { + return angle * constants.RAD_TO_DEG; + }; + /** + * Converts an angle measured in degrees to its value in radians. + * + * Degrees and radians are both units for measuring angles. There are 360˚ in + * one full rotation. A full rotation is 2 × π (about 6.28) radians. + * + * The same angle can be expressed in with either unit. For example, 90° is a + * quarter of a full rotation. The same angle is 2 × π ÷ 4 + * (about 1.57) radians. + * + * @method radians + * @param {Number} degrees degree value to convert to radians. + * @return {Number} converted angle. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Caclulate the angle conversion. + * let deg = 45; + * let rad = radians(deg); + * + * // Display the angle conversion. + * text(`${deg}˚ = ${round(rad, 3)} rad`, 10, 50); + * + * describe('The text "45˚ = 0.785 rad".'); + * } + * + *
        + */ + _main.default.prototype.radians = function (angle) { + return angle * constants.DEG_TO_RAD; + }; + /** + * Changes the unit system used to measure angles. + * + * Degrees and radians are both units for measuring angles. There are 360˚ in + * one full rotation. A full rotation is 2 × π (about 6.28) radians. + * + * Functions such as rotate() and + * sin() expect angles measured radians by default. + * Calling `angleMode(DEGREES)` switches to degrees. Calling + * `angleMode(RADIANS)` switches back to radians. + * + * Calling `angleMode()` with no arguments returns current angle mode, which + * is either `RADIANS` or `DEGREES`. + * + * @method angleMode + * @param {Constant} mode either RADIANS or DEGREES. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Rotate 1/8 turn. + * rotate(QUARTER_PI); + * + * // Draw a line. + * line(0, 0, 80, 0); + * + * describe('A diagonal line radiating from the top-left corner of a square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Use degrees. + * angleMode(DEGREES); + * + * // Rotate 1/8 turn. + * rotate(45); + * + * // Draw a line. + * line(0, 0, 80, 0); + * + * describe('A diagonal line radiating from the top-left corner of a square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Calculate the angle to rotate. + * let angle = TWO_PI / 7; + * + * // Move the origin to the center. + * translate(50, 50); + * + * // Style the flower. + * noStroke(); + * fill(255, 50); + * + * // Draw the flower. + * for (let i = 0; i < 7; i += 1) { + * ellipse(0, 0, 80, 20); + * rotate(angle); + * } + * + * describe('A translucent white flower on a dark background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(50); + * + * // Use degrees. + * angleMode(DEGREES); + * + * // Calculate the angle to rotate. + * let angle = 360 / 7; + * + * // Move the origin to the center. + * translate(50, 50); + * + * // Style the flower. + * noStroke(); + * fill(255, 50); + * + * // Draw the flower. + * for (let i = 0; i < 7; i += 1) { + * ellipse(0, 0, 80, 20); + * rotate(angle); + * } + * + * describe('A translucent white flower on a dark background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white ball on a string oscillates left and right.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the coordinates. + * let x = 30 * cos(frameCount * 0.05) + 50; + * let y = 50; + * + * // Draw the oscillator. + * line(50, y, x, y); + * circle(x, y, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * // Use degrees. + * angleMode(DEGREES); + * + * describe('A white ball on a string oscillates left and right.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the coordinates. + * let x = 30 * cos(frameCount * 2.86) + 50; + * let y = 50; + * + * // Draw the oscillator. + * line(50, y, x, y); + * circle(x, y, 20); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw the upper line. + * rotate(PI / 6); + * line(0, 0, 80, 0); + * + * // Use degrees. + * angleMode(DEGREES); + * + * // Draw the lower line. + * rotate(30); + * line(0, 0, 80, 0); + * + * describe('Two diagonal lines radiating from the top-left corner of a square. The lines are oriented 30 degrees from the edges of the square and 30 degrees apart from each other.'); + * } + * + *
        + */ + /** + * @method angleMode + * @return {Constant} mode either RADIANS or DEGREES + */ + _main.default.prototype.angleMode = function (mode) { + _main.default._validateParameters('angleMode', arguments); + if (typeof mode === 'undefined') { + return this._angleMode; + } else if (mode === constants.DEGREES || mode === constants.RADIANS) { + var prevMode = this._angleMode; + // No change + if (mode === prevMode) return; + // Otherwise adjust pRotation according to new mode + // This is necessary for acceleration events to work properly + if (mode === constants.RADIANS) { + // Change pRotation to radians + this._setProperty('pRotationX', this.pRotationX * constants.DEG_TO_RAD); + this._setProperty('pRotationY', this.pRotationY * constants.DEG_TO_RAD); + this._setProperty('pRotationZ', this.pRotationZ * constants.DEG_TO_RAD); + } else { + // Change pRotation to degrees + this._setProperty('pRotationX', this.pRotationX * constants.RAD_TO_DEG); + this._setProperty('pRotationY', this.pRotationY * constants.RAD_TO_DEG); + this._setProperty('pRotationZ', this.pRotationZ * constants.RAD_TO_DEG); + } + this._angleMode = mode; + } + }; + /** + * converts angles from the current angleMode to RADIANS + * + * @method _toRadians + * @private + * @param {Number} angle + * @returns {Number} + */ + _main.default.prototype._toRadians = function (angle) { + if (this._angleMode === constants.DEGREES) { + return angle * constants.DEG_TO_RAD; + } + return angle; + }; + /** + * converts angles from the current angleMode to DEGREES + * + * @method _toDegrees + * @private + * @param {Number} angle + * @returns {Number} + */ + _main.default.prototype._toDegrees = function (angle) { + if (this._angleMode === constants.RADIANS) { + return angle * constants.RAD_TO_DEG; + } + return angle; + }; + /** + * converts angles from RADIANS into the current angleMode + * + * @method _fromRadians + * @private + * @param {Number} angle + * @returns {Number} + */ + _main.default.prototype._fromRadians = function (angle) { + if (this._angleMode === constants.DEGREES) { + return angle * constants.RAD_TO_DEG; + } + return angle; + }; + /** + * converts angles from DEGREES into the current angleMode + * + * @method _fromDegrees + * @private + * @param {Number} angle + * @returns {Number} + */ + _main.default.prototype._fromDegrees = function (angle) { + if (this._angleMode === constants.RADIANS) { + return angle * constants.DEG_TO_RAD; + } + return angle; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 339: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Typography + * @submodule Attributes + * @for p5 + * @requires core + * @requires constants + */ + /** + * Sets the way text is aligned when text() is called. + * + * By default, calling `text('hi', 10, 20)` places the bottom-left corner of + * the text's bounding box at (10, 20). + * + * The first parameter, `horizAlign`, changes the way + * text() interprets x-coordinates. By default, the + * x-coordinate sets the left edge of the bounding box. `textAlign()` accepts + * the following values for `horizAlign`: `LEFT`, `CENTER`, or `RIGHT`. + * + * The second parameter, `vertAlign`, is optional. It changes the way + * text() interprets y-coordinates. By default, the + * y-coordinate sets the bottom edge of the bounding box. `textAlign()` + * accepts the following values for `vertAlign`: `TOP`, `BOTTOM`, `CENTER`, + * or `BASELINE`. + * + * @method textAlign + * @param {Constant} horizAlign horizontal alignment, either LEFT, + * CENTER, or RIGHT. + * @param {Constant} [vertAlign] vertical alignment, either TOP, + * BOTTOM, CENTER, or BASELINE. + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Draw a vertical line. + * strokeWeight(0.5); + * line(50, 0, 50, 100); + * + * // Top line. + * textSize(16); + * textAlign(RIGHT); + * text('ABCD', 50, 30); + * + * // Middle line. + * textAlign(CENTER); + * text('EFGH', 50, 50); + * + * // Bottom line. + * textAlign(LEFT); + * text('IJKL', 50, 70); + * + * describe('The letters ABCD displayed at top-left, EFGH at center, and IJKL at bottom-right. A vertical line divides the canvas in half.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * strokeWeight(0.5); + * + * // First line. + * line(0, 12, width, 12); + * textAlign(CENTER, TOP); + * text('TOP', 50, 12); + * + * // Second line. + * line(0, 37, width, 37); + * textAlign(CENTER, CENTER); + * text('CENTER', 50, 37); + * + * // Third line. + * line(0, 62, width, 62); + * textAlign(CENTER, BASELINE); + * text('BASELINE', 50, 62); + * + * // Fourth line. + * line(0, 97, width, 97); + * textAlign(CENTER, BOTTOM); + * text('BOTTOM', 50, 97); + * + * describe('The words "TOP", "CENTER", "BASELINE", and "BOTTOM" each drawn relative to a horizontal line. Their positions demonstrate different vertical alignments.'); + * } + * + *
        + */ + /** + * @method textAlign + * @return {Object} + */ + + _main.default.prototype.textAlign = function (horizAlign, vertAlign) { + var _this$_renderer; + _main.default._validateParameters('textAlign', arguments); + return (_this$_renderer = this._renderer).textAlign.apply(_this$_renderer, arguments); + }; + /** + * Sets the spacing between lines of text when + * text() is called. + * + * Note: Spacing is measured in pixels. + * + * Calling `textLeading()` without an argument returns the current spacing. + * + * @method textLeading + * @param {Number} leading spacing between lines of text in units of pixels. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // "\n" starts a new line of text. + * let lines = 'one\ntwo'; + * + * // Left. + * text(lines, 10, 25); + * + * // Right. + * textLeading(30); + * text(lines, 70, 25); + * + * describe('The words "one" and "two" written on separate lines twice. The words on the left have less vertical spacing than the words on the right.'); + * } + * + *
        + */ + /** + * @method textLeading + * @return {Number} + */ + _main.default.prototype.textLeading = function (theLeading) { + var _this$_renderer2; + _main.default._validateParameters('textLeading', arguments); + return (_this$_renderer2 = this._renderer).textLeading.apply(_this$_renderer2, arguments); + }; + /** + * Sets the font size when + * text() is called. + * + * Note: Font size is measured in pixels. + * + * Calling `textSize()` without an arugment returns the current size. + * + * @method textSize + * @param {Number} size size of the letters in units of pixels. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Top. + * textSize(12); + * text('Font Size 12', 10, 30); + * + * // Middle. + * textSize(14); + * text('Font Size 14', 10, 60); + * + * // Bottom. + * textSize(16); + * text('Font Size 16', 10, 90); + * + * describe('The text "Font Size 12" drawn small, "Font Size 14" drawn medium, and "Font Size 16" drawn large.'); + * } + * + *
        + */ + /** + * @method textSize + * @return {Number} + */ + _main.default.prototype.textSize = function (theSize) { + var _this$_renderer3; + _main.default._validateParameters('textSize', arguments); + return (_this$_renderer3 = this._renderer).textSize.apply(_this$_renderer3, arguments); + }; + /** + * Sets the style for system fonts when + * text() is called. + * + * The parameter, `style`, can be either `NORMAL`, `ITALIC`, `BOLD`, or + * `BOLDITALIC`. + * + * `textStyle()` may be overridden by CSS styling. This function doesn't + * affect fonts loaded with loadFont(). + * + * @method textStyle + * @param {Constant} style styling for text, either NORMAL, + * ITALIC, BOLD or BOLDITALIC. + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textSize(12); + * textAlign(CENTER); + * + * // First row. + * textStyle(NORMAL); + * text('Normal', 50, 15); + * + * // Second row. + * textStyle(ITALIC); + * text('Italic', 50, 40); + * + * // Third row. + * textStyle(BOLD); + * text('Bold', 50, 65); + * + * // Fourth row. + * textStyle(BOLDITALIC); + * text('Bold Italic', 50, 90); + * + * describe('The words "Normal" displayed normally, "Italic" in italic, "Bold" in bold, and "Bold Italic" in bold italics.'); + * } + * + *
        + */ + /** + * @method textStyle + * @return {String} + */ + _main.default.prototype.textStyle = function (theStyle) { + var _this$_renderer4; + _main.default._validateParameters('textStyle', arguments); + return (_this$_renderer4 = this._renderer).textStyle.apply(_this$_renderer4, arguments); + }; + /** + * Calculates the maximum width of a string of text drawn when + * text() is called. + * + * @method textWidth + * @param {String} str string of text to measure. + * @return {Number} width measured in units of pixels. + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textSize(28); + * strokeWeight(0.5); + * + * // Calculate the text width. + * let s = 'yoyo'; + * let w = textWidth(s); + * + * // Display the text. + * text(s, 22, 55); + * + * // Underline the text. + * line(22, 55, 22 + w, 55); + * + * describe('The word "yoyo" underlined.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textSize(28); + * strokeWeight(0.5); + * + * // Calculate the text width. + * // "\n" starts a new line. + * let s = 'yo\nyo'; + * let w = textWidth(s); + * + * // Display the text. + * text(s, 22, 55); + * + * // Underline the text. + * line(22, 55, 22 + w, 55); + * + * describe('The word "yo" written twice, one copy beneath the other. The words are divided by a horizontal line.'); + * } + * + *
        + */ + _main.default.prototype.textWidth = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + args[0] += ''; + _main.default._validateParameters('textWidth', args); + if (args[0].length === 0) { + return 0; + } // Only use the line with the longest width, and replace tabs with double-space + + var textLines = args[0].replace(/\t/g, ' ').split(/\r?\n|\r|\n/g); + var newArr = [ + ]; + // Return the textWidth for every line + for (var i = 0; i < textLines.length; i++) { + newArr.push(this._renderer.textWidth(textLines[i])); + } // Return the largest textWidth + + var largestWidth = Math.max.apply(Math, newArr); + return largestWidth; + }; + /** + * Calculates the ascent of the current font at its current size. + * + * The ascent represents the distance, in pixels, of the tallest character + * above the baseline. + * + * @method textAscent + * @return {Number} ascent measured in units of pixels. + * @example + *
        + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textFont(font); + * + * // Different for each font. + * let fontScale = 0.8; + * + * let baseY = 75; + * strokeWeight(0.5); + * + * // Draw small text. + * textSize(24); + * text('dp', 0, baseY); + * + * // Draw baseline and ascent. + * let a = textAscent() * fontScale; + * line(0, baseY, 23, baseY); + * line(23, baseY - a, 23, baseY); + * + * // Draw large text. + * textSize(48); + * text('dp', 45, baseY); + * + * // Draw baseline and ascent. + * a = textAscent() * fontScale; + * line(45, baseY, 91, baseY); + * line(91, baseY - a, 91, baseY); + * + * describe('The letters "dp" written twice in different sizes. Each version has a horizontal baseline. A vertical line extends upward from each baseline to the top of the "d".'); + * } + * + *
        + */ + _main.default.prototype.textAscent = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('textAscent', args); + return this._renderer.textAscent(); + }; + /** + * Calculates the descent of the current font at its current size. + * + * The descent represents the distance, in pixels, of the character with the + * longest descender below the baseline. + * + * @method textDescent + * @return {Number} descent measured in units of pixels. + * @example + *
        + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the font. + * textFont(font); + * + * // Different for each font. + * let fontScale = 0.9; + * + * let baseY = 75; + * strokeWeight(0.5); + * + * // Draw small text. + * textSize(24); + * text('dp', 0, baseY); + * + * // Draw baseline and descent. + * let d = textDescent() * fontScale; + * line(0, baseY, 23, baseY); + * line(23, baseY, 23, baseY + d); + * + * // Draw large text. + * textSize(48); + * text('dp', 45, baseY); + * + * // Draw baseline and descent. + * d = textDescent() * fontScale; + * line(45, baseY, 91, baseY); + * line(91, baseY, 91, baseY + d); + * + * describe('The letters "dp" written twice in different sizes. Each version has a horizontal baseline. A vertical line extends downward from each baseline to the bottom of the "p".'); + * } + * + *
        + */ + _main.default.prototype.textDescent = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('textDescent', args); + return this._renderer.textDescent(); + }; + /** + * Helper function to measure ascent and descent. + */ + _main.default.prototype._updateTextMetrics = function () { + return this._renderer._updateTextMetrics(); + }; + /** + * Sets the style for wrapping text when + * text() is called. + * + * The parameter, `style`, can be one of the following values: + * + * `WORD` starts new lines of text at spaces. If a string of text doesn't + * have spaces, it may overflow the text box and the canvas. This is the + * default style. + * + * `CHAR` starts new lines as needed to stay within the text box. + * + * `textWrap()` only works when the maximum width is set for a text box. For + * example, calling `text('Have a wonderful day', 0, 10, 100)` sets the + * maximum width to 100 pixels. + * + * Calling `textWrap()` without an argument returns the current style. + * + * @method textWrap + * @param {Constant} style text wrapping style, either WORD or CHAR. + * @return {String} style + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textSize(20); + * textWrap(WORD); + * + * // Display the text. + * text('Have a wonderful day', 0, 10, 100); + * + * describe('The text "Have a wonderful day" written across three lines.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textSize(20); + * textWrap(CHAR); + * + * // Display the text. + * text('Have a wonderful day', 0, 10, 100); + * + * describe('The text "Have a wonderful day" written across two lines.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textSize(20); + * textWrap(CHAR); + * + * // Display the text. + * text('祝你有美好的一天', 0, 10, 100); + * + * describe('The text "祝你有美好的一天" written across two lines.'); + * } + * + *
        + */ + _main.default.prototype.textWrap = function (wrapStyle) { + _main.default._validateParameters('textWrap', [ + wrapStyle + ]); + return this._renderer.textWrap(wrapStyle); + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.string.split': 221 + } + ], + 340: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.last-index-of'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.split'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + var opentype = _interopRequireWildcard(_dereq_('opentype.js')); + _dereq_('../core/friendly_errors/validate_params'); + _dereq_('../core/friendly_errors/file_errors'); + _dereq_('../core/friendly_errors/fes_core'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Typography + * @submodule Loading & Displaying + * @for p5 + * @requires core + */ + /** + * Loads a font and creates a p5.Font object. + * `loadFont()` can load fonts in either .otf or .ttf format. Loaded fonts can + * be used to style text on the canvas and in HTML elements. + * + * The first parameter, `path`, is the path to a font file. + * Paths to local files should be relative. For example, + * `'assets/inconsolata.otf'`. The Inconsolata font used in the following + * examples can be downloaded for free + * here. + * Paths to remote files should be URLs. For example, + * `'https://example.com/inconsolata.otf'`. URLs may be blocked due to browser + * security. + * + * The second parameter, `successCallback`, is optional. If a function is + * passed, it will be called once the font has loaded. The callback function + * may use the new p5.Font object if needed. + * + * The third parameter, `failureCallback`, is also optional. If a function is + * passed, it will be called if the font fails to load. The callback function + * may use the error + * Event + * object if needed. + * + * Fonts can take time to load. Calling `loadFont()` in + * preload() ensures fonts load before they're + * used in setup() or + * draw(). + * + * @method loadFont + * @param {String} path path of the font to be loaded. + * @param {Function} [successCallback] function called with the + * p5.Font object after it + * loads. + * @param {Function} [failureCallback] function called with the error + * Event + * object if the font fails to load. + * @return {p5.Font} p5.Font object. + * @example + * + *
        + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * fill('deeppink'); + * textFont(font); + * textSize(36); + * text('p5*js', 10, 50); + * + * describe('The text "p5*js" written in pink on a white background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * loadFont('assets/inconsolata.otf', font => { + * fill('deeppink'); + * textFont(font); + * textSize(36); + * text('p5*js', 10, 50); + * + * describe('The text "p5*js" written in pink on a white background.'); + * }); + * } + * + *
        + * + *
        + * + * function setup() { + * loadFont('assets/inconsolata.otf', success, failure); + * } + * + * function success(font) { + * fill('deeppink'); + * textFont(font); + * textSize(36); + * text('p5*js', 10, 50); + * + * describe('The text "p5*js" written in pink on a white background.'); + * } + * + * function failure(event) { + * console.error('Oops!', event); + * } + * + *
        + * + *
        + * + * function preload() { + * loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * let p = createP('p5*js'); + * p.style('color', 'deeppink'); + * p.style('font-family', 'Inconsolata'); + * p.style('font-size', '36px'); + * p.position(10, 50); + * + * describe('The text "p5*js" written in pink on a white background.'); + * } + * + *
        + */ + + _main.default.prototype.loadFont = function (path, onSuccess, onError) { + _main.default._validateParameters('loadFont', arguments); + var p5Font = new _main.default.Font(this); + var self = this; + opentype.load(path, function (err, font) { + if (err) { + _main.default._friendlyFileLoadError(4, path); + if (typeof onError !== 'undefined') { + return onError(err); + } + console.error(err, path); + return; + } + p5Font.font = font; + if (typeof onSuccess !== 'undefined') { + onSuccess(p5Font); + } + self._decrementPreload(); + // check that we have an acceptable font type + var validFontTypes = [ + 'ttf', + 'otf', + 'woff', + 'woff2' + ]; + var fileNoPath = path.split('\\').pop().split('/').pop(); + var lastDotIdx = fileNoPath.lastIndexOf('.'); + var fontFamily; + var newStyle; + var fileExt = lastDotIdx < 1 ? null : fileNoPath.slice(lastDotIdx + 1); + // if so, add it to the DOM (name-only) for use with DOM module + if (validFontTypes.includes(fileExt)) { + fontFamily = fileNoPath.slice(0, lastDotIdx !== - 1 ? lastDotIdx : 0); + newStyle = document.createElement('style'); + newStyle.appendChild(document.createTextNode('\n@font-face {\nfont-family: '.concat(fontFamily, ';\nsrc: url(').concat(path, ');\n}\n'))); + document.head.appendChild(newStyle); + } + }); + return p5Font; + }; + /** + * Draws text to the canvas. + * + * The first parameter, `str`, is the text to be drawn. The second and third + * parameters, `x` and `y`, set the coordinates of the text's bottom-left + * corner. See textAlign() for other ways to + * align text. + * + * The fourth and fifth parameters, `maxWidth` and `maxHeight`, are optional. + * They set the dimensions of the invisible rectangle containing the text. By + * default, they set its maximum width and height. See + * rectMode() for other ways to define the + * rectangular text box. Text will wrap to fit within the text box. Text + * outside of the box won't be drawn. + * + * Text can be styled a few ways. Call the fill() + * function to set the text's fill color. Call + * stroke() and + * strokeWeight() to set the text's outline. + * Call textSize() and + * textFont() to set the text's size and font, + * respectively. + * + * Note: `WEBGL` mode only supports fonts loaded with + * loadFont(). Calling + * stroke() has no effect in `WEBGL` mode. + * + * @method text + * @param {String|Object|Array|Number|Boolean} str text to be displayed. + * @param {Number} x x-coordinate of the text box. + * @param {Number} y y-coordinate of the text box. + * @param {Number} [maxWidth] maximum width of the text box. See + * rectMode() for + * other options. + * @param {Number} [maxHeight] maximum height of the text box. See + * rectMode() for + * other options. + * + * @chainable + * @example + *
        + * + * function setup() { + * background(200); + * text('hi', 50, 50); + * + * describe('The text "hi" written in black in the middle of a gray square.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background('skyblue'); + * textSize(100); + * text('🌈', 0, 100); + * + * describe('A rainbow in a blue sky.'); + * } + * + *
        + * + *
        + * + * function setup() { + * textSize(32); + * fill(255); + * stroke(0); + * strokeWeight(4); + * text('hi', 50, 50); + * + * describe('The text "hi" written in white with a black outline.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background('black'); + * textSize(22); + * fill('yellow'); + * text('rainbows', 6, 20); + * fill('cornflowerblue'); + * text('rainbows', 6, 45); + * fill('tomato'); + * text('rainbows', 6, 70); + * fill('limegreen'); + * text('rainbows', 6, 95); + * + * describe('The text "rainbows" written on several lines, each in a different color.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background(200); + * let s = 'The quick brown fox jumps over the lazy dog.'; + * text(s, 10, 10, 70, 80); + * + * describe('The sample text "The quick brown fox..." written in black across several lines.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background(200); + * rectMode(CENTER); + * let s = 'The quick brown fox jumps over the lazy dog.'; + * text(s, 50, 50, 70, 80); + * + * describe('The sample text "The quick brown fox..." written in black across several lines.'); + * } + * + *
        + * + *
        + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * textFont(font); + * textSize(32); + * textAlign(CENTER, CENTER); + * } + * + * function draw() { + * background(0); + * rotateY(frameCount / 30); + * text('p5*js', 0, 0); + * + * describe('The text "p5*js" written in white and spinning in 3D.'); + * } + * + *
        + */ + _main.default.prototype.text = function (str, x, y, maxWidth, maxHeight) { + var _this$_renderer; + _main.default._validateParameters('text', arguments); + return !(this._renderer._doFill || this._renderer._doStroke) ? this : (_this$_renderer = this._renderer).text.apply(_this$_renderer, arguments); + }; + /** + * Sets the font used by the text() function. + * + * The first parameter, `font`, sets the font. `textFont()` recognizes either + * a p5.Font object or a string with the name of a + * system font. For example, `'Courier New'`. + * + * The second parameter, `size`, is optional. It sets the font size in pixels. + * This has the same effect as calling textSize(). + * + * Note: `WEBGL` mode only supports fonts loaded with + * loadFont(). + * + * @method textFont + * @return {Object} current font or p5 Object. + * + * @example + *
        + * + * function setup() { + * background(200); + * textFont('Courier New'); + * textSize(24); + * text('hi', 35, 55); + * + * describe('The text "hi" written in a black, monospace font on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background('black'); + * fill('palegreen'); + * textFont('Courier New', 10); + * text('You turn to the left and see a door. Do you enter?', 5, 5, 90, 90); + * text('>', 5, 70); + * + * describe('A text prompt from a game is written in a green, monospace font on a black background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * background(200); + * textFont('Verdana'); + * let currentFont = textFont(); + * text(currentFont, 25, 50); + * + * describe('The text "Verdana" written in a black, sans-serif font on a gray background.'); + * } + * + *
        + * + *
        + * + * let fontRegular; + * let fontItalic; + * let fontBold; + * + * function preload() { + * fontRegular = loadFont('assets/Regular.otf'); + * fontItalic = loadFont('assets/Italic.ttf'); + * fontBold = loadFont('assets/Bold.ttf'); + * } + * + * function setup() { + * background(200); + * textFont(fontRegular); + * text('I am Normal', 10, 30); + * textFont(fontItalic); + * text('I am Italic', 10, 50); + * textFont(fontBold); + * text('I am Bold', 10, 70); + * + * describe('The statements "I am Normal", "I am Italic", and "I am Bold" written in black on separate lines. The statements have normal, italic, and bold fonts, respectively.'); + * } + * + *
        + */ + /** + * @method textFont + * @param {Object|String} font font as a p5.Font object or a string. + * @param {Number} [size] font size in pixels. + * @chainable + */ + _main.default.prototype.textFont = function (theFont, theSize) { + _main.default._validateParameters('textFont', arguments); + if (arguments.length) { + if (!theFont) { + throw new Error('null font passed to textFont'); + } + this._renderer._setProperty('_textFont', theFont); + if (theSize) { + this._renderer._setProperty('_textSize', theSize); + if (!this._renderer._leadingSet) { + // only use a default value if not previously set (#5181) + this._renderer._setProperty('_textLeading', theSize * constants._DEFAULT_LEADMULT); + } + } + return this._renderer._applyTextProperties(); + } + return this._renderer._textFont; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/friendly_errors/fes_core': 294, + '../core/friendly_errors/file_errors': 295, + '../core/friendly_errors/validate_params': 298, + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.last-index-of': 184, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261, + 'opentype.js': 276 + } + ], + 341: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + function _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; + } /** + * This module defines the p5.Font class and functions for + * drawing text to the display canvas. + * @module Typography + * @submodule Loading & Displaying + * @requires core + * @requires constants + */ + /** + * A class to describe fonts. + * + * @class p5.Font + * @constructor + * @param {p5} [pInst] pointer to p5 instance. + * @example + *
        + * + * let font; + * + * function preload() { + * // Creates a p5.Font object. + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * // Style the text. + * fill('deeppink'); + * textFont(font); + * textSize(36); + * + * // Display the text. + * text('p5*js', 10, 50); + * + * describe('The text "p5*js" written in pink on a gray background.'); + * } + * + *
        + */ + + _main.default.Font = /*#__PURE__*/ function () { + function _class(p) { + _classCallCheck(this, _class); + this.parent = p; + this.cache = { + }; + /** + * The font's underlying + * opentype.js + * font object. + * + * @property font + * @name font + */ + this.font = undefined; + } /** + * Returns the bounding box for a string of text written using the font. + * + * The bounding box is the smallest rectangle that can contain a string of + * text. `font.textBounds()` returns an object with the bounding box's + * location and size. For example, calling `font.textBounds('p5*js', 5, 20)` + * returns an object in the format + * `{ x: 5.7, y: 12.1 , w: 9.9, h: 28.6 }`. The `x` and `y` properties are + * always the coordinates of the bounding box's top-left corner. + * + * The first parameter, `str`, is a string of text. The second and third + * parameters, `x` and `y`, are the text's position. By default, they set the + * coordinates of the bounding box's bottom-left corner. See + * textAlign() for more ways to align text. + * + * The fourth parameter, `fontSize`, is optional. It sets the font size used to + * determine the bounding box. By default, `font.textBounds()` will use the + * current textSize(). + * + * @method textBounds + * @param {String} str string of text. + * @param {Number} x x-coordinate of the text. + * @param {Number} y y-coordinate of the text. + * @param {Number} [fontSize] font size. Defaults to the current + * textSize(). + * @return {Object} object describing the bounding box with + * properties x, y, w, and h. + * + * @example + *
        + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Display the bounding box. + * let bbox = font.textBounds('p5*js', 35, 53); + * rect(bbox.x, bbox.y, bbox.w, bbox.h); + * + * // Style the text. + * textFont(font); + * + * // Display the text. + * text('p5*js', 35, 53); + * + * describe('The text "p5*js" written in black inside a white rectangle.'); + * } + * + *
        + * + *
        + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textFont(font); + * textSize(15); + * textAlign(CENTER, CENTER); + * + * // Display the bounding box. + * let bbox = font.textBounds('p5*js', 50, 50); + * rect(bbox.x, bbox.y, bbox.w, bbox.h); + * + * // Display the text. + * text('p5*js', 50, 50); + * + * describe('The text "p5*js" written in black inside a white rectangle.'); + * } + * + *
        + * + *
        + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Display the bounding box. + * let bbox = font.textBounds('p5*js', 31, 53, 15); + * rect(bbox.x, bbox.y, bbox.w, bbox.h); + * + * // Style the text. + * textFont(font); + * textSize(15); + * + * // Display the text. + * text('p5*js', 31, 53); + * + * describe('The text "p5*js" written in black inside a white rectangle.'); + * } + * + *
        + */ + + _createClass(_class, [ + { + key: 'textBounds', + value: function textBounds(str) { + var x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var fontSize = arguments.length > 3 ? arguments[3] : undefined; + var opts = arguments.length > 4 ? arguments[4] : undefined; + // Check cache for existing bounds. Take into consideration the text alignment + // settings. Default alignment should match opentype's origin: left-aligned & + // alphabetic baseline. + var p = opts && opts.renderer && opts.renderer._pInst || this.parent; + var ctx = p._renderer.drawingContext; + var alignment = ctx.textAlign || constants.LEFT; + var baseline = ctx.textBaseline || constants.BASELINE; + var cacheResults = false; + var result; + var key; + fontSize = fontSize || p._renderer._textSize; + // NOTE: cache disabled for now pending further discussion of #3436 + if (cacheResults) { + key = cacheKey('textBounds', str, x, y, fontSize, alignment, baseline); + result = this.cache[key]; + } + if (!result) { + var minX = [ + ]; + var minY; + var maxX = [ + ]; + var maxY; + var pos; + var xCoords = [ + ]; + xCoords[0] = [ + ]; + var yCoords = [ + ]; + var scale = this._scale(fontSize); + var lineHeight = p._renderer.textLeading(); + var lineCount = 0; + this.font.forEachGlyph(str, x, y, fontSize, opts, function (glyph, gX, gY, gFontSize) { + var gm = glyph.getMetrics(); + if (glyph.index === 0) { + lineCount += 1; + xCoords[lineCount] = [ + ]; + } else { + xCoords[lineCount].push(gX + gm.xMin * scale); + xCoords[lineCount].push(gX + gm.xMax * scale); + yCoords.push(gY + lineCount * lineHeight + - gm.yMin * scale); + yCoords.push(gY + lineCount * lineHeight + - gm.yMax * scale); + } + }); + if (xCoords[lineCount].length > 0) { + minX[lineCount] = Math.min.apply(null, xCoords[lineCount]); + maxX[lineCount] = Math.max.apply(null, xCoords[lineCount]); + } + var finalMaxX = 0; + for (var i = 0; i <= lineCount; i++) { + minX[i] = Math.min.apply(null, xCoords[i]); + maxX[i] = Math.max.apply(null, xCoords[i]); + var lineLength = maxX[i] - minX[i]; + if (lineLength > finalMaxX) { + finalMaxX = lineLength; + } + } + var finalMinX = Math.min.apply(null, minX); + minY = Math.min.apply(null, yCoords); + maxY = Math.max.apply(null, yCoords); + result = { + x: finalMinX, + y: minY, + h: maxY - minY, + w: finalMaxX, + advance: finalMinX - x + }; + // Bounds are now calculated, so shift the x & y to match alignment settings + pos = this._handleAlignment(p._renderer, str, result.x, result.y, result.w + result.advance); + result.x = pos.x; + result.y = pos.y; + if (cacheResults) { + this.cache[key] = result; + } + } + return result; + } /** + * Returns an array of points outlining a string of text written using the + * font. + * + * Each point object in the array has three properties that describe the + * point's location and orientation, called its path angle. For example, + * `{ x: 10, y: 20, alpha: 450 }`. + * + * The first parameter, `str`, is a string of text. The second and third + * parameters, `x` and `y`, are the text's position. By default, they set the + * coordinates of the bounding box's bottom-left corner. See + * textAlign() for more ways to align text. + * + * The fourth parameter, `fontSize`, is optional. It sets the text's font + * size. By default, `font.textToPoints()` will use the current + * textSize(). + * + * The fifth parameter, `options`, is also optional. `font.textToPoints()` + * expects an object with the following properties: + * + * `sampleFactor` is the ratio of the text's path length to the number of + * samples. It defaults to 0.1. Higher values produce more points along the + * path and are more precise. + * + * `simplifyThreshold` removes collinear points if it's set to a number other + * than 0. The value represents the threshold angle to use when determining + * whether two edges are collinear. + * + * @method textToPoints + * @param {String} str string of text. + * @param {Number} x x-coordinate of the text. + * @param {Number} y y-coordinate of the text. + * @param {Number} [fontSize] font size. Defaults to the current + * textSize(). + * @param {Object} [options] object with sampleFactor and simplifyThreshold + * properties. + * @return {Array} array of point objects, each with x, y, and alpha (path angle) properties. + * + * @example + *
        + * + * let font; + * + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the point array. + * let points = font.textToPoints('p5*js', 6, 60, 35, { sampleFactor: 0.5 }); + * + * // Draw a dot at each point. + * for (let p of points) { + * point(p.x, p.y); + * } + * + * describe('A set of black dots outlining the text "p5*js" on a gray background.'); + * } + * + *
        + */ + + }, + { + key: 'textToPoints', + value: function textToPoints(txt, x, y, fontSize, options) { + var xOriginal = x; + var result = [ + ]; + var lines = txt.split(/\r?\n|\r|\n/g); + fontSize = fontSize || this.parent._renderer._textSize; + function isSpace(i, text, glyphsLine) { + return glyphsLine[i].name && glyphsLine[i].name === 'space' || text.length === glyphsLine.length && text[i] === ' ' //|| + //(glyphs[i].index && glyphs[i].index === 3) + ; + } + for (var i = 0; i < lines.length; i++) { + var xoff = 0; + x = xOriginal; + var line = lines[i]; + line = line.replace('\t', ' '); + var glyphs = this._getGlyphs(line); + for (var j = 0; j < glyphs.length; j++) { + if (!isSpace(j, line, glyphs)) { + // fix to #1817, #2069 + var gpath = glyphs[j].getPath(x, y, fontSize), + paths = splitPaths(gpath.commands); + for (var k = 0; k < paths.length; k++) { + var pts = pathToPoints(paths[k], options); + for (var l = 0; l < pts.length; l++) { + pts[l].x += xoff; + result.push(pts[l]); + } + } + } + xoff += glyphs[j].advanceWidth * this._scale(fontSize); + } + y = y + this.parent._renderer._textLeading; + } + return result; + } // ----------------------------- End API ------------------------------ + /** + * Returns the set of opentype glyphs for the supplied string. + * + * Note that there is not a strict one-to-one mapping between characters + * and glyphs, so the list of returned glyphs can be larger or smaller + * than the length of the given string. + * + * @private + * @param {String} str the string to be converted + * @return {Array} the opentype glyphs + */ + + }, + { + key: '_getGlyphs', + value: function _getGlyphs(str) { + return this.font.stringToGlyphs(str); + } /** + * Returns an opentype path for the supplied string and position. + * + * @private + * @param {String} line a line of text + * @param {Number} x x-position + * @param {Number} y y-position + * @param {Object} options opentype options (optional) + * @return {Object} the opentype path + */ + + }, + { + key: '_getPath', + value: function _getPath(line, x, y, options) { + var p = options && options.renderer && options.renderer._pInst || this.parent, + renderer = p._renderer, + pos = this._handleAlignment(renderer, line, x, y); + return this.font.getPath(line, pos.x, pos.y, renderer._textSize, options); + } /* + * Creates an SVG-formatted path-data string + * (See http://www.w3.org/TR/SVG/paths.html#PathData) + * from the given opentype path or string/position + * + * @param {Object} path an opentype path, OR the following: + * + * @param {String} line a line of text + * @param {Number} x x-position + * @param {Number} y y-position + * @param {Object} options opentype options (optional), set options.decimals + * to set the decimal precision of the path-data + * + * @return {Object} this p5.Font object + */ + + }, + { + key: '_getPathData', + value: function _getPathData(line, x, y, options) { + var decimals = 3; + // create path from string/position + if (typeof line === 'string' && arguments.length > 2) { + line = this._getPath(line, x, y, options); + } else if (_typeof(x) === 'object') { + // handle options specified in 2nd arg + options = x; + } // handle svg arguments + + if (options && typeof options.decimals === 'number') { + decimals = options.decimals; + } + return line.toPathData(decimals); + } /* + * Creates an SVG element, as a string, + * from the given opentype path or string/position + * + * @param {Object} path an opentype path, OR the following: + * + * @param {String} line a line of text + * @param {Number} x x-position + * @param {Number} y y-position + * @param {Object} options opentype options (optional), set options.decimals + * to set the decimal precision of the path-data in the element, + * options.fill to set the fill color for the element, + * options.stroke to set the stroke color for the element, + * options.strokeWidth to set the strokeWidth for the element. + * + * @return {Object} this p5.Font object + */ + + }, + { + key: '_getSVG', + value: function _getSVG(line, x, y, options) { + var decimals = 3; + // create path from string/position + if (typeof line === 'string' && arguments.length > 2) { + line = this._getPath(line, x, y, options); + } else if (_typeof(x) === 'object') { + // handle options specified in 2nd arg + options = x; + } // handle svg arguments + + if (options) { + if (typeof options.decimals === 'number') { + decimals = options.decimals; + } + if (typeof options.strokeWidth === 'number') { + line.strokeWidth = options.strokeWidth; + } + if (typeof options.fill !== 'undefined') { + line.fill = options.fill; + } + if (typeof options.stroke !== 'undefined') { + line.stroke = options.stroke; + } + } + return line.toSVG(decimals); + } /* + * Renders an opentype path or string/position + * to the current graphics context + * + * @param {Object} path an opentype path, OR the following: + * + * @param {String} line a line of text + * @param {Number} x x-position + * @param {Number} y y-position + * @param {Object} options opentype options (optional) + * + * @return {p5.Font} this p5.Font object + */ + + }, + { + key: '_renderPath', + value: function _renderPath(line, x, y, options) { + var pdata; + var pg = options && options.renderer || this.parent._renderer; + var ctx = pg.drawingContext; + if (_typeof(line) === 'object' && line.commands) { + pdata = line.commands; + } else { + //pos = handleAlignment(p, ctx, line, x, y); + pdata = this._getPath(line, x, y, options).commands; + } + ctx.beginPath(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = pdata[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var cmd = _step.value; + if (cmd.type === 'M') { + ctx.moveTo(cmd.x, cmd.y); + } else if (cmd.type === 'L') { + ctx.lineTo(cmd.x, cmd.y); + } else if (cmd.type === 'C') { + ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === 'Q') { + ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === 'Z') { + ctx.closePath(); + } + } // only draw stroke if manually set by user + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + if (pg._doStroke && pg._strokeSet && !pg._clipping) { + ctx.stroke(); + } + if (pg._doFill && !pg._clipping) { + // if fill hasn't been set by user, use default-text-fill + if (!pg._fillSet) { + pg._setFill(constants._DEFAULT_TEXT_FILL); + } + ctx.fill(); + } + return this; + } + }, + { + key: '_textWidth', + value: function _textWidth(str, fontSize) { + return this.font.getAdvanceWidth(str, fontSize); + } + }, + { + key: '_textAscent', + value: function _textAscent(fontSize) { + return this.font.ascender * this._scale(fontSize); + } + }, + { + key: '_textDescent', + value: function _textDescent(fontSize) { + return - this.font.descender * this._scale(fontSize); + } + }, + { + key: '_scale', + value: function _scale(fontSize) { + return 1 / this.font.unitsPerEm * (fontSize || this.parent._renderer._textSize); + } + }, + { + key: '_handleAlignment', + value: function _handleAlignment(renderer, line, x, y, textWidth) { + var fontSize = renderer._textSize; + if (typeof textWidth === 'undefined') { + textWidth = this._textWidth(line, fontSize); + } + switch (renderer._textAlign) { + case constants.CENTER: + x -= textWidth / 2; + break; + case constants.RIGHT: + x -= textWidth; + break; + } + switch (renderer._textBaseline) { + case constants.TOP: + y += this._textAscent(fontSize); + break; + case constants.CENTER: + y += this._textAscent(fontSize) / 2; + break; + case constants.BOTTOM: + y -= this._textDescent(fontSize); + break; + } + return { + x: x, + y: y + }; + } + } + ]); + return _class; + }(); + // path-utils + function pathToPoints(cmds, options) { + var opts = parseOpts(options, { + sampleFactor: 0.1, + simplifyThreshold: 0 + }); + var // total-length + len = pointAtLength(cmds, 0, 1), + t = len / (len * opts.sampleFactor), + pts = [ + ]; + for (var i = 0; i < len; i += t) { + pts.push(pointAtLength(cmds, i)); + } + if (opts.simplifyThreshold) { + simplify(pts, opts.simplifyThreshold); + } + return pts; + } + function simplify(pts) { + var angle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var num = 0; + for (var i = pts.length - 1; pts.length > 3 && i >= 0; --i) { + if (collinear(at(pts, i - 1), at(pts, i), at(pts, i + 1), angle)) { + // Remove the middle point + pts.splice(i % pts.length, 1); + num++; + } + } + return num; + } + function splitPaths(cmds) { + var paths = [ + ]; + var current; + for (var i = 0; i < cmds.length; i++) { + if (cmds[i].type === 'M') { + if (current) { + paths.push(current); + } + current = [ + ]; + } + current.push(cmdToArr(cmds[i])); + } + paths.push(current); + return paths; + } + function cmdToArr(cmd) { + var arr = [ + cmd.type + ]; + if (cmd.type === 'M' || cmd.type === 'L') { + // moveto or lineto + arr.push(cmd.x, cmd.y); + } else if (cmd.type === 'C') { + arr.push(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === 'Q') { + arr.push(cmd.x1, cmd.y1, cmd.x, cmd.y); + } // else if (cmd.type === 'Z') { /* no-op */ } + + return arr; + } + function parseOpts(options, defaults) { + if (_typeof(options) !== 'object') { + options = defaults; + } else { + for (var key in defaults) { + if (typeof options[key] === 'undefined') { + options[key] = defaults[key]; + } + } + } + return options; + } //////////////////////// Helpers //////////////////////////// + + function at(v, i) { + var s = v.length; + return v[i < 0 ? i % s + s : i % s]; + } + function collinear(a, b, c, thresholdAngle) { + if (!thresholdAngle) { + return areaTriangle(a, b, c) === 0; + } + if (typeof collinear.tmpPoint1 === 'undefined') { + collinear.tmpPoint1 = [ + ]; + collinear.tmpPoint2 = [ + ]; + } + var ab = collinear.tmpPoint1, + bc = collinear.tmpPoint2; + ab.x = b.x - a.x; + ab.y = b.y - a.y; + bc.x = c.x - b.x; + bc.y = c.y - b.y; + var dot = ab.x * bc.x + ab.y * bc.y, + magA = Math.sqrt(ab.x * ab.x + ab.y * ab.y), + magB = Math.sqrt(bc.x * bc.x + bc.y * bc.y), + angle = Math.acos(dot / (magA * magB)); + return angle < thresholdAngle; + } + function areaTriangle(a, b, c) { + return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]); + } // Portions of below code copyright 2008 Dmitry Baranovskiy (via MIT license) + + function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { + var t1 = 1 - t; + var t13 = Math.pow(t1, 3); + var t12 = Math.pow(t1, 2); + var t2 = t * t; + var t3 = t2 * t; + var x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x; + var y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y; + var mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x); + var my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y); + var nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x); + var ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y); + var ax = t1 * p1x + t * c1x; + var ay = t1 * p1y + t * c1y; + var cx = t1 * c2x + t * p2x; + var cy = t1 * c2y + t * p2y; + var alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI; + if (mx > nx || my < ny) { + alpha += 180; + } + return { + x: x, + y: y, + m: { + x: mx, + y: my + }, + n: { + x: nx, + y: ny + }, + start: { + x: ax, + y: ay + }, + end: { + x: cx, + y: cy + }, + alpha: alpha + }; + } + function getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) { + return length == null ? bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) : findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); + } + function pointAtLength(path, length, istotal) { + path = path2curve(path); + var x; + var y; + var p; + var l; + var sp = ''; + var subpaths = { + }; + var point; + var len = 0; + for (var i = 0, ii = path.length; i < ii; i++) { + p = path[i]; + if (p[0] === 'M') { + x = + p[1]; + y = + p[2]; + } else { + l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); + if (len + l > length) { + if (!istotal) { + point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len); + return { + x: point.x, + y: point.y, + alpha: point.alpha + }; + } + } + len += l; + x = + p[5]; + y = + p[6]; + } + sp += p.shift() + p; + } + subpaths.end = sp; + point = istotal ? len : findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1); + if (point.alpha) { + point = { + x: point.x, + y: point.y, + alpha: point.alpha + }; + } + return point; + } + function pathToAbsolute(pathArray) { + var res = [ + ], + x = 0, + y = 0, + mx = 0, + my = 0, + start = 0; + if (!pathArray) { + // console.warn("Unexpected state: undefined pathArray"); // shouldn't happen + return res; + } + if (pathArray[0][0] === 'M') { + x = + pathArray[0][1]; + y = + pathArray[0][2]; + mx = x; + my = y; + start++; + res[0] = [ + 'M', + x, + y + ]; + } + var dots; + var crz = pathArray.length === 3 && pathArray[0][0] === 'M' && pathArray[1][0].toUpperCase() === 'R' && pathArray[2][0].toUpperCase() === 'Z'; + for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { + res.push(r = [ + ]); + pa = pathArray[i]; + if (pa[0] !== pa[0].toUpperCase()) { + r[0] = pa[0].toUpperCase(); + switch (r[0]) { + case 'A': + r[1] = pa[1]; + r[2] = pa[2]; + r[3] = pa[3]; + r[4] = pa[4]; + r[5] = pa[5]; + r[6] = + (pa[6] + x); + r[7] = + (pa[7] + y); + break; + case 'V': + r[1] = + pa[1] + y; + break; + case 'H': + r[1] = + pa[1] + x; + break; + case 'R': + dots = [ + x, + y + ].concat(pa.slice(1)); + for (var j = 2, jj = dots.length; j < jj; j++) { + dots[j] = + dots[j] + x; + dots[++j] = + dots[j] + y; + } + res.pop(); + res = res.concat(catmullRom2bezier(dots, crz)); + break; + case 'M': + mx = + pa[1] + x; + my = + pa[2] + y; + break; + default: + for (var _j = 1, _jj = pa.length; _j < _jj; _j++) { + r[_j] = + pa[_j] + (_j % 2 ? x : y); + } + } + } else if (pa[0] === 'R') { + dots = [ + x, + y + ].concat(pa.slice(1)); + res.pop(); + res = res.concat(catmullRom2bezier(dots, crz)); + r = [ + 'R' + ].concat(pa.slice( - 2)); + } else { + for (var k = 0, kk = pa.length; k < kk; k++) { + r[k] = pa[k]; + } + } + switch (r[0]) { + case 'Z': + x = mx; + y = my; + break; + case 'H': + x = r[1]; + break; + case 'V': + y = r[1]; + break; + case 'M': + mx = r[r.length - 2]; + my = r[r.length - 1]; + break; + default: + x = r[r.length - 2]; + y = r[r.length - 1]; + } + } + return res; + } + function path2curve(path, path2) { + var p = pathToAbsolute(path), + p2 = path2 && pathToAbsolute(path2); + var attrs = { + x: 0, + y: 0, + bx: 0, + by: 0, + X: 0, + Y: 0, + qx: null, + qy: null + }; + var attrs2 = { + x: 0, + y: 0, + bx: 0, + by: 0, + X: 0, + Y: 0, + qx: null, + qy: null + }; + var pcoms1 = [ + ]; // path commands of original path p + var pcoms2 = [ + ]; // path commands of original path p2 + var ii; + var processPath = function processPath(path, d, pcom) { + var nx; + var ny; + var tq = { + T: 1, + Q: 1 + }; + if (!path) { + return ['C', + d.x, + d.y, + d.x, + d.y, + d.x, + d.y]; + } + if (!(path[0] in tq)) { + d.qx = d.qy = null; + } + switch (path[0]) { + case 'M': + d.X = path[1]; + d.Y = path[2]; + break; + case 'A': + path = [ + 'C' + ].concat(a2c.apply(0, [ + d.x, + d.y + ].concat(path.slice(1)))); + break; + case 'S': + if (pcom === 'C' || pcom === 'S') { + nx = d.x * 2 - d.bx; + ny = d.y * 2 - d.by; + } else { + nx = d.x; + ny = d.y; + } + path = [ + 'C', + nx, + ny + ].concat(path.slice(1)); + break; + case 'T': + if (pcom === 'Q' || pcom === 'T') { + d.qx = d.x * 2 - d.qx; + d.qy = d.y * 2 - d.qy; + } else { + d.qx = d.x; + d.qy = d.y; + } + path = [ + 'C' + ].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); + break; + case 'Q': + d.qx = path[1]; + d.qy = path[2]; + path = [ + 'C' + ].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4])); + break; + case 'L': + path = [ + 'C' + ].concat(l2c(d.x, d.y, path[1], path[2])); + break; + case 'H': + path = [ + 'C' + ].concat(l2c(d.x, d.y, path[1], d.y)); + break; + case 'V': + path = [ + 'C' + ].concat(l2c(d.x, d.y, d.x, path[1])); + break; + case 'Z': + path = [ + 'C' + ].concat(l2c(d.x, d.y, d.X, d.Y)); + break; + } + return path; + }, + fixArc = function fixArc(pp, i) { + if (pp[i].length > 7) { + pp[i].shift(); + var pi = pp[i]; + while (pi.length) { + pcoms1[i] = 'A'; + if (p2) { + pcoms2[i] = 'A'; + } + pp.splice(i++, 0, [ + 'C' + ].concat(pi.splice(0, 6))); + } + pp.splice(i, 1); + ii = Math.max(p.length, p2 && p2.length || 0); + } + }, + fixM = function fixM(path1, path2, a1, a2, i) { + if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') { + path2.splice(i, 0, [ + 'M', + a2.x, + a2.y + ]); + a1.bx = 0; + a1.by = 0; + a1.x = path1[i][1]; + a1.y = path1[i][2]; + ii = Math.max(p.length, p2 && p2.length || 0); + } + }; + var pfirst = ''; // temporary holder for original path command + var pcom = ''; // holder for previous path command of original path + ii = Math.max(p.length, p2 && p2.length || 0); + for (var i = 0; i < ii; i++) { + if (p[i]) { + pfirst = p[i][0]; + } // save current path command + + if (pfirst !== 'C') { + pcoms1[i] = pfirst; // Save current path command + if (i) { + pcom = pcoms1[i - 1]; + } // Get previous path command pcom + + } + p[i] = processPath(p[i], attrs, pcom); + if (pcoms1[i] !== 'A' && pfirst === 'C') { + pcoms1[i] = 'C'; + } + fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1 + if (p2) { + // the same procedures is done to p2 + if (p2[i]) { + pfirst = p2[i][0]; + } + if (pfirst !== 'C') { + pcoms2[i] = pfirst; + if (i) { + pcom = pcoms2[i - 1]; + } + } + p2[i] = processPath(p2[i], attrs2, pcom); + if (pcoms2[i] !== 'A' && pfirst === 'C') { + pcoms2[i] = 'C'; + } + fixArc(p2, i); + } + fixM(p, p2, attrs, attrs2, i); + fixM(p2, p, attrs2, attrs, i); + var seg = p[i], + seg2 = p2 && p2[i], + seglen = seg.length, + seg2len = p2 && seg2.length; + attrs.x = seg[seglen - 2]; + attrs.y = seg[seglen - 1]; + attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x; + attrs.by = parseFloat(seg[seglen - 3]) || attrs.y; + attrs2.bx = p2 && (parseFloat(seg2[seg2len - 4]) || attrs2.x); + attrs2.by = p2 && (parseFloat(seg2[seg2len - 3]) || attrs2.y); + attrs2.x = p2 && seg2[seg2len - 2]; + attrs2.y = p2 && seg2[seg2len - 1]; + } + return p2 ? [ + p, + p2 + ] : p; + } + function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { + // for more information of where this Math came from visit: + // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes + var PI = Math.PI; + var _120 = PI * 120 / 180; + var f1; + var f2; + var cx; + var cy; + var rad = PI / 180 * ( + angle || 0); + var res = [ + ]; + var xy; + var rotate = function rotate(x, y, rad) { + var X = x * Math.cos(rad) - y * Math.sin(rad), + Y = x * Math.sin(rad) + y * Math.cos(rad); + return { + x: X, + y: Y + }; + }; + if (!recursive) { + xy = rotate(x1, y1, - rad); + x1 = xy.x; + y1 = xy.y; + xy = rotate(x2, y2, - rad); + x2 = xy.x; + y2 = xy.y; + var x = (x1 - x2) / 2; + var y = (y1 - y2) / 2; + var h = x * x / (rx * rx) + y * y / (ry * ry); + if (h > 1) { + h = Math.sqrt(h); + rx = h * rx; + ry = h * ry; + } + var rx2 = rx * rx, + ry2 = ry * ry; + var k = (lac === sweep_flag ? - 1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))); + cx = k * rx * y / ry + (x1 + x2) / 2; + cy = k * - ry * x / rx + (y1 + y2) / 2; + f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); + f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); + f1 = x1 < cx ? PI - f1 : f1; + f2 = x2 < cx ? PI - f2 : f2; + if (f1 < 0) { + f1 = PI * 2 + f1; + } + if (f2 < 0) { + f2 = PI * 2 + f2; + } + if (sweep_flag && f1 > f2) { + f1 = f1 - PI * 2; + } + if (!sweep_flag && f2 > f1) { + f2 = f2 - PI * 2; + } + } else { + f1 = recursive[0]; + f2 = recursive[1]; + cx = recursive[2]; + cy = recursive[3]; + } + var df = f2 - f1; + if (Math.abs(df) > _120) { + var f2old = f2, + x2old = x2, + y2old = y2; + f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : - 1); + x2 = cx + rx * Math.cos(f2); + y2 = cy + ry * Math.sin(f2); + res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [ + f2, + f2old, + cx, + cy + ]); + } + df = f2 - f1; + var c1 = Math.cos(f1), + s1 = Math.sin(f1), + c2 = Math.cos(f2), + s2 = Math.sin(f2), + t = Math.tan(df / 4), + hx = 4 / 3 * rx * t, + hy = 4 / 3 * ry * t, + m1 = [ + x1, + y1 + ], + m2 = [ + x1 + hx * s1, + y1 - hy * c1 + ], + m3 = [ + x2 + hx * s2, + y2 - hy * c2 + ], + m4 = [ + x2, + y2 + ]; + m2[0] = 2 * m1[0] - m2[0]; + m2[1] = 2 * m1[1] - m2[1]; + if (recursive) { + return [m2, + m3, + m4].concat(res); + } else { + res = [ + m2, + m3, + m4 + ].concat(res).join().split(','); + var newres = [ + ]; + for (var i = 0, ii = res.length; i < ii; i++) { + newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; + } + return newres; + } + } // http://schepers.cc/getting-to-the-point + + function catmullRom2bezier(crp, z) { + var d = [ + ]; + for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { + var p = [ + { + x: + crp[i - 2], + y: + crp[i - 1] + }, + { + x: + crp[i], + y: + crp[i + 1] + }, + { + x: + crp[i + 2], + y: + crp[i + 3] + }, + { + x: + crp[i + 4], + y: + crp[i + 5] + } + ]; + if (z) { + if (!i) { + p[0] = { + x: + crp[iLen - 2], + y: + crp[iLen - 1] + }; + } else if (iLen - 4 === i) { + p[3] = { + x: + crp[0], + y: + crp[1] + }; + } else if (iLen - 2 === i) { + p[2] = { + x: + crp[0], + y: + crp[1] + }; + p[3] = { + x: + crp[2], + y: + crp[3] + }; + } + } else { + if (iLen - 4 === i) { + p[3] = p[2]; + } else if (!i) { + p[0] = { + x: + crp[i], + y: + crp[i + 1] + }; + } + } + d.push(['C', + ( - p[0].x + 6 * p[1].x + p[2].x) / 6, + ( - p[0].y + 6 * p[1].y + p[2].y) / 6, + (p[1].x + 6 * p[2].x - p[3].x) / 6, + (p[1].y + 6 * p[2].y - p[3].y) / 6, + p[2].x, + p[2].y]); + } + return d; + } + function l2c(x1, y1, x2, y2) { + return [x1, + y1, + x2, + y2, + x2, + y2]; + } + function q2c(x1, y1, ax, ay, x2, y2) { + var _13 = 1 / 3, + _23 = 2 / 3; + return [_13 * x1 + _23 * ax, + _13 * y1 + _23 * ay, + _13 * x2 + _23 * ax, + _13 * y2 + _23 * ay, + x2, + y2]; + } + function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { + if (z == null) { + z = 1; + } + z = z > 1 ? 1 : z < 0 ? 0 : z; + var z2 = z / 2; + var n = 12; + var Tvalues = [ + - 0.1252, + 0.1252, + - 0.3678, + 0.3678, + - 0.5873, + 0.5873, + - 0.7699, + 0.7699, + - 0.9041, + 0.9041, + - 0.9816, + 0.9816 + ]; + var sum = 0; + var Cvalues = [ + 0.2491, + 0.2491, + 0.2335, + 0.2335, + 0.2032, + 0.2032, + 0.1601, + 0.1601, + 0.1069, + 0.1069, + 0.0472, + 0.0472 + ]; + for (var i = 0; i < n; i++) { + var ct = z2 * Tvalues[i] + z2, + xbase = base3(ct, x1, x2, x3, x4), + ybase = base3(ct, y1, y2, y3, y4), + comb = xbase * xbase + ybase * ybase; + sum += Cvalues[i] * Math.sqrt(comb); + } + return z2 * sum; + } + function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { + if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { + return; + } + var t = 1; + var step = t / 2; + var t2 = t - step; + var l; + var e = 0.01; + l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); + while (Math.abs(l - ll) > e) { + step /= 2; + t2 += (l < ll ? 1 : - 1) * step; + l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); + } + return t2; + } + function base3(t, p1, p2, p3, p4) { + var t1 = - 3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, + t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; + return t * t2 - 3 * p1 + 3 * p2; + } + function cacheKey() { + var hash = ''; + for (var i = arguments.length - 1; i >= 0; --i) { + hash += '?'.concat(i < 0 || arguments.length <= i ? undefined : arguments[i]); + } + return hash; + } + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.fill': 173, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.splice': 188, + 'core-js/modules/es.function.name': 191, + 'core-js/modules/es.number.to-fixed': 198, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 342: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.array-buffer.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.array-buffer.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Data + * @submodule Array Functions + * @for p5 + * @requires core + */ + /** + * Adds a value to the end of an array. Extends the length of + * the array by one. Maps to Array.push(). + * + * @method append + * @deprecated Use array.push(value) instead. + * @param {Array} array Array to append + * @param {any} value to be added to the Array + * @return {Array} the array that was appended to + * @example + *
        + * function setup() { + * let myArray = ['Mango', 'Apple', 'Papaya']; + * print(myArray); // ['Mango', 'Apple', 'Papaya'] + * + * append(myArray, 'Peach'); + * print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach'] + * } + *
        + */ + + _main.default.prototype.append = function (array, value) { + array.push(value); + return array; + }; + /** + * Copies an array (or part of an array) to another array. The src array is + * copied to the dst array, beginning at the position specified by + * srcPosition and into the position specified by dstPosition. The number of + * elements to copy is determined by length. Note that copying values + * overwrites existing values in the destination array. To append values + * instead of overwriting them, use concat(). + * + * The simplified version with only two arguments, arrayCopy(src, dst), + * copies an entire array to another of the same size. It is equivalent to + * arrayCopy(src, 0, dst, 0, src.length). + * + * Using this function is far more efficient for copying array data than + * iterating through a for() loop and copying each element individually. + * + * @method arrayCopy + * @deprecated Use arr1.copyWithin(arr2) instead. + * @param {Array} src the source Array + * @param {Integer} srcPosition starting position in the source Array + * @param {Array} dst the destination Array + * @param {Integer} dstPosition starting position in the destination Array + * @param {Integer} length number of Array elements to be copied + * + * @example + *
        + * let src = ['A', 'B', 'C']; + * let dst = [1, 2, 3]; + * let srcPosition = 1; + * let dstPosition = 0; + * let length = 2; + * + * print(src); // ['A', 'B', 'C'] + * print(dst); // [ 1 , 2 , 3 ] + * + * arrayCopy(src, srcPosition, dst, dstPosition, length); + * print(dst); // ['B', 'C', 3] + *
        + */ + /** + * @method arrayCopy + * @deprecated Use arr1.copyWithin(arr2) instead. + * @param {Array} src + * @param {Array} dst + * @param {Integer} [length] + */ + _main.default.prototype.arrayCopy = function (src, srcPosition, dst, dstPosition, length) { + // the index to begin splicing from dst array + var start; + var end; + if (typeof length !== 'undefined') { + end = Math.min(length, src.length); + start = dstPosition; + src = src.slice(srcPosition, end + srcPosition); + } else { + if (typeof dst !== 'undefined') { + // src, dst, length + // rename so we don't get confused + end = dst; + end = Math.min(end, src.length); + } else { + // src, dst + end = src.length; + } + start = 0; + // rename so we don't get confused + dst = srcPosition; + src = src.slice(0, end); + } // Since we are not returning the array and JavaScript is pass by reference + // we must modify the actual values of the array + // instead of reassigning arrays + + Array.prototype.splice.apply(dst, [ + start, + end + ].concat(src)); + }; + /** + * Concatenates two arrays, maps to Array.concat(). Does not modify the + * input arrays. + * + * @method concat + * @deprecated Use arr1.concat(arr2) instead. + * @param {Array} a first Array to concatenate + * @param {Array} b second Array to concatenate + * @return {Array} concatenated array + * + * @example + *
        + * function setup() { + * let arr1 = ['A', 'B', 'C']; + * let arr2 = [1, 2, 3]; + * + * print(arr1); // ['A','B','C'] + * print(arr2); // [1,2,3] + * + * let arr3 = concat(arr1, arr2); + * + * print(arr1); // ['A','B','C'] + * print(arr2); // [1, 2, 3] + * print(arr3); // ['A','B','C', 1, 2, 3] + * } + *
        + */ + _main.default.prototype.concat = function (list0, list1) { + return list0.concat(list1); + }; + /** + * Reverses the order of an array, maps to Array.reverse() + * + * @method reverse + * @deprecated Use array.reverse() instead. + * @param {Array} list Array to reverse + * @return {Array} the reversed list + * @example + *
        + * function setup() { + * let myArray = ['A', 'B', 'C']; + * print(myArray); // ['A','B','C'] + * + * reverse(myArray); + * print(myArray); // ['C','B','A'] + * } + *
        + */ + _main.default.prototype.reverse = function (list) { + return list.reverse(); + }; + /** + * Decreases an array by one element and returns the shortened array, + * maps to Array.pop(). + * + * @method shorten + * @deprecated Use array.pop() instead. + * @param {Array} list Array to shorten + * @return {Array} shortened Array + * @example + *
        + * function setup() { + * let myArray = ['A', 'B', 'C']; + * print(myArray); // ['A', 'B', 'C'] + * let newArray = shorten(myArray); + * print(myArray); // ['A','B','C'] + * print(newArray); // ['A','B'] + * } + *
        + */ + _main.default.prototype.shorten = function (list) { + list.pop(); + return list; + }; + /** + * Shuffles the elements of an array. + * + * The first parameter, `array`, is the array to be shuffled. For example, + * calling `shuffle(myArray)` will shuffle the elements of `myArray`. By + * default, the original array won’t be modified. Instead, a copy will be + * created, shuffled, and returned. + * + * The second parameter, `modify`, is optional. If `true` is passed, as in + * `shuffle(myArray, true)`, then the array will be shuffled in place without + * making a copy. + * + * @method shuffle + * @param {Array} array array to shuffle. + * @param {Boolean} [bool] if `true`, shuffle the original array in place. Defaults to `false`. + * @return {Array} shuffled array. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of colors. + * let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; + * + * // Create a shuffled copy of the array. + * let shuffledColors = shuffle(colors); + * + * // Draw a row of circles using the original array. + * for (let i = 0; i < colors.length; i += 1) { + * // Calculate the x-coordinate. + * let x = (i + 1) * 12.5; + * + * // Style the circle. + * let c = colors[i]; + * fill(c); + * + * // Draw the circle. + * circle(x, 33, 10); + * } + * + * // Draw a row of circles using the original array. + * for (let i = 0; i < shuffledColors.length; i += 1) { + * // Calculate the x-coordinate. + * let x = (i + 1) * 12.5; + * + * // Style the circle. + * let c = shuffledColors[i]; + * fill(c); + * + * // Draw the circle. + * circle(x, 67, 10); + * } + * + * describe( + * 'Two rows of circles on a gray background. The top row follows the color sequence ROYGBIV. The bottom row has all the same colors but they are shuffled.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of colors. + * let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; + * + * // Shuffle the array. + * shuffle(colors, true); + * + * // Draw a row of circles using the original array. + * for (let i = 0; i < colors.length; i += 1) { + * // Calculate the x-coordinate. + * let x = (i + 1) * 12.5; + * + * // Style the circle. + * let c = colors[i]; + * fill(c); + * + * // Draw the circle. + * circle(x, 50, 10); + * } + * + * describe( + * 'A row of colorful circles on a gray background. Their sequence changes each time the sketch runs.' + * ); + * } + * + *
        + */ + _main.default.prototype.shuffle = function (arr, bool) { + var isView = ArrayBuffer && ArrayBuffer.isView && ArrayBuffer.isView(arr); + arr = bool || isView ? arr : arr.slice(); + var rnd, + tmp, + idx = arr.length; + while (idx > 1) { + rnd = this.random(0, 1) * idx | 0; + tmp = arr[--idx]; + arr[idx] = arr[rnd]; + arr[rnd] = tmp; + } + return arr; + }; + /** + * Sorts an array of numbers from smallest to largest, or puts an array of + * words in alphabetical order. The original array is not modified; a + * re-ordered array is returned. The count parameter states the number of + * elements to sort. For example, if there are 12 elements in an array and + * count is set to 5, only the first 5 elements in the array will be sorted. + * + * @method sort + * @deprecated Use array.sort() instead. + * @param {Array} list Array to sort + * @param {Integer} [count] number of elements to sort, starting from 0 + * @return {Array} the sorted list + * + * @example + *
        + * function setup() { + * let words = ['banana', 'apple', 'pear', 'lime']; + * print(words); // ['banana', 'apple', 'pear', 'lime'] + * let count = 4; // length of array + * + * words = sort(words, count); + * print(words); // ['apple', 'banana', 'lime', 'pear'] + * } + *
        + *
        + * function setup() { + * let numbers = [2, 6, 1, 5, 14, 9, 8, 12]; + * print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12] + * let count = 5; // Less than the length of the array + * + * numbers = sort(numbers, count); + * print(numbers); // [1,2,5,6,14,9,8,12] + * } + *
        + */ + _main.default.prototype.sort = function (list, count) { + var arr = count ? list.slice(0, Math.min(count, list.length)) : list; + var rest = count ? list.slice(Math.min(count, list.length)) : [ + ]; + if (typeof arr[0] === 'string') { + arr = arr.sort(); + } else { + arr = arr.sort(function (a, b) { + return a - b; + }); + } + return arr.concat(rest); + }; + /** + * Inserts a value or an array of values into an existing array. The first + * parameter specifies the initial array to be modified, and the second + * parameter defines the data to be inserted. The third parameter is an index + * value which specifies the array position from which to insert data. + * (Remember that array index numbering starts at zero, so the first position + * is 0, the second position is 1, and so on.) + * + * @method splice + * @deprecated Use array.splice() instead. + * @param {Array} list Array to splice into + * @param {any} value value to be spliced in + * @param {Integer} position in the array from which to insert data + * @return {Array} the list + * + * @example + *
        + * function setup() { + * let myArray = [0, 1, 2, 3, 4]; + * let insArray = ['A', 'B', 'C']; + * print(myArray); // [0, 1, 2, 3, 4] + * print(insArray); // ['A','B','C'] + * + * splice(myArray, insArray, 3); + * print(myArray); // [0,1,2,'A','B','C',3,4] + * } + *
        + */ + _main.default.prototype.splice = function (list, value, index) { + // note that splice returns spliced elements and not an array + Array.prototype.splice.apply(list, [ + index, + 0 + ].concat(value)); + return list; + }; + /** + * Extracts an array of elements from an existing array. The list parameter + * defines the array from which the elements will be copied, and the start + * and count parameters specify which elements to extract. If no count is + * given, elements will be extracted from the start to the end of the array. + * When specifying the start, remember that the first array element is 0. + * This function does not change the source array. + * + * @method subset + * @deprecated Use array.slice() instead. + * @param {Array} list Array to extract from + * @param {Integer} start position to begin + * @param {Integer} [count] number of values to extract + * @return {Array} Array of extracted elements + * + * @example + *
        + * function setup() { + * let myArray = [1, 2, 3, 4, 5]; + * print(myArray); // [1, 2, 3, 4, 5] + * + * let sub1 = subset(myArray, 0, 3); + * let sub2 = subset(myArray, 2, 2); + * print(sub1); // [1,2,3] + * print(sub2); // [3,4] + * } + *
        + */ + _main.default.prototype.subset = function (list, start, count) { + if (typeof count !== 'undefined') { + return list.slice(start, start + count); + } else { + return list.slice(start, list.length); + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array-buffer.constructor': 169, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.splice': 188, + 'core-js/modules/es.object.to-string': 205 + } + ], + 343: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.repeat'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.repeat'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Data + * @submodule Conversion + * @for p5 + * @requires core + */ + /** + * Converts a `String` to a floating point (decimal) `Number`. + * + * `float()` converts strings that resemble numbers, such as `'12.34'`, into + * numbers. + * + * The parameter, `str`, is the string value to convert. For example, calling + * `float('12.34')` returns the number `12.34`. If an array of strings is + * passed, as in `float(['12.34', '56.78'])`, then an array of numbers will be + * returned. + * + * Note: If a string can't be converted to a number, as in `float('giraffe')`, + * then the value `NaN` (not a number) will be returned. + * + * @method float + * @param {String} str string to convert. + * @return {Number} converted number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let original = '12.3'; + * + * // Convert the string to a number. + * let converted = float(original); + * + * // Double the converted value. + * let twice = converted * 2; + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(12); + * + * // Display the original and converted values. + * text(`${original} × 2 = ${twice}`, 50, 50); + * + * describe('The text "12.3 × 2 = 24.6" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of strings. + * let original = ['60', '30', '15']; + * + * // Convert the strings to numbers. + * let diameters = float(original); + * + * for (let d of diameters) { + * // Draw a circle. + * circle(50, 50, d); + * } + * + * describe('Three white, concentric circles on a gray background.'); + * } + * + *
        + */ + /** + * @method float + * @param {String[]} ns array of strings to convert. + * @return {Number[]} converted numbers. + */ + + _main.default.prototype.float = function (str) { + if (str instanceof Array) { + return str.map(parseFloat); + } + return parseFloat(str); + }; + /** + * Converts a `Boolean`, `String`, or decimal `Number` to an integer. + * + * `int()` converts values to integers. Integers are positive or negative + * numbers without decimals. If the original value has decimals, as in -34.56, + * they're removed to produce an integer such as -34. + * + * The parameter, `n`, is the value to convert. If `n` is a Boolean, as in + * `int(false)` or `int(true)`, then the number 0 (`false`) or 1 (`true`) will + * be returned. If `n` is a string or number, as in `int('45')` or + * `int(67.89)`, then an integer will be returned. If an array is passed, as + * in `int([12.34, 56.78])`, then an array of integers will be returned. + * + * Note: If a value can't be converted to a number, as in `int('giraffe')`, + * then the value `NaN` (not a number) will be returned. + * + * @method int + * @param {String|Boolean|Number} n value to convert. + * @return {Number} converted number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a Boolean variable. + * let original = false; + * + * // Convert the Boolean to an integer. + * let converted = int(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} : ${converted}`, 50, 50); + * + * describe('The text "false : 0" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let original = '12.34'; + * + * // Convert the string to an integer. + * let converted = int(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Display the original and converted values. + * text(`${original} ≈ ${converted}`, 50, 50); + * + * describe('The text "12.34 ≈ 12" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a decimal number variable. + * let original = 12.34; + * + * // Convert the decimal number to an integer. + * let converted = int(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Display the original and converted values. + * text(`${original} ≈ ${converted}`, 50, 50); + * + * describe('The text "12.34 ≈ 12" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of strings. + * let original = ['60', '30', '15']; + * + * // Convert the strings to integers. + * let diameters = int(original); + * + * for (let d of diameters) { + * // Draw a circle. + * circle(50, 50, d); + * } + * + * describe('Three white, concentric circles on a gray background.'); + * } + * + *
        + */ + /** + * @method int + * @param {Array} ns values to convert. + * @return {Number[]} converted numbers. + */ + _main.default.prototype.int = function (n) { + var radix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + if (n === Infinity || n === 'Infinity') { + return Infinity; + } else if (n === - Infinity || n === '-Infinity') { + return - Infinity; + } else if (typeof n === 'string') { + return parseInt(n, radix); + } else if (typeof n === 'number') { + return n | 0; + } else if (typeof n === 'boolean') { + return n ? 1 : 0; + } else if (n instanceof Array) { + return n.map(function (n) { + return _main.default.prototype.int(n, radix); + }); + } + }; + /** + * Converts a `Boolean` or `Number` to `String`. + * + * `str()` converts values to strings. See the + * String reference page for guidance on using + * template literals instead. + * + * The parameter, `n`, is the value to convert. If `n` is a Boolean, as in + * `str(false)` or `str(true)`, then the value will be returned as a string, + * as in `'false'` or `'true'`. If `n` is a number, as in `str(123)`, then its + * value will be returned as a string, as in `'123'`. If an array is passed, + * as in `str([12.34, 56.78])`, then an array of strings will be returned. + * + * @method str + * @param {String|Boolean|Number} n value to convert. + * @return {String} converted string. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a Boolean variable. + * let original = false; + * + * // Convert the Boolean to a string. + * let converted = str(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} : ${converted}`, 50, 50); + * + * describe('The text "false : false" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a number variable. + * let original = 123; + * + * // Convert the number to a string. + * let converted = str(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} = ${converted}`, 50, 50); + * + * describe('The text "123 = 123" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of numbers. + * let original = [12, 34, 56]; + * + * // Convert the numbers to strings. + * let strings = str(original); + * + * // Create an empty string variable. + * let final = ''; + * + * // Concatenate all the strings. + * for (let s of strings) { + * final += s; + * } + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the concatenated string. + * text(final, 50, 50); + * + * describe('The text "123456" written in black on a gray background.'); + * } + * + *
        + */ + _main.default.prototype.str = function (n) { + if (n instanceof Array) { + return n.map(_main.default.prototype.str); + } else { + return String(n); + } + }; + /** + * Converts a `String` or `Number` to a `Boolean`. + * + * `boolean()` converts values to `true` or `false`. + * + * The parameter, `n`, is the value to convert. If `n` is a string, then + * `boolean('true')` will return `true` and every other string value will + * return `false`. If `n` is a number, then `boolean(0)` will return `false` + * and every other numeric value will return `true`. If an array is passed, as + * `in boolean([0, 1, 'true', 'blue'])`, then an array of Boolean values will + * be returned. + * + * @method boolean + * @param {String|Boolean|Number} n value to convert. + * @return {Boolean} converted Boolean value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a number variable. + * let original = 0; + * + * // Convert the number to a Boolean value. + * let converted = boolean(original); + * + * // Style the circle based on the converted value. + * if (converted === true) { + * fill('blue'); + * } else { + * fill('red'); + * } + * + * // Draw the circle. + * circle(50, 50, 40); + * + * describe('A red circle on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let original = 'true'; + * + * // Convert the string to a Boolean value. + * let converted = boolean(original); + * + * // Style the circle based on the converted value. + * if (converted === true) { + * fill('blue'); + * } else { + * fill('red'); + * } + * + * // Draw the circle. + * circle(50, 50, 40); + * + * describe('A blue circle on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of values. + * let original = [0, 'hi', 123, 'true']; + * + * // Convert the array to a Boolean values. + * let converted = boolean(original); + * + * // Iterate over the array of converted Boolean values. + * for (let i = 0; i < converted.length; i += 1) { + * + * // Style the circle based on the converted value. + * if (converted[i] === true) { + * fill('blue'); + * } else { + * fill('red'); + * } + * + * // Calculate the x-coordinate. + * let x = (i + 1) * 20; + * + * // Draw the circle. + * circle(x, 50, 15); + * } + * + * describe( + * 'A row of circles on a gray background. The two circles on the left are red and the two on the right are blue.' + * ); + * } + * + *
        + */ + /** + * @method boolean + * @param {Array} ns values to convert. + * @return {Boolean[]} converted Boolean values. + */ + _main.default.prototype.boolean = function (n) { + if (typeof n === 'number') { + return n !== 0; + } else if (typeof n === 'string') { + return n.toLowerCase() === 'true'; + } else if (typeof n === 'boolean') { + return n; + } else if (n instanceof Array) { + return n.map(_main.default.prototype.boolean); + } + }; + /** + * Converts a `Boolean`, `String`, or `Number` to its byte value. + * + * `byte()` converts a value to an integer (whole number) between -128 and + * 127. Values greater than 127 wrap around while negative values are + * unchanged. For example, 128 becomes -128 and -129 remains the same. + * + * The parameter, `n`, is the value to convert. If `n` is a Boolean, as in + * `byte(false)` or `byte(true)`, the number 0 (`false`) or 1 (`true`) will be + * returned. If `n` is a string or number, as in `byte('256')` or `byte(256)`, + * then the byte value will be returned. Decimal values are ignored. If an + * array is passed, as in `byte([true, 123, '456'])`, then an array of byte + * values will be returned. + * + * Note: If a value can't be converted to a number, as in `byte('giraffe')`, + * then the value `NaN` (not a number) will be returned. + * + * @method byte + * @param {String|Boolean|Number} n value to convert. + * @return {Number} converted byte value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a Boolean variable. + * let original = true; + * + * // Convert the Boolean to its byte value. + * let converted = byte(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} : ${converted}`, 50, 50); + * + * describe('The text "true : 1" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let original = '256'; + * + * // Convert the string to its byte value. + * let converted = byte(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} : ${converted}`, 50, 50); + * + * describe('The text "256 : 0" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a number variable. + * let original = 256; + * + * // Convert the number to its byte value. + * let converted = byte(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} : ${converted}`, 50, 50); + * + * describe('The text "256 : 0" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of values. + * let original = [false, '64', 383]; + * + * // Convert the array elements to their byte values. + * let converted = byte(original); + * + * // Iterate over the converted array elements. + * for (let i = 0; i < converted.length; i += 1) { + * + * // Style the circle. + * fill(converted[i]); + * + * // Calculate the x-coordinate. + * let x = (i + 1) * 25; + * + * // Draw the circle. + * circle(x, 50, 20); + * } + * + * describe( + * 'Three gray circles on a gray background. The circles get lighter from left to right.' + * ); + * } + * + *
        + */ + /** + * @method byte + * @param {Array} ns values to convert. + * @return {Number[]} converted byte values. + */ + _main.default.prototype.byte = function (n) { + var nn = _main.default.prototype.int(n, 10); + if (typeof nn === 'number') { + return (nn + 128) % 256 - 128; + } else if (nn instanceof Array) { + return nn.map(_main.default.prototype.byte); + } + }; + /** + * Converts a `Number` or `String` to a single-character `String`. + * + * `char()` converts numbers to their single-character string representations. + * + * The parameter, `n`, is the value to convert. If a number is passed, as in + * `char(65)`, the corresponding single-character string is returned. If a + * string is passed, as in `char('65')`, the string is converted to an integer + * (whole number) and the corresponding single-character string is returned. + * If an array is passed, as in `char([65, 66, 67])`, an array of + * single-character strings is returned. + * + * See MDN + * for more information about conversions. + * + * @method char + * @param {String|Number} n value to convert. + * @return {String} converted single-character string. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a number variable. + * let original = 65; + * + * // Convert the number to a char. + * let converted = char(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} : ${converted}`, 50, 50); + * + * describe('The text "65 : A" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let original = '65'; + * + * // Convert the string to a char. + * let converted = char(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} : ${converted}`, 50, 50); + * + * describe('The text "65 : A" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of numbers. + * let original = ['65', 66, '67']; + * + * // Convert the string to a char. + * let converted = char(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Iterate over elements of the converted array. + * for (let i = 0; i < converted.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Display the original and converted values. + * text(`${original[i]} : ${converted[i]}`, 50, y); + * } + * + * describe( + * 'The text "65 : A", "66 : B", and "67 : C" written on three separate lines. The text is in black on a gray background.' + * ); + * } + * + *
        + */ + /** + * @method char + * @param {Array} ns values to convert. + * @return {String[]} converted single-character strings. + */ + _main.default.prototype.char = function (n) { + if (typeof n === 'number' && !isNaN(n)) { + return String.fromCharCode(n); + } else if (n instanceof Array) { + return n.map(_main.default.prototype.char); + } else if (typeof n === 'string') { + return _main.default.prototype.char(parseInt(n, 10)); + } + }; + /** + * Converts a single-character `String` to a `Number`. + * + * `unchar()` converts single-character strings to their corresponding + * integer (whole number). + * + * The parameter, `n`, is the character to convert. For example, + * `unchar('A')`, returns the number 65. If an array is passed, as in + * `unchar(['A', 'B', 'C'])`, an array of integers is returned. + * + * @method unchar + * @param {String} n value to convert. + * @return {Number} converted number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let original = 'A'; + * + * // Convert the string to a number. + * let converted = unchar(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} : ${converted}`, 50, 50); + * + * describe('The text "A : 65" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of characters. + * let original = ['A', 'B', 'C']; + * + * // Convert the string to a number. + * let converted = unchar(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Iterate over elements of the converted array. + * for (let i = 0; i < converted.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Display the original and converted values. + * text(`${original[i]} : ${converted[i]}`, 50, y); + * } + * + * describe( + * 'The text "A : 65", "B : 66", and "C :67" written on three separate lines. The text is in black on a gray background.' + * ); + * } + * + *
        + */ + /** + * @method unchar + * @param {String[]} ns values to convert. + * @return {Number[]} converted numbers. + */ + _main.default.prototype.unchar = function (n) { + if (typeof n === 'string' && n.length === 1) { + return n.charCodeAt(0); + } else if (n instanceof Array) { + return n.map(_main.default.prototype.unchar); + } + }; + /** + * Converts a `Number` to a `String` with its hexadecimal value. + * + * `hex()` converts a number to a string with its hexadecimal number value. + * Hexadecimal (hex) numbers are base-16, which means there are 16 unique + * digits. Hex extends the numbers 0–9 with the letters A–F. For example, the + * number `11` (eleven) in base-10 is written as the letter `B` in hex. + * + * The first parameter, `n`, is the number to convert. For example, `hex(20)`, + * returns the string `'00000014'`. If an array is passed, as in + * `hex([1, 10, 100])`, an array of hexadecimal strings is returned. + * + * The second parameter, `digits`, is optional. If a number is passed, as in + * `hex(20, 2)`, it sets the number of hexadecimal digits to display. For + * example, calling `hex(20, 2)` returns the string `'14'`. + * + * @method hex + * @param {Number} n value to convert. + * @param {Number} [digits] number of digits to include. + * @return {String} converted hexadecimal value. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a number variable. + * let original = 20; + * + * // Convert the number to a hex string. + * let converted = hex(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Display the original and converted values. + * text(`${original} = ${converted}`, 50, 50); + * + * describe('The text "20 = 00000014" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a number variable. + * let original = 20; + * + * // Convert the number to a hex string. + * // Only display two hex digits. + * let converted = hex(original, 2); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} = ${converted}`, 50, 50); + * + * describe('The text "20 = 14" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of numbers. + * let original = [1, 10, 100]; + * + * // Convert the numbers to hex strings. + * // Only use two hex digits. + * let converted = hex(original, 2); + * + * // Style the text. + * textAlign(RIGHT, CENTER); + * textSize(16); + * + * // Iterate over the converted values. + * for (let i = 0; i < converted.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Display the original and converted values. + * text(`${ original[i]} = ${converted[i]}`, 75, y); + * } + * + * describe( + * 'The text "1 = 01", "10 = 0A", and "100 = 64" written on three separate lines. The text is in black on a gray background.' + * ); + * } + * + *
        + */ + /** + * @method hex + * @param {Number[]} ns values to convert. + * @param {Number} [digits] + * @return {String[]} converted hexadecimal values. + */ + _main.default.prototype.hex = function (n, digits) { + digits = digits === undefined || digits === null ? digits = 8 : digits; + if (n instanceof Array) { + return n.map(function (n) { + return _main.default.prototype.hex(n, digits); + }); + } else if (n === Infinity || n === - Infinity) { + var c = n === Infinity ? 'F' : '0'; + return c.repeat(digits); + } else if (typeof n === 'number') { + if (n < 0) { + n = 4294967295 + n + 1; + } + var hex = Number(n).toString(16).toUpperCase(); + while (hex.length < digits) { + hex = '0'.concat(hex); + } + if (hex.length >= digits) { + hex = hex.substring(hex.length - digits, hex.length); + } + return hex; + } + }; + /** + * Converts a `String` with a hexadecimal value to a `Number`. + * + * `unhex()` converts a string with its hexadecimal number value to a number. + * Hexadecimal (hex) numbers are base-16, which means there are 16 unique + * digits. Hex extends the numbers 0–9 with the letters A–F. For example, the + * number `11` (eleven) in base-10 is written as the letter `B` in hex. + * + * The first parameter, `n`, is the hex string to convert. For example, + * `unhex('FF')`, returns the number 255. If an array is passed, as in + * `unhex(['00', '80', 'FF'])`, an array of numbers is returned. + * + * @method unhex + * @param {String} n value to convert. + * @return {Number} converted number. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a a hex string variable + * let original = 'FF'; + * + * // Convert the hex string to a number. + * let converted = unhex(original); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the original and converted values. + * text(`${original} = ${converted}`, 50, 50); + * + * describe('The text "FF = 255" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of numbers. + * let original = ['00', '80', 'FF']; + * + * // Convert the numbers to hex strings. + * // Only use two hex digits. + * let converted = unhex(original, 2); + * + * // Style the text. + * textAlign(RIGHT, CENTER); + * textSize(16); + * + * // Iterate over the converted values. + * for (let i = 0; i < converted.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Display the original and converted values. + * text(`${ original[i]} = ${converted[i]}`, 80, y); + * } + * + * describe( + * 'The text "00 = 0", "80 = 128", and "FF = 255" written on three separate lines. The text is in black on a gray background.' + * ); + * } + * + *
        + */ + /** + * @method unhex + * @param {String[]} ns values to convert. + * @return {Number[]} converted numbers. + */ + _main.default.prototype.unhex = function (n) { + if (n instanceof Array) { + return n.map(_main.default.prototype.unhex); + } else { + return parseInt('0x'.concat(n), 16); + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.number.constructor': 196, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.repeat': 218 + } + ], + 344: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.pad-start'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.constructor'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.pad-start'); + _dereq_('core-js/modules/es.string.replace'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + _dereq_('../core/friendly_errors/validate_params'); + _dereq_('../core/friendly_errors/file_errors'); + _dereq_('../core/friendly_errors/fes_core'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); + } + function _nonIterableRest() { + throw new TypeError('Invalid attempt to destructure non-iterable instance'); + } + function _iterableToArrayLimit(arr, i) { + if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === '[object Arguments]')) { + return; + } + var _arr = [ + ]; + var _n = true; + var _d = false; + var _e = undefined; + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i['return'] != null) _i['return'](); + } finally { + if (_d) throw _e; + } + } + return _arr; + } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } /** + * @module Data + * @submodule String Functions + * @for p5 + * @requires core + */ + //return p5; //LM is this a mistake? + /** + * Combines an array of strings into one string. + * + * The first parameter, `list`, is the array of strings to join. + * + * The second parameter, `separator`, is the character(s) that should be used + * to separate the combined strings. For example, calling + * `join(myWords, ' : ')` would return a string of words each separated by a + * colon and spaces. + * + * @method join + * @param {Array} list array of strings to combine. + * @param {String} separator character(s) to place between strings when they're combined. + * @return {String} combined string. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of strings. + * let myWords = ['one', 'two', 'three']; + * + * // Create a combined string + * let combined = join(myWords, ' : '); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * + * // Display the combined string. + * text(combined, 50, 50); + * + * describe('The text "one : two : three" written in black on a gray canvas.'); + * } + * + *
        + */ + + _main.default.prototype.join = function (list, separator) { + _main.default._validateParameters('join', arguments); + return list.join(separator); + }; + /** + * Applies a regular expression to a string and returns an array with the + * first match. + * + * `match()` uses regular expressions (regex) to match patterns in text. For + * example, the regex `abc` can be used to search a string for the exact + * sequence of characters `abc`. See + * MDN. + * for more information about regexes. + * + * The first parameter, `str`, is the string to search. + * + * The second parameter, `regex`, is a string with the regular expression to + * apply. For example, calling `match('Hello, p5*js!', '[a-z][0-9]')` would + * return the array `['p5']`. + * + * Note: If no matches are found, `null` is returned. + * + * @method match + * @param {String} str string to search. + * @param {String} regexp regular expression to match. + * @return {String[]} match if found. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let string = 'Hello, p5*js!'; + * + * // Match the characters that are lowercase + * // letters followed by digits. + * let matches = match(string, '[a-z][0-9]'); + * + * // Print the matches array to the console: + * // ['p5'] + * print(matches); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the matches. + * text(matches, 50, 50); + * + * describe('The text "p5" written in black on a gray canvas.'); + * } + * + *
        + */ + _main.default.prototype.match = function (str, reg) { + _main.default._validateParameters('match', arguments); + return str.match(reg); + }; + /** + * Applies a regular expression to a string and returns an array of matches. + * + * `match()` uses regular expressions (regex) to match patterns in text. For + * example, the regex `abc` can be used to search a string for the exact + * sequence of characters `abc`. See + * MDN. + * for more information about regexes. `matchAll()` is different from + * match() because it returns every match, not just + * the first. + * + * The first parameter, `str`, is the string to search. + * + * The second parameter, `regex`, is a string with the regular expression to + * apply. For example, calling + * `matchAll('p5*js is easier than abc123', '[a-z][0-9]')` would return the + * 2D array `[['p5'], ['c1']]`. + * + * Note: If no matches are found, an empty array `[]` is returned. + * + * @method matchAll + * @param {String} str string to search. + * @param {String} regexp regular expression to match. + * @return {String[]} matches found. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let string = 'p5*js is easier than abc123'; + * + * // Match the character sequences that are + * // lowercase letters followed by digits. + * let matches = matchAll(string, '[a-z][0-9]'); + * + * // Print the matches array to the console: + * // [['p5'], ['c1']] + * print(matches); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Iterate over the matches array. + * for (let i = 0; i < matches.length; i += 1) { + * + * // Calculate the y-coordainate. + * let y = (i + 1) * 33; + * + * // Display the match. + * text(matches[i], 50, y); + * } + * + * describe( + * 'The text "p5" and "c1" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + */ + _main.default.prototype.matchAll = function (str, reg) { + _main.default._validateParameters('matchAll', arguments); + var re = new RegExp(reg, 'g'); + var match = re.exec(str); + var matches = [ + ]; + while (match !== null) { + matches.push(match); + // matched text: match[0] + // match start: match.index + // capturing group n: match[n] + match = re.exec(str); + } + return matches; + }; + /** + * Converts a `Number` into a `String` with a given number of digits. + * + * `nf()` converts numbers such as `123.45` into strings formatted with a set + * number of digits, as in `'123.4500'`. + * + * The first parameter, `num`, is the number to convert to a string. For + * example, calling `nf(123.45)` returns the string `'123.45'`. If an array of + * numbers is passed, as in `nf([123.45, 67.89])`, an array of formatted + * strings will be returned. + * + * The second parameter, `left`, is optional. If a number is passed, as in + * `nf(123.45, 4)`, it sets the minimum number of digits to include to the + * left of the decimal place. If `left` is larger than the number of digits in + * `num`, then unused digits will be set to 0. For example, calling + * `nf(123.45, 4)` returns the string `'0123.45'`. + * + * The third parameter, `right`, is also optional. If a number is passed, as + * in `nf(123.45, 4, 1)`, it sets the minimum number of digits to include to + * the right of the decimal place. If `right` is smaller than the number of + * decimal places in `num`, then `num` will be rounded to the given number of + * decimal places. For example, calling `nf(123.45, 4, 1)` returns the string + * `'0123.5'`. If right is larger than the number of decimal places in `num`, + * then unused decimal places will be set to 0. For example, calling + * `nf(123.45, 4, 3)` returns the string `'0123.450'`. + * + * @method nf + * @param {Number|String} num number to format. + * @param {Integer|String} [left] number of digits to include to the left of + * the decimal point. + * @param {Integer|String} [right] number of digits to include to the right + * of the decimal point. + * @return {String} formatted string. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(16); + * + * // Create a number variable. + * let number = 123.45; + * + * // Display the number as a string. + * let formatted = nf(number); + * text(formatted, 20, 25); + * + * // Display the number with four digits + * // to the left of the decimal. + * let left = nf(number, 4); + * text(left, 20, 50); + * + * // Display the number with four digits + * // to the left of the decimal and one + * // to the right. + * let right = nf(number, 4, 1); + * text(right, 20, 75); + * + * describe( + * 'The numbers "123.45", "0123.45", and "0123.5" written on three separate lines. The text is in black on a gray background.' + * ); + * } + * + *
        + */ + /** + * @method nf + * @param {Number[]} nums numbers to format. + * @param {Integer|String} [left] + * @param {Integer|String} [right] + * @return {String[]} formatted strings. + */ + _main.default.prototype.nf = function (nums, left, right) { + _main.default._validateParameters('nf', arguments); + if (nums instanceof Array) { + return nums.map(function (x) { + return doNf(x, left, right); + }); + } else { + var typeOfFirst = Object.prototype.toString.call(nums); + if (typeOfFirst === '[object Arguments]') { + if (nums.length === 3) { + return this.nf(nums[0], nums[1], nums[2]); + } else if (nums.length === 2) { + return this.nf(nums[0], nums[1]); + } else { + return this.nf(nums[0]); + } + } else { + return doNf(nums, left, right); + } + } + }; + function doNf(num, left, right) { + var _num$toString$split = num.toString().split('.'), + _num$toString$split2 = _slicedToArray(_num$toString$split, 2), + leftPart = _num$toString$split2[0], + rightPart = _num$toString$split2[1]; + if (typeof right === 'undefined') { + leftPart = leftPart.padStart(left, '0'); + return rightPart ? leftPart + '.' + rightPart : leftPart; + } else { + var roundedOff = num.toFixed(right); + var _roundedOff$toString$ = roundedOff.toString().split('.'); + var _roundedOff$toString$2 = _slicedToArray(_roundedOff$toString$, 2); + leftPart = _roundedOff$toString$2[0]; + rightPart = _roundedOff$toString$2[1]; + leftPart = leftPart.padStart(left, '0'); + if (typeof rightPart === 'undefined') { + return leftPart; + } else { + return leftPart + '.' + rightPart; + } + } + } /** + * Converts a `Number` into a `String` with commas to mark units of 1,000. + * + * `nfc()` converts numbers such as 12345 into strings formatted with commas + * to mark the thousands place, as in `'12,345'`. + * + * The first parameter, `num`, is the number to convert to a string. For + * example, calling `nfc(12345)` returns the string `'12,345'`. + * + * The second parameter, `right`, is optional. If a number is passed, as in + * `nfc(12345, 1)`, it sets the minimum number of digits to include to the + * right of the decimal place. If `right` is smaller than the number of + * decimal places in `num`, then `num` will be rounded to the given number of + * decimal places. For example, calling `nfc(12345.67, 1)` returns the string + * `'12,345.7'`. If `right` is larger than the number of decimal places in + * `num`, then unused decimal places will be set to 0. For example, calling + * `nfc(12345.67, 3)` returns the string `'12,345.670'`. + * + * @method nfc + * @param {Number|String} num number to format. + * @param {Integer|String} [right] number of digits to include to the right + * of the decimal point. + * @return {String} formatted string. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(16); + * + * // Create a number variable. + * let number = 12345; + * + * // Display the number as a string. + * let commas = nfc(number); + * text(commas, 15, 33); + * + * // Display the number with four digits + * // to the left of the decimal. + * let decimals = nfc(number, 2); + * text(decimals, 15, 67); + * + * describe( + * 'The numbers "12,345" and "12,345.00" written on separate lines. The text is in black on a gray background.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of numbers. + * let numbers = [12345, 6789]; + * + * // Convert the numbers to formatted strings. + * let formatted = nfc(numbers); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Iterate over the array. + * for (let i = 0; i < formatted.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 33; + * + * // Display the original and formatted numbers. + * text(`${numbers[i]} : ${formatted[i]}`, 50, y); + * } + * + * describe( + * 'The text "12345 : 12,345" and "6789 : 6,789" written on two separate lines. The text is in black on a gray background.' + * ); + * } + * + *
        + */ + /** + * @method nfc + * @param {Number[]} nums numbers to format. + * @param {Integer|String} [right] + * @return {String[]} formatted strings. + */ + + _main.default.prototype.nfc = function (num, right) { + _main.default._validateParameters('nfc', arguments); + if (num instanceof Array) { + return num.map(function (x) { + return doNfc(x, right); + }); + } else { + return doNfc(num, right); + } + }; + function doNfc(num, right) { + num = num.toString(); + var dec = num.indexOf('.'); + var rem = dec !== - 1 ? num.substring(dec) : ''; + var n = dec !== - 1 ? num.substring(0, dec) : num; + n = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); + if (right === 0) { + rem = ''; + } else if (typeof right !== 'undefined') { + if (right > rem.length) { + rem += dec === - 1 ? '.' : ''; + var len = right - rem.length + 1; + for (var i = 0; i < len; i++) { + rem += '0'; + } + } else { + rem = rem.substring(0, right + 1); + } + } + return n + rem; + } /** + * Converts a `Number` into a `String` with a plus or minus sign. + * + * `nfp()` converts numbers such as 123 into strings formatted with a `+` or + * `-` symbol to mark whether they're positive or negative, as in `'+123'`. + * + * The first parameter, `num`, is the number to convert to a string. For + * example, calling `nfp(123.45)` returns the string `'+123.45'`. If an array + * of numbers is passed, as in `nfp([123.45, -6.78])`, an array of formatted + * strings will be returned. + * + * The second parameter, `left`, is optional. If a number is passed, as in + * `nfp(123.45, 4)`, it sets the minimum number of digits to include to the + * left of the decimal place. If `left` is larger than the number of digits in + * `num`, then unused digits will be set to 0. For example, calling + * `nfp(123.45, 4)` returns the string `'+0123.45'`. + * + * The third parameter, `right`, is also optional. If a number is passed, as + * in `nfp(123.45, 4, 1)`, it sets the minimum number of digits to include to + * the right of the decimal place. If `right` is smaller than the number of + * decimal places in `num`, then `num` will be rounded to the given number of + * decimal places. For example, calling `nfp(123.45, 4, 1)` returns the + * string `'+0123.5'`. If `right` is larger than the number of decimal places + * in `num`, then unused decimal places will be set to 0. For example, + * calling `nfp(123.45, 4, 3)` returns the string `'+0123.450'`. + * + * @method nfp + * @param {Number} num number to format. + * @param {Integer} [left] number of digits to include to the left of the + * decimal point. + * @param {Integer} [right] number of digits to include to the right of the + * decimal point. + * @return {String} formatted string. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create number variables. + * let positive = 123; + * let negative = -123; + * + * // Convert the positive number to a formatted string. + * let p = nfp(positive); + * + * // Convert the negative number to a formatted string + * // with four digits to the left of the decimal + * // and two digits to the right of the decimal. + * let n = nfp(negative, 4, 2); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Display the original and formatted numbers. + * text(`${positive} : ${p}`, 50, 33); + * text(`${negative} : ${n}`, 50, 67); + * + * describe( + * 'The text "123 : +123" and "-123 : -123.00" written on separate lines. The text is in black on a gray background.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create number variables. + * let numbers = [123, -4.56]; + * + * // Convert the numbers to formatted strings + * // with four digits to the left of the decimal + * // and one digit to the right of the decimal. + * let formatted = nfp(numbers, 4, 1); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(14); + * + * // Iterate over the array. + * for (let i = 0; i < formatted.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 33; + * + * // Display the original and formatted numbers. + * text(`${numbers[i]} : ${formatted[i]}`, 50, y); + * } + * + * describe( + * 'The text "123 : +0123.0" and "-4.56 : 00-4.6" written on separate lines. The text is in black on a gray background.' + * ); + * } + * + *
        + */ + /** + * @method nfp + * @param {Number[]} nums numbers to format. + * @param {Integer} [left] + * @param {Integer} [right] + * @return {String[]} formatted strings. + */ + + _main.default.prototype.nfp = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('nfp', args); + var nfRes = _main.default.prototype.nf.apply(this, args); + if (nfRes instanceof Array) { + return nfRes.map(addNfp); + } else { + return addNfp(nfRes); + } + }; + function addNfp(num) { + return parseFloat(num) > 0 ? '+'.concat(num.toString()) : num.toString(); + } /** + * Converts a positive `Number` into a `String` with an extra space in front. + * + * `nfs()` converts positive numbers such as 123.45 into strings formatted + * with an extra space in front, as in ' 123.45'. Doing so can be helpful for + * aligning positive and negative numbers. + * + * The first parameter, `num`, is the number to convert to a string. For + * example, calling `nfs(123.45)` returns the string `' 123.45'`. + * + * The second parameter, `left`, is optional. If a number is passed, as in + * `nfs(123.45, 4)`, it sets the minimum number of digits to include to the + * left of the decimal place. If `left` is larger than the number of digits in + * `num`, then unused digits will be set to 0. For example, calling + * `nfs(123.45, 4)` returns the string `' 0123.45'`. + * + * The third parameter, `right`, is also optional. If a number is passed, as + * in `nfs(123.45, 4, 1)`, it sets the minimum number of digits to include to + * the right of the decimal place. If `right` is smaller than the number of + * decimal places in `num`, then `num` will be rounded to the given number of + * decimal places. For example, calling `nfs(123.45, 4, 1)` returns the + * string `' 0123.5'`. If `right` is larger than the number of decimal places + * in `num`, then unused decimal places will be set to 0. For example, + * calling `nfs(123.45, 4, 3)` returns the string `' 0123.450'`. + * + * @method nfs + * @param {Number} num number to format. + * @param {Integer} [left] number of digits to include to the left of the + * decimal point. + * @param {Integer} [right] number of digits to include to the right of the + * decimal point. + * @return {String} formatted string. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create number variables. + * let positive = 123; + * let negative = -123; + * + * // Convert the positive number to a formatted string. + * let formatted = nfs(positive); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(16); + * + * // Display the negative number and the formatted positive number. + * text(negative, 50, 33); + * text(formatted, 50, 67); + * + * describe( + * 'The numbers -123 and 123 written on separate lines. The numbers align vertically. The text is in black on a gray background.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a number variable. + * let number = 123.45; + * + * // Convert the positive number to a formatted string. + * // Use four digits to the left of the decimal and + * // one digit to the right. + * let formatted = nfs(number, 4, 1); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(16); + * + * // Display a negative version of the number and + * // the formatted positive version. + * text('-0123.5', 50, 33); + * text(formatted, 50, 67); + * + * describe( + * 'The numbers "-0123.5" and "0123.5" written on separate lines. The numbers align vertically. The text is in black on a gray background.' + * ); + * } + * + *
        + */ + /** + * @method nfs + * @param {Array} nums numbers to format. + * @param {Integer} [left] + * @param {Integer} [right] + * @return {String[]} formatted strings. + */ + + _main.default.prototype.nfs = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('nfs', args); + var nfRes = _main.default.prototype.nf.apply(this, args); + if (nfRes instanceof Array) { + return nfRes.map(addNfs); + } else { + return addNfs(nfRes); + } + }; + function addNfs(num) { + return parseFloat(num) >= 0 ? ' '.concat(num.toString()) : num.toString(); + } /** + * Splits a `String` into pieces and returns an array containing the pieces. + * + * The first parameter, `value`, is the string to split. + * + * The second parameter, `delim`, is the character(s) that should be used to + * split the string. For example, calling + * `split('rock...paper...scissors', '...')` would return the array + * `['rock', 'paper', 'scissors']` because there are three periods `...` + * between each word. + * + * @method split + * @param {String} value the String to be split + * @param {String} delim the String used to separate the data + * @return {String[]} Array of Strings + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let string = 'rock...paper...scissors'; + * + * // Split the string at each ... + * let words = split(string, '...'); + * + * // Print the array to the console: + * // ["rock", "paper", "scissors"] + * print(words); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(16); + * + * // Iterate over the words array. + * for (let i = 0; i < words.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 25; + * + * // Display the word. + * text(words[i], 50, y); + * } + * + * describe( + * 'The words "rock", "paper", and "scissors" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + */ + + _main.default.prototype.split = function (str, delim) { + _main.default._validateParameters('split', arguments); + return str.split(delim); + }; + /** + * Splits a `String` into pieces and returns an array containing the pieces. + * + * `splitTokens()` is an enhanced version of + * split(). It can split a string when any characters + * from a list are detected. + * + * The first parameter, `value`, is the string to split. + * + * The second parameter, `delim`, is optional. It sets the character(s) that + * should be used to split the string. `delim` can be a single string, as in + * `splitTokens('rock...paper...scissors...shoot', '...')`, or an array of + * strings, as in + * `splitTokens('rock;paper,scissors...shoot, [';', ',', '...'])`. By default, + * if no `delim` characters are specified, then any whitespace character is + * used to split. Whitespace characters include tab (`\t`), line feed (`\n`), + * carriage return (`\r`), form feed (`\f`), and space. + * + * @method splitTokens + * @param {String} value string to split. + * @param {String} [delim] character(s) to use for splitting the string. + * @return {String[]} separated strings. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let string = 'rock paper scissors shoot'; + * + * // Split the string at each space. + * let words = splitTokens(string); + * + * // Print the array to the console. + * print(words); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Iterate over the words array. + * for (let i = 0; i < words.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 20; + * + * // Display the word. + * text(words[i], 50, y); + * } + * + * describe( + * 'The words "rock", "paper", "scissors", and "shoot" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let string = 'rock...paper...scissors...shoot'; + * + * // Split the string at each ... + * let words = splitTokens(string, '...'); + * + * // Print the array to the console. + * print(words); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Iterate over the words array. + * for (let i = 0; i < words.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 20; + * + * // Display the word. + * text(words[i], 50, y); + * } + * + * describe( + * 'The words "rock", "paper", "scissors", and "shoot" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let string = 'rock;paper,scissors...shoot'; + * + * // Split the string at each semicolon, comma, or ... + * let words = splitTokens(string, [';', ',', '...']); + * + * // Print the array to the console. + * print(words); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(12); + * + * // Iterate over the words array. + * for (let i = 0; i < words.length; i += 1) { + * + * // Calculate the y-coordinate. + * let y = (i + 1) * 20; + * + * // Display the word. + * text(words[i], 50, y); + * } + * + * describe( + * 'The words "rock", "paper", "scissors", and "shoot" written on separate lines. The text is black on a gray background.' + * ); + * } + * + *
        + */ + _main.default.prototype.splitTokens = function (value, delims) { + _main.default._validateParameters('splitTokens', arguments); + var d; + if (typeof delims !== 'undefined') { + var str = delims; + var sqc = /\]/g.exec(str); + var sqo = /\[/g.exec(str); + if (sqo && sqc) { + str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); + sqo = /\[/g.exec(str); + str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); + d = new RegExp('[\\['.concat(str, '\\]]'), 'g'); + } else if (sqc) { + str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); + d = new RegExp('['.concat(str, '\\]]'), 'g'); + } else if (sqo) { + str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); + d = new RegExp('['.concat(str, '\\[]'), 'g'); + } else { + d = new RegExp('['.concat(str, ']'), 'g'); + } + } else { + d = /\s/g; + } + return value.split(d).filter(function (n) { + return n; + }); + }; + /** + * Removes whitespace from the start and end of a `String` without changing the middle. + * + * `trim()` trims + * whitespace characters + * such as spaces, carriage returns, tabs, Unicode "nbsp" character. + * + * The parameter, `str`, is the string to trim. If a single string is passed, + * as in `trim(' pad ')`, a single string is returned. If an array of + * strings is passed, as in `trim([' pad ', '\n space \n'])`, an array of + * strings is returned. + * + * @method trim + * @param {String} str string to trim. + * @return {String} trimmed string. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create a string variable. + * let string = ' p5*js '; + * + * // Trim the whitespace. + * let trimmed = trim(string); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textSize(16); + * + * // Display the text. + * text(`Hello, ${trimmed}!`, 50, 50); + * + * describe('The text "Hello, p5*js!" written in black on a gray background.'); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Create an array of strings. + * let strings = [' wide ', '\n open ', '\n spaces ']; + * + * // Trim the whitespace. + * let trimmed = trim(strings); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont('Courier New'); + * textSize(10); + * + * // Display the text. + * text(`${trimmed[0]} ${trimmed[1]} ${trimmed[2]}`, 50, 50); + * + * describe('The text "wide open spaces" written in black on a gray background.'); + * } + * + *
        + */ + /** + * @method trim + * @param {String[]} strs strings to trim. + * @return {String[]} trimmed strings. + */ + _main.default.prototype.trim = function (str) { + _main.default._validateParameters('trim', arguments); + if (str instanceof Array) { + return str.map(this.trim); + } else { + return str.trim(); + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/friendly_errors/fes_core': 294, + '../core/friendly_errors/file_errors': 295, + '../core/friendly_errors/validate_params': 298, + '../core/main': 303, + 'core-js/modules/es.array.filter': 174, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.number.to-fixed': 198, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.constructor': 209, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.match': 216, + 'core-js/modules/es.string.pad-start': 217, + 'core-js/modules/es.string.replace': 219, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.string.trim': 224, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 345: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module IO + * @submodule Time & Date + * @for p5 + * @requires core + */ + /** + * Returns the current day as a number from 1–31. + * + * @method day + * @return {Integer} current day between 1 and 31. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the current day. + * let d = day(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(12); + * textFont('Courier New'); + * + * // Display the day. + * text(`Current day: ${d}`, 20, 50, 60); + * + * describe(`The text 'Current day: ${d}' written in black on a gray background.`); + * } + * + *
        + */ + + _main.default.prototype.day = function () { + return new Date().getDate(); + }; + /** + * Returns the current hour as a number from 0–23. + * + * @method hour + * @return {Integer} current hour between 0 and 23. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the current hour. + * let h = hour(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(12); + * textFont('Courier New'); + * + * // Display the hour. + * text(`Current hour: ${h}`, 20, 50, 60); + * + * describe(`The text 'Current hour: ${h}' written in black on a gray background.`); + * } + * + *
        + */ + _main.default.prototype.hour = function () { + return new Date().getHours(); + }; + /** + * Returns the current minute as a number from 0–59. + * + * @method minute + * @return {Integer} current minute between 0 and 59. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the current minute. + * let m = minute(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(12); + * textFont('Courier New'); + * + * // Display the minute. + * text(`Current minute: ${m}`, 10, 50, 80); + * + * describe(`The text 'Current minute: ${m}' written in black on a gray background.`); + * } + * + *
        + */ + _main.default.prototype.minute = function () { + return new Date().getMinutes(); + }; + /** + * Returns the number of milliseconds since a sketch started running. + * + * `millis()` keeps track of how long a sketch has been running in + * milliseconds (thousandths of a second). This information is often + * helpful for timing events and animations. + * + * If a sketch has a + * setup() function, then `millis()` begins tracking + * time before the code in setup() runs. If a + * sketch includes a preload() function, then + * `millis()` begins tracking time as soon as the code in + * preload() starts running. + * + * @method millis + * @return {Number} number of milliseconds since starting the sketch. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the number of milliseconds the sketch has run. + * let ms = millis(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(10); + * textFont('Courier New'); + * + * // Display how long it took setup() to be called. + * text(`Startup time: ${round(ms, 2)} ms`, 5, 50, 90); + * + * describe( + * `The text 'Startup time: ${round(ms, 2)} ms' written in black on a gray background.` + * ); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('The text "Running time: S sec" written in black on a gray background. The number S increases as the sketch runs.'); + * } + * + * function draw() { + * background(200); + * + * // Get the number of seconds the sketch has run. + * let s = millis() / 1000; + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(10); + * textFont('Courier New'); + * + * // Display how long the sketch has run. + * text(`Running time: ${nf(s, 1, 1)} sec`, 5, 50, 90); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * describe('A white circle oscillates left and right on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Get the number of seconds the sketch has run. + * let s = millis() / 1000; + * + * // Calculate an x-coordinate. + * let x = 30 * sin(s) + 50; + * + * // Draw the circle. + * circle(x, 50, 30); + * } + * + *
        + * + *
        + * + * // Load the GeoJSON. + * function preload() { + * loadJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson'); + * } + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the number of milliseconds the sketch has run. + * let ms = millis(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textFont('Courier New'); + * textSize(11); + * + * // Display how long it took to load the data. + * text(`It took ${round(ms, 2)} ms to load the data`, 5, 50, 100); + * + * describe( + * `The text "It took ${round(ms, 2)} ms to load the data" written in black on a gray background.` + * ); + * } + * + *
        + */ + _main.default.prototype.millis = function () { + if (this._millisStart === - 1) { + // Sketch has not started + return 0; + } else { + return window.performance.now() - this._millisStart; + } + }; + /** + * Returns the current month as a number from 1–12. + * + * @method month + * @return {Integer} current month between 1 and 12. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the current month. + * let m = month(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(12); + * textFont('Courier New'); + * + * // Display the month. + * text(`Current month: ${m}`, 10, 50, 80); + * + * describe(`The text 'Current month: ${m}' written in black on a gray background.`); + * } + * + *
        + */ + _main.default.prototype.month = function () { + //January is 0! + return new Date().getMonth() + 1; + }; + /** + * Returns the current second as a number from 0–59. + * + * @method second + * @return {Integer} current second between 0 and 59. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the current second. + * let s = second(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(12); + * textFont('Courier New'); + * + * // Display the second. + * text(`Current second: ${s}`, 10, 50, 80); + * + * describe(`The text 'Current second: ${s}' written in black on a gray background.`); + * } + * + *
        + */ + _main.default.prototype.second = function () { + return new Date().getSeconds(); + }; + /** + * Returns the current year as a number such as 1999. + * + * @method year + * @return {Integer} current year. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100); + * + * background(200); + * + * // Get the current year. + * let y = year(); + * + * // Style the text. + * textAlign(LEFT, CENTER); + * textSize(12); + * textFont('Courier New'); + * + * // Display the year. + * text(`Current year: ${y}`, 10, 50, 80); + * + * describe(`The text 'Current year: ${y}' written in black on a gray background.`); + * } + * + *
        + */ + _main.default.prototype.year = function () { + return new Date().getFullYear(); + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303 + } + ], + 346: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.number.to-fixed'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + _dereq_('./p5.Geometry'); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module Shape + * @submodule 3D Primitives + * @for p5 + * @requires core + * @requires p5.Geometry + */ + /** + * Begins adding shapes to a new + * p5.Geometry object. + * + * The `beginGeometry()` and endGeometry() + * functions help with creating complex 3D shapes from simpler ones such as + * sphere(). `beginGeometry()` begins adding shapes + * to a custom p5.Geometry object and + * endGeometry() stops adding them. + * + * `beginGeometry()` and endGeometry() can help + * to make sketches more performant. For example, if a complex 3D shape + * doesn’t change while a sketch runs, then it can be created with + * `beginGeometry()` and endGeometry(). + * Creating a p5.Geometry object once and then + * drawing it will run faster than repeatedly drawing the individual pieces. + * + * See buildGeometry() for another way to + * build 3D shapes. + * + * Note: `beginGeometry()` can only be used in WebGL mode. + * + * @method beginGeometry + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Start building the p5.Geometry object. + * beginGeometry(); + * + * // Add a cone. + * cone(); + * + * // Stop building the p5.Geometry object. + * shape = endGeometry(); + * + * describe('A white cone drawn on a gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the p5.Geometry object. + * noStroke(); + * + * // Draw the p5.Geometry object. + * model(shape); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the p5.Geometry object. + * createArrow(); + * + * describe('A white arrow drawn on a gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the p5.Geometry object. + * noStroke(); + * + * // Draw the p5.Geometry object. + * model(shape); + * } + * + * function createArrow() { + * // Start building the p5.Geometry object. + * beginGeometry(); + * + * // Add shapes. + * push(); + * rotateX(PI); + * cone(10); + * translate(0, -10, 0); + * cylinder(3, 20); + * pop(); + * + * // Stop building the p5.Geometry object. + * shape = endGeometry(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let blueArrow; + * let redArrow; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the arrows. + * redArrow = createArrow('red'); + * blueArrow = createArrow('blue'); + * + * describe('A red arrow and a blue arrow drawn on a gray background. The blue arrow rotates slowly.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the arrows. + * noStroke(); + * + * // Draw the red arrow. + * model(redArrow); + * + * // Translate and rotate the coordinate system. + * translate(30, 0, 0); + * rotateZ(frameCount * 0.01); + * + * // Draw the blue arrow. + * model(blueArrow); + * } + * + * function createArrow(fillColor) { + * // Start building the p5.Geometry object. + * beginGeometry(); + * + * fill(fillColor); + * + * // Add shapes to the p5.Geometry object. + * push(); + * rotateX(PI); + * cone(10); + * translate(0, -10, 0); + * cylinder(3, 20); + * pop(); + * + * // Stop building the p5.Geometry object. + * let shape = endGeometry(); + * + * return shape; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let button; + * let particles; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a button to reset the particle system. + * button = createButton('Reset'); + * + * // Call resetModel() when the user presses the button. + * button.mousePressed(resetModel); + * + * // Add the original set of particles. + * resetModel(); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the particles. + * noStroke(); + * + * // Draw the particles. + * model(particles); + * } + * + * function resetModel() { + * // If the p5.Geometry object has already been created, + * // free those resources. + * if (particles) { + * freeGeometry(particles); + * } + * + * // Create a new p5.Geometry object with random spheres. + * particles = createParticles(); + * } + * + * function createParticles() { + * // Start building the p5.Geometry object. + * beginGeometry(); + * + * // Add shapes. + * for (let i = 0; i < 60; i += 1) { + * // Calculate random coordinates. + * let x = randomGaussian(0, 20); + * let y = randomGaussian(0, 20); + * let z = randomGaussian(0, 20); + * + * push(); + * // Translate to the particle's coordinates. + * translate(x, y, z); + * // Draw the particle. + * sphere(5); + * pop(); + * } + * + * // Stop building the p5.Geometry object. + * let shape = endGeometry(); + * + * return shape; + * } + * + *
        + */ + + _main.default.prototype.beginGeometry = function () { + return this._renderer.beginGeometry(); + }; + /** + * Stops adding shapes to a new + * p5.Geometry object and returns the object. + * + * The `beginGeometry()` and endGeometry() + * functions help with creating complex 3D shapes from simpler ones such as + * sphere(). `beginGeometry()` begins adding shapes + * to a custom p5.Geometry object and + * endGeometry() stops adding them. + * + * `beginGeometry()` and endGeometry() can help + * to make sketches more performant. For example, if a complex 3D shape + * doesn’t change while a sketch runs, then it can be created with + * `beginGeometry()` and endGeometry(). + * Creating a p5.Geometry object once and then + * drawing it will run faster than repeatedly drawing the individual pieces. + * + * See buildGeometry() for another way to + * build 3D shapes. + * + * Note: `endGeometry()` can only be used in WebGL mode. + * + * @method endGeometry + * @returns {p5.Geometry} new 3D shape. + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Start building the p5.Geometry object. + * beginGeometry(); + * + * // Add a cone. + * cone(); + * + * // Stop building the p5.Geometry object. + * shape = endGeometry(); + * + * describe('A white cone drawn on a gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the p5.Geometry object. + * noStroke(); + * + * // Draw the p5.Geometry object. + * model(shape); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the p5.Geometry object. + * createArrow(); + * + * describe('A white arrow drawn on a gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the p5.Geometry object. + * noStroke(); + * + * // Draw the p5.Geometry object. + * model(shape); + * } + * + * function createArrow() { + * // Start building the p5.Geometry object. + * beginGeometry(); + * + * // Add shapes. + * push(); + * rotateX(PI); + * cone(10); + * translate(0, -10, 0); + * cylinder(3, 20); + * pop(); + * + * // Stop building the p5.Geometry object. + * shape = endGeometry(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let blueArrow; + * let redArrow; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the arrows. + * redArrow = createArrow('red'); + * blueArrow = createArrow('blue'); + * + * describe('A red arrow and a blue arrow drawn on a gray background. The blue arrow rotates slowly.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the arrows. + * noStroke(); + * + * // Draw the red arrow. + * model(redArrow); + * + * // Translate and rotate the coordinate system. + * translate(30, 0, 0); + * rotateZ(frameCount * 0.01); + * + * // Draw the blue arrow. + * model(blueArrow); + * } + * + * function createArrow(fillColor) { + * // Start building the p5.Geometry object. + * beginGeometry(); + * + * fill(fillColor); + * + * // Add shapes to the p5.Geometry object. + * push(); + * rotateX(PI); + * cone(10); + * translate(0, -10, 0); + * cylinder(3, 20); + * pop(); + * + * // Stop building the p5.Geometry object. + * let shape = endGeometry(); + * + * return shape; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let button; + * let particles; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a button to reset the particle system. + * button = createButton('Reset'); + * + * // Call resetModel() when the user presses the button. + * button.mousePressed(resetModel); + * + * // Add the original set of particles. + * resetModel(); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the particles. + * noStroke(); + * + * // Draw the particles. + * model(particles); + * } + * + * function resetModel() { + * // If the p5.Geometry object has already been created, + * // free those resources. + * if (particles) { + * freeGeometry(particles); + * } + * + * // Create a new p5.Geometry object with random spheres. + * particles = createParticles(); + * } + * + * function createParticles() { + * // Start building the p5.Geometry object. + * beginGeometry(); + * + * // Add shapes. + * for (let i = 0; i < 60; i += 1) { + * // Calculate random coordinates. + * let x = randomGaussian(0, 20); + * let y = randomGaussian(0, 20); + * let z = randomGaussian(0, 20); + * + * push(); + * // Translate to the particle's coordinates. + * translate(x, y, z); + * // Draw the particle. + * sphere(5); + * pop(); + * } + * + * // Stop building the p5.Geometry object. + * let shape = endGeometry(); + * + * return shape; + * } + * + *
        + */ + _main.default.prototype.endGeometry = function () { + return this._renderer.endGeometry(); + }; + /** + * Creates a custom p5.Geometry object from + * simpler 3D shapes. + * + * `buildGeometry()` helps with creating complex 3D shapes from simpler ones + * such as sphere(). It can help to make sketches + * more performant. For example, if a complex 3D shape doesn’t change while a + * sketch runs, then it can be created with `buildGeometry()`. Creating a + * p5.Geometry object once and then drawing it + * will run faster than repeatedly drawing the individual pieces. + * + * The parameter, `callback`, is a function with the drawing instructions for + * the new p5.Geometry object. It will be called + * once to create the new 3D shape. + * + * See beginGeometry() and + * endGeometry() for another way to build 3D + * shapes. + * + * Note: `buildGeometry()` can only be used in WebGL mode. + * + * @method buildGeometry + * @param {Function} callback function that draws the shape. + * @returns {p5.Geometry} new 3D shape. + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the p5.Geometry object. + * shape = buildGeometry(createShape); + * + * describe('A white cone drawn on a gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the p5.Geometry object. + * noStroke(); + * + * // Draw the p5.Geometry object. + * model(shape); + * } + * + * // Create p5.Geometry object from a single cone. + * function createShape() { + * cone(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the arrow. + * shape = buildGeometry(createArrow); + * + * describe('A white arrow drawn on a gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the arrow. + * noStroke(); + * + * // Draw the arrow. + * model(shape); + * } + * + * function createArrow() { + * // Add shapes to the p5.Geometry object. + * push(); + * rotateX(PI); + * cone(10); + * translate(0, -10, 0); + * cylinder(3, 20); + * pop(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the p5.Geometry object. + * shape = buildGeometry(createArrow); + * + * describe('Two white arrows drawn on a gray background. The arrow on the right rotates slowly.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the arrows. + * noStroke(); + * + * // Draw the p5.Geometry object. + * model(shape); + * + * // Translate and rotate the coordinate system. + * translate(30, 0, 0); + * rotateZ(frameCount * 0.01); + * + * // Draw the p5.Geometry object again. + * model(shape); + * } + * + * function createArrow() { + * // Add shapes to the p5.Geometry object. + * push(); + * rotateX(PI); + * cone(10); + * translate(0, -10, 0); + * cylinder(3, 20); + * pop(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let button; + * let particles; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a button to reset the particle system. + * button = createButton('Reset'); + * + * // Call resetModel() when the user presses the button. + * button.mousePressed(resetModel); + * + * // Add the original set of particles. + * resetModel(); + * + * describe('A set of white spheres on a gray background. The spheres are positioned randomly. Their positions reset when the user presses the Reset button.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the particles. + * noStroke(); + * + * // Draw the particles. + * model(particles); + * } + * + * function resetModel() { + * // If the p5.Geometry object has already been created, + * // free those resources. + * if (particles) { + * freeGeometry(particles); + * } + * + * // Create a new p5.Geometry object with random spheres. + * particles = buildGeometry(createParticles); + * } + * + * function createParticles() { + * for (let i = 0; i < 60; i += 1) { + * // Calculate random coordinates. + * let x = randomGaussian(0, 20); + * let y = randomGaussian(0, 20); + * let z = randomGaussian(0, 20); + * + * push(); + * // Translate to the particle's coordinates. + * translate(x, y, z); + * // Draw the particle. + * sphere(5); + * pop(); + * } + * } + * + *
        + */ + _main.default.prototype.buildGeometry = function (callback) { + return this._renderer.buildGeometry(callback); + }; + /** + * Clears a p5.Geometry object from the graphics + * processing unit (GPU) memory. + * + * p5.Geometry objects can contain lots of data + * about their vertices, surface normals, colors, and so on. Complex 3D shapes + * can use lots of memory which is a limited resource in many GPUs. Calling + * `freeGeometry()` can improve performance by freeing a + * p5.Geometry object’s resources from GPU memory. + * `freeGeometry()` works with p5.Geometry objects + * created with beginGeometry() and + * endGeometry(), + * buildGeometry(), and + * loadModel(). + * + * The parameter, `geometry`, is the p5.Geometry + * object to be freed. + * + * Note: A p5.Geometry object can still be drawn + * after its resources are cleared from GPU memory. It may take longer to draw + * the first time it’s redrawn. + * + * Note: `freeGeometry()` can only be used in WebGL mode. + * + * @method freeGeometry + * @param {p5.Geometry} geometry 3D shape whose resources should be freed. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create a p5.Geometry object. + * beginGeometry(); + * cone(); + * let shape = endGeometry(); + * + * // Draw the shape. + * model(shape); + * + * // Free the shape's resources. + * freeGeometry(shape); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let button; + * let particles; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a button to reset the particle system. + * button = createButton('Reset'); + * + * // Call resetModel() when the user presses the button. + * button.mousePressed(resetModel); + * + * // Add the original set of particles. + * resetModel(); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the particles. + * noStroke(); + * + * // Draw the particles. + * model(particles); + * } + * + * function resetModel() { + * // If the p5.Geometry object has already been created, + * // free those resources. + * if (particles) { + * freeGeometry(particles); + * } + * + * // Create a new p5.Geometry object with random spheres. + * particles = buildGeometry(createParticles); + * } + * + * function createParticles() { + * for (let i = 0; i < 60; i += 1) { + * // Calculate random coordinates. + * let x = randomGaussian(0, 20); + * let y = randomGaussian(0, 20); + * let z = randomGaussian(0, 20); + * + * push(); + * // Translate to the particle's coordinates. + * translate(x, y, z); + * // Draw the particle. + * sphere(5); + * pop(); + * } + * } + * + *
        + */ + _main.default.prototype.freeGeometry = function (geometry) { + this._renderer._freeBuffers(geometry.gid); + }; + /** + * Draws a plane. + * + * A plane is a four-sided, flat shape with every angle measuring 90˚. It’s + * similar to a rectangle and offers advanced drawing features in WebGL mode. + * + * The first parameter, `width`, is optional. If a `Number` is passed, as in + * `plane(20)`, it sets the plane’s width and height. By default, `width` is + * 50. + * + * The second parameter, `height`, is also optional. If a `Number` is passed, + * as in `plane(20, 30)`, it sets the plane’s height. By default, `height` is + * set to the plane’s `width`. + * + * The third parameter, `detailX`, is also optional. If a `Number` is passed, + * as in `plane(20, 30, 5)` it sets the number of triangle subdivisions to use + * along the x-axis. All 3D shapes are made by connecting triangles to form + * their surfaces. By default, `detailX` is 1. + * + * The fourth parameter, `detailY`, is also optional. If a `Number` is passed, + * as in `plane(20, 30, 5, 7)` it sets the number of triangle subdivisions to + * use along the y-axis. All 3D shapes are made by connecting triangles to + * form their surfaces. By default, `detailY` is 1. + * + * Note: `plane()` can only be used in WebGL mode. + * + * @method plane + * @param {Number} [width] width of the plane. + * @param {Number} [height] height of the plane. + * @param {Integer} [detailX] number of triangle subdivisions along the x-axis. + * @param {Integer} [detailY] number of triangle subdivisions along the y-axis. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white plane on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the plane. + * plane(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white plane on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the plane. + * // Set its width and height to 30. + * plane(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white plane on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the plane. + * // Set its width to 30 and height to 50. + * plane(30, 50); + * } + * + *
        + */ + _main.default.prototype.plane = function () { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : width; + var detailX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var detailY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + this._assert3d('plane'); + _main.default._validateParameters('plane', arguments); + var gId = 'plane|'.concat(detailX, '|').concat(detailY); + if (!this._renderer.geometryInHash(gId)) { + var _plane = function _plane() { + var u, + v, + p; + for (var i = 0; i <= this.detailY; i++) { + v = i / this.detailY; + for (var j = 0; j <= this.detailX; j++) { + u = j / this.detailX; + p = new _main.default.Vector(u - 0.5, v - 0.5, 0); + this.vertices.push(p); + this.uvs.push(u, v); + } + } + }; + var planeGeom = new _main.default.Geometry(detailX, detailY, _plane); + planeGeom.computeFaces().computeNormals(); + if (detailX <= 1 && detailY <= 1) { + planeGeom._makeTriangleEdges()._edgesToVertices(); + } else if (this._renderer._doStroke) { + console.log('Cannot draw stroke on plane objects with more' + ' than 1 detailX or 1 detailY'); + } + this._renderer.createBuffers(gId, planeGeom); + } + this._renderer.drawBuffersScaled(gId, width, height, 1); + return this; + }; + /** + * Draws a box (rectangular prism). + * + * A box is a 3D shape with six faces. Each face makes a 90˚ with four + * neighboring faces. + * + * The first parameter, `width`, is optional. If a `Number` is passed, as in + * `box(20)`, it sets the box’s width and height. By default, `width` is 50. + * + * The second parameter, `height`, is also optional. If a `Number` is passed, + * as in `box(20, 30)`, it sets the box’s height. By default, `height` is set + * to the box’s `width`. + * + * The third parameter, `depth`, is also optional. If a `Number` is passed, as + * in `box(20, 30, 40)`, it sets the box’s depth. By default, `depth` is set + * to the box’s `height`. + * + * The fourth parameter, `detailX`, is also optional. If a `Number` is passed, + * as in `box(20, 30, 40, 5)`, it sets the number of triangle subdivisions to + * use along the x-axis. All 3D shapes are made by connecting triangles to + * form their surfaces. By default, `detailX` is 1. + * + * The fifth parameter, `detailY`, is also optional. If a number is passed, as + * in `box(20, 30, 40, 5, 7)`, it sets the number of triangle subdivisions to + * use along the y-axis. All 3D shapes are made by connecting triangles to + * form their surfaces. By default, `detailY` is 1. + * + * Note: `box()` can only be used in WebGL mode. + * + * @method box + * @param {Number} [width] width of the box. + * @param {Number} [height] height of the box. + * @param {Number} [depth] depth of the box. + * @param {Integer} [detailX] number of triangle subdivisions along the x-axis. + * @param {Integer} [detailY] number of triangle subdivisions along the y-axis. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white box on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white box on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the box. + * // Set its width and height to 30. + * box(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white box on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the box. + * // Set its width to 30 and height to 50. + * box(30, 50); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white box on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the box. + * // Set its width to 30, height to 50, and depth to 10. + * box(30, 50, 10); + * } + * + *
        + */ + _main.default.prototype.box = function (width, height, depth, detailX, detailY) { + this._assert3d('box'); + _main.default._validateParameters('box', arguments); + if (typeof width === 'undefined') { + width = 50; + } + if (typeof height === 'undefined') { + height = width; + } + if (typeof depth === 'undefined') { + depth = height; + } + var perPixelLighting = this._renderer.attributes && this._renderer.attributes.perPixelLighting; + if (typeof detailX === 'undefined') { + detailX = perPixelLighting ? 1 : 4; + } + if (typeof detailY === 'undefined') { + detailY = perPixelLighting ? 1 : 4; + } + var gId = 'box|'.concat(detailX, '|').concat(detailY); + if (!this._renderer.geometryInHash(gId)) { + var _box = function _box() { + var _this = this; + var cubeIndices = [ + [0, + 4, + 2, + 6], + // -1, 0, 0],// -x + [ + 1, + 3, + 5, + 7 + ], + // +1, 0, 0],// +x + [ + 0, + 1, + 4, + 5 + ], + // 0, -1, 0],// -y + [ + 2, + 6, + 3, + 7 + ], + // 0, +1, 0],// +y + [ + 0, + 2, + 1, + 3 + ], + // 0, 0, -1],// -z + [ + 4, + 5, + 6, + 7 + ] // 0, 0, +1] // +z + ]; + //using custom edges + //to avoid diagonal stroke lines across face of box + this.edges = [ + [0, + 1], + [ + 1, + 3 + ], + [ + 3, + 2 + ], + [ + 6, + 7 + ], + [ + 8, + 9 + ], + [ + 9, + 11 + ], + [ + 14, + 15 + ], + [ + 16, + 17 + ], + [ + 17, + 19 + ], + [ + 18, + 19 + ], + [ + 20, + 21 + ], + [ + 22, + 23 + ] + ]; + cubeIndices.forEach(function (cubeIndex, i) { + var v = i * 4; + for (var j = 0; j < 4; j++) { + var d = cubeIndex[j]; + //inspired by lightgl: + //https://github.com/evanw/lightgl.js + //octants:https://en.wikipedia.org/wiki/Octant_(solid_geometry) + var octant = new _main.default.Vector(((d & 1) * 2 - 1) / 2, ((d & 2) - 1) / 2, ((d & 4) / 2 - 1) / 2); + _this.vertices.push(octant); + _this.uvs.push(j & 1, (j & 2) / 2); + } + _this.faces.push([v, + v + 1, + v + 2]); + _this.faces.push([v + 2, + v + 1, + v + 3]); + }); + }; + var boxGeom = new _main.default.Geometry(detailX, detailY, _box); + boxGeom.computeNormals(); + if (detailX <= 4 && detailY <= 4) { + boxGeom._edgesToVertices(); + } else if (this._renderer._doStroke) { + console.log('Cannot draw stroke on box objects with more' + ' than 4 detailX or 4 detailY'); + } //initialize our geometry buffer with + //the key val pair: + //geometry Id, Geom object + + this._renderer.createBuffers(gId, boxGeom); + } + this._renderer.drawBuffersScaled(gId, width, height, depth); + return this; + }; + /** + * Draws a sphere. + * + * A sphere is a 3D shape with triangular faces that connect to form a round + * surface. Spheres with few faces look like crystals. Spheres with many faces + * have smooth surfaces and look like balls. + * + * The first parameter, `radius`, is optional. If a `Number` is passed, as in + * `sphere(20)`, it sets the radius of the sphere. By default, `radius` is 50. + * + * The second parameter, `detailX`, is also optional. If a `Number` is passed, + * as in `sphere(20, 5)`, it sets the number of triangle subdivisions to use + * along the x-axis. All 3D shapes are made by connecting triangles to form + * their surfaces. By default, `detailX` is 24. + * + * The third parameter, `detailY`, is also optional. If a `Number` is passed, + * as in `sphere(20, 5, 2)`, it sets the number of triangle subdivisions to + * use along the y-axis. All 3D shapes are made by connecting triangles to + * form their surfaces. By default, `detailY` is 16. + * + * Note: `sphere()` can only be used in WebGL mode. + * + * @method sphere + * @param {Number} [radius] radius of the sphere. Defaults to 50. + * @param {Integer} [detailX] number of triangle subdivisions along the x-axis. Defaults to 24. + * @param {Integer} [detailY] number of triangle subdivisions along the y-axis. Defaults to 16. + * + * @chainable + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white sphere on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the sphere. + * sphere(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white sphere on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the sphere. + * // Set its radius to 30. + * sphere(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white sphere on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the sphere. + * // Set its radius to 30. + * // Set its detailX to 6. + * sphere(30, 6); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white sphere on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the sphere. + * // Set its radius to 30. + * // Set its detailX to 24. + * // Set its detailY to 4. + * sphere(30, 24, 4); + * } + * + *
        + */ + _main.default.prototype.sphere = function () { + var radius = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var detailX = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 24; + var detailY = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16; + this._assert3d('sphere'); + _main.default._validateParameters('sphere', arguments); + this.ellipsoid(radius, radius, radius, detailX, detailY); + return this; + }; + /** + * @private + * Helper function for creating both cones and cylinders + * Will only generate well-defined geometry when bottomRadius, height > 0 + * and topRadius >= 0 + * If topRadius == 0, topCap should be false + */ + var _truncatedCone = function _truncatedCone(bottomRadius, topRadius, height, detailX, detailY, bottomCap, topCap) { + bottomRadius = bottomRadius <= 0 ? 1 : bottomRadius; + topRadius = topRadius < 0 ? 0 : topRadius; + height = height <= 0 ? bottomRadius : height; + detailX = detailX < 3 ? 3 : detailX; + detailY = detailY < 1 ? 1 : detailY; + bottomCap = bottomCap === undefined ? true : bottomCap; + topCap = topCap === undefined ? topRadius !== 0 : topCap; + var start = bottomCap ? - 2 : 0; + var end = detailY + (topCap ? 2 : 0); + //ensure constant slant for interior vertex normals + var slant = Math.atan2(bottomRadius - topRadius, height); + var sinSlant = Math.sin(slant); + var cosSlant = Math.cos(slant); + var yy, + ii, + jj; + for (yy = start; yy <= end; ++yy) { + var v = yy / detailY; + var y = height * v; + var ringRadius = void 0; + if (yy < 0) { + //for the bottomCap edge + y = 0; + v = 0; + ringRadius = bottomRadius; + } else if (yy > detailY) { + //for the topCap edge + y = height; + v = 1; + ringRadius = topRadius; + } else { + //for the middle + ringRadius = bottomRadius + (topRadius - bottomRadius) * v; + } + if (yy === - 2 || yy === detailY + 2) { + //center of bottom or top caps + ringRadius = 0; + } + y -= height / 2; //shift coordiate origin to the center of object + for (ii = 0; ii < detailX; ++ii) { + var u = ii / (detailX - 1); + var ur = 2 * Math.PI * u; + var sur = Math.sin(ur); + var cur = Math.cos(ur); + //VERTICES + this.vertices.push(new _main.default.Vector(sur * ringRadius, y, cur * ringRadius)); + //VERTEX NORMALS + var vertexNormal = void 0; + if (yy < 0) { + vertexNormal = new _main.default.Vector(0, - 1, 0); + } else if (yy > detailY && topRadius) { + vertexNormal = new _main.default.Vector(0, 1, 0); + } else { + vertexNormal = new _main.default.Vector(sur * cosSlant, sinSlant, cur * cosSlant); + } + this.vertexNormals.push(vertexNormal); + //UVs + this.uvs.push(u, v); + } + } + var startIndex = 0; + if (bottomCap) { + for (jj = 0; jj < detailX; ++jj) { + var nextjj = (jj + 1) % detailX; + this.faces.push([startIndex + jj, + startIndex + detailX + nextjj, + startIndex + detailX + jj]); + } + startIndex += detailX * 2; + } + for (yy = 0; yy < detailY; ++yy) { + for (ii = 0; ii < detailX; ++ii) { + var nextii = (ii + 1) % detailX; + this.faces.push([startIndex + ii, + startIndex + nextii, + startIndex + detailX + nextii]); + this.faces.push([startIndex + ii, + startIndex + detailX + nextii, + startIndex + detailX + ii]); + } + startIndex += detailX; + } + if (topCap) { + startIndex += detailX; + for (ii = 0; ii < detailX; ++ii) { + this.faces.push([startIndex + ii, + startIndex + (ii + 1) % detailX, + startIndex + detailX]); + } + } + }; + /** + * Draws a cylinder. + * + * A cylinder is a 3D shape with triangular faces that connect a flat bottom + * to a flat top. Cylinders with few faces look like boxes. Cylinders with + * many faces have smooth surfaces. + * + * The first parameter, `radius`, is optional. If a `Number` is passed, as in + * `cylinder(20)`, it sets the radius of the cylinder’s base. By default, + * `radius` is 50. + * + * The second parameter, `height`, is also optional. If a `Number` is passed, + * as in `cylinder(20, 30)`, it sets the cylinder’s height. By default, + * `height` is set to the cylinder’s `radius`. + * + * The third parameter, `detailX`, is also optional. If a `Number` is passed, + * as in `cylinder(20, 30, 5)`, it sets the number of edges used to form the + * cylinder's top and bottom. Using more edges makes the top and bottom look + * more like circles. By default, `detailX` is 24. + * + * The fourth parameter, `detailY`, is also optional. If a `Number` is passed, + * as in `cylinder(20, 30, 5, 2)`, it sets the number of triangle subdivisions + * to use along the y-axis, between cylinder's the top and bottom. All 3D + * shapes are made by connecting triangles to form their surfaces. By default, + * `detailY` is 1. + * + * The fifth parameter, `bottomCap`, is also optional. If a `false` is passed, + * as in `cylinder(20, 30, 5, 2, false)` the cylinder’s bottom won’t be drawn. + * By default, `bottomCap` is `true`. + * + * The sixth parameter, `topCap`, is also optional. If a `false` is passed, as + * in `cylinder(20, 30, 5, 2, false, false)` the cylinder’s top won’t be + * drawn. By default, `topCap` is `true`. + * + * Note: `cylinder()` can only be used in WebGL mode. + * + * @method cylinder + * @param {Number} [radius] radius of the cylinder. Defaults to 50. + * @param {Number} [height] height of the cylinder. Defaults to the value of `radius`. + * @param {Integer} [detailX] number of edges along the top and bottom. Defaults to 24. + * @param {Integer} [detailY] number of triangle subdivisions along the y-axis. Defaults to 1. + * @param {Boolean} [bottomCap] whether to draw the cylinder's bottom. Defaults to `true`. + * @param {Boolean} [topCap] whether to draw the cylinder's top. Defaults to `true`. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cylinder on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cylinder. + * cylinder(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cylinder on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cylinder. + * // Set its radius and height to 30. + * cylinder(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cylinder on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cylinder. + * // Set its radius to 30 and height to 50. + * cylinder(30, 50); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white box on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cylinder. + * // Set its radius to 30 and height to 50. + * // Set its detailX to 5. + * cylinder(30, 50, 5); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cylinder on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cylinder. + * // Set its radius to 30 and height to 50. + * // Set its detailX to 24 and detailY to 2. + * cylinder(30, 50, 24, 2); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cylinder on a gray background. Its top is missing.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cylinder. + * // Set its radius to 30 and height to 50. + * // Set its detailX to 24 and detailY to 1. + * // Don't draw its bottom. + * cylinder(30, 50, 24, 1, false); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cylinder on a gray background. Its top and bottom are missing.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cylinder. + * // Set its radius to 30 and height to 50. + * // Set its detailX to 24 and detailY to 1. + * // Don't draw its bottom or top. + * cylinder(30, 50, 24, 1, false, false); + * } + * + *
        + */ + _main.default.prototype.cylinder = function () { + var radius = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : radius; + var detailX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 24; + var detailY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var bottomCap = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; + var topCap = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true; + this._assert3d('cylinder'); + _main.default._validateParameters('cylinder', arguments); + var gId = 'cylinder|'.concat(detailX, '|').concat(detailY, '|').concat(bottomCap, '|').concat(topCap); + if (!this._renderer.geometryInHash(gId)) { + var cylinderGeom = new _main.default.Geometry(detailX, detailY); + _truncatedCone.call(cylinderGeom, 1, 1, 1, detailX, detailY, bottomCap, topCap); + // normals are computed in call to _truncatedCone + if (detailX <= 24 && detailY <= 16) { + cylinderGeom._makeTriangleEdges()._edgesToVertices(); + } else if (this._renderer._doStroke) { + console.log('Cannot draw stroke on cylinder objects with more' + ' than 24 detailX or 16 detailY'); + } + this._renderer.createBuffers(gId, cylinderGeom); + } + this._renderer.drawBuffersScaled(gId, radius, height, radius); + return this; + }; + /** + * Draws a cone. + * + * A cone is a 3D shape with triangular faces that connect a flat bottom to a + * single point. Cones with few faces look like pyramids. Cones with many + * faces have smooth surfaces. + * + * The first parameter, `radius`, is optional. If a `Number` is passed, as in + * `cone(20)`, it sets the radius of the cone’s base. By default, `radius` is + * 50. + * + * The second parameter, `height`, is also optional. If a `Number` is passed, + * as in `cone(20, 30)`, it sets the cone’s height. By default, `height` is + * set to the cone’s `radius`. + * + * The third parameter, `detailX`, is also optional. If a `Number` is passed, + * as in `cone(20, 30, 5)`, it sets the number of edges used to form the + * cone's base. Using more edges makes the base look more like a circle. By + * default, `detailX` is 24. + * + * The fourth parameter, `detailY`, is also optional. If a `Number` is passed, + * as in `cone(20, 30, 5, 7)`, it sets the number of triangle subdivisions to + * use along the y-axis connecting the base to the tip. All 3D shapes are made + * by connecting triangles to form their surfaces. By default, `detailY` is 1. + * + * The fifth parameter, `cap`, is also optional. If a `false` is passed, as + * in `cone(20, 30, 5, 7, false)` the cone’s base won’t be drawn. By default, + * `cap` is `true`. + * + * Note: `cone()` can only be used in WebGL mode. + * + * @method cone + * @param {Number} [radius] radius of the cone's base. Defaults to 50. + * @param {Number} [height] height of the cone. Defaults to the value of `radius`. + * @param {Integer} [detailX] number of edges used to draw the base. Defaults to 24. + * @param {Integer} [detailY] number of triangle subdivisions along the y-axis. Defaults to 1. + * @param {Boolean} [cap] whether to draw the cone's base. Defaults to `true`. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cone on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cone. + * cone(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cone on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cone. + * // Set its radius and height to 30. + * cone(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cone on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cone. + * // Set its radius to 30 and height to 50. + * cone(30, 50); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cone on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cone. + * // Set its radius to 30 and height to 50. + * // Set its detailX to 5. + * cone(30, 50, 5); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white pyramid on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cone. + * // Set its radius to 30 and height to 50. + * // Set its detailX to 5. + * cone(30, 50, 5); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cone on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cone. + * // Set its radius to 30 and height to 50. + * // Set its detailX to 24 and detailY to 2. + * cone(30, 50, 24, 2); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cone on a gray background. Its base is missing.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the cone. + * // Set its radius to 30 and height to 50. + * // Set its detailX to 24 and detailY to 1. + * // Don't draw its base. + * cone(30, 50, 24, 1, false); + * } + * + *
        + */ + _main.default.prototype.cone = function () { + var radius = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : radius; + var detailX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 24; + var detailY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var cap = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; + this._assert3d('cone'); + _main.default._validateParameters('cone', arguments); + var gId = 'cone|'.concat(detailX, '|').concat(detailY, '|').concat(cap); + if (!this._renderer.geometryInHash(gId)) { + var coneGeom = new _main.default.Geometry(detailX, detailY); + _truncatedCone.call(coneGeom, 1, 0, 1, detailX, detailY, cap, false); + if (detailX <= 24 && detailY <= 16) { + coneGeom._makeTriangleEdges()._edgesToVertices(); + } else if (this._renderer._doStroke) { + console.log('Cannot draw stroke on cone objects with more' + ' than 24 detailX or 16 detailY'); + } + this._renderer.createBuffers(gId, coneGeom); + } + this._renderer.drawBuffersScaled(gId, radius, height, radius); + return this; + }; + /** + * Draws an ellipsoid. + * + * An ellipsoid is a 3D shape with triangular faces that connect to form a + * round surface. Ellipsoids with few faces look like crystals. Ellipsoids + * with many faces have smooth surfaces and look like eggs. `ellipsoid()` + * defines a shape by its radii. This is different from + * ellipse() which uses diameters + * (width and height). + * + * The first parameter, `radiusX`, is optional. If a `Number` is passed, as in + * `ellipsoid(20)`, it sets the radius of the ellipsoid along the x-axis. By + * default, `radiusX` is 50. + * + * The second parameter, `radiusY`, is also optional. If a `Number` is passed, + * as in `ellipsoid(20, 30)`, it sets the ellipsoid’s radius along the y-axis. + * By default, `radiusY` is set to the ellipsoid’s `radiusX`. + * + * The third parameter, `radiusZ`, is also optional. If a `Number` is passed, + * as in `ellipsoid(20, 30, 40)`, it sets the ellipsoid’s radius along the + * z-axis. By default, `radiusZ` is set to the ellipsoid’s `radiusY`. + * + * The fourth parameter, `detailX`, is also optional. If a `Number` is passed, + * as in `ellipsoid(20, 30, 40, 5)`, it sets the number of triangle + * subdivisions to use along the x-axis. All 3D shapes are made by connecting + * triangles to form their surfaces. By default, `detailX` is 24. + * + * The fifth parameter, `detailY`, is also optional. If a `Number` is passed, + * as in `ellipsoid(20, 30, 40, 5, 7)`, it sets the number of triangle + * subdivisions to use along the y-axis. All 3D shapes are made by connecting + * triangles to form their surfaces. By default, `detailY` is 16. + * + * Note: `ellipsoid()` can only be used in WebGL mode. + * + * @method ellipsoid + * @param {Number} [radiusX] radius of the ellipsoid along the x-axis. Defaults to 50. + * @param {Number} [radiusY] radius of the ellipsoid along the y-axis. Defaults to `radiusX`. + * @param {Number} [radiusZ] radius of the ellipsoid along the z-axis. Defaults to `radiusY`. + * @param {Integer} [detailX] number of triangle subdivisions along the x-axis. Defaults to 24. + * @param {Integer} [detailY] number of triangle subdivisions along the y-axis. Defaults to 16. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white sphere on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the ellipsoid. + * // Set its radiusX to 30. + * ellipsoid(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white ellipsoid on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the ellipsoid. + * // Set its radiusX to 30. + * // Set its radiusY to 40. + * ellipsoid(30, 40); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white ellipsoid on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the ellipsoid. + * // Set its radiusX to 30. + * // Set its radiusY to 40. + * // Set its radiusZ to 50. + * ellipsoid(30, 40, 50); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white ellipsoid on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the ellipsoid. + * // Set its radiusX to 30. + * // Set its radiusY to 40. + * // Set its radiusZ to 50. + * // Set its detailX to 4. + * ellipsoid(30, 40, 50, 4); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white ellipsoid on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the ellipsoid. + * // Set its radiusX to 30. + * // Set its radiusY to 40. + * // Set its radiusZ to 50. + * // Set its detailX to 4. + * // Set its detailY to 3. + * ellipsoid(30, 40, 50, 4, 3); + * } + * + *
        + */ + _main.default.prototype.ellipsoid = function () { + var radiusX = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var radiusY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : radiusX; + var radiusZ = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : radiusX; + var detailX = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 24; + var detailY = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 16; + this._assert3d('ellipsoid'); + _main.default._validateParameters('ellipsoid', arguments); + var gId = 'ellipsoid|'.concat(detailX, '|').concat(detailY); + if (!this._renderer.geometryInHash(gId)) { + var _ellipsoid = function _ellipsoid() { + for (var i = 0; i <= this.detailY; i++) { + var v = i / this.detailY; + var phi = Math.PI * v - Math.PI / 2; + var cosPhi = Math.cos(phi); + var sinPhi = Math.sin(phi); + for (var j = 0; j <= this.detailX; j++) { + var u = j / this.detailX; + var theta = 2 * Math.PI * u; + var cosTheta = Math.cos(theta); + var sinTheta = Math.sin(theta); + var p = new _main.default.Vector(cosPhi * sinTheta, sinPhi, cosPhi * cosTheta); + this.vertices.push(p); + this.vertexNormals.push(p); + this.uvs.push(u, v); + } + } + }; + var ellipsoidGeom = new _main.default.Geometry(detailX, detailY, _ellipsoid); + ellipsoidGeom.computeFaces(); + if (detailX <= 24 && detailY <= 24) { + ellipsoidGeom._makeTriangleEdges()._edgesToVertices(); + } else if (this._renderer._doStroke) { + console.log('Cannot draw stroke on ellipsoids with more' + ' than 24 detailX or 24 detailY'); + } + this._renderer.createBuffers(gId, ellipsoidGeom); + } + this._renderer.drawBuffersScaled(gId, radiusX, radiusY, radiusZ); + return this; + }; + /** + * Draws a torus. + * + * A torus is a 3D shape with triangular faces that connect to form a ring. + * Toruses with few faces look flattened. Toruses with many faces have smooth + * surfaces. + * + * The first parameter, `radius`, is optional. If a `Number` is passed, as in + * `torus(30)`, it sets the radius of the ring. By default, `radius` is 50. + * + * The second parameter, `tubeRadius`, is also optional. If a `Number` is + * passed, as in `torus(30, 15)`, it sets the radius of the tube. By default, + * `tubeRadius` is 10. + * + * The third parameter, `detailX`, is also optional. If a `Number` is passed, + * as in `torus(30, 15, 5)`, it sets the number of edges used to draw the hole + * of the torus. Using more edges makes the hole look more like a circle. By + * default, `detailX` is 24. + * + * The fourth parameter, `detailY`, is also optional. If a `Number` is passed, + * as in `torus(30, 15, 5, 7)`, it sets the number of triangle subdivisions to + * use while filling in the torus’ height. By default, `detailY` is 16. + * + * Note: `torus()` can only be used in WebGL mode. + * + * @method torus + * @param {Number} [radius] radius of the torus. Defaults to 50. + * @param {Number} [tubeRadius] radius of the tube. Defaults to 10. + * @param {Integer} [detailX] number of edges that form the hole. Defaults to 24. + * @param {Integer} [detailY] number of triangle subdivisions along the y-axis. Defaults to 16. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white torus on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the torus. + * torus(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white torus on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the torus. + * // Set its radius to 30. + * torus(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white torus on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the torus. + * // Set its radius to 30 and tubeRadius to 15. + * torus(30, 15); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white torus on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the torus. + * // Set its radius to 30 and tubeRadius to 15. + * // Set its detailX to 5. + * torus(30, 15, 5); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white torus on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the torus. + * // Set its radius to 30 and tubeRadius to 15. + * // Set its detailX to 5. + * // Set its detailY to 3. + * torus(30, 15, 5, 3); + * } + * + *
        + */ + _main.default.prototype.torus = function (radius, tubeRadius, detailX, detailY) { + this._assert3d('torus'); + _main.default._validateParameters('torus', arguments); + if (typeof radius === 'undefined') { + radius = 50; + } else if (!radius) { + return; // nothing to draw + } + if (typeof tubeRadius === 'undefined') { + tubeRadius = 10; + } else if (!tubeRadius) { + return; // nothing to draw + } + if (typeof detailX === 'undefined') { + detailX = 24; + } + if (typeof detailY === 'undefined') { + detailY = 16; + } + var tubeRatio = (tubeRadius / radius).toPrecision(4); + var gId = 'torus|'.concat(tubeRatio, '|').concat(detailX, '|').concat(detailY); + if (!this._renderer.geometryInHash(gId)) { + var _torus = function _torus() { + for (var i = 0; i <= this.detailY; i++) { + var v = i / this.detailY; + var phi = 2 * Math.PI * v; + var cosPhi = Math.cos(phi); + var sinPhi = Math.sin(phi); + var r = 1 + tubeRatio * cosPhi; + for (var j = 0; j <= this.detailX; j++) { + var u = j / this.detailX; + var theta = 2 * Math.PI * u; + var cosTheta = Math.cos(theta); + var sinTheta = Math.sin(theta); + var p = new _main.default.Vector(r * cosTheta, r * sinTheta, tubeRatio * sinPhi); + var n = new _main.default.Vector(cosPhi * cosTheta, cosPhi * sinTheta, sinPhi); + this.vertices.push(p); + this.vertexNormals.push(n); + this.uvs.push(u, v); + } + } + }; + var torusGeom = new _main.default.Geometry(detailX, detailY, _torus); + torusGeom.computeFaces(); + if (detailX <= 24 && detailY <= 16) { + torusGeom._makeTriangleEdges()._edgesToVertices(); + } else if (this._renderer._doStroke) { + console.log('Cannot draw strokes on torus object with more' + ' than 24 detailX or 16 detailY'); + } + this._renderer.createBuffers(gId, torusGeom); + } + this._renderer.drawBuffersScaled(gId, radius, radius, radius); + return this; + }; + /////////////////////// + /// 2D primitives + ///////////////////////// + // + // Note: Documentation is not generated on the p5.js website for functions on + // the p5.RendererGL prototype. + /** + * Draws a point, a coordinate in space at the dimension of one pixel, + * given x, y and z coordinates. The color of the point is determined + * by the current stroke, while the point size is determined by current + * stroke weight. + * @private + * @param {Number} x x-coordinate of point + * @param {Number} y y-coordinate of point + * @param {Number} z z-coordinate of point + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(50); + * stroke(255); + * strokeWeight(4); + * point(25, 0); + * strokeWeight(3); + * point(-25, 0); + * strokeWeight(2); + * point(0, 25); + * strokeWeight(1); + * point(0, -25); + * } + * + *
        + */ + _main.default.RendererGL.prototype.point = function (x, y) { + var z = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var _vertex = [ + ]; + _vertex.push(new _main.default.Vector(x, y, z)); + this._drawPoints(_vertex, this.immediateMode.buffers.point); + return this; + }; + _main.default.RendererGL.prototype.triangle = function (args) { + var x1 = args[0], + y1 = args[1]; + var x2 = args[2], + y2 = args[3]; + var x3 = args[4], + y3 = args[5]; + var gId = 'tri'; + if (!this.geometryInHash(gId)) { + var _triangle = function _triangle() { + var vertices = [ + ]; + vertices.push(new _main.default.Vector(0, 0, 0)); + vertices.push(new _main.default.Vector(1, 0, 0)); + vertices.push(new _main.default.Vector(0, 1, 0)); + this.edges = [ + [0, + 1], + [ + 1, + 2 + ], + [ + 2, + 0 + ] + ]; + this.vertices = vertices; + this.faces = [ + [0, + 1, + 2] + ]; + this.uvs = [ + 0, + 0, + 1, + 0, + 1, + 1 + ]; + }; + var triGeom = new _main.default.Geometry(1, 1, _triangle); + triGeom._edgesToVertices(); + triGeom.computeNormals(); + this.createBuffers(gId, triGeom); + } // only one triangle is cached, one point is at the origin, and the + // two adjacent sides are tne unit vectors along the X & Y axes. + // + // this matrix multiplication transforms those two unit vectors + // onto the required vector prior to rendering, and moves the + // origin appropriately. + + var uMVMatrix = this.uMVMatrix.copy(); + try { + // triangle orientation. + var orientation = Math.sign(x1 * y2 - x2 * y1 + x2 * y3 - x3 * y2 + x3 * y1 - x1 * y3); + var mult = new _main.default.Matrix([x2 - x1, + y2 - y1, + 0, + 0, + // the resulting unit X-axis + x3 - x1, + y3 - y1, + 0, + 0, + // the resulting unit Y-axis + 0, + 0, + orientation, + 0, + // the resulting unit Z-axis (Reflect the specified order of vertices) + x1, + y1, + 0, + 1 // the resulting origin + ]).mult(this.uMVMatrix); + this.uMVMatrix = mult; + this.drawBuffers(gId); + } finally { + this.uMVMatrix = uMVMatrix; + } + return this; + }; + _main.default.RendererGL.prototype.ellipse = function (args) { + this.arc(args[0], args[1], args[2], args[3], 0, constants.TWO_PI, constants.OPEN, args[4]); + }; + _main.default.RendererGL.prototype.arc = function () { + var x = arguments.length <= 0 ? undefined : arguments[0]; + var y = arguments.length <= 1 ? undefined : arguments[1]; + var width = arguments.length <= 2 ? undefined : arguments[2]; + var height = arguments.length <= 3 ? undefined : arguments[3]; + var start = arguments.length <= 4 ? undefined : arguments[4]; + var stop = arguments.length <= 5 ? undefined : arguments[5]; + var mode = arguments.length <= 6 ? undefined : arguments[6]; + var detail = (arguments.length <= 7 ? undefined : arguments[7]) || 25; + var shape; + var gId; + // check if it is an ellipse or an arc + if (Math.abs(stop - start) >= constants.TWO_PI) { + shape = 'ellipse'; + gId = ''.concat(shape, '|').concat(detail, '|'); + } else { + shape = 'arc'; + gId = ''.concat(shape, '|').concat(start, '|').concat(stop, '|').concat(mode, '|').concat(detail, '|'); + } + if (!this.geometryInHash(gId)) { + var _arc = function _arc() { + // if the start and stop angles are not the same, push vertices to the array + if (start.toFixed(10) !== stop.toFixed(10)) { + // if the mode specified is PIE or null, push the mid point of the arc in vertices + if (mode === constants.PIE || typeof mode === 'undefined') { + this.vertices.push(new _main.default.Vector(0.5, 0.5, 0)); + this.uvs.push([0.5, + 0.5]); + } // vertices for the perimeter of the circle + + for (var i = 0; i <= detail; i++) { + var u = i / detail; + var theta = (stop - start) * u + start; + var _x = 0.5 + Math.cos(theta) / 2; + var _y = 0.5 + Math.sin(theta) / 2; + this.vertices.push(new _main.default.Vector(_x, _y, 0)); + this.uvs.push([_x, + _y]); + if (i < detail - 1) { + this.faces.push([0, + i + 1, + i + 2]); + this.edges.push([i + 1, + i + 2]); + } + } // check the mode specified in order to push vertices and faces, different for each mode + + switch (mode) { + case constants.PIE: + this.faces.push([0, + this.vertices.length - 2, + this.vertices.length - 1]); + this.edges.push([0, + 1]); + this.edges.push([this.vertices.length - 2, + this.vertices.length - 1]); + this.edges.push([0, + this.vertices.length - 1]); + break; + case constants.CHORD: + this.edges.push([0, + 1]); + this.edges.push([0, + this.vertices.length - 1]); + break; + case constants.OPEN: + this.edges.push([0, + 1]); + break; + default: + this.faces.push([0, + this.vertices.length - 2, + this.vertices.length - 1]); + this.edges.push([this.vertices.length - 2, + this.vertices.length - 1]); + } + } + }; + var arcGeom = new _main.default.Geometry(detail, 1, _arc); + arcGeom.computeNormals(); + if (detail <= 50) { + arcGeom._edgesToVertices(arcGeom); + } else if (this._doStroke) { + console.log('Cannot apply a stroke to an '.concat(shape, ' with more than 50 detail')); + } + this.createBuffers(gId, arcGeom); + } + var uMVMatrix = this.uMVMatrix.copy(); + try { + this.uMVMatrix.translate([x, + y, + 0]); + this.uMVMatrix.scale(width, height, 1); + this.drawBuffers(gId); + } finally { + this.uMVMatrix = uMVMatrix; + } + return this; + }; + _main.default.RendererGL.prototype.rect = function (args) { + var x = args[0]; + var y = args[1]; + var width = args[2]; + var height = args[3]; + if (typeof args[4] === 'undefined') { + // Use the retained mode for drawing rectangle, + // if args for rounding rectangle is not provided by user. + var perPixelLighting = this._pInst._glAttributes.perPixelLighting; + var detailX = args[4] || (perPixelLighting ? 1 : 24); + var detailY = args[5] || (perPixelLighting ? 1 : 16); + var gId = 'rect|'.concat(detailX, '|').concat(detailY); + if (!this.geometryInHash(gId)) { + var _rect = function _rect() { + for (var i = 0; i <= this.detailY; i++) { + var v = i / this.detailY; + for (var j = 0; j <= this.detailX; j++) { + var u = j / this.detailX; + var p = new _main.default.Vector(u, v, 0); + this.vertices.push(p); + this.uvs.push(u, v); + } + } // using stroke indices to avoid stroke over face(s) of rectangle + + if (detailX > 0 && detailY > 0) { + this.edges = [ + [0, + detailX], + [ + detailX, + (detailX + 1) * (detailY + 1) - 1 + ], + [ + (detailX + 1) * (detailY + 1) - 1, + (detailX + 1) * detailY + ], + [ + (detailX + 1) * detailY, + 0 + ] + ]; + } + }; + var rectGeom = new _main.default.Geometry(detailX, detailY, _rect); + rectGeom.computeFaces().computeNormals()._edgesToVertices(); + this.createBuffers(gId, rectGeom); + } // only a single rectangle (of a given detail) is cached: a square with + // opposite corners at (0,0) & (1,1). + // + // before rendering, this square is scaled & moved to the required location. + + var uMVMatrix = this.uMVMatrix.copy(); + try { + this.uMVMatrix.translate([x, + y, + 0]); + this.uMVMatrix.scale(width, height, 1); + this.drawBuffers(gId); + } finally { + this.uMVMatrix = uMVMatrix; + } + } else { + // Use Immediate mode to round the rectangle corner, + // if args for rounding corners is provided by user + var tl = args[4]; + var tr = typeof args[5] === 'undefined' ? tl : args[5]; + var br = typeof args[6] === 'undefined' ? tr : args[6]; + var bl = typeof args[7] === 'undefined' ? br : args[7]; + var a = x; + var b = y; + var c = width; + var d = height; + c += a; + d += b; + if (a > c) { + var temp = a; + a = c; + c = temp; + } + if (b > d) { + var _temp = b; + b = d; + d = _temp; + } + var maxRounding = Math.min((c - a) / 2, (d - b) / 2); + if (tl > maxRounding) tl = maxRounding; + if (tr > maxRounding) tr = maxRounding; + if (br > maxRounding) br = maxRounding; + if (bl > maxRounding) bl = maxRounding; + var x1 = a; + var y1 = b; + var x2 = c; + var y2 = d; + this.beginShape(); + if (tr !== 0) { + this.vertex(x2 - tr, y1); + this.quadraticVertex(x2, y1, x2, y1 + tr); + } else { + this.vertex(x2, y1); + } + if (br !== 0) { + this.vertex(x2, y2 - br); + this.quadraticVertex(x2, y2, x2 - br, y2); + } else { + this.vertex(x2, y2); + } + if (bl !== 0) { + this.vertex(x1 + bl, y2); + this.quadraticVertex(x1, y2, x1, y2 - bl); + } else { + this.vertex(x1, y2); + } + if (tl !== 0) { + this.vertex(x1, y1 + tl); + this.quadraticVertex(x1, y1, x1 + tl, y1); + } else { + this.vertex(x1, y1); + } + this.immediateMode.geometry.uvs.length = 0; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.immediateMode.geometry.vertices[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var vert = _step.value; + var u = (vert.x - x1) / width; + var v = (vert.y - y1) / height; + this.immediateMode.geometry.uvs.push(u, v); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + this.endShape(constants.CLOSE); + } + return this; + }; + /* eslint-disable max-len */ + _main.default.RendererGL.prototype.quad = function (x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { + var detailX = arguments.length > 12 && arguments[12] !== undefined ? arguments[12] : 2; + var detailY = arguments.length > 13 && arguments[13] !== undefined ? arguments[13] : 2; + /* eslint-enable max-len */ + var gId = 'quad|'.concat(x1, '|').concat(y1, '|').concat(z1, '|').concat(x2, '|').concat(y2, '|').concat(z2, '|').concat(x3, '|').concat(y3, '|').concat(z3, '|').concat(x4, '|').concat(y4, '|').concat(z4, '|').concat(detailX, '|').concat(detailY); + if (!this.geometryInHash(gId)) { + var quadGeom = new _main.default.Geometry(detailX, detailY, function () { + //algorithm adapted from c++ to js + //https://stackoverflow.com/questions/16989181/whats-the-correct-way-to-draw-a-distorted-plane-in-opengl/16993202#16993202 + var xRes = 1 / (this.detailX - 1); + var yRes = 1 / (this.detailY - 1); + for (var y = 0; y < this.detailY; y++) { + for (var x = 0; x < this.detailX; x++) { + var pctx = x * xRes; + var pcty = y * yRes; + var linePt0x = (1 - pcty) * x1 + pcty * x4; + var linePt0y = (1 - pcty) * y1 + pcty * y4; + var linePt0z = (1 - pcty) * z1 + pcty * z4; + var linePt1x = (1 - pcty) * x2 + pcty * x3; + var linePt1y = (1 - pcty) * y2 + pcty * y3; + var linePt1z = (1 - pcty) * z2 + pcty * z3; + var ptx = (1 - pctx) * linePt0x + pctx * linePt1x; + var pty = (1 - pctx) * linePt0y + pctx * linePt1y; + var ptz = (1 - pctx) * linePt0z + pctx * linePt1z; + this.vertices.push(new _main.default.Vector(ptx, pty, ptz)); + this.uvs.push([pctx, + pcty]); + } + } + }); + quadGeom.faces = [ + ]; + for (var y = 0; y < detailY - 1; y++) { + for (var x = 0; x < detailX - 1; x++) { + var pt0 = x + y * detailX; + var pt1 = x + 1 + y * detailX; + var pt2 = x + 1 + (y + 1) * detailX; + var pt3 = x + (y + 1) * detailX; + quadGeom.faces.push([pt0, + pt1, + pt2]); + quadGeom.faces.push([pt0, + pt2, + pt3]); + } + } + quadGeom.computeNormals(); + quadGeom.edges.length = 0; + var vertexOrder = [ + 0, + 2, + 3, + 1 + ]; + for (var i = 0; i < vertexOrder.length; i++) { + var startVertex = vertexOrder[i]; + var endVertex = vertexOrder[(i + 1) % vertexOrder.length]; + quadGeom.edges.push([startVertex, + endVertex]); + } + quadGeom._edgesToVertices(); + this.createBuffers(gId, quadGeom); + } + this.drawBuffers(gId); + return this; + }; + //this implementation of bezier curve + //is based on Bernstein polynomial + // pretier-ignore + _main.default.RendererGL.prototype.bezier = function (x1, y1, z1, // x2 + x2, // y2 + y2, // x3 + z2, // y3 + x3, // x4 + y3, // y4 + z3, x4, y4, z4) { + if (arguments.length === 8) { + y4 = y3; + x4 = x3; + y3 = z2; + x3 = y2; + y2 = x2; + x2 = z1; + z1 = z2 = z3 = z4 = 0; + } + var bezierDetail = this._pInst._bezierDetail || 20; //value of Bezier detail + this.beginShape(); + for (var i = 0; i <= bezierDetail; i++) { + var c1 = Math.pow(1 - i / bezierDetail, 3); + var c2 = 3 * (i / bezierDetail) * Math.pow(1 - i / bezierDetail, 2); + var c3 = 3 * Math.pow(i / bezierDetail, 2) * (1 - i / bezierDetail); + var c4 = Math.pow(i / bezierDetail, 3); + this.vertex(x1 * c1 + x2 * c2 + x3 * c3 + x4 * c4, y1 * c1 + y2 * c2 + y3 * c3 + y4 * c4, z1 * c1 + z2 * c2 + z3 * c3 + z4 * c4); + } + this.endShape(); + return this; + }; + // pretier-ignore + _main.default.RendererGL.prototype.curve = function (x1, y1, z1, // x2 + x2, // y2 + y2, // x3 + z2, // y3 + x3, // x4 + y3, // y4 + z3, x4, y4, z4) { + if (arguments.length === 8) { + x4 = x3; + y4 = y3; + x3 = y2; + y3 = x2; + x2 = z1; + y2 = x2; + z1 = z2 = z3 = z4 = 0; + } + var curveDetail = this._pInst._curveDetail; + this.beginShape(); + for (var i = 0; i <= curveDetail; i++) { + var c1 = Math.pow(i / curveDetail, 3) * 0.5; + var c2 = Math.pow(i / curveDetail, 2) * 0.5; + var c3 = i / curveDetail * 0.5; + var c4 = 0.5; + var vx = c1 * ( - x1 + 3 * x2 - 3 * x3 + x4) + c2 * (2 * x1 - 5 * x2 + 4 * x3 - x4) + c3 * ( - x1 + x3) + c4 * (2 * x2); + var vy = c1 * ( - y1 + 3 * y2 - 3 * y3 + y4) + c2 * (2 * y1 - 5 * y2 + 4 * y3 - y4) + c3 * ( - y1 + y3) + c4 * (2 * y2); + var vz = c1 * ( - z1 + 3 * z2 - 3 * z3 + z4) + c2 * (2 * z1 - 5 * z2 + 4 * z3 - z4) + c3 * ( - z1 + z3) + c4 * (2 * z2); + this.vertex(vx, vy, vz); + } + this.endShape(); + return this; + }; + /** + * Draw a line given two points + * @private + * @param {Number} x0 x-coordinate of first vertex + * @param {Number} y0 y-coordinate of first vertex + * @param {Number} z0 z-coordinate of first vertex + * @param {Number} x1 x-coordinate of second vertex + * @param {Number} y1 y-coordinate of second vertex + * @param {Number} z1 z-coordinate of second vertex + * @chainable + * @example + *
        + * + * //draw a line + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(200); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * // Use fill instead of stroke to change the color of shape. + * fill(255, 0, 0); + * line(10, 10, 0, 60, 60, 20); + * } + * + *
        + */ + _main.default.RendererGL.prototype.line = function () { + if (arguments.length === 6) { + this.beginShape(constants.LINES); + this.vertex(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + this.vertex(arguments.length <= 3 ? undefined : arguments[3], arguments.length <= 4 ? undefined : arguments[4], arguments.length <= 5 ? undefined : arguments[5]); + this.endShape(); + } else if (arguments.length === 4) { + this.beginShape(constants.LINES); + this.vertex(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], 0); + this.vertex(arguments.length <= 2 ? undefined : arguments[2], arguments.length <= 3 ? undefined : arguments[3], 0); + this.endShape(); + } + return this; + }; + _main.default.RendererGL.prototype.bezierVertex = function () { + if (this.immediateMode._bezierVertex.length === 0) { + throw Error('vertex() must be used once before calling bezierVertex()'); + } else { + var w_x = [ + ]; + var w_y = [ + ]; + var w_z = [ + ]; + var t, + _x, + _y, + _z, + i, + k, + m; + // variable i for bezierPoints, k for components, and m for anchor points. + var argLength = arguments.length; + t = 0; + if (this._lookUpTableBezier.length === 0 || this._lutBezierDetail !== this._pInst._curveDetail) { + this._lookUpTableBezier = [ + ]; + this._lutBezierDetail = this._pInst._curveDetail; + var step = 1 / this._lutBezierDetail; + var start = 0; + var end = 1; + var j = 0; + while (start < 1) { + t = parseFloat(start.toFixed(6)); + this._lookUpTableBezier[j] = this._bezierCoefficients(t); + if (end.toFixed(6) === step.toFixed(6)) { + t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6)); + ++j; + this._lookUpTableBezier[j] = this._bezierCoefficients(t); + break; + } + start += step; + end -= step; + ++j; + } + } + var LUTLength = this._lookUpTableBezier.length; + // fillColors[0]: start point color + // fillColors[1],[2]: control point color + // fillColors[3]: end point color + var fillColors = [ + ]; + for (m = 0; m < 4; m++) { + fillColors.push([]); + } + fillColors[0] = this.immediateMode.geometry.vertexColors.slice( - 4); + fillColors[3] = this.curFillColor.slice(); + // Do the same for strokeColor. + var strokeColors = [ + ]; + for (m = 0; m < 4; m++) { + strokeColors.push([]); + } + strokeColors[0] = this.immediateMode.geometry.vertexStrokeColors.slice( - 4); + strokeColors[3] = this.curStrokeColor.slice(); + if (argLength === 6) { + this.isBezier = true; + w_x = [ + this.immediateMode._bezierVertex[0], + arguments.length <= 0 ? undefined : arguments[0], + arguments.length <= 2 ? undefined : arguments[2], + arguments.length <= 4 ? undefined : arguments[4] + ]; + w_y = [ + this.immediateMode._bezierVertex[1], + arguments.length <= 1 ? undefined : arguments[1], + arguments.length <= 3 ? undefined : arguments[3], + arguments.length <= 5 ? undefined : arguments[5] + ]; + // The ratio of the distance between the start point, the two control- + // points, and the end point determines the intermediate color. + var d0 = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1]); + var d1 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2]); + var d2 = Math.hypot(w_x[2] - w_x[3], w_y[2] - w_y[3]); + var totalLength = d0 + d1 + d2; + d0 /= totalLength; + d2 /= totalLength; + for (k = 0; k < 4; k++) { + fillColors[1].push(fillColors[0][k] * (1 - d0) + fillColors[3][k] * d0); + fillColors[2].push(fillColors[0][k] * d2 + fillColors[3][k] * (1 - d2)); + strokeColors[1].push(strokeColors[0][k] * (1 - d0) + strokeColors[3][k] * d0); + strokeColors[2].push(strokeColors[0][k] * d2 + strokeColors[3][k] * (1 - d2)); + } + for (i = 0; i < LUTLength; i++) { + // Interpolate colors using control points + this.curFillColor = [ + 0, + 0, + 0, + 0 + ]; + this.curStrokeColor = [ + 0, + 0, + 0, + 0 + ]; + _x = _y = 0; + for (m = 0; m < 4; m++) { + for (k = 0; k < 4; k++) { + this.curFillColor[k] += this._lookUpTableBezier[i][m] * fillColors[m][k]; + this.curStrokeColor[k] += this._lookUpTableBezier[i][m] * strokeColors[m][k]; + } + _x += w_x[m] * this._lookUpTableBezier[i][m]; + _y += w_y[m] * this._lookUpTableBezier[i][m]; + } + this.vertex(_x, _y); + } // so that we leave currentColor with the last value the user set it to + + this.curFillColor = fillColors[3]; + this.curStrokeColor = strokeColors[3]; + this.immediateMode._bezierVertex[0] = arguments.length <= 4 ? undefined : arguments[4]; + this.immediateMode._bezierVertex[1] = arguments.length <= 5 ? undefined : arguments[5]; + } else if (argLength === 9) { + this.isBezier = true; + w_x = [ + this.immediateMode._bezierVertex[0], + arguments.length <= 0 ? undefined : arguments[0], + arguments.length <= 3 ? undefined : arguments[3], + arguments.length <= 6 ? undefined : arguments[6] + ]; + w_y = [ + this.immediateMode._bezierVertex[1], + arguments.length <= 1 ? undefined : arguments[1], + arguments.length <= 4 ? undefined : arguments[4], + arguments.length <= 7 ? undefined : arguments[7] + ]; + w_z = [ + this.immediateMode._bezierVertex[2], + arguments.length <= 2 ? undefined : arguments[2], + arguments.length <= 5 ? undefined : arguments[5], + arguments.length <= 8 ? undefined : arguments[8] + ]; + // The ratio of the distance between the start point, the two control- + // points, and the end point determines the intermediate color. + var _d = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1], w_z[0] - w_z[1]); + var _d2 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2], w_z[1] - w_z[2]); + var _d3 = Math.hypot(w_x[2] - w_x[3], w_y[2] - w_y[3], w_z[2] - w_z[3]); + var _totalLength = _d + _d2 + _d3; + _d /= _totalLength; + _d3 /= _totalLength; + for (k = 0; k < 4; k++) { + fillColors[1].push(fillColors[0][k] * (1 - _d) + fillColors[3][k] * _d); + fillColors[2].push(fillColors[0][k] * _d3 + fillColors[3][k] * (1 - _d3)); + strokeColors[1].push(strokeColors[0][k] * (1 - _d) + strokeColors[3][k] * _d); + strokeColors[2].push(strokeColors[0][k] * _d3 + strokeColors[3][k] * (1 - _d3)); + } + for (i = 0; i < LUTLength; i++) { + // Interpolate colors using control points + this.curFillColor = [ + 0, + 0, + 0, + 0 + ]; + this.curStrokeColor = [ + 0, + 0, + 0, + 0 + ]; + _x = _y = _z = 0; + for (m = 0; m < 4; m++) { + for (k = 0; k < 4; k++) { + this.curFillColor[k] += this._lookUpTableBezier[i][m] * fillColors[m][k]; + this.curStrokeColor[k] += this._lookUpTableBezier[i][m] * strokeColors[m][k]; + } + _x += w_x[m] * this._lookUpTableBezier[i][m]; + _y += w_y[m] * this._lookUpTableBezier[i][m]; + _z += w_z[m] * this._lookUpTableBezier[i][m]; + } + this.vertex(_x, _y, _z); + } // so that we leave currentColor with the last value the user set it to + + this.curFillColor = fillColors[3]; + this.curStrokeColor = strokeColors[3]; + this.immediateMode._bezierVertex[0] = arguments.length <= 6 ? undefined : arguments[6]; + this.immediateMode._bezierVertex[1] = arguments.length <= 7 ? undefined : arguments[7]; + this.immediateMode._bezierVertex[2] = arguments.length <= 8 ? undefined : arguments[8]; + } + } + }; + _main.default.RendererGL.prototype.quadraticVertex = function () { + if (this.immediateMode._quadraticVertex.length === 0) { + throw Error('vertex() must be used once before calling quadraticVertex()'); + } else { + var w_x = [ + ]; + var w_y = [ + ]; + var w_z = [ + ]; + var t, + _x, + _y, + _z, + i, + k, + m; + // variable i for bezierPoints, k for components, and m for anchor points. + var argLength = arguments.length; + t = 0; + if (this._lookUpTableQuadratic.length === 0 || this._lutQuadraticDetail !== this._pInst._curveDetail) { + this._lookUpTableQuadratic = [ + ]; + this._lutQuadraticDetail = this._pInst._curveDetail; + var step = 1 / this._lutQuadraticDetail; + var start = 0; + var end = 1; + var j = 0; + while (start < 1) { + t = parseFloat(start.toFixed(6)); + this._lookUpTableQuadratic[j] = this._quadraticCoefficients(t); + if (end.toFixed(6) === step.toFixed(6)) { + t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6)); + ++j; + this._lookUpTableQuadratic[j] = this._quadraticCoefficients(t); + break; + } + start += step; + end -= step; + ++j; + } + } + var LUTLength = this._lookUpTableQuadratic.length; + // fillColors[0]: start point color + // fillColors[1]: control point color + // fillColors[2]: end point color + var fillColors = [ + ]; + for (m = 0; m < 3; m++) { + fillColors.push([]); + } + fillColors[0] = this.immediateMode.geometry.vertexColors.slice( - 4); + fillColors[2] = this.curFillColor.slice(); + // Do the same for strokeColor. + var strokeColors = [ + ]; + for (m = 0; m < 3; m++) { + strokeColors.push([]); + } + strokeColors[0] = this.immediateMode.geometry.vertexStrokeColors.slice( - 4); + strokeColors[2] = this.curStrokeColor.slice(); + if (argLength === 4) { + this.isQuadratic = true; + w_x = [ + this.immediateMode._quadraticVertex[0], + arguments.length <= 0 ? undefined : arguments[0], + arguments.length <= 2 ? undefined : arguments[2] + ]; + w_y = [ + this.immediateMode._quadraticVertex[1], + arguments.length <= 1 ? undefined : arguments[1], + arguments.length <= 3 ? undefined : arguments[3] + ]; + // The ratio of the distance between the start point, the control- + // point, and the end point determines the intermediate color. + var d0 = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1]); + var d1 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2]); + var totalLength = d0 + d1; + d0 /= totalLength; + for (k = 0; k < 4; k++) { + fillColors[1].push(fillColors[0][k] * (1 - d0) + fillColors[2][k] * d0); + strokeColors[1].push(strokeColors[0][k] * (1 - d0) + strokeColors[2][k] * d0); + } + for (i = 0; i < LUTLength; i++) { + // Interpolate colors using control points + this.curFillColor = [ + 0, + 0, + 0, + 0 + ]; + this.curStrokeColor = [ + 0, + 0, + 0, + 0 + ]; + _x = _y = 0; + for (m = 0; m < 3; m++) { + for (k = 0; k < 4; k++) { + this.curFillColor[k] += this._lookUpTableQuadratic[i][m] * fillColors[m][k]; + this.curStrokeColor[k] += this._lookUpTableQuadratic[i][m] * strokeColors[m][k]; + } + _x += w_x[m] * this._lookUpTableQuadratic[i][m]; + _y += w_y[m] * this._lookUpTableQuadratic[i][m]; + } + this.vertex(_x, _y); + } // so that we leave currentColor with the last value the user set it to + + this.curFillColor = fillColors[2]; + this.curStrokeColor = strokeColors[2]; + this.immediateMode._quadraticVertex[0] = arguments.length <= 2 ? undefined : arguments[2]; + this.immediateMode._quadraticVertex[1] = arguments.length <= 3 ? undefined : arguments[3]; + } else if (argLength === 6) { + this.isQuadratic = true; + w_x = [ + this.immediateMode._quadraticVertex[0], + arguments.length <= 0 ? undefined : arguments[0], + arguments.length <= 3 ? undefined : arguments[3] + ]; + w_y = [ + this.immediateMode._quadraticVertex[1], + arguments.length <= 1 ? undefined : arguments[1], + arguments.length <= 4 ? undefined : arguments[4] + ]; + w_z = [ + this.immediateMode._quadraticVertex[2], + arguments.length <= 2 ? undefined : arguments[2], + arguments.length <= 5 ? undefined : arguments[5] + ]; + // The ratio of the distance between the start point, the control- + // point, and the end point determines the intermediate color. + var _d4 = Math.hypot(w_x[0] - w_x[1], w_y[0] - w_y[1], w_z[0] - w_z[1]); + var _d5 = Math.hypot(w_x[1] - w_x[2], w_y[1] - w_y[2], w_z[1] - w_z[2]); + var _totalLength2 = _d4 + _d5; + _d4 /= _totalLength2; + for (k = 0; k < 4; k++) { + fillColors[1].push(fillColors[0][k] * (1 - _d4) + fillColors[2][k] * _d4); + strokeColors[1].push(strokeColors[0][k] * (1 - _d4) + strokeColors[2][k] * _d4); + } + for (i = 0; i < LUTLength; i++) { + // Interpolate colors using control points + this.curFillColor = [ + 0, + 0, + 0, + 0 + ]; + this.curStrokeColor = [ + 0, + 0, + 0, + 0 + ]; + _x = _y = _z = 0; + for (m = 0; m < 3; m++) { + for (k = 0; k < 4; k++) { + this.curFillColor[k] += this._lookUpTableQuadratic[i][m] * fillColors[m][k]; + this.curStrokeColor[k] += this._lookUpTableQuadratic[i][m] * strokeColors[m][k]; + } + _x += w_x[m] * this._lookUpTableQuadratic[i][m]; + _y += w_y[m] * this._lookUpTableQuadratic[i][m]; + _z += w_z[m] * this._lookUpTableQuadratic[i][m]; + } + this.vertex(_x, _y, _z); + } // so that we leave currentColor with the last value the user set it to + + this.curFillColor = fillColors[2]; + this.curStrokeColor = strokeColors[2]; + this.immediateMode._quadraticVertex[0] = arguments.length <= 3 ? undefined : arguments[3]; + this.immediateMode._quadraticVertex[1] = arguments.length <= 4 ? undefined : arguments[4]; + this.immediateMode._quadraticVertex[2] = arguments.length <= 5 ? undefined : arguments[5]; + } + } + }; + _main.default.RendererGL.prototype.curveVertex = function () { + var w_x = [ + ]; + var w_y = [ + ]; + var w_z = [ + ]; + var t, + _x, + _y, + _z, + i; + t = 0; + var argLength = arguments.length; + if (this._lookUpTableBezier.length === 0 || this._lutBezierDetail !== this._pInst._curveDetail) { + this._lookUpTableBezier = [ + ]; + this._lutBezierDetail = this._pInst._curveDetail; + var step = 1 / this._lutBezierDetail; + var start = 0; + var end = 1; + var j = 0; + while (start < 1) { + t = parseFloat(start.toFixed(6)); + this._lookUpTableBezier[j] = this._bezierCoefficients(t); + if (end.toFixed(6) === step.toFixed(6)) { + t = parseFloat(end.toFixed(6)) + parseFloat(start.toFixed(6)); + ++j; + this._lookUpTableBezier[j] = this._bezierCoefficients(t); + break; + } + start += step; + end -= step; + ++j; + } + } + var LUTLength = this._lookUpTableBezier.length; + if (argLength === 2) { + this.immediateMode._curveVertex.push(arguments.length <= 0 ? undefined : arguments[0]); + this.immediateMode._curveVertex.push(arguments.length <= 1 ? undefined : arguments[1]); + if (this.immediateMode._curveVertex.length === 8) { + this.isCurve = true; + w_x = this._bezierToCatmull([this.immediateMode._curveVertex[0], + this.immediateMode._curveVertex[2], + this.immediateMode._curveVertex[4], + this.immediateMode._curveVertex[6]]); + w_y = this._bezierToCatmull([this.immediateMode._curveVertex[1], + this.immediateMode._curveVertex[3], + this.immediateMode._curveVertex[5], + this.immediateMode._curveVertex[7]]); + for (i = 0; i < LUTLength; i++) { + _x = w_x[0] * this._lookUpTableBezier[i][0] + w_x[1] * this._lookUpTableBezier[i][1] + w_x[2] * this._lookUpTableBezier[i][2] + w_x[3] * this._lookUpTableBezier[i][3]; + _y = w_y[0] * this._lookUpTableBezier[i][0] + w_y[1] * this._lookUpTableBezier[i][1] + w_y[2] * this._lookUpTableBezier[i][2] + w_y[3] * this._lookUpTableBezier[i][3]; + this.vertex(_x, _y); + } + for (i = 0; i < argLength; i++) { + this.immediateMode._curveVertex.shift(); + } + } + } else if (argLength === 3) { + this.immediateMode._curveVertex.push(arguments.length <= 0 ? undefined : arguments[0]); + this.immediateMode._curveVertex.push(arguments.length <= 1 ? undefined : arguments[1]); + this.immediateMode._curveVertex.push(arguments.length <= 2 ? undefined : arguments[2]); + if (this.immediateMode._curveVertex.length === 12) { + this.isCurve = true; + w_x = this._bezierToCatmull([this.immediateMode._curveVertex[0], + this.immediateMode._curveVertex[3], + this.immediateMode._curveVertex[6], + this.immediateMode._curveVertex[9]]); + w_y = this._bezierToCatmull([this.immediateMode._curveVertex[1], + this.immediateMode._curveVertex[4], + this.immediateMode._curveVertex[7], + this.immediateMode._curveVertex[10]]); + w_z = this._bezierToCatmull([this.immediateMode._curveVertex[2], + this.immediateMode._curveVertex[5], + this.immediateMode._curveVertex[8], + this.immediateMode._curveVertex[11]]); + for (i = 0; i < LUTLength; i++) { + _x = w_x[0] * this._lookUpTableBezier[i][0] + w_x[1] * this._lookUpTableBezier[i][1] + w_x[2] * this._lookUpTableBezier[i][2] + w_x[3] * this._lookUpTableBezier[i][3]; + _y = w_y[0] * this._lookUpTableBezier[i][0] + w_y[1] * this._lookUpTableBezier[i][1] + w_y[2] * this._lookUpTableBezier[i][2] + w_y[3] * this._lookUpTableBezier[i][3]; + _z = w_z[0] * this._lookUpTableBezier[i][0] + w_z[1] * this._lookUpTableBezier[i][1] + w_z[2] * this._lookUpTableBezier[i][2] + w_z[3] * this._lookUpTableBezier[i][3]; + this.vertex(_x, _y, _z); + } + for (i = 0; i < argLength; i++) { + this.immediateMode._curveVertex.shift(); + } + } + } + }; + _main.default.RendererGL.prototype.image = function (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) { + if (this._isErasing) { + this.blendMode(this._cachedBlendMode); + } + this._pInst.push(); + this._pInst.noLights(); + this._pInst.noStroke(); + this._pInst.texture(img); + this._pInst.textureMode(constants.NORMAL); + var u0 = 0; + if (sx <= img.width) { + u0 = sx / img.width; + } + var u1 = 1; + if (sx + sWidth <= img.width) { + u1 = (sx + sWidth) / img.width; + } + var v0 = 0; + if (sy <= img.height) { + v0 = sy / img.height; + } + var v1 = 1; + if (sy + sHeight <= img.height) { + v1 = (sy + sHeight) / img.height; + } + this.beginShape(); + this.vertex(dx, dy, 0, u0, v0); + this.vertex(dx + dWidth, dy, 0, u1, v0); + this.vertex(dx + dWidth, dy + dHeight, 0, u1, v1); + this.vertex(dx, dy + dHeight, 0, u0, v1); + this.endShape(constants.CLOSE); + this._pInst.pop(); + if (this._isErasing) { + this.blendMode(constants.REMOVE); + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + './p5.Geometry': 355, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.math.hypot': 193, + 'core-js/modules/es.math.sign': 195, + 'core-js/modules/es.number.to-fixed': 198, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 347: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.object.assign'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } + function _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; + } /** + * @private + * A class responsible for converting successive WebGL draw calls into a single + * `p5.Geometry` that can be reused and drawn with `model()`. + */ + + var GeometryBuilder = /*#__PURE__*/ function () { + function GeometryBuilder(renderer) { + _classCallCheck(this, GeometryBuilder); + this.renderer = renderer; + renderer._pInst.push(); + this.identityMatrix = new _main.default.Matrix(); + renderer.uMVMatrix = new _main.default.Matrix(); + this.geometry = new _main.default.Geometry(); + this.geometry.gid = '_p5_GeometryBuilder_'.concat(GeometryBuilder.nextGeometryId); + GeometryBuilder.nextGeometryId++; + this.hasTransform = false; + } /** + * @private + * Applies the current transformation matrix to each vertex. + */ + + _createClass(GeometryBuilder, [ + { + key: 'transformVertices', + value: function transformVertices(vertices) { + var _this = this; + if (!this.hasTransform) return vertices; + return vertices.map(function (v) { + return _this.renderer.uMVMatrix.multiplyPoint(v); + }); + } /** + * @private + * Applies the current normal matrix to each normal. + */ + + }, + { + key: 'transformNormals', + value: function transformNormals(normals) { + var _this2 = this; + if (!this.hasTransform) return normals; + return normals.map(function (v) { + return _this2.renderer.uNMatrix.multiplyVec3(v); + }); + } /** + * @private + * Adds a p5.Geometry to the builder's combined geometry, flattening + * transformations. + */ + + }, + { + key: 'addGeometry', + value: function addGeometry(input) { + var _this3 = this, + _this$geometry$vertic, + _this$geometry$vertex, + _this$geometry$uvs, + _this$geometry$vertex2; + this.hasTransform = !this.renderer.uMVMatrix.mat4.every(function (v, i) { + return v === _this3.identityMatrix.mat4[i]; + }); + if (this.hasTransform) { + this.renderer.uNMatrix.inverseTranspose(this.renderer.uMVMatrix); + } + var startIdx = this.geometry.vertices.length; + (_this$geometry$vertic = this.geometry.vertices).push.apply(_this$geometry$vertic, _toConsumableArray(this.transformVertices(input.vertices))); + (_this$geometry$vertex = this.geometry.vertexNormals).push.apply(_this$geometry$vertex, _toConsumableArray(this.transformNormals(input.vertexNormals))); + (_this$geometry$uvs = this.geometry.uvs).push.apply(_this$geometry$uvs, _toConsumableArray(input.uvs)); + if (this.renderer._doFill) { + var _this$geometry$faces; + (_this$geometry$faces = this.geometry.faces).push.apply(_this$geometry$faces, _toConsumableArray(input.faces.map(function (f) { + return f.map(function (idx) { + return idx + startIdx; + }); + }))); + } + if (this.renderer._doStroke) { + var _this$geometry$edges; + (_this$geometry$edges = this.geometry.edges).push.apply(_this$geometry$edges, _toConsumableArray(input.edges.map(function (edge) { + return edge.map(function (idx) { + return idx + startIdx; + }); + }))); + } + var vertexColors = _toConsumableArray(input.vertexColors); + while (vertexColors.length < input.vertices.length * 4) { + vertexColors.push.apply(vertexColors, _toConsumableArray(this.renderer.curFillColor)); + }(_this$geometry$vertex2 = this.geometry.vertexColors).push.apply(_this$geometry$vertex2, _toConsumableArray(vertexColors)); + } /** + * Adds geometry from the renderer's immediate mode into the builder's + * combined geometry. + */ + + }, + { + key: 'addImmediate', + value: function addImmediate() { + var geometry = this.renderer.immediateMode.geometry; + var shapeMode = this.renderer.immediateMode.shapeMode; + var faces = [ + ]; + if (this.renderer._doFill) { + if (shapeMode === constants.TRIANGLE_STRIP || shapeMode === constants.QUAD_STRIP) { + for (var i = 2; i < geometry.vertices.length; i++) { + if (i % 2 === 0) { + faces.push([i, + i - 1, + i - 2]); + } else { + faces.push([i, + i - 2, + i - 1]); + } + } + } else if (shapeMode === constants.TRIANGLE_FAN) { + for (var _i = 2; _i < geometry.vertices.length; _i++) { + faces.push([0, + _i - 1, + _i]); + } + } else { + for (var _i2 = 0; _i2 < geometry.vertices.length; _i2 += 3) { + faces.push([_i2, + _i2 + 1, + _i2 + 2]); + } + } + } + this.addGeometry(Object.assign({ + }, geometry, { + faces: faces + })); + } /** + * Adds geometry from the renderer's retained mode into the builder's + * combined geometry. + */ + + }, + { + key: 'addRetained', + value: function addRetained(geometry) { + this.addGeometry(geometry.model); + } /** + * Cleans up the state of the renderer and returns the combined geometry that + * was built. + * @returns p5.Geometry The flattened, combined geometry + */ + + }, + { + key: 'finish', + value: function finish() { + this.renderer._pInst.pop(); + return this.geometry; + } + } + ]); + return GeometryBuilder; + }(); + /** + * Keeps track of how many custom geometry objects have been made so that each + * can be assigned a unique ID. + */ + GeometryBuilder.nextGeometryId = 0; + var _default = GeometryBuilder; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + 'core-js/modules/es.array.every': 172, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.object.assign': 199, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 348: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.math.sign'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } /** + * @module 3D + * @submodule Interaction + * @for p5 + * @requires core + */ + /** + * Allows the user to orbit around a 3D sketch using a mouse, trackpad, or + * touchscreen. + * + * 3D sketches are viewed through an imaginary camera. Calling + * `orbitControl()` within the draw() function allows + * the user to change the camera’s position: + * + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Rest of sketch. + * } + * + * + * Left-clicking and dragging or swipe motion will rotate the camera position + * about the center of the sketch. Right-clicking and dragging or multi-swipe + * will pan the camera position without rotation. Using the mouse wheel + * (scrolling) or pinch in/out will move the camera further or closer from the + * center of the sketch. + * + * The first three parameters, `sensitivityX`, `sensitivityY`, and + * `sensitivityZ`, are optional. They’re numbers that set the sketch’s + * sensitivity to movement along each axis. For example, calling + * `orbitControl(1, 2, -1)` keeps movement along the x-axis at its default + * value, makes the sketch twice as sensitive to movement along the y-axis, + * and reverses motion along the z-axis. By default, all sensitivity values + * are 1. + * + * The fourth parameter, `options`, is also optional. It’s an object that + * changes the behavior of orbiting. For example, calling + * `orbitControl(1, 1, 1, options)` keeps the default sensitivity values while + * changing the behaviors set with `options`. The object can have the + * following properties: + * + * + * let options = { + * // Setting this to false makes mobile interactions smoother by + * // preventing accidental interactions with the page while orbiting. + * // By default, it's true. + * disableTouchActions: true, + * + * // Setting this to true makes the camera always rotate in the + * // direction the mouse/touch is moving. + * // By default, it's false. + * freeRotation: false + * }; + * + * orbitControl(1, 1, 1, options); + * + * + * @method orbitControl + * @for p5 + * @param {Number} [sensitivityX] sensitivity to movement along the x-axis. Defaults to 1. + * @param {Number} [sensitivityY] sensitivity to movement along the y-axis. Defaults to 1. + * @param {Number} [sensitivityZ] sensitivity to movement along the z-axis. Defaults to 1. + * @param {Object} [options] object with two optional properties, `disableTouchActions` + * and `freeRotation`. Both are `Boolean`s. `disableTouchActions` + * defaults to `true` and `freeRotation` defaults to `false`. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the box. + * normalMaterial(); + * + * // Draw the box. + * box(30, 50); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * // Make the interactions 3X sensitive. + * orbitControl(3, 3, 3); + * + * // Style the box. + * normalMaterial(); + * + * // Draw the box. + * box(30, 50); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.'); + * } + * + * function draw() { + * background(200); + * + * // Create an options object. + * let options = { + * disableTouchActions: false, + * freeRotation: true + * }; + * + * // Enable orbiting with the mouse. + * // Prevent accidental touch actions on touchscreen devices + * // and enable free rotation. + * orbitControl(1, 1, 1, options); + * + * // Style the box. + * normalMaterial(); + * + * // Draw the box. + * box(30, 50); + * } + * + *
        + */ + // implementation based on three.js 'orbitControls': + // https://github.com/mrdoob/three.js/blob/6afb8595c0bf8b2e72818e42b64e6fe22707d896/examples/jsm/controls/OrbitControls.js#L22 + + _main.default.prototype.orbitControl = function (sensitivityX, sensitivityY, sensitivityZ, options) { + var _this = this; + this._assert3d('orbitControl'); + _main.default._validateParameters('orbitControl', arguments); + var cam = this._renderer._curCamera; + if (typeof sensitivityX === 'undefined') { + sensitivityX = 1; + } + if (typeof sensitivityY === 'undefined') { + sensitivityY = sensitivityX; + } + if (typeof sensitivityZ === 'undefined') { + sensitivityZ = 1; + } + if (_typeof(options) !== 'object') { + options = { + }; + } // default right-mouse and mouse-wheel behaviors (context menu and scrolling, + // respectively) are disabled here to allow use of those events for panning and + // zooming. However, whether or not to disable touch actions is an option. + // disable context menu for canvas element and add 'contextMenuDisabled' + // flag to p5 instance + + if (this.contextMenuDisabled !== true) { + this.canvas.oncontextmenu = function () { + return false; + }; + this._setProperty('contextMenuDisabled', true); + } // disable default scrolling behavior on the canvas element and add + // 'wheelDefaultDisabled' flag to p5 instance + + if (this.wheelDefaultDisabled !== true) { + this.canvas.onwheel = function () { + return false; + }; + this._setProperty('wheelDefaultDisabled', true); + } // disable default touch behavior on the canvas element and add + // 'touchActionsDisabled' flag to p5 instance + + var _options = options, + _options$disableTouch = _options.disableTouchActions, + disableTouchActions = _options$disableTouch === void 0 ? true : _options$disableTouch; + if (this.touchActionsDisabled !== true && disableTouchActions) { + this.canvas.style['touch-action'] = 'none'; + this._setProperty('touchActionsDisabled', true); + } // If option.freeRotation is true, the camera always rotates freely in the direction + // the pointer moves. default value is false (normal behavior) + + var _options2 = options, + _options2$freeRotatio = _options2.freeRotation, + freeRotation = _options2$freeRotatio === void 0 ? false : _options2$freeRotatio; // get moved touches. + var movedTouches = [ + ]; + this.touches.forEach(function (curTouch) { + _this._renderer.prevTouches.forEach(function (prevTouch) { + if (curTouch.id === prevTouch.id) { + var movedTouch = { + x: curTouch.x, + y: curTouch.y, + px: prevTouch.x, + py: prevTouch.y + }; + movedTouches.push(movedTouch); + } + }); + }); + this._renderer.prevTouches = this.touches; + // The idea of using damping is based on the following website. thank you. + // https://github.com/freshfork/p5.EasyCam/blob/9782964680f6a5c4c9bee825c475d9f2021d5134/p5.easycam.js#L1124 + // variables for interaction + var deltaRadius = 0; + var deltaTheta = 0; + var deltaPhi = 0; + var moveDeltaX = 0; + var moveDeltaY = 0; + // constants for dampingProcess + var damping = 0.85; + var rotateAccelerationFactor = 0.6; + var moveAccelerationFactor = 0.15; + // For touches, the appropriate scale is different + // because the distance difference is multiplied. + var mouseZoomScaleFactor = 0.01; + var touchZoomScaleFactor = 0.0004; + var scaleFactor = this.height < this.width ? this.height : this.width; + // Flag whether the mouse or touch pointer is inside the canvas + var pointersInCanvas = false; + // calculate and determine flags and variables. + if (movedTouches.length > 0) { + /* for touch */ + // if length === 1, rotate + // if length > 1, zoom and move + // for touch, it is calculated based on one moved touch pointer position. + pointersInCanvas = movedTouches[0].x > 0 && movedTouches[0].x < this.width && movedTouches[0].y > 0 && movedTouches[0].y < this.height; + if (movedTouches.length === 1) { + var t = movedTouches[0]; + deltaTheta = - sensitivityX * (t.x - t.px) / scaleFactor; + deltaPhi = sensitivityY * (t.y - t.py) / scaleFactor; + } else { + var t0 = movedTouches[0]; + var t1 = movedTouches[1]; + var distWithTouches = Math.hypot(t0.x - t1.x, t0.y - t1.y); + var prevDistWithTouches = Math.hypot(t0.px - t1.px, t0.py - t1.py); + var changeDist = distWithTouches - prevDistWithTouches; + // move the camera farther when the distance between the two touch points + // decreases, move the camera closer when it increases. + deltaRadius = - changeDist * sensitivityZ * touchZoomScaleFactor; + // Move the center of the camera along with the movement of + // the center of gravity of the two touch points. + moveDeltaX = 0.5 * (t0.x + t1.x) - 0.5 * (t0.px + t1.px); + moveDeltaY = 0.5 * (t0.y + t1.y) - 0.5 * (t0.py + t1.py); + } + if (this.touches.length > 0) { + if (pointersInCanvas) { + // Initiate an interaction if touched in the canvas + this._renderer.executeRotateAndMove = true; + this._renderer.executeZoom = true; + } + } else { + // End an interaction when the touch is released + this._renderer.executeRotateAndMove = false; + this._renderer.executeZoom = false; + } + } else { + /* for mouse */ + // if wheelDeltaY !== 0, zoom + // if mouseLeftButton is down, rotate + // if mouseRightButton is down, move + // For mouse, it is calculated based on the mouse position. + pointersInCanvas = this.mouseX > 0 && this.mouseX < this.width && this.mouseY > 0 && this.mouseY < this.height; + if (this._mouseWheelDeltaY !== 0) { + // zoom the camera depending on the value of _mouseWheelDeltaY. + // move away if positive, move closer if negative + deltaRadius = Math.sign(this._mouseWheelDeltaY) * sensitivityZ; + deltaRadius *= mouseZoomScaleFactor; + this._mouseWheelDeltaY = 0; + // start zoom when the mouse is wheeled within the canvas. + if (pointersInCanvas) this._renderer.executeZoom = true; + } else { + // quit zoom when you stop wheeling. + this._renderer.executeZoom = false; + } + if (this.mouseIsPressed) { + if (this.mouseButton === this.LEFT) { + deltaTheta = - sensitivityX * this.movedX / scaleFactor; + deltaPhi = sensitivityY * this.movedY / scaleFactor; + } else if (this.mouseButton === this.RIGHT) { + moveDeltaX = this.movedX; + moveDeltaY = this.movedY * cam.yScale; + } // start rotate and move when mouse is pressed within the canvas. + + if (pointersInCanvas) this._renderer.executeRotateAndMove = true; + } else { + // quit rotate and move if mouse is released. + this._renderer.executeRotateAndMove = false; + } + } // interactions + // zoom process + + if (deltaRadius !== 0 && this._renderer.executeZoom) { + // accelerate zoom velocity + this._renderer.zoomVelocity += deltaRadius; + } + if (Math.abs(this._renderer.zoomVelocity) > 0.001) { + // if freeRotation is true, we use _orbitFree() instead of _orbit() + if (freeRotation) { + cam._orbitFree(0, 0, this._renderer.zoomVelocity); + } else { + cam._orbit(0, 0, this._renderer.zoomVelocity); + } // In orthogonal projection, the scale does not change even if + // the distance to the gaze point is changed, so the projection matrix + // needs to be modified. + + if (cam.projMatrix.mat4[15] !== 0) { + cam.projMatrix.mat4[0] *= Math.pow(10, - this._renderer.zoomVelocity); + cam.projMatrix.mat4[5] *= Math.pow(10, - this._renderer.zoomVelocity); + // modify uPMatrix + this._renderer.uPMatrix.mat4[0] = cam.projMatrix.mat4[0]; + this._renderer.uPMatrix.mat4[5] = cam.projMatrix.mat4[5]; + } // damping + + this._renderer.zoomVelocity *= damping; + } else { + this._renderer.zoomVelocity = 0; + } // rotate process + + if ((deltaTheta !== 0 || deltaPhi !== 0) && this._renderer.executeRotateAndMove) { + // accelerate rotate velocity + this._renderer.rotateVelocity.add(deltaTheta * rotateAccelerationFactor, deltaPhi * rotateAccelerationFactor); + } + if (this._renderer.rotateVelocity.magSq() > 0.000001) { + // if freeRotation is true, the camera always rotates freely in the direction the pointer moves + if (freeRotation) { + cam._orbitFree( - this._renderer.rotateVelocity.x, this._renderer.rotateVelocity.y, 0); + } else { + cam._orbit(this._renderer.rotateVelocity.x, this._renderer.rotateVelocity.y, 0); + } // damping + + this._renderer.rotateVelocity.mult(damping); + } else { + this._renderer.rotateVelocity.set(0, 0); + } // move process + + if ((moveDeltaX !== 0 || moveDeltaY !== 0) && this._renderer.executeRotateAndMove) { + // Normalize movement distance + var ndcX = moveDeltaX * 2 / this.width; + var ndcY = - moveDeltaY * 2 / this.height; + // accelerate move velocity + this._renderer.moveVelocity.add(ndcX * moveAccelerationFactor, ndcY * moveAccelerationFactor); + } + if (this._renderer.moveVelocity.magSq() > 0.000001) { + // Translate the camera so that the entire object moves + // perpendicular to the line of sight when the mouse is moved + // or when the centers of gravity of the two touch pointers move. + var local = cam._getLocalAxes(); + // Calculate the z coordinate in the view coordinates of + // the center, that is, the distance to the view point + var diffX = cam.eyeX - cam.centerX; + var diffY = cam.eyeY - cam.centerY; + var diffZ = cam.eyeZ - cam.centerZ; + var viewZ = Math.sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ); + // position vector of the center. + var cv = new _main.default.Vector(cam.centerX, cam.centerY, cam.centerZ); + // Calculate the normalized device coordinates of the center. + cv = cam.cameraMatrix.multiplyPoint(cv); + cv = this._renderer.uPMatrix.multiplyAndNormalizePoint(cv); + // Move the center by this distance + // in the normalized device coordinate system. + cv.x -= this._renderer.moveVelocity.x; + cv.y -= this._renderer.moveVelocity.y; + // Calculate the translation vector + // in the direction perpendicular to the line of sight of center. + var dx, + dy; + var uP = this._renderer.uPMatrix.mat4; + if (uP[15] === 0) { + dx = (uP[8] + cv.x) / uP[0] * viewZ; + dy = (uP[9] + cv.y) / uP[5] * viewZ; + } else { + dx = (cv.x - uP[12]) / uP[0]; + dy = (cv.y - uP[13]) / uP[5]; + } // translate the camera. + + cam.setPosition(cam.eyeX + dx * local.x[0] + dy * local.y[0], cam.eyeY + dx * local.x[1] + dy * local.y[1], cam.eyeZ + dx * local.x[2] + dy * local.y[2]); + // damping + this._renderer.moveVelocity.mult(damping); + } else { + this._renderer.moveVelocity.set(0, 0); + } + return this; + }; + /** + * Adds a grid and an axes icon to clarify orientation in 3D sketches. + * + * `debugMode()` adds a grid that shows where the “ground” is in a sketch. By + * default, the grid will run through the origin `(0, 0, 0)` of the sketch + * along the XZ plane. `debugMode()` also adds an axes icon that points along + * the positive x-, y-, and z-axes. Calling `debugMode()` displays the grid + * and axes icon with their default size and position. + * + * There are four ways to call `debugMode()` with optional parameters to + * customize the debugging environment. + * + * The first way to call `debugMode()` has one parameter, `mode`. If the + * system constant `GRID` is passed, as in `debugMode(GRID)`, then the grid + * will be displayed and the axes icon will be hidden. If the constant `AXES` + * is passed, as in `debugMode(AXES)`, then the axes icon will be displayed + * and the grid will be hidden. + * + * The second way to call `debugMode()` has six parameters. The first + * parameter, `mode`, selects either `GRID` or `AXES` to be displayed. The + * next five parameters, `gridSize`, `gridDivisions`, `xOff`, `yOff`, and + * `zOff` are optional. They’re numbers that set the appearance of the grid + * (`gridSize` and `gridDivisions`) and the placement of the axes icon + * (`xOff`, `yOff`, and `zOff`). For example, calling + * `debugMode(20, 5, 10, 10, 10)` sets the `gridSize` to 20 pixels, the number + * of `gridDivisions` to 5, and offsets the axes icon by 10 pixels along the + * x-, y-, and z-axes. + * + * The third way to call `debugMode()` has five parameters. The first + * parameter, `mode`, selects either `GRID` or `AXES` to be displayed. The + * next four parameters, `axesSize`, `xOff`, `yOff`, and `zOff` are optional. + * They’re numbers that set the appearance of the size of the axes icon + * (`axesSize`) and its placement (`xOff`, `yOff`, and `zOff`). + * + * The fourth way to call `debugMode()` has nine optional parameters. The + * first five parameters, `gridSize`, `gridDivisions`, `gridXOff`, `gridYOff`, + * and `gridZOff` are numbers that set the appearance of the grid. For + * example, calling `debugMode(100, 5, 0, 0, 0)` sets the `gridSize` to 100, + * the number of `gridDivisions` to 5, and sets all the offsets to 0 so that + * the grid is centered at the origin. The next four parameters, `axesSize`, + * `xOff`, `yOff`, and `zOff` are numbers that set the appearance of the size + * of the axes icon (`axesSize`) and its placement (`axesXOff`, `axesYOff`, + * and `axesZOff`). For example, calling + * `debugMode(100, 5, 0, 0, 0, 50, 10, 10, 10)` sets the `gridSize` to 100, + * the number of `gridDivisions` to 5, and sets all the offsets to 0 so that + * the grid is centered at the origin. It then sets the `axesSize` to 50 and + * offsets the icon 10 pixels along each axis. + * + * @method debugMode + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Enable debug mode. + * debugMode(); + * + * describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the box. + * normalMaterial(); + * + * // Draw the box. + * box(20, 40); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Enable debug mode. + * // Only display the axes icon. + * debugMode(AXES); + * + * describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the box. + * normalMaterial(); + * + * // Draw the box. + * box(20, 40); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Enable debug mode. + * // Only display the grid and customize it: + * // - size: 50 + * // - divisions: 10 + * // - offsets: 0, 20, 0 + * debugMode(GRID, 50, 10, 0, 20, 0); + * + * describe('A multicolor box on a gray background. A grid is displayed below the box.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the box. + * normalMaterial(); + * + * // Draw the box. + * box(20, 40); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Enable debug mode. + * // Display the grid and axes icon and customize them: + * // Grid + * // ---- + * // - size: 50 + * // - divisions: 10 + * // - offsets: 0, 20, 0 + * // Axes + * // ---- + * // - size: 50 + * // - offsets: 0, 0, 0 + * debugMode(50, 10, 0, 20, 0, 50, 0, 0, 0); + * + * describe('A multicolor box on a gray background. A grid is displayed below the box. An axes icon is displayed at the center of the box.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the box. + * normalMaterial(); + * + * // Draw the box. + * box(20, 40); + * } + * + *
        + */ + /** + * @method debugMode + * @param {Constant} mode either GRID or AXES + */ + /** + * @method debugMode + * @param {Constant} mode + * @param {Number} [gridSize] side length of the grid. + * @param {Number} [gridDivisions] number of divisions in the grid. + * @param {Number} [xOff] offset from origin along the x-axis. + * @param {Number} [yOff] offset from origin along the y-axis. + * @param {Number} [zOff] offset from origin along the z-axis. + */ + /** + * @method debugMode + * @param {Constant} mode + * @param {Number} [axesSize] length of axes icon markers. + * @param {Number} [xOff] + * @param {Number} [yOff] + * @param {Number} [zOff] + */ + /** + * @method debugMode + * @param {Number} [gridSize] + * @param {Number} [gridDivisions] + * @param {Number} [gridXOff] grid offset from the origin along the x-axis. + * @param {Number} [gridYOff] grid offset from the origin along the y-axis. + * @param {Number} [gridZOff] grid offset from the origin along the z-axis. + * @param {Number} [axesSize] + * @param {Number} [axesXOff] axes icon offset from the origin along the x-axis. + * @param {Number} [axesYOff] axes icon offset from the origin along the y-axis. + * @param {Number} [axesZOff] axes icon offset from the origin along the z-axis. + */ + _main.default.prototype.debugMode = function () { + this._assert3d('debugMode'); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('debugMode', args); + // start by removing existing 'post' registered debug methods + for (var i = this._registeredMethods.post.length - 1; i >= 0; i--) { + // test for equality... + if (this._registeredMethods.post[i].toString() === this._grid().toString() || this._registeredMethods.post[i].toString() === this._axesIcon().toString()) { + this._registeredMethods.post.splice(i, 1); + } + } // then add new debugMode functions according to the argument list + + if (args[0] === constants.GRID) { + this.registerMethod('post', this._grid(args[1], args[2], args[3], args[4], args[5])); + } else if (args[0] === constants.AXES) { + this.registerMethod('post', this._axesIcon(args[1], args[2], args[3], args[4])); + } else { + this.registerMethod('post', this._grid(args[0], args[1], args[2], args[3], args[4])); + this.registerMethod('post', this._axesIcon(args[5], args[6], args[7], args[8])); + } + }; + /** + * Turns off debugMode() in a 3D sketch. + * + * @method noDebugMode + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Enable debug mode. + * debugMode(); + * + * describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box. They disappear when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the box. + * normalMaterial(); + * + * // Draw the box. box(20, 40); + * } + * + * // Disable debug mode when the user double-clicks. + * function doubleClicked() { + * noDebugMode(); + * } + * + *
        + */ + _main.default.prototype.noDebugMode = function () { + this._assert3d('noDebugMode'); + // start by removing existing 'post' registered debug methods + for (var i = this._registeredMethods.post.length - 1; i >= 0; i--) { + // test for equality... + if (this._registeredMethods.post[i].toString() === this._grid().toString() || this._registeredMethods.post[i].toString() === this._axesIcon().toString()) { + this._registeredMethods.post.splice(i, 1); + } + } + }; + /** + * For use with debugMode + * @private + * @method _grid + * @param {Number} [size] size of grid sides + * @param {Number} [div] number of grid divisions + * @param {Number} [xOff] offset of grid center from origin in X axis + * @param {Number} [yOff] offset of grid center from origin in Y axis + * @param {Number} [zOff] offset of grid center from origin in Z axis + */ + _main.default.prototype._grid = function (size, numDivs, xOff, yOff, zOff) { + if (typeof size === 'undefined') { + size = this.width / 2; + } + if (typeof numDivs === 'undefined') { + // ensure at least 2 divisions + numDivs = Math.round(size / 30) < 4 ? 4 : Math.round(size / 30); + } + if (typeof xOff === 'undefined') { + xOff = 0; + } + if (typeof yOff === 'undefined') { + yOff = 0; + } + if (typeof zOff === 'undefined') { + zOff = 0; + } + var spacing = size / numDivs; + var halfSize = size / 2; + return function () { + this.push(); + this.stroke(this._renderer.curStrokeColor[0] * 255, this._renderer.curStrokeColor[1] * 255, this._renderer.curStrokeColor[2] * 255); + this._renderer.uMVMatrix.set(this._renderer._curCamera.cameraMatrix); + // Lines along X axis + for (var q = 0; q <= numDivs; q++) { + this.beginShape(this.LINES); + this.vertex( - halfSize + xOff, yOff, q * spacing - halfSize + zOff); + this.vertex( + halfSize + xOff, yOff, q * spacing - halfSize + zOff); + this.endShape(); + } // Lines along Z axis + + for (var i = 0; i <= numDivs; i++) { + this.beginShape(this.LINES); + this.vertex(i * spacing - halfSize + xOff, yOff, - halfSize + zOff); + this.vertex(i * spacing - halfSize + xOff, yOff, + halfSize + zOff); + this.endShape(); + } + this.pop(); + }; + }; + /** + * For use with debugMode + * @private + * @method _axesIcon + * @param {Number} [size] size of axes icon lines + * @param {Number} [xOff] offset of icon from origin in X axis + * @param {Number} [yOff] offset of icon from origin in Y axis + * @param {Number} [zOff] offset of icon from origin in Z axis + */ + _main.default.prototype._axesIcon = function (size, xOff, yOff, zOff) { + if (typeof size === 'undefined') { + size = this.width / 20 > 40 ? this.width / 20 : 40; + } + if (typeof xOff === 'undefined') { + xOff = - this.width / 4; + } + if (typeof yOff === 'undefined') { + yOff = xOff; + } + if (typeof zOff === 'undefined') { + zOff = xOff; + } + return function () { + this.push(); + this._renderer.uMVMatrix.set(this._renderer._curCamera.cameraMatrix); + // X axis + this.strokeWeight(2); + this.stroke(255, 0, 0); + this.beginShape(this.LINES); + this.vertex(xOff, yOff, zOff); + this.vertex(xOff + size, yOff, zOff); + this.endShape(); + // Y axis + this.stroke(0, 255, 0); + this.beginShape(this.LINES); + this.vertex(xOff, yOff, zOff); + this.vertex(xOff, yOff + size, zOff); + this.endShape(); + // Z axis + this.stroke(0, 0, 255); + this.beginShape(this.LINES); + this.vertex(xOff, yOff, zOff); + this.vertex(xOff, yOff, zOff + size); + this.endShape(); + this.pop(); + }; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.splice': 188, + 'core-js/modules/es.math.hypot': 193, + 'core-js/modules/es.math.sign': 195, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.for-each': 260, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 349: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.filter'); + _dereq_('core-js/modules/es.array.filter'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module 3D + * @submodule Lights + * @for p5 + * @requires core + */ + /** + * Creates a light that shines from all directions. + * + * Ambient light does not come from one direction. Instead, 3D shapes are + * lit evenly from all sides. Ambient lights are almost always used in + * combination with other types of lights. + * + * There are three ways to call `ambientLight()` with optional parameters to + * set the light’s color. + * + * The first way to call `ambientLight()` has two parameters, `gray` and + * `alpha`. `alpha` is optional. Grayscale and alpha values between 0 and 255 + * can be passed to set the ambient light’s color, as in `ambientLight(50)` or + * `ambientLight(50, 30)`. + * + * The second way to call `ambientLight()` has one parameter, color. A + * p5.Color object, an array of color values, or a + * CSS color string, as in `ambientLight('magenta')`, can be passed to set the + * ambient light’s color. + * + * The third way to call `ambientLight()` has four parameters, `v1`, `v2`, + * `v3`, and `alpha`. `alpha` is optional. RGBA, HSBA, or HSLA values can be + * passed to set the ambient light’s colors, as in `ambientLight(255, 0, 0)` + * or `ambientLight(255, 0, 0, 30)`. Color values will be interpreted using + * the current colorMode(). + * + * @method ambientLight + * @param {Number} v1 red or hue value in the current + * colorMode(). + * @param {Number} v2 green or saturation value in the current + * colorMode(). + * @param {Number} v3 blue, brightness, or lightness value in the current + * colorMode(). + * @param {Number} [alpha] alpha (transparency) value in the current + * colorMode(). + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click the canvas to turn on the light. + * + * let isLit = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere drawn against a gray background. The sphere appears to change color when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Control the light. + * if (isLit === true) { + * // Use a grayscale value of 80. + * ambientLight(80); + * } + * + * // Draw the sphere. + * sphere(30); + * } + * + * // Turn on the ambient light when the user double-clicks. + * function doubleClicked() { + * isLit = true; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A faded magenta sphere drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * // Use a p5.Color object. + * let c = color('orchid'); + * ambientLight(c); + * + * // Draw the sphere. + * sphere(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A faded magenta sphere drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * // Use a CSS color string. + * ambientLight('#DA70D6'); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A faded magenta sphere drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * // Use RGB values + * ambientLight(218, 112, 214); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + */ + /** + * @method ambientLight + * @param {Number} gray grayscale value between 0 and 255. + * @param {Number} [alpha] + * @chainable + */ + /** + * @method ambientLight + * @param {String} value color as a CSS string. + * @chainable + */ + /** + * @method ambientLight + * @param {Number[]} values color as an array of RGBA, HSBA, or HSLA + * values. + * @chainable + */ + /** + * @method ambientLight + * @param {p5.Color} color color as a p5.Color object. + * @chainable + */ + + _main.default.prototype.ambientLight = function (v1, v2, v3, a) { + this._assert3d('ambientLight'); + _main.default._validateParameters('ambientLight', arguments); + var color = this.color.apply(this, arguments); + this._renderer.ambientLightColors.push(color._array[0], color._array[1], color._array[2]); + this._renderer._enableLighting = true; + return this; + }; + /** + * Sets the specular color for lights. + * + * `specularColor()` affects lights that bounce off a surface in a preferred + * direction. These lights include + * directionalLight(), + * pointLight(), and + * spotLight(). The function helps to create + * highlights on p5.Geometry objects that are + * styled with specularMaterial(). If a + * geometry does not use + * specularMaterial(), then + * `specularColor()` will have no effect. + * + * Note: `specularColor()` doesn’t affect lights that bounce in all + * directions, including ambientLight() and + * imageLight(). + * + * There are three ways to call `specularColor()` with optional parameters to + * set the specular highlight color. + * + * The first way to call `specularColor()` has two optional parameters, `gray` + * and `alpha`. Grayscale and alpha values between 0 and 255, as in + * `specularColor(50)` or `specularColor(50, 80)`, can be passed to set the + * specular highlight color. + * + * The second way to call `specularColor()` has one optional parameter, + * `color`. A p5.Color object, an array of color + * values, or a CSS color string can be passed to set the specular highlight + * color. + * + * The third way to call `specularColor()` has four optional parameters, `v1`, + * `v2`, `v3`, and `alpha`. RGBA, HSBA, or HSLA values, as in + * `specularColor(255, 0, 0, 80)`, can be passed to set the specular highlight + * color. Color values will be interpreted using the current + * colorMode(). + * + * @method specularColor + * @param {Number} v1 red or hue value in the current + * colorMode(). + * @param {Number} v2 green or saturation value in the current + * colorMode(). + * @param {Number} v3 blue, brightness, or lightness value in the current + * colorMode(). + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white sphere drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // No specular color. + * // Draw the sphere. + * sphere(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click the canvas to add a point light. + * + * let isLit = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere drawn on a gray background. A spotlight starts shining when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the sphere. + * noStroke(); + * specularColor(100); + * specularMaterial(255, 255, 255); + * + * // Control the light. + * if (isLit === true) { + * // Add a white point light from the top-right. + * pointLight(255, 255, 255, 30, -20, 40); + * } + * + * // Draw the sphere. + * sphere(30); + * } + * + * // Turn on the point light when the user double-clicks. + * function doubleClicked() { + * isLit = true; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a specular highlight. + * // Use a p5.Color object. + * let c = color('dodgerblue'); + * specularColor(c); + * + * // Add a white point light from the top-right. + * pointLight(255, 255, 255, 30, -20, 40); + * + * // Style the sphere. + * noStroke(); + * + * // Add a white specular material. + * specularMaterial(255, 255, 255); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a specular highlight. + * // Use a CSS color string. + * specularColor('#1E90FF'); + * + * // Add a white point light from the top-right. + * pointLight(255, 255, 255, 30, -20, 40); + * + * // Style the sphere. + * noStroke(); + * + * // Add a white specular material. + * specularMaterial(255, 255, 255); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a specular highlight. + * // Use RGB values. + * specularColor(30, 144, 255); + * + * // Add a white point light from the top-right. + * pointLight(255, 255, 255, 30, -20, 40); + * + * // Style the sphere. + * noStroke(); + * + * // Add a white specular material. + * specularMaterial(255, 255, 255); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + */ + /** + * @method specularColor + * @param {Number} gray grayscale value between 0 and 255. + * @chainable + */ + /** + * @method specularColor + * @param {String} value color as a CSS string. + * @chainable + */ + /** + * @method specularColor + * @param {Number[]} values color as an array of RGBA, HSBA, or HSLA + * values. + * @chainable + */ + /** + * @method specularColor + * @param {p5.Color} color color as a p5.Color object. + * @chainable + */ + _main.default.prototype.specularColor = function (v1, v2, v3) { + this._assert3d('specularColor'); + _main.default._validateParameters('specularColor', arguments); + var color = this.color.apply(this, arguments); + this._renderer.specularColors = [ + color._array[0], + color._array[1], + color._array[2] + ]; + return this; + }; + /** + * Creates a light that shines in one direction. + * + * Directional lights don’t shine from a specific point. They’re like a sun + * that shines from somewhere offscreen. The light’s direction is set using + * three `(x, y, z)` values between -1 and 1. For example, setting a light’s + * direction as `(1, 0, 0)` will light p5.Geometry + * objects from the left since the light faces directly to the right. + * + * There are four ways to call `directionalLight()` with parameters to set the + * light’s color and direction. + * + * The first way to call `directionalLight()` has six parameters. The first + * three parameters, `v1`, `v2`, and `v3`, set the light’s color using the + * current colorMode(). The last three + * parameters, `x`, `y`, and `z`, set the light’s direction. For example, + * `directionalLight(255, 0, 0, 1, 0, 0)` creates a red `(255, 0, 0)` light + * that shines to the right `(1, 0, 0)`. + * + * The second way to call `directionalLight()` has four parameters. The first + * three parameters, `v1`, `v2`, and `v3`, set the light’s color using the + * current colorMode(). The last parameter, + * `direction` sets the light’s direction using a + * p5.Geometry object. For example, + * `directionalLight(255, 0, 0, lightDir)` creates a red `(255, 0, 0)` light + * that shines in the direction the `lightDir` vector points. + * + * The third way to call `directionalLight()` has four parameters. The first + * parameter, `color`, sets the light’s color using a + * p5.Color object or an array of color values. The + * last three parameters, `x`, `y`, and `z`, set the light’s direction. For + * example, `directionalLight(myColor, 1, 0, 0)` creates a light that shines + * to the right `(1, 0, 0)` with the color value of `myColor`. + * + * The fourth way to call `directionalLight()` has two parameters. The first + * parameter, `color`, sets the light’s color using a + * p5.Color object or an array of color values. The + * second parameter, `direction`, sets the light’s direction using a + * p5.Color object. For example, + * `directionalLight(myColor, lightDir)` creates a light that shines in the + * direction the `lightDir` vector points with the color value of `myColor`. + * + * @method directionalLight + * @param {Number} v1 red or hue value in the current + * colorMode(). + * @param {Number} v2 green or saturation value in the current + * colorMode(). + * @param {Number} v3 blue, brightness, or lightness value in the current + * colorMode(). + * @param {Number} x x-component of the light's direction between -1 and 1. + * @param {Number} y y-component of the light's direction between -1 and 1. + * @param {Number} z z-component of the light's direction between -1 and 1. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click to turn on the directional light. + * + * let isLit = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere drawn on a gray background. A red light starts shining from above when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Control the light. + * if (isLit === true) { + * // Add a red directional light from above. + * // Use RGB values and XYZ directions. + * directionalLight(255, 0, 0, 0, 1, 0); + * } + * + * // Style the sphere. + * noStroke(); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a red directional light from above. + * // Use a p5.Color object and XYZ directions. + * let c = color(255, 0, 0); + * directionalLight(c, 0, 1, 0); + * + * // Style the sphere. + * noStroke(); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a red directional light from above. + * // Use a p5.Color object and a p5.Vector object. + * let c = color(255, 0, 0); + * let lightDir = createVector(0, 1, 0); + * directionalLight(c, lightDir); + * + * // Style the sphere. + * noStroke(); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + */ + /** + * @method directionalLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {p5.Vector} direction direction of the light as a + * p5.Vector object. + * @chainable + */ + /** + * @method directionalLight + * @param {p5.Color|Number[]|String} color color as a p5.Color object, + * an array of color values, or as a CSS string. + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @chainable + */ + /** + * @method directionalLight + * @param {p5.Color|Number[]|String} color + * @param {p5.Vector} direction + * @chainable + */ + _main.default.prototype.directionalLight = function (v1, v2, v3, x, y, z) { + this._assert3d('directionalLight'); + _main.default._validateParameters('directionalLight', arguments); + //@TODO: check parameters number + var color; + if (v1 instanceof _main.default.Color) { + color = v1; + } else { + color = this.color(v1, v2, v3); + } + var _x, + _y, + _z; + var v = arguments[arguments.length - 1]; + if (typeof v === 'number') { + _x = arguments[arguments.length - 3]; + _y = arguments[arguments.length - 2]; + _z = arguments[arguments.length - 1]; + } else { + _x = v.x; + _y = v.y; + _z = v.z; + } // normalize direction + + var l = Math.sqrt(_x * _x + _y * _y + _z * _z); + this._renderer.directionalLightDirections.push(_x / l, _y / l, _z / l); + this._renderer.directionalLightDiffuseColors.push(color._array[0], color._array[1], color._array[2]); + Array.prototype.push.apply(this._renderer.directionalLightSpecularColors, this._renderer.specularColors); + this._renderer._enableLighting = true; + return this; + }; + /** + * Creates a light that shines from a point in all directions. + * + * Point lights are like light bulbs that shine in all directions. They can be + * placed at different positions to achieve different lighting effects. A + * maximum of 5 point lights can be active at once. + * + * There are four ways to call `pointLight()` with parameters to set the + * light’s color and position. + * + * The first way to call `pointLight()` has six parameters. The first three + * parameters, `v1`, `v2`, and `v3`, set the light’s color using the current + * colorMode(). The last three parameters, `x`, + * `y`, and `z`, set the light’s position. For example, + * `pointLight(255, 0, 0, 50, 0, 0)` creates a red `(255, 0, 0)` light that + * shines from the coordinates `(50, 0, 0)`. + * + * The second way to call `pointLight()` has four parameters. The first three + * parameters, `v1`, `v2`, and `v3`, set the light’s color using the current + * colorMode(). The last parameter, position sets + * the light’s position using a p5.Vector object. + * For example, `pointLight(255, 0, 0, lightPos)` creates a red `(255, 0, 0)` + * light that shines from the position set by the `lightPos` vector. + * + * The third way to call `pointLight()` has four parameters. The first + * parameter, `color`, sets the light’s color using a + * p5.Color object or an array of color values. The + * last three parameters, `x`, `y`, and `z`, set the light’s position. For + * example, `directionalLight(myColor, 50, 0, 0)` creates a light that shines + * from the coordinates `(50, 0, 0)` with the color value of `myColor`. + * + * The fourth way to call `pointLight()` has two parameters. The first + * parameter, `color`, sets the light’s color using a + * p5.Color object or an array of color values. The + * second parameter, `position`, sets the light’s position using a + * p5.Vector object. For example, + * `directionalLight(myColor, lightPos)` creates a light that shines from the + * position set by the `lightPos` vector with the color value of `myColor`. + * + * @method pointLight + * @param {Number} v1 red or hue value in the current + * colorMode(). + * @param {Number} v2 green or saturation value in the current + * colorMode(). + * @param {Number} v3 blue, brightness, or lightness value in the current + * colorMode(). + * @param {Number} x x-coordinate of the light. + * @param {Number} y y-coordinate of the light. + * @param {Number} z z-coordinate of the light. + * @chainable + * + * @example + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click to turn on the point light. + * + * let isLit = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere drawn on a gray background. A red light starts shining from above when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Control the light. + * if (isLit === true) { + * // Add a red point light from above. + * // Use RGB values and XYZ coordinates. + * pointLight(255, 0, 0, 0, -150, 0); + * } + * + * // Style the sphere. + * noStroke(); + * + * // Draw the sphere. + * sphere(30); + * } + * + * // Turn on the point light when the user double-clicks. + * function doubleClicked() { + * isLit = true; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a red point light from above. + * // Use a p5.Color object and XYZ directions. + * let c = color(255, 0, 0); + * pointLight(c, 0, -150, 0); + * + * // Style the sphere. + * noStroke(); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a red point light from above. + * // Use a p5.Color object and a p5.Vector object. + * let c = color(255, 0, 0); + * let lightPos = createVector(0, -150, 0); + * pointLight(c, lightPos); + * + * // Style the sphere. + * noStroke(); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('Four spheres arranged in a square and drawn on a gray background. The spheres appear bright red toward the center of the square. The color gets darker toward the corners of the square.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a red point light that points to the center of the scene. + * // Use a p5.Color object and a p5.Vector object. + * let c = color(255, 0, 0); + * let lightPos = createVector(0, 0, 65); + * pointLight(c, lightPos); + * + * // Style the spheres. + * noStroke(); + * + * // Draw a sphere up and to the left. + * push(); + * translate(-25, -25, 25); + * sphere(10); + * pop(); + * + * // Draw a box up and to the right. + * push(); + * translate(25, -25, 25); + * sphere(10); + * pop(); + * + * // Draw a sphere down and to the left. + * push(); + * translate(-25, 25, 25); + * sphere(10); + * pop(); + * + * // Draw a box down and to the right. + * push(); + * translate(25, 25, 25); + * sphere(10); + * pop(); + * } + * + *
        + */ + /** + * @method pointLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {p5.Vector} position position of the light as a + * p5.Vector object. + * @chainable + */ + /** + * @method pointLight + * @param {p5.Color|Number[]|String} color color as a p5.Color object, + * an array of color values, or a CSS string. + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @chainable + */ + /** + * @method pointLight + * @param {p5.Color|Number[]|String} color + * @param {p5.Vector} position + * @chainable + */ + _main.default.prototype.pointLight = function (v1, v2, v3, x, y, z) { + this._assert3d('pointLight'); + _main.default._validateParameters('pointLight', arguments); + //@TODO: check parameters number + var color; + if (v1 instanceof _main.default.Color) { + color = v1; + } else { + color = this.color(v1, v2, v3); + } + var _x, + _y, + _z; + var v = arguments[arguments.length - 1]; + if (typeof v === 'number') { + _x = arguments[arguments.length - 3]; + _y = arguments[arguments.length - 2]; + _z = arguments[arguments.length - 1]; + } else { + _x = v.x; + _y = v.y; + _z = v.z; + } + this._renderer.pointLightPositions.push(_x, _y, _z); + this._renderer.pointLightDiffuseColors.push(color._array[0], color._array[1], color._array[2]); + Array.prototype.push.apply(this._renderer.pointLightSpecularColors, this._renderer.specularColors); + this._renderer._enableLighting = true; + return this; + }; + /** + * Creates an ambient light from an image. + * + * `imageLight()` simulates a light shining from all directions. The effect is + * like placing the sketch at the center of a giant sphere that uses the image + * as its texture. The image's diffuse light will be affected by + * fill() and the specular reflections will be + * affected by specularMaterial() and + * shininess(). + * + * The parameter, `img`, is the p5.Image object to + * use as the light source. + * + * @method imageLight + * @param {p5.image} img image to use as the light source. + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let img; + * + * // Load an image and create a p5.Image object. + * function preload() { + * img = loadImage('assets/outdoor_spheremap.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere floating above a landscape. The surface of the sphere reflects the landscape.'); + * } + * + * function draw() { + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the image as a panorama (360˚ background). + * panorama(img); + * + * // Add a soft ambient light. + * ambientLight(50); + * + * // Add light from the image. + * imageLight(img); + * + * // Style the sphere. + * specularMaterial(20); + * shininess(100); + * noStroke(); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + */ + _main.default.prototype.imageLight = function (img) { + // activeImageLight property is checked by _setFillUniforms + // for sending uniforms to the fillshader + this._renderer.activeImageLight = img; + this._renderer._enableLighting = true; + }; + /** + * Creates an immersive 3D background. + * + * `panorama()` transforms images containing 360˚ content, such as maps or + * HDRIs, into immersive 3D backgrounds that surround a sketch. Exploring the + * space requires changing the camera's perspective with functions such as + * orbitControl() or + * camera(). + * + * @method panorama + * @param {p5.Image} img 360˚ image to use as the background. + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let img; + * + * // Load an image and create a p5.Image object. + * function preload() { + * img = loadImage('assets/outdoor_spheremap.jpg'); + * } + * + * function setup() { + * createCanvas(100 ,100 ,WEBGL); + * + * describe('A sphere floating above a landscape. The surface of the sphere reflects the landscape. The full landscape is viewable in 3D as the user drags the mouse.'); + * } + * + * function draw() { + * // Add the panorama. + * panorama(img); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Use the image as a light source. + * imageLight(img); + * + * // Style the sphere. + * noStroke(); + * specularMaterial(50); + * shininess(200); + * metalness(100); + * + * // Draw the sphere. + * sphere(30); + * } + * + *
        + */ + _main.default.prototype.panorama = function (img) { + this.filter(this._renderer._getSphereMapping(img)); + }; + /** + * Places an ambient and directional light in the scene. + * The lights are set to ambientLight(128, 128, 128) and + * directionalLight(128, 128, 128, 0, 0, -1). + * + * Note: lights need to be called (whether directly or indirectly) + * within draw() to remain persistent in a looping program. + * Placing them in setup() will cause them to only have an effect + * the first time through the loop. + * + * @method lights + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click to turn on the lights. + * + * let isLit = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white box drawn against a gray background. The quality of the light changes when the user double-clicks.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Control the lights. + * if (isLit === true) { + * lights(); + * } + * + * // Draw the box. + * box(); + * } + * + * // Turn on the lights when the user double-clicks. + * function doubleClicked() { + * isLit = true; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white box drawn against a gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * ambientLight(128, 128, 128); + * directionalLight(128, 128, 128, 0, 0, -1); + * + * // Draw the box. + * box(); + * } + * + *
        + */ + _main.default.prototype.lights = function () { + this._assert3d('lights'); + // Both specify gray by default. + var grayColor = this.color('rgb(128,128,128)'); + this.ambientLight(grayColor); + this.directionalLight(grayColor, 0, 0, - 1); + return this; + }; + /** + * Sets the falloff rate for pointLight() + * and spotLight(). + * + * A light’s falloff describes the intensity of its beam at a distance. For + * example, a lantern has a slow falloff, a flashlight has a medium falloff, + * and a laser pointer has a sharp falloff. + * + * `lightFalloff()` has three parameters, `constant`, `linear`, and + * `quadratic`. They’re numbers used to calculate falloff at a distance, `d`, + * as follows: + * + * `falloff = 1 / (constant + d * linear + (d * d) * quadratic)` + * + * Note: `constant`, `linear`, and `quadratic` should always be set to values + * greater than 0. + * + * @method lightFalloff + * @param {Number} constant constant value for calculating falloff. + * @param {Number} linear linear value for calculating falloff. + * @param {Number} quadratic quadratic value for calculating falloff. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click to change the falloff rate. + * + * let useFalloff = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A sphere drawn against a gray background. The intensity of the light changes when the user double-clicks.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Set the light falloff. + * if (useFalloff === true) { + * lightFalloff(2, 0, 0); + * } + * + * // Add a white point light from the front. + * pointLight(255, 255, 255, 0, 0, 100); + * + * // Style the sphere. + * noStroke(); + * + * // Draw the sphere. + * sphere(30); + * } + * + * // Change the falloff value when the user double-clicks. + * function doubleClicked() { + * useFalloff = true; + * } + * + *
        + */ + _main.default.prototype.lightFalloff = function (constantAttenuation, linearAttenuation, quadraticAttenuation) { + this._assert3d('lightFalloff'); + _main.default._validateParameters('lightFalloff', arguments); + if (constantAttenuation < 0) { + constantAttenuation = 0; + console.warn('Value of constant argument in lightFalloff() should be never be negative. Set to 0.'); + } + if (linearAttenuation < 0) { + linearAttenuation = 0; + console.warn('Value of linear argument in lightFalloff() should be never be negative. Set to 0.'); + } + if (quadraticAttenuation < 0) { + quadraticAttenuation = 0; + console.warn('Value of quadratic argument in lightFalloff() should be never be negative. Set to 0.'); + } + if (constantAttenuation === 0 && linearAttenuation === 0 && quadraticAttenuation === 0) { + constantAttenuation = 1; + console.warn('Either one of the three arguments in lightFalloff() should be greater than zero. Set constant argument to 1.'); + } + this._renderer.constantAttenuation = constantAttenuation; + this._renderer.linearAttenuation = linearAttenuation; + this._renderer.quadraticAttenuation = quadraticAttenuation; + return this; + }; + /** + * Creates a light that shines from a point in one direction. + * + * Spot lights are like flashlights that shine in one direction creating a + * cone of light. The shape of the cone can be controlled using the angle and + * concentration parameters. A maximum of 5 spot lights can be active at once. + * + * There are eight ways to call `spotLight()` with parameters to set the + * light’s color, position, direction. For example, + * `spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0)` creates a red `(255, 0, 0)` light + * at the origin `(0, 0, 0)` that points to the right `(1, 0, 0)`. + * + * The `angle` parameter is optional. It sets the radius of the light cone. + * For example, `spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16)` creates a + * red `(255, 0, 0)` light at the origin `(0, 0, 0)` that points to the right + * `(1, 0, 0)` with an angle of `PI / 16` radians. By default, `angle` is + * `PI / 3` radians. + * + * The `concentration` parameter is also optional. It focuses the light + * towards the center of the light cone. For example, + * `spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16, 50)` creates a red + * `(255, 0, 0)` light at the origin `(0, 0, 0)` that points to the right + * `(1, 0, 0)` with an angle of `PI / 16` radians at concentration of 50. By + * default, `concentration` is 100. + * + * @method spotLight + * @param {Number} v1 red or hue value in the current + * colorMode(). + * @param {Number} v2 green or saturation value in the current + * colorMode(). + * @param {Number} v3 blue, brightness, or lightness value in the current + * colorMode(). + * @param {Number} x x-coordinate of the light. + * @param {Number} y y-coordinate of the light. + * @param {Number} z z-coordinate of the light. + * @param {Number} rx x-component of light direction between -1 and 1. + * @param {Number} ry y-component of light direction between -1 and 1. + * @param {Number} rz z-component of light direction between -1 and 1. + * @param {Number} [angle] angle of the light cone. Defaults to `PI / 3`. + * @param {Number} [concentration] concentration of the light. Defaults to 100. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click to adjust the spotlight. + * + * let isLit = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white sphere drawn on a gray background. A red spotlight starts shining when the user double-clicks.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Control the spotlight. + * if (isLit === true) { + * // Add a red spot light that shines into the screen. + * // Set its angle to PI / 32 radians. + * spotLight(255, 0, 0, 0, 0, 100, 0, 0, -1, PI / 32); + * } + * + * // Draw the sphere. + * sphere(30); + * } + * + * // Turn on the spotlight when the user double-clicks. + * function doubleClicked() { + * isLit = true; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click to adjust the spotlight. + * + * let isLit = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white sphere drawn on a gray background. A red spotlight starts shining when the user double-clicks.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Control the spotlight. + * if (isLit === true) { + * // Add a red spot light that shines into the screen. + * // Set its angle to PI / 3 radians (default). + * // Set its concentration to 1000. + * let c = color(255, 0, 0); + * let position = createVector(0, 0, 100); + * let direction = createVector(0, 0, -1); + * spotLight(c, position, direction, PI / 3, 1000); + * } + * + * // Draw the sphere. + * sphere(30); + * } + * + * // Turn on the spotlight when the user double-clicks. + * function doubleClicked() { + * isLit = true; + * } + * + *
        + */ + /** + * @method spotLight + * @param {p5.Color|Number[]|String} color color as a p5.Color object, + * an array of color values, or a CSS string. + * @param {p5.Vector} position position of the light as a p5.Vector object. + * @param {p5.Vector} direction direction of light as a p5.Vector object. + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {p5.Vector} position + * @param {p5.Vector} direction + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {p5.Color|Number[]|String} color + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {p5.Vector} direction + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {p5.Color|Number[]|String} color + * @param {p5.Vector} position + * @param {Number} rx + * @param {Number} ry + * @param {Number} rz + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {p5.Vector} direction + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {Number} v1 + * @param {Number} v2 + * @param {Number} v3 + * @param {p5.Vector} position + * @param {Number} rx + * @param {Number} ry + * @param {Number} rz + * @param {Number} [angle] + * @param {Number} [concentration] + */ + /** + * @method spotLight + * @param {p5.Color|Number[]|String} color + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {Number} rx + * @param {Number} ry + * @param {Number} rz + * @param {Number} [angle] + * @param {Number} [concentration] + */ + _main.default.prototype.spotLight = function (v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration) { + this._assert3d('spotLight'); + _main.default._validateParameters('spotLight', arguments); + var color, + position, + direction; + var length = arguments.length; + switch (length) { + case 11: + case 10: + color = this.color(v1, v2, v3); + position = new _main.default.Vector(x, y, z); + direction = new _main.default.Vector(nx, ny, nz); + break; + case 9: + if (v1 instanceof _main.default.Color) { + color = v1; + position = new _main.default.Vector(v2, v3, x); + direction = new _main.default.Vector(y, z, nx); + angle = ny; + concentration = nz; + } else if (x instanceof _main.default.Vector) { + color = this.color(v1, v2, v3); + position = x; + direction = new _main.default.Vector(y, z, nx); + angle = ny; + concentration = nz; + } else if (nx instanceof _main.default.Vector) { + color = this.color(v1, v2, v3); + position = new _main.default.Vector(x, y, z); + direction = nx; + angle = ny; + concentration = nz; + } else { + color = this.color(v1, v2, v3); + position = new _main.default.Vector(x, y, z); + direction = new _main.default.Vector(nx, ny, nz); + } + break; + case 8: + if (v1 instanceof _main.default.Color) { + color = v1; + position = new _main.default.Vector(v2, v3, x); + direction = new _main.default.Vector(y, z, nx); + angle = ny; + } else if (x instanceof _main.default.Vector) { + color = this.color(v1, v2, v3); + position = x; + direction = new _main.default.Vector(y, z, nx); + angle = ny; + } else { + color = this.color(v1, v2, v3); + position = new _main.default.Vector(x, y, z); + direction = nx; + angle = ny; + } + break; + case 7: + if (v1 instanceof _main.default.Color && v2 instanceof _main.default.Vector) { + color = v1; + position = v2; + direction = new _main.default.Vector(v3, x, y); + angle = z; + concentration = nx; + } else if (v1 instanceof _main.default.Color && y instanceof _main.default.Vector) { + color = v1; + position = new _main.default.Vector(v2, v3, x); + direction = y; + angle = z; + concentration = nx; + } else if (x instanceof _main.default.Vector && y instanceof _main.default.Vector) { + color = this.color(v1, v2, v3); + position = x; + direction = y; + angle = z; + concentration = nx; + } else if (v1 instanceof _main.default.Color) { + color = v1; + position = new _main.default.Vector(v2, v3, x); + direction = new _main.default.Vector(y, z, nx); + } else if (x instanceof _main.default.Vector) { + color = this.color(v1, v2, v3); + position = x; + direction = new _main.default.Vector(y, z, nx); + } else { + color = this.color(v1, v2, v3); + position = new _main.default.Vector(x, y, z); + direction = nx; + } + break; + case 6: + if (x instanceof _main.default.Vector && y instanceof _main.default.Vector) { + color = this.color(v1, v2, v3); + position = x; + direction = y; + angle = z; + } else if (v1 instanceof _main.default.Color && y instanceof _main.default.Vector) { + color = v1; + position = new _main.default.Vector(v2, v3, x); + direction = y; + angle = z; + } else if (v1 instanceof _main.default.Color && v2 instanceof _main.default.Vector) { + color = v1; + position = v2; + direction = new _main.default.Vector(v3, x, y); + angle = z; + } + break; + case 5: + if (v1 instanceof _main.default.Color && v2 instanceof _main.default.Vector && v3 instanceof _main.default.Vector) { + color = v1; + position = v2; + direction = v3; + angle = x; + concentration = y; + } else if (x instanceof _main.default.Vector && y instanceof _main.default.Vector) { + color = this.color(v1, v2, v3); + position = x; + direction = y; + } else if (v1 instanceof _main.default.Color && y instanceof _main.default.Vector) { + color = v1; + position = new _main.default.Vector(v2, v3, x); + direction = y; + } else if (v1 instanceof _main.default.Color && v2 instanceof _main.default.Vector) { + color = v1; + position = v2; + direction = new _main.default.Vector(v3, x, y); + } + break; + case 4: + color = v1; + position = v2; + direction = v3; + angle = x; + break; + case 3: + color = v1; + position = v2; + direction = v3; + break; + default: + console.warn('Sorry, input for spotlight() is not in prescribed format. Too '.concat(length < 3 ? 'few' : 'many', ' arguments were provided')); + return this; + } + this._renderer.spotLightDiffuseColors.push(color._array[0], color._array[1], color._array[2]); + Array.prototype.push.apply(this._renderer.spotLightSpecularColors, this._renderer.specularColors); + this._renderer.spotLightPositions.push(position.x, position.y, position.z); + direction.normalize(); + this._renderer.spotLightDirections.push(direction.x, direction.y, direction.z); + if (angle === undefined) { + angle = Math.PI / 3; + } + if (concentration !== undefined && concentration < 1) { + concentration = 1; + console.warn('Value of concentration needs to be greater than 1. Setting it to 1'); + } else if (concentration === undefined) { + concentration = 100; + } + angle = this._renderer._pInst._toRadians(angle); + this._renderer.spotLightAngle.push(Math.cos(angle)); + this._renderer.spotLightConc.push(concentration); + this._renderer._enableLighting = true; + return this; + }; + /** + * Removes all lights from the sketch. + * + * Calling `noLights()` removes any lights created with + * lights(), + * ambientLight(), + * directionalLight(), + * pointLight(), or + * spotLight(). These functions may be called + * after `noLights()` to create a new lighting scheme. + * + * @method noLights + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('Two spheres drawn against a gray background. The top sphere is white and the bottom sphere is red.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the spheres. + * noStroke(); + * + * // Draw the top sphere. + * push(); + * translate(0, -25, 0); + * sphere(20); + * pop(); + * + * // Turn off the lights. + * noLights(); + * + * // Add a red directional light that points into the screen. + * directionalLight(255, 0, 0, 0, 0, -1); + * + * // Draw the bottom sphere. + * push(); + * translate(0, 25, 0); + * sphere(20); + * pop(); + * } + * + *
        + */ + _main.default.prototype.noLights = function () { + this._assert3d('noLights'); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('noLights', args); + this._renderer.activeImageLight = null; + this._renderer._enableLighting = false; + this._renderer.ambientLightColors.length = 0; + this._renderer.specularColors = [ + 1, + 1, + 1 + ]; + this._renderer.directionalLightDirections.length = 0; + this._renderer.directionalLightDiffuseColors.length = 0; + this._renderer.directionalLightSpecularColors.length = 0; + this._renderer.pointLightPositions.length = 0; + this._renderer.pointLightDiffuseColors.length = 0; + this._renderer.pointLightSpecularColors.length = 0; + this._renderer.spotLightPositions.length = 0; + this._renderer.spotLightDirections.length = 0; + this._renderer.spotLightDiffuseColors.length = 0; + this._renderer.spotLightSpecularColors.length = 0; + this._renderer.spotLightAngle.length = 0; + this._renderer.spotLightConc.length = 0; + this._renderer.constantAttenuation = 1; + this._renderer.linearAttenuation = 0; + this._renderer.quadraticAttenuation = 0; + this._renderer._useShininess = 1; + this._renderer._useMetalness = 0; + return this; + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.filter': 174 + } + ], + 350: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.splice'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.promise'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.match'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.trim'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + _dereq_('regenerator-runtime/runtime'); + var _main = _interopRequireDefault(_dereq_('../core/main')); + _dereq_('./p5.Geometry'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value); + } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err); + } + _next(undefined); + }); + }; + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } /** + * @module Shape + * @submodule 3D Models + * @for p5 + * @requires core + * @requires p5.Geometry + */ + /** + * Loads a 3D model to create a + * p5.Geometry object. + * + * `loadModel()` can load 3D models from OBJ and STL files. Once the model is + * loaded, it can be displayed with the + * model() function, as in `model(shape)`. + * + * There are three ways to call `loadModel()` with optional parameters to help + * process the model. + * + * The first parameter, `path`, is always a `String` with the path to the + * file. Paths to local files should be relative, as in + * `loadModel('assets/model.obj')`. URLs such as + * `'https://example.com/model.obj'` may be blocked due to browser security. + * + * The first way to call `loadModel()` has three optional parameters after the + * file path. The first optional parameter, `successCallback`, is a function + * to call once the model loads. For example, + * `loadModel('assets/model.obj', handleModel)` will call the `handleModel()` + * function once the model loads. The second optional parameter, + * `failureCallback`, is a function to call if the model fails to load. For + * example, `loadModel('assets/model.obj', handleModel, handleFailure)` will + * call the `handleFailure()` function if an error occurs while loading. The + * third optional parameter, `fileType`, is the model’s file extension as a + * string. For example, + * `loadModel('assets/model', handleModel, handleFailure, '.obj')` will try to + * load the file model as a `.obj` file. + * + * The second way to call `loadModel()` has four optional parameters after the + * file path. The first optional parameter is a `Boolean` value. If `true` is + * passed, as in `loadModel('assets/model.obj', true)`, then the model will be + * resized to ensure it fits the canvas. The next three parameters are + * `successCallback`, `failureCallback`, and `fileType` as described above. + * + * The third way to call `loadModel()` has one optional parameter after the + * file path. The optional parameter, `options`, is an `Object` with options, + * as in `loadModel('assets/model.obj', options)`. The `options` object can + * have the following properties: + * + * + * let options = { + * // Enables standardized size scaling during loading if set to true. + * normalize: true, + * + * // Function to call once the model loads. + * successCallback: handleModel, + * + * // Function to call if an error occurs while loading. + * failureCallback: handleError, + * + * // Model's file extension. + * fileType: '.stl', + * + * // Flips the U texture coordinates of the model. + * flipU: false, + * + * // Flips the V texture coordinates of the model. + * flipV: false + * }; + * + * // Pass the options object to loadModel(). + * loadModel('assets/model.obj', options); + * + * + * Models can take time to load. Calling `loadModel()` in + * preload() ensures models load before they're + * used in setup() or draw(). + * + * Note: There’s no support for colored STL files. STL files with color will + * be rendered without color. + * + * @method loadModel + * @param {String} path path of the model to be loaded. + * @param {Boolean} normalize if `true`, scale the model to fit the canvas. + * @param {function(p5.Geometry)} [successCallback] function to call once the model is loaded. Will be passed + * the p5.Geometry object. + * @param {function(Event)} [failureCallback] function to call if the model fails to load. Will be passed an `Error` event object. + * @param {String} [fileType] model’s file extension. Either `'.obj'` or `'.stl'`. + * @return {p5.Geometry} the p5.Geometry object + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * // Load the file and create a p5.Geometry object. + * function preload() { + * shape = loadModel('assets/teapot.obj'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white teapot drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the shape. + * model(shape); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * // Load the file and create a p5.Geometry object. + * // Normalize the geometry's size to fit the canvas. + * function preload() { + * shape = loadModel('assets/teapot.obj', true); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white teapot drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the shape. + * model(shape); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * // Load the file and create a p5.Geometry object. + * function preload() { + * loadModel('assets/teapot.obj', true, handleModel); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white teapot drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the shape. + * model(shape); + * } + * + * // Set the shape variable and log the geometry's + * // ID to the console. + * function handleModel(data) { + * shape = data; + * console.log(shape.gid); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * // Load the file and create a p5.Geometry object. + * function preload() { + * loadModel('assets/wrong.obj', true, handleModel, handleError); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white teapot drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the shape. + * model(shape); + * } + * + * // Set the shape variable and print the geometry's + * // ID to the console. + * function handleModel(data) { + * shape = data; + * console.log(shape.gid); + * } + * + * // Print an error message if the file doesn't load. + * function handleError(error) { + * console.error('Oops!', error); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * // Load the file and create a p5.Geometry object. + * function preload() { + * loadModel('assets/teapot.obj', true, handleModel, handleError, '.obj'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white teapot drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the shape. + * model(shape); + * } + * + * // Set the shape variable and print the geometry's + * // ID to the console. + * function handleModel(data) { + * shape = data; + * console.log(shape.gid); + * } + * + * // Print an error message if the file doesn't load. + * function handleError(error) { + * console.error('Oops!', error); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * let options = { + * normalize: true, + * successCallback: handleModel, + * failureCallback: handleError, + * fileType: '.obj' + * }; + * + * // Load the file and create a p5.Geometry object. + * function preload() { + * loadModel('assets/teapot.obj', options); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white teapot drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the shape. + * model(shape); + * } + * + * // Set the shape variable and print the geometry's + * // ID to the console. + * function handleModel(data) { + * shape = data; + * console.log(shape.gid); + * } + * + * // Print an error message if the file doesn't load. + * function handleError(error) { + * console.error('Oops!', error); + * } + * + *
        + */ + /** + * @method loadModel + * @param {String} path + * @param {function(p5.Geometry)} [successCallback] + * @param {function(Event)} [failureCallback] + * @param {String} [fileType] + * @return {p5.Geometry} new p5.Geometry object. + */ + /** + * @method loadModel + * @param {String} path + * @param {Object} [options] loading options. + * @param {function(p5.Geometry)} [options.successCallback] + * @param {function(Event)} [options.failureCallback] + * @param {String} [options.fileType] + * @param {boolean} [options.normalize] + * @param {boolean} [options.flipU] + * @param {boolean} [options.flipV] + * @return {p5.Geometry} new p5.Geometry object. + */ + + _main.default.prototype.loadModel = function (path, options) { + _main.default._validateParameters('loadModel', arguments); + var normalize = false; + var successCallback; + var failureCallback; + var flipU = false; + var flipV = false; + var fileType = path.slice( - 4); + if (options && _typeof(options) === 'object') { + normalize = options.normalize || false; + successCallback = options.successCallback; + failureCallback = options.failureCallback; + fileType = options.fileType || fileType; + flipU = options.flipU || false; + flipV = options.flipV || false; + } else if (typeof options === 'boolean') { + normalize = options; + successCallback = arguments[2]; + failureCallback = arguments[3]; + if (typeof arguments[4] !== 'undefined') { + fileType = arguments[4]; + } + } else { + successCallback = typeof arguments[1] === 'function' ? arguments[1] : undefined; + failureCallback = arguments[2]; + if (typeof arguments[3] !== 'undefined') { + fileType = arguments[3]; + } + } + var model = new _main.default.Geometry(); + model.gid = ''.concat(path, '|').concat(normalize); + var self = this; + function getMaterials(_x) { + return _getMaterials.apply(this, arguments); + } + function _getMaterials() { + _getMaterials = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee2(lines) { + var parsedMaterialPromises, + i, + mtllibMatch, + parsedMaterials, + materials; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + parsedMaterialPromises = [ + ]; + for (i = 0; i < lines.length; i++) { + mtllibMatch = lines[i].match(/^mtllib (.+)/); + if (mtllibMatch) { + (function () { + var mtlPath = ''; + var mtlFilename = mtllibMatch[1]; + var objPathParts = path.split('/'); + if (objPathParts.length > 1) { + objPathParts.pop(); + var objFolderPath = objPathParts.join('/'); + mtlPath = objFolderPath + '/' + mtlFilename; + } else { + mtlPath = mtlFilename; + } + parsedMaterialPromises.push(fileExists(mtlPath).then(function (exists) { + if (exists) { + return parseMtl(self, mtlPath); + } else { + console.warn('MTL file not found or error in parsing; proceeding without materials: '.concat(mtlPath)); + return { + }; + } + }).catch(function (error) { + console.warn('Error loading MTL file: '.concat(mtlPath), error); + return { + }; + })); + }) (); + } + } + _context2.prev = 2; + _context2.next = 5; + return Promise.all(parsedMaterialPromises); + case 5: + parsedMaterials = _context2.sent; + materials = Object.assign.apply(Object, [ + { + } + ].concat(_toConsumableArray(parsedMaterials))); + return _context2.abrupt('return', materials); + case 10: + _context2.prev = 10; + _context2.t0 = _context2['catch'](2); + return _context2.abrupt('return', { + }); + case 13: + case 'end': + return _context2.stop(); + } + } + }, _callee2, null, [ + [2, + 10] + ]); + })); + return _getMaterials.apply(this, arguments); + } + function fileExists(_x2) { + return _fileExists.apply(this, arguments); + } + function _fileExists() { + _fileExists = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee3(url) { + var response; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.prev = 0; + _context3.next = 3; + return fetch(url, { + method: 'HEAD' + }); + case 3: + response = _context3.sent; + return _context3.abrupt('return', response.ok); + case 7: + _context3.prev = 7; + _context3.t0 = _context3['catch'](0); + return _context3.abrupt('return', false); + case 10: + case 'end': + return _context3.stop(); + } + } + }, _callee3, null, [ + [0, + 7] + ]); + })); + return _fileExists.apply(this, arguments); + } + if (fileType.match(/\.stl$/i)) { + this.httpDo(path, 'GET', 'arrayBuffer', function (arrayBuffer) { + parseSTL(model, arrayBuffer); + if (normalize) { + model.normalize(); + } + if (flipU) { + model.flipU(); + } + if (flipV) { + model.flipV(); + } + self._decrementPreload(); + if (typeof successCallback === 'function') { + successCallback(model); + } + }, failureCallback); + } else if (fileType.match(/\.obj$/i)) { + this.loadStrings(path, /*#__PURE__*/ function () { + var _ref = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(lines) { + var parsedMaterials; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return getMaterials(lines); + case 3: + parsedMaterials = _context.sent; + parseObj(model, lines, parsedMaterials); + _context.next = 11; + break; + case 7: + _context.prev = 7; + _context.t0 = _context['catch'](0); + if (failureCallback) { + failureCallback(_context.t0); + } else { + _main.default._friendlyError('Error during parsing: ' + _context.t0.message); + } + return _context.abrupt('return'); + case 11: + _context.prev = 11; + if (normalize) { + model.normalize(); + } + if (flipU) { + model.flipU(); + } + if (flipV) { + model.flipV(); + } + self._decrementPreload(); + if (typeof successCallback === 'function') { + successCallback(model); + } + return _context.finish(11); + case 18: + case 'end': + return _context.stop(); + } + } + }, _callee, null, [ + [0, + 7, + 11, + 18] + ]); + })); + return function (_x3) { + return _ref.apply(this, arguments); + }; + }(), failureCallback); + } else { + _main.default._friendlyFileLoadError(3, path); + if (failureCallback) { + failureCallback(); + } else { + _main.default._friendlyError('Sorry, the file type is invalid. Only OBJ and STL files are supported.'); + } + } + return model; + }; + function parseMtl(p5, mtlPath) { + return new Promise(function (resolve, reject) { + var currentMaterial = null; + var materials = { + }; + p5.loadStrings(mtlPath, function (lines) { + for (var line = 0; line < lines.length; ++line) { + var tokens = lines[line].trim().split(/\s+/); + if (tokens[0] === 'newmtl') { + var materialName = tokens[1]; + currentMaterial = materialName; + materials[currentMaterial] = { + }; + } else if (tokens[0] === 'Kd') { + //Diffuse color + materials[currentMaterial].diffuseColor = [ + parseFloat(tokens[1]), + parseFloat(tokens[2]), + parseFloat(tokens[3]) + ]; + } else if (tokens[0] === 'Ka') { + //Ambient Color + materials[currentMaterial].ambientColor = [ + parseFloat(tokens[1]), + parseFloat(tokens[2]), + parseFloat(tokens[3]) + ]; + } else if (tokens[0] === 'Ks') { + //Specular color + materials[currentMaterial].specularColor = [ + parseFloat(tokens[1]), + parseFloat(tokens[2]), + parseFloat(tokens[3]) + ]; + } else if (tokens[0] === 'map_Kd') { + //Texture path + materials[currentMaterial].texturePath = tokens[1]; + } + } + resolve(materials); + }, reject); + }); + } /** + * Parse OBJ lines into model. For reference, this is what a simple model of a + * square might look like: + * + * v -0.5 -0.5 0.5 + * v -0.5 -0.5 -0.5 + * v -0.5 0.5 -0.5 + * v -0.5 0.5 0.5 + * + * f 4 3 2 1 + */ + + function parseObj(model, lines) { + var materials = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + }; + // OBJ allows a face to specify an index for a vertex (in the above example), + // but it also allows you to specify a custom combination of vertex, UV + // coordinate, and vertex normal. So, "3/4/3" would mean, "use vertex 3 with + // UV coordinate 4 and vertex normal 3". In WebGL, every vertex with different + // parameters must be a different vertex, so loadedVerts is used to + // temporarily store the parsed vertices, normals, etc., and indexedVerts is + // used to map a specific combination (keyed on, for example, the string + // "3/4/3"), to the actual index of the newly created vertex in the final + // object. + var loadedVerts = { + v: [ + ], + vt: [ + ], + vn: [ + ] + }; + // Map from source index → Map of material → destination index + var usedVerts = { + }; // Track colored vertices + var currentMaterial = null; + var coloredVerts = new Set(); //unique vertices with color + var hasColoredVertices = false; + var hasColorlessVertices = false; + for (var line = 0; line < lines.length; ++line) { + // Each line is a separate object (vertex, face, vertex normal, etc) + // For each line, split it into tokens on whitespace. The first token + // describes the type. + var tokens = lines[line].trim().split(/\b\s+/); + if (tokens.length > 0) { + if (tokens[0] === 'usemtl') { + // Switch to a new material + currentMaterial = tokens[1]; + } else if (tokens[0] === 'v' || tokens[0] === 'vn') { + // Check if this line describes a vertex or vertex normal. + // It will have three numeric parameters. + var vertex = new _main.default.Vector(parseFloat(tokens[1]), parseFloat(tokens[2]), parseFloat(tokens[3])); + loadedVerts[tokens[0]].push(vertex); + } else if (tokens[0] === 'vt') { + // Check if this line describes a texture coordinate. + // It will have two numeric parameters U and V (W is omitted). + // Because of WebGL texture coordinates rendering behaviour, the V + // coordinate is inversed. + var texVertex = [ + parseFloat(tokens[1]), + 1 - parseFloat(tokens[2]) + ]; + loadedVerts[tokens[0]].push(texVertex); + } else if (tokens[0] === 'f') { + // Check if this line describes a face. + // OBJ faces can have more than three points. Triangulate points. + for (var tri = 3; tri < tokens.length; ++tri) { + var face = [ + ]; + var vertexTokens = [ + 1, + tri - 1, + tri + ]; + for (var tokenInd = 0; tokenInd < vertexTokens.length; ++tokenInd) { + // Now, convert the given token into an index + var vertString = tokens[vertexTokens[tokenInd]]; + var vertParts = vertString.split('/'); + // TODO: Faces can technically use negative numbers to refer to the + // previous nth vertex. I haven't seen this used in practice, but + // it might be good to implement this in the future. + for (var i = 0; i < vertParts.length; i++) { + vertParts[i] = parseInt(vertParts[i]) - 1; + } + if (!usedVerts[vertString]) { + usedVerts[vertString] = { + }; + } + if (usedVerts[vertString][currentMaterial] === undefined) { + var vertIndex = model.vertices.length; + model.vertices.push(loadedVerts.v[vertParts[0]].copy()); + model.uvs.push(loadedVerts.vt[vertParts[1]] ? loadedVerts.vt[vertParts[1]].slice() : [ + 0, + 0 + ]); + model.vertexNormals.push(loadedVerts.vn[vertParts[2]] ? loadedVerts.vn[vertParts[2]].copy() : new _main.default.Vector()); + usedVerts[vertString][currentMaterial] = vertIndex; + face.push(vertIndex); + if (currentMaterial && materials[currentMaterial] && materials[currentMaterial].diffuseColor) { + // Mark this vertex as colored + coloredVerts.add(loadedVerts.v[vertParts[0]]); //since a set would only push unique values + } + } else { + face.push(usedVerts[vertString][currentMaterial]); + } + } + if (face[0] !== face[1] && face[0] !== face[2] && face[1] !== face[2]) { + model.faces.push(face); + //same material for all vertices in a particular face + if (currentMaterial && materials[currentMaterial] && materials[currentMaterial].diffuseColor) { + hasColoredVertices = true; + //flag to track color or no color model + hasColoredVertices = true; + var materialDiffuseColor = materials[currentMaterial].diffuseColor; + for (var _i = 0; _i < face.length; _i++) { + model.vertexColors.push(materialDiffuseColor[0]); + model.vertexColors.push(materialDiffuseColor[1]); + model.vertexColors.push(materialDiffuseColor[2]); + } + } else { + hasColorlessVertices = true; + } + } + } + } + } + } // If the model doesn't have normals, compute the normals + + if (model.vertexNormals.length === 0) { + model.computeNormals(); + } + if (hasColoredVertices === hasColorlessVertices) { + // If both are true or both are false, throw an error because the model is inconsistent + throw new Error('Model coloring is inconsistent. Either all vertices should have colors or none should.'); + } + return model; + } /** + * STL files can be of two types, ASCII and Binary, + * + * We need to convert the arrayBuffer to an array of strings, + * to parse it as an ASCII file. + */ + + function parseSTL(model, buffer) { + if (isBinary(buffer)) { + parseBinarySTL(model, buffer); + } else { + var reader = new DataView(buffer); + if (!('TextDecoder' in window)) { + console.warn('Sorry, ASCII STL loading only works in browsers that support TextDecoder (https://caniuse.com/#feat=textencoder)'); + return model; + } + var decoder = new TextDecoder('utf-8'); + var lines = decoder.decode(reader); + var lineArray = lines.split('\n'); + parseASCIISTL(model, lineArray); + } + return model; + } /** + * This function checks if the file is in ASCII format or in Binary format + * + * It is done by searching keyword `solid` at the start of the file. + * + * An ASCII STL data must begin with `solid` as the first six bytes. + * However, ASCII STLs lacking the SPACE after the `d` are known to be + * plentiful. So, check the first 5 bytes for `solid`. + * + * Several encodings, such as UTF-8, precede the text with up to 5 bytes: + * https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding + * Search for `solid` to start anywhere after those prefixes. + */ + + function isBinary(data) { + var reader = new DataView(data); + // US-ASCII ordinal values for `s`, `o`, `l`, `i`, `d` + var solid = [ + 115, + 111, + 108, + 105, + 100 + ]; + for (var off = 0; off < 5; off++) { + // If "solid" text is matched to the current offset, declare it to be an ASCII STL. + if (matchDataViewAt(solid, reader, off)) return false; + } // Couldn't find "solid" text at the beginning; it is binary STL. + + return true; + } /** + * This function matches the `query` at the provided `offset` + */ + + function matchDataViewAt(query, reader, offset) { + // Check if each byte in query matches the corresponding byte from the current offset + for (var i = 0, il = query.length; i < il; i++) { + if (query[i] !== reader.getUint8(offset + i, false)) return false; + } + return true; + } /** + * This function parses the Binary STL files. + * https://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL + * + * Currently there is no support for the colors provided in STL files. + */ + + function parseBinarySTL(model, buffer) { + var reader = new DataView(buffer); + // Number of faces is present following the header + var faces = reader.getUint32(80, true); + var r, + g, + b, + hasColors = false, + colors; + var defaultR, + defaultG, + defaultB; + // Binary files contain 80-byte header, which is generally ignored. + for (var index = 0; index < 80 - 10; index++) { + // Check for `COLOR=` + if (reader.getUint32(index, false) === 1129270351 /*COLO*/ && reader.getUint8(index + 4) === 82 /*'R'*/ && reader.getUint8(index + 5) === 61 /*'='*/ ) { + hasColors = true; + colors = [ + ]; + defaultR = reader.getUint8(index + 6) / 255; + defaultG = reader.getUint8(index + 7) / 255; + defaultB = reader.getUint8(index + 8) / 255; + // To be used when color support is added + // alpha = reader.getUint8(index + 9) / 255; + } + } + var dataOffset = 84; + var faceLength = 12 * 4 + 2; + // Iterate the faces + for (var face = 0; face < faces; face++) { + var start = dataOffset + face * faceLength; + var normalX = reader.getFloat32(start, true); + var normalY = reader.getFloat32(start + 4, true); + var normalZ = reader.getFloat32(start + 8, true); + if (hasColors) { + var packedColor = reader.getUint16(start + 48, true); + if ((packedColor & 32768) === 0) { + // facet has its own unique color + r = (packedColor & 31) / 31; + g = (packedColor >> 5 & 31) / 31; + b = (packedColor >> 10 & 31) / 31; + } else { + r = defaultR; + g = defaultG; + b = defaultB; + } + } + var newNormal = new _main.default.Vector(normalX, normalY, normalZ); + for (var i = 1; i <= 3; i++) { + var vertexstart = start + i * 12; + var newVertex = new _main.default.Vector(reader.getFloat32(vertexstart, true), reader.getFloat32(vertexstart + 4, true), reader.getFloat32(vertexstart + 8, true)); + model.vertices.push(newVertex); + model.vertexNormals.push(newNormal); + if (hasColors) { + colors.push(r, g, b); + } + } + model.faces.push([3 * face, + 3 * face + 1, + 3 * face + 2]); + model.uvs.push([0, + 0], [ + 0, + 0 + ], [ + 0, + 0 + ]); + } + if (hasColors) { + // add support for colors here. + } + return model; + } /** + * ASCII STL file starts with `solid 'nameOfFile'` + * Then contain the normal of the face, starting with `facet normal` + * Next contain a keyword indicating the start of face vertex, `outer loop` + * Next comes the three vertex, starting with `vertex x y z` + * Vertices ends with `endloop` + * Face ends with `endfacet` + * Next face starts with `facet normal` + * The end of the file is indicated by `endsolid` + */ + + function parseASCIISTL(model, lines) { + var state = ''; + var curVertexIndex = [ + ]; + var newNormal, + newVertex; + for (var iterator = 0; iterator < lines.length; ++iterator) { + var line = lines[iterator].trim(); + var parts = line.split(' '); + for (var partsiterator = 0; partsiterator < parts.length; ++partsiterator) { + if (parts[partsiterator] === '') { + // Ignoring multiple whitespaces + parts.splice(partsiterator, 1); + } + } + if (parts.length === 0) { + // Remove newline + continue; + } + switch (state) { + case '': + // First run + if (parts[0] !== 'solid') { + // Invalid state + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "solid"')); + return; + } else { + state = 'solid'; + } + break; + case 'solid': + // First face + if (parts[0] !== 'facet' || parts[1] !== 'normal') { + // Invalid state + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "facet normal"')); + return; + } else { + // Push normal for first face + newNormal = new _main.default.Vector(parseFloat(parts[2]), parseFloat(parts[3]), parseFloat(parts[4])); + model.vertexNormals.push(newNormal, newNormal, newNormal); + state = 'facet normal'; + } + break; + case 'facet normal': + // After normal is defined + if (parts[0] !== 'outer' || parts[1] !== 'loop') { + // Invalid State + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "outer loop"')); + return; + } else { + // Next should be vertices + state = 'vertex'; + } + break; + case 'vertex': + if (parts[0] === 'vertex') { + //Vertex of triangle + newVertex = new _main.default.Vector(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3])); + model.vertices.push(newVertex); + model.uvs.push([0, + 0]); + curVertexIndex.push(model.vertices.indexOf(newVertex)); + } else if (parts[0] === 'endloop') { + // End of vertices + model.faces.push(curVertexIndex); + curVertexIndex = [ + ]; + state = 'endloop'; + } else { + // Invalid State + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "vertex" or "endloop"')); + return; + } + break; + case 'endloop': + if (parts[0] !== 'endfacet') { + // End of face + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "endfacet"')); + return; + } else { + state = 'endfacet'; + } + break; + case 'endfacet': + if (parts[0] === 'endsolid') { + // End of solid + } else if (parts[0] === 'facet' && parts[1] === 'normal') { + // Next face + newNormal = new _main.default.Vector(parseFloat(parts[2]), parseFloat(parts[3]), parseFloat(parts[4])); + model.vertexNormals.push(newNormal, newNormal, newNormal); + state = 'facet normal'; + } else { + // Invalid State + console.error(line); + console.error('Invalid state "'.concat(parts[0], '", should be "endsolid" or "facet normal"')); + return; + } + break; + default: + console.error('Invalid state "'.concat(state, '"')); + break; + } + } + return model; + } /** + * Draws a p5.Geometry object to the canvas. + * + * The parameter, `model`, is the + * p5.Geometry object to draw. + * p5.Geometry objects can be built with + * buildGeometry(), or + * beginGeometry() and + * endGeometry(). They can also be loaded from + * a file with loadGeometry(). + * + * Note: `model()` can only be used in WebGL mode. + * + * @method model + * @param {p5.Geometry} model 3D shape to be drawn. + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the p5.Geometry object. + * shape = buildGeometry(createShape); + * + * describe('A white cone drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the p5.Geometry object. + * model(shape); + * } + * + * // Create p5.Geometry object from a single cone. + * function createShape() { + * cone(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the p5.Geometry object. + * shape = buildGeometry(createArrow); + * + * describe('Two white arrows drawn on a gray background. The arrow on the right rotates slowly.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the arrows. + * noStroke(); + * + * // Draw the p5.Geometry object. + * model(shape); + * + * // Translate and rotate the coordinate system. + * translate(30, 0, 0); + * rotateZ(frameCount * 0.01); + * + * // Draw the p5.Geometry object again. + * model(shape); + * } + * + * function createArrow() { + * // Add shapes to the p5.Geometry object. + * push(); + * rotateX(PI); + * cone(10); + * translate(0, -10, 0); + * cylinder(3, 20); + * pop(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let shape; + * + * // Load the file and create a p5.Geometry object. + * function preload() { + * shape = loadModel('assets/octahedron.obj'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white octahedron drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the shape. + * model(shape); + * } + * + *
        + */ + + _main.default.prototype.model = function (model) { + this._assert3d('model'); + _main.default._validateParameters('model', arguments); + if (model.vertices.length > 0) { + if (!this._renderer.geometryInHash(model.gid)) { + if (model.edges.length === 0) { + model._makeTriangleEdges(); + } + model._edgesToVertices(); + this._renderer.createBuffers(model.gid, model); + } + this._renderer.drawBuffers(model.gid); + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/main': 303, + './p5.Geometry': 355, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.splice': 188, + 'core-js/modules/es.object.assign': 199, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.promise': 206, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.set': 212, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.match': 216, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.string.trim': 224, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.iterator': 261, + 'regenerator-runtime/runtime': 279 + } + ], + 351: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.join'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + _dereq_('./p5.Texture'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } /** + * @module 3D + * @submodule Material + * @for p5 + * @requires core + */ + /** + * Loads vertex and fragment shaders to create a + * p5.Shader object. + * + * Shaders are programs that run on the graphics processing unit (GPU). They + * can process many pixels at the same time, making them fast for many + * graphics tasks. They’re written in a language called + * GLSL + * and run along with the rest of the code in a sketch. + * + * Once the p5.Shader object is created, it can be + * used with the shader() function, as in + * `shader(myShader)`. A shader program consists of two files, a vertex shader + * and a fragment shader. The vertex shader affects where 3D geometry is drawn + * on the screen and the fragment shader affects color. + * + * `loadShader()` loads the vertex and fragment shaders from their `.vert` and + * `.frag` files. For example, calling + * `loadShader('assets/shader.vert', 'assets/shader.frag')` loads both + * required shaders and returns a p5.Shader object. + * + * The third parameter, `successCallback`, is optional. If a function is + * passed, it will be called once the shader has loaded. The callback function + * can use the new p5.Shader object as its + * parameter. + * + * The fourth parameter, `failureCallback`, is also optional. If a function is + * passed, it will be called if the shader fails to load. The callback + * function can use the event error as its parameter. + * + * Shaders can take time to load. Calling `loadShader()` in + * preload() ensures shaders load before they're + * used in setup() or draw(). + * + * Note: Shaders can only be used in WebGL mode. + * + * @method loadShader + * @param {String} vertFilename path of the vertex shader to be loaded. + * @param {String} fragFilename path of the fragment shader to be loaded. + * @param {function} [successCallback] function to call once the shader is loaded. Can be passed the + * p5.Shader object. + * @param {function} [failureCallback] function to call if the shader fails to load. Can be passed an + * `Error` event object. + * @return {p5.Shader} new shader created from the vertex and fragment shader files. + * + * @example + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * let mandelbrot; + * + * // Load the shader and create a p5.Shader object. + * function preload() { + * mandelbrot = loadShader('assets/shader.vert', 'assets/shader.frag'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Compile and apply the p5.Shader object. + * shader(mandelbrot); + * + * // Set the shader uniform p to an array. + * mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); + * + * // Set the shader uniform r to the value 1.5. + * mandelbrot.setUniform('r', 1.5); + * + * // Add a quad as a display surface for the shader. + * quad(-1, -1, 1, -1, 1, 1, -1, 1); + * + * describe('A black fractal image on a magenta background.'); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * let mandelbrot; + * + * // Load the shader and create a p5.Shader object. + * function preload() { + * mandelbrot = loadShader('assets/shader.vert', 'assets/shader.frag'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Use the p5.Shader object. + * shader(mandelbrot); + * + * // Set the shader uniform p to an array. + * mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); + * + * describe('A fractal image zooms in and out of focus.'); + * } + * + * function draw() { + * // Set the shader uniform r to a value that oscillates between 0 and 2. + * mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1); + * + * // Add a quad as a display surface for the shader. + * quad(-1, -1, 1, -1, 1, 1, -1, 1); + * } + * + *
        + */ + + _main.default.prototype.loadShader = function (vertFilename, fragFilename, successCallback, failureCallback) { + _main.default._validateParameters('loadShader', arguments); + if (!failureCallback) { + failureCallback = console.error; + } + var loadedShader = new _main.default.Shader(); + var self = this; + var loadedFrag = false; + var loadedVert = false; + var onLoad = function onLoad() { + self._decrementPreload(); + if (successCallback) { + successCallback(loadedShader); + } + }; + this.loadStrings(vertFilename, function (result) { + loadedShader._vertSrc = result.join('\n'); + loadedVert = true; + if (loadedFrag) { + onLoad(); + } + }, failureCallback); + this.loadStrings(fragFilename, function (result) { + loadedShader._fragSrc = result.join('\n'); + loadedFrag = true; + if (loadedVert) { + onLoad(); + } + }, failureCallback); + return loadedShader; + }; + /** + * Creates a new p5.Shader object. + * + * Shaders are programs that run on the graphics processing unit (GPU). They + * can process many pixels at the same time, making them fast for many + * graphics tasks. They’re written in a language called + * GLSL + * and run along with the rest of the code in a sketch. + * + * Once the p5.Shader object is created, it can be + * used with the shader() function, as in + * `shader(myShader)`. A shader program consists of two parts, a vertex shader + * and a fragment shader. The vertex shader affects where 3D geometry is drawn + * on the screen and the fragment shader affects color. + * + * The first parameter, `vertSrc`, sets the vertex shader. It’s a string that + * contains the vertex shader program written in GLSL. + * + * The second parameter, `fragSrc`, sets the fragment shader. It’s a string + * that contains the fragment shader program written in GLSL. + * + * Note: Only filter shaders can be used in 2D mode. All shaders can be used + * in WebGL mode. + * + * @method createShader + * @param {String} vertSrc source code for the vertex shader. + * @param {String} fragSrc source code for the fragment shader. + * @returns {p5.Shader} new shader object created from the + * vertex and fragment shaders. + * + * @example + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision highp float; + * + * void main() { + * // Set each pixel's RGBA value to yellow. + * gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); + * } + * `; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * let shaderProgram = createShader(vertSrc, fragSrc); + * + * // Compile and apply the p5.Shader object. + * shader(shaderProgram); + * + * // Style the drawing surface. + * noStroke(); + * + * // Add a plane as a drawing surface. + * plane(100, 100); + * + * describe('A yellow square.'); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision highp float; + * uniform vec2 p; + * uniform float r; + * const int numIterations = 500; + * varying vec2 vTexCoord; + * + * void main() { + * vec2 c = p + gl_FragCoord.xy * r; + * vec2 z = c; + * float n = 0.0; + * + * for (int i = numIterations; i > 0; i--) { + * if (z.x * z.x + z.y * z.y > 4.0) { + * n = float(i) / float(numIterations); + * break; + * } + * z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c; + * } + * + * gl_FragColor = vec4( + * 0.5 - cos(n * 17.0) / 2.0, + * 0.5 - cos(n * 13.0) / 2.0, + * 0.5 - cos(n * 23.0) / 2.0, + * 1.0 + * ); + * } + * `; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * let mandelbrot = createShader(vertSrc, fragSrc); + * + * // Compile and apply the p5.Shader object. + * shader(mandelbrot); + * + * // Set the shader uniform p to an array. + * // p is the center point of the Mandelbrot image. + * mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); + * + * // Set the shader uniform r to 0.005. + * // r is the size of the image in Mandelbrot-space. + * mandelbrot.setUniform('r', 0.005); + * + * // Style the drawing surface. + * noStroke(); + * + * // Add a plane as a drawing surface. + * plane(100, 100); + * + * describe('A black fractal image on a magenta background.'); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision highp float; + * uniform vec2 p; + * uniform float r; + * const int numIterations = 500; + * varying vec2 vTexCoord; + * + * void main() { + * vec2 c = p + gl_FragCoord.xy * r; + * vec2 z = c; + * float n = 0.0; + * + * for (int i = numIterations; i > 0; i--) { + * if (z.x * z.x + z.y * z.y > 4.0) { + * n = float(i) / float(numIterations); + * break; + * } + * + * z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c; + * } + * + * gl_FragColor = vec4( + * 0.5 - cos(n * 17.0) / 2.0, + * 0.5 - cos(n * 13.0) / 2.0, + * 0.5 - cos(n * 23.0) / 2.0, + * 1.0 + * ); + * } + * `; + * + * let mandelbrot; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * mandelbrot = createShader(vertSrc, fragSrc); + * + * // Apply the p5.Shader object. + * shader(mandelbrot); + * + * // Set the shader uniform p to an array. + * // p is the center point of the Mandelbrot image. + * mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); + * + * describe('A fractal image zooms in and out of focus.'); + * } + * + * function draw() { + * // Set the shader uniform r to a value that oscillates + * // between 0 and 0.005. + * // r is the size of the image in Mandelbrot-space. + * let radius = 0.005 * (sin(frameCount * 0.01) + 1); + * mandelbrot.setUniform('r', radius); + * + * // Style the drawing surface. + * noStroke(); + * + * // Add a plane as a drawing surface. + * plane(100, 100); + * } + * + *
        + */ + _main.default.prototype.createShader = function (vertSrc, fragSrc) { + _main.default._validateParameters('createShader', arguments); + return new _main.default.Shader(this._renderer, vertSrc, fragSrc); + }; + /** + * Creates a p5.Shader object to be used with the + * filter() function. + * + * `createFilterShader()` works like + * createShader() but has a default vertex + * shader included. `createFilterShader()` is intended to be used along with + * filter() for filtering the contents of a canvas. + * A filter shader will be applied to the whole canvas instead of just + * p5.Geometry objects. + * + * The parameter, `fragSrc`, sets the fragment shader. It’s a string that + * contains the fragment shader program written in + * GLSL. + * + * The p5.Shader object that's created has some + * uniforms that can be set: + * - `sampler2D tex0`, which contains the canvas contents as a texture. + * - `vec2 canvasSize`, which is the width and height of the canvas, not including pixel density. + * - `vec2 texelSize`, which is the size of a physical pixel including pixel density. This is calculated as `1.0 / (width * density)` for the pixel width and `1.0 / (height * density)` for the pixel height. + * + * The p5.Shader that's created also provides + * `varying vec2 vTexCoord`, a coordinate with values between 0 and 1. + * `vTexCoord` describes where on the canvas the pixel will be drawn. + * + * For more info about filters and shaders, see Adam Ferriss' repo of shader examples + * or the Introduction to Shaders tutorial. + * + * @method createFilterShader + * @param {String} fragSrc source code for the fragment shader. + * @returns {p5.Shader} new shader object created from the fragment shader. + * + * @example + *
        + * + * function setup() { + * let fragSrc = `precision highp float; + * void main() { + * gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); + * }`; + * + * createCanvas(100, 100, WEBGL); + * let s = createFilterShader(fragSrc); + * filter(s); + * describe('a yellow canvas'); + * } + * + *
        + * + *
        + * + * let img, s; + * function preload() { + * img = loadImage('assets/bricks.jpg'); + * } + * function setup() { + * let fragSrc = `precision highp float; + * + * // x,y coordinates, given from the vertex shader + * varying vec2 vTexCoord; + * + * // the canvas contents, given from filter() + * uniform sampler2D tex0; + * // other useful information from the canvas + * uniform vec2 texelSize; + * uniform vec2 canvasSize; + * // a custom variable from this sketch + * uniform float darkness; + * + * void main() { + * // get the color at current pixel + * vec4 color = texture2D(tex0, vTexCoord); + * // set the output color + * color.b = 1.0; + * color *= darkness; + * gl_FragColor = vec4(color.rgb, 1.0); + * }`; + * + * createCanvas(100, 100, WEBGL); + * s = createFilterShader(fragSrc); + * } + * function draw() { + * image(img, -50, -50); + * s.setUniform('darkness', 0.5); + * filter(s); + * describe('a image of bricks tinted dark blue'); + * } + * + *
        + */ + _main.default.prototype.createFilterShader = function (fragSrc) { + _main.default._validateParameters('createFilterShader', arguments); + var defaultVertV1 = '\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n attribute vec3 aPosition;\n // texcoords only come from p5 to vertex shader\n // so pass texcoords on to the fragment shader in a varying variable\n attribute vec2 aTexCoord;\n varying vec2 vTexCoord;\n\n void main() {\n // transferring texcoords for the frag shader\n vTexCoord = aTexCoord;\n\n // copy position with a fourth coordinate for projection (1.0 is normal)\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // project to 3D space\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n }\n '; + var defaultVertV2 = '#version 300 es\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n in vec3 aPosition;\n in vec2 aTexCoord;\n out vec2 vTexCoord;\n\n void main() {\n // transferring texcoords for the frag shader\n vTexCoord = aTexCoord;\n\n // copy position with a fourth coordinate for projection (1.0 is normal)\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // project to 3D space\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n }\n '; + var vertSrc = fragSrc.includes('#version 300 es') ? defaultVertV2 : defaultVertV1; + var shader = new _main.default.Shader(this._renderer, vertSrc, fragSrc); + if (this._renderer.GL) { + shader.ensureCompiledOnContext(this); + } else { + shader.ensureCompiledOnContext(this._renderer.getFilterGraphicsLayer()); + } + return shader; + }; + /** + * Sets the p5.Shader object to apply while drawing. + * + * Shaders are programs that run on the graphics processing unit (GPU). They + * can process many pixels or vertices at the same time, making them fast for + * many graphics tasks. They’re written in a language called + * GLSL + * and run along with the rest of the code in a sketch. + * p5.Shader objects can be created using the + * createShader() and + * loadShader() functions. + * + * The parameter, `s`, is the p5.Shader object to + * apply. For example, calling `shader(myShader)` applies `myShader` to + * process each pixel on the canvas. The shader will be used for: + * - Fills when a texture is enabled if it includes a uniform `sampler2D`. + * - Fills when lights are enabled if it includes the attribute `aNormal`, or if it has any of the following uniforms: `uUseLighting`, `uAmbientLightCount`, `uDirectionalLightCount`, `uPointLightCount`, `uAmbientColor`, `uDirectionalDiffuseColors`, `uDirectionalSpecularColors`, `uPointLightLocation`, `uPointLightDiffuseColors`, `uPointLightSpecularColors`, `uLightingDirection`, or `uSpecular`. + * - Fills whenever there are no lights or textures. + * - Strokes if it includes the uniform `uStrokeWeight`. + * + * The source code from a p5.Shader object's + * fragment and vertex shaders will be compiled the first time it's passed to + * `shader()`. See + * MDN + * for more information about compiling shaders. + * + * Calling resetShader() restores a sketch’s + * default shaders. + * + * Note: Shaders can only be used in WebGL mode. + * + * @method shader + * @chainable + * @param {p5.Shader} s p5.Shader object + * to apply. + * + * @example + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision highp float; + * + * void main() { + * // Set each pixel's RGBA value to yellow. + * gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); + * } + * `; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * let shaderProgram = createShader(vertSrc, fragSrc); + * + * // Apply the p5.Shader object. + * shader(shaderProgram); + * + * // Style the drawing surface. + * noStroke(); + * + * // Add a plane as a drawing surface. + * plane(100, 100); + * + * describe('A yellow square.'); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * let mandelbrot; + * + * // Load the shader and create a p5.Shader object. + * function preload() { + * mandelbrot = loadShader('assets/shader.vert', 'assets/shader.frag'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Use the p5.Shader object. + * shader(mandelbrot); + * + * // Set the shader uniform p to an array. + * mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); + * + * describe('A fractal image zooms in and out of focus.'); + * } + * + * function draw() { + * // Set the shader uniform r to a value that oscillates between 0 and 2. + * mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1); + * + * // Add a quad as a display surface for the shader. + * quad(-1, -1, 1, -1, 1, 1, -1, 1); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * let redGreen; + * let orangeBlue; + * let showRedGreen = false; + * + * // Load the shader and create two separate p5.Shader objects. + * function preload() { + * redGreen = loadShader('assets/shader.vert', 'assets/shader-gradient.frag'); + * orangeBlue = loadShader('assets/shader.vert', 'assets/shader-gradient.frag'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Initialize the redGreen shader. + * shader(redGreen); + * + * // Set the redGreen shader's center and background color. + * redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]); + * redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]); + * + * // Initialize the orangeBlue shader. + * shader(orangeBlue); + * + * // Set the orangeBlue shader's center and background color. + * orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]); + * orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]); + * + * describe( + * 'The scene toggles between two circular gradients when the user double-clicks. An orange and blue gradient vertically, and red and green gradient moves horizontally.' + * ); + * } + * + * function draw() { + * // Update the offset values for each shader. + * // Move orangeBlue vertically. + * // Move redGreen horizontally. + * orangeBlue.setUniform('offset', [0, sin(frameCount * 0.01) + 1]); + * redGreen.setUniform('offset', [sin(frameCount * 0.01), 1]); + * + * if (showRedGreen === true) { + * shader(redGreen); + * } else { + * shader(orangeBlue); + * } + * + * // Style the drawing surface. + * noStroke(); + * + * // Add a quad as a drawing surface. + * quad(-1, -1, 1, -1, 1, 1, -1, 1); + * } + * + * // Toggle between shaders when the user double-clicks. + * function doubleClicked() { + * showRedGreen = !showRedGreen; + * } + * + *
        + */ + _main.default.prototype.shader = function (s) { + this._assert3d('shader'); + _main.default._validateParameters('shader', arguments); + s.ensureCompiledOnContext(this); + if (s.isStrokeShader()) { + this._renderer.userStrokeShader = s; + } else { + this._renderer.userFillShader = s; + this._renderer._useNormalMaterial = false; + } + return this; + }; + /** + * Restores the default shaders. + * + * `resetShader()` deactivates any shaders previously applied by + * shader(). + * + * Note: Shaders can only be used in WebGL mode. + * + * @method resetShader + * @chainable + * + * @example + *
        + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * uniform mat4 uProjectionMatrix; + * uniform mat4 uModelViewMatrix; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 position = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * position; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision mediump float; + * varying vec2 vTexCoord; + * + * void main() { + * vec2 uv = vTexCoord; + * vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0)); + * gl_FragColor = vec4(color, 1.0); + * } + * `; + * + * let myShader; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * myShader = createShader(vertSrc, fragSrc); + * + * describe( + * 'Two rotating cubes on a gray background. The left one has a blue-purple gradient on each face. The right one is red.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw a box using the p5.Shader. + * // shader() sets the active shader to myShader. + * shader(myShader); + * push(); + * translate(-25, 0, 0); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * box(width / 4); + * pop(); + * + * // Draw a box using the default fill shader. + * // resetShader() restores the default fill shader. + * resetShader(); + * fill(255, 0, 0); + * push(); + * translate(25, 0, 0); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * box(width / 4); + * pop(); + * } + * + *
        + */ + _main.default.prototype.resetShader = function () { + this._renderer.userFillShader = this._renderer.userStrokeShader = null; + return this; + }; + /** + * Sets the texture that will be used on shapes. + * + * A texture is like a skin that wraps around a shape. `texture()` works with + * built-in shapes, such as square() and + * sphere(), and custom shapes created with + * functions such as buildGeometry(). To + * texture a geometry created with beginShape(), + * uv coordinates must be passed to each + * vertex() call. + * + * The parameter, `tex`, is the texture to apply. `texture()` can use a range + * of sources including images, videos, and offscreen renderers such as + * p5.Graphics and + * p5.Framebuffer objects. + * + * To texture a geometry created with beginShape(), + * you will need to specify uv coordinates in vertex(). + * + * Note: `texture()` can only be used in WebGL mode. + * + * @method texture + * @param {p5.Image|p5.MediaElement|p5.Graphics|p5.Texture|p5.Framebuffer|p5.FramebufferTexture} tex media to use as the texture. + * @chainable + * + * @example + *
        + * + * let img; + * + * // Load an image and create a p5.Image object. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A spinning cube with an image of a ceiling on each face.'); + * } + * + * function draw() { + * background(0); + * + * // Rotate around the x-, y-, and z-axes. + * rotateZ(frameCount * 0.01); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * + * // Apply the image as a texture. + * texture(img); + * + * // Draw the box. + * box(50); + * } + * + *
        + * + *
        + * + * let pg; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Graphics object. + * pg = createGraphics(100, 100); + * + * // Draw a circle to the p5.Graphics object. + * pg.background(200); + * pg.circle(50, 50, 30); + * + * describe('A spinning cube with circle at the center of each face.'); + * } + * + * function draw() { + * background(0); + * + * // Rotate around the x-, y-, and z-axes. + * rotateZ(frameCount * 0.01); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * + * // Apply the p5.Graphics object as a texture. + * texture(pg); + * + * // Draw the box. + * box(50); + * } + * + *
        + * + *
        + * + * let vid; + * + * // Load a video and create a p5.MediaElement object. + * function preload() { + * vid = createVideo('assets/fingers.mov'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Hide the video. + * vid.hide(); + * + * // Set the video to loop. + * vid.loop(); + * + * describe('A rectangle with video as texture'); + * } + * + * function draw() { + * background(0); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Apply the video as a texture. + * texture(vid); + * + * // Draw the rectangle. + * rect(-40, -40, 80, 80); + * } + * + *
        + * + *
        + * + * let vid; + * + * // Load a video and create a p5.MediaElement object. + * function preload() { + * vid = createVideo('assets/fingers.mov'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Hide the video. + * vid.hide(); + * + * // Set the video to loop. + * vid.loop(); + * + * describe('A rectangle with video as texture'); + * } + * + * function draw() { + * background(0); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Set the texture mode. + * textureMode(NORMAL); + * + * // Apply the video as a texture. + * texture(vid); + * + * // Draw a custom shape using uv coordinates. + * beginShape(); + * vertex(-40, -40, 0, 0); + * vertex(40, -40, 1, 0); + * vertex(40, 40, 1, 1); + * vertex(-40, 40, 0, 1); + * endShape(); + * } + * + *
        + */ + _main.default.prototype.texture = function (tex) { + this._assert3d('texture'); + _main.default._validateParameters('texture', arguments); + if (tex.gifProperties) { + tex._animateGif(this); + } + this._renderer.drawMode = constants.TEXTURE; + this._renderer._useNormalMaterial = false; + this._renderer._tex = tex; + this._renderer._setProperty('_doFill', true); + return this; + }; + /** + * Changes the coordinate system used for textures when they’re applied to + * custom shapes. + * + * In order for texture() to work, a shape needs a + * way to map the points on its surface to the pixels in an image. Built-in + * shapes such as rect() and + * box() already have these texture mappings based on + * their vertices. Custom shapes created with + * vertex() require texture mappings to be passed as + * uv coordinates. + * + * Each call to vertex() must include 5 arguments, + * as in `vertex(x, y, z, u, v)`, to map the vertex at coordinates `(x, y, z)` + * to the pixel at coordinates `(u, v)` within an image. For example, the + * corners of a rectangular image are mapped to the corners of a rectangle by default: + * + * + * // Apply the image as a texture. + * texture(img); + * + * // Draw the rectangle. + * rect(0, 0, 30, 50); + * + * + * If the image in the code snippet above has dimensions of 300 x 500 pixels, + * the same result could be achieved as follows: + * + * + * // Apply the image as a texture. + * texture(img); + * + * // Draw the rectangle. + * beginShape(); + * + * // Top-left. + * // u: 0, v: 0 + * vertex(0, 0, 0, 0, 0); + * + * // Top-right. + * // u: 300, v: 0 + * vertex(30, 0, 0, 300, 0); + * + * // Bottom-right. + * // u: 300, v: 500 + * vertex(30, 50, 0, 300, 500); + * + * // Bottom-left. + * // u: 0, v: 500 + * vertex(0, 50, 0, 0, 500); + * + * endShape(); + * + * + * `textureMode()` changes the coordinate system for uv coordinates. + * + * The parameter, `mode`, accepts two possible constants. If `NORMAL` is + * passed, as in `textureMode(NORMAL)`, then the texture’s uv coordinates can + * be provided in the range 0 to 1 instead of the image’s dimensions. This can + * be helpful for using the same code for multiple images of different sizes. + * For example, the code snippet above could be rewritten as follows: + * + * + * // Set the texture mode to use normalized coordinates. + * textureMode(NORMAL); + * + * // Apply the image as a texture. + * texture(img); + * + * // Draw the rectangle. + * beginShape(); + * + * // Top-left. + * // u: 0, v: 0 + * vertex(0, 0, 0, 0, 0); + * + * // Top-right. + * // u: 1, v: 0 + * vertex(30, 0, 0, 1, 0); + * + * // Bottom-right. + * // u: 1, v: 1 + * vertex(30, 50, 0, 1, 1); + * + * // Bottom-left. + * // u: 0, v: 1 + * vertex(0, 50, 0, 0, 1); + * + * endShape(); + * + * + * By default, `mode` is `IMAGE`, which scales uv coordinates to the + * dimensions of the image. Calling `textureMode(IMAGE)` applies the default. + * + * Note: `textureMode()` can only be used in WebGL mode. + * + * @method textureMode + * @param {Constant} mode either IMAGE or NORMAL. + * + * @example + *
        + * + * let img; + * + * // Load an image and create a p5.Image object. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('An image of a ceiling against a black background.'); + * } + * + * function draw() { + * background(0); + * + * // Apply the image as a texture. + * texture(img); + * + * // Draw the custom shape. + * // Use the image's width and height as uv coordinates. + * beginShape(); + * vertex(-30, -30, 0, 0); + * vertex(30, -30, img.width, 0); + * vertex(30, 30, img.width, img.height); + * vertex(-30, 30, 0, img.height); + * endShape(); + * } + * + *
        + * + *
        + * + * let img; + * + * // Load an image and create a p5.Image object. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('An image of a ceiling against a black background.'); + * } + * + * function draw() { + * background(0); + * + * // Set the texture mode. + * textureMode(NORMAL); + * + * // Apply the image as a texture. + * texture(img); + * + * // Draw the custom shape. + * // Use normalized uv coordinates. + * beginShape(); + * vertex(-30, -30, 0, 0); + * vertex(30, -30, 1, 0); + * vertex(30, 30, 1, 1); + * vertex(-30, 30, 0, 1); + * endShape(); + * } + * + *
        + */ + _main.default.prototype.textureMode = function (mode) { + if (mode !== constants.IMAGE && mode !== constants.NORMAL) { + console.warn('You tried to set '.concat(mode, ' textureMode only supports IMAGE & NORMAL ')); + } else { + this._renderer.textureMode = mode; + } + }; + /** + * Changes the way textures behave when a shape’s uv coordinates go beyond the + * texture. + * + * In order for texture() to work, a shape needs a + * way to map the points on its surface to the pixels in an image. Built-in + * shapes such as rect() and + * box() already have these texture mappings based on + * their vertices. Custom shapes created with + * vertex() require texture mappings to be passed as + * uv coordinates. + * + * Each call to vertex() must include 5 arguments, + * as in `vertex(x, y, z, u, v)`, to map the vertex at coordinates `(x, y, z)` + * to the pixel at coordinates `(u, v)` within an image. For example, the + * corners of a rectangular image are mapped to the corners of a rectangle by default: + * + * + * // Apply the image as a texture. + * texture(img); + * + * // Draw the rectangle. + * rect(0, 0, 30, 50); + * + * + * If the image in the code snippet above has dimensions of 300 x 500 pixels, + * the same result could be achieved as follows: + * + * + * // Apply the image as a texture. + * texture(img); + * + * // Draw the rectangle. + * beginShape(); + * + * // Top-left. + * // u: 0, v: 0 + * vertex(0, 0, 0, 0, 0); + * + * // Top-right. + * // u: 300, v: 0 + * vertex(30, 0, 0, 300, 0); + * + * // Bottom-right. + * // u: 300, v: 500 + * vertex(30, 50, 0, 300, 500); + * + * // Bottom-left. + * // u: 0, v: 500 + * vertex(0, 50, 0, 0, 500); + * + * endShape(); + * + * + * `textureWrap()` controls how textures behave when their uv's go beyond the + * texture. Doing so can produce interesting visual effects such as tiling. + * For example, the custom shape above could have u-coordinates are greater + * than the image’s width: + * + * + * // Apply the image as a texture. + * texture(img); + * + * // Draw the rectangle. + * beginShape(); + * vertex(0, 0, 0, 0, 0); + * + * // Top-right. + * // u: 600 + * vertex(30, 0, 0, 600, 0); + * + * // Bottom-right. + * // u: 600 + * vertex(30, 50, 0, 600, 500); + * + * vertex(0, 50, 0, 0, 500); + * endShape(); + * + * + * The u-coordinates of 600 are greater than the texture image’s width of 300. + * This creates interesting possibilities. + * + * The first parameter, `wrapX`, accepts three possible constants. If `CLAMP` + * is passed, as in `textureWrap(CLAMP)`, the pixels at the edge of the + * texture will extend to the shape’s edges. If `REPEAT` is passed, as in + * `textureWrap(REPEAT)`, the texture will tile repeatedly until reaching the + * shape’s edges. If `MIRROR` is passed, as in `textureWrap(MIRROR)`, the + * texture will tile repeatedly until reaching the shape’s edges, flipping + * its orientation between tiles. By default, textures `CLAMP`. + * + * The second parameter, `wrapY`, is optional. It accepts the same three + * constants, `CLAMP`, `REPEAT`, and `MIRROR`. If one of these constants is + * passed, as in `textureWRAP(MIRROR, REPEAT)`, then the texture will `MIRROR` + * horizontally and `REPEAT` vertically. By default, `wrapY` will be set to + * the same value as `wrapX`. + * + * Note: `textureWrap()` can only be used in WebGL mode. + * + * @method textureWrap + * @param {Constant} wrapX either CLAMP, REPEAT, or MIRROR + * @param {Constant} [wrapY] either CLAMP, REPEAT, or MIRROR + * + * @example + *
        + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies128.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'An image of a landscape occupies the top-left corner of a square. Its edge colors smear to cover the other thre quarters of the square.' + * ); + * } + * + * function draw() { + * background(0); + * + * // Set the texture mode. + * textureMode(NORMAL); + * + * // Set the texture wrapping. + * // Note: CLAMP is the default mode. + * textureWrap(CLAMP); + * + * // Apply the image as a texture. + * texture(img); + * + * // Style the shape. + * noStroke(); + * + * // Draw the shape. + * // Use uv coordinates > 1. + * beginShape(); + * vertex(-30, -30, 0, 0, 0); + * vertex(30, -30, 0, 2, 0); + * vertex(30, 30, 0, 2, 2); + * vertex(-30, 30, 0, 0, 2); + * endShape(); + * } + * + *
        + * + *
        + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies128.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('Four identical images of a landscape arranged in a grid.'); + * } + * + * function draw() { + * background(0); + * + * // Set the texture mode. + * textureMode(NORMAL); + * + * // Set the texture wrapping. + * textureWrap(REPEAT); + * + * // Apply the image as a texture. + * texture(img); + * + * // Style the shape. + * noStroke(); + * + * // Draw the shape. + * // Use uv coordinates > 1. + * beginShape(); + * vertex(-30, -30, 0, 0, 0); + * vertex(30, -30, 0, 2, 0); + * vertex(30, 30, 0, 2, 2); + * vertex(-30, 30, 0, 0, 2); + * endShape(); + * } + * + *
        + * + *
        + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies128.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'Four identical images of a landscape arranged in a grid. The images are reflected horizontally and vertically, creating a kaleidoscope effect.' + * ); + * } + * + * function draw() { + * background(0); + * + * // Set the texture mode. + * textureMode(NORMAL); + * + * // Set the texture wrapping. + * textureWrap(MIRROR); + * + * // Apply the image as a texture. + * texture(img); + * + * // Style the shape. + * noStroke(); + * + * // Draw the shape. + * // Use uv coordinates > 1. + * beginShape(); + * vertex(-30, -30, 0, 0, 0); + * vertex(30, -30, 0, 2, 0); + * vertex(30, 30, 0, 2, 2); + * vertex(-30, 30, 0, 0, 2); + * endShape(); + * } + * + *
        + * + *
        + * + * let img; + * + * function preload() { + * img = loadImage('assets/rockies128.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'Four identical images of a landscape arranged in a grid. The top row and bottom row are reflections of each other.' + * ); + * } + * + * function draw() { + * background(0); + * + * // Set the texture mode. + * textureMode(NORMAL); + * + * // Set the texture wrapping. + * textureWrap(REPEAT, MIRROR); + * + * // Apply the image as a texture. + * texture(img); + * + * // Style the shape. + * noStroke(); + * + * // Draw the shape. + * // Use uv coordinates > 1. + * beginShape(); + * vertex(-30, -30, 0, 0, 0); + * vertex(30, -30, 0, 2, 0); + * vertex(30, 30, 0, 2, 2); + * vertex(-30, 30, 0, 0, 2); + * endShape(); + * } + * + *
        + */ + _main.default.prototype.textureWrap = function (wrapX) { + var wrapY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : wrapX; + this._renderer.textureWrapX = wrapX; + this._renderer.textureWrapY = wrapY; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this._renderer.textures.values() [Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var texture = _step.value; + texture.setWrapMode(wrapX, wrapY); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + }; + /** + * Sets the current material as a normal material. + * + * A normal material sets surfaces facing the x-axis to red, those facing the + * y-axis to green, and those facing the z-axis to blue. Normal material isn't + * affected by light. It’s often used as a placeholder material when debugging. + * + * Note: `normalMaterial()` can only be used in WebGL mode. + * + * @method normalMaterial + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A multicolor torus drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Style the torus. + * normalMaterial(); + * + * // Draw the torus. + * torus(30); + * } + * + *
        + */ + _main.default.prototype.normalMaterial = function () { + this._assert3d('normalMaterial'); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('normalMaterial', args); + this._renderer.drawMode = constants.FILL; + this._renderer._useSpecularMaterial = false; + this._renderer._useEmissiveMaterial = false; + this._renderer._useNormalMaterial = true; + this._renderer.curFillColor = [ + 1, + 1, + 1, + 1 + ]; + this._renderer._setProperty('_doFill', true); + this.noStroke(); + return this; + }; + /** + * Sets the ambient color of shapes’ surface material. + * + * The `ambientMaterial()` color sets the components of the + * ambientLight() color that shapes will + * reflect. For example, calling `ambientMaterial(255, 255, 0)` would cause a + * shape to reflect red and green light, but not blue light. + * + * `ambientMaterial()` can be called three ways with different parameters to + * set the material’s color. + * + * The first way to call `ambientMaterial()` has one parameter, `gray`. + * Grayscale values between 0 and 255, as in `ambientMaterial(50)`, can be + * passed to set the material’s color. Higher grayscale values make shapes + * appear brighter. + * + * The second way to call `ambientMaterial()` has one parameter, `color`. A + * p5.Color object, an array of color values, or a + * CSS color string, as in `ambientMaterial('magenta')`, can be passed to set + * the material’s color. + * + * The third way to call `ambientMaterial()` has three parameters, `v1`, `v2`, + * and `v3`. RGB, HSB, or HSL values, as in `ambientMaterial(255, 0, 0)`, can + * be passed to set the material’s colors. Color values will be interpreted + * using the current colorMode(). + * + * Note: `ambientMaterial()` can only be used in WebGL mode. + * + * @method ambientMaterial + * @param {Number} v1 red or hue value in the current + * colorMode(). + * @param {Number} v2 green or saturation value in the + * current colorMode(). + * @param {Number} v3 blue, brightness, or lightness value in the + * current colorMode(). + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A magenta cube drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a magenta ambient light. + * ambientLight(255, 0, 255); + * + * // Draw the box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A purple cube drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a magenta ambient light. + * ambientLight(255, 0, 255); + * + * // Add a dark gray ambient material. + * ambientMaterial(150); + * + * // Draw the box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A red cube drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a magenta ambient light. + * ambientLight(255, 0, 255); + * + * // Add a yellow ambient material using RGB values. + * ambientMaterial(255, 255, 0); + * + * // Draw the box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A red cube drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a magenta ambient light. + * ambientLight(255, 0, 255); + * + * // Add a yellow ambient material using a p5.Color object. + * let c = color(255, 255, 0); + * ambientMaterial(c); + * + * // Draw the box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A red cube drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a magenta ambient light. + * ambientLight(255, 0, 255); + * + * // Add a yellow ambient material using a color string. + * ambientMaterial('yellow'); + * + * // Draw the box. + * box(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A yellow cube drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a white ambient light. + * ambientLight(255, 255, 255); + * + * // Add a yellow ambient material using a color string. + * ambientMaterial('yellow'); + * + * // Draw the box. + * box(); + * } + * + *
        + */ + /** + * @method ambientMaterial + * @param {Number} gray grayscale value between 0 (black) and 255 (white). + * @chainable + */ + /** + * @method ambientMaterial + * @param {p5.Color|Number[]|String} color + * color as a p5.Color object, + * an array of color values, or a CSS string. + * @chainable + */ + _main.default.prototype.ambientMaterial = function (v1, v2, v3) { + this._assert3d('ambientMaterial'); + _main.default._validateParameters('ambientMaterial', arguments); + var color = _main.default.prototype.color.apply(this, arguments); + this._renderer._hasSetAmbient = true; + this._renderer.curAmbientColor = color._array; + this._renderer._useNormalMaterial = false; + this._renderer._enableLighting = true; + this._renderer._setProperty('_doFill', true); + return this; + }; + /** + * Sets the emissive color of shapes’ surface material. + * + * The `emissiveMaterial()` color sets a color shapes display at full + * strength, regardless of lighting. This can give the appearance that a shape + * is glowing. However, emissive materials don’t actually emit light that + * can affect surrounding objects. + * + * `emissiveMaterial()` can be called three ways with different parameters to + * set the material’s color. + * + * The first way to call `emissiveMaterial()` has one parameter, `gray`. + * Grayscale values between 0 and 255, as in `emissiveMaterial(50)`, can be + * passed to set the material’s color. Higher grayscale values make shapes + * appear brighter. + * + * The second way to call `emissiveMaterial()` has one parameter, `color`. A + * p5.Color object, an array of color values, or a + * CSS color string, as in `emissiveMaterial('magenta')`, can be passed to set + * the material’s color. + * + * The third way to call `emissiveMaterial()` has four parameters, `v1`, `v2`, + * `v3`, and `alpha`. `alpha` is optional. RGBA, HSBA, or HSLA values can be + * passed to set the material’s colors, as in `emissiveMaterial(255, 0, 0)` or + * `emissiveMaterial(255, 0, 0, 30)`. Color values will be interpreted using + * the current colorMode(). + * + * Note: `emissiveMaterial()` can only be used in WebGL mode. + * + * @method emissiveMaterial + * @param {Number} v1 red or hue value in the current + * colorMode(). + * @param {Number} v2 green or saturation value in the + * current colorMode(). + * @param {Number} v3 blue, brightness, or lightness value in the + * current colorMode(). + * @param {Number} [alpha] alpha value in the current + * colorMode(). + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A red cube drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a white ambient light. + * ambientLight(255, 255, 255); + * + * // Add a red emissive material using RGB values. + * emissiveMaterial(255, 0, 0); + * + * // Draw the box. + * box(); + * } + * + *
        + */ + /** + * @method emissiveMaterial + * @param {Number} gray grayscale value between 0 (black) and 255 (white). + * @chainable + */ + /** + * @method emissiveMaterial + * @param {p5.Color|Number[]|String} color + * color as a p5.Color object, + * an array of color values, or a CSS string. + * @chainable + */ + _main.default.prototype.emissiveMaterial = function (v1, v2, v3, a) { + this._assert3d('emissiveMaterial'); + _main.default._validateParameters('emissiveMaterial', arguments); + var color = _main.default.prototype.color.apply(this, arguments); + this._renderer.curEmissiveColor = color._array; + this._renderer._useEmissiveMaterial = true; + this._renderer._useNormalMaterial = false; + this._renderer._enableLighting = true; + return this; + }; + /** + * Sets the specular color of shapes’ surface material. + * + * The `specularMaterial()` color sets the components of light color that + * glossy coats on shapes will reflect. For example, calling + * `specularMaterial(255, 255, 0)` would cause a shape to reflect red and + * green light, but not blue light. + * + * Unlike ambientMaterial(), + * `specularMaterial()` will reflect the full color of light sources including + * directionalLight(), + * pointLight(), + * and spotLight(). This is what gives it shapes + * their "shiny" appearance. The material’s shininess can be controlled by the + * shininess() function. + * + * `specularMaterial()` can be called three ways with different parameters to + * set the material’s color. + * + * The first way to call `specularMaterial()` has one parameter, `gray`. + * Grayscale values between 0 and 255, as in `specularMaterial(50)`, can be + * passed to set the material’s color. Higher grayscale values make shapes + * appear brighter. + * + * The second way to call `specularMaterial()` has one parameter, `color`. A + * p5.Color> object, an array of color values, or a CSS + * color string, as in `specularMaterial('magenta')`, can be passed to set the + * material’s color. + * + * The third way to call `specularMaterial()` has four parameters, `v1`, `v2`, + * `v3`, and `alpha`. `alpha` is optional. RGBA, HSBA, or HSLA values can be + * passed to set the material’s colors, as in `specularMaterial(255, 0, 0)` or + * `specularMaterial(255, 0, 0, 30)`. Color values will be interpreted using + * the current colorMode(). + * + * @method specularMaterial + * @param {Number} gray grayscale value between 0 (black) and 255 (white). + * @param {Number} [alpha] alpha value in the current current + * colorMode(). + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click the canvas to apply a specular material. + * + * let isGlossy = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A red torus drawn on a gray background. It becomes glossy when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a white point light at the top-right. + * pointLight(255, 255, 255, 30, -40, 30); + * + * // Add a glossy coat if the user has double-clicked. + * if (isGlossy === true) { + * specularMaterial(255); + * shininess(50); + * } + * + * // Style the torus. + * noStroke(); + * fill(255, 0, 0); + * + * // Draw the torus. + * torus(30); + * } + * + * // Make the torus glossy when the user double-clicks. + * function doubleClicked() { + * isGlossy = true; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click the canvas to apply a specular material. + * + * let isGlossy = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a white point light at the top-right. + * pointLight(255, 255, 255, 30, -40, 30); + * + * // Add a glossy green coat if the user has double-clicked. + * if (isGlossy === true) { + * specularMaterial(0, 255, 0); + * shininess(50); + * } + * + * // Style the torus. + * noStroke(); + * fill(255, 0, 0); + * + * // Draw the torus. + * torus(30); + * } + * + * // Make the torus glossy when the user double-clicks. + * function doubleClicked() { + * isGlossy = true; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click the canvas to apply a specular material. + * + * let isGlossy = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a white point light at the top-right. + * pointLight(255, 255, 255, 30, -40, 30); + * + * // Add a glossy green coat if the user has double-clicked. + * if (isGlossy === true) { + * // Create a p5.Color object. + * let c = color('green'); + * specularMaterial(c); + * shininess(50); + * } + * + * // Style the torus. + * noStroke(); + * fill(255, 0, 0); + * + * // Draw the torus. + * torus(30); + * } + * + * // Make the torus glossy when the user double-clicks. + * function doubleClicked() { + * isGlossy = true; + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * // Double-click the canvas to apply a specular material. + * + * let isGlossy = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on a white point light at the top-right. + * pointLight(255, 255, 255, 30, -40, 30); + * + * // Add a glossy green coat if the user has double-clicked. + * if (isGlossy === true) { + * specularMaterial('#00FF00'); + * shininess(50); + * } + * + * // Style the torus. + * noStroke(); + * fill(255, 0, 0); + * + * // Draw the torus. + * torus(30); + * } + * + * // Make the torus glossy when the user double-clicks. + * function doubleClicked() { + * isGlossy = true; + * } + * + *
        + */ + /** + * @method specularMaterial + * @param {Number} v1 red or hue value in + * the current colorMode(). + * @param {Number} v2 green or saturation value + * in the current colorMode(). + * @param {Number} v3 blue, brightness, or lightness value + * in the current colorMode(). + * @param {Number} [alpha] + * @chainable + */ + /** + * @method specularMaterial + * @param {p5.Color|Number[]|String} color + * color as a p5.Color object, + * an array of color values, or a CSS string. + * @chainable + */ + _main.default.prototype.specularMaterial = function (v1, v2, v3, alpha) { + this._assert3d('specularMaterial'); + _main.default._validateParameters('specularMaterial', arguments); + var color = _main.default.prototype.color.apply(this, arguments); + this._renderer.curSpecularColor = color._array; + this._renderer._useSpecularMaterial = true; + this._renderer._useNormalMaterial = false; + this._renderer._enableLighting = true; + return this; + }; + /** + * Sets the amount of gloss ("shininess") of a + * specularMaterial(). + * + * Shiny materials focus reflected light more than dull materials. + * `shininess()` affects the way materials reflect light sources including + * directionalLight(), + * pointLight(), + * and spotLight(). + * + * The parameter, `shine`, is a number that sets the amount of shininess. + * `shine` must be greater than 1, which is its default value. + * + * @method shininess + * @param {Number} shine amount of shine. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'Two red spheres drawn on a gray background. White light reflects from their surfaces as the mouse moves. The right sphere is shinier than the left sphere.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Turn on a red ambient light. + * ambientLight(255, 0, 0); + * + * // Get the mouse's coordinates. + * let mx = mouseX - 50; + * let my = mouseY - 50; + * + * // Turn on a white point light that follows the mouse. + * pointLight(255, 255, 255, mx, my, 50); + * + * // Style the sphere. + * noStroke(); + * + * // Add a specular material with a grayscale value. + * specularMaterial(255); + * + * // Draw the left sphere with low shininess. + * translate(-25, 0, 0); + * shininess(10); + * sphere(20); + * + * // Draw the right sphere with high shininess. + * translate(50, 0, 0); + * shininess(100); + * sphere(20); + * } + * + *
        + */ + _main.default.prototype.shininess = function (shine) { + this._assert3d('shininess'); + _main.default._validateParameters('shininess', arguments); + if (shine < 1) { + shine = 1; + } + this._renderer._useShininess = shine; + return this; + }; + /** + * Sets the amount of "metalness" of a + * specularMaterial(). + * + * `metalness()` can make materials appear more metallic. It affects the way + * materials reflect light sources including + * affects the way materials reflect light sources including + * directionalLight(), + * pointLight(), + * spotLight(), and + * imageLight(). + * + * The parameter, `metallic`, is a number that sets the amount of metalness. + * `metallic` must be greater than 1, which is its default value. Higher + * values, such as `metalness(100)`, make specular materials appear more + * metallic. + * + * @method metalness + * @param {Number} metallic amount of metalness. + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'Two blue spheres drawn on a gray background. White light reflects from their surfaces as the mouse moves. The right sphere is more metallic than the left sphere.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Turn on an ambient light. + * ambientLight(200); + * + * // Get the mouse's coordinates. + * let mx = mouseX - 50; + * let my = mouseY - 50; + * + * // Turn on a white point light that follows the mouse. + * pointLight(255, 255, 255, mx, my, 50); + * + * // Style the spheres. + * noStroke(); + * fill(30, 30, 255); + * specularMaterial(255); + * shininess(20); + * + * // Draw the left sphere with low metalness. + * translate(-25, 0, 0); + * metalness(1); + * sphere(20); + * + * // Draw the right sphere with high metalness. + * translate(50, 0, 0); + * metalness(50); + * sphere(20); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let img; + * + * function preload() { + * img = loadImage('assets/outdoor_spheremap.jpg'); + * } + * + * function setup() { + * createCanvas(100 ,100 ,WEBGL); + * + * describe( + * 'Two spheres floating above a landscape. The surface of the spheres reflect the landscape. The right sphere is more reflective than the left sphere.' + * ); + * } + * + * function draw() { + * // Add the panorama. + * panorama(img); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Use the image as a light source. + * imageLight(img); + * + * // Style the spheres. + * noStroke(); + * specularMaterial(50); + * shininess(200); + * + * // Draw the left sphere with low metalness. + * translate(-25, 0, 0); + * metalness(1); + * sphere(20); + * + * // Draw the right sphere with high metalness. + * translate(50, 0, 0); + * metalness(50); + * sphere(20); + * } + * + *
        + */ + _main.default.prototype.metalness = function (metallic) { + this._assert3d('metalness'); + var metalMix = 1 - Math.exp( - metallic / 100); + this._renderer._useMetalness = metalMix; + return this; + }; + /** + * @private blends colors according to color components. + * If alpha value is less than 1, or non-standard blendMode + * we need to enable blending on our gl context. + * @param {Number[]} color The currently set color, with values in 0-1 range + * @param {Boolean} [hasTransparency] Whether the shape being drawn has other + * transparency internally, e.g. via vertex colors + * @return {Number[]]} Normalized numbers array + */ + _main.default.RendererGL.prototype._applyColorBlend = function (colors, hasTransparency) { + var gl = this.GL; + var isTexture = this.drawMode === constants.TEXTURE; + var doBlend = hasTransparency || this.userFillShader || this.userStrokeShader || this.userPointShader || isTexture || this.curBlendMode !== constants.BLEND || colors[colors.length - 1] < 1 || this._isErasing; + if (doBlend !== this._isBlending) { + if (doBlend || this.curBlendMode !== constants.BLEND && this.curBlendMode !== constants.ADD) { + gl.enable(gl.BLEND); + } else { + gl.disable(gl.BLEND); + } + gl.depthMask(true); + this._isBlending = doBlend; + } + this._applyBlendMode(); + return colors; + }; + /** + * @private sets blending in gl context to curBlendMode + * @param {Number[]} color [description] + * @return {Number[]} Normalized numbers array + */ + _main.default.RendererGL.prototype._applyBlendMode = function () { + if (this._cachedBlendMode === this.curBlendMode) { + return; + } + var gl = this.GL; + switch (this.curBlendMode) { + case constants.BLEND: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case constants.ADD: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE); + break; + case constants.REMOVE: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA); + break; + case constants.MULTIPLY: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA); + break; + case constants.SCREEN: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR); + break; + case constants.EXCLUSION: + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE_MINUS_DST_COLOR, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE); + break; + case constants.REPLACE: + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + break; + case constants.SUBTRACT: + gl.blendEquationSeparate(gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case constants.DARKEST: + if (this.blendExt) { + gl.blendEquationSeparate(this.blendExt.MIN || this.blendExt.MIN_EXT, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE); + } else { + console.warn('blendMode(DARKEST) does not work in your browser in WEBGL mode.'); + } + break; + case constants.LIGHTEST: + if (this.blendExt) { + gl.blendEquationSeparate(this.blendExt.MAX || this.blendExt.MAX_EXT, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE); + } else { + console.warn('blendMode(LIGHTEST) does not work in your browser in WEBGL mode.'); + } + break; + default: + console.error('Oops! Somehow RendererGL set curBlendMode to an unsupported mode.'); + break; + } + if (!this._isErasing) { + this._cachedBlendMode = this.curBlendMode; + } + }; + var _default = _main.default; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + './p5.Texture': 362, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.join': 183, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 352: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.hypot'); + _dereq_('core-js/modules/es.string.sub'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * @module 3D + * @submodule Camera + * @requires core + */ + //////////////////////////////////////////////////////////////////////////////// + // p5.Prototype Methods + //////////////////////////////////////////////////////////////////////////////// + /** + * Sets the position and orientation of the current camera in a 3D sketch. + * + * `camera()` allows objects to be viewed from different angles. It has nine + * parameters that are all optional. + * + * The first three parameters, `x`, `y`, and `z`, are the coordinates of the + * camera’s position. For example, calling `camera(0, 0, 0)` places the camera + * at the origin `(0, 0, 0)`. By default, the camera is placed at + * `(0, 0, 800)`. + * + * The next three parameters, `centerX`, `centerY`, and `centerZ` are the + * coordinates of the point where the camera faces. For example, calling + * `camera(0, 0, 0, 10, 20, 30)` places the camera at the origin `(0, 0, 0)` + * and points it at `(10, 20, 30)`. By default, the camera points at the + * origin `(0, 0, 0)`. + * + * The last three parameters, `upX`, `upY`, and `upZ` are the components of + * the "up" vector. The "up" vector orients the camera’s y-axis. For example, + * calling `camera(0, 0, 0, 10, 20, 30, 0, -1, 0)` places the camera at the + * origin `(0, 0, 0)`, points it at `(10, 20, 30)`, and sets the "up" vector + * to `(0, -1, 0)` which is like holding it upside-down. By default, the "up" + * vector is `(0, 1, 0)`. + * + * Note: `camera()` can only be used in WebGL mode. + * + * @method camera + * @constructor + * @for p5 + * @param {Number} [x] x-coordinate of the camera. Defaults to 0. + * @param {Number} [y] y-coordinate of the camera. Defaults to 0. + * @param {Number} [z] z-coordinate of the camera. Defaults to 800. + * @param {Number} [centerX] x-coordinate of the point the camera faces. Defaults to 0. + * @param {Number} [centerY] y-coordinate of the point the camera faces. Defaults to 0. + * @param {Number} [centerZ] z-coordinate of the point the camera faces. Defaults to 0. + * @param {Number} [upX] x-component of the camera’s "up" vector. Defaults to 0. + * @param {Number} [upY] y-component of the camera’s "up" vector. Defaults to 1. + * @param {Number} [upZ] z-component of the camera’s "up" vector. Defaults to 0. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Move the camera to the top-right. + * camera(200, -400, 800); + * + * // Draw the box. + * box(); + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube apperas to sway left and right on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the camera's x-coordinate. + * let x = 400 * cos(frameCount * 0.01); + * + * // Orbit the camera around the box. + * camera(x, -400, 800); + * + * // Draw the box. + * box(); + * } + * + *
        + * + *
        + * + * // Adjust the range sliders to change the camera's position. + * + * let xSlider; + * let ySlider; + * let zSlider; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create slider objects to set the camera's coordinates. + * xSlider = createSlider(-400, 400, 400); + * xSlider.position(0, 100); + * xSlider.size(100); + * ySlider = createSlider(-400, 400, -200); + * ySlider.position(0, 120); + * ySlider.size(100); + * zSlider = createSlider(0, 1600, 800); + * zSlider.position(0, 140); + * zSlider.size(100); + * + * describe( + * 'A white cube drawn against a gray background. Three range sliders appear beneath the image. The camera position changes when the user moves the sliders.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Get the camera's coordinates from the sliders. + * let x = xSlider.value(); + * let y = ySlider.value(); + * let z = zSlider.value(); + * + * // Move the camera. + * camera(x, y, z); + * + * // Draw the box. + * box(); + * } + * + *
        + */ + + _main.default.prototype.camera = function () { + var _this$_renderer$_curC; + this._assert3d('camera'); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _main.default._validateParameters('camera', args); + (_this$_renderer$_curC = this._renderer._curCamera).camera.apply(_this$_renderer$_curC, args); + return this; + }; + /** + * Sets a perspective projection for the current camera in a 3D sketch. + * + * In a perspective projection, shapes that are further from the camera appear + * smaller than shapes that are near the camera. This technique, called + * foreshortening, creates realistic 3D scenes. It’s applied by default in + * WebGL mode. + * + * `perspective()` changes the camera’s perspective by changing its viewing + * frustum. The frustum is the volume of space that’s visible to the camera. + * Its shape is a pyramid with its top cut off. The camera is placed where + * the top of the pyramid should be and views everything between the frustum’s + * top (near) plane and its bottom (far) plane. + * + * The first parameter, `fovy`, is the camera’s vertical field of view. It’s + * an angle that describes how tall or narrow a view the camera has. For + * example, calling `perspective(0.5)` sets the camera’s vertical field of + * view to 0.5 radians. By default, `fovy` is calculated based on the sketch’s + * height and the camera’s default z-coordinate, which is 800. The formula for + * the default `fovy` is `2 * atan(height / 2 / 800)`. + * + * The second parameter, `aspect`, is the camera’s aspect ratio. It’s a number + * that describes the ratio of the top plane’s width to its height. For + * example, calling `perspective(0.5, 1.5)` sets the camera’s field of view to + * 0.5 radians and aspect ratio to 1.5, which would make shapes appear thinner + * on a square canvas. By default, aspect is set to `width / height`. + * + * The third parameter, `near`, is the distance from the camera to the near + * plane. For example, calling `perspective(0.5, 1.5, 100)` sets the camera’s + * field of view to 0.5 radians, its aspect ratio to 1.5, and places the near + * plane 100 pixels from the camera. Any shapes drawn less than 100 pixels + * from the camera won’t be visible. By default, near is set to `0.1 * 800`, + * which is 1/10th the default distance between the camera and the origin. + * + * The fourth parameter, `far`, is the distance from the camera to the far + * plane. For example, calling `perspective(0.5, 1.5, 100, 10000)` sets the + * camera’s field of view to 0.5 radians, its aspect ratio to 1.5, places the + * near plane 100 pixels from the camera, and places the far plane 10,000 + * pixels from the camera. Any shapes drawn more than 10,000 pixels from the + * camera won’t be visible. By default, far is set to `10 * 800`, which is 10 + * times the default distance between the camera and the origin. + * + * Note: `perspective()` can only be used in WebGL mode. + * + * @method perspective + * @for p5 + * @param {Number} [fovy] camera frustum vertical field of view. Defaults to + * `2 * atan(height / 2 / 800)`. + * @param {Number} [aspect] camera frustum aspect ratio. Defaults to + * `width / height`. + * @param {Number} [near] distance from the camera to the near clipping plane. + * Defaults to `0.1 * 800`. + * @param {Number} [far] distance from the camera to the far clipping plane. + * Defaults to `10 * 800`. + * @chainable + * + * @example + *
        + * + * // Double-click to squeeze the box. + * + * let isSqueezed = false; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white rectangular prism on a gray background. The box appears to become thinner when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Place the camera at the top-right. + * camera(400, -400, 800); + * + * if (isSqueezed === true) { + * // Set fovy to 0.2. + * // Set aspect to 1.5. + * perspective(0.2, 1.5); + * } + * + * // Draw the box. + * box(); + * } + * + * // Change the camera's perspective when the user double-clicks. + * function doubleClicked() { + * isSqueezed = true; + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white rectangular prism on a gray background. The prism moves away from the camera until it disappears.'); + * } + * + * function draw() { + * background(200); + * + * // Place the camera at the top-right. + * camera(400, -400, 800); + * + * // Set fovy to 0.2. + * // Set aspect to 1.5. + * // Set near to 600. + * // Set far to 1200. + * perspective(0.2, 1.5, 600, 1200); + * + * // Move the origin away from the camera. + * let x = -frameCount; + * let y = frameCount; + * let z = -2 * frameCount; + * translate(x, y, z); + * + * // Draw the box. + * box(); + * } + * + *
        + */ + _main.default.prototype.perspective = function () { + var _this$_renderer$_curC2; + this._assert3d('perspective'); + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + _main.default._validateParameters('perspective', args); + (_this$_renderer$_curC2 = this._renderer._curCamera).perspective.apply(_this$_renderer$_curC2, args); + return this; + }; + /** + * Enables or disables perspective for lines in 3D sketches. + * + * In WebGL mode, lines can be drawn with a thinner stroke when they’re + * further from the camera. Doing so gives them a more realistic appearance. + * + * By default, lines are drawn differently based on the type of perspective + * being used: + * - `perspective()` and `frustum()` simulate a realistic perspective. In + * these modes, stroke weight is affected by the line’s distance from the + * camera. Doing so results in a more natural appearance. `perspective()` is + * the default mode for 3D sketches. + * - `ortho()` doesn’t simulate a realistic perspective. In this mode, stroke + * weights are consistent regardless of the line’s distance from the camera. + * Doing so results in a more predictable and consistent appearance. + * + * `linePerspective()` can override the default line drawing mode. + * + * The parameter, `enable`, is optional. It’s a `Boolean` value that sets the + * way lines are drawn. If `true` is passed, as in `linePerspective(true)`, + * then lines will appear thinner when they are further from the camera. If + * `false` is passed, as in `linePerspective(false)`, then lines will have + * consistent stroke weights regardless of their distance from the camera. By + * default, `linePerspective()` is enabled. + * + * Calling `linePerspective()` without passing an argument returns `true` if + * it's enabled and `false` if not. + * + * Note: `linePerspective()` can only be used in WebGL mode. + * + * @method linePerspective + * @for p5 + * @param {boolean} enable whether to enable line perspective. + * + * @example + *
        + * + * // Double-click the canvas to toggle the line perspective. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'A white cube with black edges on a gray background. Its edges toggle between thick and thin when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 600); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -40); + * box(10); + * } + * } + * + * // Toggle the line perspective when the user double-clicks. + * function doubleClicked() { + * let isEnabled = linePerspective(); + * linePerspective(!isEnabled); + * } + * + *
        + * + *
        + * + * // Double-click the canvas to toggle the line perspective. + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe( + * 'A row of cubes with black edges on a gray background. Their edges toggle between thick and thin when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Use an orthographic projection. + * ortho(); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 600); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -40); + * box(10); + * } + * } + * + * // Toggle the line perspective when the user double-clicks. + * function doubleClicked() { + * let isEnabled = linePerspective(); + * linePerspective(!isEnabled); + * } + * + *
        + */ + /** + * @method linePerspective + * @return {boolean} whether line perspective is enabled. + */ + _main.default.prototype.linePerspective = function (enable) { + _main.default._validateParameters('linePerspective', arguments); + if (!(this._renderer instanceof _main.default.RendererGL)) { + throw new Error('linePerspective() must be called in WebGL mode.'); + } + if (enable !== undefined) { + // Set the line perspective if enable is provided + this._renderer._curCamera.useLinePerspective = enable; + } else { + // If no argument is provided, return the current value + return this._renderer._curCamera.useLinePerspective; + } + }; + /** + * Sets an orthographic projection for the current camera in a 3D sketch. + * + * In an orthographic projection, shapes with the same size always appear the + * same size, regardless of whether they are near or far from the camera. + * + * `ortho()` changes the camera’s perspective by changing its viewing frustum + * from a truncated pyramid to a rectangular prism. The camera is placed in + * front of the frustum and views everything between the frustum’s near plane + * and its far plane. `ortho()` has six optional parameters to define the + * frustum. + * + * The first four parameters, `left`, `right`, `bottom`, and `top`, set the + * coordinates of the frustum’s sides, bottom, and top. For example, calling + * `ortho(-100, 100, 200, -200)` creates a frustum that’s 200 pixels wide and + * 400 pixels tall. By default, these coordinates are set based on the + * sketch’s width and height, as in + * `ortho(-width / 2, width / 2, -height / 2, height / 2)`. + * + * The last two parameters, `near` and `far`, set the distance of the + * frustum’s near and far plane from the camera. For example, calling + * `ortho(-100, 100, 200, 200, 50, 1000)` creates a frustum that’s 200 pixels + * wide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000 + * pixels from the camera. By default, `near` and `far` are set to 0 and + * `max(width, height) + 800`, respectively. + * + * Note: `ortho()` can only be used in WebGL mode. + * + * @method ortho + * @for p5 + * @param {Number} [left] x-coordinate of the frustum’s left plane. Defaults to `-width / 2`. + * @param {Number} [right] x-coordinate of the frustum’s right plane. Defaults to `width / 2`. + * @param {Number} [bottom] y-coordinate of the frustum’s bottom plane. Defaults to `height / 2`. + * @param {Number} [top] y-coordinate of the frustum’s top plane. Defaults to `-height / 2`. + * @param {Number} [near] z-coordinate of the frustum’s near plane. Defaults to 0. + * @param {Number} [far] z-coordinate of the frustum’s far plane. Defaults to `max(width, height) + 800`. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A row of tiny, white cubes on a gray background. All the cubes appear the same size.'); + * } + * + * function draw() { + * background(200); + * + * // Apply an orthographic projection. + * ortho(); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 600); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -40); + * box(10); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Apply an orthographic projection. + * // Center the frustum. + * // Set its width and height to 20. + * // Place its near plane 300 pixels from the camera. + * // Place its far plane 350 pixels from the camera. + * ortho(-10, 10, -10, 10, 300, 350); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 600); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -40); + * box(10); + * } + * } + * + *
        + */ + _main.default.prototype.ortho = function () { + var _this$_renderer$_curC3; + this._assert3d('ortho'); + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + _main.default._validateParameters('ortho', args); + (_this$_renderer$_curC3 = this._renderer._curCamera).ortho.apply(_this$_renderer$_curC3, args); + return this; + }; + /** + * Sets the frustum of the current camera in a 3D sketch. + * + * In a frustum projection, shapes that are further from the camera appear + * smaller than shapes that are near the camera. This technique, called + * foreshortening, creates realistic 3D scenes. + * + * `frustum()` changes the default camera’s perspective by changing its + * viewing frustum. The frustum is the volume of space that’s visible to the + * camera. The frustum’s shape is a pyramid with its top cut off. The camera + * is placed where the top of the pyramid should be and points towards the + * base of the pyramid. It views everything within the frustum. + * + * The first four parameters, `left`, `right`, `bottom`, and `top`, set the + * coordinates of the frustum’s sides, bottom, and top. For example, calling + * `frustum(-100, 100, 200, -200)` creates a frustum that’s 200 pixels wide + * and 400 pixels tall. By default, these coordinates are set based on the + * sketch’s width and height, as in + * `ortho(-width / 20, width / 20, height / 20, -height / 20)`. + * + * The last two parameters, `near` and `far`, set the distance of the + * frustum’s near and far plane from the camera. For example, calling + * `ortho(-100, 100, 200, -200, 50, 1000)` creates a frustum that’s 200 pixels + * wide, 400 pixels tall, starts 50 pixels from the camera, and ends 1,000 + * pixels from the camera. By default, near is set to `0.1 * 800`, which is + * 1/10th the default distance between the camera and the origin. `far` is set + * to `10 * 800`, which is 10 times the default distance between the camera + * and the origin. + * + * Note: `frustum()` can only be used in WebGL mode. + * + * @method frustum + * @for p5 + * @param {Number} [left] x-coordinate of the frustum’s left plane. Defaults to `-width / 20`. + * @param {Number} [right] x-coordinate of the frustum’s right plane. Defaults to `width / 20`. + * @param {Number} [bottom] y-coordinate of the frustum’s bottom plane. Defaults to `height / 20`. + * @param {Number} [top] y-coordinate of the frustum’s top plane. Defaults to `-height / 20`. + * @param {Number} [near] z-coordinate of the frustum’s near plane. Defaults to `0.1 * 800`. + * @param {Number} [far] z-coordinate of the frustum’s far plane. Defaults to `10 * 800`. + * @chainable + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * describe('A row of white cubes on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Apply the default frustum projection. + * frustum(); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 600); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -40); + * box(10); + * } + * } + * + *
        + * + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * describe('A white cube on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Adjust the frustum. + * // Center it. + * // Set its width and height to 20 pixels. + * // Place its near plane 300 pixels from the camera. + * // Place its far plane 350 pixels from the camera. + * frustum(-10, 10, -10, 10, 300, 350); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 600); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -40); + * box(10); + * } + * } + * + *
        + */ + _main.default.prototype.frustum = function () { + var _this$_renderer$_curC4; + this._assert3d('frustum'); + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + _main.default._validateParameters('frustum', args); + (_this$_renderer$_curC4 = this._renderer._curCamera).frustum.apply(_this$_renderer$_curC4, args); + return this; + }; + //////////////////////////////////////////////////////////////////////////////// + // p5.Camera + //////////////////////////////////////////////////////////////////////////////// + /** + * Creates a new p5.Camera object and sets it + * as the current (active) camera. + * + * The new camera is initialized with a default position `(0, 0, 800)` and a + * default perspective projection. Its properties can be controlled with + * p5.Camera methods such as + * `myCamera.lookAt(0, 0, 0)`. + * + * Note: Every 3D sketch starts with a default camera initialized. + * This camera can be controlled with the functions + * camera(), + * perspective(), + * ortho(), and + * frustum() if it's the only camera in the scene. + * + * Note: `createCamera()` can only be used in WebGL mode. + * + * @method createCamera + * @return {p5.Camera} the new camera. + * @for p5 + * + * @example + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let usingCam1 = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * // Place it at the top-left. + * // Point it at the origin. + * cam2 = createCamera(); + * cam2.setPosition(400, -400, 800); + * cam2.lookAt(0, 0, 0); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe('A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Draw the box. + * box(); + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (usingCam1 === true) { + * setCamera(cam2); + * usingCam1 = false; + * } else { + * setCamera(cam1); + * usingCam1 = true; + * } + * } + * + *
        + */ + _main.default.prototype.createCamera = function () { + this._assert3d('createCamera'); + var _cam = new _main.default.Camera(this._renderer); + // compute default camera settings, then set a default camera + _cam._computeCameraDefaultSettings(); + _cam._setDefaultCamera(); + // set renderer current camera to the new camera + this._renderer._curCamera = _cam; + return _cam; + }; + /** + * A class to describe a camera for viewing a 3D sketch. + * + * Each `p5.Camera` object represents a camera that views a section of 3D + * space. It stores information about the camera’s position, orientation, and + * projection. + * + * In WebGL mode, the default camera is a `p5.Camera` object that can be + * controlled with the camera(), + * perspective(), + * ortho(), and + * frustum() functions. Additional cameras can be + * created with createCamera() and activated + * with setCamera(). + * + * Note: `p5.Camera`’s methods operate in two coordinate systems: + * - The “world” coordinate system describes positions in terms of their + * relationship to the origin along the x-, y-, and z-axes. For example, + * calling `myCamera.setPosition()` places the camera in 3D space using + * "world" coordinates. + * - The "local" coordinate system describes positions from the camera's point + * of view: left-right, up-down, and forward-backward. For example, calling + * `myCamera.move()` moves the camera along its own axes. + * + * @class p5.Camera + * @param {rendererGL} rendererGL instance of WebGL renderer + * + * @example + *
        + * + * let cam; + * let delta = 0.001; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube on a gray background. The cube goes in and out of view as the camera pans left and right.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Turn the camera left and right, called "panning". + * cam.pan(delta); + * + * // Switch directions every 120 frames. + * if (frameCount % 120 === 0) { + * delta *= -1; + * } + * + * // Draw the box. + * box(); + * } + * + *
        + * + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * // Place it at the top-left. + * // Point it at the origin. + * cam2 = createCamera(); + * cam2.setPosition(400, -400, 800); + * cam2.lookAt(0, 0, 0); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe( + * 'A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw the box. + * box(); + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + */ + _main.default.Camera = /*#__PURE__*/ function () { + function Camera(renderer) { + _classCallCheck(this, Camera); + this._renderer = renderer; + this.cameraType = 'default'; + this.useLinePerspective = true; + this.cameraMatrix = new _main.default.Matrix(); + this.projMatrix = new _main.default.Matrix(); + this.yScale = 1; + } /** + * The camera’s y-coordinate. + * + * By default, the camera’s y-coordinate is set to 0 in "world" space. + * + * @property {Number} eyeX + * @readonly + * + * @example + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube on a gray background. The text "eyeX: 0" is written in black beneath it.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the value of eyeX, rounded to the nearest integer. + * text(`eyeX: ${round(cam.eyeX)}`, 0, 55); + * } + * + *
        + * + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube on a gray background. The cube appears to move left and right as the camera moves. The text "eyeX: X" is written in black beneath the cube. X oscillates between -25 and 25.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Calculate the new x-coordinate. + * let x = 25 * sin(frameCount * 0.01); + * + * // Set the camera's position. + * cam.setPosition(x, -400, 800); + * + * // Display the value of eyeX, rounded to the nearest integer. + * text(`eyeX: ${round(cam.eyeX)}`, 0, 55); + * } + * + *
        + */ + /** + * The camera’s y-coordinate. + * + * By default, the camera’s y-coordinate is set to 0 in "world" space. + * + * @property {Number} eyeY + * @readonly + * + * @example + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube on a gray background. The text "eyeY: -400" is written in black beneath it.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the value of eyeY, rounded to the nearest integer. + * text(`eyeX: ${round(cam.eyeY)}`, 0, 55); + * } + * + *
        + * + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube on a gray background. The cube appears to move up and down as the camera moves. The text "eyeY: Y" is written in black beneath the cube. Y oscillates between -374 and -425.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Calculate the new y-coordinate. + * let y = 25 * sin(frameCount * 0.01) - 400; + * + * // Set the camera's position. + * cam.setPosition(0, y, 800); + * + * // Display the value of eyeY, rounded to the nearest integer. + * text(`eyeY: ${round(cam.eyeY)}`, 0, 55); + * } + * + *
        + */ + /** + * The camera’s z-coordinate. + * + * By default, the camera’s z-coordinate is set to 800 in "world" space. + * + * @property {Number} eyeZ + * @readonly + * + * @example + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube on a gray background. The text "eyeZ: 800" is written in black beneath it.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the value of eyeZ, rounded to the nearest integer. + * text(`eyeZ: ${round(cam.eyeZ)}`, 0, 55); + * } + * + *
        + * + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube on a gray background. The cube appears to move forward and back as the camera moves. The text "eyeZ: Z" is written in black beneath the cube. Z oscillates between 700 and 900.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Calculate the new z-coordinate. + * let z = 100 * sin(frameCount * 0.01) + 800; + * + * // Set the camera's position. + * cam.setPosition(0, -400, z); + * + * // Display the value of eyeZ, rounded to the nearest integer. + * text(`eyeZ: ${round(cam.eyeZ)}`, 0, 55); + * } + * + *
        + */ + /** + * The x-coordinate of the place where the camera looks. + * + * By default, the camera looks at the origin `(0, 0, 0)` in "world" space, so + * `myCamera.centerX` is 0. + * + * @property {Number} centerX + * @readonly + * + * @example + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at (10, 20, -30). + * cam.lookAt(10, 20, -30); + * + * describe( + * 'A white cube on a gray background. The text "centerX: 10" is written in black beneath it.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the value of centerX, rounded to the nearest integer. + * text(`centerX: ${round(cam.centerX)}`, 0, 55); + * } + * + *
        + * + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-right. + * cam.setPosition(100, -400, 800); + * + * // Point the camera at (10, 20, -30). + * cam.lookAt(10, 20, -30); + * + * describe( + * 'A white cube on a gray background. The cube appears to move left and right as the camera shifts its focus. The text "centerX: X" is written in black beneath the cube. X oscillates between -15 and 35.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Calculate the new x-coordinate. + * let x = 25 * sin(frameCount * 0.01) + 10; + * + * // Point the camera. + * cam.lookAt(x, 20, -30); + * + * // Display the value of centerX, rounded to the nearest integer. + * text(`centerX: ${round(cam.centerX)}`, 0, 55); + * } + * + *
        + */ + /** + * The y-coordinate of the place where the camera looks. + * + * By default, the camera looks at the origin `(0, 0, 0)` in "world" space, so + * `myCamera.centerY` is 0. + * + * @property {Number} centerY + * @readonly + * + * @example + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at (10, 20, -30). + * cam.lookAt(10, 20, -30); + * + * describe( + * 'A white cube on a gray background. The text "centerY: 20" is written in black beneath it.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the value of centerY, rounded to the nearest integer. + * text(`centerY: ${round(cam.centerY)}`, 0, 55); + * } + * + *
        + * + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-right. + * cam.setPosition(100, -400, 800); + * + * // Point the camera at (10, 20, -30). + * cam.lookAt(10, 20, -30); + * + * describe( + * 'A white cube on a gray background. The cube appears to move up and down as the camera shifts its focus. The text "centerY: Y" is written in black beneath the cube. Y oscillates between -5 and 45.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Calculate the new y-coordinate. + * let y = 25 * sin(frameCount * 0.01) + 20; + * + * // Point the camera. + * cam.lookAt(10, y, -30); + * + * // Display the value of centerY, rounded to the nearest integer. + * text(`centerY: ${round(cam.centerY)}`, 0, 55); + * } + * + *
        + */ + /** + * The y-coordinate of the place where the camera looks. + * + * By default, the camera looks at the origin `(0, 0, 0)` in "world" space, so + * `myCamera.centerZ` is 0. + * + * @property {Number} centerZ + * @readonly + * + * @example + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at (10, 20, -30). + * cam.lookAt(10, 20, -30); + * + * describe( + * 'A white cube on a gray background. The text "centerZ: -30" is written in black beneath it.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the value of centerZ, rounded to the nearest integer. + * text(`centerZ: ${round(cam.centerZ)}`, 0, 55); + * } + * + *
        + * + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-right. + * cam.setPosition(100, -400, 800); + * + * // Point the camera at (10, 20, -30). + * cam.lookAt(10, 20, -30); + * + * describe( + * 'A white cube on a gray background. The cube appears to move forward and back as the camera shifts its focus. The text "centerZ: Z" is written in black beneath the cube. Z oscillates between -55 and -25.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Calculate the new z-coordinate. + * let z = 25 * sin(frameCount * 0.01) - 30; + * + * // Point the camera. + * cam.lookAt(10, 20, z); + * + * // Display the value of centerZ, rounded to the nearest integer. + * text(`centerZ: ${round(cam.centerZ)}`, 0, 55); + * } + * + *
        + */ + /** + * The x-component of the camera's "up" vector. + * + * The camera's "up" vector orients its y-axis. By default, the "up" vector is + * `(0, 1, 0)`, so its x-component is 0 in "local" space. + * + * @property {Number} upX + * @readonly + * + * @example + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-right: (100, -400, 800) + * // Point it at the origin: (0, 0, 0) + * // Set its "up" vector: (0, 1, 0). + * cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); + * + * describe( + * 'A white cube on a gray background. The text "upX: 0" is written in black beneath it.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the value of upX, rounded to the nearest tenth. + * text(`upX: ${round(cam.upX, 1)}`, 0, 55); + * } + * + *
        + * + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-right: (100, -400, 800) + * // Point it at the origin: (0, 0, 0) + * // Set its "up" vector: (0, 1, 0). + * cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); + * + * describe( + * 'A white cube on a gray background. The cube appears to rock back and forth. The text "upX: X" is written in black beneath it. X oscillates between -1 and 1.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Calculate the x-component. + * let x = sin(frameCount * 0.01); + * + * // Update the camera's "up" vector. + * cam.camera(100, -400, 800, 0, 0, 0, x, 1, 0); + * + * // Display the value of upX, rounded to the nearest tenth. + * text(`upX: ${round(cam.upX, 1)}`, 0, 55); + * } + * + *
        + */ + /** + * The y-component of the camera's "up" vector. + * + * The camera's "up" vector orients its y-axis. By default, the "up" vector is + * `(0, 1, 0)`, so its y-component is 1 in "local" space. + * + * @property {Number} upY + * @readonly + * + * @example + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-right: (100, -400, 800) + * // Point it at the origin: (0, 0, 0) + * // Set its "up" vector: (0, 1, 0). + * cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); + * + * describe( + * 'A white cube on a gray background. The text "upY: 1" is written in black beneath it.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the value of upY, rounded to the nearest tenth. + * text(`upY: ${round(cam.upY, 1)}`, 0, 55); + * } + * + *
        + * + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-right: (100, -400, 800) + * // Point it at the origin: (0, 0, 0) + * // Set its "up" vector: (0, 1, 0). + * cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); + * + * describe( + * 'A white cube on a gray background. The cube flips upside-down periodically. The text "upY: Y" is written in black beneath it. Y oscillates between -1 and 1.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Calculate the y-component. + * let y = sin(frameCount * 0.01); + * + * // Update the camera's "up" vector. + * cam.camera(100, -400, 800, 0, 0, 0, 0, y, 0); + * + * // Display the value of upY, rounded to the nearest tenth. + * text(`upY: ${round(cam.upY, 1)}`, 0, 55); + * } + * + *
        + */ + /** + * The z-component of the camera's "up" vector. + * + * The camera's "up" vector orients its y-axis. By default, the "up" vector is + * `(0, 1, 0)`, so its z-component is 0 in "local" space. + * + * @property {Number} upZ + * @readonly + * + * @example + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-right: (100, -400, 800) + * // Point it at the origin: (0, 0, 0) + * // Set its "up" vector: (0, 1, 0). + * cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); + * + * describe( + * 'A white cube on a gray background. The text "upZ: 0" is written in black beneath it.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Display the value of upZ, rounded to the nearest tenth. + * text(`upZ: ${round(cam.upZ, 1)}`, 0, 55); + * } + * + *
        + * + *
        + * + * let cam; + * let font; + * + * // Load a font and create a p5.Font object. + * function preload() { + * font = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-right: (100, -400, 800) + * // Point it at the origin: (0, 0, 0) + * // Set its "up" vector: (0, 1, 0). + * cam.camera(100, -400, 800, 0, 0, 0, 0, 1, 0); + * + * describe( + * 'A white cube on a gray background. The cube appears to rock back and forth. The text "upZ: Z" is written in black beneath it. Z oscillates between -1 and 1.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Style the box. + * fill(255); + * + * // Draw the box. + * box(); + * + * // Style the text. + * textAlign(CENTER); + * textSize(16); + * textFont(font); + * fill(0); + * + * // Calculate the z-component. + * let z = sin(frameCount * 0.01); + * + * // Update the camera's "up" vector. + * cam.camera(100, -400, 800, 0, 0, 0, 0, 1, z); + * + * // Display the value of upZ, rounded to the nearest tenth. + * text(`upZ: ${round(cam.upZ, 1)}`, 0, 55); + * } + * + *
        + */ + //////////////////////////////////////////////////////////////////////////////// + // Camera Projection Methods + //////////////////////////////////////////////////////////////////////////////// + /** + * Sets a perspective projection for the camera. + * + * In a perspective projection, shapes that are further from the camera appear + * smaller than shapes that are near the camera. This technique, called + * foreshortening, creates realistic 3D scenes. It’s applied by default in new + * `p5.Camera` objects. + * + * `myCamera.perspective()` changes the camera’s perspective by changing its + * viewing frustum. The frustum is the volume of space that’s visible to the + * camera. The frustum’s shape is a pyramid with its top cut off. The camera + * is placed where the top of the pyramid should be and points towards the + * base of the pyramid. It views everything within the frustum. + * + * The first parameter, `fovy`, is the camera’s vertical field of view. It’s + * an angle that describes how tall or narrow a view the camera has. For + * example, calling `myCamera.perspective(0.5)` sets the camera’s vertical + * field of view to 0.5 radians. By default, `fovy` is calculated based on the + * sketch’s height and the camera’s default z-coordinate, which is 800. The + * formula for the default `fovy` is `2 * atan(height / 2 / 800)`. + * + * The second parameter, `aspect`, is the camera’s aspect ratio. It’s a number + * that describes the ratio of the top plane’s width to its height. For + * example, calling `myCamera.perspective(0.5, 1.5)` sets the camera’s field + * of view to 0.5 radians and aspect ratio to 1.5, which would make shapes + * appear thinner on a square canvas. By default, `aspect` is set to + * `width / height`. + * + * The third parameter, `near`, is the distance from the camera to the near + * plane. For example, calling `myCamera.perspective(0.5, 1.5, 100)` sets the + * camera’s field of view to 0.5 radians, its aspect ratio to 1.5, and places + * the near plane 100 pixels from the camera. Any shapes drawn less than 100 + * pixels from the camera won’t be visible. By default, `near` is set to + * `0.1 * 800`, which is 1/10th the default distance between the camera and + * the origin. + * + * The fourth parameter, `far`, is the distance from the camera to the far + * plane. For example, calling `myCamera.perspective(0.5, 1.5, 100, 10000)` + * sets the camera’s field of view to 0.5 radians, its aspect ratio to 1.5, + * places the near plane 100 pixels from the camera, and places the far plane + * 10,000 pixels from the camera. Any shapes drawn more than 10,000 pixels + * from the camera won’t be visible. By default, `far` is set to `10 * 800`, + * which is 10 times the default distance between the camera and the origin. + * + * @method perspective + * @for p5.Camera + * @param {Number} [fovy] camera frustum vertical field of view. Defaults to + * `2 * atan(height / 2 / 800)`. + * @param {Number} [aspect] camera frustum aspect ratio. Defaults to + * `width / height`. + * @param {Number} [near] distance from the camera to the near clipping plane. + * Defaults to `0.1 * 800`. + * @param {Number} [far] distance from the camera to the far clipping plane. + * Defaults to `10 * 800`. + * + * @example + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Place it at the top-right. + * cam2.camera(400, -400, 800); + * + * // Set its fovy to 0.2. + * // Set its aspect to 1.5. + * // Set its near to 600. + * // Set its far to 1200. + * cam2.perspective(0.2, 1.5, 600, 1200); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe('A white cube on a gray background. The camera toggles between a frontal view and a skewed aerial view when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Draw the box. + * box(); + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + * + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Place it at the top-right. + * cam2.camera(400, -400, 800); + * + * // Set its fovy to 0.2. + * // Set its aspect to 1.5. + * // Set its near to 600. + * // Set its far to 1200. + * cam2.perspective(0.2, 1.5, 600, 1200); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe('A white cube moves left and right on a gray background. The camera toggles between a frontal and a skewed aerial view when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin left and right. + * let x = 100 * sin(frameCount * 0.01); + * translate(x, 0, 0); + * + * // Draw the box. + * box(); + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + */ + + _createClass(Camera, [ + { + key: 'perspective', + value: function perspective(fovy, aspect, near, far) { + this.cameraType = arguments.length > 0 ? 'custom' : 'default'; + if (typeof fovy === 'undefined') { + fovy = this.defaultCameraFOV; + // this avoids issue where setting angleMode(DEGREES) before calling + // perspective leads to a smaller than expected FOV (because + // _computeCameraDefaultSettings computes in radians) + this.cameraFOV = fovy; + } else { + this.cameraFOV = this._renderer._pInst._toRadians(fovy); + } + if (typeof aspect === 'undefined') { + aspect = this.defaultAspectRatio; + } + if (typeof near === 'undefined') { + near = this.defaultCameraNear; + } + if (typeof far === 'undefined') { + far = this.defaultCameraFar; + } + if (near <= 0.0001) { + near = 0.01; + console.log('Avoid perspective near plane values close to or below 0. ' + 'Setting value to 0.01.'); + } + if (far < near) { + console.log('Perspective far plane value is less than near plane value. ' + 'Nothing will be shown.'); + } + this.aspectRatio = aspect; + this.cameraNear = near; + this.cameraFar = far; + this.projMatrix = _main.default.Matrix.identity(); + var f = 1 / Math.tan(this.cameraFOV / 2); + var nf = 1 / (this.cameraNear - this.cameraFar); + /* eslint-disable indent */ + this.projMatrix.set(f / aspect, 0, 0, 0, 0, - f * this.yScale, 0, 0, 0, 0, (far + near) * nf, - 1, 0, 0, 2 * far * near * nf, 0); + /* eslint-enable indent */ + if (this._isActive()) { + this._renderer.uPMatrix.set(this.projMatrix); + } + } /** + * Sets an orthographic projection for the camera. + * + * In an orthographic projection, shapes with the same size always appear the + * same size, regardless of whether they are near or far from the camera. + * + * `myCamera.ortho()` changes the camera’s perspective by changing its viewing + * frustum from a truncated pyramid to a rectangular prism. The frustum is the + * volume of space that’s visible to the camera. The camera is placed in front + * of the frustum and views everything within the frustum. `myCamera.ortho()` + * has six optional parameters to define the viewing frustum. + * + * The first four parameters, `left`, `right`, `bottom`, and `top`, set the + * coordinates of the frustum’s sides, bottom, and top. For example, calling + * `myCamera.ortho(-100, 100, 200, -200)` creates a frustum that’s 200 pixels + * wide and 400 pixels tall. By default, these dimensions are set based on + * the sketch’s width and height, as in + * `myCamera.ortho(-width / 2, width / 2, -height / 2, height / 2)`. + * + * The last two parameters, `near` and `far`, set the distance of the + * frustum’s near and far plane from the camera. For example, calling + * `myCamera.ortho(-100, 100, 200, -200, 50, 1000)` creates a frustum that’s + * 200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and + * ends 1,000 pixels from the camera. By default, `near` and `far` are set to + * 0 and `max(width, height) + 800`, respectively. + * + * @method ortho + * @for p5.Camera + * @param {Number} [left] x-coordinate of the frustum’s left plane. Defaults to `-width / 2`. + * @param {Number} [right] x-coordinate of the frustum’s right plane. Defaults to `width / 2`. + * @param {Number} [bottom] y-coordinate of the frustum’s bottom plane. Defaults to `height / 2`. + * @param {Number} [top] y-coordinate of the frustum’s top plane. Defaults to `-height / 2`. + * @param {Number} [near] z-coordinate of the frustum’s near plane. Defaults to 0. + * @param {Number} [far] z-coordinate of the frustum’s far plane. Defaults to `max(width, height) + 800`. + * + * @example + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Apply an orthographic projection. + * cam2.ortho(); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe('A row of white cubes against a gray background. The camera toggles between a perspective and an orthographic projection when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 500); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -40); + * box(10); + * } + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + * + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Apply an orthographic projection. + * cam2.ortho(); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe('A row of white cubes slither like a snake against a gray background. The camera toggles between a perspective and an orthographic projection when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 500); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * push(); + * // Calculate the box's coordinates. + * let x = 10 * sin(frameCount * 0.02 + i * 0.6); + * let z = -40 * i; + * // Translate the origin. + * translate(x, 0, z); + * // Draw the box. + * box(10); + * pop(); + * } + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + */ + + }, + { + key: 'ortho', + value: function ortho(left, right, bottom, top, near, far) { + if (left === undefined) left = - this._renderer.width / 2; + if (right === undefined) right = + this._renderer.width / 2; + if (bottom === undefined) bottom = - this._renderer.height / 2; + if (top === undefined) top = + this._renderer.height / 2; + if (near === undefined) near = 0; + if (far === undefined) far = Math.max(this._renderer.width, this._renderer.height) + 800; + this.cameraNear = near; + this.cameraFar = far; + var w = right - left; + var h = top - bottom; + var d = far - near; + var x = + 2 / w; + var y = + 2 / h * this.yScale; + var z = - 2 / d; + var tx = - (right + left) / w; + var ty = - (top + bottom) / h; + var tz = - (far + near) / d; + this.projMatrix = _main.default.Matrix.identity(); + /* eslint-disable indent */ + this.projMatrix.set(x, 0, 0, 0, 0, - y, 0, 0, 0, 0, z, 0, tx, ty, tz, 1); + /* eslint-enable indent */ + if (this._isActive()) { + this._renderer.uPMatrix.set(this.projMatrix); + } + this.cameraType = 'custom'; + } /** + * Sets the camera's frustum. + * + * In a frustum projection, shapes that are further from the camera appear + * smaller than shapes that are near the camera. This technique, called + * foreshortening, creates realistic 3D scenes. + * + * `myCamera.frustum()` changes the camera’s perspective by changing its + * viewing frustum. The frustum is the volume of space that’s visible to the + * camera. The frustum’s shape is a pyramid with its top cut off. The camera + * is placed where the top of the pyramid should be and points towards the + * base of the pyramid. It views everything within the frustum. + * + * The first four parameters, `left`, `right`, `bottom`, and `top`, set the + * coordinates of the frustum’s sides, bottom, and top. For example, calling + * `myCamera.frustum(-100, 100, 200, -200)` creates a frustum that’s 200 + * pixels wide and 400 pixels tall. By default, these coordinates are set + * based on the sketch’s width and height, as in + * `myCamera.frustum(-width / 20, width / 20, height / 20, -height / 20)`. + * + * The last two parameters, `near` and `far`, set the distance of the + * frustum’s near and far plane from the camera. For example, calling + * `myCamera.frustum(-100, 100, 200, -200, 50, 1000)` creates a frustum that’s + * 200 pixels wide, 400 pixels tall, starts 50 pixels from the camera, and ends + * 1,000 pixels from the camera. By default, near is set to `0.1 * 800`, which + * is 1/10th the default distance between the camera and the origin. `far` is + * set to `10 * 800`, which is 10 times the default distance between the + * camera and the origin. + * + * @method frustum + * @for p5.Camera + * @param {Number} [left] x-coordinate of the frustum’s left plane. Defaults to `-width / 20`. + * @param {Number} [right] x-coordinate of the frustum’s right plane. Defaults to `width / 20`. + * @param {Number} [bottom] y-coordinate of the frustum’s bottom plane. Defaults to `height / 20`. + * @param {Number} [top] y-coordinate of the frustum’s top plane. Defaults to `-height / 20`. + * @param {Number} [near] z-coordinate of the frustum’s near plane. Defaults to `0.1 * 800`. + * @param {Number} [far] z-coordinate of the frustum’s far plane. Defaults to `10 * 800`. + * + * @example + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Adjust the frustum. + * // Center it. + * // Set its width and height to 20 pixels. + * // Place its near plane 300 pixels from the camera. + * // Place its far plane 350 pixels from the camera. + * cam2.frustum(-10, 10, -10, 10, 300, 350); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe( + * 'A row of white cubes against a gray background. The camera zooms in on one cube when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 600); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -40); + * box(10); + * } + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + */ + + }, + { + key: 'frustum', + value: function frustum(left, right, bottom, top, near, far) { + if (left === undefined) left = - this._renderer.width * 0.05; + if (right === undefined) right = + this._renderer.width * 0.05; + if (bottom === undefined) bottom = + this._renderer.height * 0.05; + if (top === undefined) top = - this._renderer.height * 0.05; + if (near === undefined) near = this.defaultCameraNear; + if (far === undefined) far = this.defaultCameraFar; + this.cameraNear = near; + this.cameraFar = far; + var w = right - left; + var h = top - bottom; + var d = far - near; + var x = + (2 * near) / w; + var y = + (2 * near) / h * this.yScale; + var z = - (2 * far * near) / d; + var tx = (right + left) / w; + var ty = (top + bottom) / h; + var tz = - (far + near) / d; + this.projMatrix = _main.default.Matrix.identity(); + /* eslint-disable indent */ + this.projMatrix.set(x, 0, 0, 0, 0, - y, 0, 0, tx, ty, tz, - 1, 0, 0, z, 0); + /* eslint-enable indent */ + if (this._isActive()) { + this._renderer.uPMatrix.set(this.projMatrix); + } + this.cameraType = 'custom'; + } //////////////////////////////////////////////////////////////////////////////// + // Camera Orientation Methods + //////////////////////////////////////////////////////////////////////////////// + /** + * Rotate camera view about arbitrary axis defined by x,y,z + * based on http://learnwebgl.brown37.net/07_cameras/camera_rotating_motion.html + * @method _rotateView + * @private + */ + + }, + { + key: '_rotateView', + value: function _rotateView(a, x, y, z) { + var centerX = this.centerX; + var centerY = this.centerY; + var centerZ = this.centerZ; + // move center by eye position such that rotation happens around eye position + centerX -= this.eyeX; + centerY -= this.eyeY; + centerZ -= this.eyeZ; + var rotation = _main.default.Matrix.identity(this._renderer._pInst); + rotation.rotate(this._renderer._pInst._toRadians(a), x, y, z); + /* eslint-disable max-len */ + var rotatedCenter = [ + centerX * rotation.mat4[0] + centerY * rotation.mat4[4] + centerZ * rotation.mat4[8], + centerX * rotation.mat4[1] + centerY * rotation.mat4[5] + centerZ * rotation.mat4[9], + centerX * rotation.mat4[2] + centerY * rotation.mat4[6] + centerZ * rotation.mat4[10] + ]; + /* eslint-enable max-len */ + // add eye position back into center + rotatedCenter[0] += this.eyeX; + rotatedCenter[1] += this.eyeY; + rotatedCenter[2] += this.eyeZ; + this.camera(this.eyeX, this.eyeY, this.eyeZ, rotatedCenter[0], rotatedCenter[1], rotatedCenter[2], this.upX, this.upY, this.upZ); + } /** + * Rotates the camera left and right. + * + * Panning rotates the camera without changing its position. The rotation + * happens in the camera’s "local" space. + * + * The parameter, `angle`, is the angle the camera should rotate. Passing a + * positive angle, as in `myCamera.pan(0.001)`, rotates the camera to the + * right. Passing a negative angle, as in `myCamera.pan(-0.001)`, rotates the + * camera to the left. + * + * Note: Angles are interpreted based on the current + * angleMode(). + * + * @method pan + * @param {Number} angle amount to rotate in the current + * angleMode(). + * + * @example + *
        + * + * let cam; + * let delta = 0.001; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube on a gray background. The cube goes in and out of view as the camera pans left and right.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Pan with the camera. + * cam.pan(delta); + * + * // Switch directions every 120 frames. + * if (frameCount % 120 === 0) { + * delta *= -1; + * } + * + * // Draw the box. + * box(); + * } + * + *
        + */ + + }, + { + key: 'pan', + value: function pan(amount) { + var local = this._getLocalAxes(); + this._rotateView(amount, local.y[0], local.y[1], local.y[2]); + } /** + * Rotates the camera up and down. + * + * Tilting rotates the camera without changing its position. The rotation + * happens in the camera’s "local" space. + * + * The parameter, `angle`, is the angle the camera should rotate. Passing a + * positive angle, as in `myCamera.tilt(0.001)`, rotates the camera down. + * Passing a negative angle, as in `myCamera.tilt(-0.001)`, rotates the camera + * up. + * + * Note: Angles are interpreted based on the current + * angleMode(). + * + * @method tilt + * @param {Number} angle amount to rotate in the current + * angleMode(). + * + * @example + *
        + * + * let cam; + * let delta = 0.001; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube on a gray background. The cube goes in and out of view as the camera tilts up and down.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Pan with the camera. + * cam.tilt(delta); + * + * // Switch directions every 120 frames. + * if (frameCount % 120 === 0) { + * delta *= -1; + * } + * + * // Draw the box. + * box(); + * } + * + *
        + */ + + }, + { + key: 'tilt', + value: function tilt(amount) { + var local = this._getLocalAxes(); + this._rotateView(amount, local.x[0], local.x[1], local.x[2]); + } /** + * Points the camera at a location. + * + * `myCamera.lookAt()` changes the camera’s orientation without changing its + * position. + * + * The parameters, `x`, `y`, and `z`, are the coordinates in "world" space + * where the camera should point. For example, calling + * `myCamera.lookAt(10, 20, 30)` points the camera at the coordinates + * `(10, 20, 30)`. + * + * @method lookAt + * @for p5.Camera + * @param {Number} x x-coordinate of the position where the camera should look in "world" space. + * @param {Number} y y-coordinate of the position where the camera should look in "world" space. + * @param {Number} z z-coordinate of the position where the camera should look in "world" space. + * + * @example + *
        + * + * // Double-click to look at a different cube. + * + * let cam; + * let isLookingLeft = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Camera object. + * cam = createCamera(); + * + * // Place the camera at the top-center. + * cam.setPosition(0, -400, 800); + * + * // Point the camera at the origin. + * cam.lookAt(-30, 0, 0); + * + * describe( + * 'A red cube and a blue cube on a gray background. The camera switches focus between the cubes when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Draw the box on the left. + * push(); + * // Translate the origin to the left. + * translate(-30, 0, 0); + * // Style the box. + * fill(255, 0, 0); + * // Draw the box. + * box(20); + * pop(); + * + * // Draw the box on the right. + * push(); + * // Translate the origin to the right. + * translate(30, 0, 0); + * // Style the box. + * fill(0, 0, 255); + * // Draw the box. + * box(20); + * pop(); + * } + * + * // Change the camera's focus when the user double-clicks. + * function doubleClicked() { + * if (isLookingLeft === true) { + * cam.lookAt(30, 0, 0); + * isLookingLeft = false; + * } else { + * cam.lookAt(-30, 0, 0); + * isLookingLeft = true; + * } + * } + * + *
        + */ + + }, + { + key: 'lookAt', + value: function lookAt(x, y, z) { + this.camera(this.eyeX, this.eyeY, this.eyeZ, x, y, z, this.upX, this.upY, this.upZ); + } //////////////////////////////////////////////////////////////////////////////// + // Camera Position Methods + //////////////////////////////////////////////////////////////////////////////// + /** + * Sets the position and orientation of the camera. + * + * `myCamera.camera()` allows objects to be viewed from different angles. It + * has nine parameters that are all optional. + * + * The first three parameters, `x`, `y`, and `z`, are the coordinates of the + * camera’s position in "world" space. For example, calling + * `myCamera.camera(0, 0, 0)` places the camera at the origin `(0, 0, 0)`. By + * default, the camera is placed at `(0, 0, 800)`. + * + * The next three parameters, `centerX`, `centerY`, and `centerZ` are the + * coordinates of the point where the camera faces in "world" space. For + * example, calling `myCamera.camera(0, 0, 0, 10, 20, 30)` places the camera + * at the origin `(0, 0, 0)` and points it at `(10, 20, 30)`. By default, the + * camera points at the origin `(0, 0, 0)`. + * + * The last three parameters, `upX`, `upY`, and `upZ` are the components of + * the "up" vector in "local" space. The "up" vector orients the camera’s + * y-axis. For example, calling + * `myCamera.camera(0, 0, 0, 10, 20, 30, 0, -1, 0)` places the camera at the + * origin `(0, 0, 0)`, points it at `(10, 20, 30)`, and sets the "up" vector + * to `(0, -1, 0)` which is like holding it upside-down. By default, the "up" + * vector is `(0, 1, 0)`. + * + * @method camera + * @for p5.Camera + * @param {Number} [x] x-coordinate of the camera. Defaults to 0. + * @param {Number} [y] y-coordinate of the camera. Defaults to 0. + * @param {Number} [z] z-coordinate of the camera. Defaults to 800. + * @param {Number} [centerX] x-coordinate of the point the camera faces. Defaults to 0. + * @param {Number} [centerY] y-coordinate of the point the camera faces. Defaults to 0. + * @param {Number} [centerZ] z-coordinate of the point the camera faces. Defaults to 0. + * @param {Number} [upX] x-component of the camera’s "up" vector. Defaults to 0. + * @param {Number} [upY] x-component of the camera’s "up" vector. Defaults to 1. + * @param {Number} [upZ] z-component of the camera’s "up" vector. Defaults to 0. + * + * @example + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Place it at the top-right: (1200, -600, 100) + * // Point it at the row of boxes: (-10, -10, 400) + * // Set its "up" vector to the default: (0, 1, 0) + * cam2.camera(1200, -600, 100, -10, -10, 400, 0, 1, 0); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe( + * 'A row of white cubes against a gray background. The camera toggles between a frontal and an aerial view when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 500); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -30); + * box(10); + * } + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + * + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Place it at the right: (1200, 0, 100) + * // Point it at the row of boxes: (-10, -10, 400) + * // Set its "up" vector to the default: (0, 1, 0) + * cam2.camera(1200, 0, 100, -10, -10, 400, 0, 1, 0); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe( + * 'A row of white cubes against a gray background. The camera toggles between a static frontal view and an orbiting view when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Update cam2's position. + * let x = 1200 * cos(frameCount * 0.01); + * let y = -600 * sin(frameCount * 0.01); + * cam2.camera(x, y, 100, -10, -10, 400, 0, 1, 0); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 500); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -30); + * box(10); + * } + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + */ + + }, + { + key: 'camera', + value: function camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) { + if (typeof eyeX === 'undefined') { + eyeX = this.defaultEyeX; + eyeY = this.defaultEyeY; + eyeZ = this.defaultEyeZ; + centerX = eyeX; + centerY = eyeY; + centerZ = 0; + upX = 0; + upY = 1; + upZ = 0; + } + this.eyeX = eyeX; + this.eyeY = eyeY; + this.eyeZ = eyeZ; + if (typeof centerX !== 'undefined') { + this.centerX = centerX; + this.centerY = centerY; + this.centerZ = centerZ; + } + if (typeof upX !== 'undefined') { + this.upX = upX; + this.upY = upY; + this.upZ = upZ; + } + var local = this._getLocalAxes(); + // the camera affects the model view matrix, insofar as it + // inverse translates the world to the eye position of the camera + // and rotates it. + /* eslint-disable indent */ + this.cameraMatrix.set(local.x[0], local.y[0], local.z[0], 0, local.x[1], local.y[1], local.z[1], 0, local.x[2], local.y[2], local.z[2], 0, 0, 0, 0, 1); + /* eslint-enable indent */ + var tx = - eyeX; + var ty = - eyeY; + var tz = - eyeZ; + this.cameraMatrix.translate([tx, + ty, + tz]); + if (this._isActive()) { + this._renderer.uMVMatrix.set(this.cameraMatrix); + } + return this; + } /** + * Moves the camera along its "local" axes without changing its orientation. + * + * The parameters, `x`, `y`, and `z`, are the distances the camera should + * move. For example, calling `myCamera.move(10, 20, 30)` moves the camera 10 + * pixels to the right, 20 pixels down, and 30 pixels backward in its "local" + * space. + * + * @method move + * @param {Number} x distance to move along the camera’s "local" x-axis. + * @param {Number} y distance to move along the camera’s "local" y-axis. + * @param {Number} z distance to move along the camera’s "local" z-axis. + * @example + *
        + * + * // Click the canvas to begin detecting key presses. + * + * let cam; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam = createCamera(); + * + * // Place the camera at the top-right. + * cam.setPosition(400, -400, 800); + * + * // Point it at the origin. + * cam.lookAt(0, 0, 0); + * + * describe( + * 'A white cube drawn against a gray background. The cube appears to move when the user presses certain keys.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Move the camera along its "local" axes + * // when the user presses certain keys. + * if (keyIsPressed === true) { + * + * // Move horizontally. + * if (keyCode === LEFT_ARROW) { + * cam.move(-1, 0, 0); + * } + * if (keyCode === RIGHT_ARROW) { + * cam.move(1, 0, 0); + * } + * + * // Move vertically. + * if (keyCode === UP_ARROW) { + * cam.move(0, -1, 0); + * } + * if (keyCode === DOWN_ARROW) { + * cam.move(0, 1, 0); + * } + * + * // Move in/out of the screen. + * if (key === 'i') { + * cam.move(0, 0, -1); + * } + * if (key === 'o') { + * cam.move(0, 0, 1); + * } + * } + * + * // Draw the box. + * box(); + * } + * + *
        + */ + + }, + { + key: 'move', + value: function move(x, y, z) { + var local = this._getLocalAxes(); + // scale local axes by movement amounts + // based on http://learnwebgl.brown37.net/07_cameras/camera_linear_motion.html + var dx = [ + local.x[0] * x, + local.x[1] * x, + local.x[2] * x + ]; + var dy = [ + local.y[0] * y, + local.y[1] * y, + local.y[2] * y + ]; + var dz = [ + local.z[0] * z, + local.z[1] * z, + local.z[2] * z + ]; + this.camera(this.eyeX + dx[0] + dy[0] + dz[0], this.eyeY + dx[1] + dy[1] + dz[1], this.eyeZ + dx[2] + dy[2] + dz[2], this.centerX + dx[0] + dy[0] + dz[0], this.centerY + dx[1] + dy[1] + dz[1], this.centerZ + dx[2] + dy[2] + dz[2], this.upX, this.upY, this.upZ); + } /** + * Sets the camera’s position in "world" space without changing its + * orientation. + * + * The parameters, `x`, `y`, and `z`, are the coordinates where the camera + * should be placed. For example, calling `myCamera.setPosition(10, 20, 30)` + * places the camera at coordinates `(10, 20, 30)` in "world" space. + * + * @method setPosition + * @param {Number} x x-coordinate in "world" space. + * @param {Number} y y-coordinate in "world" space. + * @param {Number} z z-coordinate in "world" space. + * + * @example + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Place it closer to the origin. + * cam2.setPosition(0, 0, 600); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe( + * 'A row of white cubes against a gray background. The camera toggles the amount of zoom when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 500); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -30); + * box(10); + * } + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + * + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let isDefaultCamera = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Place it closer to the origin. + * cam2.setPosition(0, 0, 600); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe( + * 'A row of white cubes against a gray background. The camera toggles between a static view and a view that zooms in and out when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Update cam2's z-coordinate. + * let z = 100 * sin(frameCount * 0.01) + 700; + * cam2.setPosition(0, 0, z); + * + * // Translate the origin toward the camera. + * translate(-10, 10, 500); + * + * // Rotate the coordinate system. + * rotateY(-0.1); + * rotateX(-0.1); + * + * // Draw the row of boxes. + * for (let i = 0; i < 6; i += 1) { + * translate(0, 0, -30); + * box(10); + * } + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (isDefaultCamera === true) { + * setCamera(cam2); + * isDefaultCamera = false; + * } else { + * setCamera(cam1); + * isDefaultCamera = true; + * } + * } + * + *
        + */ + + }, + { + key: 'setPosition', + value: function setPosition(x, y, z) { + var diffX = x - this.eyeX; + var diffY = y - this.eyeY; + var diffZ = z - this.eyeZ; + this.camera(x, y, z, this.centerX + diffX, this.centerY + diffY, this.centerZ + diffZ, this.upX, this.upY, this.upZ); + } /** + * Sets the camera’s position, orientation, and projection by copying another + * camera. + * + * The parameter, `cam`, is the `p5.Camera` object to copy. For example, calling + * `cam2.set(cam1)` will set `cam2` using `cam1`’s configuration. + * + * @method set + * @param {p5.Camera} cam camera to copy. + * + * @example + *
        + * + * // Double-click to "reset" the camera zoom. + * + * let cam1; + * let cam2; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * cam1 = createCamera(); + * + * // Place the camera at the top-right. + * cam1.setPosition(400, -400, 800); + * + * // Point it at the origin. + * cam1.lookAt(0, 0, 0); + * + * // Create the second camera. + * cam2 = createCamera(); + * + * // Copy cam1's configuration. + * cam2.set(cam1); + * + * describe( + * 'A white cube drawn against a gray background. The camera slowly moves forward. The camera resets when the user double-clicks.' + * ); + * } + * + * function draw() { + * background(200); + * + * // Update cam2's position. + * cam2.move(0, 0, -1); + * + * // Draw the box. + * box(); + * } + * + * // "Reset" the camera when the user double-clicks. + * function doubleClicked() { + * cam2.set(cam1); + * } + */ + + }, + { + key: 'set', + value: function set(cam) { + var keyNamesOfThePropToCopy = [ + 'eyeX', + 'eyeY', + 'eyeZ', + 'centerX', + 'centerY', + 'centerZ', + 'upX', + 'upY', + 'upZ', + 'cameraFOV', + 'aspectRatio', + 'cameraNear', + 'cameraFar', + 'cameraType', + 'yScale' + ]; + for (var _i = 0, _keyNamesOfThePropToC = keyNamesOfThePropToCopy; _i < _keyNamesOfThePropToC.length; _i++) { + var keyName = _keyNamesOfThePropToC[_i]; + this[keyName] = cam[keyName]; + } + this.cameraMatrix = cam.cameraMatrix.copy(); + this.projMatrix = cam.projMatrix.copy(); + // If the target camera is active, update uMVMatrix and uPMatrix. + if (this._isActive()) { + this._renderer.uMVMatrix.mat4 = this.cameraMatrix.mat4.slice(); + this._renderer.uPMatrix.mat4 = this.projMatrix.mat4.slice(); + } + } /** + * Sets the camera’s position and orientation to values that are in-between + * those of two other cameras. + * + * `myCamera.slerp()` uses spherical linear interpolation to calculate a + * position and orientation that’s in-between two other cameras. Doing so is + * helpful for transitioning smoothly between two perspectives. + * + * The first two parameters, `cam0` and `cam1`, are the `p5.Camera` objects + * that should be used to set the current camera. + * + * The third parameter, `amt`, is the amount to interpolate between `cam0` and + * `cam1`. 0.0 keeps the camera’s position and orientation equal to `cam0`’s, + * 0.5 sets them halfway between `cam0`’s and `cam1`’s , and 1.0 sets the + * position and orientation equal to `cam1`’s. + * + * For example, calling `myCamera.slerp(cam0, cam1, 0.1)` sets cam’s position + * and orientation very close to `cam0`’s. Calling + * `myCamera.slerp(cam0, cam1, 0.9)` sets cam’s position and orientation very + * close to `cam1`’s. + * + * Note: All of the cameras must use the same projection. + * + * @method slerp + * @param {p5.Camera} cam0 first camera. + * @param {p5.Camera} cam1 second camera. + * @param {Number} amt amount of interpolation between 0.0 (`cam0`) and 1.0 (`cam1`). + * + * @example + *
        + * + * let cam; + * let cam0; + * let cam1; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the main camera. + * // Keep its default settings. + * cam = createCamera(); + * + * // Create the first camera. + * // Keep its default settings. + * cam0 = createCamera(); + * + * // Create the second camera. + * cam1 = createCamera(); + * + * // Place it at the top-right. + * cam1.setPosition(400, -400, 800); + * + * // Point it at the origin. + * cam1.lookAt(0, 0, 0); + * + * // Set the current camera to cam. + * setCamera(cam); + * + * describe('A white cube drawn against a gray background. The camera slowly oscillates between a frontal view and an aerial view.'); + * } + * + * function draw() { + * background(200); + * + * // Calculate the amount to interpolate between cam0 and cam1. + * let amt = 0.5 * sin(frameCount * 0.01) + 0.5; + * + * // Update the main camera's position and orientation. + * cam.slerp(cam0, cam1, amt); + * + * box(); + * } + * + *
        + */ + + }, + { + key: 'slerp', + value: function slerp(cam0, cam1, amt) { + // If t is 0 or 1, do not interpolate and set the argument camera. + if (amt === 0) { + this.set(cam0); + return; + } else if (amt === 1) { + this.set(cam1); + return; + } // For this cameras is ortho, assume that cam0 and cam1 are also ortho + // and interpolate the elements of the projection matrix. + // Use logarithmic interpolation for interpolation. + + if (this.projMatrix.mat4[15] !== 0) { + this.projMatrix.mat4[0] = cam0.projMatrix.mat4[0] * Math.pow(cam1.projMatrix.mat4[0] / cam0.projMatrix.mat4[0], amt); + this.projMatrix.mat4[5] = cam0.projMatrix.mat4[5] * Math.pow(cam1.projMatrix.mat4[5] / cam0.projMatrix.mat4[5], amt); + // If the camera is active, make uPMatrix reflect changes in projMatrix. + if (this._isActive()) { + this._renderer.uPMatrix.mat4 = this.projMatrix.mat4.slice(); + } + } // prepare eye vector and center vector of argument cameras. + + var eye0 = new _main.default.Vector(cam0.eyeX, cam0.eyeY, cam0.eyeZ); + var eye1 = new _main.default.Vector(cam1.eyeX, cam1.eyeY, cam1.eyeZ); + var center0 = new _main.default.Vector(cam0.centerX, cam0.centerY, cam0.centerZ); + var center1 = new _main.default.Vector(cam1.centerX, cam1.centerY, cam1.centerZ); + // Calculate the distance between eye and center for each camera. + // Logarithmically interpolate these with amt. + var dist0 = _main.default.Vector.dist(eye0, center0); + var dist1 = _main.default.Vector.dist(eye1, center1); + var lerpedDist = dist0 * Math.pow(dist1 / dist0, amt); + // Next, calculate the ratio to interpolate the eye and center by a constant + // ratio for each camera. This ratio is the same for both. Also, with this ratio + // of points, the distance is the minimum distance of the two points of + // the same ratio. + // With this method, if the viewpoint is fixed, linear interpolation is performed + // at the viewpoint, and if the center is fixed, linear interpolation is performed + // at the center, resulting in reasonable interpolation. If both move, the point + // halfway between them is taken. + var eyeDiff = _main.default.Vector.sub(eye0, eye1); + var diffDiff = eye0.copy().sub(eye1).sub(center0).add(center1); + // Suppose there are two line segments. Consider the distance between the points + // above them as if they were taken in the same ratio. This calculation figures out + // a ratio that minimizes this. + // Each line segment is, a line segment connecting the viewpoint and the center + // for each camera. + var divider = diffDiff.magSq(); + var ratio = 1; // default. + if (divider > 0.000001) { + ratio = _main.default.Vector.dot(eyeDiff, diffDiff) / divider; + ratio = Math.max(0, Math.min(ratio, 1)); + } // Take the appropriate proportions and work out the points + // that are between the new viewpoint and the new center position. + + var lerpedMedium = _main.default.Vector.lerp(_main.default.Vector.lerp(eye0, center0, ratio), _main.default.Vector.lerp(eye1, center1, ratio), amt); + // Prepare each of rotation matrix from their camera matrix + var rotMat0 = cam0.cameraMatrix.createSubMatrix3x3(); + var rotMat1 = cam1.cameraMatrix.createSubMatrix3x3(); + // get front and up vector from local-coordinate-system. + var front0 = rotMat0.row(2); + var front1 = rotMat1.row(2); + var up0 = rotMat0.row(1); + var up1 = rotMat1.row(1); + // prepare new vectors. + var newFront = new _main.default.Vector(); + var newUp = new _main.default.Vector(); + var newEye = new _main.default.Vector(); + var newCenter = new _main.default.Vector(); + // Create the inverse matrix of mat0 by transposing mat0, + // and multiply it to mat1 from the right. + // This matrix represents the difference between the two. + // 'deltaRot' means 'difference of rotation matrices'. + var deltaRot = rotMat1.mult3x3(rotMat0.copy().transpose3x3()); + // Calculate the trace and from it the cos value of the angle. + // An orthogonal matrix is just an orthonormal basis. If this is not the identity + // matrix, it is a centered orthonormal basis plus some angle of rotation about + // some axis. That's the angle. Letting this be theta, trace becomes 1+2cos(theta). + // reference: https://en.wikipedia.org/wiki/Rotation_matrix#Determining_the_angle + var diag = deltaRot.diagonal(); + var cosTheta = 0.5 * (diag[0] + diag[1] + diag[2] - 1); + // If the angle is close to 0, the two matrices are very close, + // so in that case we execute linearly interpolate. + if (1 - cosTheta < 1e-7) { + // Obtain the front vector and up vector by linear interpolation + // and normalize them. + // calculate newEye, newCenter with newFront vector. + newFront.set(_main.default.Vector.lerp(front0, front1, amt)).normalize(); + newEye.set(newFront).mult(ratio * lerpedDist).add(lerpedMedium); + newCenter.set(newFront).mult((ratio - 1) * lerpedDist).add(lerpedMedium); + newUp.set(_main.default.Vector.lerp(up0, up1, amt)).normalize(); + // set the camera + this.camera(newEye.x, newEye.y, newEye.z, newCenter.x, newCenter.y, newCenter.z, newUp.x, newUp.y, newUp.z); + return; + } // Calculates the axis vector and the angle of the difference orthogonal matrix. + // The axis vector is what I explained earlier in the comments. + // similar calculation is here: + // https://github.com/mrdoob/three.js/blob/883249620049d1632e8791732808fefd1a98c871/src/math/Quaternion.js#L294 + + var a, + b, + c, + sinTheta; + var invOneMinusCosTheta = 1 / (1 - cosTheta); + var maxDiag = Math.max(diag[0], diag[1], diag[2]); + var offDiagSum13 = deltaRot.mat3[1] + deltaRot.mat3[3]; + var offDiagSum26 = deltaRot.mat3[2] + deltaRot.mat3[6]; + var offDiagSum57 = deltaRot.mat3[5] + deltaRot.mat3[7]; + if (maxDiag === diag[0]) { + a = Math.sqrt((diag[0] - cosTheta) * invOneMinusCosTheta); // not zero. + invOneMinusCosTheta /= a; + b = 0.5 * offDiagSum13 * invOneMinusCosTheta; + c = 0.5 * offDiagSum26 * invOneMinusCosTheta; + sinTheta = 0.5 * (deltaRot.mat3[7] - deltaRot.mat3[5]) / a; + } else if (maxDiag === diag[1]) { + b = Math.sqrt((diag[1] - cosTheta) * invOneMinusCosTheta); // not zero. + invOneMinusCosTheta /= b; + c = 0.5 * offDiagSum57 * invOneMinusCosTheta; + a = 0.5 * offDiagSum13 * invOneMinusCosTheta; + sinTheta = 0.5 * (deltaRot.mat3[2] - deltaRot.mat3[6]) / b; + } else { + c = Math.sqrt((diag[2] - cosTheta) * invOneMinusCosTheta); // not zero. + invOneMinusCosTheta /= c; + a = 0.5 * offDiagSum26 * invOneMinusCosTheta; + b = 0.5 * offDiagSum57 * invOneMinusCosTheta; + sinTheta = 0.5 * (deltaRot.mat3[3] - deltaRot.mat3[1]) / c; + } // Constructs a new matrix after interpolating the angles. + // Multiplying mat0 by the first matrix yields mat1, but by creating a state + // in the middle of that matrix, you can obtain a matrix that is + // an intermediate state between mat0 and mat1. + + var angle = amt * Math.atan2(sinTheta, cosTheta); + var cosAngle = Math.cos(angle); + var sinAngle = Math.sin(angle); + var oneMinusCosAngle = 1 - cosAngle; + var ab = a * b; + var bc = b * c; + var ca = c * a; + var lerpedRotMat = new _main.default.Matrix('mat3', [ + cosAngle + oneMinusCosAngle * a * a, + oneMinusCosAngle * ab + sinAngle * c, + oneMinusCosAngle * ca - sinAngle * b, + oneMinusCosAngle * ab - sinAngle * c, + cosAngle + oneMinusCosAngle * b * b, + oneMinusCosAngle * bc + sinAngle * a, + oneMinusCosAngle * ca + sinAngle * b, + oneMinusCosAngle * bc - sinAngle * a, + cosAngle + oneMinusCosAngle * c * c + ]); + // Multiply this to mat0 from left to get the interpolated front vector. + // calculate newEye, newCenter with newFront vector. + lerpedRotMat.multiplyVec3(front0, newFront); + newEye.set(newFront).mult(ratio * lerpedDist).add(lerpedMedium); + newCenter.set(newFront).mult((ratio - 1) * lerpedDist).add(lerpedMedium); + lerpedRotMat.multiplyVec3(up0, newUp); + // We also get the up vector in the same way and set the camera. + // The eye position and center position are calculated based on the front vector. + this.camera(newEye.x, newEye.y, newEye.z, newCenter.x, newCenter.y, newCenter.z, newUp.x, newUp.y, newUp.z); + } //////////////////////////////////////////////////////////////////////////////// + // Camera Helper Methods + //////////////////////////////////////////////////////////////////////////////// + // @TODO: combine this function with _setDefaultCamera to compute these values + // as-needed + + }, + { + key: '_computeCameraDefaultSettings', + value: function _computeCameraDefaultSettings() { + this.defaultAspectRatio = this._renderer.width / this._renderer.height; + this.defaultEyeX = 0; + this.defaultEyeY = 0; + this.defaultEyeZ = 800; + this.defaultCameraFOV = 2 * Math.atan(this._renderer.height / 2 / this.defaultEyeZ); + this.defaultCenterX = 0; + this.defaultCenterY = 0; + this.defaultCenterZ = 0; + this.defaultCameraNear = this.defaultEyeZ * 0.1; + this.defaultCameraFar = this.defaultEyeZ * 10; + } //detect if user didn't set the camera + //then call this function below + + }, + { + key: '_setDefaultCamera', + value: function _setDefaultCamera() { + this.cameraFOV = this.defaultCameraFOV; + this.aspectRatio = this.defaultAspectRatio; + this.eyeX = this.defaultEyeX; + this.eyeY = this.defaultEyeY; + this.eyeZ = this.defaultEyeZ; + this.centerX = this.defaultCenterX; + this.centerY = this.defaultCenterY; + this.centerZ = this.defaultCenterZ; + this.upX = 0; + this.upY = 1; + this.upZ = 0; + this.cameraNear = this.defaultCameraNear; + this.cameraFar = this.defaultCameraFar; + this.perspective(); + this.camera(); + this.cameraType = 'default'; + } + }, + { + key: '_resize', + value: function _resize() { + // If we're using the default camera, update the aspect ratio + if (this.cameraType === 'default') { + this._computeCameraDefaultSettings(); + this.cameraFOV = this.defaultCameraFOV; + this.aspectRatio = this.defaultAspectRatio; + this.perspective(); + } + } /** + * Returns a copy of a camera. + * @method copy + * @private + */ + + }, + { + key: 'copy', + value: function copy() { + var _cam = new _main.default.Camera(this._renderer); + _cam.cameraFOV = this.cameraFOV; + _cam.aspectRatio = this.aspectRatio; + _cam.eyeX = this.eyeX; + _cam.eyeY = this.eyeY; + _cam.eyeZ = this.eyeZ; + _cam.centerX = this.centerX; + _cam.centerY = this.centerY; + _cam.centerZ = this.centerZ; + _cam.upX = this.upX; + _cam.upY = this.upY; + _cam.upZ = this.upZ; + _cam.cameraNear = this.cameraNear; + _cam.cameraFar = this.cameraFar; + _cam.cameraType = this.cameraType; + _cam.cameraMatrix = this.cameraMatrix.copy(); + _cam.projMatrix = this.projMatrix.copy(); + _cam.yScale = this.yScale; + return _cam; + } /** + * Returns a camera's local axes: left-right, up-down, and forward-backward, + * as defined by vectors in world-space. + * @method _getLocalAxes + * @private + */ + + }, + { + key: '_getLocalAxes', + value: function _getLocalAxes() { + // calculate camera local Z vector + var z0 = this.eyeX - this.centerX; + var z1 = this.eyeY - this.centerY; + var z2 = this.eyeZ - this.centerZ; + // normalize camera local Z vector + var eyeDist = Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + if (eyeDist !== 0) { + z0 /= eyeDist; + z1 /= eyeDist; + z2 /= eyeDist; + } // calculate camera Y vector + + var y0 = this.upX; + var y1 = this.upY; + var y2 = this.upZ; + // compute camera local X vector as up vector (local Y) cross local Z + var x0 = y1 * z2 - y2 * z1; + var x1 = - y0 * z2 + y2 * z0; + var x2 = y0 * z1 - y1 * z0; + // recompute y = z cross x + y0 = z1 * x2 - z2 * x1; + y1 = - z0 * x2 + z2 * x0; + y2 = z0 * x1 - z1 * x0; + // cross product gives area of parallelogram, which is < 1.0 for + // non-perpendicular unit-length vectors; so normalize x, y here: + var xmag = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + if (xmag !== 0) { + x0 /= xmag; + x1 /= xmag; + x2 /= xmag; + } + var ymag = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + if (ymag !== 0) { + y0 /= ymag; + y1 /= ymag; + y2 /= ymag; + } + return { + x: [ + x0, + x1, + x2 + ], + y: [ + y0, + y1, + y2 + ], + z: [ + z0, + z1, + z2 + ] + }; + } /** + * Orbits the camera about center point. For use with orbitControl(). + * @method _orbit + * @private + * @param {Number} dTheta change in spherical coordinate theta + * @param {Number} dPhi change in spherical coordinate phi + * @param {Number} dRadius change in radius + */ + + }, + { + key: '_orbit', + value: function _orbit(dTheta, dPhi, dRadius) { + // Calculate the vector and its magnitude from the center to the viewpoint + var diffX = this.eyeX - this.centerX; + var diffY = this.eyeY - this.centerY; + var diffZ = this.eyeZ - this.centerZ; + var camRadius = Math.hypot(diffX, diffY, diffZ); + // front vector. unit vector from center to eye. + var front = new _main.default.Vector(diffX, diffY, diffZ).normalize(); + // up vector. normalized camera's up vector. + var up = new _main.default.Vector(this.upX, this.upY, this.upZ).normalize(); // y-axis + // side vector. Right when viewed from the front + var side = _main.default.Vector.cross(up, front).normalize(); // x-axis + // vertical vector. normalized vector of projection of front vector. + var vertical = _main.default.Vector.cross(side, up); // z-axis + // update camRadius + camRadius *= Math.pow(10, dRadius); + // prevent zooming through the center: + if (camRadius < this.cameraNear) { + camRadius = this.cameraNear; + } + if (camRadius > this.cameraFar) { + camRadius = this.cameraFar; + } // calculate updated camera angle + // Find the angle between the "up" and the "front", add dPhi to that. + // angleBetween() may return negative value. Since this specification is subject to change + // due to version updates, it cannot be adopted, so here we calculate using a method + // that directly obtains the absolute value. + + var camPhi = Math.acos(Math.max( - 1, Math.min(1, _main.default.Vector.dot(front, up)))) + dPhi; + // Rotate by dTheta in the shortest direction from "vertical" to "side" + var camTheta = dTheta; + // Invert camera's upX, upY, upZ if dPhi is below 0 or above PI + if (camPhi <= 0 || camPhi >= Math.PI) { + this.upX *= - 1; + this.upY *= - 1; + this.upZ *= - 1; + } // update eye vector by calculate new front vector + + up.mult(Math.cos(camPhi)); + vertical.mult(Math.cos(camTheta) * Math.sin(camPhi)); + side.mult(Math.sin(camTheta) * Math.sin(camPhi)); + front.set(up).add(vertical).add(side); + this.eyeX = camRadius * front.x + this.centerX; + this.eyeY = camRadius * front.y + this.centerY; + this.eyeZ = camRadius * front.z + this.centerZ; + // update camera + this.camera(this.eyeX, this.eyeY, this.eyeZ, this.centerX, this.centerY, this.centerZ, this.upX, this.upY, this.upZ); + } /** + * Orbits the camera about center point. For use with orbitControl(). + * Unlike _orbit(), the direction of rotation always matches the direction of pointer movement. + * @method _orbitFree + * @private + * @param {Number} dx the x component of the rotation vector. + * @param {Number} dy the y component of the rotation vector. + * @param {Number} dRadius change in radius + */ + + }, + { + key: '_orbitFree', + value: function _orbitFree(dx, dy, dRadius) { + // Calculate the vector and its magnitude from the center to the viewpoint + var diffX = this.eyeX - this.centerX; + var diffY = this.eyeY - this.centerY; + var diffZ = this.eyeZ - this.centerZ; + var camRadius = Math.hypot(diffX, diffY, diffZ); + // front vector. unit vector from center to eye. + var front = new _main.default.Vector(diffX, diffY, diffZ).normalize(); + // up vector. camera's up vector. + var up = new _main.default.Vector(this.upX, this.upY, this.upZ); + // side vector. Right when viewed from the front. (like x-axis) + var side = _main.default.Vector.cross(up, front).normalize(); + // down vector. Bottom when viewed from the front. (like y-axis) + var down = _main.default.Vector.cross(front, side); + // side vector and down vector are no longer used as-is. + // Create a vector representing the direction of rotation + // in the form cos(direction)*side + sin(direction)*down. + // Make the current side vector into this. + var directionAngle = Math.atan2(dy, dx); + down.mult(Math.sin(directionAngle)); + side.mult(Math.cos(directionAngle)).add(down); + // The amount of rotation is the size of the vector (dx, dy). + var rotAngle = Math.sqrt(dx * dx + dy * dy); + // The vector that is orthogonal to both the front vector and + // the rotation direction vector is the rotation axis vector. + var axis = _main.default.Vector.cross(front, side); + // update camRadius + camRadius *= Math.pow(10, dRadius); + // prevent zooming through the center: + if (camRadius < this.cameraNear) { + camRadius = this.cameraNear; + } + if (camRadius > this.cameraFar) { + camRadius = this.cameraFar; + } // If the axis vector is likened to the z-axis, the front vector is + // the x-axis and the side vector is the y-axis. Rotate the up and front + // vectors respectively by thinking of them as rotations around the z-axis. + // Calculate the components by taking the dot product and + // calculate a rotation based on that. + + var c = Math.cos(rotAngle); + var s = Math.sin(rotAngle); + var dotFront = up.dot(front); + var dotSide = up.dot(side); + var ux = dotFront * c + dotSide * s; + var uy = - dotFront * s + dotSide * c; + var uz = up.dot(axis); + up.x = ux * front.x + uy * side.x + uz * axis.x; + up.y = ux * front.y + uy * side.y + uz * axis.y; + up.z = ux * front.z + uy * side.z + uz * axis.z; + // We won't be using the side vector and the front vector anymore, + // so let's make the front vector into the vector from the center to the new eye. + side.mult( - s); + front.mult(c).add(side).mult(camRadius); + // it's complete. let's update camera. + this.camera(front.x + this.centerX, front.y + this.centerY, front.z + this.centerZ, this.centerX, this.centerY, this.centerZ, up.x, up.y, up.z); + } /** + * Returns true if camera is currently attached to renderer. + * @method _isActive + * @private + */ + + }, + { + key: '_isActive', + value: function _isActive() { + return this === this._renderer._curCamera; + } + } + ]); + return Camera; + }(); + /** + * Sets the current (active) camera of a 3D sketch. + * + * `setCamera()` allows for switching between multiple cameras created with + * createCamera(). + * + * Note: `setCamera()` can only be used in WebGL mode. + * + * @method setCamera + * @param {p5.Camera} cam camera that should be made active. + * @for p5 + * + * @example + *
        + * + * // Double-click to toggle between cameras. + * + * let cam1; + * let cam2; + * let usingCam1 = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = createCamera(); + * + * // Create the second camera. + * // Place it at the top-left. + * // Point it at the origin. + * cam2 = createCamera(); + * cam2.setPosition(400, -400, 800); + * cam2.lookAt(0, 0, 0); + * + * // Set the current camera to cam1. + * setCamera(cam1); + * + * describe('A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Draw the box. + * box(); + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (usingCam1 === true) { + * setCamera(cam2); + * usingCam1 = false; + * } else { + * setCamera(cam1); + * usingCam1 = true; + * } + * } + * + *
        + */ + _main.default.prototype.setCamera = function (cam) { + this._renderer._curCamera = cam; + // set the projection matrix (which is not normally updated each frame) + this._renderer.uPMatrix.set(cam.projMatrix); + }; + var _default = _main.default.Camera; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.math.hypot': 193, + 'core-js/modules/es.string.sub': 223 + } + ], + 353: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.log2'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.math.log2'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * An internal class to store data that will be sent to a p5.RenderBuffer. + * Those need to eventually go into a Float32Array, so this class provides a + * variable-length array container backed by a Float32Array so that it can be + * sent to the GPU without allocating a new array each frame. + * + * Like a C++ vector, its fixed-length Float32Array backing its contents will + * double in size when it goes over its capacity. + * + * @example + *
        + * + * // Initialize storage with a capacity of 4 + * const storage = new DataArray(4); + * console.log(storage.data.length); // 4 + * console.log(storage.length); // 0 + * console.log(storage.dataArray()); // Empty Float32Array + * + * storage.push(1, 2, 3, 4, 5, 6); + * console.log(storage.data.length); // 8 + * console.log(storage.length); // 6 + * console.log(storage.dataArray()); // Float32Array{1, 2, 3, 4, 5, 6} + * + *
        + */ + + _main.default.DataArray = /*#__PURE__*/ function () { + function DataArray() { + var initialLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 128; + _classCallCheck(this, DataArray); + this.length = 0; + this.data = new Float32Array(initialLength); + this.initialLength = initialLength; + } /** + * Returns a Float32Array window sized to the exact length of the data + */ + + _createClass(DataArray, [ + { + key: 'dataArray', + value: function dataArray() { + return this.subArray(0, this.length); + } /** + * A "soft" clear, which keeps the underlying storage size the same, but + * empties the contents of its dataArray() + */ + + }, + { + key: 'clear', + value: function clear() { + this.length = 0; + } /** + * Can be used to scale a DataArray back down to fit its contents. + */ + + }, + { + key: 'rescale', + value: function rescale() { + if (this.length < this.data.length / 2) { + // Find the power of 2 size that fits the data + var targetLength = 1 << Math.ceil(Math.log2(this.length)); + var newData = new Float32Array(targetLength); + newData.set(this.data.subarray(0, this.length), 0); + this.data = newData; + } + } /** + * A full reset, which allocates a new underlying Float32Array at its initial + * length + */ + + }, + { + key: 'reset', + value: function reset() { + this.clear(); + this.data = new Float32Array(this.initialLength); + } /** + * Adds values to the DataArray, expanding its internal storage to + * accommodate the new items. + */ + + }, + { + key: 'push', + value: function push() { + for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) { + values[_key] = arguments[_key]; + } + this.ensureLength(this.length + values.length); + this.data.set(values, this.length); + this.length += values.length; + } /** + * Returns a copy of the data from the index `from`, inclusive, to the index + * `to`, exclusive + */ + + }, + { + key: 'slice', + value: function slice(from, to) { + return this.data.slice(from, Math.min(to, this.length)); + } /** + * Returns a mutable Float32Array window from the index `from`, inclusive, to + * the index `to`, exclusive + */ + + }, + { + key: 'subArray', + value: function subArray(from, to) { + return this.data.subarray(from, Math.min(to, this.length)); + } /** + * Expand capacity of the internal storage until it can fit a target size + */ + + }, + { + key: 'ensureLength', + value: function ensureLength(target) { + while (this.data.length < target) { + var newData = new Float32Array(this.data.length * 2); + newData.set(this.data, 0); + this.data = newData; + } + } + } + ]); + return DataArray; + }(); + var _default = _main.default.DataArray; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.math.log2': 194, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.float32-array': 234, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254 + } + ], + 354: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.reflect.get'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint8-clamped-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint8-clamped-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + var _p = _dereq_('./p5.Texture'); + var _p2 = _dereq_('./p5.RendererGL'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); + } + function _nonIterableRest() { + throw new TypeError('Invalid attempt to destructure non-iterable instance'); + } + function _iterableToArrayLimit(arr, i) { + if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === '[object Arguments]')) { + return; + } + var _arr = [ + ]; + var _n = true; + var _d = false; + var _e = undefined; + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i['return'] != null) _i['return'](); + } finally { + if (_d) throw _e; + } + } + return _arr; + } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } + function _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; + } + 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 = _getPrototypeOf(object); + if (object === null) break; + } + return object; + } + 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 _createSuper(Derived) { + function 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; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_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); + } /** + * @module Rendering + * @requires constants + */ + + var FramebufferCamera = /*#__PURE__*/ function (_p5$Camera) { + _inherits(FramebufferCamera, _p5$Camera); + var _super = _createSuper(FramebufferCamera); + /** + * A p5.Camera attached to a + * p5.Framebuffer. + * + * @class p5.FramebufferCamera + * @constructor + * @param {p5.Framebuffer} framebuffer The framebuffer this camera is + * attached to + * @private + */ + function FramebufferCamera(framebuffer) { + var _this; + _classCallCheck(this, FramebufferCamera); + _this = _super.call(this, framebuffer.target._renderer); + _this.fbo = framebuffer; + // WebGL textures are upside-down compared to textures that come from + // images and graphics. Framebuffer cameras need to invert their y + // axes when being rendered to so that the texture comes out rightway up + // when read in shaders or image(). + _this.yScale = - 1; + return _this; + } + _createClass(FramebufferCamera, [ + { + key: '_computeCameraDefaultSettings', + value: function _computeCameraDefaultSettings() { + _get(_getPrototypeOf(FramebufferCamera.prototype), '_computeCameraDefaultSettings', this).call(this); + this.defaultAspectRatio = this.fbo.width / this.fbo.height; + this.defaultCameraFOV = 2 * Math.atan(this.fbo.height / 2 / this.defaultEyeZ); + } + } + ]); + return FramebufferCamera; + }(_main.default.Camera); + _main.default.FramebufferCamera = FramebufferCamera; + var FramebufferTexture = /*#__PURE__*/ function () { + /** + * A p5.Texture corresponding to a property of a + * p5.Framebuffer. + * + * @class p5.FramebufferTexture + * @param {p5.Framebuffer} framebuffer The framebuffer represented by this + * texture + * @param {String} property The property of the framebuffer represented by + * this texture, either `color` or `depth` + * @private + */ + function FramebufferTexture(framebuffer, property) { + _classCallCheck(this, FramebufferTexture); + this.framebuffer = framebuffer; + this.property = property; + } + _createClass(FramebufferTexture, [ + { + key: 'rawTexture', + value: function rawTexture() { + return this.framebuffer[this.property]; + } + }, + { + key: 'width', + get: function get() { + return this.framebuffer.width * this.framebuffer.density; + } + }, + { + key: 'height', + get: function get() { + return this.framebuffer.height * this.framebuffer.density; + } + } + ]); + return FramebufferTexture; + }(); + _main.default.FramebufferTexture = FramebufferTexture; + var Framebuffer = /*#__PURE__*/ function () { + /** + * A class to describe a high-performance drawing surface for textures. + * + * Each `p5.Framebuffer` object provides a dedicated drawing surface called + * a *framebuffer*. They're similar to + * p5.Graphics objects but can run much faster. + * Performance is improved because the framebuffer shares the same WebGL + * context as the canvas used to create it. + * + * `p5.Framebuffer` objects have all the drawing features of the main + * canvas. Drawing instructions meant for the framebuffer must be placed + * between calls to + * myBuffer.begin() and + * myBuffer.end(). The resulting image + * can be applied as a texture by passing the `p5.Framebuffer` object to the + * texture() function, as in `texture(myBuffer)`. + * It can also be displayed on the main canvas by passing it to the + * image() function, as in `image(myBuffer, 0, 0)`. + * + * Note: createFramebuffer() is the + * recommended way to create an instance of this class. + * + * @class p5.Framebuffer + * @constructor + * @param {p5.Graphics|p5} target sketch instance or + * p5.Graphics + * object. + * @param {Object} [settings] configuration options. + */ + function Framebuffer(target) { + var _this2 = this; + var settings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }; + _classCallCheck(this, Framebuffer); + this.target = target; + this.target._renderer.framebuffers.add(this); + this._isClipApplied = false; + /** + * An array containing the color of each pixel in the framebuffer. + * + * myBuffer.loadPixels() must be + * called before accessing the `myBuffer.pixels` array. + * myBuffer.updatePixels() + * must be called after any changes are made. + * + * Note: Updating pixels via this property is slower than drawing to the + * framebuffer directly. Consider using a + * p5.Shader object instead of looping over + * `myBuffer.pixels`. + * + * @property {Number[]} pixels + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create a p5.Framebuffer object. + * let myBuffer = createFramebuffer(); + * + * // Load the pixels array. + * myBuffer.loadPixels(); + * + * // Get the number of pixels in the + * // top half of the framebuffer. + * let numPixels = myBuffer.pixels.length / 2; + * + * // Set the framebuffer's top half to pink. + * for (let i = 0; i < numPixels; i += 4) { + * myBuffer.pixels[i] = 255; + * myBuffer.pixels[i + 1] = 102; + * myBuffer.pixels[i + 2] = 204; + * myBuffer.pixels[i + 3] = 255; + * } + * + * // Update the pixels array. + * myBuffer.updatePixels(); + * + * // Draw the p5.Framebuffer object to the canvas. + * image(myBuffer, -50, -50); + * + * describe('A pink rectangle above a gray rectangle.'); + * } + * + *
        + */ + this.pixels = [ + ]; + this.format = settings.format || constants.UNSIGNED_BYTE; + this.channels = settings.channels || (target._renderer._pInst._glAttributes.alpha ? constants.RGBA : constants.RGB); + this.useDepth = settings.depth === undefined ? true : settings.depth; + this.depthFormat = settings.depthFormat || constants.FLOAT; + this.textureFiltering = settings.textureFiltering || constants.LINEAR; + if (settings.antialias === undefined) { + this.antialiasSamples = target._renderer._pInst._glAttributes.antialias ? 2 : 0; + } else if (typeof settings.antialias === 'number') { + this.antialiasSamples = settings.antialias; + } else { + this.antialiasSamples = settings.antialias ? 2 : 0; + } + this.antialias = this.antialiasSamples > 0; + if (this.antialias && target.webglVersion !== constants.WEBGL2) { + console.warn('Antialiasing is unsupported in a WebGL 1 context'); + this.antialias = false; + } + this.density = settings.density || target.pixelDensity(); + var gl = target._renderer.GL; + this.gl = gl; + if (settings.width && settings.height) { + var dimensions = target._renderer._adjustDimensions(settings.width, settings.height); + this.width = dimensions.adjustedWidth; + this.height = dimensions.adjustedHeight; + this._autoSized = false; + } else { + if (settings.width === undefined !== (settings.height === undefined)) { + console.warn('Please supply both width and height for a framebuffer to give it a ' + 'size. Only one was given, so the framebuffer will match the size ' + 'of its canvas.'); + } + this.width = target.width; + this.height = target.height; + this._autoSized = true; + } + this._checkIfFormatsAvailable(); + if (settings.stencil && !this.useDepth) { + console.warn('A stencil buffer can only be used if also using depth. Since the framebuffer has no depth buffer, the stencil buffer will be ignored.'); + } + this.useStencil = this.useDepth && (settings.stencil === undefined ? true : settings.stencil); + this.framebuffer = gl.createFramebuffer(); + if (!this.framebuffer) { + throw new Error('Unable to create a framebuffer'); + } + if (this.antialias) { + this.aaFramebuffer = gl.createFramebuffer(); + if (!this.aaFramebuffer) { + throw new Error('Unable to create a framebuffer for antialiasing'); + } + } + this._recreateTextures(); + var prevCam = this.target._renderer._curCamera; + this.defaultCamera = this.createCamera(); + this.filterCamera = this.createCamera(); + this.target._renderer._curCamera = prevCam; + this.draw(function () { + return _this2.target.clear(); + }); + } /** + * Resizes the framebuffer to a given width and height. + * + * The parameters, `width` and `height`, set the dimensions of the + * framebuffer. For example, calling `myBuffer.resize(300, 500)` resizes + * the framebuffer to 300×500 pixels, then sets `myBuffer.width` to 300 + * and `myBuffer.height` 500. + * + * @method resize + * @param {Number} width width of the framebuffer. + * @param {Number} height height of the framebuffer. + * + * @example + *
        + * + * let myBuffer; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * describe('A multicolor sphere on a white surface. The image grows larger or smaller when the user moves the mouse, revealing a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Draw to the p5.Framebuffer object. + * myBuffer.begin(); + * background(255); + * normalMaterial(); + * sphere(20); + * myBuffer.end(); + * + * // Display the p5.Framebuffer object. + * image(myBuffer, -50, -50); + * } + * + * // Resize the p5.Framebuffer object when the + * // user moves the mouse. + * function mouseMoved() { + * myBuffer.resize(mouseX, mouseY); + * } + * + *
        + */ + + _createClass(Framebuffer, [ + { + key: 'resize', + value: function resize(width, height) { + this._autoSized = false; + var dimensions = this.target._renderer._adjustDimensions(width, height); + width = dimensions.adjustedWidth; + height = dimensions.adjustedHeight; + this.width = width; + this.height = height; + this._handleResize(); + } /** + * Sets the framebuffer's pixel density or returns its current density. + * + * Computer displays are grids of little lights called pixels. A display's + * pixel density describes how many pixels it packs into an area. Displays + * with smaller pixels have a higher pixel density and create sharper + * images. + * + * The parameter, `density`, is optional. If a number is passed, as in + * `myBuffer.pixelDensity(1)`, it sets the framebuffer's pixel density. By + * default, the framebuffer's pixel density will match that of the canvas + * where it was created. All canvases default to match the display's pixel + * density. + * + * Calling `myBuffer.pixelDensity()` without an argument returns its current + * pixel density. + * + * @method pixelDensity + * @param {Number} [density] pixel density to set. + * @returns {Number} current pixel density. + * + * @example + *
        + * + * let myBuffer; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * describe("A white circle on a gray canvas. The circle's edge become fuzzy while the user presses and holds the mouse."); + * } + * + * function draw() { + * // Draw to the p5.Framebuffer object. + * myBuffer.begin(); + * background(200); + * circle(0, 0, 40); + * myBuffer.end(); + * + * // Display the p5.Framebuffer object. + * image(myBuffer, -50, -50); + * } + * + * // Decrease the pixel density when the user + * // presses the mouse. + * function mousePressed() { + * myBuffer.pixelDensity(1); + * } + * + * // Increase the pixel density when the user + * // releases the mouse. + * function mouseReleased() { + * myBuffer.pixelDensity(2); + * } + * + *
        + * + *
        + * + * let myBuffer; + * let myFont; + * + * // Load a font and create a p5.Font object. + * function preload() { + * myFont = loadFont('assets/inconsolata.otf'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * // Get the p5.Framebuffer object's pixel density. + * let d = myBuffer.pixelDensity(); + * + * // Style the text. + * textAlign(CENTER, CENTER); + * textFont(myFont); + * textSize(16); + * fill(0); + * + * // Display the pixel density. + * text(`Density: ${d}`, 0, 0); + * + * describe(`The text "Density: ${d}" written in black on a gray background.`); + * } + * + *
        + */ + + }, + { + key: 'pixelDensity', + value: function pixelDensity(density) { + if (density) { + this._autoSized = false; + this.density = density; + this._handleResize(); + } else { + return this.density; + } + } /** + * Toggles the framebuffer's autosizing mode or returns the current mode. + * + * By default, the framebuffer automatically resizes to match the canvas + * that created it. Calling `myBuffer.autoSized(false)` disables this + * behavior and calling `myBuffer.autoSized(true)` re-enables it. + * + * Calling `myBuffer.autoSized()` without an argument returns `true` if + * the framebuffer automatically resizes and `false` if not. + * + * @method autoSized + * @param {Boolean} [autoSized] whether to automatically resize the framebuffer to match the canvas. + * @returns {Boolean} current autosize setting. + * + * @example + *
        + * + * // Double-click to toggle the autosizing mode. + * + * let myBuffer; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * describe('A multicolor sphere on a gray background. The image resizes when the user moves the mouse.'); + * } + * + * function draw() { + * background(50); + * + * // Draw to the p5.Framebuffer object. + * myBuffer.begin(); + * background(200); + * normalMaterial(); + * sphere(width / 4); + * myBuffer.end(); + * + * // Display the p5.Framebuffer object. + * image(myBuffer, -width / 2, -height / 2); + * } + * + * // Resize the canvas when the user moves the mouse. + * function mouseMoved() { + * let w = constrain(mouseX, 0, 100); + * let h = constrain(mouseY, 0, 100); + * resizeCanvas(w, h); + * } + * + * // Toggle autoSizing when the user double-clicks. + * // Note: opened an issue to fix(?) this. + * function doubleClicked() { + * let isAuto = myBuffer.autoSized(); + * myBuffer.autoSized(!isAuto); + * } + * + *
        + */ + + }, + { + key: 'autoSized', + value: function autoSized(_autoSized) { + if (_autoSized === undefined) { + return this._autoSized; + } else { + this._autoSized = _autoSized; + this._handleResize(); + } + } /** + * Checks the capabilities of the current WebGL environment to see if the + * settings supplied by the user are capable of being fulfilled. If they + * are not, warnings will be logged and the settings will be changed to + * something close that can be fulfilled. + * + * @private + */ + + }, + { + key: '_checkIfFormatsAvailable', + value: function _checkIfFormatsAvailable() { + var gl = this.gl; + if (this.useDepth && this.target.webglVersion === constants.WEBGL && !gl.getExtension('WEBGL_depth_texture')) { + console.warn('Unable to create depth textures in this environment. Falling back ' + 'to a framebuffer without depth.'); + this.useDepth = false; + } + if (this.useDepth && this.target.webglVersion === constants.WEBGL && this.depthFormat === constants.FLOAT) { + console.warn('FLOAT depth format is unavailable in WebGL 1. ' + 'Defaulting to UNSIGNED_INT.'); + this.depthFormat = constants.UNSIGNED_INT; + } + if (![constants.UNSIGNED_BYTE, + constants.FLOAT, + constants.HALF_FLOAT].includes(this.format)) { + console.warn('Unknown Framebuffer format. ' + 'Please use UNSIGNED_BYTE, FLOAT, or HALF_FLOAT. ' + 'Defaulting to UNSIGNED_BYTE.'); + this.format = constants.UNSIGNED_BYTE; + } + if (this.useDepth && ![constants.UNSIGNED_INT, + constants.FLOAT].includes(this.depthFormat)) { + console.warn('Unknown Framebuffer depth format. ' + 'Please use UNSIGNED_INT or FLOAT. Defaulting to FLOAT.'); + this.depthFormat = constants.FLOAT; + } + var support = (0, _p.checkWebGLCapabilities) (this.target._renderer); + if (!support.float && this.format === constants.FLOAT) { + console.warn('This environment does not support FLOAT textures. ' + 'Falling back to UNSIGNED_BYTE.'); + this.format = constants.UNSIGNED_BYTE; + } + if (this.useDepth && !support.float && this.depthFormat === constants.FLOAT) { + console.warn('This environment does not support FLOAT depth textures. ' + 'Falling back to UNSIGNED_INT.'); + this.depthFormat = constants.UNSIGNED_INT; + } + if (!support.halfFloat && this.format === constants.HALF_FLOAT) { + console.warn('This environment does not support HALF_FLOAT textures. ' + 'Falling back to UNSIGNED_BYTE.'); + this.format = constants.UNSIGNED_BYTE; + } + if (this.channels === constants.RGB && [ + constants.FLOAT, + constants.HALF_FLOAT + ].includes(this.format)) { + console.warn('FLOAT and HALF_FLOAT formats do not work cross-platform with only ' + 'RGB channels. Falling back to RGBA.'); + this.channels = constants.RGBA; + } + } /** + * Creates new textures and renderbuffers given the current size of the + * framebuffer. + * + * @private + */ + + }, + { + key: '_recreateTextures', + value: function _recreateTextures() { + var gl = this.gl; + this._updateSize(); + var prevBoundTexture = gl.getParameter(gl.TEXTURE_BINDING_2D); + var prevBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + var colorTexture = gl.createTexture(); + if (!colorTexture) { + throw new Error('Unable to create color texture'); + } + gl.bindTexture(gl.TEXTURE_2D, colorTexture); + var colorFormat = this._glColorFormat(); + gl.texImage2D(gl.TEXTURE_2D, 0, colorFormat.internalFormat, this.width * this.density, this.height * this.density, 0, colorFormat.format, colorFormat.type, null); + this.colorTexture = colorTexture; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTexture, 0); + if (this.useDepth) { + // Create the depth texture + var depthTexture = gl.createTexture(); + if (!depthTexture) { + throw new Error('Unable to create depth texture'); + } + var depthFormat = this._glDepthFormat(); + gl.bindTexture(gl.TEXTURE_2D, depthTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, depthFormat.internalFormat, this.width * this.density, this.height * this.density, 0, depthFormat.format, depthFormat.type, null); + gl.framebufferTexture2D(gl.FRAMEBUFFER, this.useStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0); + this.depthTexture = depthTexture; + } // Create separate framebuffer for antialiasing + + if (this.antialias) { + this.colorRenderbuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, this.colorRenderbuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, Math.max(0, Math.min(this.antialiasSamples, gl.getParameter(gl.MAX_SAMPLES))), colorFormat.internalFormat, this.width * this.density, this.height * this.density); + if (this.useDepth) { + var _depthFormat = this._glDepthFormat(); + this.depthRenderbuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, this.depthRenderbuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, Math.max(0, Math.min(this.antialiasSamples, gl.getParameter(gl.MAX_SAMPLES))), _depthFormat.internalFormat, this.width * this.density, this.height * this.density); + } + gl.bindFramebuffer(gl.FRAMEBUFFER, this.aaFramebuffer); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, this.colorRenderbuffer); + if (this.useDepth) { + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, this.useStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.depthRenderbuffer); + } + } + if (this.useDepth) { + this.depth = new FramebufferTexture(this, 'depthTexture'); + var depthFilter = gl.NEAREST; + this.depthP5Texture = new _main.default.Texture(this.target._renderer, this.depth, { + minFilter: depthFilter, + magFilter: depthFilter + }); + this.target._renderer.textures.set(this.depth, this.depthP5Texture); + } + this.color = new FramebufferTexture(this, 'colorTexture'); + var filter = this.textureFiltering === constants.LINEAR ? gl.LINEAR : gl.NEAREST; + this.colorP5Texture = new _main.default.Texture(this.target._renderer, this.color, { + minFilter: filter, + magFilter: filter + }); + this.target._renderer.textures.set(this.color, this.colorP5Texture); + gl.bindTexture(gl.TEXTURE_2D, prevBoundTexture); + gl.bindFramebuffer(gl.FRAMEBUFFER, prevBoundFramebuffer); + } /** + * To create a WebGL texture, one needs to supply three pieces of information: + * the type (the data type each channel will be stored as, e.g. int or float), + * the format (the color channels that will each be stored in the previously + * specified type, e.g. rgb or rgba), and the internal format (the specifics + * of how data for each channel, in the aforementioned type, will be packed + * together, such as how many bits to use, e.g. RGBA32F or RGB565.) + * + * The format and channels asked for by the user hint at what these values + * need to be, and the WebGL version affects what options are avaiable. + * This method returns the values for these three properties, given the + * framebuffer's settings. + * + * @private + */ + + }, + { + key: '_glColorFormat', + value: function _glColorFormat() { + var type, + format, + internalFormat; + var gl = this.gl; + if (this.format === constants.FLOAT) { + type = gl.FLOAT; + } else if (this.format === constants.HALF_FLOAT) { + type = this.target.webglVersion === constants.WEBGL2 ? gl.HALF_FLOAT : gl.getExtension('OES_texture_half_float').HALF_FLOAT_OES; + } else { + type = gl.UNSIGNED_BYTE; + } + if (this.channels === constants.RGBA) { + format = gl.RGBA; + } else { + format = gl.RGB; + } + if (this.target.webglVersion === constants.WEBGL2) { + var _gl$UNSIGNED_BYTE, + _table; + // https://webgl2fundamentals.org/webgl/lessons/webgl-data-textures.html + var table = (_table = { + }, _defineProperty(_table, gl.FLOAT, _defineProperty({ + }, gl.RGBA, gl.RGBA32F)), _defineProperty(_table, gl.HALF_FLOAT, _defineProperty({ + }, gl.RGBA, gl.RGBA16F)), _defineProperty(_table, gl.UNSIGNED_BYTE, (_gl$UNSIGNED_BYTE = { + }, _defineProperty(_gl$UNSIGNED_BYTE, gl.RGBA, gl.RGBA8), _defineProperty(_gl$UNSIGNED_BYTE, gl.RGB, gl.RGB8), _gl$UNSIGNED_BYTE)), _table); + internalFormat = table[type][format]; + } else if (this.format === constants.HALF_FLOAT) { + internalFormat = gl.RGBA; + } else { + internalFormat = format; + } + return { + internalFormat: internalFormat, + format: format, + type: type + }; + } /** + * To create a WebGL texture, one needs to supply three pieces of information: + * the type (the data type each channel will be stored as, e.g. int or float), + * the format (the color channels that will each be stored in the previously + * specified type, e.g. rgb or rgba), and the internal format (the specifics + * of how data for each channel, in the aforementioned type, will be packed + * together, such as how many bits to use, e.g. RGBA32F or RGB565.) + * + * This method takes into account the settings asked for by the user and + * returns values for these three properties that can be used for the + * texture storing depth information. + * + * @private + */ + + }, + { + key: '_glDepthFormat', + value: function _glDepthFormat() { + var type, + format, + internalFormat; + var gl = this.gl; + if (this.useStencil) { + if (this.depthFormat === constants.FLOAT) { + type = gl.FLOAT_32_UNSIGNED_INT_24_8_REV; + } else if (this.target.webglVersion === constants.WEBGL2) { + type = gl.UNSIGNED_INT_24_8; + } else { + type = gl.getExtension('WEBGL_depth_texture').UNSIGNED_INT_24_8_WEBGL; + } + } else { + if (this.depthFormat === constants.FLOAT) { + type = gl.FLOAT; + } else { + type = gl.UNSIGNED_INT; + } + } + if (this.useStencil) { + format = gl.DEPTH_STENCIL; + } else { + format = gl.DEPTH_COMPONENT; + } + if (this.useStencil) { + if (this.depthFormat === constants.FLOAT) { + internalFormat = gl.DEPTH32F_STENCIL8; + } else if (this.target.webglVersion === constants.WEBGL2) { + internalFormat = gl.DEPTH24_STENCIL8; + } else { + internalFormat = gl.DEPTH_STENCIL; + } + } else if (this.target.webglVersion === constants.WEBGL2) { + if (this.depthFormat === constants.FLOAT) { + internalFormat = gl.DEPTH_COMPONENT32F; + } else { + internalFormat = gl.DEPTH_COMPONENT24; + } + } else { + internalFormat = gl.DEPTH_COMPONENT; + } + return { + internalFormat: internalFormat, + format: format, + type: type + }; + } /** + * A method that will be called when recreating textures. If the framebuffer + * is auto-sized, it will update its width, height, and density properties. + * + * @private + */ + + }, + { + key: '_updateSize', + value: function _updateSize() { + if (this._autoSized) { + this.width = this.target.width; + this.height = this.target.height; + this.density = this.target.pixelDensity(); + } + } /** + * Called when the canvas that the framebuffer is attached to resizes. If the + * framebuffer is auto-sized, it will update its textures to match the new + * size. + * + * @private + */ + + }, + { + key: '_canvasSizeChanged', + value: function _canvasSizeChanged() { + if (this._autoSized) { + this._handleResize(); + } + } /** + * Called when the size of the framebuffer has changed (either by being + * manually updated or from auto-size updates when its canvas changes size.) + * Old textures and renderbuffers will be deleted, and then recreated with the + * new size. + * + * @private + */ + + }, + { + key: '_handleResize', + value: function _handleResize() { + var oldColor = this.color; + var oldDepth = this.depth; + var oldColorRenderbuffer = this.colorRenderbuffer; + var oldDepthRenderbuffer = this.depthRenderbuffer; + this._deleteTexture(oldColor); + if (oldDepth) this._deleteTexture(oldDepth); + var gl = this.gl; + if (oldColorRenderbuffer) gl.deleteRenderbuffer(oldColorRenderbuffer); + if (oldDepthRenderbuffer) gl.deleteRenderbuffer(oldDepthRenderbuffer); + this._recreateTextures(); + this.defaultCamera._resize(); + } /** + * Creates a new + * p5.Camera object to use with the framebuffer. + * + * The new camera is initialized with a default position `(0, 0, 800)` and a + * default perspective projection. Its properties can be controlled with + * p5.Camera methods such as `myCamera.lookAt(0, 0, 0)`. + * + * Framebuffer cameras should be created between calls to + * myBuffer.begin() and + * myBuffer.end() like so: + * + * ```js + * let myCamera; + * + * myBuffer.begin(); + * + * // Create the camera for the framebuffer. + * myCamera = myBuffer.createCamera(); + * + * myBuffer.end(); + * ``` + * + * Calling setCamera() updates the + * framebuffer's projection using the camera. + * resetMatrix() must also be called for the + * view to change properly: + * + * ```js + * myBuffer.begin(); + * + * // Set the camera for the framebuffer. + * setCamera(myCamera); + * + * // Reset all transformations. + * resetMatrix(); + * + * // Draw stuff... + * + * myBuffer.end(); + * ``` + * + * @method createCamera + * @returns {p5.Camera} new camera. + * + * @example + *
        + * + * // Double-click to toggle between cameras. + * + * let myBuffer; + * let cam1; + * let cam2; + * let usingCam1 = true; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * // Create the cameras between begin() and end(). + * myBuffer.begin(); + * + * // Create the first camera. + * // Keep its default settings. + * cam1 = myBuffer.createCamera(); + * + * // Create the second camera. + * // Place it at the top-left. + * // Point it at the origin. + * cam2 = myBuffer.createCamera(); + * cam2.setPosition(400, -400, 800); + * cam2.lookAt(0, 0, 0); + * + * myBuffer.end(); + * + * describe( + * 'A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.' + * ); + * } + * + * function draw() { + * // Draw to the p5.Framebuffer object. + * myBuffer.begin(); + * background(200); + * + * // Set the camera. + * if (usingCam1 === true) { + * setCamera(cam1); + * } else { + * setCamera(cam2); + * } + * + * // Reset all transformations. + * resetMatrix(); + * + * // Draw the box. + * box(); + * + * myBuffer.end(); + * + * // Display the p5.Framebuffer object. + * image(myBuffer, -50, -50); + * } + * + * // Toggle the current camera when the user double-clicks. + * function doubleClicked() { + * if (usingCam1 === true) { + * usingCam1 = false; + * } else { + * usingCam1 = true; + * } + * } + * + *
        + */ + + }, + { + key: 'createCamera', + value: function createCamera() { + var cam = new FramebufferCamera(this); + cam._computeCameraDefaultSettings(); + cam._setDefaultCamera(); + this.target._renderer._curCamera = cam; + return cam; + } /** + * Given a raw texture wrapper, delete its stored texture from WebGL memory, + * and remove it from p5's list of active textures. + * + * @param {p5.FramebufferTexture} texture + * @private + */ + + }, + { + key: '_deleteTexture', + value: function _deleteTexture(texture) { + var gl = this.gl; + gl.deleteTexture(texture.rawTexture()); + this.target._renderer.textures.delete(texture); + } /** + * Deletes the framebuffer from GPU memory. + * + * Calling `myBuffer.remove()` frees the GPU memory used by the framebuffer. + * The framebuffer also uses a bit of memory on the CPU which can be freed + * like so: + * + * ```js + * // Delete the framebuffer from GPU memory. + * myBuffer.remove(); + * + * // Delete the framebuffer from CPU memory. + * myBuffer = undefined; + * ``` + * + * Note: All variables that reference the framebuffer must be assigned + * the value `undefined` to delete the framebuffer from CPU memory. If any + * variable still refers to the framebuffer, then it won't be garbage + * collected. + * + * @method remove + * + * @example + *
        + * + * // Double-click to remove the p5.Framebuffer object. + * + * let myBuffer; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create an options object. + * let options = { width: 60, height: 60 }; + * + * // Create a p5.Framebuffer object and + * // configure it using options. + * myBuffer = createFramebuffer(options); + * + * describe('A white circle at the center of a dark gray square disappears when the user double-clicks.'); + * } + * + * function draw() { + * background(200); + * + * // Display the p5.Framebuffer object if + * // it's available. + * if (myBuffer) { + * // Draw to the p5.Framebuffer object. + * myBuffer.begin(); + * background(100); + * circle(0, 0, 20); + * myBuffer.end(); + * + * image(myBuffer, -30, -30); + * } + * } + * + * // Remove the p5.Framebuffer object when the + * // the user double-clicks. + * function doubleClicked() { + * // Delete the framebuffer from GPU memory. + * myBuffer.remove(); + * + * // Delete the framebuffer from CPU memory. + * myBuffer = undefined; + * } + * + *
        + */ + + }, + { + key: 'remove', + value: function remove() { + var gl = this.gl; + this._deleteTexture(this.color); + if (this.depth) this._deleteTexture(this.depth); + gl.deleteFramebuffer(this.framebuffer); + if (this.aaFramebuffer) { + gl.deleteFramebuffer(this.aaFramebuffer); + } + if (this.depthRenderbuffer) { + gl.deleteRenderbuffer(this.depthRenderbuffer); + } + if (this.colorRenderbuffer) { + gl.deleteRenderbuffer(this.colorRenderbuffer); + } + this.target._renderer.framebuffers.delete(this); + } /** + * Begins drawing shapes to the framebuffer. + * + * `myBuffer.begin()` and myBuffer.end() + * allow shapes to be drawn to the framebuffer. `myBuffer.begin()` begins + * drawing to the framebuffer and + * myBuffer.end() stops drawing to the + * framebuffer. Changes won't be visible until the framebuffer is displayed + * as an image or texture. + * + * @method begin + * + * @example + *
        + * + * let myBuffer; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.'); + * } + * + * function draw() { + * background(200); + * + * // Start drawing to the p5.Framebuffer object. + * myBuffer.begin(); + * + * background(50); + * rotateY(frameCount * 0.01); + * normalMaterial(); + * torus(30); + * + * // Stop drawing to the p5.Framebuffer object. + * myBuffer.end(); + * + * // Display the p5.Framebuffer object while + * // the user presses the mouse. + * if (mouseIsPressed === true) { + * image(myBuffer, -50, -50); + * } + * } + * + *
        + */ + + }, + { + key: 'begin', + value: function begin() { + this.prevFramebuffer = this.target._renderer.activeFramebuffer(); + if (this.prevFramebuffer) { + this.prevFramebuffer._beforeEnd(); + } + this.target._renderer.activeFramebuffers.push(this); + this._beforeBegin(); + this.target.push(); + // Apply the framebuffer's camera. This does almost what + // RendererGL.reset() does, but this does not try to clear any buffers; + // it only sets the camera. + this.target.setCamera(this.defaultCamera); + this.target._renderer.uMVMatrix.set(this.target._renderer._curCamera.cameraMatrix); + this.target._renderer._applyStencilTestIfClipping(); + } /** + * When making a p5.Framebuffer active so that it may be drawn to, this method + * returns the underlying WebGL framebuffer that needs to be active to + * support this. Antialiased framebuffers first write to a multisampled + * renderbuffer, while other framebuffers can write directly to their main + * framebuffers. + * + * @method _framebufferToBind + * @private + */ + + }, + { + key: '_framebufferToBind', + value: function _framebufferToBind() { + if (this.antialias) { + // If antialiasing, draw to an antialiased renderbuffer rather + // than directly to the texture. In end() we will copy from the + // renderbuffer to the texture. + return this.aaFramebuffer; + } else { + return this.framebuffer; + } + } /** + * Ensures that the framebuffer is ready to be drawn to + * + * @method _beforeBegin + * @private + */ + + }, + { + key: '_beforeBegin', + value: function _beforeBegin() { + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebufferToBind()); + this.target._renderer.viewport(this.width * this.density, this.height * this.density); + } /** + * Ensures that the framebuffer is ready to be read by other framebuffers. + * + * @method _beforeEnd + * @private + */ + + }, + { + key: '_beforeEnd', + value: function _beforeEnd() { + if (this.antialias) { + var gl = this.gl; + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, this.aaFramebuffer); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, this.framebuffer); + var partsToCopy = [ + [gl.COLOR_BUFFER_BIT, + this.colorP5Texture.glMagFilter] + ]; + if (this.useDepth) { + partsToCopy.push([gl.DEPTH_BUFFER_BIT, + this.depthP5Texture.glMagFilter]); + } + for (var _i = 0, _partsToCopy = partsToCopy; _i < _partsToCopy.length; _i++) { + var _partsToCopy$_i = _slicedToArray(_partsToCopy[_i], 2), + flag = _partsToCopy$_i[0], + filter = _partsToCopy$_i[1]; + gl.blitFramebuffer(0, 0, this.width * this.density, this.height * this.density, 0, 0, this.width * this.density, this.height * this.density, flag, filter); + } + } + } /** + * Stops drawing shapes to the framebuffer. + * + * myBuffer.begin() and `myBuffer.end()` + * allow shapes to be drawn to the framebuffer. + * myBuffer.begin() begins drawing to + * the framebuffer and `myBuffer.end()` stops drawing to the framebuffer. + * Changes won't be visible until the framebuffer is displayed as an image + * or texture. + * + * @method end + * + * @example + *
        + * + * let myBuffer; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.'); + * } + * + * function draw() { + * background(200); + * + * // Start drawing to the p5.Framebuffer object. + * myBuffer.begin(); + * + * background(50); + * rotateY(frameCount * 0.01); + * normalMaterial(); + * torus(30); + * + * // Stop drawing to the p5.Framebuffer object. + * myBuffer.end(); + * + * // Display the p5.Framebuffer object while + * // the user presses the mouse. + * if (mouseIsPressed === true) { + * image(myBuffer, -50, -50); + * } + * } + * + *
        + */ + + }, + { + key: 'end', + value: function end() { + var gl = this.gl; + this.target.pop(); + var fbo = this.target._renderer.activeFramebuffers.pop(); + if (fbo !== this) { + throw new Error('It looks like you\'ve called end() while another Framebuffer is active.'); + } + this._beforeEnd(); + if (this.prevFramebuffer) { + this.prevFramebuffer._beforeBegin(); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + this.target._renderer.viewport(this.target._renderer._origViewport.width, this.target._renderer._origViewport.height); + } + this.target._renderer._applyStencilTestIfClipping(); + } /** + * Draws to the framebuffer by calling a function that contains drawing + * instructions. + * + * The parameter, `callback`, is a function with the drawing instructions + * for the framebuffer. For example, calling `myBuffer.draw(myFunction)` + * will call a function named `myFunction()` to draw to the framebuffer. + * Doing so has the same effect as the following: + * + * ```js + * myBuffer.begin(); + * myFunction(); + * myBuffer.end(); + * ``` + * + * @method draw + * @param {Function} callback function that draws to the framebuffer. + * + * @example + *
        + * + * // Click the canvas to display the framebuffer. + * + * let myBuffer; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.'); + * } + * + * function draw() { + * background(200); + * + * // Draw to the p5.Framebuffer object. + * myBuffer.draw(bagel); + * + * // Display the p5.Framebuffer object while + * // the user presses the mouse. + * if (mouseIsPressed === true) { + * image(myBuffer, -50, -50); + * } + * } + * + * // Draw a rotating, multicolor torus. + * function bagel() { + * background(50); + * rotateY(frameCount * 0.01); + * normalMaterial(); + * torus(30); + * } + * + *
        + */ + + }, + { + key: 'draw', + value: function draw(callback) { + this.begin(); + callback(); + this.end(); + } /** + * Loads the current value of each pixel in the framebuffer into its + * pixels array. + * + * `myBuffer.loadPixels()` must be called before reading from or writing to + * myBuffer.pixels. + * + * @method loadPixels + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create a p5.Framebuffer object. + * let myBuffer = createFramebuffer(); + * + * // Load the pixels array. + * myBuffer.loadPixels(); + * + * // Get the number of pixels in the + * // top half of the framebuffer. + * let numPixels = myBuffer.pixels.length / 2; + * + * // Set the framebuffer's top half to pink. + * for (let i = 0; i < numPixels; i += 4) { + * myBuffer.pixels[i] = 255; + * myBuffer.pixels[i + 1] = 102; + * myBuffer.pixels[i + 2] = 204; + * myBuffer.pixels[i + 3] = 255; + * } + * + * // Update the pixels array. + * myBuffer.updatePixels(); + * + * // Draw the p5.Framebuffer object to the canvas. + * image(myBuffer, -50, -50); + * + * describe('A pink rectangle above a gray rectangle.'); + * } + * + *
        + */ + + }, + { + key: 'loadPixels', + value: function loadPixels() { + var gl = this.gl; + var prevFramebuffer = this.target._renderer.activeFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); + var colorFormat = this._glColorFormat(); + this.pixels = (0, _p2.readPixelsWebGL) (this.pixels, gl, this.framebuffer, 0, 0, this.width * this.density, this.height * this.density, colorFormat.format, colorFormat.type); + if (prevFramebuffer) { + gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer._framebufferToBind()); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } + } /** + * Gets a pixel or a region of pixels from the framebuffer. + * + * `myBuffer.get()` is easy to use but it's not as fast as + * myBuffer.pixels. Use + * myBuffer.pixels to read many pixel + * values. + * + * The version of `myBuffer.get()` with no parameters returns the entire + * framebuffer as a a p5.Image object. + * + * The version of `myBuffer.get()` with two parameters interprets them as + * coordinates. It returns an array with the `[R, G, B, A]` values of the + * pixel at the given point. + * + * The version of `myBuffer.get()` with four parameters interprets them as + * coordinates and dimensions. It returns a subsection of the framebuffer as + * a p5.Image object. The first two parameters are + * the coordinates for the upper-left corner of the subsection. The last two + * parameters are the width and height of the subsection. + * + * @method get + * @param {Number} x x-coordinate of the pixel. Defaults to 0. + * @param {Number} y y-coordinate of the pixel. Defaults to 0. + * @param {Number} w width of the subsection to be returned. + * @param {Number} h height of the subsection to be returned. + * @return {p5.Image} subsection as a p5.Image object. + */ + /** + * @method get + * @return {p5.Image} entire framebuffer as a p5.Image object. + */ + /** + * @method get + * @param {Number} x + * @param {Number} y + * @return {Number[]} color of the pixel at `(x, y)` as an array of color values `[R, G, B, A]`. + */ + + }, + { + key: 'get', + value: function get(x, y, w, h) { + _main.default._validateParameters('p5.Framebuffer.get', arguments); + var colorFormat = this._glColorFormat(); + if (x === undefined && y === undefined) { + x = 0; + y = 0; + w = this.width; + h = this.height; + } else if (w === undefined && h === undefined) { + if (x < 0 || y < 0 || x >= this.width || y >= this.height) { + console.warn('The x and y values passed to p5.Framebuffer.get are outside of its range and will be clamped.'); + x = this.target.constrain(x, 0, this.width - 1); + y = this.target.constrain(y, 0, this.height - 1); + } + return (0, _p2.readPixelWebGL) (this.gl, this.framebuffer, x * this.density, y * this.density, colorFormat.format, colorFormat.type); + } + x = this.target.constrain(x, 0, this.width - 1); + y = this.target.constrain(y, 0, this.height - 1); + w = this.target.constrain(w, 1, this.width - x); + h = this.target.constrain(h, 1, this.height - y); + var rawData = (0, _p2.readPixelsWebGL) (undefined, this.gl, this.framebuffer, x * this.density, y * this.density, w * this.density, h * this.density, colorFormat.format, colorFormat.type); + // Framebuffer data might be either a Uint8Array or Float32Array + // depending on its format, and it may or may not have an alpha channel. + // To turn it into an image, we have to normalize the data into a + // Uint8ClampedArray with alpha. + var fullData = new Uint8ClampedArray(w * h * this.density * this.density * 4); + // Default channels that aren't in the framebuffer (e.g. alpha, if the + // framebuffer is in RGB mode instead of RGBA) to 255 + fullData.fill(255); + var channels = colorFormat.type === this.gl.RGB ? 3 : 4; + for (var _y = 0; _y < h * this.density; _y++) { + for (var _x = 0; _x < w * this.density; _x++) { + for (var channel = 0; channel < 4; channel++) { + var idx = (_y * w * this.density + _x) * 4 + channel; + if (channel < channels) { + // Find the index of this pixel in `rawData`, which might have a + // different number of channels + var rawDataIdx = channels === 4 ? idx : (_y * w * this.density + _x) * channels + channel; + fullData[idx] = rawData[rawDataIdx]; + } + } + } + } // Create an image from the data + + var region = new _main.default.Image(w * this.density, h * this.density); + region.imageData = region.canvas.getContext('2d').createImageData(region.width, region.height); + region.imageData.data.set(fullData); + region.pixels = region.imageData.data; + region.updatePixels(); + if (this.density !== 1) { + // TODO: support get() at a pixel density > 1 + region.resize(w, h); + } + return region; + } /** + * Updates the framebuffer with the RGBA values in the + * pixels array. + * + * `myBuffer.updatePixels()` only needs to be called after changing values + * in the myBuffer.pixels array. Such + * changes can be made directly after calling + * myBuffer.loadPixels(). + * + * @method updatePixels + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create a p5.Framebuffer object. + * let myBuffer = createFramebuffer(); + * + * // Load the pixels array. + * myBuffer.loadPixels(); + * + * // Get the number of pixels in the + * // top half of the framebuffer. + * let numPixels = myBuffer.pixels.length / 2; + * + * // Set the framebuffer's top half to pink. + * for (let i = 0; i < numPixels; i += 4) { + * myBuffer.pixels[i] = 255; + * myBuffer.pixels[i + 1] = 102; + * myBuffer.pixels[i + 2] = 204; + * myBuffer.pixels[i + 3] = 255; + * } + * + * // Update the pixels array. + * myBuffer.updatePixels(); + * + * // Draw the p5.Framebuffer object to the canvas. + * image(myBuffer, -50, -50); + * + * describe('A pink rectangle above a gray rectangle.'); + * } + * + *
        + */ + + }, + { + key: 'updatePixels', + value: function updatePixels() { + var gl = this.gl; + this.colorP5Texture.bindTexture(); + var colorFormat = this._glColorFormat(); + var channels = colorFormat.format === gl.RGBA ? 4 : 3; + var len = this.width * this.height * this.density * this.density * channels; + var TypedArrayClass = colorFormat.type === gl.UNSIGNED_BYTE ? Uint8Array : Float32Array; + if (!(this.pixels instanceof TypedArrayClass) || this.pixels.length !== len) { + throw new Error('The pixels array has not been set correctly. Please call loadPixels() before updatePixels().'); + } + gl.texImage2D(gl.TEXTURE_2D, 0, colorFormat.internalFormat, this.width * this.density, this.height * this.density, 0, colorFormat.format, colorFormat.type, this.pixels); + this.colorP5Texture.unbindTexture(); + var prevFramebuffer = this.target._renderer.activeFramebuffer(); + if (this.antialias) { + // We need to make sure the antialiased framebuffer also has the updated + // pixels so that if more is drawn to it, it goes on top of the updated + // pixels instead of replacing them. + // We can't blit the framebuffer to the multisampled antialias + // framebuffer to leave both in the same state, so instead we have + // to use image() to put the framebuffer texture onto the antialiased + // framebuffer. + this.begin(); + this.target.push(); + this.target.imageMode(this.target.CENTER); + this.target.resetMatrix(); + this.target.noStroke(); + this.target.clear(); + this.target.image(this, 0, 0); + this.target.pop(); + if (this.useDepth) { + gl.clearDepth(1); + gl.clear(gl.DEPTH_BUFFER_BIT); + } + this.end(); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); + if (this.useDepth) { + gl.clearDepth(1); + gl.clear(gl.DEPTH_BUFFER_BIT); + } + if (prevFramebuffer) { + gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer._framebufferToBind()); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } + } + } + } + ]); + return Framebuffer; + }(); + /** + * An object that stores the framebuffer's color data. + * + * Each framebuffer uses a + * WebGLTexture + * object internally to store its color data. The `myBuffer.color` property + * makes it possible to pass this data directly to other functions. For + * example, calling `texture(myBuffer.color)` or + * `myShader.setUniform('colorTexture', myBuffer.color)` may be helpful for + * advanced use cases. + * + * Note: By default, a framebuffer's y-coordinates are flipped compared to + * images and videos. It's easy to flip a framebuffer's y-coordinates as + * needed when applying it as a texture. For example, calling + * `plane(myBuffer.width, -myBuffer.height)` will flip the framebuffer. + * + * @property {p5.FramebufferTexture} color + * @for p5.Framebuffer + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create a p5.Framebuffer object. + * let myBuffer = createFramebuffer(); + * + * // Start drawing to the p5.Framebuffer object. + * myBuffer.begin(); + * + * triangle(-25, 25, 0, -25, 25, 25); + * + * // Stop drawing to the p5.Framebuffer object. + * myBuffer.end(); + * + * // Use the p5.Framebuffer object's WebGLTexture. + * texture(myBuffer.color); + * + * // Style the plane. + * noStroke(); + * + * // Draw the plane. + * plane(myBuffer.width, myBuffer.height); + * + * describe('A white triangle on a gray background.'); + * } + * + *
        + */ + /** + * An object that stores the framebuffer's dpeth data. + * + * Each framebuffer uses a + * WebGLTexture + * object internally to store its depth data. The `myBuffer.depth` property + * makes it possible to pass this data directly to other functions. For + * example, calling `texture(myBuffer.depth)` or + * `myShader.setUniform('depthTexture', myBuffer.depth)` may be helpful for + * advanced use cases. + * + * Note: By default, a framebuffer's y-coordinates are flipped compared to + * images and videos. It's easy to flip a framebuffer's y-coordinates as + * needed when applying it as a texture. For example, calling + * `plane(myBuffer.width, -myBuffer.height)` will flip the framebuffer. + * + * @property {p5.FramebufferTexture} depth + * @for p5.Framebuffer + * + * @example + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * varying vec2 vTexCoord; + * + * void main() { + * vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * viewModelPosition; + * vTexCoord = aTexCoord; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision highp float; + * varying vec2 vTexCoord; + * uniform sampler2D depth; + * + * void main() { + * // Get the pixel's depth value. + * float depthVal = texture2D(depth, vTexCoord).r; + * + * // Set the pixel's color based on its depth. + * gl_FragColor = mix( + * vec4(0., 0., 0., 1.), + * vec4(1., 0., 1., 1.), + * depthVal); + * } + * `; + * + * let myBuffer; + * let myShader; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Framebuffer object. + * myBuffer = createFramebuffer(); + * + * // Create a p5.Shader object. + * myShader = createShader(vertSrc, fragSrc); + * + * // Compile and apply the shader. + * shader(myShader); + * + * describe('The shadow of a box rotates slowly against a magenta background.'); + * } + * + * function draw() { + * // Draw to the p5.Framebuffer object. + * myBuffer.begin(); + * background(255); + * rotateX(frameCount * 0.01); + * box(20, 20, 80); + * myBuffer.end(); + * + * // Set the shader's depth uniform using + * // the framebuffer's depth texture. + * myShader.setUniform('depth', myBuffer.depth); + * + * // Style the plane. + * noStroke(); + * + * // Draw the plane. + * plane(myBuffer.width, myBuffer.height); + * } + * + *
        + */ + _main.default.Framebuffer = Framebuffer; + var _default = Framebuffer; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + './p5.RendererGL': 360, + './p5.Texture': 362, + 'core-js/modules/es.array.fill': 173, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.reflect.get': 208, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.float32-array': 234, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254, + 'core-js/modules/es.typed-array.uint8-array': 257, + 'core-js/modules/es.typed-array.uint8-clamped-array': 258, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 355: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.flat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.unscopables.flat'); + _dereq_('core-js/modules/es.map'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.flat'); + _dereq_('core-js/modules/es.array.for-each'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.unscopables.flat'); + _dereq_('core-js/modules/es.map'); + _dereq_('core-js/modules/es.number.constructor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/web.dom-collections.for-each'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } + function _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; + } /** + * @module Shape + * @submodule 3D Primitives + * @for p5 + * @requires core + * @requires p5.Geometry + */ + //some of the functions are adjusted from Three.js(http://threejs.org) + /** + * A class to describe a 3D shape. + * + * Each `p5.Geometry` object represents a 3D shape as a set of connected + * points called *vertices*. All 3D shapes are made by connecting vertices to + * form triangles that are stitched together. Each triangular patch on the + * geometry's surface is called a *face*. The geometry stores information + * about its vertices and faces for use with effects such as lighting and + * texture mapping. + * + * The first parameter, `detailX`, is optional. If a number is passed, as in + * `new p5.Geometry(24)`, it sets the number of triangle subdivisions to use + * along the geometry's x-axis. By default, `detailX` is 1. + * + * The second parameter, `detailY`, is also optional. If a number is passed, + * as in `new p5.Geometry(24, 16)`, it sets the number of triangle + * subdivisions to use along the geometry's y-axis. By default, `detailX` is + * 1. + * + * The third parameter, `callback`, is also optional. If a function is passed, + * as in `new p5.Geometry(24, 16, createShape)`, it will be called once to add + * vertices to the new 3D shape. + * + * @class p5.Geometry + * @constructor + * @param {Integer} [detailX] number of vertices along the x-axis. + * @param {Integer} [detailY] number of vertices along the y-axis. + * @param {function} [callback] function to call once the geometry is created. + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * myGeometry = new p5.Geometry(); + * + * // Create p5.Vector objects to position the vertices. + * let v0 = createVector(-40, 0, 0); + * let v1 = createVector(0, -40, 0); + * let v2 = createVector(40, 0, 0); + * + * // Add the vertices to the p5.Geometry object's vertices array. + * myGeometry.vertices.push(v0, v1, v2); + * + * describe('A white triangle drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the p5.Geometry object. + * model(myGeometry); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object using a callback function. + * myGeometry = new p5.Geometry(1, 1, createShape); + * + * describe('A white triangle drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the p5.Geometry object. + * model(myGeometry); + * } + * + * function createShape() { + * // Create p5.Vector objects to position the vertices. + * let v0 = createVector(-40, 0, 0); + * let v1 = createVector(0, -40, 0); + * let v2 = createVector(40, 0, 0); + * + * // "this" refers to the p5.Geometry object being created. + * + * // Add the vertices to the p5.Geometry object's vertices array. + * this.vertices.push(v0, v1, v2); + * + * // Add an array to list which vertices belong to the face. + * // Vertices are listed in clockwise "winding" order from + * // left to top to right. + * this.faces.push([0, 1, 2]); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object using a callback function. + * myGeometry = new p5.Geometry(1, 1, createShape); + * + * describe('A white triangle drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the p5.Geometry object. + * model(myGeometry); + * } + * + * function createShape() { + * // Create p5.Vector objects to position the vertices. + * let v0 = createVector(-40, 0, 0); + * let v1 = createVector(0, -40, 0); + * let v2 = createVector(40, 0, 0); + * + * // "this" refers to the p5.Geometry object being created. + * + * // Add the vertices to the p5.Geometry object's vertices array. + * this.vertices.push(v0, v1, v2); + * + * // Add an array to list which vertices belong to the face. + * // Vertices are listed in clockwise "winding" order from + * // left to top to right. + * this.faces.push([0, 1, 2]); + * + * // Compute the surface normals to help with lighting. + * this.computeNormals(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * // Adapted from Paul Wheeler's wonderful p5.Geometry tutorial. + * // https://www.paulwheeler.us/articles/custom-3d-geometry-in-p5js/ + * // CC-BY-SA 4.0 + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create the p5.Geometry object. + * // Set detailX to 48 and detailY to 2. + * // >>> try changing them. + * myGeometry = new p5.Geometry(48, 2, createShape); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the p5.Geometry object. + * strokeWeight(0.2); + * + * // Draw the p5.Geometry object. + * model(myGeometry); + * } + * + * function createShape() { + * // "this" refers to the p5.Geometry object being created. + * + * // Define the Möbius strip with a few parameters. + * let spread = 0.1; + * let radius = 30; + * let stripWidth = 15; + * let xInterval = 4 * PI / this.detailX; + * let yOffset = -stripWidth / 2; + * let yInterval = stripWidth / this.detailY; + * + * for (let j = 0; j <= this.detailY; j += 1) { + * // Calculate the "vertical" point along the strip. + * let v = yOffset + yInterval * j; + * + * for (let i = 0; i <= this.detailX; i += 1) { + * // Calculate the angle of rotation around the strip. + * let u = i * xInterval; + * + * // Calculate the coordinates of the vertex. + * let x = (radius + v * cos(u / 2)) * cos(u) - sin(u / 2) * 2 * spread; + * let y = (radius + v * cos(u / 2)) * sin(u); + * if (u < TWO_PI) { + * y += sin(u) * spread; + * } else { + * y -= sin(u) * spread; + * } + * let z = v * sin(u / 2) + sin(u / 4) * 4 * spread; + * + * // Create a p5.Vector object to position the vertex. + * let vert = createVector(x, y, z); + * + * // Add the vertex to the p5.Geometry object's vertices array. + * this.vertices.push(vert); + * } + * } + * + * // Compute the faces array. + * this.computeFaces(); + * + * // Compute the surface normals to help with lighting. + * this.computeNormals(); + * } + * + *
        + */ + + _main.default.Geometry = /*#__PURE__*/ function () { + function Geometry(detailX, detailY, callback) { + _classCallCheck(this, Geometry); + /** + * An array with the geometry's vertices. + * + * The geometry's vertices are stored as + * p5.Vector objects in the `myGeometry.vertices` + * array. The geometry's first vertex is the + * p5.Vector object at `myGeometry.vertices[0]`, + * its second vertex is `myGeometry.vertices[1]`, its third vertex is + * `myGeometry.vertices[2]`, and so on. + * + * @property vertices + * @name vertices + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * myGeometry = new p5.Geometry(); + * + * // Create p5.Vector objects to position the vertices. + * let v0 = createVector(-40, 0, 0); + * let v1 = createVector(0, -40, 0); + * let v2 = createVector(40, 0, 0); + * + * // Add the vertices to the p5.Geometry object's vertices array. + * myGeometry.vertices.push(v0, v1, v2); + * + * describe('A white triangle drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Draw the p5.Geometry object. + * model(myGeometry); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * beginGeometry(); + * torus(30, 15, 10, 8); + * myGeometry = endGeometry(); + * + * describe('A white torus rotates slowly against a dark gray background. Red spheres mark its vertices.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Rotate the coordinate system. + * rotateY(frameCount * 0.01); + * + * // Style the p5.Geometry object. + * fill(255); + * stroke(0); + * + * // Display the p5.Geometry object. + * model(myGeometry); + * + * // Style the vertices. + * fill(255, 0, 0); + * noStroke(); + * + * // Iterate over the vertices array. + * for (let v of myGeometry.vertices) { + * // Draw a sphere to mark the vertex. + * push(); + * translate(v); + * sphere(2.5); + * pop(); + * } + * } + * + *
        + */ + this.vertices = [ + ]; + this.boundingBoxCache = null; + //an array containing every vertex for stroke drawing + this.lineVertices = new _main.default.DataArray(); + // The tangents going into or out of a vertex on a line. Along a straight + // line segment, both should be equal. At an endpoint, one or the other + // will not exist and will be all 0. In joins between line segments, they + // may be different, as they will be the tangents on either side of the join. + this.lineTangentsIn = new _main.default.DataArray(); + this.lineTangentsOut = new _main.default.DataArray(); + // When drawing lines with thickness, entries in this buffer represent which + // side of the centerline the vertex will be placed. The sign of the number + // will represent the side of the centerline, and the absolute value will be + // used as an enum to determine which part of the cap or join each vertex + // represents. See the doc comments for _addCap and _addJoin for diagrams. + this.lineSides = new _main.default.DataArray(); + /** + * An array with the vectors that are normal to the geometry's vertices. + * + * A face's orientation is defined by its *normal vector* which points out + * of the face and is normal (perpendicular) to the surface. Calling + * `myGeometry.computeNormals()` first calculates each face's normal + * vector. Then it calculates the normal vector for each vertex by + * averaging the normal vectors of the faces surrounding the vertex. The + * vertex normals are stored as p5.Vector + * objects in the `myGeometry.vertexNormals` array. + * + * @property vertexNormals + * @name vertexNormals + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * beginGeometry(); + * torus(30, 15, 10, 8); + * myGeometry = endGeometry(); + * + * // Compute the vertex normals. + * myGeometry.computeNormals(); + * + * describe( + * 'A white torus rotates against a dark gray background. Red lines extend outward from its vertices.' + * ); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Rotate the coordinate system. + * rotateY(frameCount * 0.01); + * + * // Style the p5.Geometry object. + * stroke(0); + * + * // Display the p5.Geometry object. + * model(myGeometry); + * + * // Style the normal vectors. + * stroke(255, 0, 0); + * + * // Iterate over the vertices and vertexNormals arrays. + * for (let i = 0; i < myGeometry.vertices.length; i += 1) { + * + * // Get the vertex p5.Vector object. + * let v = myGeometry.vertices[i]; + * + * // Get the vertex normal p5.Vector object. + * let n = myGeometry.vertexNormals[i]; + * + * // Calculate a point along the vertex normal. + * let p = p5.Vector.mult(n, 8); + * + * // Draw the vertex normal as a red line. + * push(); + * translate(v); + * line(0, 0, 0, p.x, p.y, p.z); + * pop(); + * } + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * myGeometry = new p5.Geometry(); + * + * // Create p5.Vector objects to position the vertices. + * let v0 = createVector(-40, 0, 0); + * let v1 = createVector(0, -40, 0); + * let v2 = createVector(0, 40, 0); + * let v3 = createVector(40, 0, 0); + * + * // Add the vertices to the p5.Geometry object's vertices array. + * myGeometry.vertices.push(v0, v1, v2, v3); + * + * // Compute the faces array. + * myGeometry.computeFaces(); + * + * // Compute the surface normals. + * myGeometry.computeNormals(); + * + * describe('A red square drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a white point light. + * pointLight(255, 255, 255, 0, 0, 10); + * + * // Style the p5.Geometry object. + * noStroke(); + * fill(255, 0, 0); + * + * // Display the p5.Geometry object. + * model(myGeometry); + * } + * + *
        + */ + this.vertexNormals = [ + ]; + /** + * An array that lists which of the geometry's vertices form each of its + * faces. + * + * All 3D shapes are made by connecting sets of points called *vertices*. A + * geometry's surface is formed by connecting vertices to form triangles + * that are stitched together. Each triangular patch on the geometry's + * surface is called a *face*. + * + * The geometry's vertices are stored as + * p5.Vector objects in the + * myGeometry.vertices array. The + * geometry's first vertex is the p5.Vector + * object at `myGeometry.vertices[0]`, its second vertex is + * `myGeometry.vertices[1]`, its third vertex is `myGeometry.vertices[2]`, + * and so on. + * + * For example, a geometry made from a rectangle has two faces because a + * rectangle is made by joining two triangles. `myGeometry.faces` for a + * rectangle would be the two-dimensional array `[[0, 1, 2], [2, 1, 3]]`. + * The first face, `myGeometry.faces[0]`, is the array `[0, 1, 2]` because + * it's formed by connecting `myGeometry.vertices[0]`, + * `myGeometry.vertices[1]`,and `myGeometry.vertices[2]`. The second face, + * `myGeometry.faces[1]`, is the array `[2, 1, 3]` because it's formed by + * connecting `myGeometry.vertices[2]`, `myGeometry.vertices[1]`,and + * `myGeometry.vertices[3]`. + * + * @property faces + * @name faces + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * beginGeometry(); + * sphere(); + * myGeometry = endGeometry(); + * + * describe("A sphere drawn on a gray background. The sphere's surface is a grayscale patchwork of triangles."); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the p5.Geometry object. + * noStroke(); + * + * // Set a random seed. + * randomSeed(1234); + * + * // Iterate over the faces array. + * for (let face of myGeometry.faces) { + * + * // Style the face. + * let g = random(0, 255); + * fill(g); + * + * // Draw the face. + * beginShape(); + * // Iterate over the vertices that form the face. + * for (let f of face) { + * // Get the vertex's p5.Vector object. + * let v = myGeometry.vertices[f]; + * vertex(v.x, v.y, v.z); + * } + * endShape(); + * + * } + * } + * + *
        + */ + this.faces = [ + ]; + /** + * An array that lists the texture coordinates for each of the geometry's + * vertices. + * + * In order for texture() to work, the geometry + * needs a way to map the points on its surface to the pixels in a + * rectangular image that's used as a texture. The geometry's vertex at + * coordinates `(x, y, z)` maps to the texture image's pixel at coordinates + * `(u, v)`. + * + * The `myGeometry.uvs` array stores the `(u, v)` coordinates for each + * vertex in the order it was added to the geometry. For example, the + * first vertex, `myGeometry.vertices[0]`, has its `(u, v)` coordinates + * stored at `myGeometry.uvs[0]` and `myGeometry.uvs[1]`. + * + * @property uvs + * @name uvs + * + * @example + *
        + * + * let img; + * + * // Load the image and create a p5.Image object. + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create p5.Geometry objects. + * let geom1 = buildGeometry(createShape); + * let geom2 = buildGeometry(createShape); + * + * // Left (original). + * push(); + * translate(-25, 0, 0); + * texture(img); + * noStroke(); + * model(geom1); + * pop(); + * + * // Set geom2's texture coordinates. + * geom2.uvs = [0.25, 0.25, 0.75, 0.25, 0.25, 0.75, 0.75, 0.75]; + * + * // Right (zoomed in). + * push(); + * translate(25, 0, 0); + * texture(img); + * noStroke(); + * model(geom2); + * pop(); + * + * describe( + * 'Two photos of a ceiling on a gray background. The photo on the right zooms in to the center of the photo.' + * ); + * } + * + * function createShape() { + * plane(40); + * } + * + *
        + */ + this.uvs = [ + ]; + // a 2D array containing edge connectivity pattern for create line vertices + //based on faces for most objects; + this.edges = [ + ]; + this.vertexColors = [ + ]; + // One color per vertex representing the stroke color at that vertex + this.vertexStrokeColors = [ + ]; + // One color per line vertex, generated automatically based on + // vertexStrokeColors in _edgesToVertices() + this.lineVertexColors = new _main.default.DataArray(); + this.detailX = detailX !== undefined ? detailX : 1; + this.detailY = detailY !== undefined ? detailY : 1; + this.dirtyFlags = { + }; + this._hasFillTransparency = undefined; + this._hasStrokeTransparency = undefined; + if (callback instanceof Function) { + callback.call(this); + } + } /** + * Calculates the position and size of the smallest box that contains the geometry. + * + * A bounding box is the smallest rectangular prism that contains the entire + * geometry. It's defined by the box's minimum and maximum coordinates along + * each axis, as well as the size (length) and offset (center). + * + * Calling `myGeometry.calculateBoundingBox()` returns an object with four + * properties that describe the bounding box: + * + * ```js + * // Get myGeometry's bounding box. + * let bbox = myGeometry.calculateBoundingBox(); + * + * // Print the bounding box to the console. + * console.log(bbox); + * + * // { + * // // The minimum coordinate along each axis. + * // min: { x: -1, y: -2, z: -3 }, + * // + * // // The maximum coordinate along each axis. + * // max: { x: 1, y: 2, z: 3}, + * // + * // // The size (length) along each axis. + * // size: { x: 2, y: 4, z: 6}, + * // + * // // The offset (center) along each axis. + * // offset: { x: 0, y: 0, z: 0} + * // } + * ``` + * + * @method calculateBoundingBox + * @returns {Object} bounding box of the geometry. + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let particles; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a new p5.Geometry object with random spheres. + * particles = buildGeometry(createParticles); + * + * describe('Ten white spheres placed randomly against a gray background. A box encloses the spheres.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the particles. + * noStroke(); + * fill(255); + * + * // Draw the particles. + * model(particles); + * + * // Calculate the bounding box. + * let bbox = particles.calculateBoundingBox(); + * + * // Translate to the bounding box's center. + * translate(bbox.offset.x, bbox.offset.y, bbox.offset.z); + * + * // Style the bounding box. + * stroke(255); + * noFill(); + * + * // Draw the bounding box. + * box(bbox.size.x, bbox.size.y, bbox.size.z); + * } + * + * function createParticles() { + * for (let i = 0; i < 10; i += 1) { + * // Calculate random coordinates. + * let x = randomGaussian(0, 15); + * let y = randomGaussian(0, 15); + * let z = randomGaussian(0, 15); + * + * push(); + * // Translate to the particle's coordinates. + * translate(x, y, z); + * // Draw the particle. + * sphere(3); + * pop(); + * } + * } + * + *
        + */ + + _createClass(Geometry, [ + { + key: 'calculateBoundingBox', + value: function calculateBoundingBox() { + if (this.boundingBoxCache) { + return this.boundingBoxCache; // Return cached result if available + } + var minVertex = new _main.default.Vector(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + var maxVertex = new _main.default.Vector(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE); + for (var i = 0; i < this.vertices.length; i++) { + var vertex = this.vertices[i]; + minVertex.x = Math.min(minVertex.x, vertex.x); + minVertex.y = Math.min(minVertex.y, vertex.y); + minVertex.z = Math.min(minVertex.z, vertex.z); + maxVertex.x = Math.max(maxVertex.x, vertex.x); + maxVertex.y = Math.max(maxVertex.y, vertex.y); + maxVertex.z = Math.max(maxVertex.z, vertex.z); + } // Calculate size and offset properties + + var size = new _main.default.Vector(maxVertex.x - minVertex.x, maxVertex.y - minVertex.y, maxVertex.z - minVertex.z); + var offset = new _main.default.Vector((minVertex.x + maxVertex.x) / 2, (minVertex.y + maxVertex.y) / 2, (minVertex.z + maxVertex.z) / 2); + // Cache the result for future access + this.boundingBoxCache = { + min: minVertex, + max: maxVertex, + size: size, + offset: offset + }; + return this.boundingBoxCache; + } + }, + { + key: 'reset', + value: function reset() { + this._hasFillTransparency = undefined; + this._hasStrokeTransparency = undefined; + this.lineVertices.clear(); + this.lineTangentsIn.clear(); + this.lineTangentsOut.clear(); + this.lineSides.clear(); + this.vertices.length = 0; + this.edges.length = 0; + this.vertexColors.length = 0; + this.vertexStrokeColors.length = 0; + this.lineVertexColors.clear(); + this.vertexNormals.length = 0; + this.uvs.length = 0; + this.dirtyFlags = { + }; + } + }, + { + key: 'hasFillTransparency', + value: function hasFillTransparency() { + if (this._hasFillTransparency === undefined) { + this._hasFillTransparency = false; + for (var i = 0; i < this.vertexColors.length; i += 4) { + if (this.vertexColors[i + 3] < 1) { + this._hasFillTransparency = true; + break; + } + } + } + return this._hasFillTransparency; + } + }, + { + key: 'hasStrokeTransparency', + value: function hasStrokeTransparency() { + if (this._hasStrokeTransparency === undefined) { + this._hasStrokeTransparency = false; + for (var i = 0; i < this.lineVertexColors.length; i += 4) { + if (this.lineVertexColors[i + 3] < 1) { + this._hasStrokeTransparency = true; + break; + } + } + } + return this._hasStrokeTransparency; + } /** + * Removes the geometry’s internal colors. + * + * `p5.Geometry` objects can be created with "internal colors" assigned to + * vertices or the entire shape. When a geometry has internal colors, + * fill() has no effect. Calling + * `myGeometry.clearColors()` allows the + * fill() function to apply color to the geometry. + * + * @method clearColors + * + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create a p5.Geometry object. + * // Set its internal color to red. + * beginGeometry(); + * fill(255, 0, 0); + * plane(20); + * let myGeometry = endGeometry(); + * + * // Style the shape. + * noStroke(); + * + * // Draw the p5.Geometry object (center). + * model(myGeometry); + * + * // Translate the origin to the bottom-right. + * translate(25, 25, 0); + * + * // Try to fill the geometry with green. + * fill(0, 255, 0); + * + * // Draw the geometry again (bottom-right). + * model(myGeometry); + * + * // Clear the geometry's colors. + * myGeometry.clearColors(); + * + * // Fill the geometry with blue. + * fill(0, 0, 255); + * + * // Translate the origin up. + * translate(0, -50, 0); + * + * // Draw the geometry again (top-right). + * model(myGeometry); + * + * describe( + * 'Three squares drawn against a gray background. Red squares are at the center and the bottom-right. A blue square is at the top-right.' + * ); + * } + * + *
        + */ + + }, + { + key: 'clearColors', + value: function clearColors() { + this.vertexColors = [ + ]; + return this; + } /** + * Flips the geometry’s texture u-coordinates. + * + * In order for texture() to work, the geometry + * needs a way to map the points on its surface to the pixels in a rectangular + * image that's used as a texture. The geometry's vertex at coordinates + * `(x, y, z)` maps to the texture image's pixel at coordinates `(u, v)`. + * + * The myGeometry.uvs array stores the + * `(u, v)` coordinates for each vertex in the order it was added to the + * geometry. Calling `myGeometry.flipU()` flips a geometry's u-coordinates + * so that the texture appears mirrored horizontally. + * + * For example, a plane's four vertices are added clockwise starting from the + * top-left corner. Here's how calling `myGeometry.flipU()` would change a + * plane's texture coordinates: + * + * ```js + * // Print the original texture coordinates. + * // Output: [0, 0, 1, 0, 0, 1, 1, 1] + * console.log(myGeometry.uvs); + * + * // Flip the u-coordinates. + * myGeometry.flipU(); + * + * // Print the flipped texture coordinates. + * // Output: [1, 0, 0, 0, 1, 1, 0, 1] + * console.log(myGeometry.uvs); + * + * // Notice the swaps: + * // Top vertices: [0, 0, 1, 0] --> [1, 0, 0, 0] + * // Bottom vertices: [0, 1, 1, 1] --> [1, 1, 0, 1] + * ``` + * + * @method flipU + * @for p5.Geometry + * + * @example + *
        + * + * let img; + * + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create p5.Geometry objects. + * let geom1 = buildGeometry(createShape); + * let geom2 = buildGeometry(createShape); + * + * // Flip geom2's U texture coordinates. + * geom2.flipU(); + * + * // Left (original). + * push(); + * translate(-25, 0, 0); + * texture(img); + * noStroke(); + * model(geom1); + * pop(); + * + * // Right (flipped). + * push(); + * translate(25, 0, 0); + * texture(img); + * noStroke(); + * model(geom2); + * pop(); + * + * describe( + * 'Two photos of a ceiling on a gray background. The photos are mirror images of each other.' + * ); + * } + * + * function createShape() { + * plane(40); + * } + * + *
        + */ + + }, + { + key: 'flipU', + value: function flipU() { + this.uvs = this.uvs.flat().map(function (val, index) { + if (index % 2 === 0) { + return 1 - val; + } else { + return val; + } + }); + } /** + * Flips the geometry’s texture v-coordinates. + * + * In order for texture() to work, the geometry + * needs a way to map the points on its surface to the pixels in a rectangular + * image that's used as a texture. The geometry's vertex at coordinates + * `(x, y, z)` maps to the texture image's pixel at coordinates `(u, v)`. + * + * The myGeometry.uvs array stores the + * `(u, v)` coordinates for each vertex in the order it was added to the + * geometry. Calling `myGeometry.flipV()` flips a geometry's v-coordinates + * so that the texture appears mirrored vertically. + * + * For example, a plane's four vertices are added clockwise starting from the + * top-left corner. Here's how calling `myGeometry.flipV()` would change a + * plane's texture coordinates: + * + * ```js + * // Print the original texture coordinates. + * // Output: [0, 0, 1, 0, 0, 1, 1, 1] + * console.log(myGeometry.uvs); + * + * // Flip the v-coordinates. + * myGeometry.flipV(); + * + * // Print the flipped texture coordinates. + * // Output: [0, 1, 1, 1, 0, 0, 1, 0] + * console.log(myGeometry.uvs); + * + * // Notice the swaps: + * // Left vertices: [0, 0] <--> [1, 0] + * // Right vertices: [1, 0] <--> [1, 1] + * ``` + * + * @method flipV + * @for p5.Geometry + * + * @example + *
        + * + * let img; + * + * function preload() { + * img = loadImage('assets/laDefense.jpg'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create p5.Geometry objects. + * let geom1 = buildGeometry(createShape); + * let geom2 = buildGeometry(createShape); + * + * // Flip geom2's V texture coordinates. + * geom2.flipV(); + * + * // Left (original). + * push(); + * translate(-25, 0, 0); + * texture(img); + * noStroke(); + * model(geom1); + * pop(); + * + * // Right (flipped). + * push(); + * translate(25, 0, 0); + * texture(img); + * noStroke(); + * model(geom2); + * pop(); + * + * describe( + * 'Two photos of a ceiling on a gray background. The photos are mirror images of each other.' + * ); + * } + * + * function createShape() { + * plane(40); + * } + * + *
        + */ + + }, + { + key: 'flipV', + value: function flipV() { + this.uvs = this.uvs.flat().map(function (val, index) { + if (index % 2 === 0) { + return val; + } else { + return 1 - val; + } + }); + } /** + * Computes the geometry's faces using its vertices. + * + * All 3D shapes are made by connecting sets of points called *vertices*. A + * geometry's surface is formed by connecting vertices to form triangles that + * are stitched together. Each triangular patch on the geometry's surface is + * called a *face*. `myGeometry.computeFaces()` performs the math needed to + * define each face based on the distances between vertices. + * + * The geometry's vertices are stored as p5.Vector + * objects in the myGeometry.vertices + * array. The geometry's first vertex is the + * p5.Vector object at `myGeometry.vertices[0]`, + * its second vertex is `myGeometry.vertices[1]`, its third vertex is + * `myGeometry.vertices[2]`, and so on. + * + * Calling `myGeometry.computeFaces()` fills the + * myGeometry.faces array with three-element + * arrays that list the vertices that form each face. For example, a geometry + * made from a rectangle has two faces because a rectangle is made by joining + * two triangles. myGeometry.faces for a + * rectangle would be the two-dimensional array + * `[[0, 1, 2], [2, 1, 3]]`. The first face, `myGeometry.faces[0]`, is the + * array `[0, 1, 2]` because it's formed by connecting + * `myGeometry.vertices[0]`, `myGeometry.vertices[1]`,and + * `myGeometry.vertices[2]`. The second face, `myGeometry.faces[1]`, is the + * array `[2, 1, 3]` because it's formed by connecting + * `myGeometry.vertices[2]`, `myGeometry.vertices[1]`, and + * `myGeometry.vertices[3]`. + * + * Note: `myGeometry.computeFaces()` only works when geometries have four or more vertices. + * + * @method computeFaces + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * myGeometry = new p5.Geometry(); + * + * // Create p5.Vector objects to position the vertices. + * let v0 = createVector(-40, 0, 0); + * let v1 = createVector(0, -40, 0); + * let v2 = createVector(0, 40, 0); + * let v3 = createVector(40, 0, 0); + * + * // Add the vertices to myGeometry's vertices array. + * myGeometry.vertices.push(v0, v1, v2, v3); + * + * // Compute myGeometry's faces array. + * myGeometry.computeFaces(); + * + * describe('A red square drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the shape. + * noStroke(); + * fill(255, 0, 0); + * + * // Draw the p5.Geometry object. + * model(myGeometry); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object using a callback function. + * myGeometry = new p5.Geometry(1, 1, createShape); + * + * describe('A red square drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Style the shape. + * noStroke(); + * fill(255, 0, 0); + * + * // Draw the p5.Geometry object. + * model(myGeometry); + * } + * + * function createShape() { + * // Create p5.Vector objects to position the vertices. + * let v0 = createVector(-40, 0, 0); + * let v1 = createVector(0, -40, 0); + * let v2 = createVector(0, 40, 0); + * let v3 = createVector(40, 0, 0); + * + * // Add the vertices to the p5.Geometry object's vertices array. + * this.vertices.push(v0, v1, v2, v3); + * + * // Compute the faces array. + * this.computeFaces(); + * } + * + *
        + */ + + }, + { + key: 'computeFaces', + value: function computeFaces() { + this.faces.length = 0; + var sliceCount = this.detailX + 1; + var a, + b, + c, + d; + for (var i = 0; i < this.detailY; i++) { + for (var j = 0; j < this.detailX; j++) { + a = i * sliceCount + j; // + offset; + b = i * sliceCount + j + 1; // + offset; + c = (i + 1) * sliceCount + j + 1; // + offset; + d = (i + 1) * sliceCount + j; // + offset; + this.faces.push([a, + b, + d]); + this.faces.push([d, + b, + c]); + } + } + return this; + } + }, + { + key: '_getFaceNormal', + value: function _getFaceNormal(faceId) { + //This assumes that vA->vB->vC is a counter-clockwise ordering + var face = this.faces[faceId]; + var vA = this.vertices[face[0]]; + var vB = this.vertices[face[1]]; + var vC = this.vertices[face[2]]; + var ab = _main.default.Vector.sub(vB, vA); + var ac = _main.default.Vector.sub(vC, vA); + var n = _main.default.Vector.cross(ab, ac); + var ln = _main.default.Vector.mag(n); + var sinAlpha = ln / (_main.default.Vector.mag(ab) * _main.default.Vector.mag(ac)); + if (sinAlpha === 0 || isNaN(sinAlpha)) { + console.warn('p5.Geometry.prototype._getFaceNormal:', 'face has colinear sides or a repeated vertex'); + return n; + } + if (sinAlpha > 1) sinAlpha = 1; // handle float rounding error + return n.mult(Math.asin(sinAlpha) / ln); + } /** + * Calculates the normal vector for each vertex on the geometry. + * + * All 3D shapes are made by connecting sets of points called *vertices*. A + * geometry's surface is formed by connecting vertices to create triangles + * that are stitched together. Each triangular patch on the geometry's + * surface is called a *face*. `myGeometry.computeNormals()` performs the + * math needed to orient each face. Orientation is important for lighting + * and other effects. + * + * A face's orientation is defined by its *normal vector* which points out + * of the face and is normal (perpendicular) to the surface. Calling + * `myGeometry.computeNormals()` first calculates each face's normal vector. + * Then it calculates the normal vector for each vertex by averaging the + * normal vectors of the faces surrounding the vertex. The vertex normals + * are stored as p5.Vector objects in the + * myGeometry.vertexNormals array. + * + * The first parameter, `shadingType`, is optional. Passing the constant + * `FLAT`, as in `myGeometry.computeNormals(FLAT)`, provides neighboring + * faces with their own copies of the vertices they share. Surfaces appear + * tiled with flat shading. Passing the constant `SMOOTH`, as in + * `myGeometry.computeNormals(SMOOTH)`, makes neighboring faces reuse their + * shared vertices. Surfaces appear smoother with smooth shading. By + * default, `shadingType` is `FLAT`. + * + * The second parameter, `options`, is also optional. If an object with a + * `roundToPrecision` property is passed, as in + * `myGeometry.computeNormals(SMOOTH, { roundToPrecision: 5 })`, it sets the + * number of decimal places to use for calculations. By default, + * `roundToPrecision` uses 3 decimal places. + * + * @method computeNormals + * @param {String} [shadingType] shading type. either FLAT or SMOOTH. Defaults to `FLAT`. + * @param {Object} [options] shading options. + * @chainable + * + * @example + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * beginGeometry(); + * torus(); + * myGeometry = endGeometry(); + * + * // Compute the vertex normals. + * myGeometry.computeNormals(); + * + * describe( + * "A white torus drawn on a dark gray background. Red lines extend outward from the torus' vertices." + * ); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Rotate the coordinate system. + * rotateX(1); + * + * // Style the helix. + * stroke(0); + * + * // Display the helix. + * model(myGeometry); + * + * // Style the normal vectors. + * stroke(255, 0, 0); + * + * // Iterate over the vertices and vertexNormals arrays. + * for (let i = 0; i < myGeometry.vertices.length; i += 1) { + * + * // Get the vertex p5.Vector object. + * let v = myGeometry.vertices[i]; + * + * // Get the vertex normal p5.Vector object. + * let n = myGeometry.vertexNormals[i]; + * + * // Calculate a point along the vertex normal. + * let p = p5.Vector.mult(n, 5); + * + * // Draw the vertex normal as a red line. + * push(); + * translate(v); + * line(0, 0, 0, p.x, p.y, p.z); + * pop(); + * } + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object using a callback function. + * myGeometry = new p5.Geometry(); + * + * // Create p5.Vector objects to position the vertices. + * let v0 = createVector(-40, 0, 0); + * let v1 = createVector(0, -40, 0); + * let v2 = createVector(0, 40, 0); + * let v3 = createVector(40, 0, 0); + * + * // Add the vertices to the p5.Geometry object's vertices array. + * myGeometry.vertices.push(v0, v1, v2, v3); + * + * // Compute the faces array. + * myGeometry.computeFaces(); + * + * // Compute the surface normals. + * myGeometry.computeNormals(); + * + * describe('A red square drawn on a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Add a white point light. + * pointLight(255, 255, 255, 0, 0, 10); + * + * // Style the p5.Geometry object. + * noStroke(); + * fill(255, 0, 0); + * + * // Draw the p5.Geometry object. + * model(myGeometry); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * myGeometry = buildGeometry(createShape); + * + * // Compute normals using default (FLAT) shading. + * myGeometry.computeNormals(FLAT); + * + * describe('A white, helical structure drawn on a dark gray background. Its faces appear faceted.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Rotate the coordinate system. + * rotateX(1); + * + * // Style the helix. + * noStroke(); + * + * // Display the helix. + * model(myGeometry); + * } + * + * function createShape() { + * // Create a helical shape. + * beginShape(); + * for (let i = 0; i < TWO_PI * 3; i += 0.5) { + * let x = 30 * cos(i); + * let y = 30 * sin(i); + * let z = map(i, 0, TWO_PI * 3, -40, 40); + * vertex(x, y, z); + * } + * endShape(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * myGeometry = buildGeometry(createShape); + * + * // Compute normals using smooth shading. + * myGeometry.computeNormals(SMOOTH); + * + * describe('A white, helical structure drawn on a dark gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Rotate the coordinate system. + * rotateX(1); + * + * // Style the helix. + * noStroke(); + * + * // Display the helix. + * model(myGeometry); + * } + * + * function createShape() { + * // Create a helical shape. + * beginShape(); + * for (let i = 0; i < TWO_PI * 3; i += 0.5) { + * let x = 30 * cos(i); + * let y = 30 * sin(i); + * let z = map(i, 0, TWO_PI * 3, -40, 40); + * vertex(x, y, z); + * } + * endShape(); + * } + * + *
        + * + *
        + * + * // Click and drag the mouse to view the scene from different angles. + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Geometry object. + * myGeometry = buildGeometry(createShape); + * + * // Create an options object. + * let options = { roundToPrecision: 5 }; + * + * // Compute normals using smooth shading. + * myGeometry.computeNormals(SMOOTH, options); + * + * describe('A white, helical structure drawn on a dark gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Enable orbiting with the mouse. + * orbitControl(); + * + * // Turn on the lights. + * lights(); + * + * // Rotate the coordinate system. + * rotateX(1); + * + * // Style the helix. + * noStroke(); + * + * // Display the helix. + * model(myGeometry); + * } + * + * function createShape() { + * // Create a helical shape. + * beginShape(); + * for (let i = 0; i < TWO_PI * 3; i += 0.5) { + * let x = 30 * cos(i); + * let y = 30 * sin(i); + * let z = map(i, 0, TWO_PI * 3, -40, 40); + * vertex(x, y, z); + * } + * endShape(); + * } + * + *
        + */ + + }, + { + key: 'computeNormals', + value: function computeNormals() { + var _this = this; + var shadingType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : constants.FLAT; + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + }, + _ref$roundToPrecision = _ref.roundToPrecision, + roundToPrecision = _ref$roundToPrecision === void 0 ? 3 : _ref$roundToPrecision; + var vertexNormals = this.vertexNormals; + var vertices = this.vertices; + var faces = this.faces; + var iv; + if (shadingType === constants.SMOOTH) { + var vertexIndices = { + }; + var uniqueVertices = [ + ]; + var power = Math.pow(10, roundToPrecision); + var rounded = function rounded(val) { + return Math.round(val * power) / power; + }; + var getKey = function getKey(vert) { + return ''.concat(rounded(vert.x), ',').concat(rounded(vert.y), ',').concat(rounded(vert.z)); + }; + // loop through each vertex and add uniqueVertices + for (var i = 0; i < vertices.length; i++) { + var vertex = vertices[i]; + var key = getKey(vertex); + if (vertexIndices[key] === undefined) { + vertexIndices[key] = uniqueVertices.length; + uniqueVertices.push(vertex); + } + } // update face indices to use the deduplicated vertex indices + + faces.forEach(function (face) { + for (var fv = 0; fv < 3; ++fv) { + var originalVertexIndex = face[fv]; + var originalVertex = vertices[originalVertexIndex]; + var _key = getKey(originalVertex); + face[fv] = vertexIndices[_key]; + } + }); + // update edge indices to use the deduplicated vertex indices + this.edges.forEach(function (edge) { + for (var ev = 0; ev < 2; ++ev) { + var originalVertexIndex = edge[ev]; + var originalVertex = vertices[originalVertexIndex]; + var _key2 = getKey(originalVertex); + edge[ev] = vertexIndices[_key2]; + } + }); + // update the deduplicated vertices + this.vertices = vertices = uniqueVertices; + } // initialize the vertexNormals array with empty vectors + + vertexNormals.length = 0; + for (iv = 0; iv < vertices.length; ++iv) { + vertexNormals.push(new _main.default.Vector()); + } // loop through all the faces adding its normal to the normal + // of each of its vertices + + faces.forEach(function (face, f) { + var faceNormal = _this._getFaceNormal(f); + // all three vertices get the normal added + for (var fv = 0; fv < 3; ++fv) { + var vertexIndex = face[fv]; + vertexNormals[vertexIndex].add(faceNormal); + } + }); + // normalize the normals + for (iv = 0; iv < vertices.length; ++iv) { + vertexNormals[iv].normalize(); + } + return this; + } /** + * Averages the vertex normals. Used in curved + * surfaces + * @private + * @chainable + */ + + }, + { + key: 'averageNormals', + value: function averageNormals() { + for (var i = 0; i <= this.detailY; i++) { + var offset = this.detailX + 1; + var temp = _main.default.Vector.add(this.vertexNormals[i * offset], this.vertexNormals[i * offset + this.detailX]); + temp = _main.default.Vector.div(temp, 2); + this.vertexNormals[i * offset] = temp; + this.vertexNormals[i * offset + this.detailX] = temp; + } + return this; + } /** + * Averages pole normals. Used in spherical primitives + * @private + * @chainable + */ + + }, + { + key: 'averagePoleNormals', + value: function averagePoleNormals() { + //average the north pole + var sum = new _main.default.Vector(0, 0, 0); + for (var i = 0; i < this.detailX; i++) { + sum.add(this.vertexNormals[i]); + } + sum = _main.default.Vector.div(sum, this.detailX); + for (var _i = 0; _i < this.detailX; _i++) { + this.vertexNormals[_i] = sum; + } //average the south pole + + sum = new _main.default.Vector(0, 0, 0); + for (var _i2 = this.vertices.length - 1; _i2 > this.vertices.length - 1 - this.detailX; _i2--) { + sum.add(this.vertexNormals[_i2]); + } + sum = _main.default.Vector.div(sum, this.detailX); + for (var _i3 = this.vertices.length - 1; _i3 > this.vertices.length - 1 - this.detailX; _i3--) { + this.vertexNormals[_i3] = sum; + } + return this; + } /** + * Create a 2D array for establishing stroke connections + * @private + * @chainable + */ + + }, + { + key: '_makeTriangleEdges', + value: function _makeTriangleEdges() { + this.edges.length = 0; + for (var j = 0; j < this.faces.length; j++) { + this.edges.push([this.faces[j][0], + this.faces[j][1]]); + this.edges.push([this.faces[j][1], + this.faces[j][2]]); + this.edges.push([this.faces[j][2], + this.faces[j][0]]); + } + return this; + } /** + * Converts each line segment into the vertices and vertex attributes needed + * to turn the line into a polygon on screen. This will include: + * - Two triangles line segment to create a rectangle + * - Two triangles per endpoint to create a stroke cap rectangle. A fragment + * shader is responsible for displaying the appropriate cap style within + * that rectangle. + * - Four triangles per join between adjacent line segments, creating a quad on + * either side of the join, perpendicular to the lines. A vertex shader will + * discard the quad in the "elbow" of the join, and a fragment shader will + * display the appropriate join style within the remaining quad. + * + * @private + * @chainable + */ + + }, + { + key: '_edgesToVertices', + value: function _edgesToVertices() { + this.lineVertices.clear(); + this.lineTangentsIn.clear(); + this.lineTangentsOut.clear(); + this.lineSides.clear(); + var potentialCaps = new Map(); + var connected = new Set(); + var lastValidDir; + for (var i = 0; i < this.edges.length; i++) { + var prevEdge = this.edges[i - 1]; + var currEdge = this.edges[i]; + var begin = this.vertices[currEdge[0]]; + var end = this.vertices[currEdge[1]]; + var fromColor = this.vertexStrokeColors.length > 0 ? this.vertexStrokeColors.slice(currEdge[0] * 4, (currEdge[0] + 1) * 4) : [ + 0, + 0, + 0, + 0 + ]; + var toColor = this.vertexStrokeColors.length > 0 ? this.vertexStrokeColors.slice(currEdge[1] * 4, (currEdge[1] + 1) * 4) : [ + 0, + 0, + 0, + 0 + ]; + var dir = end.copy().sub(begin).normalize(); + var dirOK = dir.magSq() > 0; + if (dirOK) { + this._addSegment(begin, end, fromColor, toColor, dir); + } + if (i > 0 && prevEdge[1] === currEdge[0]) { + if (!connected.has(currEdge[0])) { + connected.add(currEdge[0]); + potentialCaps.delete(currEdge[0]); + // Add a join if this segment shares a vertex with the previous. Skip + // actually adding join vertices if either the previous segment or this + // one has a length of 0. + // + // Don't add a join if the tangents point in the same direction, which + // would mean the edges line up exactly, and there is no need for a join. + if (lastValidDir && dirOK && dir.dot(lastValidDir) < 1 - 1e-8) { + this._addJoin(begin, lastValidDir, dir, fromColor); + } + } + } else { + // Start a new line + if (dirOK && !connected.has(currEdge[0])) { + var existingCap = potentialCaps.get(currEdge[0]); + if (existingCap) { + this._addJoin(begin, existingCap.dir, dir, fromColor); + potentialCaps.delete(currEdge[0]); + connected.add(currEdge[0]); + } else { + potentialCaps.set(currEdge[0], { + point: begin, + dir: dir.copy().mult( - 1), + color: fromColor + }); + } + } + if (lastValidDir && !connected.has(prevEdge[1])) { + var _existingCap = potentialCaps.get(prevEdge[1]); + if (_existingCap) { + this._addJoin(this.vertices[prevEdge[1]], lastValidDir, _existingCap.dir.copy().mult( - 1), fromColor); + potentialCaps.delete(prevEdge[1]); + connected.add(prevEdge[1]); + } else { + // Close off the last segment with a cap + potentialCaps.set(prevEdge[1], { + point: this.vertices[prevEdge[1]], + dir: lastValidDir, + color: fromColor + }); + } + lastValidDir = undefined; + } + } + if (i === this.edges.length - 1 && !connected.has(currEdge[1])) { + var _existingCap2 = potentialCaps.get(currEdge[1]); + if (_existingCap2) { + this._addJoin(end, dir, _existingCap2.dir.copy().mult( - 1), toColor); + potentialCaps.delete(currEdge[1]); + connected.add(currEdge[1]); + } else { + potentialCaps.set(currEdge[1], { + point: end, + dir: dir, + color: toColor + }); + } + } + if (dirOK) { + lastValidDir = dir; + } + } + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = potentialCaps.values() [Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _step$value = _step.value, + point = _step$value.point, + _dir = _step$value.dir, + color = _step$value.color; + this._addCap(point, _dir, color); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + return this; + } /** + * Adds the vertices and vertex attributes for two triangles making a rectangle + * for a straight line segment. A vertex shader is responsible for picking + * proper coordinates on the screen given the centerline positions, the tangent, + * and the side of the centerline each vertex belongs to. Sides follow the + * following scheme: + * + * -1 -1 + * o-------------o + * | | + * o-------------o + * 1 1 + * + * @private + * @chainable + */ + + }, + { + key: '_addSegment', + value: function _addSegment(begin, end, fromColor, toColor, dir) { + var _this$lineVertices, + _this$lineVertexColor; + var a = begin.array(); + var b = end.array(); + var dirArr = dir.array(); + this.lineSides.push(1, 1, - 1, 1, - 1, - 1); + for (var _i4 = 0, _arr = [ + this.lineTangentsIn, + this.lineTangentsOut + ]; _i4 < _arr.length; _i4++) { + var tangents = _arr[_i4]; + for (var i = 0; i < 6; i++) { + tangents.push.apply(tangents, _toConsumableArray(dirArr)); + } + }(_this$lineVertices = this.lineVertices).push.apply(_this$lineVertices, _toConsumableArray(a).concat(_toConsumableArray(b), _toConsumableArray(a), _toConsumableArray(b), _toConsumableArray(b), _toConsumableArray(a))); + (_this$lineVertexColor = this.lineVertexColors).push.apply(_this$lineVertexColor, _toConsumableArray(fromColor).concat(_toConsumableArray(toColor), _toConsumableArray(fromColor), _toConsumableArray(toColor), _toConsumableArray(toColor), _toConsumableArray(fromColor))); + return this; + } /** + * Adds the vertices and vertex attributes for two triangles representing the + * stroke cap of a line. A fragment shader is responsible for displaying the + * appropriate cap style within the rectangle they make. + * + * The lineSides buffer will include the following values for the points on + * the cap rectangle: + * + * -1 -2 + * -----------o---o + * | | + * -----------o---o + * 1 2 + * @private + * @chainable + */ + + }, + { + key: '_addCap', + value: function _addCap(point, tangent, color) { + var ptArray = point.array(); + var tanInArray = tangent.array(); + var tanOutArray = [ + 0, + 0, + 0 + ]; + for (var i = 0; i < 6; i++) { + var _this$lineVertices2, + _this$lineTangentsIn, + _this$lineTangentsOut, + _this$lineVertexColor2; + (_this$lineVertices2 = this.lineVertices).push.apply(_this$lineVertices2, _toConsumableArray(ptArray)); + (_this$lineTangentsIn = this.lineTangentsIn).push.apply(_this$lineTangentsIn, _toConsumableArray(tanInArray)); + (_this$lineTangentsOut = this.lineTangentsOut).push.apply(_this$lineTangentsOut, tanOutArray); + (_this$lineVertexColor2 = this.lineVertexColors).push.apply(_this$lineVertexColor2, _toConsumableArray(color)); + } + this.lineSides.push( - 1, 2, - 2, 1, 2, - 1); + return this; + } /** + * Adds the vertices and vertex attributes for four triangles representing a + * join between two adjacent line segments. This creates a quad on either side + * of the shared vertex of the two line segments, with each quad perpendicular + * to the lines. A vertex shader will discard all but the quad in the "elbow" of + * the join, and a fragment shader will display the appropriate join style + * within the remaining quad. + * + * The lineSides buffer will include the following values for the points on + * the join rectangles: + * + * -1 -2 + * -------------o----o + * | | + * 1 o----o----o -3 + * | | 0 | + * --------o----o | + * 2| 3 | + * | | + * | | + * @private + * @chainable + */ + + }, + { + key: '_addJoin', + value: function _addJoin(point, fromTangent, toTangent, color) { + var ptArray = point.array(); + var tanInArray = fromTangent.array(); + var tanOutArray = toTangent.array(); + for (var i = 0; i < 12; i++) { + var _this$lineVertices3, + _this$lineTangentsIn2, + _this$lineTangentsOut2, + _this$lineVertexColor3; + (_this$lineVertices3 = this.lineVertices).push.apply(_this$lineVertices3, _toConsumableArray(ptArray)); + (_this$lineTangentsIn2 = this.lineTangentsIn).push.apply(_this$lineTangentsIn2, _toConsumableArray(tanInArray)); + (_this$lineTangentsOut2 = this.lineTangentsOut).push.apply(_this$lineTangentsOut2, _toConsumableArray(tanOutArray)); + (_this$lineVertexColor3 = this.lineVertexColors).push.apply(_this$lineVertexColor3, _toConsumableArray(color)); + } + this.lineSides.push( - 1, - 3, - 2, - 1, 0, - 3); + this.lineSides.push(3, 1, 2, 3, 0, 1); + return this; + } /** + * Transforms the geometry's vertices to fit snugly within a 100×100×100 box + * centered at the origin. + * + * Calling `myGeometry.normalize()` translates the geometry's vertices so that + * they're centered at the origin `(0, 0, 0)`. Then it scales the vertices so + * that they fill a 100×100×100 box. As a result, small geometries will grow + * and large geometries will shrink. + * + * Note: `myGeometry.normalize()` only works when called in the + * setup() function. + * + * @method normalize + * @chainable + * + * @example + *
        + * + * let myGeometry; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a very small torus. + * beginGeometry(); + * torus(1, 0.25); + * myGeometry = endGeometry(); + * + * // Normalize the torus so its vertices fill + * // the range [-100, 100]. + * myGeometry.normalize(); + * + * describe('A white torus rotates slowly against a dark gray background.'); + * } + * + * function draw() { + * background(50); + * + * // Turn on the lights. + * lights(); + * + * // Rotate around the y-axis. + * rotateY(frameCount * 0.01); + * + * // Style the torus. + * noStroke(); + * + * // Draw the torus. + * model(myGeometry); + * } + * + *
        + */ + + }, + { + key: 'normalize', + value: function normalize() { + if (this.vertices.length > 0) { + // Find the corners of our bounding box + var maxPosition = this.vertices[0].copy(); + var minPosition = this.vertices[0].copy(); + for (var i = 0; i < this.vertices.length; i++) { + maxPosition.x = Math.max(maxPosition.x, this.vertices[i].x); + minPosition.x = Math.min(minPosition.x, this.vertices[i].x); + maxPosition.y = Math.max(maxPosition.y, this.vertices[i].y); + minPosition.y = Math.min(minPosition.y, this.vertices[i].y); + maxPosition.z = Math.max(maxPosition.z, this.vertices[i].z); + minPosition.z = Math.min(minPosition.z, this.vertices[i].z); + } + var center = _main.default.Vector.lerp(maxPosition, minPosition, 0.5); + var dist = _main.default.Vector.sub(maxPosition, minPosition); + var longestDist = Math.max(Math.max(dist.x, dist.y), dist.z); + var scale = 200 / longestDist; + for (var _i5 = 0; _i5 < this.vertices.length; _i5++) { + this.vertices[_i5].sub(center); + this.vertices[_i5].mult(scale); + } + } + return this; + } + } + ]); + return Geometry; + }(); + var _default = _main.default.Geometry; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.flat': 177, + 'core-js/modules/es.array.for-each': 178, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.unscopables.flat': 190, + 'core-js/modules/es.map': 192, + 'core-js/modules/es.number.constructor': 196, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.set': 212, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.sub': 223, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.for-each': 260, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 356: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * @requires constants + * @todo see methods below needing further implementation. + * future consideration: implement SIMD optimizations + * when browser compatibility becomes available + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/ + * Reference/Global_Objects/SIMD + */ + + var GLMAT_ARRAY_TYPE = Array; + var isMatrixArray = function isMatrixArray(x) { + return Array.isArray(x); + }; + if (typeof Float32Array !== 'undefined') { + GLMAT_ARRAY_TYPE = Float32Array; + isMatrixArray = function isMatrixArray(x) { + return Array.isArray(x) || x instanceof Float32Array; + }; + } /** + * A class to describe a 4×4 matrix + * for model and view matrix manipulation in the p5js webgl renderer. + * @class p5.Matrix + * @private + * @constructor + * @param {Array} [mat4] column-major array literal of our 4×4 matrix + */ + + _main.default.Matrix = /*#__PURE__*/ function () { + function _class() { + var _ref; + _classCallCheck(this, _class); + // This is default behavior when object + // instantiated using createMatrix() + // @todo implement createMatrix() in core/math.js + if (arguments.length && (_ref = arguments.length - 1, _ref < 0 || arguments.length <= _ref ? undefined : arguments[_ref]) instanceof _main.default) { + var _ref2; + this.p5 = (_ref2 = arguments.length - 1, _ref2 < 0 || arguments.length <= _ref2 ? undefined : arguments[_ref2]); + } + if ((arguments.length <= 0 ? undefined : arguments[0]) === 'mat3') { + this.mat3 = Array.isArray(arguments.length <= 1 ? undefined : arguments[1]) ? arguments.length <= 1 ? undefined : arguments[1] : new GLMAT_ARRAY_TYPE([1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1]); + } else { + this.mat4 = Array.isArray(arguments.length <= 0 ? undefined : arguments[0]) ? arguments.length <= 0 ? undefined : arguments[0] : new GLMAT_ARRAY_TYPE([1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1]); + } + return this; + } /** + * Replace the entire contents of a 4x4 matrix. + * If providing an array or a p5.Matrix, the values will be copied without + * referencing the source object. + * Can also provide 16 numbers as individual arguments. + * + * @method set + * @param {p5.Matrix|Float32Array|Number[]} [inMatrix] the input p5.Matrix or + * an Array of length 16 + * @chainable + */ + /** + * @method set + * @param {Number[]} elements 16 numbers passed by value to avoid + * array copying. + * @chainable + */ + + _createClass(_class, [ + { + key: 'set', + value: function set(inMatrix) { + var refArray = arguments; + if (inMatrix instanceof _main.default.Matrix) { + refArray = inMatrix.mat4; + } else if (isMatrixArray(inMatrix)) { + refArray = inMatrix; + } + if (refArray.length !== 16) { + _main.default._friendlyError('Expected 16 values but received '.concat(refArray.length, '.'), 'p5.Matrix.set'); + return this; + } + for (var i = 0; i < 16; i++) { + this.mat4[i] = refArray[i]; + } + return this; + } /** + * Gets a copy of the vector, returns a p5.Matrix object. + * + * @method get + * @return {p5.Matrix} the copy of the p5.Matrix object + */ + + }, + { + key: 'get', + value: function get() { + return new _main.default.Matrix(this.mat4, this.p5); + } /** + * return a copy of this matrix. + * If this matrix is 4x4, a 4x4 matrix with exactly the same entries will be + * generated. The same is true if this matrix is 3x3. + * + * @method copy + * @return {p5.Matrix} the result matrix + */ + + }, + { + key: 'copy', + value: function copy() { + if (this.mat3 !== undefined) { + var copied3x3 = new _main.default.Matrix('mat3', this.p5); + copied3x3.mat3[0] = this.mat3[0]; + copied3x3.mat3[1] = this.mat3[1]; + copied3x3.mat3[2] = this.mat3[2]; + copied3x3.mat3[3] = this.mat3[3]; + copied3x3.mat3[4] = this.mat3[4]; + copied3x3.mat3[5] = this.mat3[5]; + copied3x3.mat3[6] = this.mat3[6]; + copied3x3.mat3[7] = this.mat3[7]; + copied3x3.mat3[8] = this.mat3[8]; + return copied3x3; + } + var copied = new _main.default.Matrix(this.p5); + copied.mat4[0] = this.mat4[0]; + copied.mat4[1] = this.mat4[1]; + copied.mat4[2] = this.mat4[2]; + copied.mat4[3] = this.mat4[3]; + copied.mat4[4] = this.mat4[4]; + copied.mat4[5] = this.mat4[5]; + copied.mat4[6] = this.mat4[6]; + copied.mat4[7] = this.mat4[7]; + copied.mat4[8] = this.mat4[8]; + copied.mat4[9] = this.mat4[9]; + copied.mat4[10] = this.mat4[10]; + copied.mat4[11] = this.mat4[11]; + copied.mat4[12] = this.mat4[12]; + copied.mat4[13] = this.mat4[13]; + copied.mat4[14] = this.mat4[14]; + copied.mat4[15] = this.mat4[15]; + return copied; + } /** + * return an identity matrix + * @method identity + * @return {p5.Matrix} the result matrix + */ + + }, + { + key: 'transpose', + /** + * transpose according to a given matrix + * @method transpose + * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be + * based on to transpose + * @chainable + */ + value: function transpose(a) { + var a01, + a02, + a03, + a12, + a13, + a23; + if (a instanceof _main.default.Matrix) { + a01 = a.mat4[1]; + a02 = a.mat4[2]; + a03 = a.mat4[3]; + a12 = a.mat4[6]; + a13 = a.mat4[7]; + a23 = a.mat4[11]; + this.mat4[0] = a.mat4[0]; + this.mat4[1] = a.mat4[4]; + this.mat4[2] = a.mat4[8]; + this.mat4[3] = a.mat4[12]; + this.mat4[4] = a01; + this.mat4[5] = a.mat4[5]; + this.mat4[6] = a.mat4[9]; + this.mat4[7] = a.mat4[13]; + this.mat4[8] = a02; + this.mat4[9] = a12; + this.mat4[10] = a.mat4[10]; + this.mat4[11] = a.mat4[14]; + this.mat4[12] = a03; + this.mat4[13] = a13; + this.mat4[14] = a23; + this.mat4[15] = a.mat4[15]; + } else if (isMatrixArray(a)) { + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a12 = a[6]; + a13 = a[7]; + a23 = a[11]; + this.mat4[0] = a[0]; + this.mat4[1] = a[4]; + this.mat4[2] = a[8]; + this.mat4[3] = a[12]; + this.mat4[4] = a01; + this.mat4[5] = a[5]; + this.mat4[6] = a[9]; + this.mat4[7] = a[13]; + this.mat4[8] = a02; + this.mat4[9] = a12; + this.mat4[10] = a[10]; + this.mat4[11] = a[14]; + this.mat4[12] = a03; + this.mat4[13] = a13; + this.mat4[14] = a23; + this.mat4[15] = a[15]; + } + return this; + } /** + * invert matrix according to a give matrix + * @method invert + * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be + * based on to invert + * @chainable + */ + + }, + { + key: 'invert', + value: function invert(a) { + var a00, + a01, + a02, + a03, + a10, + a11, + a12, + a13; + var a20, + a21, + a22, + a23, + a30, + a31, + a32, + a33; + if (a instanceof _main.default.Matrix) { + a00 = a.mat4[0]; + a01 = a.mat4[1]; + a02 = a.mat4[2]; + a03 = a.mat4[3]; + a10 = a.mat4[4]; + a11 = a.mat4[5]; + a12 = a.mat4[6]; + a13 = a.mat4[7]; + a20 = a.mat4[8]; + a21 = a.mat4[9]; + a22 = a.mat4[10]; + a23 = a.mat4[11]; + a30 = a.mat4[12]; + a31 = a.mat4[13]; + a32 = a.mat4[14]; + a33 = a.mat4[15]; + } else if (isMatrixArray(a)) { + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + a30 = a[12]; + a31 = a[13]; + a32 = a[14]; + a33 = a[15]; + } + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; + // Calculate the determinant + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + if (!det) { + return null; + } + det = 1 / det; + this.mat4[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + this.mat4[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + this.mat4[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + this.mat4[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + this.mat4[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + this.mat4[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + this.mat4[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + this.mat4[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + this.mat4[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + this.mat4[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + this.mat4[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + this.mat4[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + this.mat4[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + this.mat4[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + this.mat4[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + this.mat4[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + return this; + } /** + * Inverts a 3×3 matrix + * @method invert3x3 + * @chainable + */ + + }, + { + key: 'invert3x3', + value: function invert3x3() { + var a00 = this.mat3[0]; + var a01 = this.mat3[1]; + var a02 = this.mat3[2]; + var a10 = this.mat3[3]; + var a11 = this.mat3[4]; + var a12 = this.mat3[5]; + var a20 = this.mat3[6]; + var a21 = this.mat3[7]; + var a22 = this.mat3[8]; + var b01 = a22 * a11 - a12 * a21; + var b11 = - a22 * a10 + a12 * a20; + var b21 = a21 * a10 - a11 * a20; + // Calculate the determinant + var det = a00 * b01 + a01 * b11 + a02 * b21; + if (!det) { + return null; + } + det = 1 / det; + this.mat3[0] = b01 * det; + this.mat3[1] = ( - a22 * a01 + a02 * a21) * det; + this.mat3[2] = (a12 * a01 - a02 * a11) * det; + this.mat3[3] = b11 * det; + this.mat3[4] = (a22 * a00 - a02 * a20) * det; + this.mat3[5] = ( - a12 * a00 + a02 * a10) * det; + this.mat3[6] = b21 * det; + this.mat3[7] = ( - a21 * a00 + a01 * a20) * det; + this.mat3[8] = (a11 * a00 - a01 * a10) * det; + return this; + } /** + * This function is only for 3x3 matrices. + * transposes a 3×3 p5.Matrix by a mat3 + * If there is an array of arguments, the matrix obtained by transposing + * the 3x3 matrix generated based on that array is set. + * If no arguments, it transposes itself and returns it. + * + * @method transpose3x3 + * @param {Number[]} mat3 1-dimensional array + * @chainable + */ + + }, + { + key: 'transpose3x3', + value: function transpose3x3(mat3) { + if (mat3 === undefined) { + mat3 = this.mat3; + } + var a01 = mat3[1]; + var a02 = mat3[2]; + var a12 = mat3[5]; + this.mat3[0] = mat3[0]; + this.mat3[1] = mat3[3]; + this.mat3[2] = mat3[6]; + this.mat3[3] = a01; + this.mat3[4] = mat3[4]; + this.mat3[5] = mat3[7]; + this.mat3[6] = a02; + this.mat3[7] = a12; + this.mat3[8] = mat3[8]; + return this; + } /** + * converts a 4×4 matrix to its 3×3 inverse transform + * commonly used in MVMatrix to NMatrix conversions. + * @method invertTranspose + * @param {p5.Matrix} mat4 the matrix to be based on to invert + * @chainable + * @todo finish implementation + */ + + }, + { + key: 'inverseTranspose', + value: function inverseTranspose(_ref3) { + var mat4 = _ref3.mat4; + if (this.mat3 === undefined) { + _main.default._friendlyError('sorry, this function only works with mat3'); + } else { + //convert mat4 -> mat3 + this.mat3[0] = mat4[0]; + this.mat3[1] = mat4[1]; + this.mat3[2] = mat4[2]; + this.mat3[3] = mat4[4]; + this.mat3[4] = mat4[5]; + this.mat3[5] = mat4[6]; + this.mat3[6] = mat4[8]; + this.mat3[7] = mat4[9]; + this.mat3[8] = mat4[10]; + } + var inverse = this.invert3x3(); + // check inverse succeeded + if (inverse) { + inverse.transpose3x3(this.mat3); + } else { + // in case of singularity, just zero the matrix + for (var i = 0; i < 9; i++) { + this.mat3[i] = 0; + } + } + return this; + } /** + * inspired by Toji's mat4 determinant + * @method determinant + * @return {Number} Determinant of our 4×4 matrix + */ + + }, + { + key: 'determinant', + value: function determinant() { + var d00 = this.mat4[0] * this.mat4[5] - this.mat4[1] * this.mat4[4], + d01 = this.mat4[0] * this.mat4[6] - this.mat4[2] * this.mat4[4], + d02 = this.mat4[0] * this.mat4[7] - this.mat4[3] * this.mat4[4], + d03 = this.mat4[1] * this.mat4[6] - this.mat4[2] * this.mat4[5], + d04 = this.mat4[1] * this.mat4[7] - this.mat4[3] * this.mat4[5], + d05 = this.mat4[2] * this.mat4[7] - this.mat4[3] * this.mat4[6], + d06 = this.mat4[8] * this.mat4[13] - this.mat4[9] * this.mat4[12], + d07 = this.mat4[8] * this.mat4[14] - this.mat4[10] * this.mat4[12], + d08 = this.mat4[8] * this.mat4[15] - this.mat4[11] * this.mat4[12], + d09 = this.mat4[9] * this.mat4[14] - this.mat4[10] * this.mat4[13], + d10 = this.mat4[9] * this.mat4[15] - this.mat4[11] * this.mat4[13], + d11 = this.mat4[10] * this.mat4[15] - this.mat4[11] * this.mat4[14]; + // Calculate the determinant + return d00 * d11 - d01 * d10 + d02 * d09 + d03 * d08 - d04 * d07 + d05 * d06; + } /** + * multiply two mat4s + * @method mult + * @param {p5.Matrix|Float32Array|Number[]} multMatrix The matrix + * we want to multiply by + * @chainable + */ + + }, + { + key: 'mult', + value: function mult(multMatrix) { + var _src; + if (multMatrix === this || multMatrix === this.mat4) { + _src = this.copy().mat4; // only need to allocate in this rare case + } else if (multMatrix instanceof _main.default.Matrix) { + _src = multMatrix.mat4; + } else if (isMatrixArray(multMatrix)) { + _src = multMatrix; + } else if (arguments.length === 16) { + _src = arguments; + } else { + return; // nothing to do. + } // each row is used for the multiplier + + var b0 = this.mat4[0], + b1 = this.mat4[1], + b2 = this.mat4[2], + b3 = this.mat4[3]; + this.mat4[0] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; + this.mat4[1] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; + this.mat4[2] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; + this.mat4[3] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; + b0 = this.mat4[4]; + b1 = this.mat4[5]; + b2 = this.mat4[6]; + b3 = this.mat4[7]; + this.mat4[4] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; + this.mat4[5] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; + this.mat4[6] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; + this.mat4[7] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; + b0 = this.mat4[8]; + b1 = this.mat4[9]; + b2 = this.mat4[10]; + b3 = this.mat4[11]; + this.mat4[8] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; + this.mat4[9] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; + this.mat4[10] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; + this.mat4[11] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; + b0 = this.mat4[12]; + b1 = this.mat4[13]; + b2 = this.mat4[14]; + b3 = this.mat4[15]; + this.mat4[12] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; + this.mat4[13] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; + this.mat4[14] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; + this.mat4[15] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; + return this; + } + }, + { + key: 'apply', + value: function apply(multMatrix) { + var _src; + if (multMatrix === this || multMatrix === this.mat4) { + _src = this.copy().mat4; // only need to allocate in this rare case + } else if (multMatrix instanceof _main.default.Matrix) { + _src = multMatrix.mat4; + } else if (isMatrixArray(multMatrix)) { + _src = multMatrix; + } else if (arguments.length === 16) { + _src = arguments; + } else { + return; // nothing to do. + } + var mat4 = this.mat4; + // each row is used for the multiplier + var m0 = mat4[0]; + var m4 = mat4[4]; + var m8 = mat4[8]; + var m12 = mat4[12]; + mat4[0] = _src[0] * m0 + _src[1] * m4 + _src[2] * m8 + _src[3] * m12; + mat4[4] = _src[4] * m0 + _src[5] * m4 + _src[6] * m8 + _src[7] * m12; + mat4[8] = _src[8] * m0 + _src[9] * m4 + _src[10] * m8 + _src[11] * m12; + mat4[12] = _src[12] * m0 + _src[13] * m4 + _src[14] * m8 + _src[15] * m12; + var m1 = mat4[1]; + var m5 = mat4[5]; + var m9 = mat4[9]; + var m13 = mat4[13]; + mat4[1] = _src[0] * m1 + _src[1] * m5 + _src[2] * m9 + _src[3] * m13; + mat4[5] = _src[4] * m1 + _src[5] * m5 + _src[6] * m9 + _src[7] * m13; + mat4[9] = _src[8] * m1 + _src[9] * m5 + _src[10] * m9 + _src[11] * m13; + mat4[13] = _src[12] * m1 + _src[13] * m5 + _src[14] * m9 + _src[15] * m13; + var m2 = mat4[2]; + var m6 = mat4[6]; + var m10 = mat4[10]; + var m14 = mat4[14]; + mat4[2] = _src[0] * m2 + _src[1] * m6 + _src[2] * m10 + _src[3] * m14; + mat4[6] = _src[4] * m2 + _src[5] * m6 + _src[6] * m10 + _src[7] * m14; + mat4[10] = _src[8] * m2 + _src[9] * m6 + _src[10] * m10 + _src[11] * m14; + mat4[14] = _src[12] * m2 + _src[13] * m6 + _src[14] * m10 + _src[15] * m14; + var m3 = mat4[3]; + var m7 = mat4[7]; + var m11 = mat4[11]; + var m15 = mat4[15]; + mat4[3] = _src[0] * m3 + _src[1] * m7 + _src[2] * m11 + _src[3] * m15; + mat4[7] = _src[4] * m3 + _src[5] * m7 + _src[6] * m11 + _src[7] * m15; + mat4[11] = _src[8] * m3 + _src[9] * m7 + _src[10] * m11 + _src[11] * m15; + mat4[15] = _src[12] * m3 + _src[13] * m7 + _src[14] * m11 + _src[15] * m15; + return this; + } /** + * scales a p5.Matrix by scalars or a vector + * @method scale + * @param {p5.Vector|Float32Array|Number[]} s vector to scale by + * @chainable + */ + + }, + { + key: 'scale', + value: function scale(x, y, z) { + if (x instanceof _main.default.Vector) { + // x is a vector, extract the components from it. + y = x.y; + z = x.z; + x = x.x; // must be last + } else if (x instanceof Array) { + // x is an array, extract the components from it. + y = x[1]; + z = x[2]; + x = x[0]; // must be last + } + this.mat4[0] *= x; + this.mat4[1] *= x; + this.mat4[2] *= x; + this.mat4[3] *= x; + this.mat4[4] *= y; + this.mat4[5] *= y; + this.mat4[6] *= y; + this.mat4[7] *= y; + this.mat4[8] *= z; + this.mat4[9] *= z; + this.mat4[10] *= z; + this.mat4[11] *= z; + return this; + } /** + * rotate our Matrix around an axis by the given angle. + * @method rotate + * @param {Number} a The angle of rotation in radians + * @param {p5.Vector|Number[]} axis the axis(es) to rotate around + * @chainable + * inspired by Toji's gl-matrix lib, mat4 rotation + */ + + }, + { + key: 'rotate', + value: function rotate(a, x, y, z) { + if (x instanceof _main.default.Vector) { + // x is a vector, extract the components from it. + y = x.y; + z = x.z; + x = x.x; //must be last + } else if (x instanceof Array) { + // x is an array, extract the components from it. + y = x[1]; + z = x[2]; + x = x[0]; //must be last + } + var len = Math.sqrt(x * x + y * y + z * z); + x *= 1 / len; + y *= 1 / len; + z *= 1 / len; + var a00 = this.mat4[0]; + var a01 = this.mat4[1]; + var a02 = this.mat4[2]; + var a03 = this.mat4[3]; + var a10 = this.mat4[4]; + var a11 = this.mat4[5]; + var a12 = this.mat4[6]; + var a13 = this.mat4[7]; + var a20 = this.mat4[8]; + var a21 = this.mat4[9]; + var a22 = this.mat4[10]; + var a23 = this.mat4[11]; + //sin,cos, and tan of respective angle + var sA = Math.sin(a); + var cA = Math.cos(a); + var tA = 1 - cA; + // Construct the elements of the rotation matrix + var b00 = x * x * tA + cA; + var b01 = y * x * tA + z * sA; + var b02 = z * x * tA - y * sA; + var b10 = x * y * tA - z * sA; + var b11 = y * y * tA + cA; + var b12 = z * y * tA + x * sA; + var b20 = x * z * tA + y * sA; + var b21 = y * z * tA - x * sA; + var b22 = z * z * tA + cA; + // rotation-specific matrix multiplication + this.mat4[0] = a00 * b00 + a10 * b01 + a20 * b02; + this.mat4[1] = a01 * b00 + a11 * b01 + a21 * b02; + this.mat4[2] = a02 * b00 + a12 * b01 + a22 * b02; + this.mat4[3] = a03 * b00 + a13 * b01 + a23 * b02; + this.mat4[4] = a00 * b10 + a10 * b11 + a20 * b12; + this.mat4[5] = a01 * b10 + a11 * b11 + a21 * b12; + this.mat4[6] = a02 * b10 + a12 * b11 + a22 * b12; + this.mat4[7] = a03 * b10 + a13 * b11 + a23 * b12; + this.mat4[8] = a00 * b20 + a10 * b21 + a20 * b22; + this.mat4[9] = a01 * b20 + a11 * b21 + a21 * b22; + this.mat4[10] = a02 * b20 + a12 * b21 + a22 * b22; + this.mat4[11] = a03 * b20 + a13 * b21 + a23 * b22; + return this; + } /** + * @todo finish implementing this method! + * translates + * @method translate + * @param {Number[]} v vector to translate by + * @chainable + */ + + }, + { + key: 'translate', + value: function translate(v) { + var x = v[0], + y = v[1], + z = v[2] || 0; + this.mat4[12] += this.mat4[0] * x + this.mat4[4] * y + this.mat4[8] * z; + this.mat4[13] += this.mat4[1] * x + this.mat4[5] * y + this.mat4[9] * z; + this.mat4[14] += this.mat4[2] * x + this.mat4[6] * y + this.mat4[10] * z; + this.mat4[15] += this.mat4[3] * x + this.mat4[7] * y + this.mat4[11] * z; + } + }, + { + key: 'rotateX', + value: function rotateX(a) { + this.rotate(a, 1, 0, 0); + } + }, + { + key: 'rotateY', + value: function rotateY(a) { + this.rotate(a, 0, 1, 0); + } + }, + { + key: 'rotateZ', + value: function rotateZ(a) { + this.rotate(a, 0, 0, 1); + } /** + * sets the perspective matrix + * @method perspective + * @param {Number} fovy [description] + * @param {Number} aspect [description] + * @param {Number} near near clipping plane + * @param {Number} far far clipping plane + * @chainable + */ + + }, + { + key: 'perspective', + value: function perspective(fovy, aspect, near, far) { + var f = 1 / Math.tan(fovy / 2), + nf = 1 / (near - far); + this.mat4[0] = f / aspect; + this.mat4[1] = 0; + this.mat4[2] = 0; + this.mat4[3] = 0; + this.mat4[4] = 0; + this.mat4[5] = f; + this.mat4[6] = 0; + this.mat4[7] = 0; + this.mat4[8] = 0; + this.mat4[9] = 0; + this.mat4[10] = (far + near) * nf; + this.mat4[11] = - 1; + this.mat4[12] = 0; + this.mat4[13] = 0; + this.mat4[14] = 2 * far * near * nf; + this.mat4[15] = 0; + return this; + } /** + * sets the ortho matrix + * @method ortho + * @param {Number} left [description] + * @param {Number} right [description] + * @param {Number} bottom [description] + * @param {Number} top [description] + * @param {Number} near near clipping plane + * @param {Number} far far clipping plane + * @chainable + */ + + }, + { + key: 'ortho', + value: function ortho(left, right, bottom, top, near, far) { + var lr = 1 / (left - right), + bt = 1 / (bottom - top), + nf = 1 / (near - far); + this.mat4[0] = - 2 * lr; + this.mat4[1] = 0; + this.mat4[2] = 0; + this.mat4[3] = 0; + this.mat4[4] = 0; + this.mat4[5] = - 2 * bt; + this.mat4[6] = 0; + this.mat4[7] = 0; + this.mat4[8] = 0; + this.mat4[9] = 0; + this.mat4[10] = 2 * nf; + this.mat4[11] = 0; + this.mat4[12] = (left + right) * lr; + this.mat4[13] = (top + bottom) * bt; + this.mat4[14] = (far + near) * nf; + this.mat4[15] = 1; + return this; + } /** + * apply a matrix to a vector with x,y,z,w components + * get the results in the form of an array + * @method multiplyVec4 + * @param {Number} + * @return {Number[]} + */ + + }, + { + key: 'multiplyVec4', + value: function multiplyVec4(x, y, z, w) { + var result = new Array(4); + var m = this.mat4; + result[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + result[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + result[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + result[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + return result; + } /** + * Applies a matrix to a vector. + * The fourth component is set to 1. + * Returns a vector consisting of the first + * through third components of the result. + * + * @method multiplyPoint + * @param {p5.Vector} + * @return {p5.Vector} + */ + + }, + { + key: 'multiplyPoint', + value: function multiplyPoint(_ref4) { + var x = _ref4.x, + y = _ref4.y, + z = _ref4.z; + var array = this.multiplyVec4(x, y, z, 1); + return new _main.default.Vector(array[0], array[1], array[2]); + } /** + * Applies a matrix to a vector. + * The fourth component is set to 1. + * Returns the result of dividing the 1st to 3rd components + * of the result by the 4th component as a vector. + * + * @method multiplyAndNormalizePoint + * @param {p5.Vector} + * @return {p5.Vector} + */ + + }, + { + key: 'multiplyAndNormalizePoint', + value: function multiplyAndNormalizePoint(_ref5) { + var x = _ref5.x, + y = _ref5.y, + z = _ref5.z; + var array = this.multiplyVec4(x, y, z, 1); + array[0] /= array[3]; + array[1] /= array[3]; + array[2] /= array[3]; + return new _main.default.Vector(array[0], array[1], array[2]); + } /** + * Applies a matrix to a vector. + * The fourth component is set to 0. + * Returns a vector consisting of the first + * through third components of the result. + * + * @method multiplyDirection + * @param {p5.Vector} + * @return {p5.Vector} + */ + + }, + { + key: 'multiplyDirection', + value: function multiplyDirection(_ref6) { + var x = _ref6.x, + y = _ref6.y, + z = _ref6.z; + var array = this.multiplyVec4(x, y, z, 0); + return new _main.default.Vector(array[0], array[1], array[2]); + } /** + * This function is only for 3x3 matrices. + * multiply two mat3s. It is an operation to multiply the 3x3 matrix of + * the argument from the right. Arguments can be a 3x3 p5.Matrix, + * a Float32Array of length 9, or a javascript array of length 9. + * In addition, it can also be done by enumerating 9 numbers. + * + * @method mult3x3 + * @param {p5.Matrix|Float32Array|Number[]} multMatrix The matrix + * we want to multiply by + * @chainable + */ + + }, + { + key: 'mult3x3', + value: function mult3x3(multMatrix) { + var _src; + if (multMatrix === this || multMatrix === this.mat3) { + _src = this.copy().mat3; // only need to allocate in this rare case + } else if (multMatrix instanceof _main.default.Matrix) { + _src = multMatrix.mat3; + } else if (isMatrixArray(multMatrix)) { + _src = multMatrix; + } else if (arguments.length === 9) { + _src = arguments; + } else { + return; // nothing to do. + } // each row is used for the multiplier + + var b0 = this.mat3[0]; + var b1 = this.mat3[1]; + var b2 = this.mat3[2]; + this.mat3[0] = b0 * _src[0] + b1 * _src[3] + b2 * _src[6]; + this.mat3[1] = b0 * _src[1] + b1 * _src[4] + b2 * _src[7]; + this.mat3[2] = b0 * _src[2] + b1 * _src[5] + b2 * _src[8]; + b0 = this.mat3[3]; + b1 = this.mat3[4]; + b2 = this.mat3[5]; + this.mat3[3] = b0 * _src[0] + b1 * _src[3] + b2 * _src[6]; + this.mat3[4] = b0 * _src[1] + b1 * _src[4] + b2 * _src[7]; + this.mat3[5] = b0 * _src[2] + b1 * _src[5] + b2 * _src[8]; + b0 = this.mat3[6]; + b1 = this.mat3[7]; + b2 = this.mat3[8]; + this.mat3[6] = b0 * _src[0] + b1 * _src[3] + b2 * _src[6]; + this.mat3[7] = b0 * _src[1] + b1 * _src[4] + b2 * _src[7]; + this.mat3[8] = b0 * _src[2] + b1 * _src[5] + b2 * _src[8]; + return this; + } /** + * This function is only for 3x3 matrices. + * A function that returns a column vector of a 3x3 matrix. + * + * @method column + * @param {Number} columnIndex matrix column number + * @return {p5.Vector} + */ + + }, + { + key: 'column', + value: function column(columnIndex) { + return new _main.default.Vector(this.mat3[3 * columnIndex], this.mat3[3 * columnIndex + 1], this.mat3[3 * columnIndex + 2]); + } /** + * This function is only for 3x3 matrices. + * A function that returns a row vector of a 3x3 matrix. + * + * @method row + * @param {Number} rowIndex matrix row number + * @return {p5.Vector} + */ + + }, + { + key: 'row', + value: function row(rowIndex) { + return new _main.default.Vector(this.mat3[rowIndex], this.mat3[rowIndex + 3], this.mat3[rowIndex + 6]); + } /** + * Returns the diagonal elements of the matrix in the form of an array. + * A 3x3 matrix will return an array of length 3. + * A 4x4 matrix will return an array of length 4. + * + * @method diagonal + * @return {Number[]} An array obtained by arranging the diagonal elements + * of the matrix in ascending order of index + */ + + }, + { + key: 'diagonal', + value: function diagonal() { + if (this.mat3 !== undefined) { + return [this.mat3[0], + this.mat3[4], + this.mat3[8]]; + } + return [this.mat4[0], + this.mat4[5], + this.mat4[10], + this.mat4[15]]; + } /** + * This function is only for 3x3 matrices. + * Takes a vector and returns the vector resulting from multiplying to + * that vector by this matrix from left. + * + * @method multiplyVec3 + * @param {p5.Vector} multVector the vector to which this matrix applies + * @param {p5.Vector} [target] The vector to receive the result + * @return {p5.Vector} + */ + + }, + { + key: 'multiplyVec3', + value: function multiplyVec3(multVector, target) { + if (target === undefined) { + target = multVector.copy(); + } + target.x = this.row(0).dot(multVector); + target.y = this.row(1).dot(multVector); + target.z = this.row(2).dot(multVector); + return target; + } /** + * This function is only for 4x4 matrices. + * Creates a 3x3 matrix whose entries are the top left 3x3 part and returns it. + * + * @method createSubMatrix3x3 + * @return {p5.Matrix} + */ + + }, + { + key: 'createSubMatrix3x3', + value: function createSubMatrix3x3() { + var result = new _main.default.Matrix('mat3'); + result.mat3[0] = this.mat4[0]; + result.mat3[1] = this.mat4[1]; + result.mat3[2] = this.mat4[2]; + result.mat3[3] = this.mat4[4]; + result.mat3[4] = this.mat4[5]; + result.mat3[5] = this.mat4[6]; + result.mat3[6] = this.mat4[8]; + result.mat3[7] = this.mat4[9]; + result.mat3[8] = this.mat4[10]; + return result; + } /** + * PRIVATE + */ + // matrix methods adapted from: + // https://developer.mozilla.org/en-US/docs/Web/WebGL/ + // gluPerspective + // + // function _makePerspective(fovy, aspect, znear, zfar){ + // const ymax = znear * Math.tan(fovy * Math.PI / 360.0); + // const ymin = -ymax; + // const xmin = ymin * aspect; + // const xmax = ymax * aspect; + // return _makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); + // } + //// + //// glFrustum + //// + //function _makeFrustum(left, right, bottom, top, znear, zfar){ + // const X = 2*znear/(right-left); + // const Y = 2*znear/(top-bottom); + // const A = (right+left)/(right-left); + // const B = (top+bottom)/(top-bottom); + // const C = -(zfar+znear)/(zfar-znear); + // const D = -2*zfar*znear/(zfar-znear); + // const frustrumMatrix =[ + // X, 0, A, 0, + // 0, Y, B, 0, + // 0, 0, C, D, + // 0, 0, -1, 0 + //]; + //return frustrumMatrix; + // } + // function _setMVPMatrices(){ + ////an identity matrix + ////@TODO use the p5.Matrix class to abstract away our MV matrices and + ///other math + //const _mvMatrix = + //[ + // 1.0,0.0,0.0,0.0, + // 0.0,1.0,0.0,0.0, + // 0.0,0.0,1.0,0.0, + // 0.0,0.0,0.0,1.0 + //]; + + } + ], [ + { + key: 'identity', + value: function identity(pInst) { + return new _main.default.Matrix(pInst); + } + } + ]); + return _class; + }(); + var _default = _main.default.Matrix; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.float32-array': 234, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254 + } + ], + 357: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.map'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } + _main.default.RenderBuffer = /*#__PURE__*/ function () { + function _class(size, src, dst, attr, renderer, map) { + _classCallCheck(this, _class); + this.size = size; // the number of FLOATs in each vertex + this.src = src; // the name of the model's source array + this.dst = dst; // the name of the geometry's buffer + this.attr = attr; // the name of the vertex attribute + this._renderer = renderer; + this.map = map; // optional, a transformation function to apply to src + } /** + * Enables and binds the buffers used by shader when the appropriate data exists in geometry. + * Must always be done prior to drawing geometry in WebGL. + * @param {p5.Geometry} geometry Geometry that is going to be drawn + * @param {p5.Shader} shader Active shader + * @private + */ + + _createClass(_class, [ + { + key: '_prepareBuffer', + value: function _prepareBuffer(geometry, shader) { + var attributes = shader.attributes; + var gl = this._renderer.GL; + var model; + if (geometry.model) { + model = geometry.model; + } else { + model = geometry; + } // loop through each of the buffer definitions + + var attr = attributes[this.attr]; + if (!attr) { + return; + } // check if the model has the appropriate source array + + var buffer = geometry[this.dst]; + var src = model[this.src]; + if (src.length > 0) { + // check if we need to create the GL buffer + var createBuffer = !buffer; + if (createBuffer) { + // create and remember the buffer + geometry[this.dst] = buffer = gl.createBuffer(); + } // bind the buffer + + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + // check if we need to fill the buffer with data + if (createBuffer || model.dirtyFlags[this.src] !== false) { + var map = this.map; + // get the values from the model, possibly transformed + var values = map ? map(src) : src; + // fill the buffer with the values + this._renderer._bindBuffer(buffer, gl.ARRAY_BUFFER, values); + // mark the model's source array as clean + model.dirtyFlags[this.src] = false; + } // enable the attribute + + shader.enableAttrib(attr, this.size); + } else { + var loc = attr.location; + if (loc === - 1 || !this._renderer.registerEnabled.has(loc)) { + return; + } // Disable register corresponding to unused attribute + + gl.disableVertexAttribArray(loc); + // Record register availability + this._renderer.registerEnabled.delete(loc); + } + } + } + ]); + return _class; + }(); + var _default = _main.default.RenderBuffer; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.map': 185 + } + ], + 358: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.find-index'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.map'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.find-index'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.map'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + _dereq_('./p5.RenderBuffer'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } /** + * Welcome to RendererGL Immediate Mode. + * Immediate mode is used for drawing custom shapes + * from a set of vertices. Immediate Mode is activated + * when you call beginShape() & de-activated when you call endShape(). + * Immediate mode is a style of programming borrowed + * from OpenGL's (now-deprecated) immediate mode. + * It differs from p5.js' default, Retained Mode, which caches + * geometries and buffers on the CPU to reduce the number of webgl + * draw calls. Retained mode is more efficient & performative, + * however, Immediate Mode is useful for sketching quick + * geometric ideas. + */ + /** + * Begin shape drawing. This is a helpful way of generating + * custom shapes quickly. However in WEBGL mode, application + * performance will likely drop as a result of too many calls to + * beginShape() / endShape(). As a high performance alternative, + * please use p5.js geometry primitives. + * @private + * @method beginShape + * @param {Number} mode webgl primitives mode. beginShape supports the + * following modes: + * POINTS,LINES,LINE_STRIP,LINE_LOOP,TRIANGLES, + * TRIANGLE_STRIP, TRIANGLE_FAN, QUADS, QUAD_STRIP, + * and TESS(WEBGL only) + * @chainable + */ + + _main.default.RendererGL.prototype.beginShape = function (mode) { + this.immediateMode.shapeMode = mode !== undefined ? mode : constants.TESS; + this.immediateMode.geometry.reset(); + this.immediateMode.contourIndices = [ + ]; + return this; + }; + var immediateBufferStrides = { + vertices: 1, + vertexNormals: 1, + vertexColors: 4, + vertexStrokeColors: 4, + uvs: 2 + }; + _main.default.RendererGL.prototype.beginContour = function () { + if (this.immediateMode.shapeMode !== constants.TESS) { + throw new Error('WebGL mode can only use contours with beginShape(TESS).'); + } + this.immediateMode.contourIndices.push(this.immediateMode.geometry.vertices.length); + }; + /** + * adds a vertex to be drawn in a custom Shape. + * @private + * @method vertex + * @param {Number} x x-coordinate of vertex + * @param {Number} y y-coordinate of vertex + * @param {Number} z z-coordinate of vertex + * @chainable + * @TODO implement handling of p5.Vector args + */ + _main.default.RendererGL.prototype.vertex = function (x, y) { + // WebGL 1 doesn't support QUADS or QUAD_STRIP, so we duplicate data to turn + // QUADS into TRIANGLES and QUAD_STRIP into TRIANGLE_STRIP. (There is no extra + // work to convert QUAD_STRIP here, since the only difference is in how edges + // are rendered.) + if (this.immediateMode.shapeMode === constants.QUADS) { + // A finished quad turned into triangles should leave 6 vertices in the + // buffer: + // 0--3 0 3--5 + // | | --> | \ \ | + // 1--2 1--2 4 + // When vertex index 3 is being added, add the necessary duplicates. + if (this.immediateMode.geometry.vertices.length % 6 === 3) { + for (var key in immediateBufferStrides) { + var stride = immediateBufferStrides[key]; + var buffer = this.immediateMode.geometry[key]; + buffer.push.apply(buffer, _toConsumableArray(buffer.slice(buffer.length - 3 * stride, buffer.length - 2 * stride)).concat(_toConsumableArray(buffer.slice(buffer.length - stride, buffer.length)))); + } + } + } + var z, + u, + v; + // default to (x, y) mode: all other arguments assumed to be 0. + z = u = v = 0; + if (arguments.length === 3) { + // (x, y, z) mode: (u, v) assumed to be 0. + z = arguments[2]; + } else if (arguments.length === 4) { + // (x, y, u, v) mode: z assumed to be 0. + u = arguments[2]; + v = arguments[3]; + } else if (arguments.length === 5) { + // (x, y, z, u, v) mode + z = arguments[2]; + u = arguments[3]; + v = arguments[4]; + } + var vert = new _main.default.Vector(x, y, z); + this.immediateMode.geometry.vertices.push(vert); + this.immediateMode.geometry.vertexNormals.push(this._currentNormal); + var vertexColor = this.curFillColor || [ + 0.5, + 0.5, + 0.5, + 1 + ]; + this.immediateMode.geometry.vertexColors.push(vertexColor[0], vertexColor[1], vertexColor[2], vertexColor[3]); + var lineVertexColor = this.curStrokeColor || [ + 0.5, + 0.5, + 0.5, + 1 + ]; + this.immediateMode.geometry.vertexStrokeColors.push(lineVertexColor[0], lineVertexColor[1], lineVertexColor[2], lineVertexColor[3]); + if (this.textureMode === constants.IMAGE && !this.isProcessingVertices) { + if (this._tex !== null) { + if (this._tex.width > 0 && this._tex.height > 0) { + u /= this._tex.width; + v /= this._tex.height; + } + } else if (this.userFillShader !== undefined || this.userStrokeShader !== undefined || this.userPointShader !== undefined) { + // Do nothing if user-defined shaders are present + } else if (this._tex === null && arguments.length >= 4) { + // Only throw this warning if custom uv's have been provided + console.warn('You must first call texture() before using' + ' vertex() with image based u and v coordinates'); + } + } + this.immediateMode.geometry.uvs.push(u, v); + this.immediateMode._bezierVertex[0] = x; + this.immediateMode._bezierVertex[1] = y; + this.immediateMode._bezierVertex[2] = z; + this.immediateMode._quadraticVertex[0] = x; + this.immediateMode._quadraticVertex[1] = y; + this.immediateMode._quadraticVertex[2] = z; + return this; + }; + /** + * Sets the normal to use for subsequent vertices. + * @private + * @method normal + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @chainable + * + * @method normal + * @param {Vector} v + * @chainable + */ + _main.default.RendererGL.prototype.normal = function (xorv, y, z) { + if (xorv instanceof _main.default.Vector) { + this._currentNormal = xorv; + } else { + this._currentNormal = new _main.default.Vector(xorv, y, z); + } + return this; + }; + /** + * End shape drawing and render vertices to screen. + * @chainable + */ + _main.default.RendererGL.prototype.endShape = function (mode, isCurve, isBezier, isQuadratic, isContour, shapeKind) { + var count = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 1; + if (this.immediateMode.shapeMode === constants.POINTS) { + this._drawPoints(this.immediateMode.geometry.vertices, this.immediateMode.buffers.point); + return this; + } // When we are drawing a shape then the shape mode is TESS, + // but in case of triangle we can skip the breaking into small triangle + // this can optimize performance by skipping the step of breaking it into triangles + + if (this.immediateMode.geometry.vertices.length === 3 && this.immediateMode.shapeMode === constants.TESS) { + this.immediateMode.shapeMode === constants.TRIANGLES; + } + this.isProcessingVertices = true; + this._processVertices.apply(this, arguments); + this.isProcessingVertices = false; + // LINE_STRIP and LINES are not used for rendering, instead + // they only indicate a way to modify vertices during the _processVertices() step + var is_line = false; + if (this.immediateMode.shapeMode === constants.LINE_STRIP || this.immediateMode.shapeMode === constants.LINES) { + this.immediateMode.shapeMode = constants.TRIANGLE_FAN; + is_line = true; + } // WebGL doesn't support the QUADS and QUAD_STRIP modes, so we + // need to convert them to a supported format. In `vertex()`, we reformat + // the input data into the formats specified below. + + if (this.immediateMode.shapeMode === constants.QUADS) { + this.immediateMode.shapeMode = constants.TRIANGLES; + } else if (this.immediateMode.shapeMode === constants.QUAD_STRIP) { + this.immediateMode.shapeMode = constants.TRIANGLE_STRIP; + } + if (this._doFill && !is_line) { + if (!this.geometryBuilder && this.immediateMode.geometry.vertices.length >= 3) { + this._drawImmediateFill(count); + } + } + if (this._doStroke) { + if (!this.geometryBuilder && this.immediateMode.geometry.lineVertices.length >= 1) { + this._drawImmediateStroke(); + } + } + if (this.geometryBuilder) { + this.geometryBuilder.addImmediate(); + } + this.isBezier = false; + this.isQuadratic = false; + this.isCurve = false; + this.immediateMode._bezierVertex.length = 0; + this.immediateMode._quadraticVertex.length = 0; + this.immediateMode._curveVertex.length = 0; + return this; + }; + /** + * Called from endShape(). This function calculates the stroke vertices for custom shapes and + * tesselates shapes when applicable. + * @private + * @param {Number} mode webgl primitives mode. beginShape supports the + * following modes: + * POINTS,LINES,LINE_STRIP,LINE_LOOP,TRIANGLES, + * TRIANGLE_STRIP, TRIANGLE_FAN and TESS(WEBGL only) + */ + _main.default.RendererGL.prototype._processVertices = function (mode) { + if (this.immediateMode.geometry.vertices.length === 0) return; + var calculateStroke = this._doStroke; + var shouldClose = mode === constants.CLOSE; + if (calculateStroke) { + this.immediateMode.geometry.edges = this._calculateEdges(this.immediateMode.shapeMode, this.immediateMode.geometry.vertices, shouldClose); + if (!this.geometryBuilder) { + this.immediateMode.geometry._edgesToVertices(); + } + } // For hollow shapes, user must set mode to TESS + + var convexShape = this.immediateMode.shapeMode === constants.TESS; + // If the shape has a contour, we have to re-triangulate to cut out the + // contour region + var hasContour = this.immediateMode.contourIndices.length > 0; + // We tesselate when drawing curves or convex shapes + var shouldTess = this._doFill && (this.isBezier || this.isQuadratic || this.isCurve || convexShape || hasContour) && this.immediateMode.shapeMode !== constants.LINES; + if (shouldTess) { + this._tesselateShape(); + } + }; + /** + * Called from _processVertices(). This function calculates the stroke vertices for custom shapes and + * tesselates shapes when applicable. + * @private + * @returns {Array[Number]} indices for custom shape vertices indicating edges. + */ + _main.default.RendererGL.prototype._calculateEdges = function (shapeMode, verts, shouldClose) { + var res = [ + ]; + var i = 0; + var contourIndices = this.immediateMode.contourIndices.slice(); + var contourStart = 0; + switch (shapeMode) { + case constants.TRIANGLE_STRIP: + for (i = 0; i < verts.length - 2; i++) { + res.push([i, + i + 1]); + res.push([i, + i + 2]); + } + res.push([i, + i + 1]); + break; + case constants.TRIANGLE_FAN: + for (i = 1; i < verts.length - 1; i++) { + res.push([0, + i]); + res.push([i, + i + 1]); + } + res.push([0, + verts.length - 1]); + break; + case constants.TRIANGLES: + for (i = 0; i < verts.length - 2; i = i + 3) { + res.push([i, + i + 1]); + res.push([i + 1, + i + 2]); + res.push([i + 2, + i]); + } + break; + case constants.LINES: + for (i = 0; i < verts.length - 1; i = i + 2) { + res.push([i, + i + 1]); + } + break; + case constants.QUADS: + // Quads have been broken up into two triangles by `vertex()`: + // 0 3--5 + // | \ \ | + // 1--2 4 + for (i = 0; i < verts.length - 5; i += 6) { + res.push([i, + i + 1]); + res.push([i + 1, + i + 2]); + res.push([i + 3, + i + 5]); + res.push([i + 4, + i + 5]); + } + break; + case constants.QUAD_STRIP: + // 0---2---4 + // | | | + // 1---3---5 + for (i = 0; i < verts.length - 2; i += 2) { + res.push([i, + i + 1]); + res.push([i, + i + 2]); + res.push([i + 1, + i + 3]); + } + res.push([i, + i + 1]); + break; + default: + // TODO: handle contours in other modes too + for (i = 0; i < verts.length; i++) { + // Handle breaks between contours + if (i + 1 < verts.length && i + 1 !== contourIndices[0]) { + res.push([i, + i + 1]); + } else { + if (shouldClose || contourStart) { + res.push([i, + contourStart]); + } + if (contourIndices.length > 0) { + contourStart = contourIndices.shift(); + } + } + } + break; + } + if (shapeMode !== constants.TESS && shouldClose) { + res.push([verts.length - 1, + 0]); + } + return res; + }; + /** + * Called from _processVertices() when applicable. This function tesselates immediateMode.geometry. + * @private + */ + _main.default.RendererGL.prototype._tesselateShape = function () { + var _this = this; + // TODO: handle non-TESS shape modes that have contours + this.immediateMode.shapeMode = constants.TRIANGLES; + var contours = [ + [] + ]; + for (var i = 0; i < this.immediateMode.geometry.vertices.length; i++) { + if (this.immediateMode.contourIndices.length > 0 && this.immediateMode.contourIndices[0] === i) { + this.immediateMode.contourIndices.shift(); + contours.push([]); + } + contours[contours.length - 1].push(this.immediateMode.geometry.vertices[i].x, this.immediateMode.geometry.vertices[i].y, this.immediateMode.geometry.vertices[i].z, this.immediateMode.geometry.uvs[i * 2], this.immediateMode.geometry.uvs[i * 2 + 1], this.immediateMode.geometry.vertexColors[i * 4], this.immediateMode.geometry.vertexColors[i * 4 + 1], this.immediateMode.geometry.vertexColors[i * 4 + 2], this.immediateMode.geometry.vertexColors[i * 4 + 3], this.immediateMode.geometry.vertexNormals[i].x, this.immediateMode.geometry.vertexNormals[i].y, this.immediateMode.geometry.vertexNormals[i].z); + } + var polyTriangles = this._triangulate(contours); + var originalVertices = this.immediateMode.geometry.vertices; + this.immediateMode.geometry.vertices = [ + ]; + this.immediateMode.geometry.vertexNormals = [ + ]; + this.immediateMode.geometry.uvs = [ + ]; + var colors = [ + ]; + for (var j = 0, polyTriLength = polyTriangles.length; j < polyTriLength; j = j + _main.default.RendererGL.prototype.tessyVertexSize) { + colors.push.apply(colors, _toConsumableArray(polyTriangles.slice(j + 5, j + 9))); + this.normal.apply(this, _toConsumableArray(polyTriangles.slice(j + 9, j + 12))); + this.vertex.apply(this, _toConsumableArray(polyTriangles.slice(j, j + 5))); + } + if (this.geometryBuilder) { + // Tesselating the face causes the indices of edge vertices to stop being + // correct. When rendering, this is not a problem, since _edgesToVertices + // will have been called before this, and edge vertex indices are no longer + // needed. However, the geometry builder still needs this information, so + // when one is active, we need to update the indices. + // + // We record index mappings in a Map so that once we have found a + // corresponding vertex, we don't need to loop to find it again. + var newIndex = new Map(); + this.immediateMode.geometry.edges = this.immediateMode.geometry.edges.map(function (edge) { + return edge.map(function (origIdx) { + if (!newIndex.has(origIdx)) { + var orig = originalVertices[origIdx]; + var newVertIndex = _this.immediateMode.geometry.vertices.findIndex(function (v) { + return orig.x === v.x && orig.y === v.y && orig.z === v.z; + }); + if (newVertIndex === - 1) { + // The tesselation process didn't output a vertex with the exact + // coordinate as before, potentially due to numerical issues. This + // doesn't happen often, but in this case, pick the closest point + var closestDist = Infinity; + var closestIndex = 0; + for (var _i = 0; _i < _this.immediateMode.geometry.vertices.length; _i++) { + var vert = _this.immediateMode.geometry.vertices[_i]; + var dX = orig.x - vert.x; + var dY = orig.y - vert.y; + var dZ = orig.z - vert.z; + var dist = dX * dX + dY * dY + dZ * dZ; + if (dist < closestDist) { + closestDist = dist; + closestIndex = _i; + } + } + newVertIndex = closestIndex; + } + newIndex.set(origIdx, newVertIndex); + } + return newIndex.get(origIdx); + }); + }); + } + this.immediateMode.geometry.vertexColors = colors; + }; + /** + * Called from endShape(). Responsible for calculating normals, setting shader uniforms, + * enabling all appropriate buffers, applying color blend, and drawing the fill geometry. + * @private + */ + _main.default.RendererGL.prototype._drawImmediateFill = function () { + var count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var gl = this.GL; + this._useVertexColor = this.immediateMode.geometry.vertexColors.length > 0; + var shader; + shader = this._getImmediateFillShader(); + this._setFillUniforms(shader); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.immediateMode.buffers.fill[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var buff = _step.value; + buff._prepareBuffer(this.immediateMode.geometry, shader); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + shader.disableRemainingAttributes(); + this._applyColorBlend(this.curFillColor, this.immediateMode.geometry.hasFillTransparency()); + if (count === 1) { + gl.drawArrays(this.immediateMode.shapeMode, 0, this.immediateMode.geometry.vertices.length); + } else { + try { + gl.drawArraysInstanced(this.immediateMode.shapeMode, 0, this.immediateMode.geometry.vertices.length, count); + } catch (e) { + console.log('🌸 p5.js says: Instancing is only supported in WebGL2 mode'); + } + } + shader.unbindShader(); + }; + /** + * Called from endShape(). Responsible for calculating normals, setting shader uniforms, + * enabling all appropriate buffers, applying color blend, and drawing the stroke geometry. + * @private + */ + _main.default.RendererGL.prototype._drawImmediateStroke = function () { + var gl = this.GL; + this._useLineColor = this.immediateMode.geometry.vertexStrokeColors.length > 0; + var shader = this._getImmediateStrokeShader(); + this._setStrokeUniforms(shader); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = this.immediateMode.buffers.stroke[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var buff = _step2.value; + buff._prepareBuffer(this.immediateMode.geometry, shader); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + shader.disableRemainingAttributes(); + this._applyColorBlend(this.curStrokeColor, this.immediateMode.geometry.hasFillTransparency()); + gl.drawArrays(gl.TRIANGLES, 0, this.immediateMode.geometry.lineVertices.length / 3); + shader.unbindShader(); + }; + var _default = _main.default.RendererGL; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + './p5.RenderBuffer': 357, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.fill': 173, + 'core-js/modules/es.array.find-index': 175, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.map': 192, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 359: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.uint16-array'); + _dereq_('core-js/modules/es.typed-array.uint32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.uint16-array'); + _dereq_('core-js/modules/es.typed-array.uint32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + _dereq_('./p5.RendererGL'); + _dereq_('./p5.RenderBuffer'); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } //Retained Mode. The default mode for rendering 3D primitives + //in WEBGL. + /** + * @param {p5.Geometry} geometry The model whose resources will be freed + */ + + _main.default.RendererGL.prototype.freeGeometry = function (geometry) { + if (!geometry.gid) { + console.warn('The model you passed to freeGeometry does not have an id!'); + return; + } + this._freeBuffers(geometry.gid); + }; + /** + * _initBufferDefaults + * @private + * @description initializes buffer defaults. runs each time a new geometry is + * registered + * @param {String} gId key of the geometry object + * @returns {Object} a new buffer object + */ + _main.default.RendererGL.prototype._initBufferDefaults = function (gId) { + this._freeBuffers(gId); + //@TODO remove this limit on hashes in retainedMode.geometry + if (Object.keys(this.retainedMode.geometry).length > 1000) { + var key = Object.keys(this.retainedMode.geometry) [0]; + this._freeBuffers(key); + } //create a new entry in our retainedMode.geometry + + return this.retainedMode.geometry[gId] = { + }; + }; + _main.default.RendererGL.prototype._freeBuffers = function (gId) { + var buffers = this.retainedMode.geometry[gId]; + if (!buffers) { + return; + } + delete this.retainedMode.geometry[gId]; + var gl = this.GL; + if (buffers.indexBuffer) { + gl.deleteBuffer(buffers.indexBuffer); + } + function freeBuffers(defs) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = defs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var def = _step.value; + if (buffers[def.dst]) { + gl.deleteBuffer(buffers[def.dst]); + buffers[def.dst] = null; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } // free all the buffers + + freeBuffers(this.retainedMode.buffers.stroke); + freeBuffers(this.retainedMode.buffers.fill); + }; + /** + * creates a buffers object that holds the WebGL render buffers + * for a geometry. + * @private + * @param {String} gId key of the geometry object + * @param {p5.Geometry} model contains geometry data + */ + _main.default.RendererGL.prototype.createBuffers = function (gId, model) { + var gl = this.GL; + //initialize the gl buffers for our geom groups + var buffers = this._initBufferDefaults(gId); + buffers.model = model; + var indexBuffer = buffers.indexBuffer; + if (model.faces.length) { + // allocate space for faces + if (!indexBuffer) indexBuffer = buffers.indexBuffer = gl.createBuffer(); + var vals = _main.default.RendererGL.prototype._flatten(model.faces); + // If any face references a vertex with an index greater than the maximum + // un-singed 16 bit integer, then we need to use a Uint32Array instead of a + // Uint16Array + var hasVertexIndicesOverMaxUInt16 = vals.some(function (v) { + return v > 65535; + }); + var type = hasVertexIndicesOverMaxUInt16 ? Uint32Array : Uint16Array; + this._bindBuffer(indexBuffer, gl.ELEMENT_ARRAY_BUFFER, vals, type); + // If we're using a Uint32Array for our indexBuffer we will need to pass a + // different enum value to WebGL draw triangles. This happens in + // the _drawElements function. + buffers.indexBufferType = hasVertexIndicesOverMaxUInt16 ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT; + // the vertex count is based on the number of faces + buffers.vertexCount = model.faces.length * 3; + } else { + // the index buffer is unused, remove it + if (indexBuffer) { + gl.deleteBuffer(indexBuffer); + buffers.indexBuffer = null; + } // the vertex count comes directly from the model + + buffers.vertexCount = model.vertices ? model.vertices.length : 0; + } + buffers.lineVertexCount = model.lineVertices ? model.lineVertices.length / 3 : 0; + return buffers; + }; + /** + * Draws buffers given a geometry key ID + * @private + * @param {String} gId ID in our geom hash + * @chainable + */ + _main.default.RendererGL.prototype.drawBuffers = function (gId) { + var gl = this.GL; + var geometry = this.retainedMode.geometry[gId]; + if (!this.geometryBuilder && this._doFill && this.retainedMode.geometry[gId].vertexCount > 0) { + this._useVertexColor = geometry.model.vertexColors.length > 0; + var fillShader = this._getRetainedFillShader(); + this._setFillUniforms(fillShader); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = this.retainedMode.buffers.fill[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var buff = _step2.value; + buff._prepareBuffer(geometry, fillShader); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + fillShader.disableRemainingAttributes(); + if (geometry.indexBuffer) { + //vertex index buffer + this._bindBuffer(geometry.indexBuffer, gl.ELEMENT_ARRAY_BUFFER); + } + this._applyColorBlend(this.curFillColor, geometry.model.hasFillTransparency()); + this._drawElements(gl.TRIANGLES, gId); + fillShader.unbindShader(); + } + if (!this.geometryBuilder && this._doStroke && geometry.lineVertexCount > 0) { + this._useLineColor = geometry.model.vertexStrokeColors.length > 0; + var strokeShader = this._getRetainedStrokeShader(); + this._setStrokeUniforms(strokeShader); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = this.retainedMode.buffers.stroke[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _buff = _step3.value; + _buff._prepareBuffer(geometry, strokeShader); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + strokeShader.disableRemainingAttributes(); + this._applyColorBlend(this.curStrokeColor, geometry.model.hasStrokeTransparency()); + this._drawArrays(gl.TRIANGLES, gId); + strokeShader.unbindShader(); + } + if (this.geometryBuilder) { + this.geometryBuilder.addRetained(geometry); + } + return this; + }; + /** + * Calls drawBuffers() with a scaled model/view matrix. + * + * This is used by various 3d primitive methods (in primitives.js, eg. plane, + * box, torus, etc...) to allow caching of un-scaled geometries. Those + * geometries are generally created with unit-length dimensions, cached as + * such, and then scaled appropriately in this method prior to rendering. + * + * @private + * @method drawBuffersScaled + * @param {String} gId ID in our geom hash + * @param {Number} scaleX the amount to scale in the X direction + * @param {Number} scaleY the amount to scale in the Y direction + * @param {Number} scaleZ the amount to scale in the Z direction + */ + _main.default.RendererGL.prototype.drawBuffersScaled = function (gId, scaleX, scaleY, scaleZ) { + var uMVMatrix = this.uMVMatrix.copy(); + try { + this.uMVMatrix.scale(scaleX, scaleY, scaleZ); + this.drawBuffers(gId); + } finally { + this.uMVMatrix = uMVMatrix; + } + }; + _main.default.RendererGL.prototype._drawArrays = function (drawMode, gId) { + this.GL.drawArrays(drawMode, 0, this.retainedMode.geometry[gId].lineVertexCount); + return this; + }; + _main.default.RendererGL.prototype._drawElements = function (drawMode, gId) { + var buffers = this.retainedMode.geometry[gId]; + var gl = this.GL; + // render the fill + if (buffers.indexBuffer) { + // If this model is using a Uint32Array we need to ensure the + // OES_element_index_uint WebGL extension is enabled. + if (this._pInst.webglVersion !== constants.WEBGL2 && buffers.indexBufferType === gl.UNSIGNED_INT) { + if (!gl.getExtension('OES_element_index_uint')) { + throw new Error('Unable to render a 3d model with > 65535 triangles. Your web browser does not support the WebGL Extension OES_element_index_uint.'); + } + } // we're drawing faces + + gl.drawElements(gl.TRIANGLES, buffers.vertexCount, buffers.indexBufferType, 0); + } else { + // drawing vertices + gl.drawArrays(drawMode || gl.TRIANGLES, 0, buffers.vertexCount); + } + }; + _main.default.RendererGL.prototype._drawPoints = function (vertices, vertexBuffer) { + var gl = this.GL; + var pointShader = this._getImmediatePointShader(); + this._setPointUniforms(pointShader); + this._bindBuffer(vertexBuffer, gl.ARRAY_BUFFER, this._vToNArray(vertices), Float32Array, gl.STATIC_DRAW); + pointShader.enableAttrib(pointShader.attributes.aPosition, 3); + this._applyColorBlend(this.curStrokeColor); + gl.drawArrays(gl.Points, 0, vertices.length); + pointShader.unbindShader(); + }; + var _default = _main.default.RendererGL; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + './p5.RenderBuffer': 357, + './p5.RendererGL': 360, + 'core-js/modules/es.array.fill': 173, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.some': 187, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.keys': 204, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.float32-array': 234, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254, + 'core-js/modules/es.typed-array.uint16-array': 255, + 'core-js/modules/es.typed-array.uint32-array': 256, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 360: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.copy-within'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.flat'); + _dereq_('core-js/modules/es.array.flat-map'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.array.unscopables.flat'); + _dereq_('core-js/modules/es.array.unscopables.flat-map'); + _dereq_('core-js/modules/es.map'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.reflect.get'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.float64-array'); + _dereq_('core-js/modules/es.typed-array.int16-array'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint16-array'); + _dereq_('core-js/modules/es.typed-array.uint32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.concat'); + _dereq_('core-js/modules/es.array.copy-within'); + _dereq_('core-js/modules/es.array.every'); + _dereq_('core-js/modules/es.array.fill'); + _dereq_('core-js/modules/es.array.flat'); + _dereq_('core-js/modules/es.array.flat-map'); + _dereq_('core-js/modules/es.array.from'); + _dereq_('core-js/modules/es.array.includes'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.map'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.array.unscopables.flat'); + _dereq_('core-js/modules/es.array.unscopables.flat-map'); + _dereq_('core-js/modules/es.map'); + _dereq_('core-js/modules/es.object.assign'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.set'); + _dereq_('core-js/modules/es.string.includes'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.typed-array.float32-array'); + _dereq_('core-js/modules/es.typed-array.float64-array'); + _dereq_('core-js/modules/es.typed-array.int16-array'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.uint16-array'); + _dereq_('core-js/modules/es.typed-array.uint32-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.readPixelsWebGL = readPixelsWebGL; + exports.readPixelWebGL = readPixelWebGL; + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + var _GeometryBuilder = _interopRequireDefault(_dereq_('./GeometryBuilder')); + var _libtess = _interopRequireDefault(_dereq_('libtess')); + _dereq_('./p5.Shader'); + _dereq_('./p5.Camera'); + _dereq_('../core/p5.Renderer'); + _dereq_('./p5.Matrix'); + _dereq_('./p5.Framebuffer'); + var _path = _dereq_('path'); + var _p6 = _dereq_('./p5.Texture'); + var _filterShaderFrags; + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance'); + } + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === '[object Arguments]') return Array.from(iter); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + return arr2; + } + } + function _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; + } + 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 = _getPrototypeOf(object); + if (object === null) break; + } + return object; + } + 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 _createSuper(Derived) { + function 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; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_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 _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } + var STROKE_CAP_ENUM = { + }; + var STROKE_JOIN_ENUM = { + }; + var lineDefs = ''; + var defineStrokeCapEnum = function defineStrokeCapEnum(key, val) { + lineDefs += '#define STROKE_CAP_'.concat(key, ' ').concat(val, '\n'); + STROKE_CAP_ENUM[constants[key]] = val; + }; + var defineStrokeJoinEnum = function defineStrokeJoinEnum(key, val) { + lineDefs += '#define STROKE_JOIN_'.concat(key, ' ').concat(val, '\n'); + STROKE_JOIN_ENUM[constants[key]] = val; + }; + // Define constants in line shaders for each type of cap/join, and also record + // the values in JS objects + defineStrokeCapEnum('ROUND', 0); + defineStrokeCapEnum('PROJECT', 1); + defineStrokeCapEnum('SQUARE', 2); + defineStrokeJoinEnum('ROUND', 0); + defineStrokeJoinEnum('MITER', 1); + defineStrokeJoinEnum('BEVEL', 2); + var lightingShader = '#define PI 3.141592\n\nprecision highp float;\nprecision highp int;\n\nuniform mat4 uViewMatrix;\n\nuniform bool uUseLighting;\n\nuniform int uAmbientLightCount;\nuniform vec3 uAmbientColor[5];\nuniform mat3 uCameraRotation;\nuniform int uDirectionalLightCount;\nuniform vec3 uLightingDirection[5];\nuniform vec3 uDirectionalDiffuseColors[5];\nuniform vec3 uDirectionalSpecularColors[5];\n\nuniform int uPointLightCount;\nuniform vec3 uPointLightLocation[5];\nuniform vec3 uPointLightDiffuseColors[5];\t\nuniform vec3 uPointLightSpecularColors[5];\n\nuniform int uSpotLightCount;\nuniform float uSpotLightAngle[5];\nuniform float uSpotLightConc[5];\nuniform vec3 uSpotLightDiffuseColors[5];\nuniform vec3 uSpotLightSpecularColors[5];\nuniform vec3 uSpotLightLocation[5];\nuniform vec3 uSpotLightDirection[5];\n\nuniform bool uSpecular;\nuniform float uShininess;\nuniform float metallic;\n\nuniform float uConstantAttenuation;\nuniform float uLinearAttenuation;\nuniform float uQuadraticAttenuation;\n\n// setting from _setImageLightUniforms()\n// boolean to initiate the calculateImageDiffuse and calculateImageSpecular\nuniform bool uUseImageLight;\n// texture for use in calculateImageDiffuse\nuniform sampler2D environmentMapDiffused;\n// texture for use in calculateImageSpecular\nuniform sampler2D environmentMapSpecular;\n// roughness for use in calculateImageSpecular\nuniform float levelOfDetail;\n\nconst float specularFactor = 2.0;\nconst float diffuseFactor = 0.73;\n\nstruct LightResult {\n float specular;\n float diffuse;\n};\n\nfloat _phongSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float shininess) {\n\n vec3 R = reflect(lightDirection, surfaceNormal);\n return pow(max(0.0, dot(R, viewDirection)), shininess);\n}\n\nfloat _lambertDiffuse(vec3 lightDirection, vec3 surfaceNormal) {\n return max(0.0, dot(-lightDirection, surfaceNormal));\n}\n\nLightResult _light(vec3 viewDirection, vec3 normal, vec3 lightVector) {\n\n vec3 lightDir = normalize(lightVector);\n\n //compute our diffuse & specular terms\n LightResult lr;\n float specularIntensity = mix(1.0, 0.4, metallic);\n float diffuseIntensity = mix(1.0, 0.1, metallic);\n if (uSpecular)\n lr.specular = (_phongSpecular(lightDir, viewDirection, normal, uShininess)) * specularIntensity;\n lr.diffuse = _lambertDiffuse(lightDir, normal) * diffuseIntensity;\n return lr;\n}\n\n// converts the range of "value" from [min1 to max1] to [min2 to max2]\nfloat map(float value, float min1, float max1, float min2, float max2) {\n return min2 + (value - min1) * (max2 - min2) / (max1 - min1);\n}\n\nvec2 mapTextureToNormal( vec3 v ){\n // x = r sin(phi) cos(theta) \n // y = r cos(phi) \n // z = r sin(phi) sin(theta)\n float phi = acos( v.y );\n // if phi is 0, then there are no x, z components\n float theta = 0.0;\n // else \n theta = acos(v.x / sin(phi));\n float sinTheta = v.z / sin(phi);\n if (sinTheta < 0.0) {\n // Turn it into -theta, but in the 0-2PI range\n theta = 2.0 * PI - theta;\n }\n theta = theta / (2.0 * 3.14159);\n phi = phi / 3.14159 ;\n \n vec2 angles = vec2( fract(theta + 0.25), 1.0 - phi );\n return angles;\n}\n\n\nvec3 calculateImageDiffuse( vec3 vNormal, vec3 vViewPosition ){\n // make 2 seperate builds \n vec3 worldCameraPosition = vec3(0.0, 0.0, 0.0); // hardcoded world camera position\n vec3 worldNormal = normalize(vNormal * uCameraRotation);\n vec2 newTexCoor = mapTextureToNormal( worldNormal );\n vec4 texture = TEXTURE( environmentMapDiffused, newTexCoor );\n // this is to make the darker sections more dark\n // png and jpg usually flatten the brightness so it is to reverse that\n return mix(smoothstep(vec3(0.0), vec3(1.0), texture.xyz), vec3(0.0), metallic);\n}\n\nvec3 calculateImageSpecular( vec3 vNormal, vec3 vViewPosition ){\n vec3 worldCameraPosition = vec3(0.0, 0.0, 0.0);\n vec3 worldNormal = normalize(vNormal);\n vec3 lightDirection = normalize( vViewPosition - worldCameraPosition );\n vec3 R = reflect(lightDirection, worldNormal) * uCameraRotation;\n vec2 newTexCoor = mapTextureToNormal( R );\n#ifdef WEBGL2\n vec4 outColor = textureLod(environmentMapSpecular, newTexCoor, levelOfDetail);\n#else\n vec4 outColor = TEXTURE(environmentMapSpecular, newTexCoor);\n#endif\n // this is to make the darker sections more dark\n // png and jpg usually flatten the brightness so it is to reverse that\n return mix(\n pow(outColor.xyz, vec3(10)),\n pow(outColor.xyz, vec3(1.2)),\n metallic \n );\n}\n\nvoid totalLight(\n vec3 modelPosition,\n vec3 normal,\n out vec3 totalDiffuse,\n out vec3 totalSpecular\n) {\n\n totalSpecular = vec3(0.0);\n\n if (!uUseLighting) {\n totalDiffuse = vec3(1.0);\n return;\n }\n\n totalDiffuse = vec3(0.0);\n\n vec3 viewDirection = normalize(-modelPosition);\n\n for (int j = 0; j < 5; j++) {\n if (j < uDirectionalLightCount) {\n vec3 lightVector = (uViewMatrix * vec4(uLightingDirection[j], 0.0)).xyz;\n vec3 lightColor = uDirectionalDiffuseColors[j];\n vec3 specularColor = uDirectionalSpecularColors[j];\n LightResult result = _light(viewDirection, normal, lightVector);\n totalDiffuse += result.diffuse * lightColor;\n totalSpecular += result.specular * lightColor * specularColor;\n }\n\n if (j < uPointLightCount) {\n vec3 lightPosition = (uViewMatrix * vec4(uPointLightLocation[j], 1.0)).xyz;\n vec3 lightVector = modelPosition - lightPosition;\n //calculate attenuation\n float lightDistance = length(lightVector);\n float lightFalloff = 1.0 / (uConstantAttenuation + lightDistance * uLinearAttenuation + (lightDistance * lightDistance) * uQuadraticAttenuation);\n vec3 lightColor = lightFalloff * uPointLightDiffuseColors[j];\n vec3 specularColor = lightFalloff * uPointLightSpecularColors[j];\n\n LightResult result = _light(viewDirection, normal, lightVector);\n totalDiffuse += result.diffuse * lightColor;\n totalSpecular += result.specular * lightColor * specularColor;\n }\n\n if(j < uSpotLightCount) {\n vec3 lightPosition = (uViewMatrix * vec4(uSpotLightLocation[j], 1.0)).xyz;\n vec3 lightVector = modelPosition - lightPosition;\n \n float lightDistance = length(lightVector);\n float lightFalloff = 1.0 / (uConstantAttenuation + lightDistance * uLinearAttenuation + (lightDistance * lightDistance) * uQuadraticAttenuation);\n\n vec3 lightDirection = (uViewMatrix * vec4(uSpotLightDirection[j], 0.0)).xyz;\n float spotDot = dot(normalize(lightVector), normalize(lightDirection));\n float spotFalloff;\n if(spotDot < uSpotLightAngle[j]) {\n spotFalloff = 0.0;\n }\n else {\n spotFalloff = pow(spotDot, uSpotLightConc[j]);\n }\n lightFalloff *= spotFalloff;\n\n vec3 lightColor = uSpotLightDiffuseColors[j];\n vec3 specularColor = uSpotLightSpecularColors[j];\n \n LightResult result = _light(viewDirection, normal, lightVector);\n \n totalDiffuse += result.diffuse * lightColor * lightFalloff;\n totalSpecular += result.specular * lightColor * specularColor * lightFalloff;\n }\n }\n\n if( uUseImageLight ){\n totalDiffuse += calculateImageDiffuse(normal, modelPosition);\n totalSpecular += calculateImageSpecular(normal, modelPosition);\n }\n\n totalDiffuse *= diffuseFactor;\n totalSpecular *= specularFactor;\n}\n'; + var webgl2CompatibilityShader = '#ifdef WEBGL2\n\n#define IN in\n#define OUT out\n\n#ifdef FRAGMENT_SHADER\nout vec4 outColor;\n#define OUT_COLOR outColor\n#endif\n#define TEXTURE texture\n\n#else\n\n#ifdef FRAGMENT_SHADER\n#define IN varying\n#else\n#define IN attribute\n#endif\n#define OUT varying\n#define TEXTURE texture2D\n\n#ifdef FRAGMENT_SHADER\n#define OUT_COLOR gl_FragColor\n#endif\n\n#endif\n'; + var defaultShaders = { + sphereMappingFrag: '#define PI 3.141592\n\nprecision highp float;\n \nuniform sampler2D uSampler;\nuniform mat3 uNewNormalMatrix;\nuniform float uFovY;\nuniform float uAspect;\n\nvarying vec2 vTexCoord;\n \nvoid main() {\n float uFovX = uFovY * uAspect; \n vec4 newTexColor = texture2D(uSampler, vTexCoord);\n float angleY = mix(uFovY/2.0, -uFovY/2.0, vTexCoord.y);\n float angleX = mix(uFovX/2.0, -uFovX/2.0, vTexCoord.x);\n vec3 rotatedNormal = vec3( angleX, angleY, 1.0 );\n rotatedNormal = uNewNormalMatrix * normalize(rotatedNormal);\n vec2 suv;\n suv.y = 0.5 + 0.5 * (-rotatedNormal.y);\n suv.x = atan(rotatedNormal.z, rotatedNormal.x) / (2.0 * PI) + 0.5;\n newTexColor = texture2D(uSampler, suv.xy);\n gl_FragColor = newTexColor;\n}\n', + immediateVert: 'IN vec3 aPosition;\nIN vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uResolution;\nuniform float uPointSize;\n\nOUT 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: 'IN vec3 aPosition;\nIN vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nOUT 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: 'IN vec4 vColor;\nvoid main(void) {\n OUT_COLOR = vec4(vColor.rgb, 1.) * vColor.a;\n}\n', + normalVert: 'IN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\nIN vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nuniform vec4 uMaterialColor;\nuniform bool uUseVertexColor;\n\nOUT vec3 vVertexNormal;\nOUT highp vec2 vVertTexCoord;\nOUT vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertTexCoord = aTexCoord;\n vColor = (uUseVertexColor ? aVertexColor : uMaterialColor);\n}\n', + normalFrag: 'IN vec3 vVertexNormal;\nvoid main(void) {\n OUT_COLOR = vec4(vVertexNormal, 1.0);\n}\n', + basicFrag: 'IN vec4 vColor;\nvoid main(void) {\n OUT_COLOR = vec4(vColor.rgb, 1.) * vColor.a;\n}\n', + lightVert: lightingShader + '// include lighting.glgl\n\nIN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\nIN vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nuniform bool uUseVertexColor;\nuniform vec4 uMaterialColor;\n\nOUT highp vec2 vVertTexCoord;\nOUT vec3 vDiffuseColor;\nOUT vec3 vSpecularColor;\nOUT vec4 vColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition;\n\n vec3 vertexNormal = normalize(uNormalMatrix * aNormal);\n vVertTexCoord = aTexCoord;\n\n totalLight(viewModelPosition.xyz, vertexNormal, vDiffuseColor, vSpecularColor);\n\n for (int i = 0; i < 8; i++) {\n if (i < uAmbientLightCount) {\n vDiffuseColor += uAmbientColor[i];\n }\n }\n \n vColor = (uUseVertexColor ? aVertexColor : uMaterialColor);\n}\n', + lightTextureFrag: 'uniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uEmissive;\n\nIN highp vec2 vVertTexCoord;\nIN vec3 vDiffuseColor;\nIN vec3 vSpecularColor;\nIN vec4 vColor;\n\nvoid main(void) {\n if(uEmissive && !isTexture) {\n OUT_COLOR = vColor;\n }\n else {\n vec4 baseColor = isTexture\n // Textures come in with premultiplied alpha. To apply tint and still have\n // premultiplied alpha output, we need to multiply the RGB channels by the\n // tint RGB, and all channels by the tint alpha.\n ? TEXTURE(uSampler, vVertTexCoord) * vec4(uTint.rgb/255., 1.) * (uTint.a/255.)\n // Colors come in with unmultiplied alpha, so we need to multiply the RGB\n // channels by alpha to convert it to premultiplied alpha.\n : vec4(vColor.rgb * vColor.a, vColor.a);\n OUT_COLOR = vec4(baseColor.rgb * vDiffuseColor + vSpecularColor, baseColor.a);\n }\n}\n', + phongVert: 'precision highp int;\n\nIN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\nIN vec4 aVertexColor;\n\nuniform vec3 uAmbientColor[5];\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\n\nuniform bool uUseVertexColor;\nuniform vec4 uMaterialColor;\n\nOUT vec3 vNormal;\nOUT vec2 vTexCoord;\nOUT vec3 vViewPosition;\nOUT vec3 vAmbientColor;\nOUT vec4 vColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n\n // Pass varyings to fragment shader\n vViewPosition = viewModelPosition.xyz;\n gl_Position = uProjectionMatrix * viewModelPosition; \n\n vNormal = uNormalMatrix * aNormal;\n vTexCoord = aTexCoord;\n\n // TODO: this should be a uniform\n vAmbientColor = vec3(0.0);\n for (int i = 0; i < 5; i++) {\n if (i < uAmbientLightCount) {\n vAmbientColor += uAmbientColor[i];\n }\n }\n \n vColor = (uUseVertexColor ? aVertexColor : uMaterialColor);\n}\n', + phongFrag: lightingShader + '// include lighting.glsl\nprecision highp int;\n\nuniform bool uHasSetAmbient;\nuniform vec4 uSpecularMatColor;\nuniform vec4 uAmbientMatColor;\nuniform vec4 uEmissiveMatColor;\n\nuniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\n\nIN vec3 vNormal;\nIN vec2 vTexCoord;\nIN vec3 vViewPosition;\nIN vec3 vAmbientColor;\nIN vec4 vColor;\n\nvoid main(void) {\n\n vec3 diffuse;\n vec3 specular;\n totalLight(vViewPosition, normalize(vNormal), diffuse, specular);\n\n // Calculating final color as result of all lights (plus emissive term).\n\n vec4 baseColor = isTexture\n // Textures come in with premultiplied alpha. To apply tint and still have\n // premultiplied alpha output, we need to multiply the RGB channels by the\n // tint RGB, and all channels by the tint alpha.\n ? TEXTURE(uSampler, vTexCoord) * vec4(uTint.rgb/255., 1.) * (uTint.a/255.)\n // Colors come in with unmultiplied alpha, so we need to multiply the RGB\n // channels by alpha to convert it to premultiplied alpha.\n : vec4(vColor.rgb * vColor.a, vColor.a);\n OUT_COLOR = vec4(diffuse * baseColor.rgb + \n vAmbientColor * (\n uHasSetAmbient ? uAmbientMatColor.rgb : baseColor.rgb\n ) + \n specular * uSpecularMatColor.rgb + \n uEmissiveMatColor.rgb, baseColor.a);\n}\n', + fontVert: 'IN vec3 aPosition;\nIN vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nuniform vec4 uGlyphRect;\nuniform float uGlyphOffset;\n\nOUT vec2 vTexCoord;\nOUT float w;\n\nvoid main() {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // scale by the size of the glyph\'s rectangle\n positionVec4.xy *= uGlyphRect.zw - uGlyphRect.xy;\n\n // Expand glyph bounding boxes by 1px on each side to give a bit of room\n // for antialiasing\n vec3 newOrigin = (uModelViewMatrix * vec4(0., 0., 0., 1.)).xyz;\n vec3 newDX = (uModelViewMatrix * vec4(1., 0., 0., 1.)).xyz;\n vec3 newDY = (uModelViewMatrix * vec4(0., 1., 0., 1.)).xyz;\n vec2 pixelScale = vec2(\n 1. / length(newOrigin - newDX),\n 1. / length(newOrigin - newDY)\n );\n vec2 offset = pixelScale * normalize(aTexCoord - vec2(0.5, 0.5)) * vec2(1., -1.);\n vec2 textureOffset = offset * (1. / vec2(\n uGlyphRect.z - uGlyphRect.x,\n uGlyphRect.w - uGlyphRect.y\n ));\n\n // move to the corner of the glyph\n positionVec4.xy += uGlyphRect.xy;\n\n // move to the letter\'s line offset\n positionVec4.x += uGlyphOffset;\n\n positionVec4.xy += offset;\n \n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vTexCoord = aTexCoord + textureOffset;\n w = gl_Position.w;\n}\n', + fontFrag: '#ifndef WEBGL2\n#extension GL_OES_standard_derivatives : enable\n#endif\n\n#if 0\n // simulate integer math using floats\n\t#define int float\n\t#define ivec2 vec2\n\t#define INT(x) float(x)\n\n\tint ifloor(float v) { return floor(v); }\n\tivec2 ifloor(vec2 v) { return floor(v); }\n\n#else\n // use native integer math\n\tprecision highp int;\n\t#define INT(x) x\n\n\tint ifloor(float v) { return int(v); }\n\tint ifloor(int v) { return v; }\n\tivec2 ifloor(vec2 v) { return ivec2(v); }\n\n#endif\n\nuniform sampler2D uSamplerStrokes;\nuniform sampler2D uSamplerRowStrokes;\nuniform sampler2D uSamplerRows;\nuniform sampler2D uSamplerColStrokes;\nuniform sampler2D uSamplerCols;\n\nuniform ivec2 uStrokeImageSize;\nuniform ivec2 uCellsImageSize;\nuniform ivec2 uGridImageSize;\n\nuniform ivec2 uGridOffset;\nuniform ivec2 uGridSize;\nuniform vec4 uMaterialColor;\n\nIN vec2 vTexCoord;\n\n// some helper functions\nint ROUND(float v) { return ifloor(v + 0.5); }\nivec2 ROUND(vec2 v) { return ifloor(v + 0.5); }\nfloat saturate(float v) { return clamp(v, 0.0, 1.0); }\nvec2 saturate(vec2 v) { return clamp(v, 0.0, 1.0); }\n\nint mul(float v1, int v2) {\n return ifloor(v1 * float(v2));\n}\n\nivec2 mul(vec2 v1, ivec2 v2) {\n return ifloor(v1 * vec2(v2) + 0.5);\n}\n\n// unpack a 16-bit integer from a float vec2\nint getInt16(vec2 v) {\n ivec2 iv = ROUND(v * 255.0);\n return iv.x * INT(128) + iv.y;\n}\n\nvec2 pixelScale;\nvec2 coverage = vec2(0.0);\nvec2 weight = vec2(0.5);\nconst float minDistance = 1.0/8192.0;\nconst float hardness = 1.05; // amount of antialias\n\n// the maximum number of curves in a glyph\nconst int N = INT(250);\n\n// retrieves an indexed pixel from a sampler\nvec4 getTexel(sampler2D sampler, int pos, ivec2 size) {\n int width = size.x;\n int y = ifloor(pos / width);\n int x = pos - y * width; // pos % width\n\n return TEXTURE(sampler, (vec2(x, y) + 0.5) / vec2(size));\n}\n\nvoid calulateCrossings(vec2 p0, vec2 p1, vec2 p2, out vec2 C1, out vec2 C2) {\n\n // get the coefficients of the quadratic in t\n vec2 a = p0 - p1 * 2.0 + p2;\n vec2 b = p0 - p1;\n vec2 c = p0 - vTexCoord;\n\n // found out which values of \'t\' it crosses the axes\n vec2 surd = sqrt(max(vec2(0.0), b * b - a * c));\n vec2 t1 = ((b - surd) / a).yx;\n vec2 t2 = ((b + surd) / a).yx;\n\n // approximate straight lines to avoid rounding errors\n if (abs(a.y) < 0.001)\n t1.x = t2.x = c.y / (2.0 * b.y);\n\n if (abs(a.x) < 0.001)\n t1.y = t2.y = c.x / (2.0 * b.x);\n\n // plug into quadratic formula to find the corrdinates of the crossings\n C1 = ((a * t1 - b * 2.0) * t1 + c) * pixelScale;\n C2 = ((a * t2 - b * 2.0) * t2 + c) * pixelScale;\n}\n\nvoid coverageX(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n // determine on which side of the x-axis the points lie\n bool y0 = p0.y > vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n OUT_COLOR = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n OUT_COLOR *= saturate(max(antialias, cover));\n}\n', + lineVert: lineDefs + '/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nprecision mediump int;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform bool uUseLineColor;\nuniform vec4 uMaterialColor;\n\nuniform vec4 uViewport;\nuniform int uPerspective;\nuniform int uStrokeJoin;\n\nIN vec4 aPosition;\nIN vec3 aTangentIn;\nIN vec3 aTangentOut;\nIN float aSide;\nIN vec4 aVertexColor;\n\nOUT vec4 vColor;\nOUT vec2 vTangent;\nOUT vec2 vCenter;\nOUT vec2 vPosition;\nOUT float vMaxDist;\nOUT float vCap;\nOUT float vJoin;\n\nvec2 lineIntersection(vec2 aPoint, vec2 aDir, vec2 bPoint, vec2 bDir) {\n // Rotate and translate so a starts at the origin and goes out to the right\n bPoint -= aPoint;\n vec2 rotatedBFrom = vec2(\n bPoint.x*aDir.x + bPoint.y*aDir.y,\n bPoint.y*aDir.x - bPoint.x*aDir.y\n );\n vec2 bTo = bPoint + bDir;\n vec2 rotatedBTo = vec2(\n bTo.x*aDir.x + bTo.y*aDir.y,\n bTo.y*aDir.x - bTo.x*aDir.y\n );\n float intersectionDistance =\n rotatedBTo.x + (rotatedBFrom.x - rotatedBTo.x) * rotatedBTo.y /\n (rotatedBTo.y - rotatedBFrom.y);\n return aPoint + aDir * intersectionDistance;\n}\n\nvoid main() {\n // Caps have one of either the in or out tangent set to 0\n vCap = (aTangentIn == vec3(0.)) != (aTangentOut == (vec3(0.)))\n ? 1. : 0.;\n\n // Joins have two unique, defined tangents\n vJoin = (\n aTangentIn != vec3(0.) &&\n aTangentOut != vec3(0.) &&\n aTangentIn != aTangentOut\n ) ? 1. : 0.;\n\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posqIn = uModelViewMatrix * (aPosition + vec4(aTangentIn, 0));\n vec4 posqOut = uModelViewMatrix * (aPosition + vec4(aTangentOut, 0));\n\n float facingCamera = pow(\n // The word space tangent\'s z value is 0 if it\'s facing the camera\n abs(normalize(posqIn-posp).z),\n\n // Using pow() here to ramp `facingCamera` up from 0 to 1 really quickly\n // so most lines get scaled and don\'t get clipped\n 0.25\n );\n\n // using a scale <1 moves the lines towards the camera\n // in order to prevent popping effects due to half of\n // the line disappearing behind the geometry faces.\n float scale = mix(1., 0.995, facingCamera);\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posqIn.xyz = posqIn.xyz * scale;\n posqOut.xyz = posqOut.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 qIn = uProjectionMatrix * posqIn;\n vec4 qOut = uProjectionMatrix * posqOut;\n vCenter = p.xy;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don\'t care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can\'t remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangentIn = normalize((qIn.xy*p.w - p.xy*qIn.w) * uViewport.zw);\n vec2 tangentOut = normalize((qOut.xy*p.w - p.xy*qOut.w) * uViewport.zw);\n\n vec2 curPerspScale;\n if(uPerspective == 1) {\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n\n // The y value of the projection matrix may be flipped if rendering to a Framebuffer.\n // Multiplying again by its sign here negates the flip to get just the scale.\n curPerspScale = (uProjectionMatrix * vec4(1, sign(uProjectionMatrix[1][1]), 0, 0)).xy;\n } else {\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n curPerspScale = p.w / (0.5 * uViewport.zw);\n }\n\n vec2 offset;\n if (vJoin == 1.) {\n vTangent = normalize(tangentIn + tangentOut);\n vec2 normalIn = vec2(-tangentIn.y, tangentIn.x);\n vec2 normalOut = vec2(-tangentOut.y, tangentOut.x);\n float side = sign(aSide);\n float sideEnum = abs(aSide);\n\n // We generate vertices for joins on either side of the centerline, but\n // the "elbow" side is the only one needing a join. By not setting the\n // offset for the other side, all its vertices will end up in the same\n // spot and not render, effectively discarding it.\n if (sign(dot(tangentOut, vec2(-tangentIn.y, tangentIn.x))) != side) {\n // Side enums:\n // 1: the side going into the join\n // 2: the middle of the join\n // 3: the side going out of the join\n if (sideEnum == 2.) {\n // Calculate the position + tangent on either side of the join, and\n // find where the lines intersect to find the elbow of the join\n vec2 c = (posp.xy/posp.w + vec2(1.,1.)) * 0.5 * uViewport.zw;\n vec2 intersection = lineIntersection(\n c + (side * normalIn * uStrokeWeight / 2.),\n tangentIn,\n c + (side * normalOut * uStrokeWeight / 2.),\n tangentOut\n );\n offset = (intersection - c);\n\n // When lines are thick and the angle of the join approaches 180, the\n // elbow might be really far from the center. We\'ll apply a limit to\n // the magnitude to avoid lines going across the whole screen when this\n // happens.\n float mag = length(offset);\n float maxMag = 3. * uStrokeWeight;\n if (mag > maxMag) {\n offset *= maxMag / mag;\n }\n } else if (sideEnum == 1.) {\n offset = side * normalIn * uStrokeWeight / 2.;\n } else if (sideEnum == 3.) {\n offset = side * normalOut * uStrokeWeight / 2.;\n }\n }\n if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 avgNormal = vec2(-vTangent.y, vTangent.x);\n vMaxDist = abs(dot(avgNormal, normalIn * uStrokeWeight / 2.));\n } else {\n vMaxDist = uStrokeWeight / 2.;\n }\n } else {\n vec2 tangent = aTangentIn == vec3(0.) ? tangentOut : tangentIn;\n vTangent = tangent;\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float normalOffset = sign(aSide);\n // Caps will have side values of -2 or 2 on the edge of the cap that\n // extends out from the line\n float tangentOffset = abs(aSide) - 1.;\n offset = (normal * normalOffset + tangent * tangentOffset) *\n uStrokeWeight * 0.5;\n vMaxDist = uStrokeWeight / 2.;\n }\n vPosition = vCenter + offset;\n\n gl_Position.xy = p.xy + offset.xy * curPerspScale;\n gl_Position.zw = p.zw;\n \n vColor = (uUseLineColor ? aVertexColor : uMaterialColor);\n}\n', + lineFrag: lineDefs + 'precision mediump int;\n\nuniform vec4 uMaterialColor;\nuniform int uStrokeCap;\nuniform int uStrokeJoin;\nuniform float uStrokeWeight;\n\nIN vec4 vColor;\nIN vec2 vTangent;\nIN vec2 vCenter;\nIN vec2 vPosition;\nIN float vMaxDist;\nIN float vCap;\nIN float vJoin;\n\nfloat distSquared(vec2 a, vec2 b) {\n vec2 aToB = b - a;\n return dot(aToB, aToB);\n}\n\nvoid main() {\n if (vCap > 0.) {\n if (\n uStrokeCap == STROKE_CAP_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (\n uStrokeCap == STROKE_CAP_SQUARE &&\n dot(vPosition - vCenter, vTangent) > 0.\n ) {\n discard;\n }\n // Use full area for PROJECT\n } else if (vJoin > 0.) {\n if (\n uStrokeJoin == STROKE_JOIN_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 normal = vec2(-vTangent.y, vTangent.x);\n if (abs(dot(vPosition - vCenter, normal)) > vMaxDist) {\n discard;\n }\n }\n // Use full area for MITER\n }\n OUT_COLOR = vec4(vColor.rgb, 1.) * vColor.a;\n}\n', + pointVert: 'IN vec3 aPosition;\nuniform float uPointSize;\nOUT float vStrokeWeight;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvoid main() {\n\tvec4 positionVec4 = vec4(aPosition, 1.0);\n\tgl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\tgl_PointSize = uPointSize;\n\tvStrokeWeight = uPointSize;\n}\n', + pointFrag: 'precision mediump int;\nuniform vec4 uMaterialColor;\nIN float vStrokeWeight;\n\nvoid main(){\n float mask = 0.0;\n\n // make a circular mask using the gl_PointCoord (goes from 0 - 1 on a point)\n // might be able to get a nicer edge on big strokeweights with smoothstep but slightly less performant\n\n mask = step(0.98, length(gl_PointCoord * 2.0 - 1.0));\n\n // if strokeWeight is 1 or less lets just draw a square\n // this prevents weird artifacting from carving circles when our points are really small\n // if strokeWeight is larger than 1, we just use it as is\n\n mask = mix(0.0, mask, clamp(floor(vStrokeWeight - 0.5),0.0,1.0));\n\n // throw away the borders of the mask\n // otherwise we get weird alpha blending issues\n\n if(mask > 0.98){\n discard;\n }\n\n OUT_COLOR = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n}\n', + imageLightVert: 'precision highp float;\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nvarying vec3 localPos;\nvarying vec3 vWorldNormal;\nvarying vec3 vWorldPosition;\nvarying vec2 vTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvoid main() {\n // Multiply the position by the matrix.\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition; \n \n // orient the normals and pass to the fragment shader\n vWorldNormal = uNormalMatrix * aNormal;\n \n // send the view position to the fragment shader\n vWorldPosition = (uModelViewMatrix * vec4(aPosition, 1.0)).xyz;\n \n localPos = vWorldPosition;\n vTexCoord = aTexCoord;\n}\n\n\n/*\nin the vertex shader we\'ll compute the world position and world oriented normal of the vertices and pass those to the fragment shader as varyings.\n*/\n', + imageLightDiffusedFrag: 'precision highp float;\nvarying vec3 localPos;\n\n// the HDR cubemap converted (can be from an equirectangular environment map.)\nuniform sampler2D environmentMap;\nvarying vec2 vTexCoord;\n\nconst float PI = 3.14159265359;\n\nvec2 nTOE( vec3 v ){\n // x = r sin(phi) cos(theta) \n // y = r cos(phi) \n // z = r sin(phi) sin(theta)\n float phi = acos( v.y );\n // if phi is 0, then there are no x, z components\n float theta = 0.0;\n // else \n theta = acos(v.x / sin(phi));\n float sinTheta = v.z / sin(phi);\n if (sinTheta < 0.0) {\n // Turn it into -theta, but in the 0-2PI range\n theta = 2.0 * PI - theta;\n }\n theta = theta / (2.0 * 3.14159);\n phi = phi / 3.14159 ;\n \n vec2 angles = vec2( phi, theta );\n return angles;\n}\n\nfloat random(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * .1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n}\n\nvoid main()\n{ \t \n\t// the sample direction equals the hemisphere\'s orientation\n float phi = vTexCoord.x * 2.0 * PI;\n float theta = vTexCoord.y * PI;\n float x = sin(theta) * cos(phi);\n float y = sin(theta) * sin(phi);\n float z = cos(theta);\n vec3 normal = vec3( x, y, z);\n\n\t// Discretely sampling the hemisphere given the integral\'s\n // spherical coordinates translates to the following fragment code:\n\tvec3 irradiance = vec3(0.0); \n\tvec3 up\t= vec3(0.0, 1.0, 0.0);\n\tvec3 right = normalize(cross(up, normal));\n\tup = normalize(cross(normal, right));\n\n\t// We specify a fixed sampleDelta delta value to traverse\n // the hemisphere; decreasing or increasing the sample delta\n // will increase or decrease the accuracy respectively.\n\tconst float sampleDelta = 0.100;\n\tfloat nrSamples = 0.0;\n float randomOffset = random(gl_FragCoord.xy) * sampleDelta;\n\tfor(float rawPhi = 0.0; rawPhi < 2.0 * PI; rawPhi += sampleDelta)\n\t{\n float phi = rawPhi + randomOffset;\n for(float rawTheta = 0.0; rawTheta < ( 0.5 ) * PI; rawTheta += sampleDelta)\n {\n float theta = rawTheta + randomOffset;\n // spherical to cartesian (in tangent space) // tangent space to world // add each sample result to irradiance\n float x = sin(theta) * cos(phi);\n float y = sin(theta) * sin(phi);\n float z = cos(theta);\n vec3 tangentSample = vec3( x, y, z);\n \n vec3 sampleVec = tangentSample.x * right + tangentSample.y * up + tangentSample.z * normal;\n irradiance += (texture2D(environmentMap, nTOE(sampleVec)).xyz) * cos(theta) * sin(theta);\n nrSamples++;\n }\n\t}\n\t// divide by the total number of samples taken, giving us the average sampled irradiance.\n\tirradiance = PI * irradiance * (1.0 / float(nrSamples )) ;\n \n \n\tgl_FragColor = vec4(irradiance, 1.0);\n}', + imageLightSpecularFrag: 'precision highp float;\r\nvarying vec3 localPos;\r\nvarying vec2 vTexCoord;\r\n\r\n// our texture\r\nuniform sampler2D environmentMap;\r\nuniform float roughness;\r\n\r\nconst float PI = 3.14159265359;\r\n\r\nfloat VanDerCorput(int bits);\r\nvec2 HammersleyNoBitOps(int i, int N);\r\nvec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness);\r\n\r\n\r\nvec2 nTOE( vec3 v ){\r\n // x = r sin(phi) cos(theta) \r\n // y = r cos(phi) \r\n // z = r sin(phi) sin(theta)\r\n float phi = acos( v.y );\r\n // if phi is 0, then there are no x, z components\r\n float theta = 0.0;\r\n // else \r\n theta = acos(v.x / sin(phi));\r\n float sinTheta = v.z / sin(phi);\r\n if (sinTheta < 0.0) {\r\n // Turn it into -theta, but in the 0-2PI range\r\n theta = 2.0 * PI - theta;\r\n }\r\n theta = theta / (2.0 * 3.14159);\r\n phi = phi / 3.14159 ;\r\n \r\n vec2 angles = vec2( phi, theta );\r\n return angles;\r\n}\r\n\r\n\r\nvoid main(){\r\n const int SAMPLE_COUNT = 400; // 4096\r\n int lowRoughnessLimit = int(pow(2.0,(roughness+0.1)*20.0));\r\n float totalWeight = 0.0;\r\n vec3 prefilteredColor = vec3(0.0);\r\n float phi = vTexCoord.x * 2.0 * PI;\r\n float theta = vTexCoord.y * PI;\r\n float x = sin(theta) * cos(phi);\r\n float y = sin(theta) * sin(phi);\r\n float z = cos(theta);\r\n vec3 N = vec3(x,y,z);\r\n vec3 V = N;\r\n for (int i = 0; i < SAMPLE_COUNT; ++i)\r\n {\r\n // break at smaller sample numbers for low roughness levels\r\n if(i == lowRoughnessLimit)\r\n {\r\n break;\r\n }\r\n vec2 Xi = HammersleyNoBitOps(i, SAMPLE_COUNT);\r\n vec3 H = ImportanceSampleGGX(Xi, N, roughness);\r\n vec3 L = normalize(2.0 * dot(V, H) * H - V);\r\n\r\n float NdotL = max(dot(N, L), 0.0);\r\n if (NdotL > 0.0)\r\n {\r\n prefilteredColor += texture2D(environmentMap, nTOE(L)).xyz * NdotL;\r\n totalWeight += NdotL;\r\n }\r\n }\r\n prefilteredColor = prefilteredColor / totalWeight;\r\n\r\n gl_FragColor = vec4(prefilteredColor, 1.0);\r\n}\r\n\r\nvec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness){\r\n float a = roughness * roughness;\r\n\r\n float phi = 2.0 * PI * Xi.x;\r\n float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));\r\n float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\r\n // from spherical coordinates to cartesian coordinates\r\n vec3 H;\r\n H.x = cos(phi) * sinTheta;\r\n H.y = sin(phi) * sinTheta;\r\n H.z = cosTheta;\r\n\r\n // from tangent-space vector to world-space sample vector\r\n vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\r\n vec3 tangent = normalize(cross(up, N));\r\n vec3 bitangent = cross(N, tangent);\r\n\r\n vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;\r\n return normalize(sampleVec);\r\n}\r\n\r\n\r\nfloat VanDerCorput(int n, int base)\r\n{\r\n#ifdef WEBGL2\r\n\r\n uint bits = uint(n);\r\n bits = (bits << 16u) | (bits >> 16u);\r\n bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\r\n bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\r\n bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\r\n bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\r\n return float(bits) * 2.3283064365386963e-10; // / 0x100000000\r\n\r\n#else\r\n\r\n float invBase = 1.0 / float(base);\r\n float denom = 1.0;\r\n float result = 0.0;\r\n\r\n\r\n for (int i = 0; i < 32; ++i)\r\n {\r\n if (n > 0)\r\n {\r\n denom = mod(float(n), 2.0);\r\n result += denom * invBase;\r\n invBase = invBase / 2.0;\r\n n = int(float(n) / 2.0);\r\n }\r\n }\r\n\r\n\r\n return result;\r\n\r\n#endif\r\n}\r\n\r\nvec2 HammersleyNoBitOps(int i, int N)\r\n{\r\n return vec2(float(i) / float(N), VanDerCorput(i, 2));\r\n}\r\n' + }; + var sphereMapping = defaultShaders.sphereMappingFrag; + for (var key in defaultShaders) { + defaultShaders[key] = webgl2CompatibilityShader + defaultShaders[key]; + } + var filterShaderFrags = (_filterShaderFrags = { + }, _defineProperty(_filterShaderFrags, constants.GRAY, 'precision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n return dot(color, vec3(0.2126, 0.7152, 0.0722));\n}\n\nvoid main() {\n vec4 tex = texture2D(tex0, vTexCoord);\n float gray = luma(tex.rgb);\n gl_FragColor = vec4(gray, gray, gray, tex.a);\n}\n'), _defineProperty(_filterShaderFrags, constants.ERODE, '// Reduces the bright areas in an image\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform vec2 texelSize;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n // weights 77, 151, 28 taken from src/image/filters.js\n return dot(color, vec3(0.300781, 0.589844, 0.109375));\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n float lum = luma(color.rgb);\n\n // set current color as the darkest neighbor color\n\n vec4 neighbors[4];\n neighbors[0] = texture2D(tex0, vTexCoord + vec2( texelSize.x, 0.0));\n neighbors[1] = texture2D(tex0, vTexCoord + vec2(-texelSize.x, 0.0));\n neighbors[2] = texture2D(tex0, vTexCoord + vec2(0.0, texelSize.y));\n neighbors[3] = texture2D(tex0, vTexCoord + vec2(0.0, -texelSize.y));\n\n for (int i = 0; i < 4; i++) {\n vec4 neighborColor = neighbors[i];\n float neighborLum = luma(neighborColor.rgb);\n\n if (neighborLum < lum) {\n color = neighborColor;\n lum = neighborLum;\n }\n }\n\n gl_FragColor = color;\n}\n'), _defineProperty(_filterShaderFrags, constants.DILATE, '// Increase the bright areas in an image\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform vec2 texelSize;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n // weights 77, 151, 28 taken from src/image/filters.js\n return dot(color, vec3(0.300781, 0.589844, 0.109375));\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n float lum = luma(color.rgb);\n\n // set current color as the brightest neighbor color\n\n vec4 neighbors[4];\n neighbors[0] = texture2D(tex0, vTexCoord + vec2( texelSize.x, 0.0));\n neighbors[1] = texture2D(tex0, vTexCoord + vec2(-texelSize.x, 0.0));\n neighbors[2] = texture2D(tex0, vTexCoord + vec2(0.0, texelSize.y));\n neighbors[3] = texture2D(tex0, vTexCoord + vec2(0.0, -texelSize.y));\n\n for (int i = 0; i < 4; i++) {\n vec4 neighborColor = neighbors[i];\n float neighborLum = luma(neighborColor.rgb);\n\n if (neighborLum > lum) {\n color = neighborColor;\n lum = neighborLum;\n }\n }\n\n gl_FragColor = color;\n}\n'), _defineProperty(_filterShaderFrags, constants.BLUR, 'precision highp float;\n\n// Two-pass blur filter, unweighted kernel.\n// See also a similar blur at Adam Ferriss\' repo of shader examples:\n// https://github.com/aferriss/p5jsShaderExamples/blob/gh-pages/4_image-effects/4-9_single-pass-blur/effect.frag\n\n\nuniform sampler2D tex0;\nvarying vec2 vTexCoord;\nuniform vec2 direction;\nuniform vec2 canvasSize;\nuniform float radius;\n\nfloat random(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * .1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n}\n\n// This isn\'t a real Gaussian weight, it\'s a quadratic weight. It\'s what the\n// CPU mode\'s blur uses though, so we also use it here to match.\nfloat quadWeight(float x, float e) {\n return pow(e-abs(x), 2.);\n}\n\nvoid main(){\n vec2 uv = vTexCoord;\n\n // A reasonable maximum number of samples\n const float maxSamples = 64.0;\n\n float numSamples = floor(7. * radius);\n if (fract(numSamples / 2.) == 0.) {\n numSamples++;\n }\n vec4 avg = vec4(0.0);\n float total = 0.0;\n\n // Calculate the spacing to avoid skewing if numSamples > maxSamples\n float spacing = 1.0;\n if (numSamples > maxSamples) {\n spacing = numSamples / maxSamples;\n numSamples = maxSamples;\n }\n\n float randomOffset = (spacing - 1.0) * mix(-0.5, 0.5, random(gl_FragCoord.xy));\n for (float i = 0.0; i < maxSamples; i++) {\n if (i >= numSamples) break;\n\n float sample = i * spacing - (numSamples - 1.0) * 0.5 * spacing + randomOffset;\n vec2 sampleCoord = uv + vec2(sample, sample) / canvasSize * direction;\n float weight = quadWeight(sample, (numSamples - 1.0) * 0.5 * spacing);\n\n avg += weight * texture2D(tex0, sampleCoord);\n total += weight;\n }\n\n avg /= total;\n gl_FragColor = avg;\n}\n'), _defineProperty(_filterShaderFrags, constants.POSTERIZE, '// Limit color space for a stylized cartoon / poster effect\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform float filterParameter;\n\nvec3 quantize(vec3 color, float n) {\n // restrict values to N options/bins\n // and floor each channel to nearest value\n //\n // eg. when N = 5, values = 0.0, 0.25, 0.50, 0.75, 1.0\n // then quantize (0.1, 0.7, 0.9) -> (0.0, 0.5, 1.0)\n\n color = color * n;\n color = floor(color);\n color = color / (n - 1.0);\n return color;\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n\n vec3 restrictedColor = quantize(color.rgb / color.a, filterParameter);\n\n gl_FragColor = vec4(restrictedColor.rgb * color.a, color.a);\n}\n'), _defineProperty(_filterShaderFrags, constants.OPAQUE, '// Set alpha channel to entirely opaque\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n gl_FragColor = vec4(color.rgb / color.a, 1.0);\n}\n'), _defineProperty(_filterShaderFrags, constants.INVERT, '// Set each pixel to inverse value\n// Note that original INVERT does not change the opacity, so this follows suit\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\n\nvoid main() {\nvec4 color = texture2D(tex0, vTexCoord);\nvec3 origColor = color.rgb / color.a;\nvec3 invertedColor = vec3(1.0) - origColor;\ngl_FragColor = vec4(invertedColor * color.a, color.a);\n}\n'), _defineProperty(_filterShaderFrags, constants.THRESHOLD, '// Convert pixels to either white or black, \n// depending on if their luma is above or below filterParameter\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform float filterParameter;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n return dot(color, vec3(0.2126, 0.7152, 0.0722));\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n float gray = luma(color.rgb / color.a);\n // floor() used to match src/image/filters.js\n float threshold = floor(filterParameter * 255.0) / 255.0;\n float blackOrWhite = step(threshold, gray);\n gl_FragColor = vec4(vec3(blackOrWhite) * color.a, color.a);\n}\n'), _filterShaderFrags); + var filterShaderVert = 'uniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\n// texcoords only come from p5 to vertex shader\n// so pass texcoords on to the fragment shader in a varying variable\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n // transferring texcoords for the frag shader\n vTexCoord = aTexCoord;\n\n // copy position with a fourth coordinate for projection (1.0 is normal)\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n'; + /** + * @module Rendering + * @submodule Rendering + * @for p5 + */ + /** + * Set attributes for the WebGL Drawing context. + * This is a way of adjusting how the WebGL + * renderer works to fine-tune the display and performance. + * + * Note that this will reinitialize the drawing context + * if called after the WebGL canvas is made. + * + * If an object is passed as the parameter, all attributes + * not declared in the object will be set to defaults. + * + * The available attributes are: + *
        + * alpha - indicates if the canvas contains an alpha buffer + * default is true + * + * depth - indicates whether the drawing buffer has a depth buffer + * of at least 16 bits - default is true + * + * stencil - indicates whether the drawing buffer has a stencil buffer + * of at least 8 bits + * + * antialias - indicates whether or not to perform anti-aliasing + * default is false (true in Safari) + * + * premultipliedAlpha - indicates that the page compositor will assume + * the drawing buffer contains colors with pre-multiplied alpha + * default is true + * + * preserveDrawingBuffer - if true the buffers will not be cleared and + * and will preserve their values until cleared or overwritten by author + * (note that p5 clears automatically on draw loop) + * default is true + * + * perPixelLighting - if true, per-pixel lighting will be used in the + * lighting shader otherwise per-vertex lighting is used. + * default is true. + * + * version - either 1 or 2, to specify which WebGL version to ask for. By + * default, WebGL 2 will be requested. If WebGL2 is not available, it will + * fall back to WebGL 1. You can check what version is used with by looking at + * the global `webglVersion` property. + * + * @method setAttributes + * @for p5 + * @param {String} key Name of attribute + * @param {Boolean} value New value of named attribute + * @example + *
        + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(255); + * push(); + * rotateZ(frameCount * 0.02); + * rotateX(frameCount * 0.02); + * rotateY(frameCount * 0.02); + * fill(0, 0, 0); + * box(50); + * pop(); + * } + * + *
        + *
        + * Now with the antialias attribute set to true. + *
        + *
        + * + * function setup() { + * setAttributes('antialias', true); + * createCanvas(100, 100, WEBGL); + * } + * + * function draw() { + * background(255); + * push(); + * rotateZ(frameCount * 0.02); + * rotateX(frameCount * 0.02); + * rotateY(frameCount * 0.02); + * fill(0, 0, 0); + * box(50); + * pop(); + * } + * + *
        + * + *
        + * + * // press the mouse button to disable perPixelLighting + * function setup() { + * createCanvas(100, 100, WEBGL); + * noStroke(); + * fill(255); + * } + * + * let lights = [ + * { c: '#f00', t: 1.12, p: 1.91, r: 0.2 }, + * { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 }, + * { c: '#00f', t: 1.37, p: 1.57, r: 0.2 }, + * { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 }, + * { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 }, + * { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 } + * ]; + * + * function draw() { + * let t = millis() / 1000 + 1000; + * background(0); + * directionalLight(color('#222'), 1, 1, 1); + * + * for (let i = 0; i < lights.length; i++) { + * let light = lights[i]; + * pointLight( + * color(light.c), + * p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r) + * ); + * } + * + * specularMaterial(255); + * sphere(width * 0.1); + * + * rotateX(t * 0.77); + * rotateY(t * 0.83); + * rotateZ(t * 0.91); + * torus(width * 0.3, width * 0.07, 24, 10); + * } + * + * function mousePressed() { + * setAttributes('perPixelLighting', false); + * noStroke(); + * fill(255); + * } + * function mouseReleased() { + * setAttributes('perPixelLighting', true); + * noStroke(); + * fill(255); + * } + * + *
        + * + * @alt a rotating cube with smoother edges + */ + /** + * @method setAttributes + * @for p5 + * @param {Object} obj object with key-value pairs + */ + _main.default.prototype.setAttributes = function (key, value) { + if (typeof this._glAttributes === 'undefined') { + console.log('You are trying to use setAttributes on a p5.Graphics object ' + 'that does not use a WEBGL renderer.'); + return; + } + var unchanged = true; + if (typeof value !== 'undefined') { + //first time modifying the attributes + if (this._glAttributes === null) { + this._glAttributes = { + }; + } + if (this._glAttributes[key] !== value) { + //changing value of previously altered attribute + this._glAttributes[key] = value; + unchanged = false; + } //setting all attributes with some change + + } else if (key instanceof Object) { + if (this._glAttributes !== key) { + this._glAttributes = key; + unchanged = false; + } + } //@todo_FES + + if (!this._renderer.isP3D || unchanged) { + return; + } + if (!this._setupDone) { + for (var x in this._renderer.retainedMode.geometry) { + if (this._renderer.retainedMode.geometry.hasOwnProperty(x)) { + _main.default._friendlyError('Sorry, Could not set the attributes, you need to call setAttributes() ' + 'before calling the other drawing methods in setup()'); + return; + } + } + } + this.push(); + this._renderer._resetContext(); + this.pop(); + if (this._renderer._curCamera) { + this._renderer._curCamera._renderer = this._renderer; + } + }; + /** + * @private + * @param {Uint8Array|Float32Array|undefined} pixels An existing pixels array to reuse if the size is the same + * @param {WebGLRenderingContext} gl The WebGL context + * @param {WebGLFramebuffer|null} framebuffer The Framebuffer to read + * @param {Number} x The x coordiante to read, premultiplied by pixel density + * @param {Number} y The y coordiante to read, premultiplied by pixel density + * @param {Number} width The width in pixels to be read (factoring in pixel density) + * @param {Number} height The height in pixels to be read (factoring in pixel density) + * @param {GLEnum} format Either RGB or RGBA depending on how many channels to read + * @param {GLEnum} type The datatype of each channel, e.g. UNSIGNED_BYTE or FLOAT + * @param {Number|undefined} flipY If provided, the total height with which to flip the y axis about + * @returns {Uint8Array|Float32Array} pixels A pixels array with the current state of the + * WebGL context read into it + */ + function readPixelsWebGL(pixels, gl, framebuffer, x, y, width, height, format, type, flipY) { + // Record the currently bound framebuffer so we can go back to it after, and + // bind the framebuffer we want to read from + var prevFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + var channels = format === gl.RGBA ? 4 : 3; + // Make a pixels buffer if it doesn't already exist + var len = width * height * channels; + var TypedArrayClass = type === gl.UNSIGNED_BYTE ? Uint8Array : Float32Array; + if (!(pixels instanceof TypedArrayClass) || pixels.length !== len) { + pixels = new TypedArrayClass(len); + } + gl.readPixels(x, flipY ? flipY - y - height : y, width, height, format, type, pixels); + // Re-bind whatever was previously bound + gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer); + if (flipY) { + // WebGL pixels are inverted compared to 2D pixels, so we have to flip + // the resulting rows. Adapted from https://stackoverflow.com/a/41973289 + var halfHeight = Math.floor(height / 2); + var tmpRow = new TypedArrayClass(width * channels); + for (var _y = 0; _y < halfHeight; _y++) { + var topOffset = _y * width * 4; + var bottomOffset = (height - _y - 1) * width * 4; + tmpRow.set(pixels.subarray(topOffset, topOffset + width * 4)); + pixels.copyWithin(topOffset, bottomOffset, bottomOffset + width * 4); + pixels.set(tmpRow, bottomOffset); + } + } + return pixels; + } /** + * @private + * @param {WebGLRenderingContext} gl The WebGL context + * @param {WebGLFramebuffer|null} framebuffer The Framebuffer to read + * @param {Number} x The x coordinate to read, premultiplied by pixel density + * @param {Number} y The y coordinate to read, premultiplied by pixel density + * @param {GLEnum} format Either RGB or RGBA depending on how many channels to read + * @param {GLEnum} type The datatype of each channel, e.g. UNSIGNED_BYTE or FLOAT + * @param {Number|undefined} flipY If provided, the total height with which to flip the y axis about + * @returns {Number[]} pixels The channel data for the pixel at that location + */ + + function readPixelWebGL(gl, framebuffer, x, y, format, type, flipY) { + // Record the currently bound framebuffer so we can go back to it after, and + // bind the framebuffer we want to read from + var prevFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + var channels = format === gl.RGBA ? 4 : 3; + var TypedArrayClass = type === gl.UNSIGNED_BYTE ? Uint8Array : Float32Array; + var pixels = new TypedArrayClass(channels); + gl.readPixels(x, flipY ? flipY - y - 1 : y, 1, 1, format, type, pixels); + // Re-bind whatever was previously bound + gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer); + return Array.from(pixels); + } /** + * 3D graphics class + * @private + * @class p5.RendererGL + * @constructor + * @extends p5.Renderer + * @todo extend class to include public method for offscreen + * rendering (FBO). + */ + + _main.default.RendererGL = /*#__PURE__*/ function (_p5$Renderer) { + _inherits(RendererGL, _p5$Renderer); + var _super = _createSuper(RendererGL); + function RendererGL(elt, pInst, isMainCanvas, attr) { + var _this; + _classCallCheck(this, RendererGL); + _this = _super.call(this, elt, pInst, isMainCanvas); + _this._setAttributeDefaults(pInst); + _this._initContext(); + _this.isP3D = true; //lets us know we're in 3d mode + // When constructing a new p5.Geometry, this will represent the builder + _this.geometryBuilder = undefined; + // This redundant property is useful in reminding you that you are + // interacting with WebGLRenderingContext, still worth considering future removal + _this.GL = _this.drawingContext; + _this._pInst._setProperty('drawingContext', _this.drawingContext); + // erasing + _this._isErasing = false; + // clipping + _this._clipDepths = [ + ]; + _this._isClipApplied = false; + _this._stencilTestOn = false; + // lights + _this._enableLighting = false; + _this.ambientLightColors = [ + ]; + _this.mixedAmbientLight = [ + ]; + _this.mixedSpecularColor = [ + ]; + _this.specularColors = [ + 1, + 1, + 1 + ]; + _this.directionalLightDirections = [ + ]; + _this.directionalLightDiffuseColors = [ + ]; + _this.directionalLightSpecularColors = [ + ]; + _this.pointLightPositions = [ + ]; + _this.pointLightDiffuseColors = [ + ]; + _this.pointLightSpecularColors = [ + ]; + _this.spotLightPositions = [ + ]; + _this.spotLightDirections = [ + ]; + _this.spotLightDiffuseColors = [ + ]; + _this.spotLightSpecularColors = [ + ]; + _this.spotLightAngle = [ + ]; + _this.spotLightConc = [ + ]; + // This property contains the input image if imageLight function + // is called. + // activeImageLight is checked by _setFillUniforms + // for sending uniforms to the fillshader + _this.activeImageLight = null; + // If activeImageLight property is Null, diffusedTextures, + // specularTextures are Empty. + // Else, it maps a p5.Image used by imageLight() to a p5.framebuffer. + // p5.framebuffer for this are calculated in getDiffusedTexture function + _this.diffusedTextures = new Map(); + // p5.framebuffer for this are calculated in getSpecularTexture function + _this.specularTextures = new Map(); + _this.drawMode = constants.FILL; + _this.curFillColor = _this._cachedFillStyle = [ + 1, + 1, + 1, + 1 + ]; + _this.curAmbientColor = _this._cachedFillStyle = [ + 1, + 1, + 1, + 1 + ]; + _this.curSpecularColor = _this._cachedFillStyle = [ + 0, + 0, + 0, + 0 + ]; + _this.curEmissiveColor = _this._cachedFillStyle = [ + 0, + 0, + 0, + 0 + ]; + _this.curStrokeColor = _this._cachedStrokeStyle = [ + 0, + 0, + 0, + 1 + ]; + _this.curBlendMode = constants.BLEND; + _this.preEraseBlend = undefined; + _this._cachedBlendMode = undefined; + if (_this.webglVersion === constants.WEBGL2) { + _this.blendExt = _this.GL; + } else { + _this.blendExt = _this.GL.getExtension('EXT_blend_minmax'); + } + _this._isBlending = false; + _this._hasSetAmbient = false; + _this._useSpecularMaterial = false; + _this._useEmissiveMaterial = false; + _this._useNormalMaterial = false; + _this._useShininess = 1; + _this._useMetalness = 0; + _this._useLineColor = false; + _this._useVertexColor = false; + _this.registerEnabled = new Set(); + _this._tint = [ + 255, + 255, + 255, + 255 + ]; + // lightFalloff variables + _this.constantAttenuation = 1; + _this.linearAttenuation = 0; + _this.quadraticAttenuation = 0; + /** + * model view, projection, & normal + * matrices + */ + _this.uMVMatrix = new _main.default.Matrix(); + _this.uPMatrix = new _main.default.Matrix(); + _this.uNMatrix = new _main.default.Matrix('mat3'); + _this.curMatrix = new _main.default.Matrix('mat3'); + // Current vertex normal + _this._currentNormal = new _main.default.Vector(0, 0, 1); + // Camera + _this._curCamera = new _main.default.Camera(_assertThisInitialized(_this)); + _this._curCamera._computeCameraDefaultSettings(); + _this._curCamera._setDefaultCamera(); + // FilterCamera + _this.filterCamera = new _main.default.Camera(_assertThisInitialized(_this)); + _this.filterCamera._computeCameraDefaultSettings(); + _this.filterCamera._setDefaultCamera(); + // Information about the previous frame's touch object + // for executing orbitControl() + _this.prevTouches = [ + ]; + // Velocity variable for use with orbitControl() + _this.zoomVelocity = 0; + _this.rotateVelocity = new _main.default.Vector(0, 0); + _this.moveVelocity = new _main.default.Vector(0, 0); + // Flags for recording the state of zooming, rotation and moving + _this.executeZoom = false; + _this.executeRotateAndMove = false; + _this.specularShader = undefined; + _this.sphereMapping = undefined; + _this.diffusedShader = undefined; + _this._defaultLightShader = undefined; + _this._defaultImmediateModeShader = undefined; + _this._defaultNormalShader = undefined; + _this._defaultColorShader = undefined; + _this._defaultPointShader = undefined; + _this.userFillShader = undefined; + _this.userStrokeShader = undefined; + _this.userPointShader = undefined; + // Default drawing is done in Retained Mode + // Geometry and Material hashes stored here + _this.retainedMode = { + geometry: { + }, + buffers: { + stroke: [ + new _main.default.RenderBuffer(4, 'lineVertexColors', 'lineColorBuffer', 'aVertexColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineVertices', 'lineVerticesBuffer', 'aPosition', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineTangentsIn', 'lineTangentsInBuffer', 'aTangentIn', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineTangentsOut', 'lineTangentsOutBuffer', 'aTangentOut', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(1, 'lineSides', 'lineSidesBuffer', 'aSide', _assertThisInitialized(_this)) + ], + fill: [ + new _main.default.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(3, 'vertexNormals', 'normalBuffer', 'aNormal', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(4, 'vertexColors', 'colorBuffer', 'aVertexColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'vertexAmbients', 'ambientBuffer', 'aAmbientColor', _assertThisInitialized(_this)), + //new BufferDef(3, 'vertexSpeculars', 'specularBuffer', 'aSpecularColor'), + new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', _assertThisInitialized(_this), _this._flatten) + ], + text: [ + new _main.default.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', _assertThisInitialized(_this), _this._flatten) + ] + } + }; + // Immediate Mode + // Geometry and Material hashes stored here + _this.immediateMode = { + geometry: new _main.default.Geometry(), + shapeMode: constants.TRIANGLE_FAN, + contourIndices: [ + ], + _bezierVertex: [ + ], + _quadraticVertex: [ + ], + _curveVertex: [ + ], + buffers: { + fill: [ + new _main.default.RenderBuffer(3, 'vertices', 'vertexBuffer', 'aPosition', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(3, 'vertexNormals', 'normalBuffer', 'aNormal', _assertThisInitialized(_this), _this._vToNArray), + new _main.default.RenderBuffer(4, 'vertexColors', 'colorBuffer', 'aVertexColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'vertexAmbients', 'ambientBuffer', 'aAmbientColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(2, 'uvs', 'uvBuffer', 'aTexCoord', _assertThisInitialized(_this), _this._flatten) + ], + stroke: [ + new _main.default.RenderBuffer(4, 'lineVertexColors', 'lineColorBuffer', 'aVertexColor', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineVertices', 'lineVerticesBuffer', 'aPosition', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineTangentsIn', 'lineTangentsInBuffer', 'aTangentIn', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(3, 'lineTangentsOut', 'lineTangentsOutBuffer', 'aTangentOut', _assertThisInitialized(_this)), + new _main.default.RenderBuffer(1, 'lineSides', 'lineSidesBuffer', 'aSide', _assertThisInitialized(_this)) + ], + point: _this.GL.createBuffer() + } + }; + _this.pointSize = 5; //default point size + _this.curStrokeWeight = 1; + _this.curStrokeCap = constants.ROUND; + _this.curStrokeJoin = constants.ROUND; + // map of texture sources to textures created in this gl context via this.getTexture(src) + _this.textures = new Map(); + // set of framebuffers in use + _this.framebuffers = new Set(); + // stack of active framebuffers + _this.activeFramebuffers = [ + ]; + // for post processing step + _this.filterShader = undefined; + _this.filterLayer = undefined; + _this.filterLayerTemp = undefined; + _this.defaultFilterShaders = { + }; + _this.textureMode = constants.IMAGE; + // default wrap settings + _this.textureWrapX = constants.CLAMP; + _this.textureWrapY = constants.CLAMP; + _this._tex = null; + _this._curveTightness = 6; + // lookUpTable for coefficients needed to be calculated for bezierVertex, same are used for curveVertex + _this._lookUpTableBezier = [ + ]; + // lookUpTable for coefficients needed to be calculated for quadraticVertex + _this._lookUpTableQuadratic = [ + ]; + // current curveDetail in the Bezier lookUpTable + _this._lutBezierDetail = 0; + // current curveDetail in the Quadratic lookUpTable + _this._lutQuadraticDetail = 0; + // Used to distinguish between user calls to vertex() and internal calls + _this.isProcessingVertices = false; + _this._tessy = _this._initTessy(); + _this.fontInfos = { + }; + _this._curShader = undefined; + return _this; + } /** + * Starts creating a new p5.Geometry. Subsequent shapes drawn will be added + * to the geometry and then returned when + * endGeometry() is called. One can also use + * buildGeometry() to pass a function that + * draws shapes. + * + * If you need to draw complex shapes every frame which don't change over time, + * combining them upfront with `beginGeometry()` and `endGeometry()` and then + * drawing that will run faster than repeatedly drawing the individual pieces. + * + * @method beginGeometry + */ + + _createClass(RendererGL, [ + { + key: 'beginGeometry', + value: function beginGeometry() { + if (this.geometryBuilder) { + throw new Error('It looks like `beginGeometry()` is being called while another p5.Geometry is already being build.'); + } + this.geometryBuilder = new _GeometryBuilder.default(this); + } /** + * Finishes creating a new p5.Geometry that was + * started using beginGeometry(). One can also + * use buildGeometry() to pass a function that + * draws shapes. + * + * @method endGeometry + * @returns {p5.Geometry} The model that was built. + */ + + }, + { + key: 'endGeometry', + value: function endGeometry() { + if (!this.geometryBuilder) { + throw new Error('Make sure you call beginGeometry() before endGeometry()!'); + } + var geometry = this.geometryBuilder.finish(); + this.geometryBuilder = undefined; + return geometry; + } /** + * Creates a new p5.Geometry that contains all + * the shapes drawn in a provided callback function. The returned combined shape + * can then be drawn all at once using model(). + * + * If you need to draw complex shapes every frame which don't change over time, + * combining them with `buildGeometry()` once and then drawing that will run + * faster than repeatedly drawing the individual pieces. + * + * One can also draw shapes directly between + * beginGeometry() and + * endGeometry() instead of using a callback + * function. + * + * @method buildGeometry + * @param {Function} callback A function that draws shapes. + * @returns {p5.Geometry} The model that was built from the callback function. + */ + + }, + { + key: 'buildGeometry', + value: function buildGeometry(callback) { + this.beginGeometry(); + callback(); + return this.endGeometry(); + } ////////////////////////////////////////////// + // Setting + ////////////////////////////////////////////// + + }, + { + key: '_setAttributeDefaults', + value: function _setAttributeDefaults(pInst) { + // See issue #3850, safer to enable AA in Safari + var applyAA = navigator.userAgent.toLowerCase().includes('safari'); + var defaults = { + alpha: true, + depth: true, + stencil: true, + antialias: applyAA, + premultipliedAlpha: true, + preserveDrawingBuffer: true, + perPixelLighting: true, + version: 2 + }; + if (pInst._glAttributes === null) { + pInst._glAttributes = defaults; + } else { + pInst._glAttributes = Object.assign(defaults, pInst._glAttributes); + } + return; + } + }, + { + key: '_initContext', + value: function _initContext() { + if (this._pInst._glAttributes.version !== 1) { + // Unless WebGL1 is explicitly asked for, try to create a WebGL2 context + this.drawingContext = this.canvas.getContext('webgl2', this._pInst._glAttributes); + } + this.webglVersion = this.drawingContext ? constants.WEBGL2 : constants.WEBGL; + // If this is the main canvas, make sure the global `webglVersion` is set + this._pInst._setProperty('webglVersion', this.webglVersion); + if (!this.drawingContext) { + // If we were unable to create a WebGL2 context (either because it was + // disabled via `setAttributes({ version: 1 })` or because the device + // doesn't support it), fall back to a WebGL1 context + this.drawingContext = this.canvas.getContext('webgl', this._pInst._glAttributes) || this.canvas.getContext('experimental-webgl', this._pInst._glAttributes); + } + if (this.drawingContext === null) { + throw new Error('Error creating webgl context'); + } else { + var gl = this.drawingContext; + gl.enable(gl.DEPTH_TEST); + gl.depthFunc(gl.LEQUAL); + gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); + // Make sure all images are loaded into the canvas premultiplied so that + // they match the way we render colors. This will make framebuffer textures + // be encoded the same way as textures from everything else. + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); + this._viewport = this.drawingContext.getParameter(this.drawingContext.VIEWPORT); + } + } + }, + { + key: '_getParam', + value: function _getParam() { + var gl = this.drawingContext; + return gl.getParameter(gl.MAX_TEXTURE_SIZE); + } + }, + { + key: '_adjustDimensions', + value: function _adjustDimensions(width, height) { + if (!this._maxTextureSize) { + this._maxTextureSize = this._getParam(); + } + var maxTextureSize = this._maxTextureSize; + var maxAllowedPixelDimensions = _main.default.prototype._maxAllowedPixelDimensions; + maxAllowedPixelDimensions = Math.floor(maxTextureSize / this.pixelDensity()); + var adjustedWidth = Math.min(width, maxAllowedPixelDimensions); + var adjustedHeight = Math.min(height, maxAllowedPixelDimensions); + if (adjustedWidth !== width || adjustedHeight !== height) { + console.warn('Warning: The requested width/height exceeds hardware limits. ' + 'Adjusting dimensions to width: '.concat(adjustedWidth, ', height: ').concat(adjustedHeight, '.')); + } + return { + adjustedWidth: adjustedWidth, + adjustedHeight: adjustedHeight + }; + } //This is helper function to reset the context anytime the attributes + //are changed with setAttributes() + + }, + { + key: '_resetContext', + value: function _resetContext(options, callback) { + var w = this.width; + var h = this.height; + var defaultId = this.canvas.id; + var isPGraphics = this._pInst instanceof _main.default.Graphics; + if (isPGraphics) { + var pg = this._pInst; + pg.canvas.parentNode.removeChild(pg.canvas); + pg.canvas = document.createElement('canvas'); + var node = pg._pInst._userNode || document.body; + node.appendChild(pg.canvas); + _main.default.Element.call(pg, pg.canvas, pg._pInst); + pg.width = w; + pg.height = h; + } else { + var c = this.canvas; + if (c) { + c.parentNode.removeChild(c); + } + c = document.createElement('canvas'); + c.id = defaultId; + if (this._pInst._userNode) { + this._pInst._userNode.appendChild(c); + } else { + document.body.appendChild(c); + } + this._pInst.canvas = c; + this.canvas = c; + } + var renderer = new _main.default.RendererGL(this._pInst.canvas, this._pInst, !isPGraphics); + this._pInst._setProperty('_renderer', renderer); + renderer.resize(w, h); + renderer._applyDefaults(); + if (!isPGraphics) { + this._pInst._elements.push(renderer); + } + if (typeof callback === 'function') { + //setTimeout with 0 forces the task to the back of the queue, this ensures that + //we finish switching out the renderer + setTimeout(function () { + callback.apply(window._renderer, options); + }, 0); + } + } /** + * @class p5.RendererGL + */ + + }, + { + key: '_update', + value: function _update() { + // reset model view and apply initial camera transform + // (containing only look at info; no projection). + this.uMVMatrix.set(this._curCamera.cameraMatrix); + // reset light data for new frame. + this.ambientLightColors.length = 0; + this.specularColors = [ + 1, + 1, + 1 + ]; + this.directionalLightDirections.length = 0; + this.directionalLightDiffuseColors.length = 0; + this.directionalLightSpecularColors.length = 0; + this.pointLightPositions.length = 0; + this.pointLightDiffuseColors.length = 0; + this.pointLightSpecularColors.length = 0; + this.spotLightPositions.length = 0; + this.spotLightDirections.length = 0; + this.spotLightDiffuseColors.length = 0; + this.spotLightSpecularColors.length = 0; + this.spotLightAngle.length = 0; + this.spotLightConc.length = 0; + this._enableLighting = false; + //reset tint value for new frame + this._tint = [ + 255, + 255, + 255, + 255 + ]; + //Clear depth every frame + this.GL.clearStencil(0); + this.GL.clear(this.GL.DEPTH_BUFFER_BIT | this.GL.STENCIL_BUFFER_BIT); + this.GL.disable(this.GL.STENCIL_TEST); + } /** + * [background description] + */ + + }, + { + key: 'background', + value: function background() { + var _this$_pInst; + var _col = (_this$_pInst = this._pInst).color.apply(_this$_pInst, arguments); + var _r = _col.levels[0] / 255; + var _g = _col.levels[1] / 255; + var _b = _col.levels[2] / 255; + var _a = _col.levels[3] / 255; + this.clear(_r, _g, _b, _a); + } ////////////////////////////////////////////// + // COLOR + ////////////////////////////////////////////// + /** + * Basic fill material for geometry with a given color + * @method fill + * @class p5.RendererGL + * @param {Number|Number[]|String|p5.Color} v1 gray value, + * red or hue value (depending on the current color mode), + * or color Array, or CSS color string + * @param {Number} [v2] green or saturation value + * @param {Number} [v3] blue or brightness value + * @param {Number} [a] opacity + * @chainable + * @example + *
        + * + * function setup() { + * createCanvas(200, 200, WEBGL); + * } + * + * function draw() { + * background(0); + * noStroke(); + * fill(100, 100, 240); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * box(75, 75, 75); + * } + * + *
        + * + * @alt + * black canvas with purple cube spinning + */ + + }, + { + key: 'fill', + value: function fill(v1, v2, v3, a) { + //see material.js for more info on color blending in webgl + var color = _main.default.prototype.color.apply(this._pInst, arguments); + this.curFillColor = color._array; + this.drawMode = constants.FILL; + this._useNormalMaterial = false; + this._tex = null; + } /** + * Basic stroke material for geometry with a given color + * @method stroke + * @param {Number|Number[]|String|p5.Color} v1 gray value, + * red or hue value (depending on the current color mode), + * or color Array, or CSS color string + * @param {Number} [v2] green or saturation value + * @param {Number} [v3] blue or brightness value + * @param {Number} [a] opacity + * @example + *
        + * + * function setup() { + * createCanvas(200, 200, WEBGL); + * } + * + * function draw() { + * background(0); + * stroke(240, 150, 150); + * fill(100, 100, 240); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * box(75, 75, 75); + * } + * + *
        + * + * @alt + * black canvas with purple cube with pink outline spinning + */ + + }, + { + key: 'stroke', + value: function stroke(r, g, b, a) { + var color = _main.default.prototype.color.apply(this._pInst, arguments); + this.curStrokeColor = color._array; + } + }, + { + key: 'strokeCap', + value: function strokeCap(cap) { + this.curStrokeCap = cap; + } + }, + { + key: 'strokeJoin', + value: function strokeJoin(join) { + this.curStrokeJoin = join; + } + }, + { + key: 'getFilterLayer', + value: function getFilterLayer() { + if (!this.filterLayer) { + this.filterLayer = this._pInst.createFramebuffer(); + } + return this.filterLayer; + } + }, + { + key: 'getFilterLayerTemp', + value: function getFilterLayerTemp() { + if (!this.filterLayerTemp) { + this.filterLayerTemp = this._pInst.createFramebuffer(); + } + return this.filterLayerTemp; + } + }, + { + key: 'matchSize', + value: function matchSize(fboToMatch, target) { + if (fboToMatch.width !== target.width || fboToMatch.height !== target.height) { + fboToMatch.resize(target.width, target.height); + } + if (fboToMatch.pixelDensity() !== target.pixelDensity()) { + fboToMatch.pixelDensity(target.pixelDensity()); + } + } + }, + { + key: 'filter', + value: function filter() { + var _this2 = this; + var fbo = this.getFilterLayer(); + // use internal shader for filter constants BLUR, INVERT, etc + var filterParameter = undefined; + var operation = undefined; + if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') { + var _defaults; + operation = arguments.length <= 0 ? undefined : arguments[0]; + var defaults = (_defaults = { + }, _defineProperty(_defaults, constants.BLUR, 3), _defineProperty(_defaults, constants.POSTERIZE, 4), _defineProperty(_defaults, constants.THRESHOLD, 0.5), _defaults); + var useDefaultParam = operation in defaults && (arguments.length <= 1 ? undefined : arguments[1]) === undefined; + filterParameter = useDefaultParam ? defaults[operation] : arguments.length <= 1 ? undefined : arguments[1]; + // Create and store shader for constants once on initial filter call. + // Need to store multiple in case user calls different filters, + // eg. filter(BLUR) then filter(GRAY) + if (!(operation in this.defaultFilterShaders)) { + this.defaultFilterShaders[operation] = new _main.default.Shader(fbo._renderer, filterShaderVert, filterShaderFrags[operation]); + } + this.filterShader = this.defaultFilterShaders[operation]; + } // use custom user-supplied shader + else { + this.filterShader = arguments.length <= 0 ? undefined : arguments[0]; + } // Setting the target to the framebuffer when applying a filter to a framebuffer. + + var target = this.activeFramebuffer() || this; + // Resize the framebuffer 'fbo' and adjust its pixel density if it doesn't match the target. + this.matchSize(fbo, target); + fbo.draw(function () { + return _this2._pInst.clear(); + }); // prevent undesirable feedback effects accumulating secretly. + var texelSize = [ + 1 / (target.width * target.pixelDensity()), + 1 / (target.height * target.pixelDensity()) + ]; + // apply blur shader with multiple passes. + if (operation === constants.BLUR) { + // Treating 'tmp' as a framebuffer. + var tmp = this.getFilterLayerTemp(); + // Resize the framebuffer 'tmp' and adjust its pixel density if it doesn't match the target. + this.matchSize(tmp, target); + // setup + this._pInst.push(); + this._pInst.noStroke(); + this._pInst.blendMode(constants.BLEND); + // draw main to temp buffer + this._pInst.shader(this.filterShader); + this.filterShader.setUniform('texelSize', texelSize); + this.filterShader.setUniform('canvasSize', [ + target.width, + target.height + ]); + this.filterShader.setUniform('radius', Math.max(1, filterParameter)); + // Horiz pass: draw `target` to `tmp` + tmp.draw(function () { + _this2.filterShader.setUniform('direction', [ + 1, + 0 + ]); + _this2.filterShader.setUniform('tex0', target); + _this2._pInst.clear(); + _this2._pInst.shader(_this2.filterShader); + _this2._pInst.noLights(); + _this2._pInst.plane(target.width, target.height); + }); + // Vert pass: draw `tmp` to `fbo` + fbo.draw(function () { + _this2.filterShader.setUniform('direction', [ + 0, + 1 + ]); + _this2.filterShader.setUniform('tex0', tmp); + _this2._pInst.clear(); + _this2._pInst.shader(_this2.filterShader); + _this2._pInst.noLights(); + _this2._pInst.plane(target.width, target.height); + }); + this._pInst.pop(); + } // every other non-blur shader uses single pass + else { + fbo.draw(function () { + _this2._pInst.noStroke(); + _this2._pInst.blendMode(constants.BLEND); + _this2._pInst.shader(_this2.filterShader); + _this2.filterShader.setUniform('tex0', target); + _this2.filterShader.setUniform('texelSize', texelSize); + _this2.filterShader.setUniform('canvasSize', [ + target.width, + target.height + ]); + // filterParameter uniform only used for POSTERIZE, and THRESHOLD + // but shouldn't hurt to always set + _this2.filterShader.setUniform('filterParameter', filterParameter); + _this2._pInst.noLights(); + _this2._pInst.plane(target.width, target.height); + }); + } // draw fbo contents onto main renderer. + + this._pInst.push(); + this._pInst.noStroke(); + this.clear(); + this._pInst.push(); + this._pInst.imageMode(constants.CORNER); + this._pInst.blendMode(constants.BLEND); + target.filterCamera._resize(); + this._pInst.setCamera(target.filterCamera); + this._pInst.resetMatrix(); + this._pInst.image(fbo, - target.width / 2, - target.height / 2, target.width, target.height); + this._pInst.clearDepth(); + this._pInst.pop(); + this._pInst.pop(); + } // Pass this off to the host instance so that we can treat a renderer and a + // framebuffer the same in filter() + + }, + { + key: 'pixelDensity', + value: function pixelDensity(newDensity) { + if (newDensity) { + return this._pInst.pixelDensity(newDensity); + } + return this._pInst.pixelDensity(); + } + }, + { + key: 'blendMode', + value: function blendMode(mode) { + if (mode === constants.DARKEST || mode === constants.LIGHTEST || mode === constants.ADD || mode === constants.BLEND || mode === constants.SUBTRACT || mode === constants.SCREEN || mode === constants.EXCLUSION || mode === constants.REPLACE || mode === constants.MULTIPLY || mode === constants.REMOVE) this.curBlendMode = mode; + else if (mode === constants.BURN || mode === constants.OVERLAY || mode === constants.HARD_LIGHT || mode === constants.SOFT_LIGHT || mode === constants.DODGE) { + console.warn('BURN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, and DODGE only work for blendMode in 2D mode.'); + } + } + }, + { + key: 'erase', + value: function erase(opacityFill, opacityStroke) { + if (!this._isErasing) { + this.preEraseBlend = this.curBlendMode; + this._isErasing = true; + this.blendMode(constants.REMOVE); + this._cachedFillStyle = this.curFillColor.slice(); + this.curFillColor = [ + 1, + 1, + 1, + opacityFill / 255 + ]; + this._cachedStrokeStyle = this.curStrokeColor.slice(); + this.curStrokeColor = [ + 1, + 1, + 1, + opacityStroke / 255 + ]; + } + } + }, + { + key: 'noErase', + value: function noErase() { + if (this._isErasing) { + // Restore colors + this.curFillColor = this._cachedFillStyle.slice(); + this.curStrokeColor = this._cachedStrokeStyle.slice(); + // Restore blend mode + this.curBlendMode = this.preEraseBlend; + this.blendMode(this.preEraseBlend); + // Ensure that _applyBlendMode() sets preEraseBlend back to the original blend mode + this._isErasing = false; + this._applyBlendMode(); + } + } + }, + { + key: 'drawTarget', + value: function drawTarget() { + return this.activeFramebuffers[this.activeFramebuffers.length - 1] || this; + } + }, + { + key: 'beginClip', + value: function beginClip() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + }; + _get(_getPrototypeOf(RendererGL.prototype), 'beginClip', this).call(this, options); + this.drawTarget()._isClipApplied = true; + var gl = this.GL; + gl.clearStencil(0); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.enable(gl.STENCIL_TEST); + this._stencilTestOn = true; + gl.stencilFunc(gl.ALWAYS, // the test + 1, // reference value + 255 // mask + ); + gl.stencilOp(gl.KEEP, // what to do if the stencil test fails + gl.KEEP, // what to do if the depth test fails + gl.REPLACE // what to do if both tests pass + ); + gl.disable(gl.DEPTH_TEST); + this._pInst.push(); + this._pInst.resetShader(); + if (this._doFill) this._pInst.fill(0, 0); + if (this._doStroke) this._pInst.stroke(0, 0); + } + }, + { + key: 'endClip', + value: function endClip() { + this._pInst.pop(); + var gl = this.GL; + gl.stencilOp(gl.KEEP, // what to do if the stencil test fails + gl.KEEP, // what to do if the depth test fails + gl.KEEP // what to do if both tests pass + ); + gl.stencilFunc(this._clipInvert ? gl.EQUAL : gl.NOTEQUAL, // the test + 0, // reference value + 255 // mask + ); + gl.enable(gl.DEPTH_TEST); + // Mark the depth at which the clip has been applied so that we can clear it + // when we pop past this depth + this._clipDepths.push(this._pushPopDepth); + _get(_getPrototypeOf(RendererGL.prototype), 'endClip', this).call(this); + } + }, + { + key: '_clearClip', + value: function _clearClip() { + this.GL.clearStencil(1); + this.GL.clear(this.GL.STENCIL_BUFFER_BIT); + if (this._clipDepths.length > 0) { + this._clipDepths.pop(); + } + this.drawTarget()._isClipApplied = false; + } /** + * Change weight of stroke + * @method strokeWeight + * @param {Number} stroke weight to be used for drawing + * @example + *
        + * + * function setup() { + * createCanvas(200, 400, WEBGL); + * setAttributes('antialias', true); + * } + * + * function draw() { + * background(0); + * noStroke(); + * translate(0, -100, 0); + * stroke(240, 150, 150); + * fill(100, 100, 240); + * push(); + * strokeWeight(8); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * sphere(75); + * pop(); + * push(); + * translate(0, 200, 0); + * strokeWeight(1); + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * sphere(75); + * pop(); + * } + * + *
        + * + * @alt + * black canvas with two purple rotating spheres with pink + * outlines the sphere on top has much heavier outlines, + */ + + }, + { + key: 'strokeWeight', + value: function strokeWeight(w) { + if (this.curStrokeWeight !== w) { + this.pointSize = w; + this.curStrokeWeight = w; + } + } // x,y are canvas-relative (pre-scaled by _pixelDensity) + + }, + { + key: '_getPixel', + value: function _getPixel(x, y) { + var gl = this.GL; + return readPixelWebGL(gl, null, x, y, gl.RGBA, gl.UNSIGNED_BYTE, this._pInst.height * this._pInst.pixelDensity()); + } /** + * Loads the pixels data for this canvas into the pixels[] attribute. + * Note that updatePixels() and set() do not work. + * Any pixel manipulation must be done directly to the pixels[] array. + * + * @private + * @method loadPixels + */ + + }, + { + key: 'loadPixels', + value: function loadPixels() { + var pixelsState = this._pixelsState; + //@todo_FES + if (this._pInst._glAttributes.preserveDrawingBuffer !== true) { + console.log('loadPixels only works in WebGL when preserveDrawingBuffer ' + 'is true.'); + return; + } + var pd = this._pInst._pixelDensity; + var gl = this.GL; + pixelsState._setProperty('pixels', readPixelsWebGL(pixelsState.pixels, gl, null, 0, 0, this.width * pd, this.height * pd, gl.RGBA, gl.UNSIGNED_BYTE, this.height * pd)); + } + }, + { + key: 'updatePixels', + value: function updatePixels() { + var fbo = this._getTempFramebuffer(); + fbo.pixels = this._pixelsState.pixels; + fbo.updatePixels(); + this._pInst.push(); + this._pInst.resetMatrix(); + this._pInst.clear(); + this._pInst.imageMode(constants.CENTER); + this._pInst.image(fbo, 0, 0); + this._pInst.pop(); + this.GL.clearDepth(1); + this.GL.clear(this.GL.DEPTH_BUFFER_BIT); + } /** + * @private + * @returns {p5.Framebuffer} A p5.Framebuffer set to match the size and settings + * of the renderer's canvas. It will be created if it does not yet exist, and + * reused if it does. + */ + + }, + { + key: '_getTempFramebuffer', + value: function _getTempFramebuffer() { + if (!this._tempFramebuffer) { + this._tempFramebuffer = this._pInst.createFramebuffer({ + format: constants.UNSIGNED_BYTE, + useDepth: this._pInst._glAttributes.depth, + depthFormat: constants.UNSIGNED_INT, + antialias: this._pInst._glAttributes.antialias + }); + } + return this._tempFramebuffer; + } ////////////////////////////////////////////// + // HASH | for geometry + ////////////////////////////////////////////// + + }, + { + key: 'geometryInHash', + value: function geometryInHash(gId) { + return this.retainedMode.geometry[gId] !== undefined; + } + }, + { + key: 'viewport', + value: function viewport(w, h) { + this._viewport = [ + 0, + 0, + w, + h + ]; + this.GL.viewport(0, 0, w, h); + } /** + * [resize description] + * @private + * @param {Number} w [description] + * @param {Number} h [description] + */ + + }, + { + key: 'resize', + value: function resize(w, h) { + _main.default.Renderer.prototype.resize.call(this, w, h); + this._origViewport = { + width: this.GL.drawingBufferWidth, + height: this.GL.drawingBufferHeight + }; + this.viewport(this._origViewport.width, this._origViewport.height); + this._curCamera._resize(); + //resize pixels buffer + var pixelsState = this._pixelsState; + if (typeof pixelsState.pixels !== 'undefined') { + pixelsState._setProperty('pixels', new Uint8Array(this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4)); + } + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.framebuffers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var framebuffer = _step.value; + // Notify framebuffers of the resize so that any auto-sized framebuffers + // can also update their size + framebuffer._canvasSizeChanged(); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } /** + * clears color and depth buffers + * with r,g,b,a + * @private + * @param {Number} r normalized red val. + * @param {Number} g normalized green val. + * @param {Number} b normalized blue val. + * @param {Number} a normalized alpha val. + */ + + }, + { + key: 'clear', + value: function clear() { + var _r = (arguments.length <= 0 ? undefined : arguments[0]) || 0; + var _g = (arguments.length <= 1 ? undefined : arguments[1]) || 0; + var _b = (arguments.length <= 2 ? undefined : arguments[2]) || 0; + var _a = (arguments.length <= 3 ? undefined : arguments[3]) || 0; + var activeFramebuffer = this.activeFramebuffer(); + if (activeFramebuffer && activeFramebuffer.format === constants.UNSIGNED_BYTE && !activeFramebuffer.antialias && _a === 0) { + // Drivers on Intel Macs check for 0,0,0,0 exactly when drawing to a + // framebuffer and ignore the command if it's the only drawing command to + // the framebuffer. To work around it, we can set the alpha to a value so + // low that it still rounds down to 0, but that circumvents the buggy + // check in the driver. + _a = 1e-10; + } + this.GL.clearColor(_r * _a, _g * _a, _b * _a, _a); + this.GL.clearDepth(1); + this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT); + } /** + * Resets all depth information so that nothing previously drawn will + * occlude anything subsequently drawn. + */ + + }, + { + key: 'clearDepth', + value: function clearDepth() { + var depth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + this.GL.clearDepth(depth); + this.GL.clear(this.GL.DEPTH_BUFFER_BIT); + } + }, + { + key: 'applyMatrix', + value: function applyMatrix(a, b, c, d, e, f) { + if (arguments.length === 16) { + _main.default.Matrix.prototype.apply.apply(this.uMVMatrix, arguments); + } else { + this.uMVMatrix.apply([a, + b, + 0, + 0, + c, + d, + 0, + 0, + 0, + 0, + 1, + 0, + e, + f, + 0, + 1]); + } + } /** + * [translate description] + * @private + * @param {Number} x [description] + * @param {Number} y [description] + * @param {Number} z [description] + * @chainable + * @todo implement handle for components or vector as args + */ + + }, + { + key: 'translate', + value: function translate(x, y, z) { + if (x instanceof _main.default.Vector) { + z = x.z; + y = x.y; + x = x.x; + } + this.uMVMatrix.translate([x, + y, + z]); + return this; + } /** + * Scales the Model View Matrix by a vector + * @private + * @param {Number | p5.Vector | Array} x [description] + * @param {Number} [y] y-axis scalar + * @param {Number} [z] z-axis scalar + * @chainable + */ + + }, + { + key: 'scale', + value: function scale(x, y, z) { + this.uMVMatrix.scale(x, y, z); + return this; + } + }, + { + key: 'rotate', + value: function rotate(rad, axis) { + if (typeof axis === 'undefined') { + return this.rotateZ(rad); + } + _main.default.Matrix.prototype.rotate.apply(this.uMVMatrix, arguments); + return this; + } + }, + { + key: 'rotateX', + value: function rotateX(rad) { + this.rotate(rad, 1, 0, 0); + return this; + } + }, + { + key: 'rotateY', + value: function rotateY(rad) { + this.rotate(rad, 0, 1, 0); + return this; + } + }, + { + key: 'rotateZ', + value: function rotateZ(rad) { + this.rotate(rad, 0, 0, 1); + return this; + } + }, + { + key: 'push', + value: function push() { + // get the base renderer style + var style = _main.default.Renderer.prototype.push.apply(this); + // add webgl-specific style properties + var properties = style.properties; + properties.uMVMatrix = this.uMVMatrix.copy(); + properties.uPMatrix = this.uPMatrix.copy(); + properties._curCamera = this._curCamera; + // make a copy of the current camera for the push state + // this preserves any references stored using 'createCamera' + this._curCamera = this._curCamera.copy(); + properties.ambientLightColors = this.ambientLightColors.slice(); + properties.specularColors = this.specularColors.slice(); + properties.directionalLightDirections = this.directionalLightDirections.slice(); + properties.directionalLightDiffuseColors = this.directionalLightDiffuseColors.slice(); + properties.directionalLightSpecularColors = this.directionalLightSpecularColors.slice(); + properties.pointLightPositions = this.pointLightPositions.slice(); + properties.pointLightDiffuseColors = this.pointLightDiffuseColors.slice(); + properties.pointLightSpecularColors = this.pointLightSpecularColors.slice(); + properties.spotLightPositions = this.spotLightPositions.slice(); + properties.spotLightDirections = this.spotLightDirections.slice(); + properties.spotLightDiffuseColors = this.spotLightDiffuseColors.slice(); + properties.spotLightSpecularColors = this.spotLightSpecularColors.slice(); + properties.spotLightAngle = this.spotLightAngle.slice(); + properties.spotLightConc = this.spotLightConc.slice(); + properties.userFillShader = this.userFillShader; + properties.userStrokeShader = this.userStrokeShader; + properties.userPointShader = this.userPointShader; + properties.pointSize = this.pointSize; + properties.curStrokeWeight = this.curStrokeWeight; + properties.curStrokeColor = this.curStrokeColor; + properties.curFillColor = this.curFillColor; + properties.curAmbientColor = this.curAmbientColor; + properties.curSpecularColor = this.curSpecularColor; + properties.curEmissiveColor = this.curEmissiveColor; + properties._hasSetAmbient = this._hasSetAmbient; + properties._useSpecularMaterial = this._useSpecularMaterial; + properties._useEmissiveMaterial = this._useEmissiveMaterial; + properties._useShininess = this._useShininess; + properties._useMetalness = this._useMetalness; + properties.constantAttenuation = this.constantAttenuation; + properties.linearAttenuation = this.linearAttenuation; + properties.quadraticAttenuation = this.quadraticAttenuation; + properties._enableLighting = this._enableLighting; + properties._useNormalMaterial = this._useNormalMaterial; + properties._tex = this._tex; + properties.drawMode = this.drawMode; + properties._currentNormal = this._currentNormal; + properties.curBlendMode = this.curBlendMode; + // So that the activeImageLight gets reset in push/pop + properties.activeImageLight = this.activeImageLight; + return style; + } + }, + { + key: 'pop', + value: function pop() { + var _get2; + if (this._clipDepths.length > 0 && this._pushPopDepth === this._clipDepths[this._clipDepths.length - 1]) { + this._clearClip(); + } + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + }(_get2 = _get(_getPrototypeOf(RendererGL.prototype), 'pop', this)).call.apply(_get2, [ + this + ].concat(args)); + this._applyStencilTestIfClipping(); + } + }, + { + key: '_applyStencilTestIfClipping', + value: function _applyStencilTestIfClipping() { + var drawTarget = this.drawTarget(); + if (drawTarget._isClipApplied !== this._stencilTestOn) { + if (drawTarget._isClipApplied) { + this.GL.enable(this.GL.STENCIL_TEST); + this._stencilTestOn = true; + } else { + this.GL.disable(this.GL.STENCIL_TEST); + this._stencilTestOn = false; + } + } + } + }, + { + key: 'resetMatrix', + value: function resetMatrix() { + this.uMVMatrix.set(this._curCamera.cameraMatrix); + return this; + } ////////////////////////////////////////////// + // SHADER + ////////////////////////////////////////////// + /* + * shaders are created and cached on a per-renderer basis, + * on the grounds that each renderer will have its own gl context + * and the shader must be valid in that context. + */ + + }, + { + key: '_getImmediateStrokeShader', + value: function _getImmediateStrokeShader() { + // select the stroke shader to use + var stroke = this.userStrokeShader; + if (!stroke || !stroke.isStrokeShader()) { + return this._getLineShader(); + } + return stroke; + } + }, + { + key: '_getRetainedStrokeShader', + value: function _getRetainedStrokeShader() { + return this._getImmediateStrokeShader(); + } + }, + { + key: '_getSphereMapping', + value: function _getSphereMapping(img) { + if (!this.sphereMapping) { + this.sphereMapping = this._pInst.createFilterShader(sphereMapping); + } + this.uNMatrix.inverseTranspose(this.uMVMatrix); + this.uNMatrix.invert3x3(this.uNMatrix); + this.sphereMapping.setUniform('uFovY', this._curCamera.cameraFOV); + this.sphereMapping.setUniform('uAspect', this._curCamera.aspectRatio); + this.sphereMapping.setUniform('uNewNormalMatrix', this.uNMatrix.mat3); + this.sphereMapping.setUniform('uSampler', img); + return this.sphereMapping; + } /* + * selects which fill shader should be used based on renderer state, + * for use with begin/endShape and immediate vertex mode. + */ + + }, + { + key: '_getImmediateFillShader', + value: function _getImmediateFillShader() { + var fill = this.userFillShader; + if (this._useNormalMaterial) { + if (!fill || !fill.isNormalShader()) { + return this._getNormalShader(); + } + } + if (this._enableLighting) { + if (!fill || !fill.isLightShader()) { + return this._getLightShader(); + } + } else if (this._tex) { + if (!fill || !fill.isTextureShader()) { + return this._getLightShader(); + } + } else if (!fill /*|| !fill.isColorShader()*/ ) { + return this._getImmediateModeShader(); + } + return fill; + } /* + * selects which fill shader should be used based on renderer state + * for retained mode. + */ + + }, + { + key: '_getRetainedFillShader', + value: function _getRetainedFillShader() { + if (this._useNormalMaterial) { + return this._getNormalShader(); + } + var fill = this.userFillShader; + if (this._enableLighting) { + if (!fill || !fill.isLightShader()) { + return this._getLightShader(); + } + } else if (this._tex) { + if (!fill || !fill.isTextureShader()) { + return this._getLightShader(); + } + } else if (!fill /* || !fill.isColorShader()*/ ) { + return this._getColorShader(); + } + return fill; + } + }, + { + key: '_getImmediatePointShader', + value: function _getImmediatePointShader() { + // select the point shader to use + var point = this.userPointShader; + if (!point || !point.isPointShader()) { + return this._getPointShader(); + } + return point; + } + }, + { + key: '_getRetainedLineShader', + value: function _getRetainedLineShader() { + return this._getImmediateLineShader(); + } + }, + { + key: '_getLightShader', + value: function _getLightShader() { + if (!this._defaultLightShader) { + if (this._pInst._glAttributes.perPixelLighting) { + this._defaultLightShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'highp') + defaultShaders.phongVert, this._webGL2CompatibilityPrefix('frag', 'highp') + defaultShaders.phongFrag); + } else { + this._defaultLightShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'highp') + defaultShaders.lightVert, this._webGL2CompatibilityPrefix('frag', 'highp') + defaultShaders.lightTextureFrag); + } + } + return this._defaultLightShader; + } + }, + { + key: '_getImmediateModeShader', + value: function _getImmediateModeShader() { + if (!this._defaultImmediateModeShader) { + this._defaultImmediateModeShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.immediateVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.vertexColorFrag); + } + return this._defaultImmediateModeShader; + } + }, + { + key: '_getNormalShader', + value: function _getNormalShader() { + if (!this._defaultNormalShader) { + this._defaultNormalShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.normalVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.normalFrag); + } + return this._defaultNormalShader; + } + }, + { + key: '_getColorShader', + value: function _getColorShader() { + if (!this._defaultColorShader) { + this._defaultColorShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.normalVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.basicFrag); + } + return this._defaultColorShader; + } + }, + { + key: '_getPointShader', + value: function _getPointShader() { + if (!this._defaultPointShader) { + this._defaultPointShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.pointVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.pointFrag); + } + return this._defaultPointShader; + } + }, + { + key: '_getLineShader', + value: function _getLineShader() { + if (!this._defaultLineShader) { + this._defaultLineShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.lineVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.lineFrag); + } + return this._defaultLineShader; + } + }, + { + key: '_getFontShader', + value: function _getFontShader() { + if (!this._defaultFontShader) { + if (this.webglVersion === constants.WEBGL) { + this.GL.getExtension('OES_standard_derivatives'); + } + this._defaultFontShader = new _main.default.Shader(this, this._webGL2CompatibilityPrefix('vert', 'mediump') + defaultShaders.fontVert, this._webGL2CompatibilityPrefix('frag', 'mediump') + defaultShaders.fontFrag); + } + return this._defaultFontShader; + } + }, + { + key: '_webGL2CompatibilityPrefix', + value: function _webGL2CompatibilityPrefix(shaderType, floatPrecision) { + var code = ''; + if (this.webglVersion === constants.WEBGL2) { + code += '#version 300 es\n#define WEBGL2\n'; + } + if (shaderType === 'vert') { + code += '#define VERTEX_SHADER\n'; + } else if (shaderType === 'frag') { + code += '#define FRAGMENT_SHADER\n'; + } + if (floatPrecision) { + code += 'precision '.concat(floatPrecision, ' float;\n'); + } + return code; + } + }, + { + key: '_getEmptyTexture', + value: function _getEmptyTexture() { + if (!this._emptyTexture) { + // a plain white texture RGBA, full alpha, single pixel. + var im = new _main.default.Image(1, 1); + im.set(0, 0, 255); + this._emptyTexture = new _main.default.Texture(this, im); + } + return this._emptyTexture; + } + }, + { + key: 'getTexture', + value: function getTexture(input) { + var src = input; + if (src instanceof _main.default.Framebuffer) { + src = src.color; + } + var texture = this.textures.get(src); + if (texture) { + return texture; + } + var tex = new _main.default.Texture(this, src); + this.textures.set(src, tex); + return tex; + } /* + * used in imageLight, + * To create a blurry image from the input non blurry img, if it doesn't already exist + * Add it to the diffusedTexture map, + * Returns the blurry image + * maps a p5.Image used by imageLight() to a p5.Framebuffer + */ + + }, + { + key: 'getDiffusedTexture', + value: function getDiffusedTexture(input) { + var _this3 = this; + // if one already exists for a given input image + if (this.diffusedTextures.get(input) != null) { + return this.diffusedTextures.get(input); + } // if not, only then create one + + var newFramebuffer; + // hardcoded to 200px, because it's going to be blurry and smooth + var smallWidth = 200; + var width = smallWidth; + var height = Math.floor(smallWidth * (input.height / input.width)); + newFramebuffer = this._pInst.createFramebuffer({ + width: width, + height: height, + density: 1 + }); + // create framebuffer is like making a new sketch, all functions on main + // sketch it would be available on framebuffer + if (!this.diffusedShader) { + this.diffusedShader = this._pInst.createShader(defaultShaders.imageLightVert, defaultShaders.imageLightDiffusedFrag); + } + newFramebuffer.draw(function () { + _this3._pInst.shader(_this3.diffusedShader); + _this3.diffusedShader.setUniform('environmentMap', input); + _this3._pInst.noStroke(); + _this3._pInst.rectMode(constants.CENTER); + _this3._pInst.noLights(); + _this3._pInst.rect(0, 0, width, height); + }); + this.diffusedTextures.set(input, newFramebuffer); + return newFramebuffer; + } /* + * used in imageLight, + * To create a texture from the input non blurry image, if it doesn't already exist + * Creating 8 different levels of textures according to different + * sizes and atoring them in `levels` array + * Creating a new Mipmap texture with that `levels` array + * Storing the texture for input image in map called `specularTextures` + * maps the input p5.Image to a p5.MipmapTexture + */ + + }, + { + key: 'getSpecularTexture', + value: function getSpecularTexture(input) { + var _this4 = this; + // check if already exits (there are tex of diff resolution so which one to check) + // currently doing the whole array + if (this.specularTextures.get(input) != null) { + return this.specularTextures.get(input); + } // Hardcoded size + + var size = 512; + var tex; + var levels = [ + ]; + var framebuffer = this._pInst.createFramebuffer({ + width: size, + height: size, + density: 1 + }); + var count = Math.log(size) / Math.log(2); + if (!this.specularShader) { + this.specularShader = this._pInst.createShader(defaultShaders.imageLightVert, defaultShaders.imageLightSpecularFrag); + } // currently only 8 levels + // This loop calculates 8 framebuffers of varying size of canvas + // and corresponding different roughness levels. + // Roughness increases with the decrease in canvas size, + // because rougher surfaces have less detailed/more blurry reflections. + + var _loop = function _loop(w) { + framebuffer.resize(w, w); + var currCount = Math.log(w) / Math.log(2); + var roughness = 1 - currCount / count; + framebuffer.draw(function () { + _this4._pInst.shader(_this4.specularShader); + _this4._pInst.clear(); + _this4.specularShader.setUniform('environmentMap', input); + _this4.specularShader.setUniform('roughness', roughness); + _this4._pInst.noStroke(); + _this4._pInst.noLights(); + _this4._pInst.plane(w, w); + }); + levels.push(framebuffer.get().drawingContext.getImageData(0, 0, w, w)); + }; + for (var w = size; w >= 1; w /= 2) { + _loop(w); + } // Free the Framebuffer + + framebuffer.remove(); + tex = new _p6.MipmapTexture(this, levels, { + }); + this.specularTextures.set(input, tex); + return tex; + } /** + * @method activeFramebuffer + * @private + * @returns {p5.Framebuffer|null} The currently active framebuffer, or null if + * the main canvas is the current draw target. + */ + + }, + { + key: 'activeFramebuffer', + value: function activeFramebuffer() { + return this.activeFramebuffers[this.activeFramebuffers.length - 1] || null; + } + }, + { + key: 'createFramebuffer', + value: function createFramebuffer(options) { + return new _main.default.Framebuffer(this, options); + } + }, + { + key: '_setStrokeUniforms', + value: function _setStrokeUniforms(strokeShader) { + strokeShader.bindShader(); + // set the uniform values + strokeShader.setUniform('uUseLineColor', this._useLineColor); + strokeShader.setUniform('uMaterialColor', this.curStrokeColor); + strokeShader.setUniform('uStrokeWeight', this.curStrokeWeight); + strokeShader.setUniform('uStrokeCap', STROKE_CAP_ENUM[this.curStrokeCap]); + strokeShader.setUniform('uStrokeJoin', STROKE_JOIN_ENUM[this.curStrokeJoin]); + } + }, + { + key: '_setFillUniforms', + value: function _setFillUniforms(fillShader) { + var _this5 = this; + fillShader.bindShader(); + this.mixedSpecularColor = _toConsumableArray(this.curSpecularColor); + if (this._useMetalness > 0) { + this.mixedSpecularColor = this.mixedSpecularColor.map(function (mixedSpecularColor, index) { + return _this5.curFillColor[index] * _this5._useMetalness + mixedSpecularColor * (1 - _this5._useMetalness); + }); + } // TODO: optimize + + fillShader.setUniform('uUseVertexColor', this._useVertexColor); + fillShader.setUniform('uMaterialColor', this.curFillColor); + fillShader.setUniform('isTexture', !!this._tex); + if (this._tex) { + fillShader.setUniform('uSampler', this._tex); + } + fillShader.setUniform('uTint', this._tint); + fillShader.setUniform('uHasSetAmbient', this._hasSetAmbient); + fillShader.setUniform('uAmbientMatColor', this.curAmbientColor); + fillShader.setUniform('uSpecularMatColor', this.mixedSpecularColor); + fillShader.setUniform('uEmissiveMatColor', this.curEmissiveColor); + fillShader.setUniform('uSpecular', this._useSpecularMaterial); + fillShader.setUniform('uEmissive', this._useEmissiveMaterial); + fillShader.setUniform('uShininess', this._useShininess); + fillShader.setUniform('metallic', this._useMetalness); + this._setImageLightUniforms(fillShader); + fillShader.setUniform('uUseLighting', this._enableLighting); + var pointLightCount = this.pointLightDiffuseColors.length / 3; + fillShader.setUniform('uPointLightCount', pointLightCount); + fillShader.setUniform('uPointLightLocation', this.pointLightPositions); + fillShader.setUniform('uPointLightDiffuseColors', this.pointLightDiffuseColors); + fillShader.setUniform('uPointLightSpecularColors', this.pointLightSpecularColors); + var directionalLightCount = this.directionalLightDiffuseColors.length / 3; + fillShader.setUniform('uDirectionalLightCount', directionalLightCount); + fillShader.setUniform('uLightingDirection', this.directionalLightDirections); + fillShader.setUniform('uDirectionalDiffuseColors', this.directionalLightDiffuseColors); + fillShader.setUniform('uDirectionalSpecularColors', this.directionalLightSpecularColors); + // TODO: sum these here... + var ambientLightCount = this.ambientLightColors.length / 3; + this.mixedAmbientLight = _toConsumableArray(this.ambientLightColors); + if (this._useMetalness > 0) { + this.mixedAmbientLight = this.mixedAmbientLight.map(function (ambientColors) { + var mixing = ambientColors - _this5._useMetalness; + return Math.max(0, mixing); + }); + } + fillShader.setUniform('uAmbientLightCount', ambientLightCount); + fillShader.setUniform('uAmbientColor', this.mixedAmbientLight); + var spotLightCount = this.spotLightDiffuseColors.length / 3; + fillShader.setUniform('uSpotLightCount', spotLightCount); + fillShader.setUniform('uSpotLightAngle', this.spotLightAngle); + fillShader.setUniform('uSpotLightConc', this.spotLightConc); + fillShader.setUniform('uSpotLightDiffuseColors', this.spotLightDiffuseColors); + fillShader.setUniform('uSpotLightSpecularColors', this.spotLightSpecularColors); + fillShader.setUniform('uSpotLightLocation', this.spotLightPositions); + fillShader.setUniform('uSpotLightDirection', this.spotLightDirections); + fillShader.setUniform('uConstantAttenuation', this.constantAttenuation); + fillShader.setUniform('uLinearAttenuation', this.linearAttenuation); + fillShader.setUniform('uQuadraticAttenuation', this.quadraticAttenuation); + fillShader.bindTextures(); + } // getting called from _setFillUniforms + + }, + { + key: '_setImageLightUniforms', + value: function _setImageLightUniforms(shader) { + //set uniform values + shader.setUniform('uUseImageLight', this.activeImageLight != null); + // true + if (this.activeImageLight) { + // this.activeImageLight has image as a key + // look up the texture from the diffusedTexture map + var diffusedLight = this.getDiffusedTexture(this.activeImageLight); + shader.setUniform('environmentMapDiffused', diffusedLight); + var specularLight = this.getSpecularTexture(this.activeImageLight); + // In p5js the range of shininess is >= 1, + // Therefore roughness range will be ([0,1]*8)*20 or [0, 160] + // The factor of 8 is because currently the getSpecularTexture + // only calculated 8 different levels of roughness + // The factor of 20 is just to spread up this range so that, + // [1, max] of shininess is converted to [0,160] of roughness + var roughness = 20 / this._useShininess; + shader.setUniform('levelOfDetail', roughness * 8); + shader.setUniform('environmentMapSpecular', specularLight); + } + } + }, + { + key: '_setPointUniforms', + value: function _setPointUniforms(pointShader) { + pointShader.bindShader(); + // set the uniform values + pointShader.setUniform('uMaterialColor', this.curStrokeColor); + // @todo is there an instance where this isn't stroke weight? + // should be they be same var? + pointShader.setUniform('uPointSize', this.pointSize * this._pInst._pixelDensity); + } /* Binds a buffer to the drawing context + * when passed more than two arguments it also updates or initializes + * the data associated with the buffer + */ + + }, + { + key: '_bindBuffer', + value: function _bindBuffer(buffer, target, values, type, usage) { + if (!target) target = this.GL.ARRAY_BUFFER; + this.GL.bindBuffer(target, buffer); + if (values !== undefined) { + var data = values; + if (values instanceof _main.default.DataArray) { + data = values.dataArray(); + } else if (!(data instanceof (type || Float32Array))) { + data = new (type || Float32Array) (data); + } + this.GL.bufferData(target, data, usage || this.GL.STATIC_DRAW); + } + } /////////////////////////////// + //// UTILITY FUNCTIONS + ////////////////////////////// + + }, + { + key: '_arraysEqual', + value: function _arraysEqual(a, b) { + var aLength = a.length; + if (aLength !== b.length) return false; + return a.every(function (ai, i) { + return ai === b[i]; + }); + } + }, + { + key: '_isTypedArray', + value: function _isTypedArray(arr) { + return [Float32Array, + Float64Array, + Int16Array, + Uint16Array, + Uint32Array].some(function (x) { + return arr instanceof x; + }); + } /** + * turn a two dimensional array into one dimensional array + * @private + * @param {Array} arr 2-dimensional array + * @return {Array} 1-dimensional array + * [[1, 2, 3],[4, 5, 6]] -> [1, 2, 3, 4, 5, 6] + */ + + }, + { + key: '_flatten', + value: function _flatten(arr) { + return arr.flat(); + } /** + * turn a p5.Vector Array into a one dimensional number array + * @private + * @param {p5.Vector[]} arr an array of p5.Vector + * @return {Number[]} a one dimensional array of numbers + * [p5.Vector(1, 2, 3), p5.Vector(4, 5, 6)] -> + * [1, 2, 3, 4, 5, 6] + */ + + }, + { + key: '_vToNArray', + value: function _vToNArray(arr) { + return arr.flatMap(function (item) { + return [item.x, + item.y, + item.z]; + }); + } // function to calculate BezierVertex Coefficients + + }, + { + key: '_bezierCoefficients', + value: function _bezierCoefficients(t) { + var t2 = t * t; + var t3 = t2 * t; + var mt = 1 - t; + var mt2 = mt * mt; + var mt3 = mt2 * mt; + return [mt3, + 3 * mt2 * t, + 3 * mt * t2, + t3]; + } // function to calculate QuadraticVertex Coefficients + + }, + { + key: '_quadraticCoefficients', + value: function _quadraticCoefficients(t) { + var t2 = t * t; + var mt = 1 - t; + var mt2 = mt * mt; + return [mt2, + 2 * mt * t, + t2]; + } // function to convert Bezier coordinates to Catmull Rom Splines + + }, + { + key: '_bezierToCatmull', + value: function _bezierToCatmull(w) { + var p1 = w[1]; + var p2 = w[1] + (w[2] - w[0]) / this._curveTightness; + var p3 = w[2] - (w[3] - w[1]) / this._curveTightness; + var p4 = w[2]; + var p = [ + p1, + p2, + p3, + p4 + ]; + return p; + } + }, + { + key: '_initTessy', + value: function _initTessy() { + // function called for each vertex of tesselator output + function vertexCallback(data, polyVertArray) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = data[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var element = _step2.value; + polyVertArray.push(element); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + function begincallback(type) { + if (type !== _libtess.default.primitiveType.GL_TRIANGLES) { + console.log('expected TRIANGLES but got type: '.concat(type)); + } + } + function errorcallback(errno) { + console.log('error callback'); + console.log('error number: '.concat(errno)); + } // callback for when segments intersect and must be split + + function combinecallback(coords, data, weight) { + var result = new Array(_main.default.RendererGL.prototype.tessyVertexSize).fill(0); + for (var i = 0; i < weight.length; i++) { + for (var j = 0; j < result.length; j++) { + if (weight[i] === 0 || !data[i]) continue; + result[j] += data[i][j] * weight[i]; + } + } + return result; + } + function edgeCallback(flag) { + // don't really care about the flag, but need no-strip/no-fan behavior + } + var tessy = new _libtess.default.GluTesselator(); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_VERTEX_DATA, vertexCallback); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_BEGIN, begincallback); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_ERROR, errorcallback); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_COMBINE, combinecallback); + tessy.gluTessCallback(_libtess.default.gluEnum.GLU_TESS_EDGE_FLAG, edgeCallback); + tessy.gluTessProperty(_libtess.default.gluEnum.GLU_TESS_WINDING_RULE, _libtess.default.windingRule.GLU_TESS_WINDING_NONZERO); + return tessy; + } + }, + { + key: '_triangulate', + value: function _triangulate(contours) { + // libtess will take 3d verts and flatten to a plane for tesselation. + // libtess is capable of calculating a plane to tesselate on, but + // if all of the vertices have the same z values, we'll just + // assume the face is facing the camera, letting us skip any performance + // issues or bugs in libtess's automatic calculation. + var z = contours[0] ? contours[0][2] : undefined; + var allSameZ = true; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = contours[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var contour = _step3.value; + for (var j = 0; j < contour.length; j += _main.default.RendererGL.prototype.tessyVertexSize) { + if (contour[j + 2] !== z) { + allSameZ = false; + break; + } + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + if (allSameZ) { + this._tessy.gluTessNormal(0, 0, 1); + } else { + // Let libtess pick a plane for us + this._tessy.gluTessNormal(0, 0, 0); + } + var triangleVerts = [ + ]; + this._tessy.gluTessBeginPolygon(triangleVerts); + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + try { + for (var _iterator4 = contours[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _contour = _step4.value; + this._tessy.gluTessBeginContour(); + for (var _j = 0; _j < _contour.length; _j += _main.default.RendererGL.prototype.tessyVertexSize) { + var coords = _contour.slice(_j, _j + _main.default.RendererGL.prototype.tessyVertexSize); + this._tessy.gluTessVertex(coords, coords); + } + this._tessy.gluTessEndContour(); + } // finish polygon + + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + this._tessy.gluTessEndPolygon(); + return triangleVerts; + } + } + ]); + return RendererGL; + }(_main.default.Renderer); + /** + * ensures that p5 is using a 3d renderer. throws an error if not. + */ + _main.default.prototype._assert3d = function (name) { + if (!this._renderer.isP3D) throw new Error(''.concat(name, '() is only supported in WEBGL mode. If you\'d like to use 3D graphics and WebGL, see https://p5js.org/examples/form-3d-primitives.html for more information.')); + }; + // function to initialize GLU Tesselator + _main.default.RendererGL.prototype.tessyVertexSize = 12; + var _default = _main.default.RendererGL; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + '../core/p5.Renderer': 306, + './GeometryBuilder': 347, + './p5.Camera': 352, + './p5.Framebuffer': 354, + './p5.Matrix': 356, + './p5.Shader': 361, + './p5.Texture': 362, + 'core-js/modules/es.array.concat': 170, + 'core-js/modules/es.array.copy-within': 171, + 'core-js/modules/es.array.every': 172, + 'core-js/modules/es.array.fill': 173, + 'core-js/modules/es.array.flat': 177, + 'core-js/modules/es.array.flat-map': 176, + 'core-js/modules/es.array.from': 179, + 'core-js/modules/es.array.includes': 180, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.map': 185, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.some': 187, + 'core-js/modules/es.array.unscopables.flat': 190, + 'core-js/modules/es.array.unscopables.flat-map': 189, + 'core-js/modules/es.map': 192, + 'core-js/modules/es.object.assign': 199, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.reflect.get': 208, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.set': 212, + 'core-js/modules/es.string.includes': 214, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.float32-array': 234, + 'core-js/modules/es.typed-array.float64-array': 235, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.int16-array': 239, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254, + 'core-js/modules/es.typed-array.uint16-array': 255, + 'core-js/modules/es.typed-array.uint32-array': 256, + 'core-js/modules/es.typed-array.uint8-array': 257, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261, + 'libtess': 274, + 'path': 277 + } + ], + 361: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.index-of'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.array.slice'); + _dereq_('core-js/modules/es.array.some'); + _dereq_('core-js/modules/es.function.name'); + _dereq_('core-js/modules/es.object.keys'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.default = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } /** + * This module defines the p5.Shader class + * @module 3D + * @submodule Material + * @for p5 + * @requires core + */ + /** + * A class to describe a shader program. + * + * Each `p5.Shader` object contains a shader program that runs on the graphics + * processing unit (GPU). Shaders can process many pixels or vertices at the + * same time, making them fast for many graphics tasks. They’re written in a + * language called + * GLSL + * and run along with the rest of the code in a sketch. + * + * A shader program consists of two files, a vertex shader and a fragment + * shader. The vertex shader affects where 3D geometry is drawn on the screen + * and the fragment shader affects color. Once the `p5.Shader` object is + * created, it can be used with the shader() + * function, as in `shader(myShader)`. + * + * Note: createShader(), + * createFilterShader(), and + * loadShader() are the recommended ways to + * create an instance of this class. + * + * @class p5.Shader + * @constructor + * @param {p5.RendererGL} renderer WebGL context for this shader. + * @param {String} vertSrc source code for the vertex shader program. + * @param {String} fragSrc source code for the fragment shader program. + * + * @example + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision highp float; + * + * void main() { + * // Set each pixel's RGBA value to yellow. + * gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0); + * } + * `; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * let myShader = createShader(vertSrc, fragSrc); + * + * // Apply the p5.Shader object. + * shader(myShader); + * + * // Style the drawing surface. + * noStroke(); + * + * // Add a plane as a drawing surface. + * plane(100, 100); + * + * describe('A yellow square.'); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * let mandelbrot; + * + * // Load the shader and create a p5.Shader object. + * function preload() { + * mandelbrot = loadShader('assets/shader.vert', 'assets/shader.frag'); + * } + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Use the p5.Shader object. + * shader(mandelbrot); + * + * // Set the shader uniform p to an array. + * mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); + * + * describe('A fractal image zooms in and out of focus.'); + * } + * + * function draw() { + * // Set the shader uniform r to a value that oscillates between 0 and 2. + * mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1); + * + * // Add a quad as a display surface for the shader. + * quad(-1, -1, 1, -1, 1, 1, -1, 1); + * } + * + *
        + */ + + _main.default.Shader = /*#__PURE__*/ function () { + function _class(renderer, vertSrc, fragSrc) { + _classCallCheck(this, _class); + // TODO: adapt this to not take ids, but rather, + // to take the source for a vertex and fragment shader + // to enable custom shaders at some later date + this._renderer = renderer; + this._vertSrc = vertSrc; + this._fragSrc = fragSrc; + this._vertShader = - 1; + this._fragShader = - 1; + this._glProgram = 0; + this._loadedAttributes = false; + this.attributes = { + }; + this._loadedUniforms = false; + this.uniforms = { + }; + this._bound = false; + this.samplers = [ + ]; + } /** + * Creates, compiles, and links the shader based on its + * sources for the vertex and fragment shaders (provided + * to the constructor). Populates known attributes and + * uniforms from the shader. + * @method init + * @chainable + * @private + */ + + _createClass(_class, [ + { + key: 'init', + value: function init() { + if (this._glProgram === 0 /* or context is stale? */ ) { + var gl = this._renderer.GL; + // @todo: once custom shading is allowed, + // friendly error messages should be used here to share + // compiler and linker errors. + //set up the shader by + // 1. creating and getting a gl id for the shader program, + // 2. compliling its vertex & fragment sources, + // 3. linking the vertex and fragment shaders + this._vertShader = gl.createShader(gl.VERTEX_SHADER); + //load in our default vertex shader + gl.shaderSource(this._vertShader, this._vertSrc); + gl.compileShader(this._vertShader); + // if our vertex shader failed compilation? + if (!gl.getShaderParameter(this._vertShader, gl.COMPILE_STATUS)) { + _main.default._friendlyError('Yikes! An error occurred compiling the vertex shader:'.concat(gl.getShaderInfoLog(this._vertShader))); + return null; + } + this._fragShader = gl.createShader(gl.FRAGMENT_SHADER); + //load in our material frag shader + gl.shaderSource(this._fragShader, this._fragSrc); + gl.compileShader(this._fragShader); + // if our frag shader failed compilation? + if (!gl.getShaderParameter(this._fragShader, gl.COMPILE_STATUS)) { + _main.default._friendlyError('Darn! An error occurred compiling the fragment shader:'.concat(gl.getShaderInfoLog(this._fragShader))); + return null; + } + this._glProgram = gl.createProgram(); + gl.attachShader(this._glProgram, this._vertShader); + gl.attachShader(this._glProgram, this._fragShader); + gl.linkProgram(this._glProgram); + if (!gl.getProgramParameter(this._glProgram, gl.LINK_STATUS)) { + _main.default._friendlyError('Snap! Error linking shader program: '.concat(gl.getProgramInfoLog(this._glProgram))); + } + this._loadAttributes(); + this._loadUniforms(); + } + return this; + } /** + * Copies the shader from one drawing context to another. + * + * Each `p5.Shader` object must be compiled by calling + * shader() before it can run. Compilation happens + * in a drawing context which is usually the main canvas or an instance of + * p5.Graphics. A shader can only be used in the + * context where it was compiled. The `copyToContext()` method compiles the + * shader again and copies it to another drawing context where it can be + * reused. + * + * The parameter, `context`, is the drawing context where the shader will be + * used. The shader can be copied to an instance of + * p5.Graphics, as in + * `myShader.copyToContext(pg)`. The shader can also be copied from a + * p5.Graphics object to the main canvas using + * the `window` variable, as in `myShader.copyToContext(window)`. + * + * Note: A p5.Shader object created with + * createShader(), + * createFilterShader(), or + * loadShader() + * can be used directly with a p5.Framebuffer + * object created with + * createFramebuffer(). Both objects + * have the same context as the main canvas. + * + * @method copyToContext + * @param {p5|p5.Graphics} context WebGL context for the copied shader. + * @returns {p5.Shader} new shader compiled for the target context. + * + * @example + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision mediump float; + * varying vec2 vTexCoord; + * + * void main() { + * vec2 uv = vTexCoord; + * vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0)); + * gl_FragColor = vec4(color, 1.0);\ + * } + * `; + * + * let pg; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * background(200); + * + * // Create a p5.Shader object. + * let original = createShader(vertSrc, fragSrc); + * + * // Compile the p5.Shader object. + * shader(original); + * + * // Create a p5.Graphics object. + * pg = createGraphics(50, 50, WEBGL); + * + * // Copy the original shader to the p5.Graphics object. + * let copied = original.copyToContext(pg); + * + * // Apply the copied shader to the p5.Graphics object. + * pg.shader(copied); + * + * // Style the display surface. + * pg.noStroke(); + * + * // Add a display surface for the shader. + * pg.plane(50, 50); + * + * describe('A square with purple-blue gradient on its surface drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Draw the p5.Graphics object to the main canvas. + * image(pg, -25, -25); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision mediump float; + * + * varying vec2 vTexCoord; + * + * void main() { + * vec2 uv = vTexCoord; + * vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0)); + * gl_FragColor = vec4(color, 1.0); + * } + * `; + * + * let copied; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Graphics object. + * let pg = createGraphics(25, 25, WEBGL); + * + * // Create a p5.Shader object. + * let original = pg.createShader(vertSrc, fragSrc); + * + * // Compile the p5.Shader object. + * pg.shader(original); + * + * // Copy the original shader to the main canvas. + * copied = original.copyToContext(window); + * + * // Apply the copied shader to the main canvas. + * shader(copied); + * + * describe('A rotating cube with a purple-blue gradient on its surface drawn against a gray background.'); + * } + * + * function draw() { + * background(200); + * + * // Rotate around the x-, y-, and z-axes. + * rotateX(frameCount * 0.01); + * rotateY(frameCount * 0.01); + * rotateZ(frameCount * 0.01); + * + * // Draw the box. + * box(50); + * } + * + *
        + */ + + }, + { + key: 'copyToContext', + value: function copyToContext(context) { + var shader = new _main.default.Shader(context._renderer, this._vertSrc, this._fragSrc); + shader.ensureCompiledOnContext(context); + return shader; + } /** + * @private + */ + + }, + { + key: 'ensureCompiledOnContext', + value: function ensureCompiledOnContext(context) { + if (this._glProgram !== 0 && this._renderer !== context._renderer) { + throw new Error('The shader being run is attached to a different context. Do you need to copy it to this context first with .copyToContext()?'); + } else if (this._glProgram === 0) { + this._renderer = context._renderer; + this.init(); + } + } /** + * Queries the active attributes for this shader and loads + * their names and locations into the attributes array. + * @method _loadAttributes + * @private + */ + + }, + { + key: '_loadAttributes', + value: function _loadAttributes() { + if (this._loadedAttributes) { + return; + } + this.attributes = { + }; + var gl = this._renderer.GL; + var numAttributes = gl.getProgramParameter(this._glProgram, gl.ACTIVE_ATTRIBUTES); + for (var i = 0; i < numAttributes; ++i) { + var attributeInfo = gl.getActiveAttrib(this._glProgram, i); + var name = attributeInfo.name; + var location = gl.getAttribLocation(this._glProgram, name); + var attribute = { + }; + attribute.name = name; + attribute.location = location; + attribute.index = i; + attribute.type = attributeInfo.type; + attribute.size = attributeInfo.size; + this.attributes[name] = attribute; + } + this._loadedAttributes = true; + } /** + * Queries the active uniforms for this shader and loads + * their names and locations into the uniforms array. + * @method _loadUniforms + * @private + */ + + }, + { + key: '_loadUniforms', + value: function _loadUniforms() { + if (this._loadedUniforms) { + return; + } + var gl = this._renderer.GL; + // Inspect shader and cache uniform info + var numUniforms = gl.getProgramParameter(this._glProgram, gl.ACTIVE_UNIFORMS); + var samplerIndex = 0; + for (var i = 0; i < numUniforms; ++i) { + var uniformInfo = gl.getActiveUniform(this._glProgram, i); + var uniform = { + }; + uniform.location = gl.getUniformLocation(this._glProgram, uniformInfo.name); + uniform.size = uniformInfo.size; + var uniformName = uniformInfo.name; + //uniforms that are arrays have their name returned as + //someUniform[0] which is a bit silly so we trim it + //off here. The size property tells us that its an array + //so we dont lose any information by doing this + if (uniformInfo.size > 1) { + uniformName = uniformName.substring(0, uniformName.indexOf('[0]')); + } + uniform.name = uniformName; + uniform.type = uniformInfo.type; + uniform._cachedData = undefined; + if (uniform.type === gl.SAMPLER_2D) { + uniform.samplerIndex = samplerIndex; + samplerIndex++; + this.samplers.push(uniform); + } + uniform.isArray = uniformInfo.size > 1 || uniform.type === gl.FLOAT_MAT3 || uniform.type === gl.FLOAT_MAT4 || uniform.type === gl.FLOAT_VEC2 || uniform.type === gl.FLOAT_VEC3 || uniform.type === gl.FLOAT_VEC4 || uniform.type === gl.INT_VEC2 || uniform.type === gl.INT_VEC4 || uniform.type === gl.INT_VEC3; + this.uniforms[uniformName] = uniform; + } + this._loadedUniforms = true; + } + }, + { + key: 'compile', + value: function compile() { + // TODO + } /** + * initializes (if needed) and binds the shader program. + * @method bindShader + * @private + */ + + }, + { + key: 'bindShader', + value: function bindShader() { + this.init(); + if (!this._bound) { + this.useProgram(); + this._bound = true; + this._setMatrixUniforms(); + this.setUniform('uViewport', this._renderer._viewport); + } + } /** + * @method unbindShader + * @chainable + * @private + */ + + }, + { + key: 'unbindShader', + value: function unbindShader() { + if (this._bound) { + this.unbindTextures(); + //this._renderer.GL.useProgram(0); ?? + this._bound = false; + } + return this; + } + }, + { + key: 'bindTextures', + value: function bindTextures() { + var gl = this._renderer.GL; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = this.samplers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var uniform = _step.value; + var tex = uniform.texture; + if (tex === undefined) { + // user hasn't yet supplied a texture for this slot. + // (or there may not be one--maybe just lighting), + // so we supply a default texture instead. + tex = this._renderer._getEmptyTexture(); + } + gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex); + tex.bindTexture(); + tex.update(); + gl.uniform1i(uniform.location, uniform.samplerIndex); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, + { + key: 'updateTextures', + value: function updateTextures() { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = this.samplers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var uniform = _step2.value; + var tex = uniform.texture; + if (tex) { + tex.update(); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + }, + { + key: 'unbindTextures', + value: function unbindTextures() { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = this.samplers[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var uniform = _step3.value; + this.setUniform(uniform.name, this._renderer._getEmptyTexture()); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + }, + { + key: '_setMatrixUniforms', + value: function _setMatrixUniforms() { + var viewMatrix = this._renderer._curCamera.cameraMatrix; + var projectionMatrix = this._renderer.uPMatrix; + var modelViewMatrix = this._renderer.uMVMatrix; + var modelViewProjectionMatrix = modelViewMatrix.copy(); + modelViewProjectionMatrix.mult(projectionMatrix); + if (this.isStrokeShader()) { + this.setUniform('uPerspective', this._renderer._curCamera.useLinePerspective ? 1 : 0); + } + this.setUniform('uViewMatrix', viewMatrix.mat4); + this.setUniform('uProjectionMatrix', projectionMatrix.mat4); + this.setUniform('uModelViewMatrix', modelViewMatrix.mat4); + this.setUniform('uModelViewProjectionMatrix', modelViewProjectionMatrix.mat4); + if (this.uniforms.uNormalMatrix) { + this._renderer.uNMatrix.inverseTranspose(this._renderer.uMVMatrix); + this.setUniform('uNormalMatrix', this._renderer.uNMatrix.mat3); + } + if (this.uniforms.uCameraRotation) { + this._renderer.curMatrix.inverseTranspose(this._renderer._curCamera.cameraMatrix); + this.setUniform('uCameraRotation', this._renderer.curMatrix.mat3); + } + } /** + * @method useProgram + * @chainable + * @private + */ + + }, + { + key: 'useProgram', + value: function useProgram() { + var gl = this._renderer.GL; + if (this._renderer._curShader !== this) { + gl.useProgram(this._glProgram); + this._renderer._curShader = this; + } + return this; + } /** + * Sets the shader’s uniform (global) variables. + * + * Shader programs run on the computer’s graphics processing unit (GPU). + * They live in part of the computer’s memory that’s completely separate + * from the sketch that runs them. Uniforms are global variables within a + * shader program. They provide a way to pass values from a sketch running + * on the CPU to a shader program running on the GPU. + * + * The first parameter, `uniformName`, is a string with the uniform’s name. + * For the shader above, `uniformName` would be `'r'`. + * + * The second parameter, `data`, is the value that should be used to set the + * uniform. For example, calling `myShader.setUniform('r', 0.5)` would set + * the `r` uniform in the shader above to `0.5`. data should match the + * uniform’s type. Numbers, strings, booleans, arrays, and many types of + * images can all be passed to a shader with `setUniform()`. + * + * @method setUniform + * @chainable + * @param {String} uniformName name of the uniform. Must match the name + * used in the vertex and fragment shaders. + * @param {Boolean|Number|Number[]|p5.Image|p5.Graphics|p5.MediaElement|p5.Texture} + * data value to assign to the uniform. Must match the uniform’s data type. + * + * @example + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision mediump float; + * + * uniform float r; + * + * void main() { + * gl_FragColor = vec4(r, 1.0, 1.0, 1.0); + * } + * `; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * let myShader = createShader(vertSrc, fragSrc); + * + * // Apply the p5.Shader object. + * shader(myShader); + * + * // Set the r uniform to 0.5. + * myShader.setUniform('r', 0.5); + * + * // Style the drawing surface. + * noStroke(); + * + * // Add a plane as a drawing surface for the shader. + * plane(100, 100); + * + * describe('A cyan square.'); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision mediump float; + * + * uniform float r; + * + * void main() { + * gl_FragColor = vec4(r, 1.0, 1.0, 1.0); + * } + * `; + * + * let myShader; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * myShader = createShader(vertSrc, fragSrc); + * + * // Compile and apply the p5.Shader object. + * shader(myShader); + * + * describe('A square oscillates color between cyan and white.'); + * } + * + * function draw() { + * background(200); + * + * // Style the drawing surface. + * noStroke(); + * + * // Update the r uniform. + * let nextR = 0.5 * (sin(frameCount * 0.01) + 1); + * myShader.setUniform('r', nextR); + * + * // Add a plane as a drawing surface. + * plane(100, 100); + * } + * + *
        + * + *
        + * + * // Note: A "uniform" is a global variable within a shader program. + * + * // Create a string with the vertex shader program. + * // The vertex shader is called for each vertex. + * let vertSrc = ` + * precision highp float; + * uniform mat4 uModelViewMatrix; + * uniform mat4 uProjectionMatrix; + * + * attribute vec3 aPosition; + * attribute vec2 aTexCoord; + * varying vec2 vTexCoord; + * + * void main() { + * vTexCoord = aTexCoord; + * vec4 positionVec4 = vec4(aPosition, 1.0); + * gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4; + * } + * `; + * + * // Create a string with the fragment shader program. + * // The fragment shader is called for each pixel. + * let fragSrc = ` + * precision highp float; + * uniform vec2 p; + * uniform float r; + * const int numIterations = 500; + * varying vec2 vTexCoord; + * + * void main() { + * vec2 c = p + gl_FragCoord.xy * r; + * vec2 z = c; + * float n = 0.0; + * + * for (int i = numIterations; i > 0; i--) { + * if (z.x * z.x + z.y * z.y > 4.0) { + * n = float(i) / float(numIterations); + * break; + * } + * + * z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c; + * } + * + * gl_FragColor = vec4( + * 0.5 - cos(n * 17.0) / 2.0, + * 0.5 - cos(n * 13.0) / 2.0, + * 0.5 - cos(n * 23.0) / 2.0, + * 1.0 + * ); + * } + * `; + * + * let mandelbrot; + * + * function setup() { + * createCanvas(100, 100, WEBGL); + * + * // Create a p5.Shader object. + * mandelbrot = createShader(vertSrc, fragSrc); + * + * // Compile and apply the p5.Shader object. + * shader(mandelbrot); + * + * // Set the shader uniform p to an array. + * // p is the center point of the Mandelbrot image. + * mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]); + * + * describe('A fractal image zooms in and out of focus.'); + * } + * + * function draw() { + * // Set the shader uniform r to a value that oscillates + * // between 0 and 0.005. + * // r is the size of the image in Mandelbrot-space. + * let radius = 0.005 * (sin(frameCount * 0.01) + 1); + * mandelbrot.setUniform('r', radius); + * + * // Style the drawing surface. + * noStroke(); + * + * // Add a plane as a drawing surface. + * plane(100, 100); + * } + * + *
        + */ + + }, + { + key: 'setUniform', + value: function setUniform(uniformName, data) { + var uniform = this.uniforms[uniformName]; + if (!uniform) { + return; + } + var gl = this._renderer.GL; + if (uniform.isArray) { + if (uniform._cachedData && this._renderer._arraysEqual(uniform._cachedData, data)) { + return; + } else { + uniform._cachedData = data.slice(0); + } + } else if (uniform._cachedData && uniform._cachedData === data) { + return; + } else { + if (Array.isArray(data)) { + uniform._cachedData = data.slice(0); + } else { + uniform._cachedData = data; + } + } + var location = uniform.location; + this.useProgram(); + switch (uniform.type) { + case gl.BOOL: + if (data === true) { + gl.uniform1i(location, 1); + } else { + gl.uniform1i(location, 0); + } + break; + case gl.INT: + if (uniform.size > 1) { + data.length && gl.uniform1iv(location, data); + } else { + gl.uniform1i(location, data); + } + break; + case gl.FLOAT: + if (uniform.size > 1) { + data.length && gl.uniform1fv(location, data); + } else { + gl.uniform1f(location, data); + } + break; + case gl.FLOAT_MAT3: + gl.uniformMatrix3fv(location, false, data); + break; + case gl.FLOAT_MAT4: + gl.uniformMatrix4fv(location, false, data); + break; + case gl.FLOAT_VEC2: + if (uniform.size > 1) { + data.length && gl.uniform2fv(location, data); + } else { + gl.uniform2f(location, data[0], data[1]); + } + break; + case gl.FLOAT_VEC3: + if (uniform.size > 1) { + data.length && gl.uniform3fv(location, data); + } else { + gl.uniform3f(location, data[0], data[1], data[2]); + } + break; + case gl.FLOAT_VEC4: + if (uniform.size > 1) { + data.length && gl.uniform4fv(location, data); + } else { + gl.uniform4f(location, data[0], data[1], data[2], data[3]); + } + break; + case gl.INT_VEC2: + if (uniform.size > 1) { + data.length && gl.uniform2iv(location, data); + } else { + gl.uniform2i(location, data[0], data[1]); + } + break; + case gl.INT_VEC3: + if (uniform.size > 1) { + data.length && gl.uniform3iv(location, data); + } else { + gl.uniform3i(location, data[0], data[1], data[2]); + } + break; + case gl.INT_VEC4: + if (uniform.size > 1) { + data.length && gl.uniform4iv(location, data); + } else { + gl.uniform4i(location, data[0], data[1], data[2], data[3]); + } + break; + case gl.SAMPLER_2D: + gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex); + uniform.texture = data instanceof _main.default.Texture ? data : this._renderer.getTexture(data); + gl.uniform1i(location, uniform.samplerIndex); + if (uniform.texture.src.gifProperties) { + uniform.texture.src._animateGif(this._renderer._pInst); + } + break; + //@todo complete all types + } + return this; + } /* NONE OF THIS IS FAST OR EFFICIENT BUT BEAR WITH ME + * + * these shader "type" query methods are used by various + * facilities of the renderer to determine if changing + * the shader type for the required action (for example, + * do we need to load the default lighting shader if the + * current shader cannot handle lighting?) + * + **/ + + }, + { + key: 'isLightShader', + value: function isLightShader() { + return [this.attributes.aNormal, + this.uniforms.uUseLighting, + this.uniforms.uAmbientLightCount, + this.uniforms.uDirectionalLightCount, + this.uniforms.uPointLightCount, + this.uniforms.uAmbientColor, + this.uniforms.uDirectionalDiffuseColors, + this.uniforms.uDirectionalSpecularColors, + this.uniforms.uPointLightLocation, + this.uniforms.uPointLightDiffuseColors, + this.uniforms.uPointLightSpecularColors, + this.uniforms.uLightingDirection, + this.uniforms.uSpecular].some(function (x) { + return x !== undefined; + }); + } + }, + { + key: 'isNormalShader', + value: function isNormalShader() { + return this.attributes.aNormal !== undefined; + } + }, + { + key: 'isTextureShader', + value: function isTextureShader() { + return this.samplers.length > 0; + } + }, + { + key: 'isColorShader', + value: function isColorShader() { + return this.attributes.aVertexColor !== undefined || this.uniforms.uMaterialColor !== undefined; + } + }, + { + key: 'isTexLightShader', + value: function isTexLightShader() { + return this.isLightShader() && this.isTextureShader(); + } + }, + { + key: 'isStrokeShader', + value: function isStrokeShader() { + return this.uniforms.uStrokeWeight !== undefined; + } /** + * @method enableAttrib + * @chainable + * @private + */ + + }, + { + key: 'enableAttrib', + value: function enableAttrib(attr, size, type, normalized, stride, offset) { + if (attr) { + if (typeof IS_MINIFIED === 'undefined' && this.attributes[attr.name] !== attr) { + console.warn('The attribute "'.concat(attr.name, '"passed to enableAttrib does not belong to this shader.')); + } + var loc = attr.location; + if (loc !== - 1) { + var gl = this._renderer.GL; + // Enable register even if it is disabled + if (!this._renderer.registerEnabled.has(loc)) { + gl.enableVertexAttribArray(loc); + // Record register availability + this._renderer.registerEnabled.add(loc); + } + this._renderer.GL.vertexAttribPointer(loc, size, type || gl.FLOAT, normalized || false, stride || 0, offset || 0); + } + } + return this; + } /** + * Once all buffers have been bound, this checks to see if there are any + * remaining active attributes, likely left over from previous renders, + * and disables them so that they don't affect rendering. + * @method disableRemainingAttributes + * @private + */ + + }, + { + key: 'disableRemainingAttributes', + value: function disableRemainingAttributes() { + var _this = this; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + try { + var _loop = function _loop() { + var location = _step4.value; + if (!Object.keys(_this.attributes).some(function (key) { + return _this.attributes[key].location === location; + })) { + _this._renderer.GL.disableVertexAttribArray(location); + _this._renderer.registerEnabled.delete(location); + } + }; + for (var _iterator4 = this._renderer.registerEnabled.values() [Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + _loop(); + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + } + ]); + return _class; + }(); + var _default = _main.default.Shader; + exports.default = _default; + }, + { + '../core/main': 303, + 'core-js/modules/es.array.index-of': 181, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.array.slice': 186, + 'core-js/modules/es.array.some': 187, + 'core-js/modules/es.function.name': 191, + 'core-js/modules/es.object.keys': 204, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 362: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.get-prototype-of'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.reflect.construct'); + _dereq_('core-js/modules/es.regexp.to-string'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.typed-array.uint8-array'); + _dereq_('core-js/modules/es.typed-array.copy-within'); + _dereq_('core-js/modules/es.typed-array.every'); + _dereq_('core-js/modules/es.typed-array.fill'); + _dereq_('core-js/modules/es.typed-array.filter'); + _dereq_('core-js/modules/es.typed-array.find'); + _dereq_('core-js/modules/es.typed-array.find-index'); + _dereq_('core-js/modules/es.typed-array.for-each'); + _dereq_('core-js/modules/es.typed-array.includes'); + _dereq_('core-js/modules/es.typed-array.index-of'); + _dereq_('core-js/modules/es.typed-array.iterator'); + _dereq_('core-js/modules/es.typed-array.join'); + _dereq_('core-js/modules/es.typed-array.last-index-of'); + _dereq_('core-js/modules/es.typed-array.map'); + _dereq_('core-js/modules/es.typed-array.reduce'); + _dereq_('core-js/modules/es.typed-array.reduce-right'); + _dereq_('core-js/modules/es.typed-array.reverse'); + _dereq_('core-js/modules/es.typed-array.set'); + _dereq_('core-js/modules/es.typed-array.slice'); + _dereq_('core-js/modules/es.typed-array.some'); + _dereq_('core-js/modules/es.typed-array.sort'); + _dereq_('core-js/modules/es.typed-array.subarray'); + _dereq_('core-js/modules/es.typed-array.to-locale-string'); + _dereq_('core-js/modules/es.typed-array.to-string'); + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.checkWebGLCapabilities = checkWebGLCapabilities; + exports.default = exports.MipmapTexture = void 0; + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + 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 _createSuper(Derived) { + function 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; + } + } + return function () { + var Super = _getPrototypeOf(Derived), + result; + if (isNativeReflectConstruct()) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self, call) { + if (call && (_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 _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; + } /** + * This module defines the p5.Texture class + * @module 3D + * @submodule Material + * @for p5 + * @requires core + */ + /** + * Texture class for WEBGL Mode + * @private + * @class p5.Texture + * @param {p5.RendererGL} renderer an instance of p5.RendererGL that + * will provide the GL context for this new p5.Texture + * @param {p5.Image|p5.Graphics|p5.Element|p5.MediaElement|ImageData|p5.Framebuffer|p5.FramebufferTexture|ImageData} [obj] the + * object containing the image data to store in the texture. + * @param {Object} [settings] optional A javascript object containing texture + * settings. + * @param {Number} [settings.format] optional The internal color component + * format for the texture. Possible values for format include gl.RGBA, + * gl.RGB, gl.ALPHA, gl.LUMINANCE, gl.LUMINANCE_ALPHA. Defaults to gl.RBGA + * @param {Number} [settings.minFilter] optional The texture minification + * filter setting. Possible values are gl.NEAREST or gl.LINEAR. Defaults + * to gl.LINEAR. Note, Mipmaps are not implemented in p5. + * @param {Number} [settings.magFilter] optional The texture magnification + * filter setting. Possible values are gl.NEAREST or gl.LINEAR. Defaults + * to gl.LINEAR. Note, Mipmaps are not implemented in p5. + * @param {Number} [settings.wrapS] optional The texture wrap settings for + * the s coordinate, or x axis. Possible values are gl.CLAMP_TO_EDGE, + * gl.REPEAT, and gl.MIRRORED_REPEAT. The mirror settings are only available + * when using a power of two sized texture. Defaults to gl.CLAMP_TO_EDGE + * @param {Number} [settings.wrapT] optional The texture wrap settings for + * the t coordinate, or y axis. Possible values are gl.CLAMP_TO_EDGE, + * gl.REPEAT, and gl.MIRRORED_REPEAT. The mirror settings are only available + * when using a power of two sized texture. Defaults to gl.CLAMP_TO_EDGE + * @param {Number} [settings.dataType] optional The data type of the texel + * data. Possible values are gl.UNSIGNED_BYTE or gl.FLOAT. There are more + * formats that are not implemented in p5. Defaults to gl.UNSIGNED_BYTE. + */ + + _main.default.Texture = /*#__PURE__*/ function () { + function Texture(renderer, obj, settings) { + _classCallCheck(this, Texture); + this._renderer = renderer; + var gl = this._renderer.GL; + settings = settings || { + }; + this.src = obj; + this.glTex = undefined; + this.glTarget = gl.TEXTURE_2D; + this.glFormat = settings.format || gl.RGBA; + this.mipmaps = false; + this.glMinFilter = settings.minFilter || gl.LINEAR; + this.glMagFilter = settings.magFilter || gl.LINEAR; + this.glWrapS = settings.wrapS || gl.CLAMP_TO_EDGE; + this.glWrapT = settings.wrapT || gl.CLAMP_TO_EDGE; + this.glDataType = settings.dataType || gl.UNSIGNED_BYTE; + var support = checkWebGLCapabilities(renderer); + if (this.glFormat === gl.HALF_FLOAT && !support.halfFloat) { + console.log('This device does not support dataType HALF_FLOAT. Falling back to FLOAT.'); + this.glDataType = gl.FLOAT; + } + if (this.glFormat === gl.HALF_FLOAT && (this.glMinFilter === gl.LINEAR || this.glMagFilter === gl.LINEAR) && !support.halfFloatLinear) { + console.log('This device does not support linear filtering for dataType FLOAT. Falling back to NEAREST.'); + if (this.glMinFilter === gl.LINEAR) this.glMinFilter = gl.NEAREST; + if (this.glMagFilter === gl.LINEAR) this.glMagFilter = gl.NEAREST; + } + if (this.glFormat === gl.FLOAT && !support.float) { + console.log('This device does not support dataType FLOAT. Falling back to UNSIGNED_BYTE.'); + this.glDataType = gl.UNSIGNED_BYTE; + } + if (this.glFormat === gl.FLOAT && (this.glMinFilter === gl.LINEAR || this.glMagFilter === gl.LINEAR) && !support.floatLinear) { + console.log('This device does not support linear filtering for dataType FLOAT. Falling back to NEAREST.'); + if (this.glMinFilter === gl.LINEAR) this.glMinFilter = gl.NEAREST; + if (this.glMagFilter === gl.LINEAR) this.glMagFilter = gl.NEAREST; + } // used to determine if this texture might need constant updating + // because it is a video or gif. + + this.isSrcMediaElement = typeof _main.default.MediaElement !== 'undefined' && obj instanceof _main.default.MediaElement; + this._videoPrevUpdateTime = 0; + this.isSrcHTMLElement = typeof _main.default.Element !== 'undefined' && obj instanceof _main.default.Element && !(obj instanceof _main.default.Graphics) && !(obj instanceof _main.default.Renderer); + this.isSrcP5Image = obj instanceof _main.default.Image; + this.isSrcP5Graphics = obj instanceof _main.default.Graphics; + this.isSrcP5Renderer = obj instanceof _main.default.Renderer; + this.isImageData = typeof ImageData !== 'undefined' && obj instanceof ImageData; + this.isFramebufferTexture = obj instanceof _main.default.FramebufferTexture; + var textureData = this._getTextureDataFromSource(); + this.width = textureData.width; + this.height = textureData.height; + this.init(textureData); + return this; + } + _createClass(Texture, [ + { + key: '_getTextureDataFromSource', + value: function _getTextureDataFromSource() { + var textureData; + if (this.isFramebufferTexture) { + textureData = this.src.rawTexture(); + } else if (this.isSrcP5Image) { + // param is a p5.Image + textureData = this.src.canvas; + } else if (this.isSrcMediaElement || this.isSrcP5Graphics || this.isSrcP5Renderer || this.isSrcHTMLElement) { + // if param is a video HTML element + textureData = this.src.elt; + } else if (this.isImageData) { + textureData = this.src; + } + return textureData; + } /** + * Initializes common texture parameters, creates a gl texture, + * tries to upload the texture for the first time if data is + * already available. + * @private + * @method init + */ + + }, + { + key: 'init', + value: function init(data) { + var gl = this._renderer.GL; + if (!this.isFramebufferTexture) { + this.glTex = gl.createTexture(); + } + this.glWrapS = this._renderer.textureWrapX; + this.glWrapT = this._renderer.textureWrapY; + this.setWrapMode(this.glWrapS, this.glWrapT); + this.bindTexture(); + //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter); + if (this.isFramebufferTexture) { + // Do nothing, the framebuffer manages its own content + } else if (this.width === 0 || this.height === 0 || this.isSrcMediaElement && !this.src.loadedmetadata) { + // assign a 1×1 empty texture initially, because data is not yet ready, + // so that no errors occur in gl console! + var tmpdata = new Uint8Array([1, + 1, + 1, + 1]); + gl.texImage2D(this.glTarget, 0, gl.RGBA, 1, 1, 0, this.glFormat, this.glDataType, tmpdata); + } else { + // data is ready: just push the texture! + gl.texImage2D(this.glTarget, 0, this.glFormat, this.glFormat, this.glDataType, data); + } + } /** + * Checks if the source data for this texture has changed (if it's + * easy to do so) and reuploads the texture if necessary. If it's not + * possible or to expensive to do a calculation to determine wheter or + * not the data has occurred, this method simply re-uploads the texture. + * @method update + */ + + }, + { + key: 'update', + value: function update() { + var data = this.src; + if (data.width === 0 || data.height === 0) { + return false; // nothing to do! + } // FramebufferTexture instances wrap raw WebGL textures already, which + // don't need any extra updating, as they already live on the GPU + + if (this.isFramebufferTexture) { + return false; + } + var textureData = this._getTextureDataFromSource(); + var updated = false; + var gl = this._renderer.GL; + // pull texture from data, make sure width & height are appropriate + if (textureData.width !== this.width || textureData.height !== this.height) { + updated = true; + // make sure that if the width and height of this.src have changed + // for some reason, we update our metadata and upload the texture again + this.width = textureData.width || data.width; + this.height = textureData.height || data.height; + if (this.isSrcP5Image) { + data.setModified(false); + } else if (this.isSrcMediaElement || this.isSrcHTMLElement) { + // on the first frame the metadata comes in, the size will be changed + // from 0 to actual size, but pixels may not be available. + // flag for update in a future frame. + // if we don't do this, a paused video, for example, may not + // send the first frame to texture memory. + data.setModified(true); + } + } else if (this.isSrcP5Image) { + // for an image, we only update if the modified field has been set, + // for example, by a call to p5.Image.set + if (data.isModified()) { + updated = true; + data.setModified(false); + } + } else if (this.isSrcMediaElement) { + // for a media element (video), we'll check if the current time in + // the video frame matches the last time. if it doesn't match, the + // video has advanced or otherwise been taken to a new frame, + // and we need to upload it. + if (data.isModified()) { + // p5.MediaElement may have also had set/updatePixels, etc. called + // on it and should be updated, or may have been set for the first + // time! + updated = true; + data.setModified(false); + } else if (data.loadedmetadata) { + // if the meta data has been loaded, we can ask the video + // what it's current position (in time) is. + if (this._videoPrevUpdateTime !== data.time()) { + // update the texture in gpu mem only if the current + // video timestamp does not match the timestamp of the last + // time we uploaded this texture (and update the time we + // last uploaded, too) + this._videoPrevUpdateTime = data.time(); + updated = true; + } + } + } else if (this.isImageData) { + if (data._dirty) { + data._dirty = false; + updated = true; + } + } else { + /* data instanceof p5.Graphics, probably */ + // there is not enough information to tell if the texture can be + // conditionally updated; so to be safe, we just go ahead and upload it. + updated = true; + } + if (updated) { + this.bindTexture(); + gl.texImage2D(this.glTarget, 0, this.glFormat, this.glFormat, this.glDataType, textureData); + } + return updated; + } /** + * Binds the texture to the appropriate GL target. + * @method bindTexture + */ + + }, + { + key: 'bindTexture', + value: function bindTexture() { + // bind texture using gl context + glTarget and + // generated gl texture object + var gl = this._renderer.GL; + gl.bindTexture(this.glTarget, this.getTexture()); + return this; + } /** + * Unbinds the texture from the appropriate GL target. + * @method unbindTexture + */ + + }, + { + key: 'unbindTexture', + value: function unbindTexture() { + // unbind per above, disable texturing on glTarget + var gl = this._renderer.GL; + gl.bindTexture(this.glTarget, null); + } + }, + { + key: 'getTexture', + value: function getTexture() { + if (this.isFramebufferTexture) { + return this.src.rawTexture(); + } else { + return this.glTex; + } + } /** + * Sets how a texture is be interpolated when upscaled or downscaled. + * Nearest filtering uses nearest neighbor scaling when interpolating + * Linear filtering uses WebGL's linear scaling when interpolating + * @method setInterpolation + * @param {String} downScale Specifies the texture filtering when + * textures are shrunk. Options are LINEAR or NEAREST + * @param {String} upScale Specifies the texture filtering when + * textures are magnified. Options are LINEAR or NEAREST + * @todo implement mipmapping filters + */ + + }, + { + key: 'setInterpolation', + value: function setInterpolation(downScale, upScale) { + var gl = this._renderer.GL; + this.glMinFilter = this.glFilter(downScale); + this.glMagFilter = this.glFilter(upScale); + this.bindTexture(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter); + this.unbindTexture(); + } + }, + { + key: 'glFilter', + value: function glFilter(filter) { + var gl = this._renderer.GL; + if (filter === constants.NEAREST) { + return gl.NEAREST; + } else { + return gl.LINEAR; + } + } /** + * Sets the texture wrapping mode. This controls how textures behave + * when their uv's go outside of the 0 - 1 range. There are three options: + * CLAMP, REPEAT, and MIRROR. REPEAT & MIRROR are only available if the texture + * is a power of two size (128, 256, 512, 1024, etc.). + * @method setWrapMode + * @param {String} wrapX Controls the horizontal texture wrapping behavior + * @param {String} wrapY Controls the vertical texture wrapping behavior + */ + + }, + { + key: 'setWrapMode', + value: function setWrapMode(wrapX, wrapY) { + var gl = this._renderer.GL; + // for webgl 1 we need to check if the texture is power of two + // if it isn't we will set the wrap mode to CLAMP + // webgl2 will support npot REPEAT and MIRROR but we don't check for it yet + var isPowerOfTwo = function isPowerOfTwo(x) { + return (x & x - 1) === 0; + }; + var textureData = this._getTextureDataFromSource(); + var wrapWidth; + var wrapHeight; + if (textureData.naturalWidth && textureData.naturalHeight) { + wrapWidth = textureData.naturalWidth; + wrapHeight = textureData.naturalHeight; + } else { + wrapWidth = this.width; + wrapHeight = this.height; + } + var widthPowerOfTwo = isPowerOfTwo(wrapWidth); + var heightPowerOfTwo = isPowerOfTwo(wrapHeight); + if (wrapX === constants.REPEAT) { + if (this._renderer.webglVersion === constants.WEBGL2 || widthPowerOfTwo && heightPowerOfTwo) { + this.glWrapS = gl.REPEAT; + } else { + console.warn('You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead'); + this.glWrapS = gl.CLAMP_TO_EDGE; + } + } else if (wrapX === constants.MIRROR) { + if (this._renderer.webglVersion === constants.WEBGL2 || widthPowerOfTwo && heightPowerOfTwo) { + this.glWrapS = gl.MIRRORED_REPEAT; + } else { + console.warn('You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead'); + this.glWrapS = gl.CLAMP_TO_EDGE; + } + } else { + // falling back to default if didn't get a proper mode + this.glWrapS = gl.CLAMP_TO_EDGE; + } + if (wrapY === constants.REPEAT) { + if (this._renderer.webglVersion === constants.WEBGL2 || widthPowerOfTwo && heightPowerOfTwo) { + this.glWrapT = gl.REPEAT; + } else { + console.warn('You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead'); + this.glWrapT = gl.CLAMP_TO_EDGE; + } + } else if (wrapY === constants.MIRROR) { + if (this._renderer.webglVersion === constants.WEBGL2 || widthPowerOfTwo && heightPowerOfTwo) { + this.glWrapT = gl.MIRRORED_REPEAT; + } else { + console.warn('You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead'); + this.glWrapT = gl.CLAMP_TO_EDGE; + } + } else { + // falling back to default if didn't get a proper mode + this.glWrapT = gl.CLAMP_TO_EDGE; + } + this.bindTexture(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.glWrapS); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.glWrapT); + this.unbindTexture(); + } + } + ]); + return Texture; + }(); + var MipmapTexture = /*#__PURE__*/ function (_p5$Texture) { + _inherits(MipmapTexture, _p5$Texture); + var _super = _createSuper(MipmapTexture); + function MipmapTexture(renderer, levels, settings) { + var _this; + _classCallCheck(this, MipmapTexture); + _this = _super.call(this, renderer, levels, settings); + var gl = _this._renderer.GL; + if (_this.glMinFilter === gl.LINEAR) { + _this.glMinFilter = gl.LINEAR_MIPMAP_LINEAR; + } + return _this; + } + _createClass(MipmapTexture, [ + { + key: 'glFilter', + value: function glFilter(_filter) { + var gl = this._renderer.GL; + // TODO: support others + return gl.LINEAR_MIPMAP_LINEAR; + } + }, + { + key: '_getTextureDataFromSource', + value: function _getTextureDataFromSource() { + return this.src; + } + }, + { + key: 'init', + value: function init(levels) { + var gl = this._renderer.GL; + this.glTex = gl.createTexture(); + this.bindTexture(); + for (var level = 0; level < levels.length; level++) { + gl.texImage2D(this.glTarget, level, this.glFormat, this.glFormat, this.glDataType, levels[level]); + } + this.glMinFilter = gl.LINEAR_MIPMAP_LINEAR; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter); + this.unbindTexture(); + } + }, + { + key: 'update', + value: function update() { + } + } + ]); + return MipmapTexture; + }(_main.default.Texture); + exports.MipmapTexture = MipmapTexture; + function checkWebGLCapabilities(_ref) { + var GL = _ref.GL, + webglVersion = _ref.webglVersion; + var gl = GL; + var supportsFloat = webglVersion === constants.WEBGL2 ? gl.getExtension('EXT_color_buffer_float') && gl.getExtension('EXT_float_blend') : gl.getExtension('OES_texture_float'); + var supportsFloatLinear = supportsFloat && gl.getExtension('OES_texture_float_linear'); + var supportsHalfFloat = webglVersion === constants.WEBGL2 ? gl.getExtension('EXT_color_buffer_float') : gl.getExtension('OES_texture_half_float'); + var supportsHalfFloatLinear = supportsHalfFloat && gl.getExtension('OES_texture_half_float_linear'); + return { + float: supportsFloat, + floatLinear: supportsFloatLinear, + halfFloat: supportsHalfFloat, + halfFloatLinear: supportsHalfFloatLinear + }; + } + var _default = _main.default.Texture; + exports.default = _default; + }, + { + '../core/constants': 291, + '../core/main': 303, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.get-prototype-of': 203, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.reflect.construct': 207, + 'core-js/modules/es.regexp.to-string': 211, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.typed-array.copy-within': 228, + 'core-js/modules/es.typed-array.every': 229, + 'core-js/modules/es.typed-array.fill': 230, + 'core-js/modules/es.typed-array.filter': 231, + 'core-js/modules/es.typed-array.find': 233, + 'core-js/modules/es.typed-array.find-index': 232, + 'core-js/modules/es.typed-array.for-each': 236, + 'core-js/modules/es.typed-array.includes': 237, + 'core-js/modules/es.typed-array.index-of': 238, + 'core-js/modules/es.typed-array.iterator': 241, + 'core-js/modules/es.typed-array.join': 242, + 'core-js/modules/es.typed-array.last-index-of': 243, + 'core-js/modules/es.typed-array.map': 244, + 'core-js/modules/es.typed-array.reduce': 246, + 'core-js/modules/es.typed-array.reduce-right': 245, + 'core-js/modules/es.typed-array.reverse': 247, + 'core-js/modules/es.typed-array.set': 248, + 'core-js/modules/es.typed-array.slice': 249, + 'core-js/modules/es.typed-array.some': 250, + 'core-js/modules/es.typed-array.sort': 251, + 'core-js/modules/es.typed-array.subarray': 252, + 'core-js/modules/es.typed-array.to-locale-string': 253, + 'core-js/modules/es.typed-array.to-string': 254, + 'core-js/modules/es.typed-array.uint8-array': 257, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 363: [ + function (_dereq_, module, exports) { + 'use strict'; + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.get-own-property-descriptor'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/es.weak-map'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + function _typeof2(obj) { + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + _typeof2 = function _typeof2(obj) { + return typeof obj; + }; + } else { + _typeof2 = function _typeof2(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj; + }; + } + return _typeof2(obj); + } + function _typeof(obj) { + if (typeof Symbol === 'function' && _typeof2(Symbol.iterator) === 'symbol') { + _typeof = function _typeof(obj) { + return _typeof2(obj); + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === 'function' && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : _typeof2(obj); + }; + } + return _typeof(obj); + } + _dereq_('core-js/modules/es.symbol'); + _dereq_('core-js/modules/es.symbol.description'); + _dereq_('core-js/modules/es.symbol.iterator'); + _dereq_('core-js/modules/es.array.iterator'); + _dereq_('core-js/modules/es.object.to-string'); + _dereq_('core-js/modules/es.regexp.exec'); + _dereq_('core-js/modules/es.string.iterator'); + _dereq_('core-js/modules/es.string.split'); + _dereq_('core-js/modules/es.string.sub'); + _dereq_('core-js/modules/web.dom-collections.iterator'); + var _main = _interopRequireDefault(_dereq_('../core/main')); + var constants = _interopRequireWildcard(_dereq_('../core/constants')); + _dereq_('./p5.Shader'); + _dereq_('./p5.RendererGL.Retained'); + function _getRequireWildcardCache() { + if (typeof WeakMap !== 'function') return null; + var cache = new WeakMap(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + return cache; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== 'object' && typeof obj !== 'function') { + return { + default: + obj + }; + } + var cache = _getRequireWildcardCache(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } + function _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; + } // Text/Typography + // @TODO: + + _main.default.RendererGL.prototype._applyTextProperties = function () { + //@TODO finish implementation + //console.error('text commands not yet implemented in webgl'); + }; + _main.default.RendererGL.prototype.textWidth = function (s) { + if (this._isOpenType()) { + return this._textFont._textWidth(s, this._textSize); + } + return 0; // TODO: error + }; + // rendering constants + // the number of rows/columns dividing each glyph + var charGridWidth = 9; + var charGridHeight = charGridWidth; + // size of the image holding the bezier stroke info + var strokeImageWidth = 64; + var strokeImageHeight = 64; + // size of the image holding the stroke indices for each row/col + var gridImageWidth = 64; + var gridImageHeight = 64; + // size of the image holding the offset/length of each row/col stripe + var cellImageWidth = 64; + var cellImageHeight = 64; + /** + * @private + * @class ImageInfos + * @param {Integer} width + * @param {Integer} height + * + * the ImageInfos class holds a list of ImageDatas of a given size. + */ + var ImageInfos = /*#__PURE__*/ function () { + function ImageInfos(width, height) { + _classCallCheck(this, ImageInfos); + this.width = width; + this.height = height; + this.infos = [ + ]; // the list of images + } /** + * + * @method findImage + * @param {Integer} space + * @return {Object} contains the ImageData, and pixel index into that + * ImageData where the free space was allocated. + * + * finds free space of a given size in the ImageData list + */ + + _createClass(ImageInfos, [ + { + key: 'findImage', + value: function findImage(space) { + var imageSize = this.width * this.height; + if (space > imageSize) throw new Error('font is too complex to render in 3D'); + // search through the list of images, looking for one with + // anough unused space. + var imageInfo, + imageData; + for (var ii = this.infos.length - 1; ii >= 0; --ii) { + var imageInfoTest = this.infos[ii]; + if (imageInfoTest.index + space < imageSize) { + // found one + imageInfo = imageInfoTest; + imageData = imageInfoTest.imageData; + break; + } + } + if (!imageInfo) { + try { + // create a new image + imageData = new ImageData(this.width, this.height); + } catch (err) { + // for browsers that don't support ImageData constructors (ie IE11) + // create an ImageData using the old method + var canvas = document.getElementsByTagName('canvas') [0]; + var created = !canvas; + if (!canvas) { + // create a temporary canvas + canvas = document.createElement('canvas'); + canvas.style.display = 'none'; + document.body.appendChild(canvas); + } + var ctx = canvas.getContext('2d'); + if (ctx) { + imageData = ctx.createImageData(this.width, this.height); + } + if (created) { + // distroy the temporary canvas, if necessary + document.body.removeChild(canvas); + } + } // construct & dd the new image info + + imageInfo = { + index: 0, + imageData: imageData + }; + this.infos.push(imageInfo); + } + var index = imageInfo.index; + imageInfo.index += space; // move to the start of the next image + imageData._dirty = true; + return { + imageData: imageData, + index: index + }; + } + } + ]); + return ImageInfos; + }(); + /** + * @function setPixel + * @param {Object} imageInfo + * @param {Number} r + * @param {Number} g + * @param {Number} b + * @param {Number} a + * + * writes the next pixel into an indexed ImageData + */ + function setPixel(imageInfo, r, g, b, a) { + var imageData = imageInfo.imageData; + var pixels = imageData.data; + var index = imageInfo.index++ * 4; + pixels[index++] = r; + pixels[index++] = g; + pixels[index++] = b; + pixels[index++] = a; + } + var SQRT3 = Math.sqrt(3); + /** + * @private + * @class FontInfo + * @param {Object} font an opentype.js font object + * + * contains cached images and glyph information for an opentype font + */ + var FontInfo = /*#__PURE__*/ function () { + function FontInfo(font) { + _classCallCheck(this, FontInfo); + this.font = font; + // the bezier curve coordinates + this.strokeImageInfos = new ImageInfos(strokeImageWidth, strokeImageHeight); + // lists of curve indices for each row/column slice + this.colDimImageInfos = new ImageInfos(gridImageWidth, gridImageHeight); + this.rowDimImageInfos = new ImageInfos(gridImageWidth, gridImageHeight); + // the offset & length of each row/col slice in the glyph + this.colCellImageInfos = new ImageInfos(cellImageWidth, cellImageHeight); + this.rowCellImageInfos = new ImageInfos(cellImageWidth, cellImageHeight); + // the cached information for each glyph + this.glyphInfos = { + }; + } /** + * @method getGlyphInfo + * @param {Glyph} glyph the x positions of points in the curve + * @returns {Object} the glyphInfo for that glyph + * + * calculates rendering info for a glyph, including the curve information, + * row & column stripes compiled into textures. + */ + + _createClass(FontInfo, [ + { + key: 'getGlyphInfo', + value: function getGlyphInfo(glyph) { + // check the cache + var gi = this.glyphInfos[glyph.index]; + if (gi) return gi; + // get the bounding box of the glyph from opentype.js + var bb = glyph.getBoundingBox(); + var xMin = bb.x1; + var yMin = bb.y1; + var gWidth = bb.x2 - xMin; + var gHeight = bb.y2 - yMin; + var cmds = glyph.path.commands; + // don't bother rendering invisible glyphs + if (gWidth === 0 || gHeight === 0 || !cmds.length) { + return this.glyphInfos[glyph.index] = { + }; + } + var i; + var strokes = [ + ]; // the strokes in this glyph + var rows = [ + ]; // the indices of strokes in each row + var cols = [ + ]; // the indices of strokes in each column + for (i = charGridWidth - 1; i >= 0; --i) { + cols.push([]); + } + for (i = charGridHeight - 1; i >= 0; --i) { + rows.push([]); + } /** + * @function push + * @param {Number[]} xs the x positions of points in the curve + * @param {Number[]} ys the y positions of points in the curve + * @param {Object} v the curve information + * + * adds a curve to the rows & columns that it intersects with + */ + + function push(xs, ys, v) { + var index = strokes.length; // the index of this stroke + strokes.push(v); // add this stroke to the list + /** + * @function minMax + * @param {Number[]} rg the list of values to compare + * @param {Number} min the initial minimum value + * @param {Number} max the initial maximum value + * + * find the minimum & maximum value in a list of values + */ + function minMax(rg, min, max) { + for (var _i = rg.length; _i-- > 0; ) { + var _v = rg[_i]; + if (min > _v) min = _v; + if (max < _v) max = _v; + } + return { + min: min, + max: max + }; + } // Expand the bounding box of the glyph by the number of cells below + // before rounding. Curves only partially through a cell won't be added + // to adjacent cells, but ones that are close will be. This helps fix + // small visual glitches that occur when curves are close to grid cell + // boundaries. + + var cellOffset = 0.5; + // loop through the rows & columns that the curve intersects + // adding the curve to those slices + var mmX = minMax(xs, 1, 0); + var ixMin = Math.max(Math.floor(mmX.min * charGridWidth - cellOffset), 0); + var ixMax = Math.min(Math.ceil(mmX.max * charGridWidth + cellOffset), charGridWidth); + for (var iCol = ixMin; iCol < ixMax; ++iCol) { + cols[iCol].push(index); + } + var mmY = minMax(ys, 1, 0); + var iyMin = Math.max(Math.floor(mmY.min * charGridHeight - cellOffset), 0); + var iyMax = Math.min(Math.ceil(mmY.max * charGridHeight + cellOffset), charGridHeight); + for (var iRow = iyMin; iRow < iyMax; ++iRow) { + rows[iRow].push(index); + } + } /** + * @function clamp + * @param {Number} v the value to clamp + * @param {Number} min the minimum value + * @param {Number} max the maxmimum value + * + * clamps a value between a minimum & maximum value + */ + + function clamp(v, min, max) { + if (v < min) return min; + if (v > max) return max; + return v; + } /** + * @function byte + * @param {Number} v the value to scale + * + * converts a floating-point number in the range 0-1 to a byte 0-255 + */ + + function byte(v) { + return clamp(255 * v, 0, 255); + } /** + * @private + * @class Cubic + * @param {Number} p0 the start point of the curve + * @param {Number} c0 the first control point + * @param {Number} c1 the second control point + * @param {Number} p1 the end point + * + * a cubic curve + */ + + var Cubic = /*#__PURE__*/ function () { + function Cubic(p0, c0, c1, p1) { + _classCallCheck(this, Cubic); + this.p0 = p0; + this.c0 = c0; + this.c1 = c1; + this.p1 = p1; + } /** + * @method toQuadratic + * @return {Object} the quadratic approximation + * + * converts the cubic to a quadtratic approximation by + * picking an appropriate quadratic control point + */ + + _createClass(Cubic, [ + { + key: 'toQuadratic', + value: function toQuadratic() { + return { + x: this.p0.x, + y: this.p0.y, + x1: this.p1.x, + y1: this.p1.y, + cx: ((this.c0.x + this.c1.x) * 3 - (this.p0.x + this.p1.x)) / 4, + cy: ((this.c0.y + this.c1.y) * 3 - (this.p0.y + this.p1.y)) / 4 + }; + } /** + * @method quadError + * @return {Number} the error + * + * calculates the magnitude of error of this curve's + * quadratic approximation. + */ + + }, + { + key: 'quadError', + value: function quadError() { + return _main.default.Vector.sub(_main.default.Vector.sub(this.p1, this.p0), _main.default.Vector.mult(_main.default.Vector.sub(this.c1, this.c0), 3)).mag() / 2; + } /** + * @method split + * @param {Number} t the value (0-1) at which to split + * @return {Cubic} the second part of the curve + * + * splits the cubic into two parts at a point 't' along the curve. + * this cubic keeps its start point and its end point becomes the + * point at 't'. the 'end half is returned. + */ + + }, + { + key: 'split', + value: function split(t) { + var m1 = _main.default.Vector.lerp(this.p0, this.c0, t); + var m2 = _main.default.Vector.lerp(this.c0, this.c1, t); + var mm1 = _main.default.Vector.lerp(m1, m2, t); + this.c1 = _main.default.Vector.lerp(this.c1, this.p1, t); + this.c0 = _main.default.Vector.lerp(m2, this.c1, t); + var pt = _main.default.Vector.lerp(mm1, this.c0, t); + var part1 = new Cubic(this.p0, m1, mm1, pt); + this.p0 = pt; + return part1; + } /** + * @method splitInflections + * @return {Cubic[]} the non-inflecting pieces of this cubic + * + * returns an array containing 0, 1 or 2 cubics split resulting + * from splitting this cubic at its inflection points. + * this cubic is (potentially) altered and returned in the list. + */ + + }, + { + key: 'splitInflections', + value: function splitInflections() { + var a = _main.default.Vector.sub(this.c0, this.p0); + var b = _main.default.Vector.sub(_main.default.Vector.sub(this.c1, this.c0), a); + var c = _main.default.Vector.sub(_main.default.Vector.sub(_main.default.Vector.sub(this.p1, this.c1), a), _main.default.Vector.mult(b, 2)); + var cubics = [ + ]; + // find the derivative coefficients + var A = b.x * c.y - b.y * c.x; + if (A !== 0) { + var B = a.x * c.y - a.y * c.x; + var C = a.x * b.y - a.y * b.x; + var disc = B * B - 4 * A * C; + if (disc >= 0) { + if (A < 0) { + A = - A; + B = - B; + C = - C; + } + var Q = Math.sqrt(disc); + var t0 = ( - B - Q) / (2 * A); // the first inflection point + var t1 = ( - B + Q) / (2 * A); // the second inflection point + // test if the first inflection point lies on the curve + if (t0 > 0 && t0 < 1) { + // split at the first inflection point + cubics.push(this.split(t0)); + // scale t2 into the second part + t1 = 1 - (1 - t1) / (1 - t0); + } // test if the second inflection point lies on the curve + + if (t1 > 0 && t1 < 1) { + // split at the second inflection point + cubics.push(this.split(t1)); + } + } + } + cubics.push(this); + return cubics; + } + } + ]); + return Cubic; + }(); + /** + * @function cubicToQuadratics + * @param {Number} x0 + * @param {Number} y0 + * @param {Number} cx0 + * @param {Number} cy0 + * @param {Number} cx1 + * @param {Number} cy1 + * @param {Number} x1 + * @param {Number} y1 + * @returns {Cubic[]} an array of cubics whose quadratic approximations + * closely match the civen cubic. + * + * converts a cubic curve to a list of quadratics. + */ + function cubicToQuadratics(x0, y0, cx0, cy0, cx1, cy1, x1, y1) { + // create the Cubic object and split it at its inflections + var cubics = new Cubic(new _main.default.Vector(x0, y0), new _main.default.Vector(cx0, cy0), new _main.default.Vector(cx1, cy1), new _main.default.Vector(x1, y1)).splitInflections(); + var qs = [ + ]; // the final list of quadratics + var precision = 30 / SQRT3; + // for each of the non-inflected pieces of the original cubic + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + try { + for (var _iterator = cubics[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var cubic = _step.value; + // the cubic is iteratively split in 3 pieces: + // the first piece is accumulated in 'qs', the result. + // the last piece is accumulated in 'tail', temporarily. + // the middle piece is repeatedly split again, while necessary. + var tail = [ + ]; + var t3 = void 0; + for (; ; ) { + // calculate this cubic's precision + t3 = precision / cubic.quadError(); + if (t3 >= 0.5 * 0.5 * 0.5) { + break; // not too bad, we're done + } // find a split point based on the error + + var t = Math.pow(t3, 1 / 3); + // split the cubic in 3 + var start = cubic.split(t); + var middle = cubic.split(1 - t / (1 - t)); + qs.push(start); // the first part + tail.push(cubic); // the last part + cubic = middle; // iterate on the middle piece + } + if (t3 < 1) { + // a little excess error, split the middle in two + qs.push(cubic.split(0.5)); + } // add the middle piece to the result + + qs.push(cubic); + // finally add the tail, reversed, onto the result + Array.prototype.push.apply(qs, tail.reverse()); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + return qs; + } /** + * @function pushLine + * @param {Number} x0 + * @param {Number} y0 + * @param {Number} x1 + * @param {Number} y1 + * + * add a straight line to the row/col grid of a glyph + */ + + function pushLine(x0, y0, x1, y1) { + var mx = (x0 + x1) / 2; + var my = (y0 + y1) / 2; + push([x0, + x1], [ + y0, + y1 + ], { + x: x0, + y: y0, + cx: mx, + cy: my + }); + } /** + * @function samePoint + * @param {Number} x0 + * @param {Number} y0 + * @param {Number} x1 + * @param {Number} y1 + * @return {Boolean} true if the two points are sufficiently close + * + * tests if two points are close enough to be considered the same + */ + + function samePoint(x0, y0, x1, y1) { + return Math.abs(x1 - x0) < 0.00001 && Math.abs(y1 - y0) < 0.00001; + } + var x0, + y0, + xs, + ys; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + try { + for (var _iterator2 = cmds[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var cmd = _step2.value; + // scale the coordinates to the range 0-1 + var x1 = (cmd.x - xMin) / gWidth; + var y1 = (cmd.y - yMin) / gHeight; + // don't bother if this point is the same as the last + if (samePoint(x0, y0, x1, y1)) continue; + switch (cmd.type) { + case 'M': + { + // move + xs = x1; + ys = y1; + break; + } + case 'L': + { + // line + pushLine(x0, y0, x1, y1); + break; + } + case 'Q': + { + // quadratic + var cx = (cmd.x1 - xMin) / gWidth; + var cy = (cmd.y1 - yMin) / gHeight; + push([x0, + x1, + cx], [ + y0, + y1, + cy + ], { + x: x0, + y: y0, + cx: cx, + cy: cy + }); + break; + } + case 'Z': + { + // end + if (!samePoint(x0, y0, xs, ys)) { + // add an extra line closing the loop, if necessary + pushLine(x0, y0, xs, ys); + strokes.push({ + x: xs, + y: ys + }); + } else { + strokes.push({ + x: x0, + y: y0 + }); + } + break; + } + case 'C': + { + // cubic + var cx1 = (cmd.x1 - xMin) / gWidth; + var cy1 = (cmd.y1 - yMin) / gHeight; + var cx2 = (cmd.x2 - xMin) / gWidth; + var cy2 = (cmd.y2 - yMin) / gHeight; + var qs = cubicToQuadratics(x0, y0, cx1, cy1, cx2, cy2, x1, y1); + for (var iq = 0; iq < qs.length; iq++) { + var q = qs[iq].toQuadratic(); + push([q.x, + q.x1, + q.cx], [ + q.y, + q.y1, + q.cy + ], q); + } + break; + } + default: + throw new Error('unknown command type: '.concat(cmd.type)); + } + x0 = x1; + y0 = y1; + } // allocate space for the strokes + + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + var strokeCount = strokes.length; + var strokeImageInfo = this.strokeImageInfos.findImage(strokeCount); + var strokeOffset = strokeImageInfo.index; + // fill the stroke image + for (var il = 0; il < strokeCount; ++il) { + var s = strokes[il]; + setPixel(strokeImageInfo, byte(s.x), byte(s.y), byte(s.cx), byte(s.cy)); + } /** + * @function layout + * @param {Number[][]} dim + * @param {ImageInfo[]} dimImageInfos + * @param {ImageInfo[]} cellImageInfos + * @return {Object} + * + * lays out the curves in a dimension (row or col) into two + * images, one for the indices of the curves themselves, and + * one containing the offset and length of those index spans. + */ + + function layout(dim, dimImageInfos, cellImageInfos) { + var dimLength = dim.length; // the number of slices in this dimension + var dimImageInfo = dimImageInfos.findImage(dimLength); + var dimOffset = dimImageInfo.index; + // calculate the total number of stroke indices in this dimension + var totalStrokes = 0; + for (var id = 0; id < dimLength; ++id) { + totalStrokes += dim[id].length; + } // allocate space for the stroke indices + + var cellImageInfo = cellImageInfos.findImage(totalStrokes); + // for each slice in the glyph + for (var _i2 = 0; _i2 < dimLength; ++_i2) { + var strokeIndices = dim[_i2]; + var _strokeCount = strokeIndices.length; + var cellLineIndex = cellImageInfo.index; + // write the offset and count into the glyph slice image + setPixel(dimImageInfo, cellLineIndex >> 7, cellLineIndex & 127, _strokeCount >> 7, _strokeCount & 127); + // for each stroke index in that slice + for (var iil = 0; iil < _strokeCount; ++iil) { + // write the stroke index into the slice's image + var strokeIndex = strokeIndices[iil] + strokeOffset; + setPixel(cellImageInfo, strokeIndex >> 7, strokeIndex & 127, 0, 0); + } + } + return { + cellImageInfo: cellImageInfo, + dimOffset: dimOffset, + dimImageInfo: dimImageInfo + }; + } // initialize the info for this glyph + + gi = this.glyphInfos[glyph.index] = { + glyph: glyph, + uGlyphRect: [ + bb.x1, + - bb.y1, + bb.x2, + - bb.y2 + ], + strokeImageInfo: strokeImageInfo, + strokes: strokes, + colInfo: layout(cols, this.colDimImageInfos, this.colCellImageInfos), + rowInfo: layout(rows, this.rowDimImageInfos, this.rowCellImageInfos) + }; + gi.uGridOffset = [ + gi.colInfo.dimOffset, + gi.rowInfo.dimOffset + ]; + return gi; + } + } + ]); + return FontInfo; + }(); + _main.default.RendererGL.prototype._renderText = function (p, line, x, y, maxY) { + if (!this._textFont || typeof this._textFont === 'string') { + console.log('WEBGL: you must load and set a font before drawing text. See `loadFont` and `textFont` for more details.'); + return; + } + if (y >= maxY || !this._doFill) { + return; // don't render lines beyond our maxY position + } + if (!this._isOpenType()) { + console.log('WEBGL: only Opentype (.otf) and Truetype (.ttf) fonts are supported'); + return p; + } + p.push(); // fix to #803 + // remember this state, so it can be restored later + var doStroke = this._doStroke; + var drawMode = this.drawMode; + this._doStroke = false; + this.drawMode = constants.TEXTURE; + // get the cached FontInfo object + var font = this._textFont.font; + var fontInfo = this._textFont._fontInfo; + if (!fontInfo) { + fontInfo = this._textFont._fontInfo = new FontInfo(font); + } // calculate the alignment and move/scale the view accordingly + + var pos = this._textFont._handleAlignment(this, line, x, y); + var fontSize = this._textSize; + var scale = fontSize / font.unitsPerEm; + this.translate(pos.x, pos.y, 0); + this.scale(scale, scale, 1); + // initialize the font shader + var gl = this.GL; + var initializeShader = !this._defaultFontShader; + var sh = this._getFontShader(); + sh.init(); + sh.bindShader(); // first time around, bind the shader fully + if (initializeShader) { + // these are constants, really. just initialize them one-time. + sh.setUniform('uGridImageSize', [ + gridImageWidth, + gridImageHeight + ]); + sh.setUniform('uCellsImageSize', [ + cellImageWidth, + cellImageHeight + ]); + sh.setUniform('uStrokeImageSize', [ + strokeImageWidth, + strokeImageHeight + ]); + sh.setUniform('uGridSize', [ + charGridWidth, + charGridHeight + ]); + } + this._applyColorBlend(this.curFillColor); + var g = this.retainedMode.geometry['glyph']; + if (!g) { + // create the geometry for rendering a quad + var geom = this._textGeom = new _main.default.Geometry(1, 1, function () { + for (var i = 0; i <= 1; i++) { + for (var j = 0; j <= 1; j++) { + this.vertices.push(new _main.default.Vector(j, i, 0)); + this.uvs.push(j, i); + } + } + }); + geom.computeFaces().computeNormals(); + g = this.createBuffers('glyph', geom); + } // bind the shader buffers + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = this.retainedMode.buffers.text[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var buff = _step3.value; + buff._prepareBuffer(g, sh); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + this._bindBuffer(g.indexBuffer, gl.ELEMENT_ARRAY_BUFFER); + // this will have to do for now... + sh.setUniform('uMaterialColor', this.curFillColor); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + try { + var dx = 0; // the x position in the line + var glyphPrev = null; // the previous glyph, used for kerning + // fetch the glyphs in the line of text + var glyphs = font.stringToGlyphs(line); + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + try { + for (var _iterator4 = glyphs[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var glyph = _step4.value; + // kern + if (glyphPrev) dx += font.getKerningValue(glyphPrev, glyph); + var gi = fontInfo.getGlyphInfo(glyph); + if (gi.uGlyphRect) { + var rowInfo = gi.rowInfo; + var colInfo = gi.colInfo; + sh.setUniform('uSamplerStrokes', gi.strokeImageInfo.imageData); + sh.setUniform('uSamplerRowStrokes', rowInfo.cellImageInfo.imageData); + sh.setUniform('uSamplerRows', rowInfo.dimImageInfo.imageData); + sh.setUniform('uSamplerColStrokes', colInfo.cellImageInfo.imageData); + sh.setUniform('uSamplerCols', colInfo.dimImageInfo.imageData); + sh.setUniform('uGridOffset', gi.uGridOffset); + sh.setUniform('uGlyphRect', gi.uGlyphRect); + sh.setUniform('uGlyphOffset', dx); + sh.bindTextures(); // afterwards, only textures need updating + // draw it + gl.drawElements(gl.TRIANGLES, 6, this.GL.UNSIGNED_SHORT, 0); + } + dx += glyph.advanceWidth; + glyphPrev = glyph; + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } finally { + // clean up + sh.unbindShader(); + this._doStroke = doStroke; + this.drawMode = drawMode; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); + p.pop(); + } + return p; + }; + }, + { + '../core/constants': 291, + '../core/main': 303, + './p5.RendererGL.Retained': 359, + './p5.Shader': 361, + 'core-js/modules/es.array.iterator': 182, + 'core-js/modules/es.object.get-own-property-descriptor': 201, + 'core-js/modules/es.object.to-string': 205, + 'core-js/modules/es.regexp.exec': 210, + 'core-js/modules/es.string.iterator': 215, + 'core-js/modules/es.string.split': 221, + 'core-js/modules/es.string.sub': 223, + 'core-js/modules/es.symbol': 227, + 'core-js/modules/es.symbol.description': 225, + 'core-js/modules/es.symbol.iterator': 226, + 'core-js/modules/es.weak-map': 259, + 'core-js/modules/web.dom-collections.iterator': 261 + } + ], + 364: [ + function (_dereq_, module, exports) { + module.exports = { + 'fes': { + 'autoplay': 'The media that tried to play (with \'{{src}}\') wasn\'t allowed to by this browser, most likely due to the browser\'s autoplay policy.\n\n+ More info: {{url}}', + 'checkUserDefinedFns': 'It seems that you may have accidentally written {{name}} instead of {{actualName}}. Please correct it if it\'s not intentional.', + 'fileLoadError': { + 'bytes': 'It looks like there was a problem loading your file. {{suggestion}}', + 'font': 'It looks like there was a problem loading your font. {{suggestion}}', + 'gif': 'There was some trouble loading your GIF. Make sure that your GIF is using 87a or 89a encoding.', + 'image': 'It looks like there was a problem loading your image. {{suggestion}}', + 'json': 'It looks like there was a problem loading your JSON file. {{suggestion}}', + 'large': 'If your large file isn\'t fetched successfully, we recommend splitting the file into smaller segments and fetching those.', + 'strings': 'It looks like there was a problem loading your text file. {{suggestion}}', + 'suggestion': 'Try checking if the file path ({{filePath}}) is correct, hosting the file online, or running a local server.\n\n+ More info: {{url}}', + 'table': 'It looks like there was a problem loading your table file. {{suggestion}}', + 'xml': 'It looks like there was a problem loading your XML file. {{suggestion}}' + }, + 'friendlyParamError': { + 'type_EMPTY_VAR': '{{location}} {{func}}() was expecting {{formatType}} for the {{position}} parameter, received an empty variable instead. If not intentional, this is often a problem with scope.\n\n+ More info: {{url}}', + 'type_TOO_FEW_ARGUMENTS': '{{location}} {{func}}() was expecting at least {{minParams}} arguments, but received only {{argCount}}.', + 'type_TOO_MANY_ARGUMENTS': '{{location}} {{func}}() was expecting no more than {{maxParams}} arguments, but received {{argCount}}.', + 'type_WRONG_TYPE': '{{location}} {{func}}() was expecting {{formatType}} for the {{position}} parameter, received {{argType}} instead.' + }, + 'globalErrors': { + 'reference': { + 'cannotAccess': '\n{{location}} "{{symbol}}" is used before declaration. Make sure you have declared the variable before using it.\n\n+ More info: {{url}}', + 'notDefined': '\n{{location}} "{{symbol}}" is not defined in the current scope. If you have defined it in your code, you should check its scope, spelling, and letter-casing (JavaScript is case-sensitive).\n\n+ More info: {{url}}' + }, + 'stackSubseq': '└[{{location}}] \n\t Called from line {{line}} in {{func}}()\n', + 'stackTop': '┌[{{location}}] \n\t Error at line {{line}} in {{func}}()\n', + 'syntax': { + 'badReturnOrYield': '\nSyntax Error - return lies outside of a function. Make sure you’re not missing any brackets, so that return lies inside a function.\n\n+ More info: {{url}}', + 'invalidToken': '\nSyntax Error - Found a symbol that JavaScript doesn\'t recognize or didn\'t expect at it\'s place.\n\n+ More info: {{url}}', + 'missingInitializer': '\nSyntax Error - A const variable is declared but not initialized. In JavaScript, an initializer for a const is required. A value must be specified in the same statement in which the variable is declared. Check the line number in the error and assign the const variable a value.\n\n+ More info: {{url}}', + 'redeclaredVariable': '\nSyntax Error - "{{symbol}}" is being redeclared. JavaScript doesn\'t allow declaring a variable more than once. Check the line number in error for redeclaration of the variable.\n\n+ More info: {{url}}', + 'unexpectedToken': '\nSyntax Error - Symbol present at a place that wasn\'t expected.\nUsually this is due to a typo. Check the line number in the error for anything missing/extra.\n\n+ More info: {{url}}' + }, + 'type': { + 'constAssign': '\n{{location}} A const variable is being re-assigned. In javascript, re-assigning a value to a constant is not allowed. If you want to re-assign new values to a variable, make sure it is declared as var or let.\n\n+ More info: {{url}}', + 'notfunc': '\n{{location}} "{{symbol}}" could not be called as a function.\nCheck the spelling, letter-casing (JavaScript is case-sensitive) and its type.\n\n+ More info: {{url}}', + 'notfuncObj': '\n{{location}} "{{symbol}}" could not be called as a function.\nVerify whether "{{obj}}" has "{{symbol}}" in it and check the spelling, letter-casing (JavaScript is case-sensitive) and its type.\n\n+ More info: {{url}}', + 'readFromNull': '\n{{location}} The property of null can\'t be read. In javascript the value null indicates that an object has no value.\n\n+ More info: {{url}}', + 'readFromUndefined': '\n{{location}} Cannot read property of undefined. Check the line number in error and make sure the variable which is being operated is not undefined.\n\n + More info: {{url}}' + } + }, + 'libraryError': '{{location}} An error with message "{{error}}" occurred inside the p5js library when {{func}} was called. If not stated otherwise, it might be an issue with the arguments passed to {{func}}.', + 'location': '[{{file}}, line {{line}}]', + 'misspelling': '{{location}} It seems that you may have accidentally written "{{name}}" instead of "{{actualName}}". Please correct it to {{actualName}} if you wish to use the {{type}} from p5.js.', + 'misspelling_plural': '{{location}} It seems that you may have accidentally written "{{name}}".\nYou may have meant one of the following: \n{{suggestions}}', + 'misusedTopLevel': 'Did you just try to use p5.js\'s {{symbolName}} {{symbolType}}? If so, you may want to move it into your sketch\'s setup() function.\n\n+ More info: {{url}}', + 'positions': { + 'p_1': 'first', + 'p_10': 'tenth', + 'p_11': 'eleventh', + 'p_12': 'twelfth', + 'p_2': 'second', + 'p_3': 'third', + 'p_4': 'fourth', + 'p_5': 'fifth', + 'p_6': 'sixth', + 'p_7': 'seventh', + 'p_8': 'eighth', + 'p_9': 'ninth' + }, + 'pre': '\n🌸 p5.js says: {{message}}', + 'sketchReaderErrors': { + 'reservedConst': 'you have used a p5.js reserved variable "{{symbol}}" make sure you change the variable name to something else.\n\n+ More info: {{url}}', + 'reservedFunc': 'you have used a p5.js reserved function "{{symbol}}" make sure you change the function name to something else.\n\n+ More info: {{url}}' + }, + 'welcome': 'Welcome! This is your friendly debugger. To turn me off, switch to using p5.min.js.', + 'wrongPreload': '{{location}} An error with message "{{error}}" occurred inside the p5js library when "{{func}}" was called. If not stated otherwise, it might be due to "{{func}}" being called from preload. Nothing besides load calls (loadImage, loadJSON, loadFont, loadStrings, etc.) should be inside the preload function.' + } + } + }, + { + } + ], + 365: [ + function (_dereq_, module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.languages = exports.default = void 0; + var _translation = _interopRequireDefault(_dereq_('./en/translation')); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: + obj + }; + } // Only one language is imported above. This is intentional as other languages + // will be hosted online and then downloaded whenever needed + /** + * Here, we define a default/fallback language which we can use without internet. + * You won't have to change this when adding a new language. + * + * `translation` is the namespace we are using for our initial set of strings + */ + + var _default = { + en: { + translation: _translation.default + } + }; + /** + * This is a list of languages that we have added so far. + * If you have just added a new language (yay!), add its key to the list below + * (`en` is english, `es` es español). Also add its export to + * dev.js, which is another file in this folder. + */ + exports.default = _default; + var languages = [ + 'en', + 'es', + 'ko', + 'zh', + 'hi', + 'ja' + ]; + exports.languages = languages; + }, + { + './en/translation': 364 + } + ] + }, { + }, [ + 286 + ]) (286) +}); diff --git a/estudiantes/09-SofiaEct/clase-15/p5.sound.min.js b/estudiantes/09-SofiaEct/clase-15/p5.sound.min.js new file mode 100644 index 00000000..44f25231 --- /dev/null +++ b/estudiantes/09-SofiaEct/clase-15/p5.sound.min.js @@ -0,0 +1,3 @@ +/** [p5.sound] Version: 1.0.1 - 2021-05-25 */ + !function(n){var i={};function r(t){if(i[t])return i[t].exports;var e=i[t]={i:t,l:!1,exports:{}};return n[t].call(e.exports,e,e.exports,r),e.l=!0,e.exports}r.m=n,r.c=i,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=40)}([function(t,e,n){var i;void 0===(i=function(){"use strict";function l(t,e){this.isUndef(t)||1===t?this.input=this.context.createGain():1t)this.cancelScheduledValues(t),this.linearRampToValueAtTime(e,t);else{var i=this._searchAfter(t);i&&(this.cancelScheduledValues(t),i.type===u.TimelineSignal.Type.Linear?this.linearRampToValueAtTime(e,t):i.type===u.TimelineSignal.Type.Exponential&&this.exponentialRampToValueAtTime(e,t)),this.setValueAtTime(e,t)}return this},u.TimelineSignal.prototype.linearRampToValueBetween=function(t,e,n){return this.setRampPoint(e),this.linearRampToValueAtTime(t,n),this},u.TimelineSignal.prototype.exponentialRampToValueBetween=function(t,e,n){return this.setRampPoint(e),this.exponentialRampToValueAtTime(t,n),this},u.TimelineSignal.prototype._searchBefore=function(t){return this._events.get(t)},u.TimelineSignal.prototype._searchAfter=function(t){return this._events.getAfter(t)},u.TimelineSignal.prototype.getValueAtTime=function(t){t=this.toSeconds(t);var e=this._searchAfter(t),n=this._searchBefore(t),i=this._initial;if(null===n)i=this._initial;else if(n.type===u.TimelineSignal.Type.Target){var r,o=this._events.getBefore(n.time);r=null===o?this._initial:o.value,i=this._exponentialApproach(n.time,r,n.value,n.constant,t)}else i=n.type===u.TimelineSignal.Type.Curve?this._curveInterpolate(n.time,n.value,n.duration,t):null===e?n.value:e.type===u.TimelineSignal.Type.Linear?this._linearInterpolate(n.time,n.value,e.time,e.value,t):e.type===u.TimelineSignal.Type.Exponential?this._exponentialInterpolate(n.time,n.value,e.time,e.value,t):n.value;return i},u.TimelineSignal.prototype.connect=u.SignalBase.prototype.connect,u.TimelineSignal.prototype._exponentialApproach=function(t,e,n,i,r){return n+(e-n)*Math.exp(-(r-t)/i)},u.TimelineSignal.prototype._linearInterpolate=function(t,e,n,i,r){return e+(r-t)/(n-t)*(i-e)},u.TimelineSignal.prototype._exponentialInterpolate=function(t,e,n,i,r){return(e=Math.max(this._minOutput,e))*Math.pow(i/e,(r-t)/(n-t))},u.TimelineSignal.prototype._curveInterpolate=function(t,e,n,i){var r=e.length;if(t+n<=i)return e[r-1];if(i<=t)return e[0];var o=(i-t)/n,s=Math.floor((r-1)*o),a=Math.ceil((r-1)*o),u=e[s],c=e[a];return a===s?u:this._linearInterpolate(s,u,a,c,o*(r-1))},u.TimelineSignal.prototype.dispose=function(){u.Signal.prototype.dispose.call(this),u.Param.prototype.dispose.call(this),this._events.dispose(),this._events=null},u.TimelineSignal}.apply(e,i))||(t.exports=r)},function(t,e,n){var i,r;i=[n(0),n(4),n(1),n(2)],void 0===(r=function(n){"use strict";return n.Scale=function(t,e){this._outputMin=this.defaultArg(t,0),this._outputMax=this.defaultArg(e,1),this._scale=this.input=new n.Multiply(1),this._add=this.output=new n.Add(0),this._scale.connect(this._add),this._setRange()},n.extend(n.Scale,n.SignalBase),Object.defineProperty(n.Scale.prototype,"min",{get:function(){return this._outputMin},set:function(t){this._outputMin=t,this._setRange()}}),Object.defineProperty(n.Scale.prototype,"max",{get:function(){return this._outputMax},set:function(t){this._outputMax=t,this._setRange()}}),n.Scale.prototype._setRange=function(){this._add.value=this._outputMin,this._scale.value=this._outputMax-this._outputMin},n.Scale.prototype.dispose=function(){return n.prototype.dispose.call(this),this._add.dispose(),this._add=null,this._scale.dispose(),this._scale=null,this},n.Scale}.apply(e,i))||(t.exports=r)},function(t,e,n){var i,r;i=[n(0),n(16),n(30),n(31),n(12)],void 0===(r=function(e){return e.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"},e.prototype.toSeconds=function(t){return this.isNumber(t)?t:this.isUndef(t)?this.now():this.isString(t)?new e.Time(t).toSeconds():t instanceof e.TimeBase?t.toSeconds():void 0},e.prototype.toFrequency=function(t){return this.isNumber(t)?t:this.isString(t)||this.isUndef(t)?new e.Frequency(t).valueOf():t instanceof e.TimeBase?t.toFrequency():void 0},e.prototype.toTicks=function(t){return this.isNumber(t)||this.isString(t)?new e.TransportTime(t).toTicks():this.isUndef(t)?e.Transport.ticks:t instanceof e.TimeBase?t.toTicks():void 0},e}.apply(e,i))||(t.exports=r)},function(t,e,n){var i,r;i=[n(0),n(18),n(9)],void 0===(r=function(n){"use strict";return window.GainNode&&!AudioContext.prototype.createGain&&(AudioContext.prototype.createGain=AudioContext.prototype.createGainNode),n.Gain=function(){var t=this.optionsObject(arguments,["gain","units"],n.Gain.defaults);this.input=this.output=this._gainNode=this.context.createGain(),this.gain=new n.Param({param:this._gainNode.gain,units:t.units,value:t.gain,convert:t.convert}),this._readOnly("gain")},n.extend(n.Gain),n.Gain.defaults={gain:1,convert:!0},n.Gain.prototype.dispose=function(){n.Param.prototype.dispose.call(this),this._gainNode.disconnect(),this._gainNode=null,this._writable("gain"),this.gain.dispose(),this.gain=null},n.prototype.createInsOuts=function(t,e){1===t?this.input=new n.Gain:1this._nextTick&&this._state;){var e=this._state.getValueAtTime(this._nextTick);if(e!==this._lastState){this._lastState=e;var n=this._state.get(this._nextTick);e===r.State.Started?(this._nextTick=n.time,this.isUndef(n.offset)||(this.ticks=n.offset),this.emit("start",n.time,this.ticks)):e===r.State.Stopped?(this.ticks=0,this.emit("stop",n.time)):e===r.State.Paused&&this.emit("pause",n.time)}var i=this._nextTick;this.frequency&&(this._nextTick+=1/this.frequency.getValueAtTime(this._nextTick),e===r.State.Started&&(this.callback(i),this.ticks++))}},r.Clock.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)},r.Clock.prototype.dispose=function(){r.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},r.Clock}.apply(e,i))||(t.exports=r)},function(t,e,n){var i,r;i=[n(0),n(14)],void 0===(r=function(i){function t(t,e,n){if(t.input)Array.isArray(t.input)?(i.prototype.isUndef(n)&&(n=0),this.connect(t.input[n])):this.connect(t.input,e,n);else try{t instanceof AudioNode?r.call(this,t,e,n):r.call(this,t,e)}catch(e){throw new Error("error connecting to node: "+t+"\n"+e)}}var r,o;return!window.hasOwnProperty("AudioContext")&&window.hasOwnProperty("webkitAudioContext")&&(window.AudioContext=window.webkitAudioContext),i.Context=function(t){for(var e in i.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={}},i.extend(i.Context,i.Emitter),i.Emitter.mixin(i.Context),i.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}})},i.Context.prototype.now=function(){return this._context.currentTime},i.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},i.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),i=0;ithis.memory){var n=this.length-this.memory;this._timeline.splice(0,n)}return this},e.Timeline.prototype.remove=function(t){if(this._iterating)this._toRemove.push(t);else{var e=this._timeline.indexOf(t);-1!==e&&this._timeline.splice(e,1)}return this},e.Timeline.prototype.get=function(t){var e=this._search(t);return-1!==e?this._timeline[e]:null},e.Timeline.prototype.peek=function(){return this._timeline[0]},e.Timeline.prototype.shift=function(){return this._timeline.shift()},e.Timeline.prototype.getAfter=function(t){var e=this._search(t);return e+1=t&&(this._timeline=[]);return this},e.Timeline.prototype.cancelBefore=function(t){if(this._timeline.length){var e=this._search(t);0<=e&&(this._timeline=this._timeline.slice(e+1))}return this},e.Timeline.prototype._search=function(t){var e=0,n=this._timeline.length,i=n;if(0t)return r;o.time>t?i=r:o.time=t;)n--;return this._iterate(e,n+1),this},e.Timeline.prototype.forEachAtTime=function(e,n){var t=this._search(e);return-1!==t&&this._iterate(function(t){t.time===e&&n(t)},0,t),this},e.Timeline.prototype.dispose=function(){e.prototype.dispose.call(this),this._timeline=null,this._toRemove=null},e.Timeline}.apply(e,i))||(t.exports=r)},function(t,e,n){var i,r;i=[n(0),n(1),n(2)],void 0===(r=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(e,i))||(t.exports=r)},function(t,e,n){var i,r;i=[n(0),n(2),n(1),n(6)],void 0===(r=function(t){"use strict";return t.GreaterThanZero=function(){this._thresh=this.output=new t.WaveShaper(function(t){return t<=0?0:1},127),this._scale=this.input=new t.Multiply(1e4),this._scale.connect(this._thresh)},t.extend(t.GreaterThanZero,t.SignalBase),t.GreaterThanZero.prototype.dispose=function(){return t.prototype.dispose.call(this),this._scale.dispose(),this._scale=null,this._thresh.dispose(),this._thresh=null,this},t.GreaterThanZero}.apply(e,i))||(t.exports=r)},function(t,e,n){var i,r,o;r=[],void 0===(o="function"==typeof(i=function(){var s=function(t,e){this._dragged=!1,this._element=t,this._bindedMove=this._moved.bind(this),this._bindedEnd=this._ended.bind(this,e),t.addEventListener("touchstart",this._bindedEnd),t.addEventListener("touchmove",this._bindedMove),t.addEventListener("touchend",this._bindedEnd),t.addEventListener("mouseup",this._bindedEnd)};function o(t){return"running"===t.state}return s.prototype._moved=function(t){this._dragged=!0},s.prototype._ended=function(t){this._dragged||function(t){var e=t.createBuffer(1,1,t.sampleRate),n=t.createBufferSource();n.buffer=e,n.connect(t.destination),n.start(0),t.resume&&t.resume()}(t),this._dragged=!1},s.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(e,t,n){var i=new Promise(function(t){!function(e,n){o(e)?n():function t(){o(e)?n():(requestAnimationFrame(t),e.resume&&e.resume())}()}(e,t)}),r=[];return function t(e,n,i){if(Array.isArray(e)||NodeList&&e instanceof NodeList)for(var r=0;r= 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(t,e,n){"use strict";n.r(e),e.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(t,e,n){"use strict";n.r(e),e.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(t,e,n){var i,r;i=[n(0),n(17)],void 0===(r=function(r){r.Frequency=function(t,e){if(!(this instanceof r.Frequency))return new r.Frequency(t,e);r.TimeBase.call(this,t,e)},r.extend(r.Frequency,r.TimeBase),r.Frequency.prototype._primaryExpressions=Object.create(r.TimeBase.prototype._primaryExpressions),r.Frequency.prototype._primaryExpressions.midi={regexp:/^(\d+(?:\.\d+)?midi)/,method:function(t){return this.midiToFrequency(t)}},r.Frequency.prototype._primaryExpressions.note={regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method:function(t,e){var n=i[t.toLowerCase()]+12*(parseInt(e)+1);return this.midiToFrequency(n)}},r.Frequency.prototype._primaryExpressions.tr={regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,n){var i=1;return t&&"0"!==t&&(i*=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(i*=this._beatsToUnits(parseFloat(e))),n&&"0"!==n&&(i*=this._beatsToUnits(parseFloat(n)/4)),i}},r.Frequency.prototype.transpose=function(t){return this._expr=function(t,e){return t()*this.intervalToFrequencyRatio(e)}.bind(this,this._expr,t),this},r.Frequency.prototype.harmonize=function(t){return this._expr=function(t,e){for(var n=t(),i=[],r=0;rthis.buffer.duration)throw"jump time out of range";if(e>this.buffer.duration-t)throw"end time out of range";var n=t||0,i=e||void 0;this.isPlaying()&&(this.stop(0),this.play(0,this.playbackRate,this.output.gain.value,n,i))}},{key:"channels",value:function(){return this.buffer.numberOfChannels}},{key:"sampleRate",value:function(){return this.buffer.sampleRate}},{key:"frames",value:function(){return this.buffer.length}},{key:"getPeaks",value:function(t){if(!this.buffer)throw"Cannot load peaks yet, buffer is not loaded";if(t=t||5*window.width,this.buffer){for(var e=this.buffer,n=e.length/t,i=~~(n/10)||1,r=e.numberOfChannels,o=new Float32Array(Math.round(t)),s=0;so[u])&&(o[u]=h)}return o}}},{key:"reverseBuffer",value:function(){if(!this.buffer)throw"SoundFile is not done loading";var t=this._lastPos/R.sampleRate,e=this.getVolume();this.setVolume(0,.001);for(var n=this.buffer.numberOfChannels,i=0;it[o].hi&&o++,r[o]=void 0!==r[o]?(r[o]+n[s])/2:n[s]}return r}},{key:"getOctaveBands",value:function(t,e){var n=t||3,i=e||15.625,r=[],o={lo:i/Math.pow(2,1/(2*n)),ctr:i,hi:i*Math.pow(2,1/(2*n))};r.push(o);for(var s=p.audiocontext.sampleRate/2;o.hi=this._maxDelay)throw new Error("Delay Time exceeds maximum delay time of "+this._maxDelay+" second.");t.connect(this.input),this.leftDelay.delayTime.setValueAtTime(o,this.ac.currentTime),this.rightDelay.delayTime.setValueAtTime(o,this.ac.currentTime),this._leftGain.gain.value=r,this._rightGain.gain.value=r,i&&(this._leftFilter.freq(i),this._rightFilter.freq(i))}},{key:"delayTime",value:function(t){"number"!=typeof t?(t.connect(this.leftDelay.delayTime),t.connect(this.rightDelay.delayTime)):(this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.leftDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime),this.rightDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime))}},{key:"feedback",value:function(t){if(t&&"number"!=typeof t)t.connect(this._leftGain.gain),t.connect(this._rightGain.gain);else{if(1<=t)throw new Error("Feedback value will force a positive feedback loop.");"number"==typeof t&&(this._leftGain.gain.value=t,this._rightGain.gain.value=t)}return this._leftGain.gain.value}},{key:"filter",value:function(t,e){this._leftFilter.set(t,e),this._rightFilter.set(t,e)}},{key:"setType",value:function(t){switch(1===t&&(t="pingPong"),this._split.disconnect(),this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._split.connect(this.leftDelay,0),this._split.connect(this.rightDelay,1),t){case"pingPong":this._rightFilter.setType(this._leftFilter.biquad.type),this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.rightDelay),this._rightFilter.output.connect(this.leftDelay);break;default:this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.leftDelay),this._rightFilter.output.connect(this.rightDelay)}}},{key:"dispose",value:function(){de(ye(e.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=void 0,this._leftFilter=void 0,this._rightFilter=void 0,this._merge=void 0,this._leftGain=void 0,this._rightGain=void 0,this.leftDelay=void 0,this.rightDelay=void 0}}]),e}();function _e(t){return(_e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function ge(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function be(t,e){for(var n=0;nthis.length&&(this.length=i.sequence.length)}},{key:"removePhrase",value:function(t){for(var e in this.phrases)this.phrases[e].name===t&&this.phrases.splice(e,1)}},{key:"getPhrase",value:function(t){for(var e in this.phrases)if(this.phrases[e].name===t)return this.phrases[e]}},{key:"replaceSequence",value:function(t,e){for(var n in this.phrases)this.phrases[n].name===t&&(this.phrases[n].sequence=e)}},{key:"incrementStep",value:function(t){this.partStep=t.parts.length?(t.scoreStep=0,t.onended()):(t.scoreStep=0,t.parts[t.currentPart-1].stop(),t.parts[t.currentPart].start())}function Ue(t,e){for(var n=0;nthis.cutoff&&e>this.threshold&&0this.treshold){this.isDetected=!0,this.callback?this.callback(this.energy):e&&e(this.energy);var n=this;setTimeout(function(){n.isDetected=!1},this.sensitivity)}this.penergy=this.energy}}]),r}();function xn(t,e){for(var n=0;n 1.0 * width && fotitoActual == 0) { + // y aqui se indica el fondo + fotitoActual = 1; + player.x = 0; + } + // pasar de 1 a 2. + else if (player.x > 1.0 * width && fotitoActual == 1) { + // y aqui se indica el fondo. + fotitoActual = 2; + player.x = 0; + } + // pasar de 1 a 0. + else if (player.x < 0.0 * width && fotitoActual == 1) { + // y aqui se indica el fondo. + fotitoActual = 0; + player.x = width; + } + // pasar de 2 a 1. + else if (player.x < 0.0 * width && fotitoActual == 2) { + // y aqui se indica el fondo. + fotitoActual = 1; + player.x = width; + } +} + +function keyPressed() { + // definiendo si se presiona una tecla esta hará una acción. + pressedKeys[key] = true; +} + +function keyReleased() { + // y esto detiene la acción de la tecla, así que la hace momentánea. + delete pressedKeys[key]; +} + +class Player { + constructor(x, y) { + this.x = x; + this.y = y; + + this.speed = 8; + } + + update() { + // movimiento del personaje. + let mvmt = createVector(0, 0); + //condicional if, si se presiona 'a' el movimiento será en la línea x (horizontal). https://p5js.org/es/reference/#/p5/if + if (pressedKeys.a) { + mvmt.x -= 1; + } + if (pressedKeys.d) { + mvmt.x += 1; + } + if (pressedKeys.w) { + mvmt.y -= 1; + } + if (pressedKeys.s) { + mvmt.y += 1; + } + + mvmt.setMag(this.speed); + + this.x += mvmt.x; + this.y += mvmt.y; + } + + draw() { + // acá definí al personaje que es el cuadrado de color rosa. + fill(234, 134, 157); + square(this.x, this.y, 60); + noStroke(); + } +} \ No newline at end of file diff --git a/estudiantes/09-SofiaEct/clase-15/style.css b/estudiantes/09-SofiaEct/clase-15/style.css new file mode 100644 index 00000000..9386f1c2 --- /dev/null +++ b/estudiantes/09-SofiaEct/clase-15/style.css @@ -0,0 +1,7 @@ +html, body { + margin: 0; + padding: 0; +} +canvas { + display: block; +}