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.
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.
Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT\n Native CSS properties: \'grab\', \'progress\', \'cell\' etc.\n External: path for cursor\'s images\n (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)\n For more information on Native CSS cursors and url visit:\n https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT
function to be fired when any user input is\n detected within the element.\n if false is passed instead, the previously\n firing function will no longer fire.
crossOrigin property of the img element; use either \'anonymous\' or \'use-credentials\' to retrieve the image with cross-origin access (for later use with canvas. if an empty string("") is passed, CORS is not used
callback function to be called upon\n \'canplaythrough\' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content
callback function to be called upon\n \'canplaythrough\' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content
A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension.
An optional object that can contain two more arguments: delay, specifying\nhow much time we should wait before recording, and units, a string that can be either \'seconds\' or\n\'frames\'. By default it\'s \'seconds\'.
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).
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).
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.
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.
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.
function to be fired when mouse is\n double clicked over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
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.
sampleFactor - the ratio of path-length to number of samples\n(default=.1); higher values yield more points and are therefore\nmore precise
\n
simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear
the data to associate with the uniform. The type can be\na boolean (true/false), a number, an array of numbers, or\nan image (p5.Image, p5.Graphics, p5.MediaElement, p5.Texture)
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.
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.
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.
This callback function handles the sources when they\n have been enumerated. The callback function\n receives the deviceList array as its only argument
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.
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.
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
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.
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.
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.
+ *
+ * describe('pink square with red heart in the bottom right corner');
+ * background('pink');
+ * fill('red');
+ * noStroke();
+ * ellipse(67, 67, 20, 20);
+ * ellipse(83, 67, 20, 20);
+ * triangle(91, 73, 75, 95, 59, 73);
+ *
+ *
+ *
+ *
+ *
+ * let x = 0;
+ * function draw() {
+ * if (x > 100) {
+ * x = 0;
+ * }
+ * background(220);
+ * fill(0, 255, 0);
+ * ellipse(x, 50, 40, 40);
+ * x = x + 0.1;
+ * describe('green circle at x pos ' + round(x) + ' moving to the right');
+ * }
+ *
+ *
+ *
+ */
+ _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);
+ }
+ }
+ };
+ /**
+ * This function creates a screen-reader accessible
+ * description for elements —shapes or groups of shapes that create
+ * meaning together— in the canvas. The first paramater should
+ * be the name of the element. The second parameter should be a string
+ * with a description of the element. The third parameter is optional.
+ * If specified, it determines how the element description is displayed.
+ *
+ * describeElement(name, text, LABEL)
+ * displays the element description to all users as a
+ *
+ * tombstone or exhibit label/caption in a div
+ * adjacent to the canvas. You can style it as you wish in your CSS.
+ *
+ * describeElement(name, text, FALLBACK)
+ * makes the element description accessible to screen-reader users
+ * only, in
+ * a sub DOM inside the canvas element. If a second parameter is not
+ * specified, by default, the element description will only be available
+ * to screen-reader users.
+ *
+ * @method describeElement
+ * @param {String} name name of the element
+ * @param {String} text description of the element
+ * @param {Constant} [display] either LABEL or FALLBACK
+ *
+ * @example
+ *
+ *
+ * describe('Heart and yellow circle over pink background');
+ * noStroke();
+ * background('pink');
+ * describeElement('Circle', 'Yellow circle in the top left corner');
+ * fill('yellow');
+ * ellipse(25, 25, 40, 40);
+ * describeElement('Heart', 'red heart in the bottom right corner');
+ * fill('red');
+ * ellipse(66.6, 66.6, 20, 20);
+ * ellipse(83.2, 66.6, 20, 20);
+ * triangle(91.2, 72.6, 75, 95, 58.6, 72.6);
+ *
+ *
+ */
+ _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 = '
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 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 adjecent 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': 290,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.string.ends-with': 202,
+ 'core-js/modules/es.string.replace': 207
+ }
+ ],
+ 270: [
+ function (_dereq_, module, exports) {
+ 'use strict';
+ _dereq_('core-js/modules/es.array.concat');
+ _dereq_('core-js/modules/es.array.map');
+ _dereq_('core-js/modules/es.array.concat');
+ _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
+ };
+ } /**
+ * @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.apply(null, Array(10)).map(function () {
+ });
+ for (var r in cells) {
+ cells[r] = Array.apply(null, Array(10)).map(function () {
+ });
+ }
+ 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 = '
';
+ }
+ 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': 290,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.map': 179
+ }
+ ],
+ 271: [
+ function (_dereq_, module, exports) {
+ 'use strict';
+ _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');
+ _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
+ };
+ } /**
+ * @module Environment
+ * @submodule Environment
+ * @for p5
+ * @requires core
+ */
+ /**
+ * textOutput() creates a screenreader
+ * accessible output that describes the shapes present on the canvas.
+ * The general description of the canvas includes canvas size,
+ * canvas color, and number of elements in the canvas
+ * (example: 'Your output is a, 400 by 400 pixels, lavender blue
+ * canvas containing the following 4 shapes:'). This description
+ * is followed by a list of shapes where the color, position, and area
+ * of each shape are described (example: "orange ellipse at top left
+ * covering 1% of the canvas"). Each element can be selected to get
+ * more details. A table of elements is also provided. In this table,
+ * shape, color, location, coordinates and area are described
+ * (example: "orange ellipse location=top left area=2").
+ *
+ * textOutput() and textOutput(FALLBACK)
+ * make the output available in
+ * a sub DOM inside the canvas element which is accessible to screen readers.
+ * textOutput(LABEL) creates an
+ * additional div with the output adjacent to the canvas, this is useful
+ * for non-screen reader users that might want to display the output outside
+ * of the canvas' sub DOM as they code. However, using LABEL will create
+ * unnecessary redundancy for screen reader users. We recommend using LABEL
+ * only as part of the development process of a sketch and removing it before
+ * publishing or sharing with screen reader users.
+ *
+ * @method textOutput
+ * @param {Constant} [display] either FALLBACK or LABEL
+ *
+ * @example
+ *
+ *
+ */
+
+ _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');
+ }
+ }
+ };
+ /**
+ * gridOutput() lays out the
+ * content of the canvas in the form of a grid (html table) based
+ * on the spatial location of each shape. A brief
+ * description of the canvas is available before the table output.
+ * This description includes: color of the background, size of the canvas,
+ * number of objects, and object types (example: "lavender blue canvas is
+ * 200 by 200 and contains 4 objects - 3 ellipses 1 rectangle"). The grid
+ * describes the content spatially, each element is placed on a cell of the
+ * table depending on its position. Within each cell an element the color
+ * and type of shape of that element are available (example: "orange ellipse").
+ * These descriptions can be selected individually to get more details.
+ * A list of elements where shape, color, location, and area are described
+ * (example: "orange ellipse location=top left area=1%") is also available.
+ *
+ * gridOutput() and gridOutput(FALLBACK)
+ * make the output available in
+ * a sub DOM inside the canvas element which is accessible to screen readers.
+ * gridOutput(LABEL) creates an
+ * additional div with the output adjacent to the canvas, this is useful
+ * for non-screen reader users that might want to display the output outside
+ * of the canvas' sub DOM as they code. However, using LABEL will create
+ * unnecessary redundancy for screen reader users. We recommend using LABEL
+ * only as part of the development process of a sketch and removing it before
+ * publishing or sharing with screen reader users.
+ *
+ * @method gridOutput
+ * @param {Constant} [display] either FALLBACK or LABEL
+ *
+ * @example
+ *
');
+ }
+ 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 = '
');
+ } 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': 290,
+ 'core-js/modules/es.array.concat': 167
+ }
+ ],
+ 273: [
+ 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.Geometry');
+ _dereq_('./webgl/p5.Matrix');
+ _dereq_('./webgl/p5.RendererGL.Immediate');
+ _dereq_('./webgl/p5.RendererGL');
+ _dereq_('./webgl/p5.RendererGL.Retained');
+ _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': 268,
+ './accessibility/describe': 269,
+ './accessibility/gridOutput': 270,
+ './accessibility/outputs': 271,
+ './accessibility/textOutput': 272,
+ './color/color_conversion': 274,
+ './color/creating_reading': 275,
+ './color/p5.Color': 276,
+ './color/setting': 277,
+ './core/constants': 278,
+ './core/environment': 279,
+ './core/friendly_errors/fes_core': 281,
+ './core/friendly_errors/file_errors': 282,
+ './core/friendly_errors/sketch_reader': 283,
+ './core/friendly_errors/stacktrace': 284,
+ './core/friendly_errors/validate_params': 285,
+ './core/helpers': 286,
+ './core/init': 287,
+ './core/legacy': 289,
+ './core/main': 290,
+ './core/p5.Element': 291,
+ './core/p5.Graphics': 292,
+ './core/p5.Renderer': 293,
+ './core/p5.Renderer2D': 294,
+ './core/preload': 295,
+ './core/rendering': 296,
+ './core/shape/2d_primitives': 297,
+ './core/shape/attributes': 298,
+ './core/shape/curves': 299,
+ './core/shape/vertex': 300,
+ './core/shim': 301,
+ './core/structure': 302,
+ './core/transform': 303,
+ './data/local_storage.js': 304,
+ './data/p5.TypedDict': 305,
+ './dom/dom': 306,
+ './events/acceleration': 307,
+ './events/keyboard': 308,
+ './events/mouse': 309,
+ './events/touch': 310,
+ './image/filters': 311,
+ './image/image': 312,
+ './image/loading_displaying': 313,
+ './image/p5.Image': 314,
+ './image/pixels': 315,
+ './io/files': 316,
+ './io/p5.Table': 317,
+ './io/p5.TableRow': 318,
+ './io/p5.XML': 319,
+ './math/calculation': 320,
+ './math/math': 321,
+ './math/noise': 322,
+ './math/p5.Vector': 323,
+ './math/random': 324,
+ './math/trigonometry': 325,
+ './typography/attributes': 326,
+ './typography/loading_displaying': 327,
+ './typography/p5.Font': 328,
+ './utilities/array_functions': 329,
+ './utilities/conversion': 330,
+ './utilities/string_functions': 331,
+ './utilities/time_date': 332,
+ './webgl/3d_primitives': 333,
+ './webgl/interaction': 334,
+ './webgl/light': 335,
+ './webgl/loading': 336,
+ './webgl/material': 337,
+ './webgl/p5.Camera': 338,
+ './webgl/p5.Geometry': 339,
+ './webgl/p5.Matrix': 340,
+ './webgl/p5.RenderBuffer': 341,
+ './webgl/p5.RendererGL': 344,
+ './webgl/p5.RendererGL.Immediate': 342,
+ './webgl/p5.RendererGL.Retained': 343,
+ './webgl/p5.Shader': 345,
+ './webgl/p5.Texture': 346,
+ './webgl/text': 347
+ }
+ ],
+ 274: [
+ 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.
+ */
+ _main.default.ColorConversion._hsbaToHSLA = function (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.
+ */
+ _main.default.ColorConversion._hsbaToRGBA = function (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.
+ */
+ _main.default.ColorConversion._hslaToHSBA = function (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.
+ */
+ _main.default.ColorConversion._hslaToRGBA = function (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.
+ */
+ _main.default.ColorConversion._rgbaToHSBA = function (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.
+ */
+ _main.default.ColorConversion._rgbaToHSLA = function (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': 290
+ }
+ ],
+ 275: [
+ 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
+ */
+ /**
+ * Extracts the alpha value from a color or pixel array.
+ *
+ * @method alpha
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the alpha value
+ *
+ * @example
+ *
+ *
+ * noStroke();
+ * let c = color(0, 126, 255, 102);
+ * fill(c);
+ * rect(15, 15, 35, 70);
+ * let value = alpha(c); // Sets 'value' to 102
+ * fill(value);
+ * rect(50, 15, 35, 70);
+ * describe('Left half of canvas light blue and right half light charcoal grey.');
+ *
+ *
+ */
+
+ _main.default.prototype.alpha = function (c) {
+ _main.default._validateParameters('alpha', arguments);
+ return this.color(c)._getAlpha();
+ };
+ /**
+ * Extracts the blue value from a color or pixel array.
+ *
+ * @method blue
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the blue value
+ * @example
+ *
+ *
+ * let c = color(175, 100, 220);
+ * fill(c);
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ * let blueValue = blue(c);
+ * fill(0, 0, blueValue);
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ * describe('Left half of canvas light purple and right half a royal blue.');
+ *
+ *
+ *
+ */
+ _main.default.prototype.blue = function (c) {
+ _main.default._validateParameters('blue', arguments);
+ return this.color(c)._getBlue();
+ };
+ /**
+ * Extracts the HSB brightness value from a color or pixel array.
+ *
+ * @method brightness
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the brightness value
+ *
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = brightness(c); // Sets 'value' to 255
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ * describe(`Left half of canvas salmon pink and the right half with its
+ * brightness colored white.`);
+ *
+ *
+ *
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color('hsb(60, 100%, 50%)');
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = brightness(c); // A 'value' of 50% is 127.5
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ * describe(`Left half of canvas olive colored and the right half with its
+ * brightness color gray.`);
+ *
+ *
+ */
+ _main.default.prototype.brightness = function (c) {
+ _main.default._validateParameters('brightness', arguments);
+ return this.color(c)._getBrightness();
+ };
+ /**
+ * Creates colors for storing in variables of the color datatype. The
+ * parameters are interpreted as RGB or HSB values depending on the
+ * current colorMode(). The default mode is RGB values from 0 to 255
+ * and, therefore, the function call color(255, 204, 0) will return a
+ * bright yellow color.
+ *
+ * Note that if only one value is provided to color(), it will be interpreted
+ * as a grayscale value. Add a second value, and it will be used for alpha
+ * transparency. When three values are specified, they are interpreted as
+ * either RGB or HSB values. Adding a fourth value applies alpha
+ * transparency.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color
+ * strings and all named color strings are supported. In this case, an alpha
+ * number value as a second argument is not supported, the RGBA form should be
+ * used.
+ *
+ * @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
+ *
+ *
+ * let c = color(255, 204, 0);
+ * fill(c);
+ * noStroke();
+ * rect(30, 20, 55, 55);
+ * describe(`Yellow rect in middle right of canvas,
+ * with 55 pixel width and height.`);
+ *
+ *
+ *
+ *
+ *
+ * let c = color(255, 204, 0);
+ * fill(c);
+ * noStroke();
+ * ellipse(25, 25, 80, 80); // Draw left circle
+ * // Using only one value generates a grayscale value.
+ * c = color(65);
+ * fill(c);
+ * ellipse(75, 75, 80, 80);
+ * describe(`Yellow ellipse in top left of canvas, black ellipse in bottom
+ * right, both 80×80.`);
+ *
+ *
+ *
+ *
+ *
+ * // You can use named SVG & CSS colors
+ * let c = color('magenta');
+ * fill(c);
+ * noStroke();
+ * rect(20, 20, 60, 60);
+ * describe('Bright fuchsia rect in middle of canvas, 60 pixel width and height.');
+ *
+ *
+ *
+ *
+ *
+ * // Example of hex color codes
+ * noStroke();
+ * let c = color('#0f0');
+ * fill(c);
+ * rect(0, 10, 45, 80);
+ * c = color('#00ff00');
+ * fill(c);
+ * rect(55, 10, 45, 80);
+ * describe('Two bright green rects on opposite sides of the canvas, both 45×80.');
+ *
+ *
+ *
+ *
+ *
+ * // RGB and RGBA color strings are also supported
+ * // these all set to the same color (solid blue)
+ * let c;
+ * noStroke();
+ * c = color('rgb(0,0,255)');
+ * fill(c);
+ * rect(10, 10, 35, 35); // Draw rectangle
+ * c = color('rgb(0%, 0%, 100%)');
+ * fill(c);
+ * rect(55, 10, 35, 35); // Draw rectangle
+ * c = color('rgba(0, 0, 255, 1)');
+ * fill(c);
+ * rect(10, 55, 35, 35); // Draw rectangle
+ * c = color('rgba(0%, 0%, 100%, 1)');
+ * fill(c);
+ * rect(55, 55, 35, 35); // Draw rectangle
+ * describe('Four blue rects in each corner of the canvas, each are 35×35.');
+ *
+ *
+ *
+ *
+ *
+ * // HSL color can also be specified by value
+ * let c = color('hsl(160, 100%, 50%)');
+ * noStroke();
+ * fill(c);
+ * rect(0, 10, 45, 80); // Draw rectangle
+ * c = color('hsla(160, 100%, 50%, 0.5)');
+ * fill(c);
+ * rect(55, 10, 45, 80); // Draw rectangle
+ * describe(`Bright sea green rect on left and darker rect on right of canvas,
+ * both 45×80.`);
+ *
+ *
+ *
+ *
+ *
+ * // HSB color can also be specified
+ * let c = color('hsb(160, 100%, 50%)');
+ * noStroke();
+ * fill(c);
+ * rect(0, 10, 45, 80); // Draw rectangle
+ * c = color('hsba(160, 100%, 50%, 0.5)');
+ * fill(c);
+ * rect(55, 10, 45, 80); // Draw rectangle
+ * describe(`Dark green rect on left and lighter green rect on right of canvas,
+ * both 45×80.`);
+ *
+ *
+ *
+ *
+ *
+ * noStroke();
+ * let c = color(50, 55, 100);
+ * fill(c);
+ * rect(0, 10, 45, 80); // Draw left rect
+ * colorMode(HSB, 100);
+ * c = color(50, 55, 100);
+ * fill(c);
+ * rect(55, 10, 45, 80);
+ * describe(`Dark blue rect on left and light teal rect on right of canvas,
+ * both 45×80.`);
+ *
+ *
+ */
+ /**
+ * @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 () {
+ _main.default._validateParameters('color', arguments);
+ if (arguments[0] instanceof _main.default.Color) {
+ return arguments[0]; // Do nothing if argument is already a color object.
+ }
+ var args = arguments[0] instanceof Array ? arguments[0] : arguments;
+ return new _main.default.Color(this, args);
+ };
+ /**
+ * Extracts the green value from a color or pixel array.
+ *
+ * @method green
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the green value
+ * @example
+ *
+ *
+ * let c = color(20, 75, 200); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * let greenValue = green(c); // Get green in 'c'
+ * print(greenValue); // Print "75.0"
+ * fill(0, greenValue, 0); // Use 'greenValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ * describe(`blue rect on left and green on right, both with black outlines
+ * & 35×60.`);
+ *
+ *
+ */
+ _main.default.prototype.green = function (c) {
+ _main.default._validateParameters('green', arguments);
+ return this.color(c)._getGreen();
+ };
+ /**
+ * Extracts the hue value from a color or pixel array.
+ *
+ * Hue exists in both HSB and HSL. This function will return the
+ * HSB-normalized hue when supplied with an HSB color object (or when supplied
+ * with a pixel array while the color mode is HSB), but will default to the
+ * HSL-normalized hue otherwise. (The values will only be different if the
+ * maximum hue setting for each system is different.)
+ *
+ * @method hue
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the hue
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = hue(c); // Sets 'value' to "0"
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ * describe('salmon pink rect on left and black on right, both 35×60.');
+ *
+ *
+ *
+ */
+ _main.default.prototype.hue = function (c) {
+ _main.default._validateParameters('hue', arguments);
+ return this.color(c)._getHue();
+ };
+ /**
+ * Blends two colors to find a third color somewhere between them. The amt
+ * parameter is the amount to interpolate between the two values where 0.0
+ * is equal to the first color, 0.1 is very near the first color, 0.5 is halfway
+ * in between, etc. An amount below 0 will be treated as 0. Likewise, amounts
+ * above 1 will be capped at 1. This is different from the behavior of lerp(),
+ * but necessary because otherwise numbers outside the range will produce
+ * strange and unexpected colors.
+ *
+ * The way that colors are interpolated depends on the current color mode.
+ *
+ * @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
+ *
+ *
+ * colorMode(RGB);
+ * stroke(255);
+ * background(51);
+ * let from = color(218, 165, 32);
+ * let to = color(72, 61, 139);
+ * colorMode(RGB); // Try changing to HSB.
+ * let interA = lerpColor(from, to, 0.33);
+ * let interB = lerpColor(from, to, 0.66);
+ * fill(from);
+ * rect(10, 20, 20, 60);
+ * fill(interA);
+ * rect(30, 20, 20, 60);
+ * fill(interB);
+ * rect(50, 20, 20, 60);
+ * fill(to);
+ * rect(70, 20, 20, 60);
+ * describe(`4 rects one tan, brown, brownish purple, purple, with white
+ * outlines & 20×60`);
+ *
+ *
+ */
+ _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.
+
+ l0 = this.lerp(fromArray[0], toArray[0], amt);
+ 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);
+ };
+ /**
+ * Extracts the HSL lightness value from a color or pixel array.
+ *
+ * @method lightness
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the lightness
+ *
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSL);
+ * let c = color(156, 100, 50, 1);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = lightness(c); // Sets 'value' to 50
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ * describe(`light pastel green rect on left and dark grey rect on right,
+ * both 35×60.`);
+ *
+ *
+ */
+ _main.default.prototype.lightness = function (c) {
+ _main.default._validateParameters('lightness', arguments);
+ return this.color(c)._getLightness();
+ };
+ /**
+ * Extracts the red value from a color or pixel array.
+ *
+ * @method red
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the red value
+ * @example
+ *
+ *
+ * let c = color(255, 204, 0); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * let redValue = red(c); // Get red in 'c'
+ * print(redValue); // Print "255.0"
+ * fill(redValue, 0, 0); // Use 'redValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ * describe(`yellow rect on left and red rect on right, both with black
+ * outlines and 35×60.`);
+ *
+ *
+ *
+ *
+ *
+ * colorMode(RGB, 255); // Sets the range for red, green, and blue to 255
+ * let c = color(127, 255, 0);
+ * colorMode(RGB, 1); // Sets the range for red, green, and blue to 1
+ * let myColor = red(c);
+ * print(myColor); // 0.4980392156862745
+ * describe('grey canvas');
+ *
+ *
+ */
+ _main.default.prototype.red = function (c) {
+ _main.default._validateParameters('red', arguments);
+ return this.color(c)._getRed();
+ };
+ /**
+ * Extracts the saturation value from a color or pixel array.
+ *
+ * Saturation is scaled differently in HSB and HSL. This function will return
+ * the HSB saturation when supplied with an HSB color object (or when supplied
+ * with a pixel array while the color mode is HSB), but will default to the
+ * HSL saturation otherwise.
+ *
+ * @method saturation
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the saturation value
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = saturation(c); // Sets 'value' to 126
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ * describe('deep pink rect on left and grey rect on right, both 35×60.');
+ *
+ *
+ */
+ _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': 278,
+ '../core/friendly_errors/fes_core': 281,
+ '../core/friendly_errors/file_errors': 282,
+ '../core/friendly_errors/validate_params': 285,
+ '../core/main': 290,
+ './p5.Color': 276,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.map': 179,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 276: [
+ 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.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.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.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.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
+ };
+ } /**
+ * @module Color
+ * @submodule Creating & Reading
+ * @for p5
+ * @requires core
+ * @requires constants
+ * @requires color_conversion
+ */
+ /**
+ * Each color stores the color mode and level maxes that were applied at the
+ * time of its construction. These are used to interpret the input arguments
+ * (at construction and later for that instance of color) and to format the
+ * output e.g. when saturation() is requested.
+ *
+ * Internally, we store an array representing the ideal RGBA values in floating
+ * point form, normalized from 0 to 1. From this we calculate the closest
+ * screen color (RGBA levels from 0 to 255) and expose this to the renderer.
+ *
+ * We also cache normalized, floating-point components of the color in various
+ * representations as they are calculated. This is done to prevent repeating a
+ * conversion that has already been performed.
+ *
+ * @class p5.Color
+ * @constructor
+ */
+
+ _main.default.Color = function (pInst, vals) {
+ // Record color mode and maxes at time of construction.
+ this._storeModeAndMaxes(pInst._colorMode, pInst._colorMaxes); // Calculate normalized RGBA values.
+ if (this.mode !== constants.RGB && this.mode !== constants.HSL && this.mode !== constants.HSB) {
+ throw new Error(''.concat(this.mode, ' is an invalid colorMode.'));
+ } else {
+ this._array = _main.default.Color._parseInputs.apply(this, vals);
+ } // Expose closest screen color.
+
+ this._calculateLevels();
+ return this;
+ };
+ /**
+ * This method returns the color formatted as a string. This can be useful
+ * for debugging, or for using p5.js with other libraries.
+ *
+ * @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
+ *
+ * @example
+ *
+ */
+ _main.default.Color.prototype.setRed = function (new_red) {
+ this._array[0] = new_red / this.maxes[constants.RGB][0];
+ this._calculateLevels();
+ };
+ /**
+ * The setGreen method sets the green component of a color.
+ * The range depends on your color mode, in the default RGB mode it's between 0 and 255.
+ * @method setGreen
+ * @param {Number} green the new green value
+ * @example
+ *
+ *
+ **/
+ _main.default.Color.prototype.setGreen = function (new_green) {
+ this._array[1] = new_green / this.maxes[constants.RGB][1];
+ this._calculateLevels();
+ };
+ /**
+ * The setBlue method sets the blue component of a color.
+ * The range depends on your color mode, in the default RGB mode it's between 0 and 255.
+ * @method setBlue
+ * @param {Number} blue the new blue value
+ * @example
+ *
+ *
+ **/
+ _main.default.Color.prototype.setBlue = function (new_blue) {
+ this._array[2] = new_blue / this.maxes[constants.RGB][2];
+ this._calculateLevels();
+ };
+ /**
+ * The setAlpha method sets the transparency (alpha) value of a color.
+ * The range depends on your color mode, in the default RGB mode it's between 0 and 255.
+ * @method setAlpha
+ * @param {Number} alpha the new alpha value
+ * @example
+ *
+ */
+ _main.default.Color._parseInputs = function (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 _main.default.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;
+ };
+ var _default = _main.default.Color;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 278,
+ '../core/main': 290,
+ './color_conversion': 274,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.join': 177,
+ 'core-js/modules/es.array.map': 179,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.constructor': 198,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.trim': 211,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 277: [
+ 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
+ */
+ /**
+ * The background() function sets the color used
+ * for the background of the p5.js canvas. The default background is transparent.
+ * This function is typically used within draw() to clear
+ * the display window at the beginning of each frame, but it can be used inside
+ * setup() to set the background on the first frame of
+ * animation or if the background need only be set once.
+ *
+ * The color is either specified in terms of the RGB, HSB, or HSL color depending
+ * on the current colorMode. (The default color space
+ * is RGB, with each value in the range from 0 to 255). The alpha range by default
+ * is also 0 to 255.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color strings
+ * and all named color strings are supported. In this case, an alpha number
+ * value as a second argument is not supported, the RGBA form should be used.
+ *
+ * A p5.Color object can also be provided to set the background color.
+ *
+ * A p5.Image can also be provided to set the background image.
+ *
+ * @method background
+ * @param {p5.Color} color any value created by the color() function
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * // p5 Color object
+ * background(color(0, 0, 255));
+ * describe('canvas with 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 or hue value (depending on the current color
+ * mode)
+ * @param {Number} v2 green or saturation value (depending on the current
+ * color mode)
+ * @param {Number} v3 blue or brightness value (depending on the current
+ * color mode)
+ * @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 within a buffer. This function only clears the canvas.
+ * It will not clear objects created by createX() methods such as
+ * createVideo() or createDiv().
+ * Unlike the main graphics context, pixels in additional graphics areas created
+ * with createGraphics() can be entirely
+ * or partially transparent. This function clears everything to make all of
+ * the pixels 100% transparent.
+ *
+ * Note: In WebGL mode, this function can be passed normalized RGBA color values in
+ * order to clear the screen to a specific color. In addition to color, it will also
+ * clear the depth buffer. If you are not using the webGL renderer
+ * these color values will have no effect.
+ *
+ * @method clear
+ * @chainable
+ * @example
+ *
+ *
+ * // Clear the screen on mouse press.
+ * function draw() {
+ * ellipse(mouseX, mouseY, 20, 20);
+ * describe(`small white ellipses are continually drawn at mouse’s x and y
+ * coordinates.`);
+ * }
+ * function mousePressed() {
+ * clear();
+ * background(128);
+ * describe(
+ * 'canvas is cleared, small white ellipse is drawn at mouse X and mouse Y'
+ * );
+ * }
+ *
+ *
+ *
+ * @param {Number} r normalized red val.
+ * @param {Number} g normalized green val.
+ * @param {Number} b normalized blue val.
+ * @param {Number} a normalized alpha val.
+ */
+ _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;
+ };
+ /**
+ * colorMode() changes the way p5.js interprets
+ * color data. By default, the parameters for fill(),
+ * stroke(), background(),
+ * and color() are defined by values between 0 and 255
+ * using the RGB color model. This is equivalent to setting colorMode(RGB, 255).
+ * Setting colorMode(HSB) lets you use the HSB system instead. By default, this
+ * is colorMode(HSB, 360, 100, 100, 1). You can also use HSL.
+ *
+ * Note: existing color objects remember the mode that they were created in,
+ * so you can change modes as you like without affecting 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
+ *
+ *
+ * noStroke();
+ * colorMode(RGB, 100);
+ * for (let i = 0; i < 100; i++) {
+ * for (let j = 0; j < 100; j++) {
+ * stroke(i, j, 0);
+ * point(i, j);
+ * }
+ * }
+ * describe(
+ * 'Green to red gradient from bottom left to top right with shading from top left'
+ * );
+ *
+ *
+ *
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 100);
+ * for (let i = 0; i < 100; i++) {
+ * for (let j = 0; j < 100; j++) {
+ * stroke(i, j, 100);
+ * point(i, j);
+ * }
+ * }
+ * describe(`Rainbow gradient from left to right.
+ * Brightness increasing to white at top.`);
+ *
+ *
+ *
+ *
+ *
+ * colorMode(RGB, 255);
+ * let c = color(127, 255, 0);
+ * colorMode(RGB, 1);
+ * let myColor = c._getRed();
+ * text(myColor, 10, 10, 80, 80);
+ * describe('value of color red 0.4980... written on canvas');
+ *
+ *
+ *
+ */
+ /**
+ * @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. For example, if you run fill(204, 102, 0),
+ * all shapes drawn after the fill command will be filled with the color orange.
+ * This color is either specified in terms of the RGB or HSB color depending on
+ * the current colorMode(). (The default color space
+ * is RGB, with each value in the range from 0 to 255). The alpha range by default
+ * is also 0 to 255.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color strings
+ * and all named color strings are supported. In this case, an alpha number
+ * value as a second argument is not supported, the RGBA form should be used.
+ *
+ * A p5.Color object can also be provided to set the fill color.
+ *
+ * @method fill
+ * @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]
+ * @chainable
+ * @example
+ *
+ *
+ * // Grayscale integer value
+ * fill(51);
+ * rect(20, 20, 60, 60);
+ * describe('dark charcoal grey rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // R, G & B integer values
+ * fill(255, 204, 0);
+ * rect(20, 20, 60, 60);
+ * describe('yellow rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // H, S & B integer values
+ * colorMode(HSB);
+ * fill(255, 204, 100);
+ * rect(20, 20, 60, 60);
+ * describe('royal blue rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // Named SVG/CSS color string
+ * fill('red');
+ * rect(20, 20, 60, 60);
+ * describe('red rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // three-digit hexadecimal RGB notation
+ * fill('#fae');
+ * rect(20, 20, 60, 60);
+ * describe('pink rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // six-digit hexadecimal RGB notation
+ * fill('#222222');
+ * rect(20, 20, 60, 60);
+ * describe('black rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // integer RGB notation
+ * fill('rgb(0,255,0)');
+ * rect(20, 20, 60, 60);
+ * describe('bright green rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // integer RGBA notation
+ * fill('rgba(0,255,0, 0.25)');
+ * rect(20, 20, 60, 60);
+ * describe('soft green rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGB notation
+ * fill('rgb(100%,0%,10%)');
+ * rect(20, 20, 60, 60);
+ * describe('red rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGBA notation
+ * fill('rgba(100%,0%,100%,0.5)');
+ * rect(20, 20, 60, 60);
+ * describe('dark fuchsia rect with black outline in center of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // p5 Color object
+ * fill(color(0, 0, 255));
+ * rect(20, 20, 60, 60);
+ * describe('blue rect with black outline in center of canvas');
+ *
+ *
+ */
+ /**
+ * @method fill
+ * @param {String} value a color string
+ * @chainable
+ */
+ /**
+ * @method fill
+ * @param {Number} gray a gray 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 filling geometry. If both noStroke() and noFill() are called,
+ * nothing will be drawn to the screen.
+ *
+ * @method noFill
+ * @chainable
+ * @example
+ *
+ *
+ * rect(15, 10, 55, 55);
+ * noFill();
+ * rect(20, 20, 60, 60);
+ * describe(`White rect at top middle and noFill rect center,
+ * both with black outlines.`);
+ *
+ *
+ */
+ _main.default.prototype.noStroke = function () {
+ this._renderer._setProperty('_doStroke', false);
+ return this;
+ };
+ /**
+ * Sets the color used to draw lines and borders around shapes. This color
+ * is either specified in terms of the RGB or HSB color depending on the
+ * current colorMode() (the default color space
+ * is RGB, with each value in the range from 0 to 255). The alpha range by
+ * default is also 0 to 255.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color
+ * strings and all named color strings are supported. In this case, an alpha
+ * number value as a second argument is not supported, the RGBA form should be
+ * used.
+ *
+ * A p5.Color object can also be provided to set the stroke color.
+ *
+ * @method stroke
+ * @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]
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * // Grayscale integer value
+ * strokeWeight(4);
+ * stroke(51);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with dark charcoal grey outline.');
+ *
+ *
+ *
+ *
+ *
+ * // R, G & B integer values
+ * stroke(255, 204, 0);
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with yellow outline.');
+ *
+ *
+ *
+ *
+ *
+ * // H, S & B integer values
+ * colorMode(HSB);
+ * strokeWeight(4);
+ * stroke(255, 204, 100);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with royal blue outline.');
+ *
+ *
+ *
+ *
+ *
+ * // Named SVG/CSS color string
+ * stroke('red');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with red outline.');
+ *
+ *
+ *
+ *
+ *
+ * // three-digit hexadecimal RGB notation
+ * stroke('#fae');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with pink outline.');
+ *
+ *
+ *
+ *
+ *
+ * // six-digit hexadecimal RGB notation
+ * stroke('#222222');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with black outline.');
+ *
+ *
+ *
+ *
+ *
+ * // integer RGB notation
+ * stroke('rgb(0,255,0)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with bright green outline.');
+ *
+ *
+ *
+ *
+ *
+ * // integer RGBA notation
+ * stroke('rgba(0,255,0,0.25)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with soft green outline.');
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGB notation
+ * stroke('rgb(100%,0%,10%)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with red outline.');
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGBA notation
+ * stroke('rgba(100%,0%,100%,0.5)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with dark fuchsia outline.');
+ *
+ *
+ *
+ *
+ *
+ * // p5 Color object
+ * stroke(color(0, 0, 255));
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ * describe('White rect at center with blue outline.');
+ *
+ *
+ */
+ /**
+ * @method stroke
+ * @param {String} value a color string
+ * @chainable
+ */
+ /**
+ * @method stroke
+ * @param {Number} gray a gray 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;
+ };
+ /**
+ * All drawing that follows erase() will subtract from
+ * the canvas. Erased areas will reveal the web page underneath the canvas. Erasing
+ * can be canceled with noErase().
+ *
+ * Drawing done with image() and
+ * background() in between erase() and
+ * noErase() will not erase the canvas but works as usual.
+ *
+ * @method erase
+ * @param {Number} [strengthFill] A number (0-255) for the strength of erasing for a shape's fill.
+ * This will default to 255 when no argument is given, which
+ * is full strength.
+ * @param {Number} [strengthStroke] A number (0-255) for the strength of erasing for a shape's stroke.
+ * This will default to 255 when no argument is given, which
+ * is full strength.
+ *
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 80×80 white quarter-circle with curve toward bottom right of canvas.
+ */
+ exports.WAIT = WAIT;
+ var HALF_PI = _PI / 2;
+ /**
+ * PI is a mathematical constant with the value
+ * 3.14159265358979323846. It is the ratio of the circumference
+ * of a circle to its diameter. It is useful in combination with
+ * the trigonometric functions sin() and cos().
+ *
+ * @property {Number} PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, PI);
+ *
+ *
+ * @alt
+ * white half-circle with curve toward bottom of canvas.
+ */
+ exports.HALF_PI = HALF_PI;
+ var PI = _PI;
+ /**
+ * QUARTER_PI is a mathematical constant with the value 0.7853982.
+ * It is one quarter the ratio of the circumference of a circle to
+ * its diameter. It is useful in combination with the trigonometric
+ * functions sin() and cos().
+ *
+ * @property {Number} QUARTER_PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, QUARTER_PI);
+ *
+ *
+ * @alt
+ * white eighth-circle rotated about 40 degrees with curve bottom right canvas.
+ */
+ exports.PI = PI;
+ var QUARTER_PI = _PI / 4;
+ /**
+ * TAU is an alias for TWO_PI, a mathematical constant with the
+ * value 6.28318530717958647693. It is twice the ratio of the
+ * circumference of a circle to its diameter. It is useful in
+ * combination with the trigonometric functions sin() and cos().
+ *
+ * @property {Number} TAU
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, TAU);
+ *
+ *
+ * @alt
+ * 80×80 white ellipse shape in center of canvas.
+ */
+ exports.QUARTER_PI = QUARTER_PI;
+ var TAU = _PI * 2;
+ /**
+ * TWO_PI is a mathematical constant with the value
+ * 6.28318530717958647693. It is twice the ratio of the
+ * circumference of a circle to its diameter. It is useful in
+ * combination with the trigonometric functions sin() and cos().
+ *
+ * @property {Number} TWO_PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, TWO_PI);
+ *
+ *
+ * @alt
+ * 80×80 white ellipse shape in center of canvas.
+ */
+ exports.TAU = TAU;
+ var TWO_PI = _PI * 2;
+ /**
+ * Constant to be used with the angleMode() function, to set the mode in
+ * which p5.js interprets and calculates angles (either DEGREES or RADIANS).
+ * @property {String} DEGREES
+ * @final
+ *
+ * @example
+ *
+ */
+ exports.TWO_PI = TWO_PI;
+ var DEGREES = 'degrees';
+ /**
+ * Constant to be used with the angleMode() function, to set the mode
+ * in which p5.js interprets and calculates angles (either RADIANS or DEGREES).
+ * @property {String} RADIANS
+ * @final
+ *
+ * @example
+ *
+ * let x = 10;
+ * print('The value of x is ' + x);
+ * // prints "The value of x is 10"
+ *
+ *
+ * @alt
+ * default grey canvas
+ */
+ _main.default.prototype.print = function () {
+ if (!arguments.length) {
+ _windowPrint();
+ } else {
+ var _console;
+ (_console = console).log.apply(_console, arguments);
+ }
+ };
+ /**
+ * The system variable frameCount contains the
+ * number of frames that have been displayed since the program started. Inside
+ * setup() the value is 0, after the first iteration
+ * of draw() it is 1, etc.
+ *
+ * @property {Integer} frameCount
+ * @readOnly
+ * @example
+ *
+ *
+ * @alt
+ * numbers rapidly counting upward with frame count set to 30.
+ */
+ _main.default.prototype.frameCount = 0;
+ /**
+ * The system variable deltaTime contains the time
+ * difference between the beginning of the previous frame and the beginning
+ * of the current frame in milliseconds.
+ *
+ * This variable is useful for creating time sensitive animation or physics
+ * calculation that should stay constant regardless of frame rate.
+ *
+ * @property {Integer} deltaTime
+ * @readOnly
+ * @example
+ *
+ * let rectX = 0;
+ * let fr = 30; //starting FPS
+ * let clr;
+ *
+ * function setup() {
+ * background(200);
+ * frameRate(fr); // Attempt to refresh at starting FPS
+ * clr = color(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rectX = rectX + 1 * (deltaTime / 50); // Move Rectangle in relation to deltaTime
+ *
+ * if (rectX >= width) {
+ * // If you go off screen.
+ * if (fr === 30) {
+ * clr = color(0, 0, 255);
+ * fr = 10;
+ * frameRate(fr); // make frameRate 10 FPS
+ * } else {
+ * clr = color(255, 0, 0);
+ * fr = 30;
+ * frameRate(fr); // make frameRate 30 FPS
+ * }
+ * rectX = 0;
+ * }
+ * fill(clr);
+ * rect(rectX, 40, 20, 20);
+ * }
+ *
+ *
+ * @alt
+ * red rect moves left to right, followed by blue rect moving at the same speed
+ * with a lower frame rate. Loops.
+ */
+ _main.default.prototype.deltaTime = 0;
+ /**
+ * Confirms if the window a p5.js program is in is "focused," meaning that
+ * the sketch will accept mouse or keyboard input. This variable is
+ * "true" if the window is focused and "false" if not.
+ *
+ * @property {Boolean} focused
+ * @readOnly
+ * @example
+ *
+ * // To demonstrate, put two windows side by side.
+ * // Click on the window that the p5 sketch isn't in!
+ * function draw() {
+ * background(200);
+ * noStroke();
+ * fill(0, 200, 0);
+ * ellipse(25, 25, 50, 50);
+ *
+ * if (!focused) {
+ // or "if (focused === false)"
+ * stroke(200, 0, 0);
+ * line(0, 0, 100, 100);
+ * line(100, 0, 0, 100);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * green 50×50 ellipse at top left. Red X covers canvas when page focus changes
+ */
+ _main.default.prototype.focused = document.hasFocus();
+ /**
+ * Sets the cursor to a predefined symbol or an image, or makes it visible
+ * if already hidden. If you are trying to set an image as the cursor, the
+ * recommended size is 16×16 or 32×32 pixels. The values for parameters x and y
+ * must be less than the dimensions of the image.
+ *
+ * @method cursor
+ * @param {String|Constant} type Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT
+ * Native CSS properties: 'grab', 'progress', 'cell' etc.
+ * External: path for cursor's images
+ * (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)
+ * For more information on Native CSS cursors and url visit:
+ * https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
+ * @param {Number} [x] the horizontal active spot of the cursor (must be less than 32)
+ * @param {Number} [y] the vertical active spot of the cursor (must be less than 32)
+ * @example
+ *
+ *
+ * @alt
+ * canvas is divided into four quadrants. cursor on first is a cross, second is a progress,
+ * third is a custom cursor using path to the cursor and fourth is a grab.
+ */
+ _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;
+ };
+ /**
+ * 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 frame rate is
+ * based on the frame rate of the display (here also called "refresh rate"),
+ * which is set to 60 frames per second on most computers. A frame rate of 24
+ * frames per second (usual for movies) or above will be enough for smooth
+ * animations. This is the same as setFrameRate(val).
+ *
+ * Calling frameRate() with no arguments returns
+ * the current framerate. The draw function must run at least once before it will
+ * return a value. This is the same as getFrameRate().
+ *
+ * Calling frameRate() with arguments that are not
+ * of the type Number or are non-positive also returns current framerate.
+ *
+ * @method frameRate
+ * @param {Number} fps number of frames to be displayed every second
+ * @chainable
+ *
+ * @example
+ *
+ *
+ *
+ * @alt
+ * blue rect moves left to right, followed by red rect moving faster. Loops.
+ */
+ /**
+ * @method frameRate
+ * @return {Number} current frameRate
+ */
+ _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 framerate.
+ *
+ * @private
+ * @param {Number} [fps] number of frames to be displayed every second
+ */
+ _main.default.prototype.setFrameRate = function (fps) {
+ return this.frameRate(fps);
+ };
+ /**
+ * Returns _targetFrameRate variable. The default _targetFrameRate is set to 60.
+ * This could be changed by calling frameRate() and setting it to the desired
+ * value. When getTargetFrameRate() is called, it should return the value that was set.
+ * @method getTargetFrameRate
+ * @return {Number} _targetFrameRate
+ * @example
+ *
+ *
+ * @alt
+ * cursor becomes 10×10 white ellipse the moves with mouse x and y.
+ */
+ _main.default.prototype.noCursor = function () {
+ this._curElement.elt.style.cursor = 'none';
+ };
+ /**
+ * System variable that stores the width of the screen display according to The
+ * default pixelDensity. This is used to run a
+ * full-screen program on any display size. To return actual screen size,
+ * multiply this by pixelDensity.
+ *
+ * @property {Number} displayWidth
+ * @readOnly
+ * @example
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _main.default.prototype.displayWidth = screen.width;
+ /**
+ * System variable that stores the height of the screen display according to The
+ * default pixelDensity. This is used to run a
+ * full-screen program on any display size. To return actual screen size,
+ * multiply this by pixelDensity.
+ *
+ * @property {Number} displayHeight
+ * @readOnly
+ * @example
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _main.default.prototype.displayHeight = screen.height;
+ /**
+ * System variable that stores the width of the inner window, it maps to
+ * window.innerWidth.
+ *
+ * @property {Number} windowWidth
+ * @readOnly
+ * @example
+ *
+ * createCanvas(windowWidth, windowHeight);
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _main.default.prototype.windowWidth = getWindowWidth();
+ /**
+ * System variable that stores the height of the inner window, it maps to
+ * window.innerHeight.
+ *
+ * @property {Number} windowHeight
+ * @readOnly
+ * @example
+ *
+ * createCanvas(windowWidth, windowHeight);
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _main.default.prototype.windowHeight = getWindowHeight();
+ /**
+ * The windowResized() function is called once
+ * every time the browser window is resized. This is a good place to resize the
+ * canvas or do any other adjustments to accommodate the new window size.
+ *
+ * @method windowResized
+ * @param {Object} [event] optional Event callback argument.
+ * @example
+ *
+ * @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;
+ } /**
+ * System variable that stores the width of the drawing canvas. This value
+ * is set by the first parameter of the createCanvas() function.
+ * For example, the function call createCanvas(320, 240) sets the width
+ * variable to the value 320. The value of width defaults to 100 if
+ * createCanvas() is not used in a program.
+ *
+ * @property {Number} width
+ * @readOnly
+ */
+
+ _main.default.prototype.width = 0;
+ /**
+ * System variable that stores the height of the drawing canvas. This value
+ * is set by the second parameter of the createCanvas() function. For
+ * example, the function call createCanvas(320, 240) sets the height
+ * variable to the value 240. The value of height defaults to 100 if
+ * createCanvas() is not used in a program.
+ *
+ * @property {Number} height
+ * @readOnly
+ */
+ _main.default.prototype.height = 0;
+ /**
+ * If argument is given, sets the sketch to fullscreen or not based on the
+ * value of the argument. If no argument is given, returns the current
+ * fullscreen state. Note that due to browser restrictions this can only
+ * be called on user input, for example, on mouse press like the example
+ * below.
+ *
+ * @method fullscreen
+ * @param {Boolean} [val] whether the sketch should be in fullscreen mode
+ * or not
+ * @return {Boolean} current fullscreen state
+ * @example
+ *
+ *
+ * // Clicking in the box toggles fullscreen on and off.
+ * function setup() {
+ * background(200);
+ * }
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {
+ * let fs = fullscreen();
+ * fullscreen(!fs);
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _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 scaling for high pixel density displays. By default
+ * pixel density is set to match display density, call pixelDensity(1)
+ * to turn this off. Calling pixelDensity() with no arguments returns
+ * the current pixel density of the sketch.
+ *
+ * @method pixelDensity
+ * @param {Number} val whether or how much the sketch should scale
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * fuzzy 50×50 white ellipse with black outline in center of canvas.
+ * sharp 50×50 white ellipse with black outline in center of 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 = 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 pixel density of the current display the sketch is running on.
+ *
+ * @method displayDensity
+ * @returns {Number} current pixel density of the display
+ * @example
+ *
+ *
+ * @alt
+ * 50×50 white ellipse with black outline in center of canvas.
+ */
+ _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();
+ }
+ } /**
+ * Gets the current URL. Note: when using the
+ * p5 Editor, this will return an empty object because the sketch
+ * is embedded in an iframe. It will work correctly if you view the
+ * sketch using the editor's present or share URLs.
+ * @method getURL
+ * @return {String} url
+ * @example
+ *
+ *
+ * @alt
+ * current url (http://p5js.org/reference/#/p5/getURL) moves right to left.
+ */
+
+ _main.default.prototype.getURL = function () {
+ return location.href;
+ };
+ /**
+ * Gets the current URL path as an array. Note: when using the
+ * p5 Editor, this will return an empty object because the sketch
+ * is embedded in an iframe. It will work correctly if you view the
+ * sketch using the editor's present or share URLs.
+ * @method getURLPath
+ * @return {String[]} path components
+ * @example
+ *
+ * function setup() {
+ * let urlPath = getURLPath();
+ * for (let i = 0; i < urlPath.length; i++) {
+ * text(urlPath[i], 10, i * 20 + 20);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _main.default.prototype.getURLPath = function () {
+ return location.pathname.split('/').filter(function (v) {
+ return v !== '';
+ });
+ };
+ /**
+ * Gets the current URL params as an Object. Note: when using the
+ * p5 Editor, this will return an empty object because the sketch
+ * is embedded in an iframe. It will work correctly if you view the
+ * sketch using the editor's present or share URLs.
+ * @method getURLParams
+ * @return {Object} URL params
+ * @example
+ *
+ *
+ * @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': 278,
+ './main': 290,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.filter': 171,
+ 'core-js/modules/es.array.includes': 174,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.string.includes': 203,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.search': 208,
+ 'core-js/modules/es.string.split': 209,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 280: [
+ 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;
+ },
+ {
+ }
+ ],
+ 281: [
+ 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.search');
+ _dereq_('core-js/modules/es.string.split');
+ _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.search');
+ _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 _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);
+ } // 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('/');
+ 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 ReferenceErrror 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 happended 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 write 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;
+ 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];
+ for (var j = 0; j < i; j++) {
+ // Due to the current build process, all p5 functions have
+ // _main.default in their names in the final build. This is the
+ // easiest way to check if a function is inside the p5 library
+ if (stacktrace[j].functionName.search('_main.default') !== - 1) {
+ isInternal = true;
+ p5FileName = stacktrace[j].fileName;
+ 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': 278,
+ '../internationalization': 288,
+ '../main': 290,
+ './browser_errors': 280,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.filter': 171,
+ 'core-js/modules/es.array.for-each': 172,
+ 'core-js/modules/es.array.includes': 174,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.join': 177,
+ 'core-js/modules/es.array.map': 179,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.array.some': 181,
+ 'core-js/modules/es.function.name': 183,
+ 'core-js/modules/es.object.assign': 190,
+ 'core-js/modules/es.object.get-own-property-names': 192,
+ 'core-js/modules/es.object.keys': 194,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.constructor': 198,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.match': 205,
+ 'core-js/modules/es.string.replace': 207,
+ 'core-js/modules/es.string.search': 208,
+ 'core-js/modules/es.string.split': 209,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/web.dom-collections.for-each': 247,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 282: [
+ 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': 288,
+ '../main': 290
+ }
+ ],
+ 283: [
+ 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.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.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/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');
+ 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;
+ }
+ } /**
+ * 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 functionArray = [
+ ]; //get the names of all p5.js functions
+ for (var _i4 = 0; _i4 < keyArray.length; _i4++) {
+ var _functionArray;
+ (_functionArray = functionArray).push.apply(_functionArray, _toConsumableArray(Object.keys(p5Constructors[keyArray[_i4]].prototype)));
+ }
+ functionArray = functionArray.filter(function (ele) {
+ return !ele.includes('_');
+ }); //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': 278,
+ '../internationalization': 288,
+ '../main': 290,
+ 'core-js/modules/es.array.filter': 171,
+ 'core-js/modules/es.array.for-each': 172,
+ 'core-js/modules/es.array.from': 173,
+ 'core-js/modules/es.array.includes': 174,
+ 'core-js/modules/es.array.index-of': 175,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.join': 177,
+ 'core-js/modules/es.array.map': 179,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.keys': 194,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.constructor': 198,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.includes': 203,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.match': 205,
+ 'core-js/modules/es.string.split': 209,
+ 'core-js/modules/es.string.trim': 211,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.for-each': 247,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 284: [
+ 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() {
+ 'use strict';
+ 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': 290,
+ 'core-js/modules/es.array.filter': 171,
+ 'core-js/modules/es.array.index-of': 175,
+ 'core-js/modules/es.array.join': 177,
+ 'core-js/modules/es.array.map': 179,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.string.match': 205,
+ 'core-js/modules/es.string.replace': 207,
+ 'core-js/modules/es.string.split': 209
+ }
+ ],
+ 285: [
+ 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.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-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/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);
+ }
+ 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 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(); // contant
+ 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 {String} a string indicating the type
+ */
+ var isNumber = function isNumber(param) {
+ 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.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 ouput:
+ * "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': 278,
+ '../internationalization': 288,
+ '../main': 290,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.for-each': 172,
+ 'core-js/modules/es.array.includes': 174,
+ 'core-js/modules/es.array.index-of': 175,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.join': 177,
+ 'core-js/modules/es.array.last-index-of': 178,
+ 'core-js/modules/es.array.map': 179,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.function.name': 183,
+ 'core-js/modules/es.map': 184,
+ 'core-js/modules/es.number.constructor': 187,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.get-prototype-of': 193,
+ 'core-js/modules/es.object.keys': 194,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.reflect.construct': 197,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.set': 201,
+ 'core-js/modules/es.string.includes': 203,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.split': 209,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.for-each': 247,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 286: [
+ 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': 278,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 287: [
+ 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': 290,
+ './internationalization': 288,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.promise': 196,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 288: [
+ 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': 349,
+ '../../translations/dev': undefined,
+ 'core-js/modules/es.array.includes': 174,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.join': 177,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.object.keys': 194,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.promise': 196,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.string.includes': 203,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.split': 209,
+ 'core-js/modules/web.dom-collections.iterator': 248,
+ 'i18next': 259,
+ 'i18next-browser-languagedetector': 256
+ }
+ ],
+ 289: [
+ 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': 290
+ }
+ ],
+ 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.for-each');
+ _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.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.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;
+ } /**
+ * 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} 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, sync) {
+ var _this = this;
+ _classCallCheck(this, p5); //////////////////////////////////////////////
+ // PUBLIC p5 PROPERTIES AND METHODS
+ //////////////////////////////////////////////
+ /**
+ * Called directly before setup(), the preload() function is used to handle
+ * asynchronous loading of external files in a blocking way. If a preload
+ * function is defined, setup() will wait until any load calls within have
+ * finished. Nothing besides load calls (loadImage, loadJSON, loadFont,
+ * loadStrings, etc.) should be inside the preload function. If asynchronous
+ * loading is preferred, the load methods can instead be called in setup()
+ * or anywhere else with the use of a callback parameter.
+ *
+ * By default the text "loading..." will be displayed. To make your own
+ * loading page, include an HTML element with id "p5_loading" in your
+ * page. More information here.
+ *
+ * @method preload
+ * @example
+ *
+ * let img;
+ * let c;
+ * function preload() {
+ * // preload() runs once
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ *
+ * function setup() {
+ * // setup() waits until preload() is done
+ * img.loadPixels();
+ * // get color of middle pixel
+ * c = img.get(img.width / 2, img.height / 2);
+ * }
+ *
+ * function draw() {
+ * background(c);
+ * image(img, 25, 25, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+ /**
+ * The setup() function is called once when the program starts. It's used to
+ * define initial environment properties such as screen size and background
+ * color and to load media such as images and fonts as the program starts.
+ * There can only be one setup() function for each program and it shouldn't
+ * be called again after its initial execution.
+ *
+ * Note: Variables declared within setup() are not accessible within other
+ * functions, including draw().
+ *
+ * @method setup
+ * @example
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+ /**
+ * Called directly after setup(), the draw() function continuously executes
+ * the lines of code contained inside its block until the program is stopped
+ * or noLoop() is called. Note if noLoop() is called in setup(), draw() will
+ * still be executed once before stopping. draw() is called automatically and
+ * should never be called explicitly.
+ *
+ * It should always be controlled with noLoop(), redraw() and loop(). After
+ * noLoop() stops the code in draw() from executing, redraw() causes the
+ * code inside draw() to execute once, and loop() will cause the code
+ * inside draw() to resume executing continuously.
+ *
+ * The number of times draw() executes in each second may be controlled with
+ * the frameRate() function.
+ *
+ * There can only be one draw() function for each sketch, and draw() must
+ * exist if you want the code to run continuously, or to process events such
+ * as mousePressed(). Sometimes, you might have an empty call to draw() in
+ * your program, as shown in the above example.
+ *
+ * It is important to note that the drawing coordinate system will be reset
+ * at the beginning of each draw() call. If any transformations are performed
+ * within draw() (ex: scale, rotate, translate), their effects will be
+ * undone at the beginning of draw(), so transformations will not accumulate
+ * over time. On the other hand, styling applied (ex: fill, stroke, etc) will
+ * remain in effect.
+ *
+ * @method draw
+ * @example
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+ //////////////////////////////////////////////
+ // PRIVATE p5 PROPERTIES AND METHODS
+ //////////////////////////////////////////////
+ this._setupDone = false;
+ this._preloadDone = false; // for handling hidpi
+ this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1;
+ this._userNode = node;
+ this._curElement = null;
+ this._elements = [
+ ];
+ this._glAttributes = null;
+ this._requestAnimId = 0;
+ this._preloadCount = 0;
+ this._isGlobal = false;
+ this._loop = true;
+ 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; // 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;
+ }
+ 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) {
+ // 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 _methods = _this._preloadMethods;
+ for (var method in _methods) {
+ // default to p5 if no object defined
+ _methods[method] = _methods[method] || p5;
+ var obj = _methods[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);
+ }
+ 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 () {
+ // 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 _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+ try {
+ for (var _iterator2 = canvases[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
+ var k = _step2.value;
+ if (k.dataset.hidden === 'true') {
+ k.style.visibility = '';
+ delete k.dataset.hidden;
+ }
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+ _this._lastTargetFrameTime = window.performance.now();
+ _this._lastRealFrameTime = window.performance.now();
+ _this._setupDone = true;
+ if (_this._accessibleOutputs.grid || _this._accessibleOutputs.text) {
+ _this._updateAccsOutput();
+ }
+ };
+ 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.redraw();
+ _this._frameRate = 1000 / (now - _this._lastRealFrameTime);
+ _this.deltaTime = now - _this._lastRealFrameTime;
+ _this._setProperty('deltaTime', _this.deltaTime);
+ _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 entire p5 sketch. This will remove the canvas and any
+ * elements created by p5.js. It will also stop the draw loop and unbind
+ * any properties or methods from the window global scope. It will
+ * leave a variable p5 in case you wanted to create a new p5 sketch.
+ * If you like, you can set p5 = null to erase it. While all functions and
+ * variables and objects created by the p5 library will be removed, any
+ * other global variables created by your code will remain.
+ *
+ * @method remove
+ * @example
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+ this.remove = function () {
+ 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 _iteratorNormalCompletion3 = true;
+ var _didIteratorError3 = false;
+ var _iteratorError3 = undefined;
+ try {
+ for (var _iterator3 = _this._elements[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
+ var e = _step3.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) {
+ _didIteratorError3 = true;
+ _iteratorError3 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
+ _iterator3.return();
+ }
+ } finally {
+ if (_didIteratorError3) {
+ throw _iteratorError3;
+ }
+ }
+ }
+ 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 {
+ window.addEventListener('load', this._start.bind(this), 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);
+ } // 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;
+ /**
+ * Turn off some features of the friendly error system (FES), which can give
+ * a significant boost to performance when needed.
+ *
+ * Note that this will disable the parts of the FES that cause performance
+ * slowdown (like argument checking). Friendly errors that have no performance
+ * cost (like giving a descriptive error if a file load fails, or warning you
+ * if you try to override p5.js functions in the global space),
+ * will remain in place.
+ *
+ * See
+ * disabling the friendly error system.
+ *
+ * @property {Boolean} disableFriendlyErrors
+ * @example
+ *
+ *
+ * @property elt
+ * @readOnly
+ */
+ this.elt = elt;
+ this._pInst = this._pixelsState = pInst;
+ this._events = {
+ };
+ this.width = this.elt.offsetWidth;
+ this.height = this.elt.offsetHeight;
+ };
+ /**
+ *
+ * Attaches the element to the parent specified. A way of setting
+ * the container for the element. Accepts either a string ID, DOM
+ * node, or p5.Element. If no arguments are given, parent node is returned.
+ * For more ways to position the canvas, see the
+ *
+ * positioning the canvas wiki page.
+ *
+ * @method parent
+ * @param {String|p5.Element|Object} parent the ID, DOM node, or p5.Element
+ * of desired parent element
+ * @chainable
+ *
+ * @example
+ *
+ * // Add the following comment to html file.
+ * // <div id="myContainer"></div>
+ *
+ * // The js code
+ * let cnv = createCanvas(100, 100);
+ * cnv.parent('myContainer');
+ *
+ *
+ *
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
+ * div1.parent(div0); // use p5.Element
+ *
+ *
+ *
+ * let div0 = createDiv('this is the parent');
+ * div0.id('apples');
+ * let div1 = createDiv('this is the child');
+ * div1.parent('apples'); // use id
+ *
+ *
+ *
+ * let elt = document.getElementById('myParentDiv');
+ * let div1 = createDiv('this is the child');
+ * div1.parent(elt); // use element from page
+ *
+ *
+ * @alt
+ * no display.
+ */
+ /**
+ * @method parent
+ * @return {p5.Element}
+ */
+ _main.default.Element.prototype.parent = function (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 ID of the element. If no ID argument is passed in, it instead
+ * returns the current ID of the element.
+ * Note that only one element can have a particular id in a page.
+ * The class() method can be used
+ * to identify multiple elements with the same class name.
+ *
+ * @method id
+ * @param {String} id ID of the element
+ * @chainable
+ *
+ * @example
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // Assigns a CSS selector ID to
+ * // the canvas element.
+ * cnv.id('mycanvas');
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ /**
+ * @method id
+ * @return {String} the id of the element
+ */
+ _main.default.Element.prototype.id = function (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 given class to the element. If no class argument is passed in, it
+ * instead returns a string containing the current class(es) of the element.
+ *
+ * @method class
+ * @param {String} class class to add
+ * @chainable
+ *
+ * @example
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // Assigns a CSS selector class 'small'
+ * // to the canvas element.
+ * cnv.class('small');
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ /**
+ * @method class
+ * @return {String} the class of the element
+ */
+ _main.default.Element.prototype.class = function (c) {
+ if (typeof c === 'undefined') {
+ return this.elt.className;
+ }
+ this.elt.className = c;
+ return this;
+ };
+ /**
+ * The mousePressed() method is called
+ * once after every time a mouse button is pressed over the element. Some mobile
+ * browsers may also trigger this event on a touch screen, if the user performs
+ * a quick tap. This can be used to attach element-specific event listeners.
+ *
+ * @method mousePressed
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * pressed over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mousePressed(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any click anywhere
+ * function mousePressed() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mousePressed = function (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;
+ };
+ /**
+ * The doubleClicked() method is called once after every time a
+ * mouse button is pressed twice over the element. This can be used to
+ * attach element and action-specific event listeners.
+ *
+ * @method doubleClicked
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * double clicked over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @return {p5.Element}
+ * @example
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.doubleClicked(changeGray); // attach listener for
+ * // canvas double click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any double click anywhere
+ * function doubleClicked() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is double clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.doubleClicked = function (fxn) {
+ _main.default.Element._adjustListener('dblclick', fxn, this);
+ return this;
+ };
+ /**
+ * The mouseWheel() method is called
+ * once after every time a mouse wheel is scrolled over the element. This can
+ * be used to attach element-specific event listeners.
+ *
+ * The method accepts a callback function as argument which will be executed
+ * when the `wheel` event is triggered on the element, the callback function is
+ * passed one argument `event`. The `event.deltaY` property returns negative
+ * values if the mouse wheel is rotated up or away from the user and positive
+ * in the other direction. The `event.deltaX` does the same as `event.deltaY`
+ * except it reads the horizontal wheel scroll of the mouse wheel.
+ *
+ * On macOS with "natural" scrolling enabled, the `event.deltaY` values are
+ * reversed.
+ *
+ * @method mouseWheel
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * scrolled over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseWheel(changeSize); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with mousewheel movement
+ * // anywhere on screen
+ * function mouseWheel() {
+ * g = g + 10;
+ * }
+ *
+ * // this function fires with mousewheel movement
+ * // over canvas only
+ * function changeSize(event) {
+ * if (event.deltaY > 0) {
+ * d = d + 10;
+ * } else {
+ * d = d - 10;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseWheel = function (fxn) {
+ _main.default.Element._adjustListener('wheel', fxn, this);
+ return this;
+ };
+ /**
+ * The mouseReleased() method is
+ * called once after every time a mouse button is released over the element.
+ * Some mobile browsers may also trigger this event on a touch screen, if the
+ * user performs a quick tap. This can be used to attach element-specific event listeners.
+ *
+ * @method mouseReleased
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * released over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseReleased(changeGray); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // released
+ * function mouseReleased() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // released while on canvas
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseReleased = function (fxn) {
+ _main.default.Element._adjustListener('mouseup', fxn, this);
+ return this;
+ };
+ /**
+ * The mouseClicked() method is
+ * called once after a mouse button is pressed and released over the element.
+ * Some mobile browsers may also trigger this event on a touch screen, if the
+ * user performs a quick tap. This can be used to attach element-specific event listeners.
+ *
+ * @method mouseClicked
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * clicked over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseClicked(changeGray); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // clicked anywhere
+ * function mouseClicked() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // clicked on canvas
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseClicked = function (fxn) {
+ _main.default.Element._adjustListener('click', fxn, this);
+ return this;
+ };
+ /**
+ * The mouseMoved() method is called once every time a
+ * mouse moves over the element. This can be used to attach an
+ * element-specific event listener.
+ *
+ * @method mouseMoved
+ * @param {Function|Boolean} fxn function to be fired when a mouse moves
+ * over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d = 30;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseMoved(changeSize); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * fill(200);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires when mouse moves anywhere on
+ * // page
+ * function mouseMoved() {
+ * g = g + 5;
+ * if (g > 255) {
+ * g = 0;
+ * }
+ * }
+ *
+ * // this function fires when mouse moves over canvas
+ * function changeSize() {
+ * d = d + 2;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseMoved = function (fxn) {
+ _main.default.Element._adjustListener('mousemove', fxn, this);
+ return this;
+ };
+ /**
+ * The mouseOver() method is called once after every time a
+ * mouse moves onto the element. This can be used to attach an
+ * element-specific event listener.
+ *
+ * @method mouseOver
+ * @param {Function|Boolean} fxn function to be fired when a mouse moves
+ * onto the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseOver(changeGray);
+ * d = 10;
+ * }
+ *
+ * function draw() {
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * function changeGray() {
+ * d = d + 10;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseOver = function (fxn) {
+ _main.default.Element._adjustListener('mouseover', fxn, this);
+ return this;
+ };
+ /**
+ * The mouseOut() method is called once after every time a
+ * mouse moves off the element. This can be used to attach an
+ * element-specific event listener.
+ *
+ * @method mouseOut
+ * @param {Function|Boolean} fxn function to be fired when a mouse
+ * moves off of an element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseOut(changeGray);
+ * d = 10;
+ * }
+ *
+ * function draw() {
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * function changeGray() {
+ * d = d + 10;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseOut = function (fxn) {
+ _main.default.Element._adjustListener('mouseout', fxn, this);
+ return this;
+ };
+ /**
+ * The touchStarted() method is called once after every time a touch is
+ * registered. This can be used to attach element-specific event listeners.
+ *
+ * @method touchStarted
+ * @param {Function|Boolean} fxn function to be fired when a touch
+ * starts over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchStarted(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any touch anywhere
+ * function touchStarted() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.touchStarted = function (fxn) {
+ _main.default.Element._adjustListener('touchstart', fxn, this);
+ return this;
+ };
+ /**
+ * The touchMoved() method is called once after every time a touch move is
+ * registered. This can be used to attach element-specific event listeners.
+ *
+ * @method touchMoved
+ * @param {Function|Boolean} fxn function to be fired when a touch moves over
+ * the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchMoved(changeGray); // attach listener for
+ * // canvas click only
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.touchMoved = function (fxn) {
+ _main.default.Element._adjustListener('touchmove', fxn, this);
+ return this;
+ };
+ /**
+ * The touchEnded() method is called once after every time a touch is
+ * registered. This can be used to attach element-specific event listeners.
+ *
+ * @method touchEnded
+ * @param {Function|Boolean} fxn function to be fired when a touch ends
+ * over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchEnded(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any touch anywhere
+ * function touchEnded() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.touchEnded = function (fxn) {
+ _main.default.Element._adjustListener('touchend', fxn, this);
+ return this;
+ };
+ /**
+ * The dragOver() method is called once after every time a
+ * file is dragged over the element. This can be used to attach an
+ * element-specific event listener.
+ *
+ * @method dragOver
+ * @param {Function|Boolean} fxn function to be fired when a file is
+ * dragged over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * // To test this sketch, simply drag a
+ * // file over the canvas
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('Drag file', width / 2, height / 2);
+ * c.dragOver(dragOverCallback);
+ * }
+ *
+ * // This function will be called whenever
+ * // a file is dragged over the canvas
+ * function dragOverCallback() {
+ * background(240);
+ * text('Dragged over', width / 2, height / 2);
+ * }
+ *
+ * @alt
+ * nothing displayed
+ */
+ _main.default.Element.prototype.dragOver = function (fxn) {
+ _main.default.Element._adjustListener('dragover', fxn, this);
+ return this;
+ };
+ /**
+ * The dragLeave() method is called once after every time a
+ * dragged file leaves the element area. This can be used to attach an
+ * element-specific event listener.
+ *
+ * @method dragLeave
+ * @param {Function|Boolean} fxn function to be fired when a file is
+ * dragged off the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * // To test this sketch, simply drag a file
+ * // over and then out of the canvas area
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('Drag file', width / 2, height / 2);
+ * c.dragLeave(dragLeaveCallback);
+ * }
+ *
+ * // This function will be called whenever
+ * // a file is dragged out of the canvas
+ * function dragLeaveCallback() {
+ * background(240);
+ * text('Dragged off', width / 2, height / 2);
+ * }
+ *
+ * @alt
+ * nothing displayed
+ */
+ _main.default.Element.prototype.dragLeave = function (fxn) {
+ _main.default.Element._adjustListener('dragleave', fxn, this);
+ return this;
+ }; // General handler for event attaching and detaching
+ _main.default.Element._adjustListener = function (ev, fxn, ctx) {
+ if (fxn === false) {
+ _main.default.Element._detachListener(ev, ctx);
+ } else {
+ _main.default.Element._attachListener(ev, fxn, ctx);
+ }
+ return this;
+ };
+ _main.default.Element._attachListener = function (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;
+ };
+ _main.default.Element._detachListener = function (ev, ctx) {
+ var f = ctx._events[ev];
+ ctx.elt.removeEventListener(ev, f, false);
+ ctx._events[ev] = null;
+ };
+ /**
+ * Helper fxn for sharing pixel methods
+ */
+ _main.default.Element.prototype._setProperty = function (prop, value) {
+ this[prop] = value;
+ };
+ var _default = _main.default.Element;
+ exports.default = _default;
+ },
+ {
+ './main': 290
+ }
+ ],
+ 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.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.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');
+ 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 Rendering
+ * @submodule Rendering
+ * @for p5
+ */
+ /**
+ * Thin wrapper around a renderer, to be used for creating a
+ * graphics buffer object. Use this class if you need
+ * to draw into an off-screen graphics buffer. The two parameters define the
+ * width and height in pixels. The fields and methods for this class are
+ * extensive, but mirror the normal drawing API for p5.
+ *
+ * @class p5.Graphics
+ * @constructor
+ * @extends p5.Element
+ * @param {Number} w width
+ * @param {Number} h height
+ * @param {Constant} renderer the renderer to use, either P2D or WEBGL
+ * @param {p5} [pInst] pointer to p5 instance
+ */
+
+ _main.default.Graphics = function (w, h, renderer, pInst) {
+ var r = renderer || constants.P2D;
+ this.canvas = document.createElement('canvas');
+ var node = pInst._userNode || document.body;
+ node.appendChild(this.canvas);
+ _main.default.Element.call(this, this.canvas, pInst); // 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(this);
+ } else {
+ this[p] = _main.default.prototype[p];
+ }
+ }
+ }
+ _main.default.prototype._initializeInstanceVariables.apply(this);
+ this.width = w;
+ this.height = h;
+ this._pixelDensity = pInst._pixelDensity;
+ if (r === constants.WEBGL) {
+ this._renderer = new _main.default.RendererGL(this.canvas, this, false);
+ } else {
+ this._renderer = new _main.default.Renderer2D(this.canvas, this, false);
+ }
+ pInst._elements.push(this);
+ Object.defineProperty(this, 'deltaTime', {
+ get: function get() {
+ return this._pInst.deltaTime;
+ }
+ });
+ this._renderer.resize(w, h);
+ this._renderer._applyDefaults();
+ return this;
+ };
+ _main.default.Graphics.prototype = Object.create(_main.default.Element.prototype);
+ /**
+ * Resets certain values such as those modified by functions in the Transform category
+ * and in the Lights category that are not automatically reset
+ * with graphics buffer objects. Calling this in draw() will copy the behavior
+ * of the standard canvas.
+ *
+ * @method reset
+ * @example
+ *
+ *
+ * let pg;
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(0);
+ * pg = createGraphics(50, 100);
+ * pg.fill(0);
+ * frameRate(5);
+ * }
+ *
+ * function draw() {
+ * image(pg, width / 2, 0);
+ * pg.background(255);
+ * // p5.Graphics object behave a bit differently in some cases
+ * // The normal canvas on the left resets the translate
+ * // with every loop through draw()
+ * // the graphics object on the right doesn't automatically reset
+ * // so translate() is additive and it moves down the screen
+ * rect(0, 0, width / 2, 5);
+ * pg.rect(0, 0, width / 2, 5);
+ * translate(0, 5, 0);
+ * pg.translate(0, 5, 0);
+ * }
+ * function mouseClicked() {
+ * // if you click you will see that
+ * // reset() resets the translate back to the initial state
+ * // of the Graphics object
+ * pg.reset();
+ * }
+ *
+ *
+ * @alt
+ * A white line on a black background stays still on the top-left half.
+ * A black line animates from top to bottom on a white background on the right half.
+ * When clicked, the black line starts back over at the top.
+ */
+ _main.default.Graphics.prototype.reset = function () {
+ this._renderer.resetMatrix();
+ if (this._renderer.isP3D) {
+ this._renderer._update();
+ }
+ };
+ /**
+ * Removes a Graphics object from the page and frees any resources
+ * associated with it.
+ *
+ * @method remove
+ *
+ * @example
+ *
+ *
+ * @alt
+ * Black line extending from top-left of canvas to bottom right.
+ */
+ _main.default.prototype.createCanvas = function (w, h, renderer) {
+ _main.default._validateParameters('createCanvas', arguments); //optional: renderer, otherwise defaults to p2d
+ var r = renderer || constants.P2D;
+ var c;
+ 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) {
+ 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);
+ } 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 given width and height. The canvas will be cleared
+ * and draw will be called immediately, allowing the sketch to re-render itself
+ * in the resized canvas.
+ * @method resizeCanvas
+ * @param {Number} w width of the canvas
+ * @param {Number} h height of the canvas
+ * @param {Boolean} [noRedraw] don't redraw the canvas immediately
+ * @example
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.prototype.noCanvas = function () {
+ if (this.canvas) {
+ this.canvas.parentNode.removeChild(this.canvas);
+ }
+ };
+ /**
+ * Creates and returns a new p5.Renderer object. Use this class if you need
+ * to draw into an off-screen graphics buffer. The two parameters define the
+ * width and height in pixels.
+ *
+ * @method createGraphics
+ * @param {Number} w width of the offscreen graphics buffer
+ * @param {Number} h height of the offscreen graphics buffer
+ * @param {Constant} [renderer] either P2D or WEBGL
+ * undefined defaults to p2d
+ * @return {p5.Graphics} offscreen graphics buffer
+ * @example
+ *
+ *
+ * @alt
+ * 4 grey squares alternating light and dark grey. White quarter circle mid-left.
+ */
+ _main.default.prototype.createGraphics = function (w, h, renderer) {
+ _main.default._validateParameters('createGraphics', arguments);
+ return new _main.default.Graphics(w, h, renderer, this);
+ };
+ /**
+ * Blends the pixels in the display window according to the defined mode.
+ * There is a choice of the following modes to blend the source pixels (A)
+ * with the ones of pixels already in the display window (B):
+ *
+ *
BLEND - linear interpolation of colours: C =
+ * A*factor + B. This is the default blending mode.
+ *
ADD - sum of A and B
+ *
DARKEST - only the darkest colour succeeds: C =
+ * min(A*factor, B).
+ *
LIGHTEST - only the lightest colour succeeds: C =
+ * max(A*factor, B).
+ *
DIFFERENCE - subtract colors from underlying image.
+ * (2D)
+ *
EXCLUSION - similar to DIFFERENCE, but less
+ * extreme.
+ *
MULTIPLY - multiply the colors, result will always be
+ * darker.
+ *
SCREEN - opposite multiply, uses inverse values of the
+ * colors.
+ *
REPLACE - the pixels entirely replace the others and
+ * don't utilize alpha (transparency) values.
+ *
REMOVE - removes pixels from B with the alpha strength of A.
+ *
OVERLAY - mix of MULTIPLY and SCREEN
+ * . Multiplies dark values, and screens light values. (2D)
+ *
HARD_LIGHT - SCREEN when greater than 50%
+ * gray, MULTIPLY when lower. (2D)
+ *
SOFT_LIGHT - mix of DARKEST and
+ * LIGHTEST. Works like OVERLAY, but not as harsh. (2D)
+ *
BURN - darker areas are applied, increasing contrast,
+ * ignores lights. (2D)
+ *
SUBTRACT - remainder of A and B (3D)
+ *
+ *
+ * (2D) indicates that this blend mode only works in the 2D renderer.
+ * (3D) indicates that this blend mode only works in the WEBGL renderer.
+ *
+ * @method blendMode
+ * @param {Constant} mode blend mode to set for canvas.
+ * either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,
+ * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
+ * SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT
+ * @example
+ *
+ *
+ * @alt
+ * translucent image thick red & blue diagonal rounded lines intersecting center
+ * Thick red & blue diagonal rounded lines intersecting center. dark at overlap
+ */
+ _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);
+ };
+ /**
+ * The p5.js API provides a lot of functionality for creating graphics, but there is
+ * some native HTML5 Canvas functionality that is not exposed by p5. You can still call
+ * it directly using the variable `drawingContext`, as in the example shown. This is
+ * the equivalent of calling `canvas.getContext('2d');` or `canvas.getContext('webgl');`.
+ * See this
+ *
+ * reference for the native canvas API for possible drawing functions you can call.
+ *
+ * @property drawingContext
+ * @example
+ *
+ *
+ * @alt
+ * white ellipse with shadow blur effect around edges
+ */
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../webgl/p5.RendererGL': 344,
+ './constants': 278,
+ './main': 290,
+ './p5.Graphics': 292,
+ './p5.Renderer2D': 294,
+ 'core-js/modules/es.array.filter': 171,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 297: [
+ 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'));
+ 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
+ };
+ } /**
+ * @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
+ };
+ };
+ /**
+ * Draw an arc to the screen. If called with only x, y, w, h, start and stop,
+ * the arc will be drawn and filled as an open pie segment. If a mode parameter
+ * is provided, the arc will be filled like an open semi-circle (OPEN), a closed
+ * semi-circle (CHORD), or as a closed pie segment (PIE). The origin may be changed
+ * with the ellipseMode() function.
+ *
+ * The arc is always drawn clockwise from wherever start falls to wherever stop
+ * falls on the ellipse. Adding or subtracting TWO_PI to either angle does not
+ * change where they fall. If both start and stop fall at the same place, a full
+ * ellipse will be drawn. Be aware that the y-axis increases in the downward
+ * direction, therefore angles are measured clockwise from the positive
+ * x-direction ("3 o'clock").
+ *
+ * @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
+ *
+ *
+ * arc(50, 55, 50, 50, 0, HALF_PI);
+ * noFill();
+ * arc(50, 55, 60, 60, HALF_PI, PI);
+ * arc(50, 55, 70, 70, PI, PI + QUARTER_PI);
+ * arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI);
+ * describe(
+ * 'shattered outline of ellipse with a quarter of a white circle bottom-right'
+ * );
+ *
+ *
+ *
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI);
+ * describe('white ellipse with top right quarter missing');
+ *
+ *
+ *
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);
+ * describe('white ellipse with black outline with top right missing');
+ *
+ *
+ *
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);
+ * describe('white open arc with black outline with top right missing');
+ *
+ *
+ *
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);
+ * describe(
+ * 'white ellipse with top right quarter missing with black outline around the shape'
+ * );
+ *
+ *
+ *
+ */
+ _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) to the screen. By default, the first two parameters
+ * set the location of the center of the ellipse, and the third and fourth
+ * parameters set the shape's width and height. If no height is specified, 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.
+ *
+ * An ellipse with equal width and height is a circle. The origin may be changed
+ * with the ellipseMode() function.
+ *
+ * @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
+ *
+ *
+ * ellipse(56, 46, 55, 55);
+ * describe('white ellipse with black outline in middle of 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 to the screen. A circle is a simple closed shape. It is the set
+ * of all points in a plane that are at a given distance from a given point,
+ * the center. This function is a special case of the
+ * ellipse() function, where the width and height
+ * of the ellipse are the same. Height and width of the ellipse correspond to
+ * the diameter of the circle. By default, the first two parameters set the
+ * location of the center of the circle, the third sets the diameter of the
+ * circle.
+ *
+ * @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
+ *
+ *
+ * // Draw a circle at location (30, 30) with a diameter of 20.
+ * circle(30, 30, 20);
+ * describe('white circle with black outline in mid of gray canvas');
+ *
+ *
+ *
+ */
+ _main.default.prototype.circle = function () {
+ _main.default._validateParameters('circle', arguments);
+ var args = Array.prototype.slice.call(arguments, 0, 2);
+ args.push(arguments[2]);
+ args.push(arguments[2]);
+ return this._renderEllipse.apply(this, args);
+ }; // 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 line (a direct path between two points) to the screen. If called with
+ * only 4 parameters, it will draw a line in 2D with a default width of 1 pixel.
+ * This width can be modified by using the
+ * strokeWeight() function. A line cannot be filled, therefore the fill() function will not affect the color of a line. So to
+ * color a line, use the stroke() function.
+ *
+ * @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
+ *
+ *
+ * line(30, 20, 85, 75);
+ * describe(
+ * 'a 78 pixels long line running from mid-top to bottom-right of canvas'
+ * );
+ *
+ *
+ *
+ *
+ *
+ * line(30, 20, 85, 20);
+ * stroke(126);
+ * line(85, 20, 85, 75);
+ * stroke(255);
+ * line(85, 75, 30, 75);
+ * describe(
+ * '3 lines of various stroke colors. Form top, bottom and right sides of a square'
+ * );
+ *
+ *
+ *
+ */
+ /**
+ * @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 _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+ _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 point, a coordinate in space at the dimension of one pixel.
+ * The first parameter is the horizontal value for the point, the second
+ * param is the vertical value for the point. The color of the point is
+ * changed with the stroke() function. The size of the point
+ * can be changed with the strokeWeight() function.
+ *
+ * @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
+ *
+ *
+ * point(30, 20);
+ * point(85, 20);
+ * stroke('purple'); // Change the color
+ * strokeWeight(10); // Make the points 10 pixels in size
+ * point(85, 75);
+ * point(30, 75);
+ * describe('2 points and 2 large purple points in middle-right of canvas');
+ *
+ *
+ *
+ *
+ *
+ * let a = createVector(10, 10);
+ * point(a);
+ * let b = createVector(10, 20);
+ * point(b);
+ * point(createVector(20, 10));
+ * point(createVector(20, 20));
+ * describe(
+ * 'four points create vertices of 10x10 pixel square on top-left of canvas'
+ * );
+ *
+ *
+ *
+ */
+ /**
+ * @method point
+ * @param {p5.Vector} coordinate_vector the coordinate vector
+ * @chainable
+ */
+ _main.default.prototype.point = function () {
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+ _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 quad on the canvas. A quad is a quadrilateral, a four-sided polygon. It is
+ * similar to a rectangle, but the angles between its edges are not
+ * constrained to ninety degrees. The first pair of parameters (x1,y1)
+ * sets the first vertex and the subsequent pairs should proceed
+ * clockwise or counter-clockwise around the defined shape.
+ * z-arguments only work when quad() is used in WEBGL mode.
+ *
+ * @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
+ *
+ *
+ * quad(38, 31, 86, 20, 69, 63, 30, 76);
+ * describe('irregular white quadrilateral with black outline');
+ *
+ *
+ *
+ */
+ /**
+ * @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 _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
+ args[_key3] = arguments[_key3];
+ }
+ _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 on the canvas. A rectangle is a four-sided closed shape with
+ * every angle at ninety degrees. By default, the first two parameters set
+ * the location of the upper-left corner, the third sets the width, and the
+ * fourth sets the height. The way these parameters are interpreted may be
+ * changed with the rectMode() function.
+ *
+ * The fifth, sixth, seventh and eighth parameters, if specified,
+ * determine corner radius for the top-left, top-right, lower-right and
+ * lower-left corners, respectively. An omitted corner radius parameter is set
+ * to the value of the previously specified radius value in the parameter list.
+ *
+ * @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
+ *
+ *
+ * // Draw a rectangle at location (30, 20) with a width and height of 55.
+ * rect(30, 20, 55, 55);
+ * describe('white rect with black outline in mid-right of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // Draw a rectangle with rounded corners, each having a radius of 20.
+ * rect(30, 20, 55, 55, 20);
+ * describe(
+ * 'white rect with black outline and round edges in mid-right of canvas'
+ * );
+ *
+ *
+ *
+ *
+ *
+ * // Draw a rectangle with rounded corners having the following radii:
+ * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.
+ * rect(30, 20, 55, 55, 20, 15, 10, 5);
+ * describe('white rect with black outline and round edges of different radii');
+ *
+ *
+ *
+ */
+ /**
+ * @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 () {
+ _main.default._validateParameters('rect', arguments);
+ return this._renderRect.apply(this, arguments);
+ };
+ /**
+ * Draws a square to the screen. A square is a four-sided shape with every angle
+ * at ninety degrees, and equal side size. This function is a special case of the
+ * rect() function, where the width and height are the same, and the parameter
+ * is called "s" for side size. By default, the first two parameters set the
+ * location of the upper-left corner, the third sets the side size of the square.
+ * The way these parameters are interpreted, may be changed with the rectMode() function.
+ *
+ * The fourth, fifth, sixth and seventh parameters, if specified,
+ * determine corner radius for the top-left, top-right, lower-right and
+ * lower-left corners, respectively. An omitted corner radius parameter is set
+ * to the value of the previously specified radius value in the parameter list.
+ *
+ * @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
+ *
+ *
+ * // Draw a square at location (30, 20) with a side size of 55.
+ * square(30, 20, 55);
+ * describe('white square with black outline in mid-right of canvas');
+ *
+ *
+ *
+ *
+ *
+ * // Draw a square with rounded corners, each having a radius of 20.
+ * square(30, 20, 55, 20);
+ * describe(
+ * 'white square with black outline and round edges in mid-right of canvas'
+ * );
+ *
+ *
+ *
+ *
+ *
+ * // Draw a square with rounded corners having the following radii:
+ * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.
+ * square(30, 20, 55, 20, 15, 10, 5);
+ * describe('white square with black outline and round edges of different radii');
+ *
+ *
+ *
+ */
+ _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 to the canvas. A triangle is a plane created by connecting
+ * three points. The first two arguments specify the first point, the middle two
+ * arguments specify the second point, and the last two arguments specify the
+ * third point.
+ *
+ * @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
+ *
+ *
+ * triangle(30, 75, 58, 20, 86, 75);
+ * describe('white triangle with black outline in mid-right of canvas');
+ *
+ *
+ *
+ */
+ _main.default.prototype.triangle = function () {
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
+ args[_key4] = arguments[_key4];
+ }
+ _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': 278,
+ '../friendly_errors/fes_core': 281,
+ '../friendly_errors/file_errors': 282,
+ '../friendly_errors/validate_params': 285,
+ '../helpers': 286,
+ '../main': 290,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 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.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
+ */
+ /**
+ * Modifies the location from which ellipses are drawn by changing the way in
+ * which parameters given to ellipse(),
+ * circle() and arc() are interpreted.
+ *
+ * The default mode is `CENTER`, in which the first two parameters are interpreted
+ * as the shape's center point's x and y coordinates respectively, while the third
+ * and fourth parameters are its width and height.
+ *
+ * `ellipseMode(RADIUS)` also uses the first two parameters as the shape's center
+ * point's x and y coordinates, but uses the third and fourth parameters to
+ * specify half of the shapes's width and height.
+ *
+ * `ellipseMode(CORNER)` interprets the first two parameters as the upper-left
+ * corner of the shape, while the third and fourth parameters are its width
+ * and height.
+ *
+ * `ellipseMode(CORNERS)` interprets the first two parameters as the location of
+ * one corner of the ellipse's bounding box, and the third and fourth parameters
+ * as the location of the opposite corner.
+ *
+ * The parameter to this method must be written in ALL CAPS because they are
+ * predefined as constants in ALL CAPS and Javascript is a case-sensitive language.
+ *
+ * @method ellipseMode
+ * @param {Constant} mode either CENTER, RADIUS, CORNER, or CORNERS
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 60×60 white ellipse and 30×30 grey ellipse with black outlines at center.
+ * 60×60 white ellipse and 30×30 grey ellipse top-right with 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 all geometry with jagged (aliased) edges.
+ *
+ * Note that smooth() is active by default in 2D mode, so it is
+ * necessary to call noSmooth() to disable smoothing of geometry,
+ * images, and fonts.
+ *
+ * In 3D mode, noSmooth() is enabled by default, so it is necessary
+ * to call smooth() if you would like smooth (antialiased) edges on your
+ * geometry.
+ *
+ * @method noSmooth
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 2 pixelated 36×36 white ellipses to left & right of center, black 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;
+ };
+ /**
+ * Modifies the location from which rectangles are drawn by changing the way
+ * in which parameters given to rect() are interpreted.
+ *
+ * The default mode is `CORNER`, which interprets the first two parameters as the
+ * upper-left corner of the shape, while the third and fourth parameters are its
+ * width and height.
+ *
+ * `rectMode(CORNERS)` interprets the first two parameters as the location of
+ * one of the corners, and the third and fourth parameters as the location of
+ * the diagonally opposite corner. Note, the rectangle is drawn between the
+ * coordinates, so it is not necessary that the first corner be the upper left
+ * corner.
+ *
+ * `rectMode(CENTER)` interprets the first two parameters as the shape's center
+ * point, while the third and fourth parameters are its width and height.
+ *
+ * `rectMode(RADIUS)` also uses the first two parameters as the shape's center
+ * point, but uses the third and fourth parameters to specify half of the shape's
+ * width and height respectively.
+ *
+ * The parameter to this method must be written in ALL CAPS because they are
+ * predefined as constants in ALL CAPS and Javascript is a case-sensitive language.
+ *
+ * @method rectMode
+ * @param {Constant} mode either CORNER, CORNERS, CENTER, or RADIUS
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 50×50 white rect at center and 25×25 grey rect in the top left of the other.
+ * 50×50 white rect at center and 25×25 grey rect in the center of the other.
+ */
+ _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 all geometry with smooth (anti-aliased) edges. smooth() will also
+ * improve image quality of resized images.
+ *
+ * Note that smooth() is active by default in 2D mode;
+ * noSmooth() can be used to disable smoothing of geometry,
+ * images, and fonts.
+ *
+ * In 3D mode, noSmooth() is enabled by default, so it is
+ * necessary to call smooth() if you would like smooth (antialiased)
+ * edges on your geometry.
+ *
+ * @method smooth
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 2 pixelated 36×36 white ellipses one left one right of center. On black.
+ */
+ _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 line endings. These ends are either rounded,
+ * squared, or extended, each of which specified with the corresponding
+ * parameters: `ROUND`, `SQUARE`, or `PROJECT`. The default cap is `ROUND`.
+ *
+ * The parameter to this method must be written in ALL CAPS because they are
+ * predefined as constants in ALL CAPS and Javascript is a case-sensitive language.
+ *
+ * @method strokeCap
+ * @param {Constant} cap either ROUND, SQUARE, or PROJECT
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3 lines. Top line: rounded ends, mid: squared, bottom: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 which connect line segments. These joints
+ * are either mitered, beveled, or rounded and specified with the
+ * corresponding parameters: `MITER`, `BEVEL`, or `ROUND`. The default joint is
+ * `MITER` in 2D mode and `ROUND` in WebGL mode.
+ *
+ * The parameter to this method must be written in ALL CAPS because they are
+ * predefined as constants in ALL CAPS and Javascript is a case-sensitive language.
+ *
+ * @method strokeJoin
+ * @param {Constant} join either MITER, BEVEL, or ROUND
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Right-facing arrowhead shape with pointed tip in center of canvas.
+ * Right-facing arrowhead shape with flat tip in center of canvas.
+ * Right-facing arrowhead shape with 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 lines, points, and the border around
+ * shapes. All widths are set in units of pixels.
+ *
+ * Note that it is affected by any transformation or scaling that has
+ * been applied previously.
+ *
+ * @method strokeWeight
+ * @param {Number} weight the weight of the stroke (in pixels)
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3 horizontal black lines. Top line: thin, mid: medium, bottom:thick.
+ * 2 horizontal black line. Top line: thin, botton line: 5 times thicker than 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': 278,
+ '../main': 290,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 299: [
+ 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 cubic Bezier curve on the screen. These curves are defined by a
+ * series of anchor and control points. The first two parameters specify
+ * the first anchor point and the last two parameters specify the other
+ * anchor point, which become the first and last points on the curve. The
+ * middle parameters specify the two control points which define the shape
+ * of the curve. Approximately speaking, control points "pull" the curve
+ * towards them.
+ *
+ * Bezier curves were developed by French automotive engineer Pierre Bezier,
+ * and are commonly used in computer graphics to define gently sloping curves.
+ * See also curve().
+ *
+ * @method bezier
+ * @param {Number} x1 x-coordinate for the first anchor point
+ * @param {Number} y1 y-coordinate for the first anchor point
+ * @param {Number} x2 x-coordinate for the first control point
+ * @param {Number} y2 y-coordinate for the first control point
+ * @param {Number} x3 x-coordinate for the second control point
+ * @param {Number} y3 y-coordinate for the second control point
+ * @param {Number} x4 x-coordinate for the second anchor point
+ * @param {Number} y4 y-coordinate for the second anchor point
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * stretched black s-shape in center with orange lines extending from end points.
+ * a white colored curve on black background from the upper-right corner to the lower right corner.
+ */
+ /**
+ * @method bezier
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1 z-coordinate for the first anchor point
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate for the first control point
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3 z-coordinate for the second control point
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4 z-coordinate for 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 resolution at which Bezier's curve is displayed. The default value is 20.
+ *
+ * Note, This function is only useful when using the WEBGL renderer
+ * as the default canvas renderer does not use this information.
+ *
+ * @method bezierDetail
+ * @param {Number} detail resolution of the curves
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * stretched black s-shape with a low level of bezier detail
+ */
+ _main.default.prototype.bezierDetail = function (d) {
+ _main.default._validateParameters('bezierDetail', arguments);
+ this._bezierDetail = d;
+ return this;
+ };
+ /**
+ * Given the x or y co-ordinate values of control and anchor points of a bezier
+ * curve, it evaluates the x or y coordinate of the bezier at position t. The
+ * parameters a and d are the x or y coordinates of first and last points on the
+ * curve while b and c are of the control points.The final parameter t is the
+ * position of the resultant point which is given between 0 and 1.
+ * This can be done once with the x coordinates and a second time
+ * with the y coordinates to get the location of a bezier curve at t.
+ *
+ * @method bezierPoint
+ * @param {Number} a coordinate of first point on the curve
+ * @param {Number} b coordinate of first control point
+ * @param {Number} c coordinate of second control point
+ * @param {Number} d coordinate of second point on the curve
+ * @param {Number} t value between 0 and 1
+ * @return {Number} the value of the Bezier at position t
+ * @example
+ *
+ *
+ * noFill();
+ * let x1 = 85,
+ x2 = 10,
+ x3 = 90,
+ x4 = 15;
+ * let y1 = 20,
+ y2 = 10,
+ y3 = 90,
+ y4 = 80;
+ * bezier(x1, y1, x2, y2, x3, y3, x4, y4);
+ * fill(255);
+ * let steps = 10;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = bezierPoint(x1, x2, x3, x4, t);
+ * let y = bezierPoint(y1, y2, y3, y4, t);
+ * circle(x, y, 5);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 10 points plotted on a given bezier at equal distances.
+ */
+ _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;
+ };
+ /**
+ * Evaluates the tangent to the Bezier at position t for points a, b, c, d.
+ * The parameters a and d are the first and last points
+ * on the curve, and b and c are the control points.
+ * The final parameter t varies between 0 and 1.
+ *
+ * @method bezierTangent
+ * @param {Number} a coordinate of first point on the curve
+ * @param {Number} b coordinate of first control point
+ * @param {Number} c coordinate of second control point
+ * @param {Number} d coordinate of second point on the curve
+ * @param {Number} t value between 0 and 1
+ * @return {Number} the tangent at position t
+ * @example
+ *
+ *
+ * noFill();
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ * let steps = 6;
+ * fill(255);
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * // Get the location of the point
+ * let x = bezierPoint(85, 10, 90, 15, t);
+ * let y = bezierPoint(20, 10, 90, 80, t);
+ * // Get the tangent points
+ * let tx = bezierTangent(85, 10, 90, 15, t);
+ * let ty = bezierTangent(20, 10, 90, 80, t);
+ * // Calculate an angle from the tangent points
+ * let a = atan2(ty, tx);
+ * a += PI;
+ * stroke(255, 102, 0);
+ * line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);
+ * // The following line of code makes a line
+ * // inverse of the above line
+ * //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);
+ * stroke(0);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * noFill();
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ * stroke(255, 102, 0);
+ * let steps = 16;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = bezierPoint(85, 10, 90, 15, t);
+ * let y = bezierPoint(20, 10, 90, 80, t);
+ * let tx = bezierTangent(85, 10, 90, 15, t);
+ * let ty = bezierTangent(20, 10, 90, 80, t);
+ * let a = atan2(ty, tx);
+ * a -= HALF_PI;
+ * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
+ * }
+ *
+ *
+ *
+ * @alt
+ * s-shaped line with 6 short orange lines showing the tangents at those points.
+ * s-shaped line with 6 short orange lines showing lines coming out the underside of the bezier.
+ */
+ _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 curved line on the screen between two points, given as the
+ * middle four parameters. The first two parameters are a control point, as
+ * if the curve came from this point even though it's not drawn. The last
+ * two parameters similarly describe the other control point.
+ * Longer curves can be created by putting a series of curve() functions
+ * together or using curveVertex(). An additional function called
+ * curveTightness() provides control for the visual quality of the curve.
+ * The curve() function is an implementation of Catmull-Rom splines.
+ *
+ * @method curve
+ * @param {Number} x1 x-coordinate for the beginning control point
+ * @param {Number} y1 y-coordinate for the beginning control point
+ * @param {Number} x2 x-coordinate for the first point
+ * @param {Number} y2 y-coordinate for the first point
+ * @param {Number} x3 x-coordinate for the second point
+ * @param {Number} y3 y-coordinate for the second point
+ * @param {Number} x4 x-coordinate for the ending control point
+ * @param {Number} y4 y-coordinate for the ending control point
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * horseshoe shape with orange ends facing left and black curved center.
+ * horseshoe shape with orange ends facing left and black curved center.
+ * curving black and orange lines.
+ */
+ /**
+ * @method curve
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1 z-coordinate for the beginning control point
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate for the first point
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3 z-coordinate for the second point
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4 z-coordinate for the ending 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 resolution at which curves display. The default value is 20 while
+ * the minimum value is 3.
+ *
+ * This function is only useful when using the WEBGL renderer
+ * as the default canvas renderer does not use this
+ * information.
+ *
+ * @method curveDetail
+ * @param {Number} resolution resolution of the curves
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white arch shape with a low level of curve detail.
+ */
+ _main.default.prototype.curveDetail = function (d) {
+ _main.default._validateParameters('curveDetail', arguments);
+ if (d < 3) {
+ this._curveDetail = 3;
+ } else {
+ this._curveDetail = d;
+ }
+ return this;
+ };
+ /**
+ * Modifies the quality of forms created with curve()
+ * and curveVertex().The parameter tightness
+ * determines how the curve fits to the vertex points. The value 0.0 is the
+ * default value for tightness (this value defines the curves to be Catmull-Rom
+ * splines) and the value 1.0 connects all the points with straight lines.
+ * Values within the range -5.0 and 5.0 will deform the curves but will leave
+ * them recognizable and as values increase in magnitude, they will continue to deform.
+ *
+ * @method curveTightness
+ * @param {Number} amount amount of deformation from the original vertices
+ * @chainable
+ * @example
+ *
+ *
+ * // Move the mouse left and right to see the curve change
+ * function setup() {
+ * createCanvas(100, 100);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * let t = map(mouseX, 0, width, -5, 5);
+ * curveTightness(t);
+ * beginShape();
+ * curveVertex(10, 26);
+ * curveVertex(10, 26);
+ * curveVertex(83, 24);
+ * curveVertex(83, 61);
+ * curveVertex(25, 65);
+ * curveVertex(25, 65);
+ * endShape();
+ * }
+ *
+ *
+ *
+ * @alt
+ * Line shaped like right-facing arrow,points move with mouse-x and warp shape.
+ */
+ _main.default.prototype.curveTightness = function (t) {
+ _main.default._validateParameters('curveTightness', arguments);
+ this._renderer._curveTightness = t;
+ return this;
+ };
+ /**
+ * Evaluates the curve at position t for points a, b, c, d.
+ * The parameter t varies between 0 and 1, a and d are control points
+ * of the curve, and b and c are the start and end points of the curve.
+ * This can be done once with the x coordinates and a second time
+ * with the y coordinates to get the location of a curve at t.
+ *
+ * @method curvePoint
+ * @param {Number} a coordinate of first control point of the curve
+ * @param {Number} b coordinate of first point
+ * @param {Number} c coordinate of second point
+ * @param {Number} d coordinate of second control point
+ * @param {Number} t value between 0 and 1
+ * @return {Number} Curve value at position t
+ * @example
+ *
+ *
+ * noFill();
+ * curve(5, 26, 5, 26, 73, 24, 73, 61);
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * fill(255);
+ * ellipseMode(CENTER);
+ * let steps = 6;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = curvePoint(5, 5, 73, 73, t);
+ * let y = curvePoint(26, 26, 24, 61, t);
+ * ellipse(x, y, 5, 5);
+ * x = curvePoint(5, 73, 73, 15, t);
+ * y = curvePoint(26, 24, 61, 65, t);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ *
+ *line hooking down to right-bottom with 13 5×5 white ellipse points
+ */
+ _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;
+ };
+ /**
+ * Evaluates the tangent to the curve at position t for points a, b, c, d.
+ * The parameter t varies between 0 and 1, a and d are points on the curve,
+ * and b and c are the control points.
+ *
+ * @method curveTangent
+ * @param {Number} a coordinate of first control point
+ * @param {Number} b coordinate of first point on the curve
+ * @param {Number} c coordinate of second point on the curve
+ * @param {Number} d coordinate of second conrol point
+ * @param {Number} t value between 0 and 1
+ * @return {Number} the tangent at position t
+ * @example
+ *
+ *
+ * noFill();
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * let steps = 6;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = curvePoint(5, 73, 73, 15, t);
+ * let y = curvePoint(26, 24, 61, 65, t);
+ * //ellipse(x, y, 5, 5);
+ * let tx = curveTangent(5, 73, 73, 15, t);
+ * let ty = curveTangent(26, 24, 61, 65, t);
+ * let a = atan2(ty, tx);
+ * a -= PI / 2.0;
+ * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
+ * }
+ *
+ *
+ *
+ * @alt
+ * right curving line mid-right of canvas with 7 short lines radiating from it.
+ */
+ _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': 281,
+ '../friendly_errors/file_errors': 282,
+ '../friendly_errors/validate_params': 285,
+ '../main': 290
+ }
+ ],
+ 300: [
+ 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;
+ /**
+ * Use the beginContour() and
+ * endContour() functions to create negative shapes
+ * within shapes such as the center of the letter 'O'. beginContour()
+ * begins recording vertices for the shape and endContour() stops recording.
+ * The vertices that define a negative shape must "wind" in the opposite direction
+ * from the exterior shape. First draw vertices for the exterior clockwise order, then for internal shapes, draw vertices
+ * shape in counter-clockwise.
+ *
+ * These functions can only be used within a beginShape()/endShape() pair and
+ * transformations such as translate(), rotate(), and scale() do not work
+ * within a beginContour()/endContour() pair. It is also not possible to use
+ * other shapes, such as ellipse() or rect() within.
+ *
+ * @method beginContour
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white rect and smaller grey rect with red outlines in center of canvas.
+ */
+ _main.default.prototype.beginContour = function () {
+ contourVertices = [
+ ];
+ isContour = true;
+ return this;
+ };
+ /**
+ * Using the beginShape() and endShape() functions allow creating more
+ * complex forms. beginShape() begins recording vertices for a shape and
+ * endShape() stops recording. The value of the kind parameter tells it which
+ * types of shapes to create from the provided vertices. With no mode
+ * specified, the shape can be any irregular polygon.
+ *
+ * The parameters available for beginShape() are:
+ *
+ * POINTS
+ * Draw a series of points
+ *
+ * LINES
+ * Draw a series of unconnected line segments (individual lines)
+ *
+ * TRIANGLES
+ * Draw a series of separate triangles
+ *
+ * TRIANGLE_FAN
+ * Draw a series of connected triangles sharing the first vertex in a fan-like fashion
+ *
+ * TRIANGLE_STRIP
+ * Draw a series of connected triangles in strip fashion
+ *
+ * QUADS
+ * Draw a series of separate quads
+ *
+ * QUAD_STRIP
+ * Draw quad strip using adjacent edges to form the next quad
+ *
+ * TESS (WEBGL only)
+ * Handle irregular polygon for filling curve by explicit tessellation
+ *
+ * After calling the beginShape() function, a series of vertex() commands must follow. To stop
+ * drawing the shape, call endShape(). Each shape will be outlined with the
+ * current stroke color and filled with the fill color.
+ *
+ * Transformations such as translate(), rotate(), and scale() do not work
+ * within beginShape(). It is also not possible to use other shapes, such as
+ * ellipse() or rect() within beginShape().
+ *
+ * @method beginShape
+ * @param {Constant} [kind] either POINTS, LINES, TRIANGLES, TRIANGLE_FAN
+ * TRIANGLE_STRIP, QUADS, QUAD_STRIP or TESS
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white square-shape with black outline in middle-right of canvas.
+ * 4 black points in a square shape in middle-right of canvas.
+ * 2 horizontal black lines. In the top-right and bottom-right of canvas.
+ * 3 line shape with horizontal on top, vertical in middle and horizontal bottom.
+ * square line shape in middle-right of canvas.
+ * 2 white triangle shapes mid-right canvas. left one pointing up and right down.
+ * 5 horizontal interlocking and alternating white triangles in mid-right canvas.
+ * 4 interlocking white triangles in 45 degree rotated square-shape.
+ * 2 white rectangle shapes in mid-right canvas. Both 20×55.
+ * 3 side-by-side white rectangles center rect is smaller in mid-right canvas.
+ * Thick white l-shape with black outline mid-top-left of canvas.
+ */
+ _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;
+ };
+ /**
+ * Specifies vertex coordinates for Bezier curves. Each call to
+ * bezierVertex() defines the position of two control points and
+ * one anchor point of a Bezier curve, adding a new segment to a
+ * line or shape. For WebGL mode bezierVertex() can be used in 2D
+ * as well as 3D mode. 2D mode expects 6 parameters, while 3D mode
+ * expects 9 parameters (including z coordinates).
+ *
+ * The first time bezierVertex() is used within a beginShape()
+ * call, it must be prefaced with a call to vertex() to set the first anchor
+ * point. This function must be used between beginShape() and endShape()
+ * and only when there is no MODE or POINTS parameter specified to
+ * beginShape().
+ *
+ * @method bezierVertex
+ * @param {Number} x2 x-coordinate for the first control point
+ * @param {Number} y2 y-coordinate for the first control point
+ * @param {Number} x3 x-coordinate for the second control point
+ * @param {Number} y3 y-coordinate for the second control point
+ * @param {Number} x4 x-coordinate for the anchor point
+ * @param {Number} y4 y-coordinate for the anchor point
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * @alt
+ * crescent-shaped line in middle of canvas. Points facing left.
+ * white crescent shape in middle of canvas. Points facing left.
+ * crescent shape in middle of canvas with another crescent shape on positive z-axis.
+ */
+ /**
+ * @method bezierVertex
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate for the first control point (for WebGL mode)
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3 z-coordinate for the second control point (for WebGL mode)
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4 z-coordinate for the anchor point (for WebGL mode)
+ * @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;
+ };
+ /**
+ * Specifies vertex coordinates for curves. This function may only
+ * be used between beginShape() and endShape() and only when there
+ * is no MODE parameter specified to beginShape().
+ * For WebGL mode curveVertex() can be used in 2D as well as 3D mode.
+ * 2D mode expects 2 parameters, while 3D mode expects 3 parameters.
+ *
+ * The first and last points in a series of curveVertex() lines will be used to
+ * guide the beginning and end of the curve. A minimum of four
+ * points is required to draw a tiny curve between the second and
+ * third points. Adding a fifth point with curveVertex() will draw
+ * the curve between the second, third, and fourth points. The
+ * curveVertex() function is an implementation of Catmull-Rom
+ * splines.
+ *
+ * @method curveVertex
+ * @param {Number} x x-coordinate of the vertex
+ * @param {Number} y y-coordinate of the vertex
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Upside-down u-shape line, mid canvas with the same shape in positive z-axis.
+ */
+ _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;
+ };
+ /**
+ * Use the beginContour() and endContour() functions to create negative
+ * shapes within shapes such as the center of the letter 'O'. beginContour()
+ * begins recording vertices for the shape and endContour() stops recording.
+ * The vertices that define a negative shape must "wind" in the opposite
+ * direction from the exterior shape. First draw vertices for the exterior
+ * clockwise order, then for internal shapes, draw vertices
+ * shape in counter-clockwise.
+ *
+ * These functions can only be used within a beginShape()/endShape() pair and
+ * transformations such as translate(), rotate(), and scale() do not work
+ * within a beginContour()/endContour() pair. It is also not possible to use
+ * other shapes, such as ellipse() or rect() within.
+ *
+ * @method endContour
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white rect and smaller grey rect with red outlines in center of canvas.
+ */
+ _main.default.prototype.endContour = function () {
+ 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;
+ };
+ /**
+ * The endShape() function is the companion to beginShape() and may only be
+ * called after beginShape(). When endShape() is called, all of the image
+ * data defined since the previous call to beginShape() is written into the image
+ * buffer. The constant CLOSE as the value for the `mode` parameter to close
+ * the shape (to connect the beginning and the end).
+ *
+ * @method endShape
+ * @param {Constant} [mode] use CLOSE to close the shape
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Triangle line shape with smallest interior angle on bottom and upside-down L.
+ */
+ _main.default.prototype.endShape = function (mode) {
+ _main.default._validateParameters('endShape', arguments);
+ if (this._renderer.isP3D) {
+ this._renderer.endShape(mode, isCurve, isBezier, isQuadratic, isContour, shapeKind);
+ } else {
+ 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;
+ };
+ /**
+ * Specifies vertex coordinates for quadratic Bezier curves. Each call to
+ * quadraticVertex() defines the position of one control points and one
+ * anchor point of a Bezier curve, adding a new segment to a line or shape.
+ * The first time quadraticVertex() is used within a beginShape() call, it
+ * must be prefaced with a call to vertex() to set the first anchor point.
+ * For WebGL mode quadraticVertex() can be used in 2D as well as 3D mode.
+ * 2D mode expects 4 parameters, while 3D mode expects 6 parameters
+ * (including z coordinates).
+ *
+ * This function must be used between beginShape() and endShape()
+ * and only when there is no MODE or POINTS parameter specified to
+ * beginShape().
+ *
+ * @method quadraticVertex
+ * @param {Number} cx x-coordinate for the control point
+ * @param {Number} cy y-coordinate for the control point
+ * @param {Number} x3 x-coordinate for the anchor point
+ * @param {Number} y3 y-coordinate for the anchor point
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * @alt
+ * backwards s-shaped black line with the same s-shaped line in positive z-axis.
+ */
+ _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;
+ };
+ /**
+ * All shapes are constructed by connecting a series of vertices. vertex()
+ * is used to specify the vertex coordinates for points, lines, triangles,
+ * quads, and polygons. It is used exclusively within the beginShape() and
+ * endShape() functions.
+ *
+ * @method vertex
+ * @param {Number} x x-coordinate of the vertex
+ * @param {Number} y y-coordinate of the vertex
+ * @chainable
+ * @example
+ *
+ *
+ * // Click to change the number of sides.
+ * // In WebGL mode, custom shapes will only
+ * // display hollow fill sections when
+ * // all calls to vertex() use the same z-value.
+ *
+ * let sides = 3;
+ * let angle, px, py;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * setAttributes('antialias', true);
+ * fill(237, 34, 93);
+ * strokeWeight(3);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateX(frameCount * 0.01);
+ * rotateZ(frameCount * 0.01);
+ * ngon(sides, 0, 0, 80);
+ * }
+ *
+ * function mouseClicked() {
+ * if (sides > 6) {
+ * sides = 3;
+ * } else {
+ * sides++;
+ * }
+ * }
+ *
+ * function ngon(n, x, y, d) {
+ * beginShape(TESS);
+ * for (let i = 0; i < n + 1; i++) {
+ * angle = TWO_PI / n * i;
+ * px = x + sin(angle) * d / 2;
+ * py = y - cos(angle) * d / 2;
+ * vertex(px, py, 0);
+ * }
+ * for (let i = 0; i < n + 1; i++) {
+ * angle = TWO_PI / n * i;
+ * px = x + sin(angle) * d / 4;
+ * py = y - cos(angle) * d / 4;
+ * vertex(px, py, 0);
+ * }
+ * endShape();
+ * }
+ *
+ *
+ * @alt
+ * 4 black points in a square shape in middle-right of canvas.
+ * 4 points making a diamond shape.
+ * 8 points making a star.
+ * 8 points making 4 lines.
+ * A rotating 3D shape with a hollow section in the middle.
+ */
+ /**
+ * @method vertex
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} [z] z-coordinate of the vertex.
+ * Defaults to 0 if not specified.
+ * @chainable
+ */
+ /**
+ * @method vertex
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} [z]
+ * @param {Number} [u] the vertex's texture u-coordinate
+ * @param {Number} [v] the vertex's texture v-coordinate
+ * @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 3d vertex normal to use for subsequent vertices drawn with
+ * vertex(). A normal is a vector that is generally
+ * nearly perpendicular to a shape's surface which controls how much light will
+ * be reflected from that part of the surface.
+ *
+ * @method normal
+ * @param {Vector} vector A p5.Vector representing the vertex normal.
+ * @chainable
+ * @example
+ *
+ *
+ * let x = 0;
+ * function setup() {
+ * createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x = x + 0.1;
+ * if (x > width) {
+ * x = 0;
+ * }
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * noLoop();
+ * }
+ *
+ * function mouseReleased() {
+ * loop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * 113 pixel long line extending from top-left to bottom right of canvas.
+ * horizontal line moves slowly from left. Loops but stops on mouse press.
+ */
+
+ _main.default.prototype.noLoop = function () {
+ this._loop = false;
+ };
+ /**
+ * By default, p5.js loops through draw() continuously, executing the code within
+ * it. However, the draw() loop may be stopped by calling
+ * noLoop(). In that case, the draw()
+ * loop can be resumed with loop().
+ *
+ * Avoid calling loop() from inside setup().
+ *
+ * Use isLooping() to check the current state of loop().
+ *
+ * @method loop
+ * @example
+ *
+ *
+ * let x = 0;
+ * function setup() {
+ * createCanvas(100, 100);
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x = x + 0.1;
+ * if (x > width) {
+ * x = 0;
+ * }
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * loop();
+ * }
+ *
+ * function mouseReleased() {
+ * noLoop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * horizontal line moves slowly from left. Loops but stops on mouse press.
+ */
+ _main.default.prototype.loop = function () {
+ if (!this._loop) {
+ this._loop = true;
+ if (this._setupDone) {
+ this._draw();
+ }
+ }
+ };
+ /**
+ * By default, p5.js loops through draw() continuously,
+ * executing the code within it. If the sketch is stopped with
+ * noLoop() or resumed with loop(),
+ * isLooping() returns the current state for use within custom event handlers.
+ *
+ * @method isLooping
+ * @returns {boolean}
+ * @example
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * translate(50, 0);
+ * ellipse(0, 50, 33, 33); // Middle circle
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(33, 50, 33, 33); // Left-middle circle
+ *
+ * push(); // Start another new drawing state
+ * stroke(0, 102, 153);
+ * ellipse(66, 50, 33, 33); // Right-middle circle
+ * pop(); // Restore previous state
+ *
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ * @alt
+ * Gold ellipse + thick black outline @center 2 white ellipses on left and right.
+ * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.
+ */
+ _main.default.prototype.push = function () {
+ this._styles.push({
+ props: {
+ _colorMode: this._colorMode
+ },
+ renderer: this._renderer.push()
+ });
+ };
+ /**
+ * The push() function saves the current drawing style
+ * settings and transformations, while pop() restores
+ * these settings. Note that these functions are always used together. They allow
+ * you to change the style and transformation settings and later return to what
+ * you had. When a new state is started with push(), it
+ * builds on the current style and transform information. The push()
+ * and pop() functions can be embedded to provide more
+ * control. (See the second example for a demonstration.)
+ *
+ * push() stores information related to the current transformation state
+ * and style settings controlled by 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(),
+ * noiseSeed().
+ *
+ * In WEBGL mode additional style settings are stored. These are controlled by
+ * the following functions:
+ * setCamera(),
+ * ambientLight(),
+ * directionalLight(),
+ * pointLight(),
+ * texture(),
+ * specularMaterial(),
+ * shininess(),
+ * normalMaterial() and
+ * shader().
+ *
+ * @method pop
+ * @example
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * translate(50, 0);
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(0, 50, 33, 33); // Middle circle
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(33, 50, 33, 33); // Left-middle circle
+ *
+ * push(); // Start another new drawing state
+ * stroke(0, 102, 153);
+ * ellipse(66, 50, 33, 33); // Right-middle circle
+ * pop(); // Restore previous state
+ *
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ * @alt
+ * Gold ellipse + thick black outline @center 2 white ellipses on left and right.
+ * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.
+ */
+ _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()');
+ }
+ };
+ /**
+ * Executes the code within draw() one time. This
+ * function allows the program to update the display window only when necessary,
+ * for example when an event registered by mousePressed()
+ * or keyPressed() occurs.
+ *
+ * In structuring a program, it only makes sense to call redraw()
+ * within events such as mousePressed(). This
+ * is because redraw() does not run
+ * draw() immediately (it only sets a flag that indicates
+ * an update is needed).
+ *
+ * The redraw() function does not work properly when
+ * called inside draw().To enable/disable animations,
+ * use loop() and noLoop().
+ *
+ * In addition you can set the number of redraws per method call. Just
+ * add an integer as single parameter for the number of redraws.
+ *
+ * @method redraw
+ * @param {Integer} [n] Redraw for n-times. The default value is 1.
+ * @example
+ *
+ *
+ * @alt
+ * black line on far left of canvas
+ * black line on far left of canvas
+ */
+ _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);
+ }
+ var callMethod = function callMethod(f) {
+ f.call(context);
+ };
+ 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);
+ context._registeredMethods.pre.forEach(callMethod);
+ this._inUserDraw = true;
+ try {
+ context.draw();
+ } finally {
+ this._inUserDraw = false;
+ }
+ context._registeredMethods.post.forEach(callMethod);
+ }
+ }
+ };
+ /**
+ * The `p5()` constructor enables you to activate "instance mode" instead of normal
+ * "global mode". This is an advanced topic. A short description and example is
+ * included below. Please see
+ *
+ * Dan Shiffman's Coding Train video tutorial or this
+ * tutorial page
+ * for more info.
+ *
+ * By default, all p5.js functions are in the global namespace (i.e. bound to the window
+ * object), meaning you can call them simply `ellipse()`, `fill()`, etc. However, this
+ * might be inconvenient if you are mixing with other JS libraries (synchronously or
+ * asynchronously) or writing long programs of your own. p5.js currently supports a
+ * way around this problem called "instance mode". In instance mode, all p5 functions
+ * are bound up in a single variable instead of polluting your global namespace.
+ *
+ * Optionally, you can specify a default container for the canvas and any other elements
+ * to append to with a second argument. You can give the ID of an element in your html,
+ * or an html node itself.
+ *
+ * Note that creating instances like this also allows you to have more than one p5 sketch on
+ * a single web page, as they will each be wrapped up with their own set up variables. Of
+ * course, you could also use iframes to have multiple sketches in global mode.
+ *
+ * @method p5
+ * @param {Object} sketch a function containing a p5.js sketch
+ * @param {String|Object} node ID or pointer to HTML DOM node to contain sketch in
+ * @example
+ *
+ * const s = p => {
+ * let x = 100;
+ * let y = 100;
+ *
+ * p.setup = function() {
+ * p.createCanvas(700, 410);
+ * };
+ *
+ * p.draw = function() {
+ * p.background(0);
+ * p.fill(255);
+ * p.rect(x, y, 50, 50);
+ * };
+ * };
+ *
+ * new p5(s); // invoke p5
+ *
+ *
+ * @alt
+ * white rectangle on black background
+ */
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ './main': 290,
+ 'core-js/modules/es.array.for-each': 172,
+ 'core-js/modules/es.object.assign': 190,
+ 'core-js/modules/web.dom-collections.for-each': 247
+ }
+ ],
+ 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.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.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');
+ 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;
+ }
+ } /**
+ * Multiplies the current matrix by the one specified through the parameters.
+ * This is a powerful operation that can perform the equivalent of translate,
+ * scale, shear and rotate all at once. You can learn more about transformation
+ * matrices on
+ * Wikipedia.
+ *
+ * The naming of the arguments here follows the naming of the
+ * WHATWG specification and corresponds to a
+ * transformation matrix of the
+ * form:
+ *
+ * >
+ *
+ *
+ *
+ * @method applyMatrix
+ * @param {Array} arr an array of numbers - should be 6 or 16 length (2*3 or 4*4 matrix values)
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * A rectangle translating to the right
+ * A rectangle shrinking to the center
+ * A rectangle rotating clockwise about the center
+ * A rectangle shearing
+ * A rectangle in the upper left corner
+ */
+ /**
+ * @method applyMatrix
+ * @param {Number} a numbers which define the 2×3 or 4x4 matrix to be multiplied
+ * @param {Number} b numbers which define the 2×3 or 4x4 matrix to be multiplied
+ * @param {Number} c numbers which define the 2×3 or 4x4 matrix to be multiplied
+ * @param {Number} d numbers which define the 2×3 or 4x4 matrix to be multiplied
+ * @param {Number} e numbers which define the 2×3 or 4x4 matrix to be multiplied
+ * @param {Number} f numbers which define the 2×3 or 4x4 matrix to be multiplied
+ * @chainable
+ */
+ /**
+ * @method applyMatrix
+ * @param {Number} a
+ * @param {Number} b
+ * @param {Number} c
+ * @param {Number} d
+ * @param {Number} e
+ * @param {Number} f
+ * @param {Number} g numbers which define the 4x4 matrix to be multiplied
+ * @param {Number} h numbers which define the 4x4 matrix to be multiplied
+ * @param {Number} i numbers which define the 4x4 matrix to be multiplied
+ * @param {Number} j numbers which define the 4x4 matrix to be multiplied
+ * @param {Number} k numbers which define the 4x4 matrix to be multiplied
+ * @param {Number} l numbers which define the 4x4 matrix to be multiplied
+ * @param {Number} m numbers which define the 4x4 matrix to be multiplied
+ * @param {Number} n numbers which define the 4x4 matrix to be multiplied
+ * @param {Number} o numbers which define the 4x4 matrix to be multiplied
+ * @param {Number} p numbers which define the 4x4 matrix to be multiplied
+ * @chainable
+ */
+
+ _main.default.prototype.applyMatrix = function () {
+ var isTypedArray = arguments[0] instanceof Object.getPrototypeOf(Uint8Array);
+ if (Array.isArray(arguments[0]) || isTypedArray) {
+ var _this$_renderer;
+ (_this$_renderer = this._renderer).applyMatrix.apply(_this$_renderer, _toConsumableArray(arguments[0]));
+ } else {
+ var _this$_renderer2;
+ (_this$_renderer2 = this._renderer).applyMatrix.apply(_this$_renderer2, arguments);
+ }
+ return this;
+ };
+ /**
+ * Replaces the current matrix with the identity matrix.
+ *
+ * @method resetMatrix
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * A rotated rectangle in the center with another at the top left corner
+ */
+ _main.default.prototype.resetMatrix = function () {
+ this._renderer.resetMatrix();
+ return this;
+ };
+ /**
+ * Rotates a shape by the amount specified by the angle parameter. This
+ * function accounts for angleMode, so angles
+ * can be entered in either RADIANS or DEGREES.
+ *
+ * Objects are always rotated around their relative position to the
+ * origin and positive numbers rotate objects in a clockwise direction.
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulate the effect. For example, calling
+ * rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).
+ * All transformations are reset when draw() begins again.
+ *
+ * Technically, rotate() multiplies the current transformation matrix
+ * by a rotation matrix. This function can be further controlled by
+ * push() and pop().
+ *
+ * @method rotate
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @param {p5.Vector|Number[]} [axis] (in 3d) the axis to rotate around
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white 52×52 rect with black outline at center rotated counter 45 degrees
+ */
+ _main.default.prototype.rotate = function (angle, axis) {
+ _main.default._validateParameters('rotate', arguments);
+ this._renderer.rotate(this._toRadians(angle), axis);
+ return this;
+ };
+ /**
+ * Rotates a shape around X axis by the amount specified in angle parameter.
+ * The angles can be entered in either RADIANS or DEGREES.
+ *
+ * Objects are always rotated around their relative position to the
+ * origin and positive numbers rotate objects in a clockwise direction.
+ * All transformations are reset when draw() begins again.
+ *
+ * @method rotateX
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3d box rotating around the x axis.
+ */
+ _main.default.prototype.rotateX = function (angle) {
+ this._assert3d('rotateX');
+ _main.default._validateParameters('rotateX', arguments);
+ this._renderer.rotateX(this._toRadians(angle));
+ return this;
+ };
+ /**
+ * Rotates a shape around Y axis by the amount specified in angle parameter.
+ * The angles can be entered in either RADIANS or DEGREES.
+ *
+ * Objects are always rotated around their relative position to the
+ * origin and positive numbers rotate objects in a clockwise direction.
+ * All transformations are reset when draw() begins again.
+ *
+ * @method rotateY
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3d box rotating around the y axis.
+ */
+ _main.default.prototype.rotateY = function (angle) {
+ this._assert3d('rotateY');
+ _main.default._validateParameters('rotateY', arguments);
+ this._renderer.rotateY(this._toRadians(angle));
+ return this;
+ };
+ /**
+ * Rotates a shape around Z axis by the amount specified in angle parameter.
+ * The angles can be entered in either RADIANS or DEGREES.
+ *
+ * This method works in WEBGL mode only.
+ *
+ * Objects are always rotated around their relative position to the
+ * origin and positive numbers rotate objects in a clockwise direction.
+ * All transformations are reset when draw() begins again.
+ *
+ * @method rotateZ
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3d box rotating around the z axis.
+ */
+ _main.default.prototype.rotateZ = function (angle) {
+ this._assert3d('rotateZ');
+ _main.default._validateParameters('rotateZ', arguments);
+ this._renderer.rotateZ(this._toRadians(angle));
+ return this;
+ };
+ /**
+ * Increases or decreases the size of a shape by expanding or contracting
+ * vertices. Objects always scale from their relative origin to the
+ * coordinate system. Scale values are specified as decimal percentages.
+ * For example, the function call scale(2.0) increases the dimension of a
+ * shape by 200%.
+ *
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function multiply the effect. For example, calling scale(2.0)
+ * and then scale(1.5) is the same as scale(3.0). If scale() is called
+ * within draw(), the transformation is reset when the loop begins again.
+ *
+ * Using this function with the z parameter is only available in WEBGL mode.
+ * This function can be further controlled with push() and pop().
+ *
+ * @method scale
+ * @param {Number|p5.Vector|Number[]} s
+ * percent to scale the object, or percentage to
+ * scale the object in the x-axis if multiple arguments
+ * are given
+ * @param {Number} [y] percent to scale the object in the y-axis
+ * @param {Number} [z] percent to scale the object in the z-axis (webgl only)
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white 52×52 rect with black outline at center rotated counter 45 degrees
+ * 2 white rects with black outline- 1 50×50 at center. other 25×65 bottom left
+ */
+ /**
+ * @method scale
+ * @param {p5.Vector|Number[]} scales per-axis percents to scale the object
+ * @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 (x instanceof Array) {
+ 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.call(this._renderer, x, y, z);
+ return this;
+ };
+ /**
+ * Shears a shape around the x-axis by the amount specified by the angle
+ * parameter. Angles should be specified in the current angleMode.
+ * Objects are always sheared around their relative position to the origin
+ * and positive numbers shear objects in a clockwise direction.
+ *
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * shearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).
+ * If shearX() is called within the draw(),
+ * the transformation is reset when the loop begins again.
+ *
+ * Technically, shearX() multiplies the current
+ * transformation matrix by a rotation matrix. This function can be further
+ * controlled by the push() and pop() functions.
+ *
+ * @method shearX
+ * @param {Number} angle angle of shear specified in radians or degrees,
+ * depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white irregular quadrilateral with black outline at top middle.
+ */
+ _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 a shape around the y-axis the amount specified by the angle
+ * parameter. Angles should be specified in the current angleMode. Objects
+ * are always sheared around their relative position to the origin and
+ * positive numbers shear objects in a clockwise direction.
+ *
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * shearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If
+ * shearY() is called within the draw(), the transformation is reset when
+ * the loop begins again.
+ *
+ * Technically, shearY() multiplies the current transformation matrix by a
+ * rotation matrix. This function can be further controlled by the
+ * push() and pop() functions.
+ *
+ * @method shearY
+ * @param {Number} angle angle of shear specified in radians or degrees,
+ * depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white irregular quadrilateral with black outline at middle bottom.
+ */
+ _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;
+ };
+ /**
+ * Specifies an amount to displace objects within the display window.
+ * The x parameter specifies left/right translation, the y parameter
+ * specifies up/down translation.
+ *
+ * Transformations are cumulative and apply to everything that happens after
+ * and subsequent calls to the function accumulates the effect. For example,
+ * calling translate(50, 0) and then translate(20, 0) is the same as
+ * translate(70, 0). If translate() is called within draw(), the
+ * transformation is reset when the loop begins again. This function can be
+ * further controlled by using push() and pop().
+ *
+ * @method translate
+ * @param {Number} x left/right translation
+ * @param {Number} y up/down translation
+ * @param {Number} [z] forward/backward translation (WEBGL only)
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white 55×55 rect with black outline at center right.
+ * 3 white 55×55 rects with black outlines at top-l, center-r and bottom-r.
+ * a 20×20 white rect moving in a circle around the canvas
+ */
+ /**
+ * @method translate
+ * @param {p5.Vector} vector the vector to translate by
+ * @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': 290,
+ 'core-js/modules/es.array.from': 173,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-prototype-of': 193,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.typed-array.copy-within': 215,
+ 'core-js/modules/es.typed-array.every': 216,
+ 'core-js/modules/es.typed-array.fill': 217,
+ 'core-js/modules/es.typed-array.filter': 218,
+ 'core-js/modules/es.typed-array.find': 220,
+ 'core-js/modules/es.typed-array.find-index': 219,
+ 'core-js/modules/es.typed-array.for-each': 223,
+ 'core-js/modules/es.typed-array.includes': 224,
+ 'core-js/modules/es.typed-array.index-of': 225,
+ 'core-js/modules/es.typed-array.iterator': 228,
+ 'core-js/modules/es.typed-array.join': 229,
+ 'core-js/modules/es.typed-array.last-index-of': 230,
+ 'core-js/modules/es.typed-array.map': 231,
+ 'core-js/modules/es.typed-array.reduce': 233,
+ 'core-js/modules/es.typed-array.reduce-right': 232,
+ 'core-js/modules/es.typed-array.reverse': 234,
+ 'core-js/modules/es.typed-array.set': 235,
+ 'core-js/modules/es.typed-array.slice': 236,
+ 'core-js/modules/es.typed-array.some': 237,
+ 'core-js/modules/es.typed-array.sort': 238,
+ 'core-js/modules/es.typed-array.subarray': 239,
+ 'core-js/modules/es.typed-array.to-locale-string': 240,
+ 'core-js/modules/es.typed-array.to-string': 241,
+ 'core-js/modules/es.typed-array.uint8-array': 244,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 304: [
+ 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.to-string');
+ _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/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.from');
+ _dereq_('core-js/modules/es.array.iterator');
+ _dereq_('core-js/modules/es.object.to-string');
+ _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/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);
+ } /**
+ *
+ * Stores a value in local storage under the key name.
+ * Local storage is saved in the browser and persists
+ * between browsing sessions and page reloads.
+ * The key can be the name of the variable but doesn't
+ * have to be. To retrieve stored items
+ * see getItem.
+ *
+ * Sensitive data such as passwords or personal information
+ * should not be stored in local storage.
+ *
+ * @method storeItem
+ * @for p5
+ * @param {String} key
+ * @param {String|Number|Object|Boolean|p5.Color|p5.Vector} value
+ *
+ * @example
+ *
+ * // Type to change the letter in the
+ * // center of the canvas.
+ * // If you reload the page, it will
+ * // still display the last key you entered
+ *
+ * let myText;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * myText = getItem('myText');
+ * if (myText === null) {
+ * myText = '';
+ * }
+ * describe(`When you type the key name is displayed as black text on white background.
+ * If you reload the page, the last letter typed is still displaying.`);
+ * }
+ *
+ * function draw() {
+ * textSize(40);
+ * background(255);
+ * text(myText, width / 2, height / 2);
+ * }
+ *
+ * function keyPressed() {
+ * myText = key;
+ * storeItem('myText', myText);
+ * }
+ *
+ */
+
+ _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 the value of an item that was stored in local storage
+ * using storeItem()
+ *
+ * @method getItem
+ * @for p5
+ * @param {String} key name that you wish to use to store in local storage
+ * @return {Number|Object|String|Boolean|p5.Color|p5.Vector} Value of stored item
+ *
+ * @example
+ *
+ * // Click the mouse to change
+ * // the color of the background
+ * // Once you have changed the color
+ * // it will stay changed even when you
+ * // reload the page.
+ *
+ * let myColor;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * myColor = getItem('myColor');
+ * }
+ *
+ * function draw() {
+ * if (myColor !== null) {
+ * background(myColor);
+ * }
+ * describe(`If you click, the canvas changes to a random color.·
+ * If you reload the page, the canvas is still the color it was when the
+ * page was previously loaded.`);
+ * }
+ *
+ * function mousePressed() {
+ * myColor = color(random(255), random(255), random(255));
+ * storeItem('myColor', myColor);
+ * }
+ *
+ */
+ _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;
+ };
+ /**
+ *
+ * Clears all local storage items set with storeItem()
+ * for the current domain.
+ *
+ * @method clearStorage
+ * @for p5
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * let myNum = 10;
+ * let myBool = false;
+ * storeItem('myNum', myNum);
+ * storeItem('myBool', myBool);
+ * print(getItem('myNum')); // logs 10 to the console
+ * print(getItem('myBool')); // logs false to the console
+ * clearStorage();
+ * print(getItem('myNum')); // logs null to the console
+ * print(getItem('myBool')); // logs null to the console
+ * }
+ *
+ */
+ _main.default.prototype.clearStorage = function () {
+ localStorage.clear();
+ };
+ /**
+ *
+ * Removes an item that was stored with storeItem()
+ *
+ * @method removeItem
+ * @param {String} key
+ * @for p5
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * let myVar = 10;
+ * storeItem('myVar', myVar);
+ * print(getItem('myVar')); // logs 10 to the console
+ * removeItem('myVar');
+ * print(getItem('myVar')); // logs null to the console
+ * }
+ *
+ */
+ _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': 290,
+ 'core-js/modules/es.array.from': 173,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.ends-with': 202,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 305: [
+ function (_dereq_, module, exports) {
+ 'use strict';
+ _dereq_('core-js/modules/es.array.concat');
+ _dereq_('core-js/modules/es.object.keys');
+ _dereq_('core-js/modules/es.string.sub');
+ _dereq_('core-js/modules/es.array.concat');
+ _dereq_('core-js/modules/es.object.keys');
+ _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
+ };
+ } /**
+ * @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 = function (key, value) {
+ 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
+ * }
+ *
+ */
+ _main.default.TypedDict.prototype.size = function () {
+ 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
+ * }
+ *
+ */
+ _main.default.TypedDict.prototype.hasKey = function (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
+ * }
+ *
+ */
+ _main.default.TypedDict.prototype.get = function (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
+ *
+ */
+ _main.default.TypedDict.prototype.set = function (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()
+ */
+ _main.default.TypedDict.prototype._addObj = function (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
+ *
+ */
+ _main.default.TypedDict.prototype.remove = function (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
+ *
+ */
+ _main.default.TypedDict.prototype.saveJSON = function (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
+ */
+ _main.default.TypedDict.prototype._validate = function (value) {
+ return true;
+ };
+ /**
+ *
+ * A simple Dictionary class for Strings.
+ *
+ * @class p5.StringDict
+ * @extends p5.TypedDict
+ */
+ _main.default.StringDict = function () {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+ _main.default.TypedDict.apply(this, args);
+ };
+ _main.default.StringDict.prototype = Object.create(_main.default.TypedDict.prototype);
+ _main.default.StringDict.prototype._validate = function (value) {
+ return typeof value === 'string';
+ };
+ /**
+ *
+ * A simple Dictionary class for Numbers.
+ *
+ * @class p5.NumberDict
+ * @constructor
+ * @extends p5.TypedDict
+ */
+ _main.default.NumberDict = function () {
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+ _main.default.TypedDict.apply(this, args);
+ };
+ _main.default.NumberDict.prototype = Object.create(_main.default.TypedDict.prototype);
+ /**
+ * private helper function to ensure that the user passed in valid
+ * values for the Dictionary type
+ */
+ _main.default.NumberDict.prototype._validate = function (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
+ *
+ *
+ */
+ _main.default.NumberDict.prototype.add = function (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
+ *
+ *
+ */
+ _main.default.NumberDict.prototype.sub = function (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
+ *
+ *
+ */
+ _main.default.NumberDict.prototype.mult = function (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
+ *
+ *
+ */
+ _main.default.NumberDict.prototype.div = function (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'
+ */
+ _main.default.NumberDict.prototype._valueTest = function (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);
+ * }
+ *
+ */
+ _main.default.NumberDict.prototype.minValue = function () {
+ 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);
+ * }
+ *
+ */
+ _main.default.NumberDict.prototype.maxValue = function () {
+ 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'
+ */
+ _main.default.NumberDict.prototype._keyTest = function (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);
+ * }
+ *
+ */
+ _main.default.NumberDict.prototype.minKey = function () {
+ 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);
+ * }
+ *
+ */
+ _main.default.NumberDict.prototype.maxKey = function () {
+ return this._keyTest( - 1);
+ };
+ var _default = _main.default.TypedDict;
+ exports.default = _default;
+ },
+ {
+ '../core/main': 290,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.object.keys': 194,
+ 'core-js/modules/es.string.sub': 210
+ }
+ ],
+ 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.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.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');
+ 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.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 _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);
+ } /**
+ * Searches the page for the first element that matches the given CSS selector string (can be an
+ * ID, class, tag name or a combination) and returns it as a p5.Element.
+ * The DOM node itself can be accessed with .elt.
+ * Returns null if none found. You can also specify a container to search within.
+ *
+ * @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
+ * HTML element to search within
+ * @return {p5.Element|null} p5.Element containing node found
+ * @example
+ *
+ * function setup() {
+ * createCanvas(50, 50);
+ * background(30);
+ * // move canvas down and right
+ * select('canvas').position(10, 30);
+ * }
+ *
+ *
+ *
+ * // select using ID
+ * let a = select('#container');
+ * let b = select('#beep', '#container');
+ * let c;
+ * if (a) {
+ * // select using class
+ * c = select('.boop', a);
+ * }
+ * // select using CSS selector string
+ * let d = select('#container #bleep');
+ * let e = select('#container p');
+ * [a, b, c, d, e]; // unused
+ *
+ */
+
+ _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 elements that match the given CSS selector string (can be an ID a class,
+ * tag name or a combination) and returns them as p5.Elements in
+ * an array.
+ * The DOM node itself can be accessed with .elt.
+ * Returns an empty array if none found.
+ * You can also specify a container to search within.
+ *
+ * @method selectAll
+ * @param {String} selectors CSS selector string of elements to search for
+ * @param {String|p5.Element|HTMLElement} [container] CSS selector string, p5.Element
+ * , or HTML element to search within
+ * @return {p5.Element[]} Array of p5.Elements containing nodes found
+ * @example
+ *
+ * function setup() {
+ * createButton('btn');
+ * createButton('2nd btn');
+ * createButton('3rd btn');
+ * let buttons = selectAll('button');
+ *
+ * for (let i = 0; i < 3; i++) {
+ * buttons[i].size(100);
+ * buttons[i].position(0, i * 30);
+ * }
+ * }
+ *
+ *
+ * // these are all valid calls to selectAll()
+ * let a = selectAll('.beep');
+ * a = selectAll('div');
+ * a = selectAll('button', '#container');
+ *
+ * let b = createDiv();
+ * b.id('container');
+ * let c = select('#container');
+ * a = selectAll('p', c);
+ * a = selectAll('#container p');
+ *
+ * let d = document.getElementById('container');
+ * a = selectAll('.boop', d);
+ * a = selectAll('#container .boop');
+ * console.log(a);
+ *
+ */
+ _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[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, except any canvas / graphics
+ * elements created by createCanvas or createGraphics.
+ * Event handlers are removed, and element is removed from the DOM.
+ * @method removeElements
+ * @example
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * background('grey');
+ * let div = createDiv('this is some text');
+ * let p = createP('this is a paragraph');
+ * div.style('font-size', '16px');
+ * p.style('font-size', '16px');
+ * }
+ * function mousePressed() {
+ * removeElements(); // this will remove the div and p, not canvas
+ * }
+ *
+ */
+ _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();
+ });
+ };
+ /**
+ * The .changed() function is called when the value of an
+ * element changes.
+ * This can be used to attach an element specific event listener.
+ *
+ * @method changed
+ * @param {Function|Boolean} fxn function to be fired when the value of
+ * an element changes.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * dropdown: pear, kiwi, grape. When selected text "it's a" + selection shown.
+ */
+ _main.default.Element.prototype.changed = function (fxn) {
+ _main.default.Element._adjustListener('change', fxn, this);
+ return this;
+ };
+ /**
+ * The .input() function is called when any user input is
+ * detected with an element. The input event is often used
+ * to detect keystrokes in a input element, or changes on a
+ * slider element. This can be used to attach an element specific
+ * event listener.
+ *
+ * @method input
+ * @param {Function|Boolean} fxn function to be fired when any user input is
+ * detected within the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * // Open your console to see the output
+ * function setup() {
+ * createCanvas(100, 100);
+ * background('grey');
+ * let inp = createInput('');
+ * inp.position(0, 0);
+ * inp.size(100);
+ * inp.input(myInputEvent);
+ * }
+ *
+ * function myInputEvent() {
+ * console.log('you are typing: ', this.value());
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _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 in the DOM with given inner HTML.
+ *
+ * @method createDiv
+ * @param {String} [html] inner HTML for element created
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * let div = createDiv('this is some text');
+ * div.style('font-size', '16px');
+ * div.position(10, 0);
+ *
+ */
+
+ _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 in the DOM with given inner HTML. Used
+ * for paragraph length text.
+ *
+ * @method createP
+ * @param {String} [html] inner HTML for element created
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * let p = createP('this is some text');
+ * p.style('font-size', '16px');
+ * p.position(10, 0);
+ *
+ */
+ _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 in the DOM with given inner HTML.
+ *
+ * @method createSpan
+ * @param {String} [html] inner HTML for element created
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * let span = createSpan('this is some text');
+ * span.position(0, 0);
+ *
+ */
+ _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 in the DOM with given src and
+ * alternate text.
+ *
+ * @method createImg
+ * @param {String} src src path or url for image
+ * @param {String} alt alternate text to be used if image does not load. You can use also an empty string (`""`) if that an image is not intended to be viewed.
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ */
+ /**
+ * @method createImg
+ * @param {String} src
+ * @param {String} alt
+ * @param {String} crossOrigin crossOrigin property of the `img` element; use either 'anonymous' or 'use-credentials' to retrieve the image with cross-origin access (for later use with `canvas`. if an empty string(`""`) is passed, CORS is not used
+ * @param {Function} [successCallback] callback to be called once image data is loaded with the p5.Element as argument
+ * @return {p5.Element} pointer to p5.Element holding created node
+ */
+ _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 in the DOM for including a hyperlink.
+ *
+ * @method createA
+ * @param {String} href url of page to link to
+ * @param {String} html inner html of link element to display
+ * @param {String} [target] target where new link should open,
+ * could be _blank, _self, _parent, _top.
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * let a = createA('http://p5js.org/', 'this is a link');
+ * a.position(0, 0);
+ *
+ */
+ _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 in the DOM.
+ * Use .size() to set the display length of the slider.
+ *
+ * @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] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value)
+ * @return {p5.Element} pointer to p5.Element holding the created node
+ * @example
+ *
+ * let slider;
+ * function setup() {
+ * slider = createSlider(0, 255, 100);
+ * slider.position(10, 10);
+ * slider.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * let val = slider.value();
+ * background(val);
+ * }
+ *
+ */
+ _main.default.prototype.createCheckbox = function () {
+ _main.default._validateParameters('createCheckbox', arguments); // 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[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 (arguments[0]) {
+ self.value(arguments[0]);
+ var span = document.createElement('span');
+ span.innerHTML = arguments[0];
+ label.appendChild(span);
+ } // Set the checked value of checkbox if passed
+
+ if (arguments[1]) {
+ checkbox.checked = true;
+ }
+ return self;
+ };
+ /**
+ * Creates a dropdown menu `<select></select>` element in the DOM.
+ * It also assigns select-related methods to p5.Element when selecting an existing select box. Options in the menu are unique by `name` (the display text).
+ * - `.option(name, [value])` can be used to add an option with `name` (the display text) and `value` to the select element. If an option with `name` already exists within the select element, this method will change its value to `value`.
+ * - `.value()` will return the currently selected option.
+ * - `.selected()` will return the current dropdown element which is an instance of p5.Element.
+ * - `.selected(value)` can be used to make given option selected by default when the page first loads.
+ * - `.disable()` marks the whole dropdown element as disabled.
+ * - `.disable(value)` marks a given option as disabled.
+ *
+ * @method createSelect
+ * @param {boolean} [multiple] true if dropdown should support multiple selections
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ */
+ /**
+ * @method createSelect
+ * @param {Object} existing DOM select element
+ * @return {p5.Element}
+ */
+ _main.default.prototype.createSelect = function () {
+ _main.default._validateParameters('createSelect', arguments);
+ var self;
+ var arg = arguments[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;
+ };
+ return self;
+ };
+ /**
+ * Creates a radio button element in the DOM. It also helps existing radio buttons
+ * assign methods of p5.Element.
+ * - `.option(value, [label])` can be used to create a new option for the
+ * element. If an option with a value already exists, it will be returned.
+ * It is recommended to use string values as input for `value`.
+ * Optionally, a label can be provided as second argument for the option.
+ * - `.remove(value)` can be used to remove an option for the element. String
+ * values recommended as input for `value`.
+ * - `.value()` method will return the currently selected value.
+ * - `.selected()` method will return the currently selected input element.
+ * - `.selected(value)` method will select the option and return it. String
+ * values recommended as input for `value`.
+ * - `.disable(Boolean)` method will enable/disable the whole radio button element.
+ *
+ * @method createRadio
+ * @param {Object} containerElement A container HTML Element, either a div
+ * or span, inside which all existing radio inputs will be considered as options.
+ * @param {string} [name] A name parameter for each Input Element.
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ */
+ /**
+ * @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 in the DOM of type 'file'.
+ * This allows users to select local files for use in a sketch.
+ *
+ * @method createFileInput
+ * @param {Function} callback callback function for when a file is loaded
+ * @param {Boolean} [multiple] optional, to allow multiple files to be selected
+ * @return {p5.Element} pointer to p5.Element holding created DOM element
+ * @example
+ *
+ */
+ _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 an HTML5 `<video>` element in the DOM for simple playback
+ * of audio/video. Shown by default, can be hidden with .hide()
+ * and drawn into canvas using image(). The first parameter
+ * can be either a single string path to a video file, or an array of string
+ * paths to different formats of the same video. This is useful for ensuring
+ * that your video can play across different browsers, as each supports
+ * different formats. See this
+ * page for further information about supported formats.
+ *
+ * @method createVideo
+ * @param {String|String[]} src path to a video file, or array of paths for
+ * supporting different browsers
+ * @param {Function} [callback] callback function to be called upon
+ * 'canplaythrough' event fire, that is, when the
+ * browser can play the media, and estimates that
+ * enough data has been loaded to play the media
+ * up to its end without having to stop for
+ * further buffering of content
+ * @return {p5.MediaElement} pointer to video p5.MediaElement
+ * @example
+ *
+ * let vid;
+ * function setup() {
+ * noCanvas();
+ *
+ * vid = createVideo(
+ * ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'],
+ * vidLoad
+ * );
+ *
+ * vid.size(100, 100);
+ * }
+ *
+ * // This function is called when the video loads
+ * function vidLoad() {
+ * vid.loop();
+ * vid.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 HTML5 `<audio>` element in the DOM for simple audio
+ * playback. The first parameter can be either a single string path to a
+ * audio file, or an array of string paths to different formats of the same
+ * audio. This is useful for ensuring that your audio can play across
+ * different browsers, as each supports different formats.
+ * See this
+ * page for further information about supported formats.
+ *
+ * @method createAudio
+ * @param {String|String[]} [src] path to an audio file, or array of paths
+ * for supporting different browsers
+ * @param {Function} [callback] callback function to be called upon
+ * 'canplaythrough' event fire, that is, when the
+ * browser can play the media, and estimates that
+ * enough data has been loaded to play the media
+ * up to its end without having to stop for
+ * further buffering of content
+ * @return {p5.MediaElement} pointer to audio p5.MediaElement
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * // here we set the element to autoplay
+ * // The element will play as soon
+ * // as it is able to do so.
+ * ele.autoplay(true);
+ * }
+ *
+ */
+ _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 new HTML5 `<video>` element that contains the audio/video feed
+ * from a webcam. The element is separate from the canvas and is displayed by
+ * default. The element can be hidden using .hide().
+ * The feed can be drawn onto the canvas using image().
+ * The loadedmetadata property can be used to detect when the element has fully
+ * loaded (see second example).
+ *
+ * More specific properties of the feed can be passing in a Constraints object.
+ * See the
+ * W3C spec for possible properties. Note that not all of these are supported
+ * by all browsers.
+ *
+ * Security note: A new browser security specification requires that
+ * getUserMedia, which is behind createCapture(),
+ * only works when you're running the code locally, or on HTTPS. Learn more
+ * here
+ * and here.
+ *
+ * @method createCapture
+ * @param {String|Constant|Object} type type of capture, either VIDEO or
+ * AUDIO if none specified, default both,
+ * or a Constraints object
+ * @param {Function} [callback] function to be called once
+ * stream has loaded
+ * @return {p5.Element} capture video p5.Element
+ * @example
+ *
+ */
+
+ _main.default.prototype.createCapture = function () {
+ _main.default._validateParameters('createCapture', arguments); // return if getUserMedia is not supported by 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 _iteratorNormalCompletion10 = true;
+ var _didIteratorError10 = false;
+ var _iteratorError10 = undefined;
+ try {
+ for (var _iterator10 = arguments[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
+ var arg = _step10.value;
+ if (arg === _main.default.prototype.VIDEO) useAudio = false;
+ else if (arg === _main.default.prototype.AUDIO) useVideo = false;
+ else if (_typeof(arg) === 'object') constraints = arg;
+ else if (typeof arg === 'function') callback = arg;
+ }
+ } catch (err) {
+ _didIteratorError10 = true;
+ _iteratorError10 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
+ _iterator10.return();
+ }
+ } finally {
+ if (_didIteratorError10) {
+ throw _iteratorError10;
+ }
+ }
+ }
+ if (!constraints) constraints = {
+ video: useVideo,
+ audio: useAudio
+ };
+ 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;
+ }
+ }, console.log);
+ 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;
+ } else {
+ videoEl.width = videoEl.elt.width = domElement.videoWidth;
+ videoEl.height = videoEl.elt.height = domElement.videoHeight;
+ }
+ videoEl.loadedmetadata = true;
+ if (callback) callback(domElement.srcObject);
+ });
+ return videoEl;
+ };
+ /**
+ * Creates element with given tag in the DOM with given content.
+ *
+ * @method createElement
+ * @param {String} tag tag for the new element
+ * @param {String} [content] html content to be inserted into the element
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * let h5 = createElement('h5', 'im an h5 p5.element!');
+ * h5.style('color', '#00a1d3');
+ * h5.position(0, 0);
+ *
+ */
+ _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 specified class to the element.
+ *
+ * @for p5.Element
+ * @method addClass
+ * @param {String} class name of class to add
+ * @chainable
+ * @example
+ *
+ * let div = createDiv('div');
+ * div.addClass('myClass');
+ *
+ */
+ _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 specified 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() {
+ * div = createDiv('div');
+ * div.addClass('myClass');
+ * }
+ *
+ * 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 specified class is already applied to element.
+ *
+ * @method hasClass
+ * @returns {boolean} a boolean value if element has specified class
+ * @param c {String} class name of class to check
+ * @example
+ *
+ */
+ _main.default.Element.prototype.hasClass = function (c) {
+ return this.elt.classList.contains(c);
+ };
+ /**
+ *
+ * Toggles element class.
+ *
+ * @method toggleClass
+ * @param c {String} class name to toggle
+ * @chainable
+ * @example
+ *
+ * let div;
+ *
+ * function setup() {
+ * div = createDiv('div');
+ * div.addClass('show');
+ * }
+ *
+ * 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 to the parent specified.
+ * Accepts either a string ID, DOM node, or p5.Element.
+ * If no argument is specified, an array of children DOM nodes is returned.
+ *
+ * @method child
+ * @returns {Node[]} an array of child nodes
+ * @example
+ *
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
+ * div0.child(div1); // use p5.Element
+ *
+ *
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
+ * div1.id('apples');
+ * div0.child('apples'); // use id
+ *
+ *
+ * // this example assumes there is a div already on the page
+ * // with id "myChildDiv"
+ * let div0 = createDiv('this is the parent');
+ * let elt = document.getElementById('myChildDiv');
+ * div0.child(elt); // use element from page
+ *
+ */
+ /**
+ * @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 a p5.Element either vertically, horizontally,
+ * or both, relative to its parent or according to
+ * the body if the p5.Element has no parent. If no argument is passed
+ * the p5.Element is aligned both vertically and horizontally.
+ *
+ * @method center
+ * @param {String} [align] passing 'vertical', 'horizontal' aligns element accordingly
+ * @chainable
+ *
+ * @example
+ *
+ * function setup() {
+ * let div = createDiv('').size(10, 10);
+ * div.style('background-color', 'orange');
+ * div.center();
+ * }
+ *
+ */
+ _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;
+ };
+ /**
+ *
+ * If an argument is given, sets the inner HTML of the element,
+ * replacing any existing HTML. If true is included as a second
+ * argument, HTML is appended instead of replacing existing HTML.
+ * If no arguments are given, returns
+ * the inner HTML of the element.
+ *
+ * @for p5.Element
+ * @method html
+ * @returns {String} the inner HTML of the element
+ * @example
+ *
+ * let div = createDiv('').size(100, 100);
+ * div.html('hi');
+ *
+ *
+ * let div = createDiv('Hello ').size(100, 100);
+ * div.html('World', true);
+ *
+ */
+ /**
+ * @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[1]) {
+ this.elt.insertAdjacentHTML('beforeend', arguments[0]);
+ return this;
+ } else {
+ this.elt.innerHTML = arguments[0];
+ return this;
+ }
+ };
+ /**
+ *
+ * Sets the position of the element. If no position type argument is given, the
+ * position will be relative to (0, 0) of the window.
+ * Essentially, this sets position:absolute and left and top
+ * properties of style. If an optional third argument specifying position type is given,
+ * the x and y-coordinates will be interpreted based on the positioning scheme.
+ * If no arguments given, the function returns the x and y position of the element.
+ *
+ * found documentation on how to be more specific with object type
+ * https://stackoverflow.com/questions/14714314/how-do-i-comment-object-literals-in-yuidoc
+ *
+ * @method position
+ * @returns {Object} object of form { x: 0, y: 0 } containing the position of the element in an object
+ * @example
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // positions canvas 50px to the right and 100px
+ * // below upper left corner of the window
+ * cnv.position(50, 100);
+ * }
+ *
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // positions canvas at upper left corner of the window
+ * // with a 'fixed' position type
+ * cnv.position(0, 0, 'fixed');
+ * }
+ *
+ */
+ /**
+ * @method position
+ * @param {Number} [x] x-position relative to upper left of window (optional)
+ * @param {Number} [y] y-position relative to upper 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[2] === 'static' || arguments[2] === 'fixed' || arguments[2] === 'relative' || arguments[2] === 'sticky' || arguments[2] === 'initial' || arguments[2] === 'inherit') {
+ positionType = arguments[2];
+ }
+ this.elt.style.position = positionType;
+ this.elt.style.left = arguments[0] + 'px';
+ this.elt.style.top = arguments[1] + 'px';
+ this.x = arguments[0];
+ this.y = 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[0] + 'px, ' + arguments[1] + 'px)';
+ } else if (arguments.length > 2) {
+ this.elt.style.transform = 'translate3d(' + arguments[0] + 'px,' + arguments[1] + 'px,' + arguments[2] + 'px)';
+ if (arguments.length === 3) {
+ this.elt.parentElement.style.perspective = '1000px';
+ } else {
+ this.elt.parentElement.style.perspective = 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[0] + 'deg)';
+ } else if (arguments.length === 2) {
+ this.elt.style.transform = 'rotate(' + arguments[0] + 'deg, ' + arguments[1] + 'deg)';
+ } else if (arguments.length === 3) {
+ this.elt.style.transform = 'rotateX(' + arguments[0] + 'deg)';
+ this.elt.style.transform += 'rotateY(' + arguments[1] + 'deg)';
+ this.elt.style.transform += 'rotateZ(' + arguments[2] + 'deg)';
+ } // add remaining transform back on
+
+ this.elt.style.transform += transform;
+ return this;
+ };
+ /**
+ * Sets the given style (CSS) property (1st arg) of the element with the
+ * given value (2nd arg). If a single argument is given, .style()
+ * returns the value of the given property; however, if a single argument
+ * is given in CSS syntax ('text-align:center'), .style() sets the CSS
+ * appropriately.
+ *
+ * @method style
+ * @param {String} property property to be set
+ * @returns {String} value of property
+ * @example
+ *
+ */
+ /**
+ * @method style
+ * @param {String} property
+ * @param {String|p5.Color} value value to assign to property
+ * @return {String} current value of property, if no value is given as second argument
+ * @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 a new attribute or changes the value of an existing attribute
+ * on the specified element. If no value is specified, returns the
+ * value of the given attribute, or null if the attribute is not set.
+ *
+ * @method attribute
+ * @return {String} value of attribute
+ *
+ * @example
+ *
+ * let myDiv = createDiv('I like pandas.');
+ * myDiv.attribute('align', 'center');
+ *
+ */
+ /**
+ * @method attribute
+ * @param {String} attr attribute to set
+ * @param {String} value value to assign to 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 on the specified element.
+ *
+ * @method removeAttribute
+ * @param {String} attr attribute to remove
+ * @chainable
+ *
+ * @example
+ *
+ */
+ _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;
+ };
+ /**
+ * Either returns the value of the element if no arguments
+ * given, or sets the value of the element.
+ *
+ * @method value
+ * @return {String|Number} value of the element
+ * @example
+ *
+ * // gets the value
+ * let inp;
+ * function setup() {
+ * inp = createInput('');
+ * }
+ *
+ * function mousePressed() {
+ * print(inp.value());
+ * }
+ *
+ *
+ * // sets the value
+ * let inp;
+ * function setup() {
+ * inp = createInput('myValue');
+ * }
+ *
+ * function mousePressed() {
+ * inp.value('myValue');
+ * }
+ *
+ */
+ /**
+ * @method value
+ * @param {String|Number} value
+ * @chainable
+ */
+ _main.default.Element.prototype.value = function () {
+ if (arguments.length > 0) {
+ this.elt.value = arguments[0];
+ return this;
+ } else {
+ if (this.elt.type === 'range') {
+ return parseFloat(this.elt.value);
+ } else return this.elt.value;
+ }
+ };
+ /**
+ *
+ * Shows the current element. Essentially, setting display:block for the style.
+ *
+ * @method show
+ * @chainable
+ * @example
+ *
+ * let div = createDiv('div');
+ * div.style('display', 'none');
+ * div.show(); // turns display to block
+ *
+ */
+ _main.default.Element.prototype.show = function () {
+ this.elt.style.display = 'block';
+ return this;
+ };
+ /**
+ * Hides the current element. Essentially, setting display:none for the style.
+ *
+ * @method hide
+ * @chainable
+ * @example
+ *
+ * let div = createDiv('this is a div');
+ * div.hide();
+ *
+ */
+ _main.default.Element.prototype.hide = function () {
+ this.elt.style.display = 'none';
+ return this;
+ };
+ /**
+ *
+ * Sets the width and height of the element. AUTO can be used to
+ * only adjust one dimension at a time. If no arguments are given, it
+ * returns the width and height of the element in an Object. In the case of
+ * elements that need to be loaded, such as images, it is recommended
+ * to call the function after the element has finished loading.
+ *
+ * @method size
+ * @return {Object} the width and height of the element in an object
+ * @example
+ *
+ * let div = createDiv('this is a div');
+ * div.size(100, 100);
+ * let img = createImg(
+ * 'assets/rockies.jpg',
+ * 'A tall mountain with a small forest and field in front of it on a sunny day',
+ * '',
+ * () => {
+ * img.size(10, 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 = this.elt.offsetWidth;
+ this.height = this.elt.offsetHeight;
+ if (this._pInst && this._pInst._curElement) {
+ // main canvas associated with p5 instance
+ if (this._pInst._curElement.elt === this.elt) {
+ this._pInst._setProperty('width', this.elt.offsetWidth);
+ this._pInst._setProperty('height', this.elt.offsetHeight);
+ }
+ }
+ }
+ return this;
+ }
+ };
+ /**
+ * Removes the element, stops all media streams, and deregisters all listeners.
+ * @method remove
+ * @example
+ *
+ * let myDiv = createDiv('this is some text');
+ * myDiv.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);
+ }
+ };
+ /**
+ * Registers a callback that gets called every time a file that is
+ * dropped on the element has been loaded.
+ * p5 will load every dropped file into memory and pass it as a p5.File object to the callback.
+ * Multiple files dropped at the same time will result in multiple calls to the callback.
+ *
+ * You can optionally pass a second callback which will be registered to the raw
+ * drop event.
+ * The callback will thus be provided the original
+ * DragEvent.
+ * Dropping multiple files at the same time will trigger the second callback once per drop,
+ * whereas the first callback will trigger for each loaded file.
+ *
+ * @method drop
+ * @param {Function} callback callback to receive loaded file, called for each file dropped.
+ * @param {Function} [fxn] callback triggered once when files are dropped with the drop event.
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Canvas turns into whatever image is dragged/dropped onto it.
+ */
+ _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
+ for (var i = 0; i < files.length; i++) {
+ var f = files[i];
+ _main.default.File._load(f, callback);
+ }
+ }, this);
+ } else {
+ console.log('The File APIs are not fully supported in this browser.');
+ }
+ return this;
+ }; // =============================================================================
+ // p5.MediaElement additions
+ // =============================================================================
+ /**
+ * Extends p5.Element to handle audio and video. In addition to the methods
+ * of p5.Element, it also contains methods for controlling media. It is not
+ * called directly, but p5.MediaElements are created by calling createVideo,
+ * createAudio, and createCapture.
+ *
+ * @class p5.MediaElement
+ * @constructor
+ * @param {String} elt DOM node that is wrapped
+ */
+ _main.default.MediaElement = function (elt, pInst) {
+ _main.default.Element.call(this, elt, pInst);
+ var self = this;
+ this.elt.crossOrigin = 'anonymous';
+ this._prevTime = 0;
+ this._cueIDCounter = 0;
+ this._cues = [
+ ];
+ this._pixelsState = this;
+ this._pixelDensity = 1;
+ this._modified = false;
+ /**
+ * Path to the media element source.
+ *
+ * @property src
+ * @return {String} src
+ * @example
+ *
+ * let ele;
+ *
+ * function setup() {
+ * background(250);
+ *
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * //We'll set up our example so that
+ * //when you click on the text,
+ * //an alert box displays the MediaElement's
+ * //src field.
+ * textAlign(CENTER);
+ * text('Click Me!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * //Show our p5.MediaElement's src field
+ * alert(ele.src);
+ * }
+ * }
+ *
+ */
+ 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);
+ };
+ };
+ _main.default.MediaElement.prototype = Object.create(_main.default.Element.prototype);
+ /**
+ * Play an HTML5 media element.
+ *
+ * @method play
+ * @chainable
+ * @example
+ *
+ * let ele;
+ *
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to Play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * //Here we call the play() function on
+ * //the p5.MediaElement we created above.
+ * //This will start the audio sample.
+ * ele.play();
+ *
+ * background(200);
+ * text('You clicked Play!', width / 2, height / 2);
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.play = function () {
+ var _this = 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(_this.src);
+ } else {
+ console.error(e);
+ }
+ } else {
+ // any other kind of error
+ console.error('Media play method encountered an unexpected error', e);
+ }
+ });
+ }
+ return this;
+ };
+ /**
+ * Stops an HTML5 media element (sets current time to zero).
+ *
+ * @method stop
+ * @chainable
+ * @example
+ *
+ * //This example both starts
+ * //and stops a sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * //if the sample is currently playing
+ * //calling the stop() function on
+ * //our p5.MediaElement will stop
+ * //it and reset its current
+ * //time to 0 (i.e. it will start
+ * //at the beginning the next time
+ * //you play it)
+ * ele.stop();
+ *
+ * sampleIsPlaying = false;
+ * text('Click to play!', width / 2, height / 2);
+ * } else {
+ * //loop our sound element until we
+ * //call ele.stop() on it.
+ * ele.loop();
+ *
+ * sampleIsPlaying = true;
+ * text('Click to stop!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ * //This example both starts
+ * //and pauses a sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * //Calling pause() on our
+ * //p5.MediaElement will stop it
+ * //playing, but when we call the
+ * //loop() or play() functions
+ * //the sample will start from
+ * //where we paused it.
+ * ele.pause();
+ *
+ * sampleIsPlaying = false;
+ * text('Click to resume!', width / 2, height / 2);
+ * } else {
+ * //loop our sound element until we
+ * //call ele.pause() on it.
+ * ele.loop();
+ *
+ * sampleIsPlaying = true;
+ * text('Click to pause!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.pause = function () {
+ this.elt.pause();
+ return this;
+ };
+ /**
+ * Set 'loop' to true for an HTML5 media element, and starts playing.
+ *
+ * @method loop
+ * @chainable
+ * @example
+ *
+ * //Clicking the canvas will loop
+ * //the audio sample until the user
+ * //clicks again to stop it
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsLooping = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to loop!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (!sampleIsLooping) {
+ * //loop our sound element until we
+ * //call ele.stop() on it.
+ * ele.loop();
+ *
+ * sampleIsLooping = true;
+ * text('Click to stop!', width / 2, height / 2);
+ * } else {
+ * ele.stop();
+ *
+ * sampleIsLooping = false;
+ * text('Click to loop!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.loop = function () {
+ this.elt.setAttribute('loop', true);
+ this.play();
+ return this;
+ };
+ /**
+ * Set 'loop' to false for an HTML5 media element. Element will stop
+ * when it reaches the end.
+ *
+ * @method noLoop
+ * @chainable
+ * @example
+ *
+ * //This example both starts
+ * //and stops loop of sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * ele.noLoop();
+ * sampleIsPlaying = false;
+ * text('No more Loops!', width / 2, height / 2);
+ * } else {
+ * ele.loop();
+ * sampleIsPlaying = true;
+ * text('Click to stop looping!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.noLoop = function () {
+ this.elt.removeAttribute('loop');
+ return this;
+ };
+ /**
+ * Sets up logic to check that autoplay succeeded.
+ *
+ * @method setupAutoplayFailDetection
+ * @private
+ */
+ _main.default.MediaElement.prototype._setupAutoplayFailDetection = function () {
+ var _this2 = this;
+ var timeout = setTimeout(function () {
+ if (typeof IS_MINIFIED === 'undefined') {
+ _main.default._friendlyAutoplayError(_this2.src);
+ } else {
+ console.error(e);
+ }
+ }, 500);
+ this.elt.addEventListener('play', function () {
+ return clearTimeout(timeout);
+ }, {
+ passive: true,
+ once: true
+ });
+ };
+ /**
+ * Set HTML5 media element to autoplay or not. If no argument is specified, by
+ * default it will autoplay.
+ *
+ * @method autoplay
+ * @param {Boolean} shouldAutoplay whether the element should autoplay
+ * @chainable
+ * @example
+ *
+ * let videoElement;
+ * function setup() {
+ * noCanvas();
+ * videoElement = createVideo(['assets/small.mp4'], onVideoLoad);
+ * }
+ * function onVideoLoad() {
+ * // The media will play as soon as it is loaded.
+ * videoElement.autoplay();
+ * videoElement.volume(0);
+ * videoElement.size(100, 100);
+ * }
+ *
+ *
+ *
+ * let videoElement;
+ * function setup() {
+ * noCanvas();
+ * videoElement = createVideo(['assets/small.mp4'], onVideoLoad);
+ * }
+ * function onVideoLoad() {
+ * // The media will not play until some explicitly triggered.
+ * videoElement.autoplay(false);
+ * videoElement.volume(0);
+ * videoElement.size(100, 100);
+ * }
+ *
+ * function mouseClicked() {
+ * videoElement.play();
+ * }
+ *
+ *
+ * @alt
+ * An example of a video element which autoplays after it is loaded.
+ * An example of a video element which waits for a trigger for playing.
+ */
+ _main.default.MediaElement.prototype.autoplay = function (val) {
+ var _this3 = 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 _this3._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 volume for this HTML5 media element. If no argument is given,
+ * returns the current volume.
+ *
+ * @method volume
+ * @return {Number} current volume
+ *
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * // p5.MediaElement objects are usually created
+ * // by calling the createAudio(), createVideo(),
+ * // and createCapture() functions.
+ * // In this example we create
+ * // a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to Play!', width / 2, height / 2);
+ * }
+ * function mouseClicked() {
+ * // Here we call the volume() function
+ * // on the sound element to set its volume
+ * // Volume must be between 0.0 and 1.0
+ * ele.volume(0.2);
+ * ele.play();
+ * background(200);
+ * text('You clicked Play!', width / 2, height / 2);
+ * }
+ *
+ */
+ /**
+ * @method volume
+ * @param {Number} val volume between 0.0 and 1.0
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.volume = function (val) {
+ if (typeof val === 'undefined') {
+ return this.elt.volume;
+ } else {
+ this.elt.volume = val;
+ }
+ };
+ /**
+ * If no arguments are given, returns the current playback speed of the
+ * element. The speed parameter sets the speed where 2.0 will play the
+ * element twice as fast, 0.5 will play at half the speed, and -1 will play
+ * the element in normal speed in reverse.(Note that not all browsers support
+ * backward playback and even if they do, playback might not be smooth.)
+ *
+ * @method speed
+ * @return {Number} current playback speed of the element
+ *
+ * @example
+ *
+ * //Clicking the canvas will loop
+ * //the audio sample until the user
+ * //clicks again to stop it
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ * let button;
+ *
+ * function setup() {
+ * createCanvas(710, 400);
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * ele.loop();
+ * background(200);
+ *
+ * button = createButton('2x speed');
+ * button.position(100, 68);
+ * button.mousePressed(twice_speed);
+ *
+ * button = createButton('half speed');
+ * button.position(200, 68);
+ * button.mousePressed(half_speed);
+ *
+ * button = createButton('reverse play');
+ * button.position(300, 68);
+ * button.mousePressed(reverse_speed);
+ *
+ * button = createButton('STOP');
+ * button.position(400, 68);
+ * button.mousePressed(stop_song);
+ *
+ * button = createButton('PLAY!');
+ * button.position(500, 68);
+ * button.mousePressed(play_speed);
+ * }
+ *
+ * function twice_speed() {
+ * ele.speed(2);
+ * }
+ *
+ * function half_speed() {
+ * ele.speed(0.5);
+ * }
+ *
+ * function reverse_speed() {
+ * ele.speed(-1);
+ * }
+ *
+ * function stop_song() {
+ * ele.stop();
+ * }
+ *
+ * function play_speed() {
+ * ele.play();
+ * }
+ *
+ */
+ /**
+ * @method speed
+ * @param {Number} speed speed multiplier for element playback
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.speed = function (val) {
+ if (typeof val === 'undefined') {
+ return this.presetPlaybackRate || this.elt.playbackRate;
+ } else {
+ if (this.loadedmetadata) {
+ this.elt.playbackRate = val;
+ } else {
+ this.presetPlaybackRate = val;
+ }
+ }
+ };
+ /**
+ * If no arguments are given, returns the current time of the element.
+ * If an argument is given the current time of the element is set to it.
+ *
+ * @method time
+ * @return {Number} current time (in seconds)
+ *
+ * @example
+ *
+ * let ele;
+ * let beginning = true;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('start at beginning', width / 2, height / 2);
+ * }
+ *
+ * // this function fires with click anywhere
+ * function mousePressed() {
+ * if (beginning === true) {
+ * // here we start the sound at the beginning
+ * // time(0) is not necessary here
+ * // as this produces the same result as
+ * // play()
+ * ele.play().time(0);
+ * background(200);
+ * text('jump 2 sec in', width / 2, height / 2);
+ * beginning = false;
+ * } else {
+ * // here we jump 2 seconds into the sound
+ * ele.play().time(2);
+ * background(250);
+ * text('start at beginning', width / 2, height / 2);
+ * beginning = true;
+ * }
+ * }
+ *
+ */
+ /**
+ * @method time
+ * @param {Number} time time to jump to (in seconds)
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.time = function (val) {
+ if (typeof val === 'undefined') {
+ return this.elt.currentTime;
+ } else {
+ this.elt.currentTime = val;
+ return this;
+ }
+ };
+ /**
+ * Returns the duration of the HTML5 media element.
+ *
+ * @method duration
+ * @return {Number} duration
+ *
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/doorbell.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to know the duration!', 10, 25, 70, 80);
+ * }
+ * function mouseClicked() {
+ * ele.play();
+ * background(200);
+ * //ele.duration dislpays the duration
+ * text(ele.duration() + ' seconds', width / 2, height / 2);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.duration = function () {
+ return this.elt.duration;
+ };
+ _main.default.MediaElement.prototype.pixels = [
+ ];
+ _main.default.MediaElement.prototype._ensureCanvas = function () {
+ if (!this.canvas) {
+ this.canvas = document.createElement('canvas');
+ this.drawingContext = this.canvas.getContext('2d');
+ this.setModified(true);
+ }
+ if (this.loadedmetadata) {
+ // 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.drawImage(this.elt, 0, 0, this.canvas.width, this.canvas.height);
+ this.setModified(true);
+ }
+ };
+ _main.default.MediaElement.prototype.loadPixels = function () {
+ this._ensureCanvas();
+ return _main.default.Renderer2D.prototype.loadPixels.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype.updatePixels = function (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;
+ };
+ _main.default.MediaElement.prototype.get = function () {
+ this._ensureCanvas();
+ return _main.default.Renderer2D.prototype.get.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype._getPixel = function () {
+ this.loadPixels();
+ return _main.default.Renderer2D.prototype._getPixel.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype.set = function (x, y, imgOrCol) {
+ if (this.loadedmetadata) {
+ // wait for metadata
+ this._ensureCanvas();
+ _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol);
+ this.setModified(true);
+ }
+ };
+ _main.default.MediaElement.prototype.copy = function () {
+ this._ensureCanvas();
+ _main.default.prototype.copy.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype.mask = function () {
+ this.loadPixels();
+ this.setModified(true);
+ _main.default.Image.prototype.mask.apply(this, arguments);
+ };
+ /**
+ * 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.
+ */
+ _main.default.MediaElement.prototype.isModified = function () {
+ 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
+ */
+ _main.default.MediaElement.prototype.setModified = function (value) {
+ this._modified = value;
+ };
+ /**
+ * Schedule an event to be called when the audio or video
+ * element reaches the end. If the element is looping,
+ * this will not be called. The element is passed in
+ * as the argument to the onended callback.
+ *
+ * @method onended
+ * @param {Function} callback function to call when the
+ * soundfile has ended. The
+ * media element will be passed
+ * in as the argument to the
+ * callback.
+ * @chainable
+ * @example
+ *
+ * function setup() {
+ * let audioEl = createAudio('assets/beat.mp3');
+ * audioEl.showControls();
+ * audioEl.onended(sayDone);
+ * }
+ *
+ * function sayDone(elt) {
+ * alert('done playing ' + elt.src);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.onended = function (callback) {
+ this._onended = callback;
+ return this;
+ };
+ /*** CONNECT TO WEB AUDIO API / p5.sound.js ***/
+ /**
+ * Send the audio output of this element to a specified audioNode or
+ * p5.sound object. If no element is provided, connects to p5's main
+ * output. That connection is established when this method is first called.
+ * All connections are removed by the .disconnect() method.
+ *
+ * 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
+ */
+ _main.default.MediaElement.prototype.connect = function (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 main output.
+ * This is useful if you want to re-route the output through
+ * audio effects, for example.
+ *
+ * @method disconnect
+ */
+ _main.default.MediaElement.prototype.disconnect = function () {
+ if (this.audioSourceNode) {
+ this.audioSourceNode.disconnect();
+ } else {
+ throw 'nothing to disconnect';
+ }
+ };
+ /*** SHOW / HIDE CONTROLS ***/
+ /**
+ * Show the default MediaElement controls, as determined by the web browser.
+ *
+ * @method showControls
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio()
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to Show Controls!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * ele.showControls();
+ * background(200);
+ * text('Controls Shown', width / 2, height / 2);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.showControls = function () {
+ // must set style for the element to show on the page
+ this.elt.style['text-align'] = 'inherit';
+ this.elt.controls = true;
+ };
+ /**
+ * Hide the default mediaElement controls.
+ * @method hideControls
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio()
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * ele.showControls();
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to hide Controls!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * ele.hideControls();
+ * background(200);
+ * text('Controls hidden', width / 2, height / 2);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.hideControls = function () {
+ this.elt.controls = false;
+ };
+ /*** SCHEDULE EVENTS ***/
+ // Cue inspired by JavaScript setTimeout, and the
+ // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org
+ var Cue = function Cue(callback, time, id, val) {
+ this.callback = callback;
+ this.time = time;
+ this.id = id;
+ this.val = val;
+ };
+ /**
+ * Schedule events to trigger every time a MediaElement
+ * (audio/video) reaches a playback cue point.
+ *
+ * Accepts a callback function, a time (in seconds) at which to trigger
+ * the callback, and an optional parameter for the callback.
+ *
+ * Time will be passed as the first parameter to the callback function,
+ * and param will be the second parameter.
+ *
+ * @method addCue
+ * @param {Number} time Time in seconds, relative to this media
+ * element's playback. For example, to trigger
+ * an event every time playback reaches two
+ * seconds, pass in the number 2. This will be
+ * passed as the first parameter to
+ * the callback function.
+ * @param {Function} callback Name of a function that will be
+ * called at the given time. The callback will
+ * receive time and (optionally) param as its
+ * two parameters.
+ * @param {Object} [value] An object to be passed as the
+ * second parameter to the
+ * callback function.
+ * @return {Number} id ID of this cue,
+ * useful for removeCue(id)
+ * @example
+ *
+ */
+ _main.default.MediaElement.prototype.addCue = function (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;
+ };
+ /**
+ * Remove a callback based on its ID. The ID is returned by the
+ * addCue method.
+ * @method removeCue
+ * @param {Number} id ID of the cue, as returned by addCue
+ * @example
+ *
+ */
+ _main.default.MediaElement.prototype.removeCue = function (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;
+ }
+ };
+ /**
+ * Remove all of the callbacks that had originally been scheduled
+ * via the addCue method.
+ * @method clearCues
+ * @param {Number} id ID of the cue, as returned by addCue
+ * @example
+ *
+ * let audioEl;
+ * function setup() {
+ * background(255, 255, 255);
+ * audioEl = createAudio('assets/beat.mp3');
+ * //Show the default MediaElement controls, as determined by the web browser
+ * audioEl.showControls();
+ * // schedule calls to changeBackground
+ * background(200);
+ * text('Click to change Cue!', 10, 25, 70, 80);
+ * audioEl.addCue(0.5, changeBackground, color(255, 0, 0));
+ * audioEl.addCue(1.0, changeBackground, color(0, 255, 0));
+ * audioEl.addCue(2.5, changeBackground, color(0, 0, 255));
+ * audioEl.addCue(3.0, changeBackground, color(0, 255, 255));
+ * audioEl.addCue(4.2, changeBackground, color(255, 255, 0));
+ * }
+ * function mousePressed() {
+ * // here we clear the scheduled callbacks
+ * audioEl.clearCues();
+ * // then we add some more callbacks
+ * audioEl.addCue(1, changeBackground, color(2, 2, 2));
+ * audioEl.addCue(3, changeBackground, color(255, 255, 0));
+ * }
+ * function changeBackground(val) {
+ * background(val);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.clearCues = function () {
+ this._cues = [
+ ];
+ this.elt.ontimeupdate = null;
+ }; // private method that checks for cues to be fired if events
+ // have been scheduled using addCue(callback, time).
+ _main.default.MediaElement.prototype._onTimeUpdate = function () {
+ 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;
+ };
+ /**
+ * Base class for a file.
+ * Used for Element.drop and createFileInput.
+ *
+ * @class p5.File
+ * @constructor
+ * @param {File} file File that is wrapped
+ */
+ _main.default.File = function (file, pInst) {
+ /**
+ * Underlying File object. All normal File methods can be called on this.
+ *
+ * @property file
+ */
+ 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('/');
+ /**
+ * File type (image, text, etc.)
+ *
+ * @property type
+ */
+ this.type = typeList[0];
+ /**
+ * File subtype (usually the file extension jpg, png, xml, etc.)
+ *
+ * @property subtype
+ */
+ this.subtype = typeList[1];
+ /**
+ * File name
+ *
+ * @property name
+ */
+ this.name = file.name;
+ /**
+ * File size
+ *
+ * @property size
+ */
+ this.size = file.size;
+ /**
+ * URL string containing either image data, the text contents of the file or
+ * a parsed object if file is JSON and p5.XML if XML
+ *
+ * @property data
+ */
+ this.data = undefined;
+ };
+ _main.default.File._createLoader = function (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;
+ };
+ _main.default.File._load = function (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);
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/main': 290,
+ 'core-js/modules/es.array.every': 169,
+ 'core-js/modules/es.array.filter': 171,
+ 'core-js/modules/es.array.for-each': 172,
+ 'core-js/modules/es.array.from': 173,
+ 'core-js/modules/es.array.index-of': 175,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.map': 179,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.array.splice': 182,
+ 'core-js/modules/es.function.name': 183,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.promise': 196,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.replace': 207,
+ 'core-js/modules/es.string.split': 209,
+ 'core-js/modules/es.string.trim': 211,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/web.dom-collections.for-each': 247,
+ 'core-js/modules/web.dom-collections.iterator': 248,
+ 'core-js/modules/web.url': 250
+ }
+ ],
+ 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.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 Acceleration
+ * @for p5
+ * @requires core
+ */
+ /**
+ * 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();
+ if (this._angleMode === constants.radians) {
+ e.beta = e.beta * (_PI / 180);
+ e.gamma = e.gamma * (_PI / 180);
+ e.alpha = e.alpha * (_PI / 180);
+ }
+ this._setProperty('rotationX', e.beta);
+ this._setProperty('rotationY', e.gamma);
+ this._setProperty('rotationZ', 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.
+ var wRX = this.rotationX + 180;
+ var wPRX = 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.rotationY + 180;
+ var wPRY = 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.
+ if (this.rotationZ - this.pRotationZ > 0 && this.rotationZ - this.pRotationZ < 270 || this.rotationZ - this.pRotationZ < - 270) {
+ rotateDirectionZ = 'clockwise';
+ } else if (this.rotationZ - this.pRotationZ < 0 || this.rotationZ - this.pRotationZ > 270) {
+ rotateDirectionZ = 'counter-clockwise';
+ }
+ if (rotateDirectionZ !== this.pRotateDirectionZ) {
+ startAngleZ = this.rotationZ;
+ }
+ if (Math.abs(this.rotationZ - startAngleZ) > 90 && Math.abs(this.rotationZ - startAngleZ) < 270) {
+ startAngleZ = this.rotationZ;
+ 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/constants': 278,
+ '../core/main': 290,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 308: [
+ 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
+ */
+ /**
+ * The boolean system variable keyIsPressed is true if any key is pressed
+ * and false if no keys are pressed.
+ *
+ * @property {Boolean} keyIsPressed
+ * @readOnly
+ * @example
+ *
+ *
+ * function draw() {
+ * if (keyIsPressed === true) {
+ * fill(0);
+ * } else {
+ * fill(255);
+ * }
+ * rect(25, 25, 50, 50);
+ * describe('50-by-50 white rect that turns black on keypress.');
+ * }
+ *
+ *
+ */
+
+ _main.default.prototype.isKeyPressed = false;
+ _main.default.prototype.keyIsPressed = false; // khan
+ /**
+ * The system variable key always contains the value of the most recent
+ * key on the keyboard that was typed. To get the proper capitalization, it
+ * is best to use it within keyTyped(). For non-ASCII keys, use the keyCode
+ * variable.
+ *
+ * @property {String} key
+ * @readOnly
+ * @example
+ *
+ * // Click any key to display it!
+ * // (Not Guaranteed to be Case Sensitive)
+ * function setup() {
+ * fill(245, 123, 158);
+ * textSize(50);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * text(key, 33, 65); // Display last key pressed.
+ * describe('canvas displays any key value that is pressed in pink font.');
+ * }
+ *
+ */
+ _main.default.prototype.key = '';
+ /**
+ * The variable keyCode is used to detect special keys such as BACKSPACE,
+ * DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,
+ * DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
+ * You can also check for custom keys by looking up the keyCode of any key
+ * on a site like this: keycode.info.
+ *
+ * @property {Integer} keyCode
+ * @readOnly
+ * @example
+ *
+ * let fillVal = 126;
+ * function draw() {
+ * fill(fillVal);
+ * rect(25, 25, 50, 50);
+ * describe(`Grey rect center. turns white when up arrow pressed and black when down.
+ * Display key pressed and its keyCode in a yellow box.`);
+ * }
+ *
+ * function keyPressed() {
+ * if (keyCode === UP_ARROW) {
+ * fillVal = 255;
+ * } else if (keyCode === DOWN_ARROW) {
+ * fillVal = 0;
+ * }
+ * }
+ *
+ */
+ _main.default.prototype.keyCode = 0;
+ /**
+ * The keyPressed() function is called once every time a key is pressed. The
+ * keyCode for the key that was pressed is stored in the keyCode variable.
+ *
+ * For non-ASCII keys, use the keyCode variable. You can check if the keyCode
+ * equals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,
+ * OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
+ *
+ * For ASCII keys, the key that was pressed is stored in the key variable. However, it
+ * does not distinguish between uppercase and lowercase. For this reason, it
+ * is recommended to use keyTyped() to read the key variable, in which the
+ * case of the variable will be distinguished.
+ *
+ * Because of how operating systems handle key repeats, holding down a key
+ * may cause multiple calls to keyTyped() (and keyReleased() as well). The
+ * rate of repeat is set by the operating system and how each computer is
+ * configured.
+ * Browsers may have different default
+ * behaviors attached to various key events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method keyPressed
+ * @param {Object} [event] optional KeyboardEvent callback argument.
+ * @example
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe(`black rect center. turns white when key pressed and black
+ * when released.`);
+ * }
+ * function keyPressed() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe(`black rect center. turns white when left arrow pressed and
+ * black when right.`);
+ * }
+ * function keyPressed() {
+ * if (keyCode === LEFT_ARROW) {
+ * value = 255;
+ * } else if (keyCode === RIGHT_ARROW) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * function keyPressed() {
+ * // Do something
+ * return false; // prevent any default behaviour
+ * }
+ *
+ *
+ */
+ _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();
+ }
+ }
+ };
+ /**
+ * The keyReleased() function is called once every time a key is released.
+ * See key and keyCode for more information.
+ * Browsers may have different 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 {Object} [event] optional KeyboardEvent callback argument.
+ * @example
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe(`black rect center. turns white when key pressed and black
+ * when pressed again`);
+ * }
+ * function keyReleased() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * return false; // prevent any default behavior
+ * }
+ *
+ *
+ */
+ _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();
+ }
+ }
+ };
+ /**
+ * The keyTyped() function is called once every time a key is pressed, but
+ * action keys such as Backspace, Delete, Ctrl, Shift, and Alt are ignored. If you are trying to detect
+ * a keyCode for one of these keys, use the keyPressed() function instead.
+ * The most recent key typed will be stored in the key variable.
+ *
+ * Because of how operating systems handle key repeats, holding down a key
+ * will cause multiple calls to keyTyped() (and keyReleased() as well). The
+ * rate of repeat is set by the operating system and how each computer is
+ * configured.
+ * Browsers may have different 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 {Object} [event] optional KeyboardEvent callback argument.
+ * @example
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe(`black rect center. turns white when 'a' key typed and
+ * black when 'b' pressed`);
+ * }
+ * 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 = {
+ };
+ };
+ /**
+ * The keyIsDown() function checks if the key is currently down, i.e. pressed.
+ * It can be used if you have an object that moves, and you want several keys
+ * to be able to affect its behaviour simultaneously, such as moving a
+ * sprite diagonally. You can put in any number representing the keyCode of
+ * the key, or use any of the variable keyCode names listed
+ * here.
+ *
+ * @method keyIsDown
+ * @param {Number} code The key to check for.
+ * @return {Boolean} whether key is down or not
+ * @example
+ *
+ * let x = 100;
+ * let y = 100;
+ *
+ * function setup() {
+ * createCanvas(512, 512);
+ * fill(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * if (keyIsDown(LEFT_ARROW)) {
+ * x -= 5;
+ * }
+ *
+ * if (keyIsDown(RIGHT_ARROW)) {
+ * x += 5;
+ * }
+ *
+ * if (keyIsDown(UP_ARROW)) {
+ * y -= 5;
+ * }
+ *
+ * if (keyIsDown(DOWN_ARROW)) {
+ * y += 5;
+ * }
+ *
+ * clear();
+ * ellipse(x, y, 50, 50);
+ * describe(`50-by-50 red ellipse moves left, right, up, and
+ * down with arrow presses.`);
+ * }
+ *
+ *
+ *
+ * let diameter = 50;
+ *
+ * function setup() {
+ * createCanvas(512, 512);
+ * }
+ *
+ * function draw() {
+ * // 107 and 187 are keyCodes for "+"
+ * if (keyIsDown(107) || keyIsDown(187)) {
+ * diameter += 1;
+ * }
+ *
+ * // 109 and 189 are keyCodes for "-"
+ * if (keyIsDown(109) || keyIsDown(189)) {
+ * diameter -= 1;
+ * }
+ *
+ * clear();
+ * fill(255, 0, 0);
+ * ellipse(50, 50, diameter, diameter);
+ * describe(`50-by-50 red ellipse gets bigger or smaller when
+ * + or - are pressed.`);
+ * }
+ *
+ */
+ _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': 290
+ }
+ ],
+ 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.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.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.array.includes');
+ _dereq_('core-js/modules/es.string.includes');
+ 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
+ */
+ /**
+ *
+ * The variable movedX contains the horizontal movement of the mouse since the last frame
+ * @property {Number} movedX
+ * @readOnly
+ * @example
+ *
+ *
+ * let x = 50;
+ * function setup() {
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * if (x > 48) {
+ * x -= 2;
+ * } else if (x < 48) {
+ * x += 2;
+ * }
+ * x += floor(movedX / 5);
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(x, 50, 50, 50);
+ * describe(`box moves left and right according to mouse movement
+ * then slowly back towards the center`);
+ * }
+ *
+ *
+ */
+
+ _main.default.prototype.movedX = 0;
+ /**
+ * The variable movedY contains the vertical movement of the mouse since the last frame
+ * @property {Number} movedY
+ * @readOnly
+ * @example
+ *
+ *
+ * let y = 50;
+ * function setup() {
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * if (y > 48) {
+ * y -= 2;
+ * } else if (y < 48) {
+ * y += 2;
+ * }
+ * y += floor(movedY / 5);
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(50, y, 50, 50);
+ * describe(`box moves up and down according to mouse movement then
+ * slowly back towards the center`);
+ * }
+ *
+ *
+ */
+ _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;
+ /**
+ * The system variable mouseX always contains the current horizontal
+ * position of the mouse, relative to (0, 0) of the canvas. The value at
+ * the top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.
+ * If touch is used instead of mouse input, mouseX will hold the x value
+ * of the most recent touch point.
+ *
+ * @property {Number} mouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas
+ * function draw() {
+ * background(244, 248, 252);
+ * line(mouseX, 0, mouseX, 100);
+ * describe('horizontal black line moves left and right with mouse x-position');
+ * }
+ *
+ *
+ */
+ _main.default.prototype.mouseX = 0;
+ /**
+ * The system variable mouseY always contains the current vertical
+ * position of the mouse, relative to (0, 0) of the canvas. The value at
+ * the top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.
+ * If touch is used instead of mouse input, mouseY will hold the y value
+ * of the most recent touch point.
+ *
+ * @property {Number} mouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas
+ * function draw() {
+ * background(244, 248, 252);
+ * line(0, mouseY, 100, mouseY);
+ * describe('vertical black line moves up and down with mouse y-position');
+ * }
+ *
+ *
+ */
+ _main.default.prototype.mouseY = 0;
+ /**
+ * The system variable pmouseX always contains the horizontal position of
+ * the mouse or finger in the frame previous to the current frame, relative to
+ * (0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and
+ * (-width/2, -height/2) for WebGL. Note: pmouseX will be reset to the current mouseX
+ * value at the start of each touch event.
+ *
+ * @property {Number} pmouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas to leave a trail
+ * function setup() {
+ * //slow down the frameRate to make it more visible
+ * frameRate(10);
+ * }
+ *
+ * function draw() {
+ * background(244, 248, 252);
+ * line(mouseX, mouseY, pmouseX, pmouseY);
+ * print(pmouseX + ' -> ' + mouseX);
+ * describe(`line trail is created from cursor movements.
+ * faster movement make longer line.`);
+ * }
+ *
+ *
+ */
+ _main.default.prototype.pmouseX = 0;
+ /**
+ * The system variable pmouseY always contains the vertical position of
+ * the mouse or finger in the frame previous to the current frame, relative to
+ * (0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and
+ * (-width/2, -height/2) for WebGL. Note: pmouseY will be reset to the current mouseY
+ * value at the start of each touch event.
+ *
+ * @property {Number} pmouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ * //draw a square only if the mouse is not moving
+ * if (mouseY === pmouseY && mouseX === pmouseX) {
+ * rect(20, 20, 60, 60);
+ * }
+ *
+ * print(pmouseY + ' -> ' + mouseY);
+ * describe(`60-by-60 black rect center, fuchsia background.
+ * rect flickers on mouse movement`);
+ * }
+ *
+ *
+ */
+ _main.default.prototype.pmouseY = 0;
+ /**
+ * The system variable winMouseX always contains the current horizontal
+ * position of the mouse, relative to (0, 0) of the window.
+ *
+ * @property {Number} winMouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * let body = document.getElementsByTagName('body')[0];
+ * myCanvas.parent(body);
+ * }
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * //move the canvas to the horizontal mouse position
+ * //relative to the window
+ * myCanvas.position(winMouseX + 1, windowHeight / 2);
+ *
+ * //the y of the square is relative to the canvas
+ * rect(20, mouseY, 60, 60);
+ * describe(`60-by-60 black rect y moves with mouse y and fuchsia
+ * canvas moves with mouse x`);
+ * }
+ *
+ *
+ */
+ _main.default.prototype.winMouseX = 0;
+ /**
+ * The system variable winMouseY always contains the current vertical
+ * position of the mouse, relative to (0, 0) of the window.
+ *
+ * @property {Number} winMouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * let body = document.getElementsByTagName('body')[0];
+ * myCanvas.parent(body);
+ * }
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * //move the canvas to the vertical mouse position
+ * //relative to the window
+ * myCanvas.position(windowWidth / 2, winMouseY + 1);
+ *
+ * //the x of the square is relative to the canvas
+ * rect(mouseX, 20, 60, 60);
+ * describe(`60-by-60 black rect x moves with mouse x and
+ * fuchsia canvas y moves with mouse y`);
+ * }
+ *
+ *
+ */
+ _main.default.prototype.winMouseY = 0;
+ /**
+ * The system variable pwinMouseX always contains the horizontal position
+ * of the mouse in the frame previous to the current frame, relative to
+ * (0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX
+ * value at the start of each touch event.
+ *
+ * @property {Number} pwinMouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * noStroke();
+ * fill(237, 34, 93);
+ * }
+ *
+ * function draw() {
+ * clear();
+ * //the difference between previous and
+ * //current x position is the horizontal mouse speed
+ * let speed = abs(winMouseX - pwinMouseX);
+ * //change the size of the circle
+ * //according to the horizontal speed
+ * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
+ * //move the canvas to the mouse position
+ * myCanvas.position(winMouseX + 1, winMouseY + 1);
+ * describe(`fuchsia ellipse moves with mouse x and y.
+ * Grows and shrinks with mouse speed`);
+ * }
+ *
+ *
+ */
+ _main.default.prototype.pwinMouseX = 0;
+ /**
+ * The system variable pwinMouseY always contains the vertical position of
+ * the mouse in the frame previous to the current frame, relative to (0, 0)
+ * of the window. Note: pwinMouseY will be reset to the current winMouseY
+ * value at the start of each touch event.
+ *
+ * @property {Number} pwinMouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * noStroke();
+ * fill(237, 34, 93);
+ * }
+ *
+ * function draw() {
+ * clear();
+ * //the difference between previous and
+ * //current y position is the vertical mouse speed
+ * let speed = abs(winMouseY - pwinMouseY);
+ * //change the size of the circle
+ * //according to the vertical speed
+ * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
+ * //move the canvas to the mouse position
+ * myCanvas.position(winMouseX + 1, winMouseY + 1);
+ * describe(`fuchsia ellipse moves with mouse x and y.
+ * Grows and shrinks with mouse speed`);
+ * }
+ *
+ *
+ */
+ _main.default.prototype.pwinMouseY = 0;
+ /**
+ * p5 automatically tracks if the mouse button is pressed and which
+ * button is pressed. The value of the system variable mouseButton is either
+ * LEFT, RIGHT, or CENTER depending on which button was pressed last.
+ * Warning: different browsers may track mouseButton differently.
+ *
+ * @property {Constant} mouseButton
+ * @readOnly
+ *
+ * @example
+ *
+ */
+ _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);
+ }
+ };
+ /**
+ * The mouseMoved() function is called every time the mouse moves and a mouse
+ * button is not pressed.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseMoved
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Move the mouse across the page
+ * // to change its value
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe(`black 50-by-50 rect becomes lighter with mouse movements until
+ * white then resets no image displayed`);
+ * }
+ * function mouseMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseMoved(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ */
+ /**
+ * The mouseDragged() function is called once every time the mouse moves and
+ * a mouse button is pressed. If no mouseDragged() function is defined, the
+ * touchMoved() function will be called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the function.
+ *
+ * @method mouseDragged
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Drag the mouse across the page
+ * // to change its value
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe(`black 50-by-50 rect turns lighter with mouse click and
+ * drag until white, resets`);
+ * }
+ * function mouseDragged() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseDragged(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ */
+ _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();
+ }
+ }
+ }
+ };
+ /**
+ * The mousePressed() function is called once after every time a mouse button
+ * is pressed. The mouseButton variable (see the related reference entry)
+ * can be used to determine which button has been pressed. If no
+ * mousePressed() function is defined, the touchStarted() function will be
+ * called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the function.
+ *
+ * @method mousePressed
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe('black 50-by-50 rect turns white with mouse click/press.');
+ * }
+ * function mousePressed() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mousePressed(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ */
+ _main.default.prototype._onmousedown = function (e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', true);
+ this._setMouseButton(e);
+ this._updateNextMouseCoords(e);
+ if (typeof context.mousePressed === 'function') {
+ executeDefault = context.mousePressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ } // only safari needs this manual fallback for consistency
+
+ } else if (navigator.userAgent.toLowerCase().includes('safari') && typeof context.touchStarted === 'function') {
+ executeDefault = context.touchStarted(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+ /**
+ * The mouseReleased() function is called every time a mouse button is
+ * released. If no mouseReleased() function is defined, the touchEnded()
+ * function will be called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the function.
+ *
+ * @method mouseReleased
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been clicked
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe('black 50-by-50 rect turns white with mouse click/press.');
+ * }
+ * function mouseReleased() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseReleased(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ */
+ _main.default.prototype._onmouseup = function (e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', false);
+ 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();
+ }
+ }
+ };
+ _main.default.prototype._ondragend = _main.default.prototype._onmouseup;
+ _main.default.prototype._ondragover = _main.default.prototype._onmousemove;
+ /**
+ * The mouseClicked() function is called once after a mouse button has been
+ * pressed and then released.
+ * Browsers handle clicks differently, so this function is only guaranteed to be
+ * run when the left mouse button is clicked. To handle other mouse buttons
+ * being pressed or released, see mousePressed() or mouseReleased().
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the function.
+ *
+ * @method mouseClicked
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been clicked
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe('black 50-by-50 rect turns white with mouse click/press.');
+ * }
+ *
+ * function mouseClicked() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseClicked(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ */
+ _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();
+ }
+ }
+ };
+ /**
+ * The doubleClicked() function is executed every time a event
+ * listener has detected a dblclick event which is a part of the
+ * DOM L3 specification. The doubleClicked event is fired when a
+ * pointing device button (usually a mouse's primary button)
+ * is clicked twice on a single element. For more info on the
+ * dblclick event refer to mozilla's documentation here:
+ * https://developer.mozilla.org/en-US/docs/Web/Events/dblclick
+ *
+ * @method doubleClicked
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been double clicked
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe('black 50-by-50 rect turns white with mouse doubleClick/press.');
+ * }
+ *
+ * function doubleClicked() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function doubleClicked(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ */
+ _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;
+ /**
+ * The function mouseWheel() is executed every time a vertical mouse wheel
+ * event is detected either triggered by an actual mouse wheel or by a
+ * touchpad.
+ * The event.delta property returns the amount the mouse wheel
+ * have scrolled. The values can be positive or negative depending on the
+ * scroll direction (on macOS with "natural" scrolling enabled, the signs
+ * are inverted).
+ * Browsers may have different default behaviors attached to various
+ * mouse events. To prevent any default behavior for this event, add
+ * "return false" to the end of the method.
+ * Due to the current support of the "wheel" event on Safari, the function
+ * may only work as expected if "return false" is included while using Safari.
+ *
+ * @method mouseWheel
+ * @param {Object} [event] optional WheelEvent callback argument.
+ *
+ * @example
+ *
+ *
+ * let pos = 25;
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(25, pos, 50, 50);
+ * describe(`black 50-by-50 rect moves up and down with vertical scroll.
+ * fuchsia background`);
+ * }
+ *
+ * function mouseWheel(event) {
+ * print(event.delta);
+ * //move the square according to the vertical scroll amount
+ * pos += event.delta;
+ * //uncomment to block page scrolling
+ * //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();
+ }
+ }
+ };
+ /**
+ * The function requestPointerLock()
+ * locks the pointer to its current position and makes it invisible.
+ * Use movedX and movedY to get the difference the mouse was moved since
+ * the last call of draw.
+ * Note that not all browsers support this feature.
+ * This enables you to create experiences that aren't limited by the mouse moving out of the screen
+ * even if it is repeatedly moved into one direction.
+ * For example, a first person perspective experience.
+ *
+ * @method requestPointerLock
+ * @example
+ *
+ *
+ * let cam;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * requestPointerLock();
+ * cam = createCamera();
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * cam.pan(-movedX * 0.001);
+ * cam.tilt(movedY * 0.001);
+ * sphere(25);
+ * describe(`3D scene moves according to mouse mouse movement in a
+ * first person perspective`);
+ * }
+ *
+ *
+ */
+ _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;
+ };
+ /**
+ * The function exitPointerLock()
+ * exits a previously triggered pointer Lock
+ * for example to make ui elements usable etc
+ *
+ * @method exitPointerLock
+ * @example
+ *
+ *
+ * //click the canvas to lock the pointer
+ * //click again to exit (otherwise escape)
+ * let locked = false;
+ * function draw() {
+ * background(237, 34, 93);
+ * describe('cursor gets locked / unlocked on mouse-click');
+ * }
+ * function mouseClicked() {
+ * if (!locked) {
+ * locked = true;
+ * requestPointerLock();
+ * } else {
+ * exitPointerLock();
+ * locked = false;
+ * }
+ * }
+ *
+ *
+ */
+ _main.default.prototype.exitPointerLock = function () {
+ document.exitPointerLock();
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 278,
+ '../core/main': 290,
+ 'core-js/modules/es.array.includes': 174,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.includes': 203,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 310: [
+ function (_dereq_, module, exports) {
+ 'use strict';
+ _dereq_('core-js/modules/es.array.includes');
+ _dereq_('core-js/modules/es.string.includes');
+ _dereq_('core-js/modules/es.array.includes');
+ _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
+ };
+ } /**
+ * @module Events
+ * @submodule Touch
+ * @for p5
+ * @requires core
+ */
+ /**
+ * The system variable touches[] contains an array of the positions of all
+ * current touch points, relative to (0, 0) of the canvas, and IDs identifying a
+ * unique touch as it moves. Each element in the array is an object with x, y,
+ * and id properties.
+ *
+ * The touches[] array is not supported on Safari and IE on touch-based
+ * desktops (laptops).
+ *
+ * @property {Object[]} touches
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // On a touchscreen device, touch
+ * // the canvas using one or more fingers
+ * // at the same time
+ * function draw() {
+ * clear();
+ * let display = touches.length + ' touches';
+ * text(display, 5, 10);
+ * describe(`Number of touches currently registered are displayed
+ * on the canvas`);
+ * }
+ *
+ *
+ */
+
+ _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
+ };
+ } /**
+ * The touchStarted() function is called once after every time a touch is
+ * registered. If no touchStarted() function is defined, the mousePressed()
+ * function will be called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchStarted
+ * @param {Object} [event] optional TouchEvent callback argument.
+ * @example
+ *
+ *
+ * // Touch within the image to change
+ * // the value of the rectangle
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe('50-by-50 black rect turns white with touch event.');
+ * }
+ * function touchStarted() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchStarted(event) {
+ * console.log(event);
+ * }
+ * describe('no image displayed');
+ *
+ *
+ */
+
+ _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();
+ } // only safari needs this manual fallback for consistency
+
+ } else if (navigator.userAgent.toLowerCase().includes('safari') && typeof context.mousePressed === 'function') {
+ executeDefault = context.mousePressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+ /**
+ * The touchMoved() function is called every time a touch move is registered.
+ * If no touchMoved() function is defined, the mouseDragged() function will
+ * be called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchMoved
+ * @param {Object} [event] optional TouchEvent callback argument.
+ * @example
+ *
+ *
+ * // Move your finger across the page
+ * // to change its value
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe('50-by-50 black rect turns lighter with touch until white. resets');
+ * }
+ * function touchMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchMoved(event) {
+ * console.log(event);
+ * }
+ * describe('no image displayed');
+ *
+ *
+ */
+ _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();
+ }
+ }
+ };
+ /**
+ * The touchEnded() function is called every time a touch ends. If no
+ * touchEnded() function is defined, the mouseReleased() function will be
+ * called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchEnded
+ * @param {Object} [event] optional TouchEvent callback argument.
+ * @example
+ *
+ *
+ * // Release touch within the image to
+ * // change the value of the rectangle
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * describe('50-by-50 black rect turns white with touch.');
+ * }
+ * function touchEnded() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 66×66 dark turquoise rect in center of canvas.
+ * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas
+ * no image displayed
+ */
+
+ _main.default.prototype.createImage = function (width, height) {
+ _main.default._validateParameters('createImage', arguments);
+ return new _main.default.Image(width, height);
+ };
+ /**
+ * Save the current canvas as an image. The browser will either save the
+ * file immediately, or prompt the user with a dialogue window.
+ *
+ * @method saveCanvas
+ * @param {p5.Element|HTMLCanvasElement} selectedCanvas a variable
+ * representing a specific html5 canvas (optional)
+ * @param {String} [filename]
+ * @param {String} [extension] 'jpg' or 'png'
+ *
+ * @example
+ *
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(255, 0, 0);
+ * saveCanvas(c, 'myCanvas', 'jpg');
+ * }
+ *
+ *
+ * // note that this example has the same result as above
+ * // if no canvas is specified, defaults to main canvas
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(255, 0, 0);
+ * saveCanvas('myCanvas', 'jpg');
+ *
+ * // all of the following are valid
+ * saveCanvas(c, 'myCanvas', 'jpg');
+ * saveCanvas(c, 'myCanvas.jpg');
+ * saveCanvas(c, 'myCanvas');
+ * saveCanvas(c);
+ * saveCanvas('myCanvas', 'png');
+ * saveCanvas('myCanvas');
+ * saveCanvas();
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ * no image displayed
+ * no image displayed
+ */
+ /**
+ * @method saveCanvas
+ * @param {String} [filename]
+ * @param {String} [extension]
+ */
+ _main.default.prototype.saveCanvas = function () {
+ _main.default._validateParameters('saveCanvas', arguments); // copy arguments to array
+ var args = [
+ ].slice.call(arguments);
+ var htmlCanvas,
+ filename,
+ extension;
+ if (arguments[0] instanceof HTMLCanvasElement) {
+ htmlCanvas = arguments[0];
+ args.shift();
+ } else if (arguments[0] instanceof _main.default.Element) {
+ htmlCanvas = arguments[0].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);
+ }, 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();
+ for (var _k = 0; _k < allFramesPixelColors[_i3].length; _k++) {
+ var _color = allFramesPixelColors[_i3][_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 _k2 = 0; _k2 < allFramesPixelColors[_i3].length; _k2++) {
+ // If this pixel in this frame has the same color in previous frame
+ if (allFramesPixelColors[_i3 - 1][_k2] === allFramesPixelColors[_i3][_k2]) {
+ pixelPaletteIndex[_k2] = 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);
+ };
+ /**
+ * Capture a sequence of frames that can be used to create a movie.
+ * Accepts a callback. For example, you may wish to send the frames
+ * to a server where they can be stored or converted into a movie.
+ * If no callback is provided, the browser will pop up save dialogues in an
+ * attempt to download all of the images that have just been created. With the
+ * callback provided the image data isn't saved by default but instead passed
+ * as an argument to the callback function as an array of objects, with the
+ * size of array equal to the total number of frames.
+ *
+ * The arguments `duration` and `framerate` are constrained to be less or equal to 15 and 22, respectively, which means you
+ * can only download a maximum of 15 seconds worth of frames at 22 frames per second, adding up to 330 frames.
+ * This is done in order to avoid memory problems since a large enough canvas can fill up the memory in your computer
+ * very easily and crash your program or even your browser.
+ *
+ * To export longer animations, you might look into a library like
+ * ccapture.js.
+ *
+ * @method saveFrames
+ * @param {String} filename
+ * @param {String} extension 'jpg' or 'png'
+ * @param {Number} duration Duration in seconds to save the frames for. This parameter will be constrained to be less or equal to 15.
+ * @param {Number} framerate Framerate to save the frames in. This parameter will be constrained to be less or equal to 22.
+ * @param {function(Array)} [callback] A 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 - an
+ image/octet-stream, filename and extension.
+ * @example
+ *
+ *
+ * function setup() {
+ * // here we use a callback to display the image after loading
+ * loadImage('assets/laDefense.jpg', img => {
+ * image(img, 0, 0);
+ * });
+ * }
+ *
+ *
+ *
+ * @alt
+ * image of the underside of a white umbrella and grided ceililng above
+ * image of the underside of a white umbrella and grided ceililng above
+ */
+
+ _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 of your current animation and downloads it to your computer!
+ *
+ * The duration argument specifies how many seconds you want to record from your animation.
+ * This value is then converted to the necessary number of frames to generate it, depending
+ * on the value of units. More on that on the next paragraph.
+ *
+ * An optional object that can contain two more arguments: delay (number) and units (string).
+ *
+ * `delay`, specifying how much time we should wait before recording
+ *
+ * `units`, a string that can be either 'seconds' or 'frames'. By default it's 'seconds'.
+ *
+ * `units` specifies how the duration and delay arguments will behave.
+ * If 'seconds', these arguments will correspond to seconds, meaning that 3 seconds worth of animation
+ * will be created. If 'frames', the arguments now correspond to the number of frames you want your
+ * animation to be, if you are very sure of this number.
+ *
+ * This may be called in setup, or, like in the example below, inside an event function,
+ * like keyPressed or mousePressed.
+ *
+ * @method saveGif
+ * @param {String} filename File name of your gif
+ * @param {Number} duration Duration in seconds that you wish to capture from your sketch
+ * @param {Object} options An optional object that can contain two more arguments: delay, specifying
+ * how much time we should wait before recording, and units, a string that can be either 'seconds' or
+ * 'frames'. By default it's 'seconds'.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * colorMode(RGB);
+ * background(30);
+ *
+ * // create a bunch of circles that move in... circles!
+ * for (let i = 0; i < 10; i++) {
+ * let opacity = map(i, 0, 10, 0, 255);
+ * noStroke();
+ * fill(230, 250, 90, opacity);
+ * circle(
+ * 30 * sin(frameCount / (30 - i)) + width / 2,
+ * 30 * cos(frameCount / (30 - i)) + height / 2,
+ * 10
+ * );
+ * }
+ * }
+ *
+ * // you can put it in the mousePressed function,
+ * // or keyPressed for example
+ * function keyPressed() {
+ * // this will download the first 5 seconds of the animation!
+ * if (key === 's') {
+ * saveGif('mySketch', 5);
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * animation of a group of yellow circles moving in circles over a dark background
+ */
+ _main.default.prototype.saveGif = /*#__PURE__*/
+ function () {
+ var _ref = _asyncToGenerator( /*#__PURE__*/
+ regeneratorRuntime.mark(function _callee(fileName, duration) {
+ var options,
+ delay,
+ units,
+ _frameRate,
+ gifFrameDelay,
+ nFrames,
+ nFramesDelay,
+ totalNumberOfFrames,
+ frameIterator,
+ lastPixelDensity,
+ frames,
+ progressBarIdName,
+ 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'
+ };
+ 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'
+ // if arguments in the options object are not correct, cancel operation
+ if (!(typeof delay !== 'number')) {
+ _context.next = 9;
+ break;
+ }
+ throw TypeError('Delay parameter must be a number');
+ case 9:
+ if (!(units !== 'seconds' && units !== 'frames')) {
+ _context.next = 11;
+ break;
+ }
+ throw TypeError('Units parameter must be either "frames" or "seconds"');
+ case 11:
+ 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 = [
+ ];
+ progressBarIdName = 'p5.gif.progressBar';
+ if (document.getElementById(progressBarIdName) !== null) document.getElementById(progressBarIdName).remove();
+ p = this.createP('');
+ p.id('progressBar');
+ 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.drawingContext instanceof WebGLRenderingContext) {
+ // if we have a WEBGL context, initialize the pixels array
+ // and the gl context to use them inside the loop
+ gl = document.getElementById('defaultCanvas0').getContext('webgl');
+ pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
+ } // stop the loop since we are going to manually redraw
+
+ this.noLoop();
+ case 36:
+ if (!(frameIterator < totalNumberOfFrames)) {
+ _context.next = 47;
+ 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.drawingContext instanceof WebGLRenderingContext) {
+ 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);
+ } else {
+ data = this.drawingContext.getImageData(0, 0, this.width, this.height).data;
+ }
+ frames.push(data);
+ frameIterator++;
+ p.html('Saved frame ' + frames.length.toString() + ' out of ' + nFrames.toString());
+ _context.next = 45;
+ return new Promise(function (resolve) {
+ return setTimeout(resolve, 0);
+ });
+ case 45:
+ _context.next = 36;
+ break;
+ case 47:
+ 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 57:
+ if (!(i < frames.length)) {
+ _context.next = 68;
+ 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;
+ 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 = 65;
+ return new Promise(function (resolve) {
+ return setTimeout(resolve, 0);
+ });
+ case 65:
+ i++;
+ _context.next = 57;
+ break;
+ case 68:
+ 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();
+ p.html('Done. Downloading your gif!🌸');
+ _main.default.prototype.downloadFile(blob, fileName, extension);
+ case 77:
+ case 'end':
+ return _context.stop();
+ }
+ }
+ }, _callee, this);
+ }));
+ return function (_x, _x2) {
+ return _ref.apply(this, arguments);
+ };
+ }();
+ function _flipPixels(pixels) {
+ // 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);
+ if (numFrames > 1) {
+ 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 0 && sVal < iVal) {
+ return sVal;
+ } else {
+ return iVal;
+ }
+ } /**
+ * Draw an image to the p5.js canvas.
+ *
+ * This function can be used with different numbers of parameters. The
+ * simplest use requires only three parameters: img, x, and y—where (x, y) is
+ * the position of the image. Two more parameters can optionally be added to
+ * specify the width and height of the image.
+ *
+ * This function can also be used with eight Number parameters. To
+ * differentiate between all these parameters, p5.js uses the language of
+ * "destination rectangle" (which corresponds to "dx", "dy", etc.) and "source
+ * image" (which corresponds to "sx", "sy", etc.) below. Specifying the
+ * "source image" dimensions can be useful when you want to display a
+ * subsection of the source image instead of the whole thing. Here's a diagram
+ * to explain further:
+ *
+ *
+ * This function can also be used to draw images without distorting the orginal aspect ratio,
+ * by adding 9th parameter, fit, which can either be COVER or CONTAIN.
+ * CONTAIN, as the name suggests, contains the whole image within the specified destination box
+ * without distorting the image ratio.
+ * COVER covers the entire destination box.
+ *
+ *
+ *
+ * @method image
+ * @param {p5.Image|p5.Element|p5.Texture} img the image to display
+ * @param {Number} x the x-coordinate of the top-left corner of the image
+ * @param {Number} y the y-coordinate of the top-left corner of the image
+ * @param {Number} [width] the width to draw the image
+ * @param {Number} [height] the height to draw the image
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * // Top-left corner of the img is at (0, 0)
+ * // Width and height are the img's original width and height
+ * image(img, 0, 0);
+ * }
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * background(50);
+ * // Top-left corner of the img is at (10, 10)
+ * // Width and height are 50×50
+ * image(img, 10, 10, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * // Here, we use a callback to display the image after loading
+ * loadImage('assets/laDefense.jpg', img => {
+ * image(img, 0, 0);
+ * });
+ * }
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/gradient.png');
+ * }
+ * function setup() {
+ * // 1. Background image
+ * // Top-left corner of the img is at (0, 0)
+ * // Width and height are the img's original width and height, 100×100
+ * image(img, 0, 0);
+ * // 2. Top right image
+ * // Top-left corner of destination rectangle is at (50, 0)
+ * // Destination rectangle width and height are 40×20
+ * // The next parameters are relative to the source image:
+ * // - Starting at position (50, 50) on the source image, capture a 50×50
+ * // subsection
+ * // - Draw this subsection to fill the dimensions of the destination rectangle
+ * image(img, 50, 0, 40, 20, 50, 50, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * // dimensions of image are 780 x 440
+ * // dimensions of canvas are 100 x 100
+ * img = loadImage('assets/moonwalk.jpg');
+ * }
+ * function setup() {
+ * // CONTAIN the whole image without distorting the image's aspect ratio
+ * // CONTAIN the image within the specified destination box and display at LEFT,CENTER position
+ * background(color('green'));
+ * image(img, 0, 0, width, height, 0, 0, img.width, img.height, CONTAIN, LEFT);
+ * }
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense50.png'); // dimensions of image are 50 x 50
+ * }
+ * function setup() {
+ * // COVER the whole destination box without distorting the image's aspect ratio
+ * // COVER the specified destination box which is of dimension 100 x 100
+ * // Without specifying xAlign or yAlign, the image will be
+ * // centered in the destination box in both axes
+ * image(img, 0, 0, width, height, 0, 0, img.width, img.height, COVER);
+ * }
+ *
+ *
+ * @alt
+ * image of the underside of a white umbrella and gridded ceiling above
+ * image of the underside of a white umbrella and gridded ceiling above
+ */
+ /**
+ * @method image
+ * @param {p5.Image|p5.Element|p5.Texture} 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 && img.elt.videoWidth && !img.canvas) {
+ // video no canvas
+ defW = img.elt.videoWidth;
+ 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 || defW;
+ var _sh = 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);
+ };
+ /**
+ * Sets the fill value for displaying images. Images can be tinted to
+ * specified colors or made transparent by including an alpha value.
+ *
+ * To apply transparency to an image without affecting its color, use
+ * white as the tint color and specify an alpha value. For instance,
+ * tint(255, 128) will make an image 50% transparent (assuming the default
+ * alpha range of 0-255, which can be changed with colorMode()).
+ *
+ * The value for the gray parameter must be less than or equal to the current
+ * maximum value as specified by colorMode(). The default maximum value is
+ * 255.
+ *
+ * @method tint
+ * @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]
+ *
+ * @example
+ *
+ *
+ * @alt
+ * 2 side by side images of umbrella and ceiling, one image with blue tint
+ * Images of umbrella and ceiling, one half of image with blue tint
+ * 2 side by side images of umbrella and ceiling, one image translucent
+ */
+ /**
+ * @method tint
+ * @param {String} value a color string
+ */
+ /**
+ * @method tint
+ * @param {Number} gray a gray value
+ * @param {Number} [alpha]
+ */
+ /**
+ * @method tint
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and 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 fill value for displaying images and reverts to
+ * displaying images with their original hues.
+ *
+ * @method noTint
+ * @example
+ *
+ *
+ * @alt
+ * 2 side by side images of bricks, left image with blue 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;
+ /**
+ * Set image mode. Modifies the location from which images are drawn by
+ * changing the way in which parameters given to image() are interpreted.
+ * The default mode is imageMode(CORNER), which interprets the second and
+ * third parameters of image() as the upper-left corner of the image. If
+ * two additional parameters are specified, they are used to set the image's
+ * width and height.
+ *
+ * imageMode(CORNERS) interprets the second and third parameters of image()
+ * as the location of one corner, and the fourth and fifth parameters as the
+ * opposite corner.
+ *
+ * imageMode(CENTER) interprets the second and third parameters of image()
+ * as the image's center point. If two additional parameters are specified,
+ * they are used to set the image's width and height.
+ *
+ * @method imageMode
+ * @param {Constant} mode either CORNER, CORNERS, or CENTER
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * image(img, 0, 0);
+ * for (let i = 0; i < img.width; i++) {
+ * let c = img.get(i, img.height / 2);
+ * stroke(c);
+ * line(i, height / 2, i, height);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * rocky mountains in top and horizontal lines in corresponding colors in bottom.
+ *
+ */
+ this.width = width;
+ /**
+ * Image height.
+ * @property {Number} height
+ * @readOnly
+ * @example
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * image(img, 0, 0);
+ * for (let i = 0; i < img.height; i++) {
+ * let c = img.get(img.width / 2, i);
+ * stroke(c);
+ * line(0, i, width / 2, i);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * rocky mountains on right and vertical lines in corresponding colors on left.
+ *
+ */
+ 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;
+ /**
+ * Array containing the values for all the pixels in the display window.
+ * These values are numbers. This array is the size (include an appropriate
+ * factor for pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. Retina and other
+ * high density displays may have more pixels (by a factor of
+ * pixelDensity^2).
+ * For example, if the image is 100×100 pixels, there will be 40,000. With
+ * pixelDensity = 2, there will be 160,000. The first four values
+ * (indices 0-3) in the array will be the R, G, B, A values of the pixel at
+ * (0, 0). The second four values (indices 4-7) will contain the R, G, B, A
+ * values of the pixel at (1, 0). More generally, to set values for a pixel
+ * at (x, y):
+ * ```javascript
+ * let d = pixelDensity();
+ * for (let i = 0; i < d; i++) {
+ * for (let j = 0; j < d; j++) {
+ * // loop over
+ * index = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[index] = r;
+ * pixels[index+1] = g;
+ * pixels[index+2] = b;
+ * pixels[index+3] = a;
+ * }
+ * }
+ * ```
+ *
+ * Before accessing this array, the data must loaded with the loadPixels()
+ * function. After the array data has been modified, the updatePixels()
+ * function must be run to update the changes.
+ * @property {Number[]} pixels
+ * @example
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains vertically stacked
+ */
+ _main.default.Image.prototype.loadPixels = function () {
+ _main.default.Renderer2D.prototype.loadPixels.call(this);
+ this.setModified(true);
+ };
+ /**
+ * Updates the backing canvas for this image with the contents of
+ * the [pixels] array.
+ *
+ * If this image is an animated GIF then the pixels will be updated
+ * in the frame that is currently displayed.
+ *
+ * @method updatePixels
+ * @param {Integer} x x-offset of the target update area for the
+ * underlying canvas
+ * @param {Integer} y y-offset of the target update area for the
+ * underlying canvas
+ * @param {Integer} w width of the target update area for the
+ * underlying canvas
+ * @param {Integer} h height of the target update area for the
+ * underlying canvas
+ * @example
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains vertically stacked
+ */
+ /**
+ * @method updatePixels
+ */
+ _main.default.Image.prototype.updatePixels = function (x, y, w, h) {
+ _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h);
+ this.setModified(true);
+ };
+ /**
+ * Get a region of pixels from an image.
+ *
+ * If no params are passed, the whole image is returned.
+ * If x and y are the only params passed a single pixel is extracted.
+ * If all params are passed a rectangle region is extracted and a p5.Image
+ * is returned.
+ *
+ * @method get
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number} w width
+ * @param {Number} h height
+ * @return {p5.Image} the rectangle p5.Image
+ * @example
+ *
+ * let myImage;
+ * let c;
+ *
+ * function preload() {
+ * myImage = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * background(myImage);
+ * noStroke();
+ * c = myImage.get(60, 90);
+ * fill(c);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * //get() returns color here
+ *
+ *
+ * @alt
+ * image of rocky mountains with 50×50 green rect in front
+ */
+ /**
+ * @method get
+ * @return {p5.Image} the whole p5.Image
+ */
+ /**
+ * @method get
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number[]} color of pixel at x,y in array format [R, G, B, A]
+ */
+ _main.default.Image.prototype.get = function (x, y, w, h) {
+ _main.default._validateParameters('p5.Image.get', arguments);
+ return _main.default.Renderer2D.prototype.get.apply(this, arguments);
+ };
+ _main.default.Image.prototype._getPixel = _main.default.Renderer2D.prototype._getPixel;
+ /**
+ * Set the color of a single pixel or write an image into
+ * this p5.Image.
+ *
+ * Note that for a large number of pixels this will
+ * be slower than directly manipulating the pixels array
+ * and then calling updatePixels().
+ *
+ * @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 |
+ * a p5.Color | image to copy
+ * @example
+ *
+ *
+ * @alt
+ * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas
+ */
+ _main.default.Image.prototype.set = function (x, y, imgOrCol) {
+ _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol);
+ this.setModified(true);
+ };
+ /**
+ * Resize the image to a new width and height. To make the image scale
+ * proportionally, use 0 as the value for the wide or high parameter.
+ * For instance, to make the width of an image 150 pixels, and change
+ * the height using the same proportion, use resize(150, 0).
+ *
+ * @method resize
+ * @param {Number} width the resized image width
+ * @param {Number} height the resized image height
+ * @example
+ *
+ *
+ * @alt
+ * image of rocky mountains. zoomed in
+ */
+ _main.default.Image.prototype.resize = function (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 a region of pixels from one image to another. If no
+ * srcImage is specified this is used as the source. If the source
+ * and destination regions aren't the same size, it will
+ * automatically resize source pixels to fit the specified
+ * target 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 photo;
+ * let bricks;
+ * let x;
+ * let y;
+ *
+ * function preload() {
+ * photo = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks.jpg');
+ * }
+ *
+ * function setup() {
+ * x = bricks.width / 2;
+ * y = bricks.height / 2;
+ * photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);
+ * image(photo, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains and smaller image on top of bricks at top left
+ */
+ /**
+ * @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.Image.prototype.copy = function () {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+ _main.default.prototype.copy.apply(this, args);
+ };
+ /**
+ * Masks part of an image from displaying by loading another
+ * image and using its alpha channel as an alpha channel for
+ * this image. Masks are cumulative, once applied to an image
+ * object, they cannot be removed.
+ *
+ * @method mask
+ * @param {p5.Image} srcImage source image
+ * @example
+ *
+ *
+ * @alt
+ * image of rocky mountains with white at right
+ *
+ * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
+ */
+ // TODO: - Accept an array of alpha values.
+ _main.default.Image.prototype.mask = function (p5Image) {
+ if (p5Image === undefined) {
+ p5Image = this;
+ }
+ var currBlend = this.drawingContext.globalCompositeOperation;
+ var scaleFactor = 1;
+ if (p5Image instanceof _main.default.Renderer) {
+ scaleFactor = p5Image._pInst._pixelDensity;
+ }
+ var copyArgs = [
+ p5Image,
+ 0,
+ 0,
+ scaleFactor * p5Image.width,
+ scaleFactor * p5Image.height,
+ 0,
+ 0,
+ this.width,
+ 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);
+ _main.default.Image.prototype.copy.apply(this, copyArgs);
+ this.gifProperties.frames[i].image = this.drawingContext.getImageData(0, 0, this.width, this.height);
+ }
+ this.drawingContext.putImageData(this.gifProperties.frames[this.gifProperties.displayIndex].image, 0, 0);
+ } else {
+ _main.default.Image.prototype.copy.apply(this, copyArgs);
+ }
+ this.drawingContext.globalCompositeOperation = currBlend;
+ this.setModified(true);
+ };
+ /**
+ * Applies an image filter to a p5.Image
+ *
+ * THRESHOLD
+ * 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.
+ *
+ * GRAY
+ * Converts any colors in the image to grayscale equivalents. No parameter
+ * is used.
+ *
+ * OPAQUE
+ * Sets the alpha channel to entirely opaque. No parameter is used.
+ *
+ * INVERT
+ * Sets each pixel to its inverse value. No parameter is used.
+ *
+ * POSTERIZE
+ * 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.
+ *
+ * BLUR
+ * Executes a Gaussian blur with the level parameter specifying the extent
+ * of the blurring. If no parameter is used, the blur is equivalent to
+ * Gaussian blur of radius 1. Larger values increase the blur.
+ *
+ * ERODE
+ * Reduces the light areas. No parameter is used.
+ *
+ * DILATE
+ * Increases the light areas. No parameter is used.
+ *
+ * filter() does not work in WEBGL mode.
+ * A similar effect can be achieved in WEBGL mode using custom
+ * shaders. Adam Ferriss has written
+ * a selection of shader examples that contains many
+ * of the effects present in the filter examples.
+ *
+ * @method filter
+ * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT,
+ * POSTERIZE, ERODE, DILATE or BLUR.
+ * See Filters.js for docs on
+ * each available filter
+ * @param {Number} [filterParam] an optional parameter unique
+ * to each filter, see above
+ * @example
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ */
+ /**
+ * @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.Image.prototype.blend = function () {
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+ _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
+ */
+ _main.default.Image.prototype.setModified = function (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.
+ */
+ _main.default.Image.prototype.isModified = function () {
+ return this._modified;
+ };
+ /**
+ * Saves the image to a file and force the browser to download it.
+ * Accepts two strings for filename and file extension
+ * Supports png (default), jpg, and gif
+ *
+ * Note that the file will only be downloaded as an animated GIF
+ * if the p5.Image was loaded from a GIF file.
+ * @method save
+ * @param {String} filename give your file a name
+ * @param {String} extension 'png' or 'jpg'
+ * @example
+ *
+ *
+ * @alt
+ * image of rocky mountains.
+ */
+ _main.default.Image.prototype.save = function (filename, extension) {
+ if (this.gifProperties) {
+ _main.default.prototype.encodeAndDownloadGif(this, filename);
+ } else {
+ _main.default.prototype.saveCanvas(this.canvas, filename, extension);
+ }
+ }; // GIF Section
+ /**
+ * Starts an animated GIF over at the beginning state.
+ *
+ * @method reset
+ * @example
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-wink-loop-once.gif');
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * // The GIF file that we loaded only loops once
+ * // so it freezes on the last frame after playing through
+ * image(gif, 0, 0);
+ * }
+ *
+ * function mousePressed() {
+ * // Click to reset the GIF and begin playback from start
+ * gif.reset();
+ * }
+ *
+ * @alt
+ * Animated image of a cartoon face that winks once and then freezes
+ * When you click it animates again, winks once and freezes
+ */
+ _main.default.Image.prototype.reset = function () {
+ 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 for the frame that is currently visible in an animated GIF.
+ *
+ * @method getCurrentFrame
+ * @return {Number} The index for the currently displaying frame in animated GIF
+ * @example
+ *
+ * @alt
+ * Animated image of a cartoon eye looking around and then
+ * looking outwards, in the lower-left hand corner a number counts
+ * up quickly to 124 and then starts back over at 0
+ */
+ _main.default.Image.prototype.getCurrentFrame = function () {
+ if (this.gifProperties) {
+ var props = this.gifProperties;
+ return props.displayIndex % props.numFrames;
+ }
+ };
+ /**
+ * Sets the index of the frame that is currently visible in an animated GIF
+ *
+ * @method setFrame
+ * @param {Number} index the index for the frame that should be displayed
+ * @example
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
+ * }
+ *
+ * // Move your mouse up and down over canvas to see the GIF
+ * // frames animate
+ * function draw() {
+ * gif.pause();
+ * image(gif, 0, 0);
+ * // Get the highest frame number which is the number of frames - 1
+ * let maxFrame = gif.numFrames() - 1;
+ * // Set the current frame that is mapped to be relative to mouse position
+ * let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));
+ * gif.setFrame(frameNumber);
+ * }
+ *
+ * @alt
+ * A still image of a cartoon eye that looks around when you move your mouse
+ * up and down over the canvas
+ */
+ _main.default.Image.prototype.setFrame = function (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}
+ * @example The number of frames in the animated GIF
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
+ * }
+ *
+ * // Move your mouse up and down over canvas to see the GIF
+ * // frames animate
+ * function draw() {
+ * gif.pause();
+ * image(gif, 0, 0);
+ * // Get the highest frame number which is the number of frames - 1
+ * let maxFrame = gif.numFrames() - 1;
+ * // Set the current frame that is mapped to be relative to mouse position
+ * let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));
+ * gif.setFrame(frameNumber);
+ * }
+ *
+ * @alt
+ * A still image of a cartoon eye that looks around when you move your mouse
+ * up and down over the canvas
+ */
+ _main.default.Image.prototype.numFrames = function () {
+ if (this.gifProperties) {
+ return this.gifProperties.numFrames;
+ }
+ };
+ /**
+ * Plays an animated GIF that was paused with
+ * pause()
+ *
+ * @method play
+ * @example
+ *
+ * @alt
+ * An animated GIF of a drawing of small child with
+ * hair blowing in the wind, when you click the image
+ * freezes when you release it animates again
+ */
+ _main.default.Image.prototype.play = function () {
+ if (this.gifProperties) {
+ this.gifProperties.playing = true;
+ }
+ };
+ /**
+ * Pauses an animated GIF.
+ *
+ * @method pause
+ * @example
+ *
+ * @alt
+ * An animated GIF of a drawing of small child with
+ * hair blowing in the wind, when you click the image
+ * freezes when you release it animates again
+ */
+ _main.default.Image.prototype.pause = function () {
+ if (this.gifProperties) {
+ this.gifProperties.playing = false;
+ }
+ };
+ /**
+ * Changes the delay between frames in an animated GIF. There is an optional second parameter that
+ * indicates an index for a specific frame that should have its delay modified. If no index is given, all frames
+ * will have the new delay.
+ *
+ * @method delay
+ * @param {Number} d the amount in milliseconds to delay between switching frames
+ * @param {Number} [index] the index of the frame that should have the new delay value {optional}
+ * @example
+ *
+ * @alt
+ * Two animated gifs of cartoon eyes looking around
+ * The gif on the left animates quickly, on the right
+ * the animation is much slower
+ */
+ _main.default.Image.prototype.delay = function (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;
+ }
+ }
+ }
+ }
+ }
+ };
+ var _default = _main.default.Image;
+ exports.default = _default;
+ },
+ {
+ '../core/main': 290,
+ './filters': 311,
+ 'core-js/modules/es.array.filter': 171,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 315: [
+ 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
+ */
+ /**
+ * Uint8ClampedArray
+ * containing the values for all the pixels in the display window.
+ * These values are numbers. This array is the size (include an appropriate
+ * factor for pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. Retina and other
+ * high density displays will have more pixels[] (by a factor of
+ * pixelDensity^2).
+ * For example, if the image is 100×100 pixels, there will be 40,000. On a
+ * retina display, there will be 160,000.
+ *
+ * The first four values (indices 0-3) in the array will be the R, G, B, A
+ * values of the pixel at (0, 0). The second four values (indices 4-7) will
+ * contain the R, G, B, A values of the pixel at (1, 0). More generally, to
+ * set values for a pixel at (x, y):
+ * ```javascript
+ * let d = pixelDensity();
+ * for (let i = 0; i < d; i++) {
+ * for (let j = 0; j < d; j++) {
+ * // loop over
+ * index = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[index] = r;
+ * pixels[index+1] = g;
+ * pixels[index+2] = b;
+ * pixels[index+3] = a;
+ * }
+ * }
+ * ```
+ * While the above method is complex, it is flexible enough to work with
+ * any pixelDensity. Note that set() will automatically take care of
+ * setting all the appropriate values in pixels[] for a given (x, y) at
+ * any pixelDensity, but the performance may not be as fast when lots of
+ * modifications are made to the pixel array.
+ *
+ * Before accessing this array, the data must loaded with the loadPixels()
+ * function. After the array data has been modified, the updatePixels()
+ * function must be run to update the changes.
+ *
+ * Note that this is not a standard javascript array. This means that
+ * standard javascript functions such as slice() or
+ * arrayCopy() do not
+ * work.
+ *
+ * @property {Number[]} pixels
+ * @example
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ *
+ */
+ /**
+ * @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 a region of the canvas to another region of the canvas
+ * and copies a region of pixels from an image used as the srcImg parameter
+ * into the canvas srcImage is specified this is used as the source. If
+ * the source and destination regions aren't the same size, it will
+ * automatically resize source pixels to fit the specified
+ * target 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
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ */
+ /**
+ * @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) {
+ srcImage.loadPixels();
+ 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) {
+ _main.default.RendererGL.prototype.image.call(dstImage._renderer, srcImage, sx + sxMod, sy + syMod, sw, sh, dx, dy, dw, dh);
+ } else {
+ dstImage.drawingContext.drawImage(srcImage.canvas, s * (sx + sxMod), s * (sy + syMod), s * sw, s * sh, dx, dy, dw, dh);
+ }
+ };
+ /**
+ * Applies a filter to the canvas. The presets options are:
+ *
+ * THRESHOLD
+ * 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.
+ *
+ * GRAY
+ * Converts any colors in the image to grayscale equivalents. No parameter
+ * is used.
+ *
+ * OPAQUE
+ * Sets the alpha channel to entirely opaque. No parameter is used.
+ *
+ * INVERT
+ * Sets each pixel to its inverse value. No parameter is used.
+ *
+ * POSTERIZE
+ * 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.
+ *
+ * BLUR
+ * Executes a Gaussian blur with the level parameter specifying the extent
+ * of the blurring. If no parameter is used, the blur is equivalent to
+ * Gaussian blur of radius 1. Larger values increase the blur.
+ *
+ * ERODE
+ * Reduces the light areas. No parameter is used.
+ *
+ * DILATE
+ * Increases the light areas. No parameter is used.
+ *
+ * filter() does not work in WEBGL mode.
+ * A similar effect can be achieved in WEBGL mode using custom
+ * shaders. Adam Ferriss has written
+ * a selection of shader examples that contains many
+ * of the effects present in the filter examples.
+ *
+ * @method filter
+ * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT,
+ * POSTERIZE, BLUR, ERODE, DILATE or BLUR.
+ * See Filters.js for docs on
+ * each available filter
+ * @param {Number} [filterParam] an optional parameter unique
+ * to each filter, see above
+ *
+ * @example
+ *
+ *
+ * @alt
+ * black and white image of a brick wall.
+ * greyscale image of a brickwall
+ * image of a brickwall
+ * jade colored image of a brickwall
+ * red and pink image of a brickwall
+ * image of a brickwall
+ * blurry image of a brickwall
+ * image of a brickwall
+ * image of a brickwall with less detail
+ */
+ _main.default.prototype.filter = function (operation, value) {
+ _main.default._validateParameters('filter', arguments);
+ if (this.canvas !== undefined) {
+ _filters.default.apply(this.canvas, _filters.default[operation], value);
+ } else {
+ _filters.default.apply(this.elt, _filters.default[operation], value);
+ }
+ };
+ /**
+ * Get a region of pixels, or a single pixel, from the canvas.
+ *
+ * Returns an array of [R,G,B,A] values for any pixel or grabs a section of
+ * an image. If no parameters are specified, the entire image is returned.
+ * Use the x and y parameters to get the value of one pixel. Get a section of
+ * the display window by specifying additional w and h parameters. When
+ * getting an image, the x and y parameters define the coordinates for the
+ * upper-left corner of the image, regardless of the current imageMode().
+ *
+ * Getting the color of a single pixel with get(x, y) is easy, but not as fast
+ * as grabbing the data directly from pixels[]. The equivalent statement to
+ * get(x, y) using pixels[] with pixel density d is
+ * ```javascript
+ * let x, y, d; // set these to the coordinates
+ * let off = (y * width + x) * d * 4;
+ * let components = [
+ * pixels[off],
+ * pixels[off + 1],
+ * pixels[off + 2],
+ * pixels[off + 3]
+ * ];
+ * print(components);
+ * ```
+ * See the reference for pixels[] for more information.
+ *
+ * If you want to extract an array of colors or a subimage from an p5.Image object,
+ * take a look at p5.Image.get()
+ *
+ * @method get
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number} w width
+ * @param {Number} h height
+ * @return {p5.Image} the rectangle p5.Image
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * let c = get();
+ * image(c, width / 2, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 images of the rocky mountains, side-by-side
+ * Image of the rocky mountains with 50×50 green rect in center of canvas
+ */
+ /**
+ * @method get
+ * @return {p5.Image} the whole p5.Image
+ */
+ /**
+ * @method get
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number[]} color of 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 pixel data for the display window into the pixels[] array. This
+ * function must always be called before reading from or writing to pixels[].
+ * Note that only changes made with set() or direct manipulation of pixels[]
+ * will occur.
+ *
+ * @method loadPixels
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * image(img, 0, 0, width, height);
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height * d / 2);
+ * loadPixels();
+ * for (let i = 0; i < halfImage; i++) {
+ * pixels[i + halfImage] = pixels[i];
+ * }
+ * updatePixels();
+ * }
+ *
+ *
+ *
+ * @alt
+ * two images of the rocky mountains. one on top, one on bottom of canvas.
+ */
+ _main.default.prototype.loadPixels = function () {
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
+ args[_key3] = arguments[_key3];
+ }
+ _main.default._validateParameters('loadPixels', args);
+ this._renderer.loadPixels();
+ };
+ /**
+ * Changes the color of any pixel, or writes an image directly to the
+ * display window.
+ * The x and y parameters specify the pixel to change and the c parameter
+ * specifies the color value. This can be a p5.Color object, or [R, G, B, A]
+ * pixel array. It can also be a single grayscale value.
+ * When setting an image, the x and y parameters define the coordinates for
+ * the upper-left corner of the image, regardless of the current imageMode().
+ *
+ * After using set(), you must call updatePixels() for your changes to appear.
+ * This should be called once all pixels have been set, and must be called before
+ * calling .get() or drawing the image.
+ *
+ * Setting the color of a single pixel with set(x, y) is easy, but not as
+ * fast as putting the data directly into pixels[]. Setting the pixels[]
+ * values directly may be complicated when working with a retina display,
+ * but will perform better when lots of pixels need to be set directly on
+ * every loop. See the reference for pixels[] for more information.
+ *
+ * @method set
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number|Number[]|Object} c insert a grayscale value | a pixel array |
+ * a p5.Color object | a p5.Image to copy
+ * @example
+ *
+ *
+ * @alt
+ * 4 black points in the shape of a square middle-right of canvas.
+ * square with orangey-brown gradient lightening at bottom right.
+ * image of the rocky mountains. with lines like an 'x' through the center.
+ */
+ _main.default.prototype.set = function (x, y, imgOrCol) {
+ this._renderer.set(x, y, imgOrCol);
+ };
+ /**
+ * Updates the display window with the data in the pixels[] array.
+ * Use in conjunction with loadPixels(). If you're only reading pixels from
+ * the array, there's no need to call updatePixels() — updating is only
+ * necessary to apply changes. updatePixels() should be called anytime the
+ * pixels array is manipulated or set() is called, and only changes made with
+ * set() or direct changes to pixels[] will occur.
+ *
+ * @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;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * image(img, 0, 0, width, height);
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height * d / 2);
+ * loadPixels();
+ * for (let i = 0; i < halfImage; i++) {
+ * pixels[i + halfImage] = pixels[i];
+ * }
+ * updatePixels();
+ * }
+ *
+ *
+ * @alt
+ * two images of the rocky mountains. one on top, one on bottom of canvas.
+ */
+ _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': 276,
+ '../core/main': 290,
+ './filters': 311,
+ 'core-js/modules/es.array.filter': 171
+ }
+ ],
+ 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.concat');
+ _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.last-index-of');
+ _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.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.index-of');
+ _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.array.splice');
+ _dereq_('core-js/modules/es.function.name');
+ _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);
+ } /**
+ * Loads a JSON file from a file or a URL, and returns an Object.
+ * Note that even if the JSON file contains an Array, an Object will be
+ * returned with index numbers as keys.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. JSONP is supported via a polyfill and you
+ * can pass in as the second argument an object with definitions of the json
+ * callback following the syntax specified here.
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadJSON
+ * @param {String} path name of the file or url to load
+ * @param {Object} [jsonpOptions] options object for jsonp related settings
+ * @param {String} [datatype] "json" or "jsonp"
+ * @param {function} [callback] function to be executed after
+ * loadJSON() 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 {Object|Array} JSON data
+ * @example
+ *
+ * Calling loadJSON() inside preload() guarantees to complete the
+ * operation before setup() and draw() are called.
+ *
+ *
+ * // 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/earthquakes/feed/v1.0/' +
+ * 'summary/all_day.geojson';
+ * earthquakes = loadJSON(url);
+ * }
+ *
+ * function setup() {
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * 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);
+ * describe(`50×50 ellipse that changes from black to white
+ * depending on the current humidity`);
+ * }
+ *
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ * function setup() {
+ * noLoop();
+ * let url =
+ 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +
+ * 'summary/all_day.geojson';
+ * loadJSON(url, drawEarthquake);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * describe(`50×50 ellipse that changes from black to white
+ * depending on the current humidity`);
+ * }
+ *
+ * function drawEarthquake(earthquakes) {
+ * // 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);
+ * }
+ *
+ */
+ /**
+ * @method loadJSON
+ * @param {String} path
+ * @param {String} datatype
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ * @return {Object|Array}
+ */
+ /**
+ * @method loadJSON
+ * @param {String} path
+ * @param {function} callback
+ * @param {function} [errorCallback]
+ * @return {Object|Array}
+ */
+
+ _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;
+ };
+ /**
+ * Reads the contents of a file and creates a String array of its individual
+ * lines. If the name of the file is used as the parameter, as in the above
+ * example, the file must be located in the sketch directory/folder.
+ *
+ * Alternatively, the file maybe be loaded from anywhere on the local
+ * computer using an absolute path (something that starts with / on Unix and
+ * Linux, or a drive letter on Windows), or the filename parameter can be a
+ * URL for a file found on a network.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed.
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadStrings
+ * @param {String} filename name of the file or url to load
+ * @param {function} [callback] function to be executed after loadStrings()
+ * completes, Array 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 {String[]} Array of Strings
+ * @example
+ *
+ * Calling loadStrings() inside preload() guarantees to complete the
+ * operation before setup() and draw() are called.
+ *
+ *
+ * let result;
+ * function preload() {
+ * result = loadStrings('assets/test.txt');
+ * }
+
+ * function setup() {
+ * background(200);
+ * text(random(result), 10, 10, 80, 80);
+ * describe(`randomly generated text from a file,
+ * for example "i smell like butter"`);
+ * }
+ *
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ *
+ * function setup() {
+ * loadStrings('assets/test.txt', pickString);
+ * describe(`randomly generated text from a file,
+ * for example "i have three feet"`);
+ * }
+ *
+ * function pickString(result) {
+ * background(200);
+ * text(random(result), 10, 10, 80, 80);
+ * }
+ *
+ */
+ _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) {
+ var ret = {
+ };
+ headers = headers || [
+ ];
+ if (typeof headers === 'undefined') {
+ for (var j = 0; j < row.length; j++) {
+ headers[j.toString()] = j;
+ }
+ }
+ for (var i = 0; i < headers.length; i++) {
+ var key = headers[i];
+ var val = row[i];
+ ret[key] = val;
+ }
+ return ret;
+ } /**
+ * Reads the contents of a file and creates an XML object with its values.
+ * If the name of the file is used as the parameter, as in the above example,
+ * the file must be located in the sketch directory/folder.
+ *
+ * Alternatively, the file maybe be loaded from anywhere on the local
+ * computer using an absolute path (something that starts with / on Unix and
+ * Linux, or a drive letter on Windows), or the filename parameter can be a
+ * URL for a file found on a network.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. Calling loadXML() 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.
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadXML
+ * @param {String} filename name of the file or URL to load
+ * @param {function} [callback] function to be executed after loadXML()
+ * completes, XML object 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 {Object} XML object containing data
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let children = xml.getChildren('animal');
+ *
+ * for (let i = 0; i < children.length; i++) {
+ * let id = children[i].getNum('id');
+ * let coloring = children[i].getString('species');
+ * let name = children[i].getContent();
+ * print(id + ', ' + coloring + ', ' + name);
+ * }
+ * describe('no image displayed');
+ * }
+ *
+ * // Sketch prints:
+ * // 0, Capra hircus, Goat
+ * // 1, Panthera pardus, Leopard
+ * // 2, Equus zebra, Zebra
+ *
+ */
+
+ _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 () {
+ _main.default._validateParameters('httpGet', arguments);
+ var args = Array.prototype.slice.call(arguments);
+ 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 () {
+ _main.default._validateParameters('httpPost', arguments);
+ var args = Array.prototype.slice.call(arguments);
+ 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 = [
+ ];
+ /**
+ * @method createWriter
+ * @param {String} name name of the file to be created
+ * @param {String} [extension]
+ * @return {p5.PrintWriter}
+ * @example
+ *
+ */
+ _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;
+ };
+ /**
+ * @class p5.PrintWriter
+ * @param {String} filename
+ * @param {String} [extension]
+ */
+ _main.default.PrintWriter = function (filename, extension) {
+ var self = this;
+ this.name = filename;
+ this.content = ''; //Changed to write because it was being overloaded by function below.
+ /**
+ * Writes data to the PrintWriter stream
+ * @method write
+ * @param {Array} data all data to be written by the PrintWriter
+ * @example
+ *
+ *
+ * // creates a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // write 'Hello world!'' to the file
+ * writer.write(['Hello world!']);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // creates a file called 'newFile2.txt'
+ * let writer = createWriter('newFile2.txt');
+ * // write 'apples,bananas,123' to the file
+ * writer.write(['apples', 'bananas', 123]);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // creates a file called 'newFile3.txt'
+ * let writer = createWriter('newFile3.txt');
+ * // write 'My name is: Teddy' to the file
+ * writer.write('My name is:');
+ * writer.write(' Teddy');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * button = createButton('SAVE FILE');
+ * button.position(21, 40);
+ * button.mousePressed(createFile);
+ * }
+ *
+ * function createFile() {
+ * // creates a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // write 'Hello world!'' to the file
+ * writer.write(['Hello world!']);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ * }
+ *
+ *
+ */
+ this.write = function (data) {
+ this.content += data;
+ };
+ /**
+ * Writes data to the PrintWriter stream, and adds a new line at the end
+ * @method print
+ * @param {Array} data all data to be printed by the PrintWriter
+ * @example
+ *
+ *
+ * // creates a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // creates a file containing
+ * // My name is:
+ * // Teddy
+ * writer.print('My name is:');
+ * writer.print('Teddy');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ * // create a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // create a file called 'newFile2.txt'
+ * let writer = createWriter('newFile2.txt');
+ * // write some data to the file
+ * writer.write([100, 101, 102]);
+ * // close the PrintWriter and save the file
+ * writer.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]);
+ }
+ }
+ }
+ };
+ /**
+ * Writes the contents of an Array or a JSON object to a .json file.
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveJSON
+ * @param {Array|Object} json
+ * @param {String} filename
+ * @param {Boolean} [optimize] If true, removes line breaks
+ * and spaces from the output
+ * file to optimize filesize
+ * (but not readability).
+ * @example
+ *
+ */
+ _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;
+ /**
+ * Writes an array of Strings to a text file, one line per String.
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveStrings
+ * @param {String[]} list string array to be written
+ * @param {String} filename filename for output
+ * @param {String} [extension] the filename's extension
+ * @param {Boolean} [isCRLF] if true, change line-break to CRLF
+ * @example
+ *
+ * let words = 'apple bear cat dog';
+ *
+ * // .split() outputs an Array
+ * let list = split(words, ' ');
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * text('click here to save', 10, 10, 70, 80);
+ * describe('no image displayed');
+ * }
+ *
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
+ * saveStrings(list, 'nouns.txt');
+ * }
+ * }
+ *
+ * // Saves the following to a file called 'nouns.txt':
+ * //
+ * // apple
+ * // bear
+ * // cat
+ * // dog
+ *
+ */
+ _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(str);
+ pWriter.print('');
+ 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('
'.concat(e));
+ 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('
'.concat(htmlEntry));
+ pWriter.print('
');
+ }
+ pWriter.print('
');
+ }
+ 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 () {
+ var x = Object.prototype.toString.call(window.HTMLElement);
+ return x.indexOf('Constructor') > 0;
+ };
+ /**
+ * 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': 281,
+ '../core/friendly_errors/file_errors': 282,
+ '../core/friendly_errors/validate_params': 285,
+ '../core/main': 290,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.includes': 174,
+ 'core-js/modules/es.array.index-of': 175,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.last-index-of': 178,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.array.splice': 182,
+ 'core-js/modules/es.function.name': 183,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.promise': 196,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.includes': 203,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.replace': 207,
+ 'core-js/modules/es.string.split': 209,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.typed-array.copy-within': 215,
+ 'core-js/modules/es.typed-array.every': 216,
+ 'core-js/modules/es.typed-array.fill': 217,
+ 'core-js/modules/es.typed-array.filter': 218,
+ 'core-js/modules/es.typed-array.find': 220,
+ 'core-js/modules/es.typed-array.find-index': 219,
+ 'core-js/modules/es.typed-array.for-each': 223,
+ 'core-js/modules/es.typed-array.includes': 224,
+ 'core-js/modules/es.typed-array.index-of': 225,
+ 'core-js/modules/es.typed-array.iterator': 228,
+ 'core-js/modules/es.typed-array.join': 229,
+ 'core-js/modules/es.typed-array.last-index-of': 230,
+ 'core-js/modules/es.typed-array.map': 231,
+ 'core-js/modules/es.typed-array.reduce': 233,
+ 'core-js/modules/es.typed-array.reduce-right': 232,
+ 'core-js/modules/es.typed-array.reverse': 234,
+ 'core-js/modules/es.typed-array.set': 235,
+ 'core-js/modules/es.typed-array.slice': 236,
+ 'core-js/modules/es.typed-array.some': 237,
+ 'core-js/modules/es.typed-array.sort': 238,
+ 'core-js/modules/es.typed-array.subarray': 239,
+ 'core-js/modules/es.typed-array.to-locale-string': 240,
+ 'core-js/modules/es.typed-array.to-string': 241,
+ 'core-js/modules/es.typed-array.uint8-array': 244,
+ 'core-js/modules/web.dom-collections.iterator': 248,
+ 'core-js/modules/web.url': 250,
+ 'es6-promise/auto': 251,
+ 'fetch-jsonp': 253,
+ 'file-saver': 254,
+ 'whatwg-fetch': 267
+ }
+ ],
+ 317: [
+ 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.string.trim');
+ _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.string.trim');
+ 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 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 = function (rows) {
+ /**
+ * An array containing the names of the columns in the table, if the "header" the table is
+ * loaded with the "header" parameter.
+ * @property columns {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() {
+ * //print the column names
+ * for (let c = 0; c < table.getColumnCount(); c++) {
+ * print('column ' + c + ' is named ' + table.columns[c]);
+ * }
+ * }
+ *
+ *
+ */
+ this.columns = [
+ ];
+ /**
+ * An array containing the p5.TableRow objects that make up the
+ * rows of the table. The same result as calling getRows()
+ * @property rows {p5.TableRow[]}
+ */
+ this.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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.addRow = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.removeRow = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getRow = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getRows = function () {
+ 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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.findRow = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.findRows = function (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"
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.matchRow = function (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
+ *
+ */
+ _main.default.Table.prototype.matchRows = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getColumn = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.clearRows = function () {
+ 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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.addColumn = function (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);
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getColumnCount = function () {
+ 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);
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getRowCount = function () {
+ 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
+ *
+ */
+ _main.default.Table.prototype.removeTokens = function (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
+ *
+ */
+ _main.default.Table.prototype.trim = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.removeColumn = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.set = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.setNum = function (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');
+ * }
+ *
+ */
+ _main.default.Table.prototype.setString = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.get = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getNum = function (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
+ *
+ */
+ _main.default.Table.prototype.getString = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getObject = function (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');
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getArray = function () {
+ var tableArray = [
+ ];
+ for (var i = 0; i < this.rows.length; i++) {
+ tableArray.push(this.rows[i].arr);
+ }
+ return tableArray;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/main': 290,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.index-of': 175,
+ 'core-js/modules/es.array.join': 177,
+ 'core-js/modules/es.array.splice': 182,
+ 'core-js/modules/es.regexp.constructor': 198,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.match': 205,
+ 'core-js/modules/es.string.replace': 207,
+ 'core-js/modules/es.string.trim': 211
+ }
+ ],
+ 318: [
+ function (_dereq_, module, exports) {
+ 'use strict';
+ _dereq_('core-js/modules/es.array.index-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.split');
+ _dereq_('core-js/modules/es.array.index-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.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 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 = function (str, separator) {
+ var arr = [
+ ];
+ var obj = {
+ };
+ if (str) {
+ separator = separator || ',';
+ arr = str.split(separator);
+ }
+ for (var i = 0; i < arr.length; i++) {
+ var key = i;
+ var val = arr[i];
+ obj[key] = val;
+ }
+ this.arr = arr;
+ this.obj = obj;
+ 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');
+ * }
+ *
+ */
+ _main.default.TableRow.prototype.set = function (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');
+ * }
+ *
+ */
+ _main.default.TableRow.prototype.setNum = function (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');
+ * }
+ *
+ */
+ _main.default.TableRow.prototype.setString = function (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');
+ * }
+ *
+ */
+ _main.default.TableRow.prototype.get = function (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');
+ * }
+ *
+ */
+ _main.default.TableRow.prototype.getNum = function (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');
+ * }
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let children = xml.getChildren('animal');
+ *
+ * for (let i = 0; i < children.length; i++) {
+ * let id = children[i].getNum('id');
+ * let coloring = children[i].getString('species');
+ * let name = children[i].getContent();
+ * print(id + ', ' + coloring + ', ' + name);
+ * }
+ *
+ * describe('no image displayed');
+ * }
+ *
+ * // Sketch prints:
+ * // 0, Capra hircus, Goat
+ * // 1, Panthera pardus, Leopard
+ * // 2, Equus zebra, Zebra
+ *
+ */
+
+ _main.default.XML = function (DOM) {
+ if (!DOM) {
+ var xmlDoc = document.implementation.createDocument(null, 'doc');
+ this.DOM = xmlDoc.createElement('root');
+ } else {
+ this.DOM = DOM;
+ }
+ };
+ /**
+ * Gets a copy of the element's parent. Returns the parent as another
+ * p5.XML object.
+ *
+ * @method getParent
+ * @return {p5.XML} element parent
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let children = xml.getChildren('animal');
+ * let parent = children[1].getParent();
+ * print(parent.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ *
+ */
+ _main.default.XML.prototype.getParent = function () {
+ return new _main.default.XML(this.DOM.parentElement);
+ };
+ /**
+ * Gets the element's full name, which is returned as a String.
+ *
+ * @method getName
+ * @return {String} the name of the node
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ *
+ */
+ _main.default.XML.prototype.getName = function () {
+ return this.DOM.tagName;
+ };
+ /**
+ * Sets the element's name, which is specified as a String.
+ *
+ * @method setName
+ * @param {String} the new name of the node
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.getName());
+ * xml.setName('fish');
+ * print(xml.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ * // fish
+ *
+ */
+ _main.default.XML.prototype.setName = function (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.nodeValue);
+ }
+ this.DOM = newDOM;
+ };
+ /**
+ * Checks whether or not the element has any children, and returns the result
+ * as a boolean.
+ *
+ * @method hasChildren
+ * @return {boolean}
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.hasChildren());
+ * }
+ *
+ * // Sketch prints:
+ * // true
+ *
+ */
+ _main.default.XML.prototype.hasChildren = function () {
+ return this.DOM.children.length > 0;
+ };
+ /**
+ * Get the names of all of the element's children, and returns the names as an
+ * array of Strings. This is the same as looping through and calling getName()
+ * on each child element individually.
+ *
+ * @method listChildren
+ * @return {String[]} names of the children of the element
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.listChildren());
+ * }
+ *
+ * // Sketch prints:
+ * // ["animal", "animal", "animal"]
+ *
+ */
+ _main.default.XML.prototype.listChildren = function () {
+ var arr = [
+ ];
+ for (var i = 0; i < this.DOM.childNodes.length; i++) {
+ arr.push(this.DOM.childNodes[i].nodeName);
+ }
+ return arr;
+ };
+ /**
+ * Returns all of the element's children as an array of p5.XML objects. When
+ * the name parameter is specified, then it will return all children that match
+ * that name.
+ *
+ * @method getChildren
+ * @param {String} [name] element name
+ * @return {p5.XML[]} children of the element
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let animals = xml.getChildren('animal');
+ *
+ * for (let i = 0; i < animals.length; i++) {
+ * print(animals[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Leopard"
+ * // "Zebra"
+ *
+ */
+ _main.default.XML.prototype.getChildren = function (param) {
+ if (param) {
+ return elementsToP5XML(this.DOM.getElementsByTagName(param));
+ } else {
+ return elementsToP5XML(this.DOM.children);
+ }
+ };
+ function elementsToP5XML(elements) {
+ var arr = [
+ ];
+ for (var i = 0; i < elements.length; i++) {
+ arr.push(new _main.default.XML(elements[i]));
+ }
+ return arr;
+ } /**
+ * Returns the first of the element's children that matches the name parameter
+ * or the child of the given index.It returns undefined if no matching
+ * child is found.
+ *
+ * @method getChild
+ * @param {String|Integer} name element name or index
+ * @return {p5.XML}
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ *
+ */
+
+ _main.default.XML.prototype.getChild = function (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]);
+ }
+ };
+ /**
+ * Appends a new child to the element. The child can be specified with
+ * either a String, which will be used as the new tag's name, or as a
+ * reference to an existing p5.XML object.
+ * A reference to the newly created child is returned as an p5.XML object.
+ *
+ * @method addChild
+ * @param {p5.XML} node a p5.XML Object which will be the child to be added
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let child = new p5.XML();
+ * child.setName('animal');
+ * child.setAttribute('id', '3');
+ * child.setAttribute('species', 'Ornithorhynchus anatinus');
+ * child.setContent('Platypus');
+ * xml.addChild(child);
+ *
+ * let animals = xml.getChildren('animal');
+ * print(animals[animals.length - 1].getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Leopard"
+ * // "Zebra"
+ *
+ */
+ _main.default.XML.prototype.addChild = function (node) {
+ if (node instanceof _main.default.XML) {
+ this.DOM.appendChild(node.DOM);
+ } else { // PEND
+ }
+ };
+ /**
+ * Removes the element specified by name or index.
+ *
+ * @method removeChild
+ * @param {String|Integer} name element name or index
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * xml.removeChild('animal');
+ * let children = xml.getChildren();
+ * for (let i = 0; i < children.length; i++) {
+ * print(children[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Leopard"
+ * // "Zebra"
+ *
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * xml.removeChild(1);
+ * let children = xml.getChildren();
+ * for (let i = 0; i < children.length; i++) {
+ * print(children[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Zebra"
+ *
+ */
+ _main.default.XML.prototype.removeChild = function (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]);
+ }
+ };
+ /**
+ * Counts the specified element's number of attributes, returned as an Number.
+ *
+ * @method getAttributeCount
+ * @return {Integer}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getAttributeCount());
+ * }
+ *
+ * // Sketch prints:
+ * // 2
+ *
+ */
+ _main.default.XML.prototype.getAttributeCount = function () {
+ return this.DOM.attributes.length;
+ };
+ /**
+ * Gets all of the specified element's attributes, and returns them as an
+ * array of Strings.
+ *
+ * @method listAttributes
+ * @return {String[]} an array of strings containing the names of attributes
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.listAttributes());
+ * }
+ *
+ * // Sketch prints:
+ * // ["id", "species"]
+ *
+ */
+ _main.default.XML.prototype.listAttributes = function () {
+ 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;
+ };
+ /**
+ * Checks whether or not an element has the specified attribute.
+ *
+ * @method hasAttribute
+ * @param {String} the attribute to be checked
+ * @return {boolean} true if attribute found else false
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.hasAttribute('species'));
+ * print(firstChild.hasAttribute('color'));
+ * }
+ *
+ * // Sketch prints:
+ * // true
+ * // false
+ *
+ */
+ _main.default.XML.prototype.hasAttribute = function (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;
+ };
+ /**
+ * Returns an attribute value of the element as an Number. If the defaultValue
+ * parameter is specified and the attribute doesn't exist, then defaultValue
+ * is returned. If no defaultValue is specified and the attribute doesn't
+ * exist, the value 0 is returned.
+ *
+ * @method getNum
+ * @param {String} name the non-null full name of the attribute
+ * @param {Number} [defaultValue] the default value of the attribute
+ * @return {Number}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getNum('id'));
+ * }
+ *
+ * // Sketch prints:
+ * // 0
+ *
+ */
+ _main.default.XML.prototype.getNum = function (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;
+ };
+ /**
+ * Returns an attribute value of the element as an String. If the defaultValue
+ * parameter is specified and the attribute doesn't exist, then defaultValue
+ * is returned. If no defaultValue is specified and the attribute doesn't
+ * exist, null is returned.
+ *
+ * @method getString
+ * @param {String} name the non-null full name of the attribute
+ * @param {Number} [defaultValue] the default value of the attribute
+ * @return {String}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getString('species'));
+ * }
+ *
+ * // Sketch prints:
+ * // "Capra hircus"
+ *
+ */
+ _main.default.XML.prototype.getString = function (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 the content of an element's attribute. The first parameter specifies
+ * the attribute name, while the second specifies the new content.
+ *
+ * @method setAttribute
+ * @param {String} name the full name of the attribute
+ * @param {Number|String|Boolean} value the value of the attribute
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getString('species'));
+ * firstChild.setAttribute('species', 'Jamides zebra');
+ * print(firstChild.getString('species'));
+ * }
+ *
+ * // Sketch prints:
+ * // "Capra hircus"
+ * // "Jamides zebra"
+ *
+ */
+ _main.default.XML.prototype.setAttribute = function (name, value) {
+ this.DOM.setAttribute(name, value);
+ };
+ /**
+ * Returns the content of an element. If there is no such content,
+ * defaultValue is returned if specified, otherwise null is returned.
+ *
+ * @method getContent
+ * @param {String} [defaultValue] value returned if no content is found
+ * @return {String}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ *
+ */
+ _main.default.XML.prototype.getContent = function (defaultValue) {
+ var str;
+ str = this.DOM.textContent;
+ str = str.replace(/\s\s+/g, ',');
+ return str || defaultValue || null;
+ };
+ /**
+ * Sets the element's content.
+ *
+ * @method setContent
+ * @param {String} text the new content
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * firstChild.setContent('Mountain Goat');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Mountain Goat"
+ *
+ */
+ _main.default.XML.prototype.setContent = function (content) {
+ if (!this.DOM.children.length) {
+ this.DOM.textContent = content;
+ }
+ };
+ /**
+ * Serializes the element into a string. This function is useful for preparing
+ * the content to be sent over a http request or saved to file.
+ *
+ * @method serialize
+ * @return {String} Serialized string of the element
+ * @example
+ *
+ */
+ _main.default.XML.prototype.serialize = function () {
+ var xmlSerializer = new XMLSerializer();
+ return xmlSerializer.serializeToString(this.DOM);
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/main': 290,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.number.constructor': 187,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.replace': 207,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 320: [
+ function (_dereq_, module, exports) {
+ 'use strict';
+ _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');
+ _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
+ };
+ } /**
+ * @module Math
+ * @submodule Calculation
+ * @for p5
+ * @requires core
+ */
+ /**
+ * Calculates the absolute value (magnitude) of a number. Maps to Math.abs().
+ * 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() {
+ * let x = -3;
+ * let y = abs(x);
+ *
+ * print(x); // -3
+ * print(y); // 3
+ *
+ * describe('no image displayed');
+ * }
+ *
+ */
+
+ _main.default.prototype.abs = Math.abs;
+ /**
+ * Calculates the closest int value that is greater than or equal to the
+ * value of the parameter. Maps to Math.ceil(). For example, ceil(9.03)
+ * returns the value 10.
+ *
+ * @method ceil
+ * @param {Number} n number to round up
+ * @return {Integer} rounded up number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * // map, mouseX between 0 and 5.
+ * let ax = map(mouseX, 0, 100, 0, 5);
+ * let ay = 66;
+ *
+ * //Get the ceiling of the mapped number.
+ * let bx = ceil(map(mouseX, 0, 100, 0, 5));
+ * let by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ *
+ * describe(`2 horizontal lines & number sets. increase with
+ * mouse x. bottom to 2 decimals`);
+ * }
+ *
+ */
+ _main.default.prototype.ceil = Math.ceil;
+ /**
+ * Constrains a value 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 draw() {
+ * background(200);
+ *
+ * let leftWall = 25;
+ * let rightWall = 75;
+ *
+ * // xm is just the mouseX, while
+ * // xc is the mouseX, but constrained
+ * // between the leftWall and rightWall!
+ * let xm = mouseX;
+ * let xc = constrain(mouseX, leftWall, rightWall);
+ *
+ * // Draw the walls.
+ * stroke(150);
+ * line(leftWall, 0, leftWall, height);
+ * line(rightWall, 0, rightWall, height);
+ *
+ * // Draw xm and xc as circles.
+ * noStroke();
+ * fill(150);
+ * ellipse(xm, 33, 9, 9); // Not Constrained
+ * fill(0);
+ * ellipse(xc, 66, 9, 9); // Constrained
+ *
+ * describe(`2 vertical lines. 2 ellipses move with mouse X,
+ * 1 does not move past lines`);
+ * }
+ *
+ */
+ _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, in either two or three dimensions.
+ * If you looking for distance between two vectors see p5.Vector.dist()
+ *
+ * @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
+ *
+ * // Move your mouse inside the canvas to see the
+ * // change in distance between two points!
+ * function draw() {
+ * background(200);
+ * fill(0);
+ *
+ * let x1 = 10;
+ * let y1 = 90;
+ * let x2 = mouseX;
+ * let y2 = mouseY;
+ *
+ * line(x1, y1, x2, y2);
+ * ellipse(x1, y1, 7, 7);
+ * ellipse(x2, y2, 7, 7);
+ *
+ * // d is the length of the line
+ * // the distance from point 1 to point 2.
+ * let d = dist(x1, y1, x2, y2);
+ *
+ * // Let's write d along the line we are drawing!
+ * push();
+ * translate((x1 + x2) / 2, (y1 + y2) / 2);
+ * rotate(atan2(y2 - y1, x2 - x1));
+ * text(nfc(d, 1), 0, -5);
+ * pop();
+ * // Fancy!
+ *
+ * describe(`2 ellipses joined by line. 1 ellipse moves with
+ * mouse X&Y. Distance displayed.`);
+ * }
+ *
+ */
+ /**
+ * @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 hypot(args[2] - args[0], args[3] - args[1]);
+ } else if (args.length === 6) {
+ //3D
+ return hypot(args[3] - args[0], args[4] - args[1], args[5] - args[2]);
+ }
+ };
+ /**
+ * Returns Euler's number e (2.71828...) raised to the power of the n
+ * parameter. Maps to Math.exp().
+ *
+ * @method exp
+ * @param {Number} n exponent to raise
+ * @return {Number} e^n
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // Compute the exp() function with a value between 0 and 2
+ * let xValue = map(mouseX, 0, width, 0, 2);
+ * let yValue = exp(xValue);
+ *
+ * let y = map(yValue, 0, 8, height, 0);
+ *
+ * let legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4);
+ * stroke(150);
+ * line(mouseX, y, mouseX, height);
+ * fill(0);
+ * text(legend, 5, 15);
+ * noStroke();
+ * ellipse(mouseX, y, 7, 7);
+ *
+ * // Draw the exp(x) curve,
+ * // over the domain of x from 0 to 2
+ * noFill();
+ * stroke(0);
+ * beginShape();
+ * for (let x = 0; x < width; x++) {
+ * xValue = map(x, 0, width, 0, 2);
+ * yValue = exp(xValue);
+ * y = map(yValue, 0, 8, height, 0);
+ * vertex(x, y);
+ * }
+ *
+ * endShape();
+ * line(0, 0, 0, height);
+ * line(0, height - 1, width, height - 1);
+ *
+ * describe('ellipse moves along a curve with mouse x. e^n displayed.');
+ * }
+ *
+ */
+ _main.default.prototype.exp = Math.exp;
+ /**
+ * Calculates the closest int value that is less than or equal to the
+ * value of the parameter. Maps to Math.floor().
+ *
+ * @method floor
+ * @param {Number} n number to round down
+ * @return {Integer} rounded down number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * //map, mouseX between 0 and 5.
+ * let ax = map(mouseX, 0, 100, 0, 5);
+ * let ay = 66;
+ *
+ * //Get the floor of the mapped number.
+ * let bx = floor(map(mouseX, 0, 100, 0, 5));
+ * let by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ *
+ * describe(`2 horizontal lines & number sets.
+ * increase with mouse x. bottom to 2 decimals`);
+ * }
+ *
+ */
+ _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 values where 0.0
+ * is equal to the first point, 0.1 is very near the first point, 0.5 is
+ * half-way in between, and 1.0 is equal to the second point. If the
+ * value of amt is more than 1.0 or less than 0.0, the number will be
+ * calculated accordingly in the ratio of the two given numbers. The lerp()
+ * function is convenient for creating motion along a straight
+ * path and for drawing dotted lines.
+ *
+ * @method lerp
+ * @param {Number} start first value
+ * @param {Number} stop second value
+ * @param {Number} amt number
+ * @return {Number} lerped value
+ * @example
+ *
+ * function setup() {
+ * background(200);
+ * 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);
+ *
+ * let y = 50;
+ *
+ * strokeWeight(5);
+ * stroke(0); // Draw the original points in black
+ * point(a, y);
+ * point(b, y);
+ *
+ * stroke(100); // Draw the lerp points in gray
+ * point(c, y);
+ * point(d, y);
+ * point(e, y);
+ *
+ * describe(`5 points horizontally staggered mid-canvas.
+ * mid 3 are grey, outer black`);
+ * }
+ *
+ */
+ _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. This
+ * function expects the n parameter to be a value greater than 0.0. Maps to
+ * Math.log().
+ *
+ * @method log
+ * @param {Number} n number greater than 0
+ * @return {Number} natural logarithm of n
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * let maxX = 2.8;
+ * let maxY = 1.5;
+ *
+ * // Compute the natural log of a value between 0 and maxX
+ * let xValue = map(mouseX, 0, width, 0, maxX);
+ * let yValue, y;
+ * if (xValue > 0) {
+ // Cannot take the log of a negative number.
+ * yValue = log(xValue);
+ * y = map(yValue, -maxY, maxY, height, 0);
+ *
+ * // Display the calculation occurring.
+ * let legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3);
+ * stroke(150);
+ * line(mouseX, y, mouseX, height);
+ * fill(0);
+ * text(legend, 5, 15);
+ * noStroke();
+ * ellipse(mouseX, y, 7, 7);
+ * }
+ *
+ * // Draw the log(x) curve,
+ * // over the domain of x from 0 to maxX
+ * noFill();
+ * stroke(0);
+ * beginShape();
+ * for (let x = 0; x < width; x++) {
+ * xValue = map(x, 0, width, 0, maxX);
+ * yValue = log(xValue);
+ * y = map(yValue, -maxY, maxY, height, 0);
+ * vertex(x, y);
+ * }
+ * endShape();
+ * line(0, 0, 0, height);
+ * line(0, height / 2, width, height / 2);
+ *
+ * describe(`ellipse moves along a curve with mouse x.
+ * natural logarithm of n displayed.`);
+ * }
+ *
+ */
+ _main.default.prototype.log = Math.log;
+ /**
+ * Calculates the magnitude (or length) of a vector. A vector is a direction
+ * in space commonly used in computer graphics and linear algebra. Because it
+ * has no "start" position, the magnitude of a vector can be thought of as
+ * the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is
+ * a shortcut for writing dist(0, 0, x, y).
+ *
+ * @method mag
+ * @param {Number} a first value
+ * @param {Number} b second value
+ * @return {Number} magnitude of vector from (0,0) to (a,b)
+ * @example
+ *
+ * function setup() {
+ * let x1 = 20;
+ * let x2 = 80;
+ * let y1 = 30;
+ * let y2 = 70;
+ *
+ * line(0, 0, x1, y1);
+ * print(mag(x1, y1)); // Prints "36.05551275463989"
+ * line(0, 0, x2, y1);
+ * print(mag(x2, y1)); // Prints "85.44003745317531"
+ * line(0, 0, x1, y2);
+ * print(mag(x1, y2)); // Prints "72.80109889280519"
+ * line(0, 0, x2, y2);
+ * print(mag(x2, y2)); // Prints "106.3014581273465"
+ *
+ * describe('4 lines of different length radiate from top left of canvas.');
+ * }
+ *
+ */
+ _main.default.prototype.mag = function (x, y) {
+ _main.default._validateParameters('mag', arguments);
+ return hypot(x, y);
+ };
+ /**
+ * Re-maps a number from one range to another.
+ *
+ * In the first example above, the number 25 is converted from a value in the
+ * range of 0 to 100 into a value that ranges from the left edge of the
+ * window (0) to the right edge (width).
+ *
+ * @method map
+ * @param {Number} value the incoming value to be converted
+ * @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
+ *
+ * let value = 25;
+ * let m = map(value, 0, 100, 0, width);
+ * ellipse(m, 50, 10, 10);
+ * describe('10×10 white ellipse with in mid left canvas');
+
+ *
+ *
+ * function setup() {
+ * noStroke();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * let x1 = map(mouseX, 0, width, 25, 75);
+ * ellipse(x1, 25, 25, 25);
+ * //This ellipse is constrained to the 0-100 range
+ * //after setting withinBounds to true
+ * let x2 = map(mouseX, 0, width, 0, 100, true);
+ * ellipse(x2, 75, 25, 25);
+ *
+ * describe(`Two 25×25 white ellipses move with mouse x.
+ * Bottom has more range from X`);
+ * }
+
+ */
+ _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);
+ }
+ };
+ /**
+ * Determines the largest value in a sequence of numbers, and then returns
+ * that value. max() accepts any number of Number parameters, or an Array
+ * of any length.
+ *
+ * @method max
+ * @param {Number} n0 Number to compare
+ * @param {Number} n1 Number to compare
+ * @return {Number} maximum Number
+ * @example
+ *
+ * function setup() {
+ * // Change the elements in the array and run the sketch
+ * // to show how max() works!
+ * let numArray = [2, 1, 5, 4, 8, 9];
+ * fill(0);
+ * noStroke();
+ * text('Array Elements', 0, 10);
+ * // Draw all numbers in the array
+ * let spacing = 15;
+ * let elemsY = 25;
+ * for (let i = 0; i < numArray.length; i++) {
+ * text(numArray[i], i * spacing, elemsY);
+ * }
+ * let maxX = 33;
+ * let maxY = 80;
+ * // Draw the Maximum value in the array.
+ * textSize(32);
+ * text(max(numArray), maxX, maxY);
+ *
+ * describe(`Small text at top reads: Array Elements 2 1 5 4 8 9.
+ * Large text at center: 9`);
+ * }
+ *
+ */
+ /**
+ * @method max
+ * @param {Number[]} nums Numbers to compare
+ * @return {Number}
+ */
+ _main.default.prototype.max = function () {
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+ if (args[0] instanceof Array) {
+ return Math.max.apply(null, args[0]);
+ } else {
+ return Math.max.apply(null, args);
+ }
+ };
+ /**
+ * Determines the smallest value in a sequence of numbers, and then returns
+ * that value. min() accepts any number of Number parameters, or an Array
+ * of any length.
+ *
+ * @method min
+ * @param {Number} n0 Number to compare
+ * @param {Number} n1 Number to compare
+ * @return {Number} minimum Number
+ * @example
+ *
+ * function setup() {
+ * // Change the elements in the array and run the sketch
+ * // to show how min() works!
+ * let numArray = [2, 1, 5, 4, 8, 9];
+ * fill(0);
+ * noStroke();
+ * text('Array Elements', 0, 10);
+ * // Draw all numbers in the array
+ * let spacing = 15;
+ * let elemsY = 25;
+ * for (let i = 0; i < numArray.length; i++) {
+ * text(numArray[i], i * spacing, elemsY);
+ * }
+ * let maxX = 33;
+ * let maxY = 80;
+ * // Draw the Minimum value in the array.
+ * textSize(32);
+ * text(min(numArray), maxX, maxY);
+ *
+ * describe(`Small text at top reads: Array Elements 2 1 5 4 8 9.
+ * Large text at center: 1`);
+ * }
+ *
+ */
+ /**
+ * @method min
+ * @param {Number[]} nums Numbers to compare
+ * @return {Number}
+ */
+ _main.default.prototype.min = function () {
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
+ args[_key3] = arguments[_key3];
+ }
+ if (args[0] instanceof Array) {
+ return Math.min.apply(null, args[0]);
+ } else {
+ return Math.min.apply(null, args);
+ }
+ };
+ /**
+ * Normalizes a number from another range into a value between 0 and 1.
+ * Identical to map(value, low, high, 0, 1).
+ * Numbers outside of the range are not clamped to 0 and 1, because
+ * out-of-range values are often intentional and useful. (See the example above.)
+ *
+ * @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 draw() {
+ * background(200);
+ * let currentNum = mouseX;
+ * let lowerBound = 0;
+ * let upperBound = width; //100;
+ * let normalized = norm(currentNum, lowerBound, upperBound);
+ * let lineY = 70;
+ * stroke(3);
+ * line(0, lineY, width, lineY);
+ * //Draw an ellipse mapped to the non-normalized value.
+ * noStroke();
+ * fill(50);
+ * let s = 7; // ellipse size
+ * ellipse(currentNum, lineY, s, s);
+ *
+ * // Draw the guide
+ * let guideY = lineY + 15;
+ * text('0', 0, guideY);
+ * textAlign(RIGHT);
+ * text('100', width, guideY);
+ *
+ * // Draw the normalized value
+ * textAlign(LEFT);
+ * fill(0);
+ * textSize(32);
+ * let normalY = 40;
+ * let normalX = 20;
+ * text(normalized, normalX, normalY);
+ *
+ * describe(`ellipse moves with mouse. 0 shown left, 100 right,
+ * and updating values center`);
+ * }
+ *
+ */
+ _main.default.prototype.norm = function (n, start, stop) {
+ _main.default._validateParameters('norm', arguments);
+ return this.map(n, start, stop, 0, 1);
+ };
+ /**
+ * Facilitates exponential expressions. The pow() function is an efficient
+ * way of multiplying numbers by themselves (or their reciprocals) in large
+ * quantities. For example, pow(3, 5) is equivalent to the expression
+ * 3 × 3 × 3 × 3 × 3 and pow(3, -5) is equivalent to 1 /
+ * 3 × 3 × 3 × 3 × 3. Maps to
+ * Math.pow().
+ *
+ * @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() {
+ * //Exponentially increase the size of an ellipse.
+ * let eSize = 3; // Original Size
+ * let eLoc = 10; // Original Location
+ *
+ * ellipse(eLoc, eLoc, eSize, eSize);
+ *
+ * ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));
+ *
+ * ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));
+ *
+ * ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));
+ *
+ * describe('small to large ellipses radiating from top left of canvas');
+ * }
+ *
+ */
+ _main.default.prototype.pow = Math.pow;
+ /**
+ * Calculates the integer closest to the n parameter. For example,
+ * round(133.8) returns the value 134. Maps to Math.round().
+ *
+ * @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
+ *
+ * let x = round(3.7);
+ * text(x, width / 2, height / 2);
+ * describe('"4" written in middle of canvas');
+ *
+ *
+ * let x = round(12.782383, 2);
+ * text(x, width / 2, height / 2);
+ * describe('"12.78" written in middle of canvas');
+ *
+ *
+ * function draw() {
+ * background(200);
+ * //map, mouseX between 0 and 5.
+ * let ax = map(mouseX, 0, 100, 0, 5);
+ * let ay = 66;
+ *
+ * // Round the mapped number.
+ * let bx = round(map(mouseX, 0, 100, 0, 5));
+ * let by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ *
+ * describe('two horizontal lines rounded values displayed on top.');
+ * }
+ *
+ */
+ _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;
+ };
+ /**
+ * Squares a number (multiplies a number by itself). The result is always a
+ * positive number, as multiplying two negative numbers always yields a
+ * positive result. For example, -1 * -1 = 1.
+ *
+ * @method sq
+ * @param {Number} n number to square
+ * @return {Number} squared number
+ * @example
+ *
+ */
+ _main.default.prototype.sq = function (n) {
+ return n * n;
+ };
+ /**
+ * Calculates the square root of a number. The square root of a number is
+ * always positive, even though there may be a valid negative root. The
+ * square root s of number a is such that s*s = a. It is the opposite of
+ * squaring. Maps to Math.sqrt().
+ *
+ * @method sqrt
+ * @param {Number} n non-negative number to square root
+ * @return {Number} square root of number
+ * @example
+ *
+ */
+ _main.default.prototype.sqrt = Math.sqrt; // Calculate the length of the hypotenuse of a right triangle
+ // This won't under- or overflow in intermediate steps
+ // https://en.wikipedia.org/wiki/Hypot
+ function hypot(x, y, z) {
+ // Use the native implementation if it's available
+ if (typeof Math.hypot === 'function') {
+ return Math.hypot.apply(null, arguments);
+ } // Otherwise use the V8 implementation
+ // https://github.com/v8/v8/blob/8cd3cf297287e581a49e487067f5cbd991b27123/src/js/math.js#L217
+
+ var length = arguments.length;
+ var args = [
+ ];
+ var max = 0;
+ for (var i = 0; i < length; i++) {
+ var n = arguments[i];
+ n = + n;
+ if (n === Infinity || n === - Infinity) {
+ return Infinity;
+ }
+ n = Math.abs(n);
+ if (n > max) {
+ max = n;
+ }
+ args[i] = n;
+ }
+ if (max === 0) {
+ max = 1;
+ }
+ var sum = 0;
+ var compensation = 0;
+ for (var j = 0; j < length; j++) {
+ var m = args[j] / max;
+ var summand = m * m - compensation;
+ var preliminary = sum + summand;
+ compensation = preliminary - sum - summand;
+ sum = preliminary;
+ }
+ return Math.sqrt(sum) * max;
+ } /**
+ * Calculates the fractional part of a number.
+ *
+ * @method fract
+ * @param {Number} num Number whose fractional part needs to be found out
+ * @returns {Number} fractional part of x, i.e, {x}
+ * @example
+ *
+ * text(7345.73472742, 10, 25);
+ * text(fract(7345.73472742), 10, 75);
+ * describe(`first row having a number and the second having
+ * the fractional part of the number`);
+ *
+ *
+ *
+ * text(1.4215e-15, 10, 25);
+ * text(fract(1.4215e-15), 10, 75);
+ * describe(`first row having a number expressed in scientific
+ * notation and the second having the fractional part of the number`);
+ *
+ */
+
+ _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': 290,
+ 'core-js/modules/es.array.includes': 174,
+ 'core-js/modules/es.array.index-of': 175,
+ 'core-js/modules/es.array.map': 179,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.math.hypot': 185,
+ 'core-js/modules/es.number.constructor': 187,
+ 'core-js/modules/es.string.includes': 203
+ }
+ ],
+ 321: [
+ 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');
+ _dereq_('core-js/modules/es.object.to-string');
+ _dereq_('core-js/modules/es.reflect.construct');
+ _dereq_('core-js/modules/es.regexp.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 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);
+ } /**
+ * Creates a new p5.Vector (the datatype for storing vectors). This provides a
+ * two or three-dimensional vector, specifically a Euclidean (also known as
+ * geometric) vector. A vector is an entity that has both magnitude and
+ * direction.
+ *
+ * @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}
+ * @example
+ *
+ * let v1;
+ * function setup() {
+ * createCanvas(100, 100);
+ * stroke(255, 0, 255);
+ * v1 = createVector(width / 2, height / 2);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * line(v1.x, v1.y, mouseX, mouseY);
+ * describe('draws a line from center of canvas to mouse pointer position.');
+ * }
+ *
+ */
+
+ _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': 290,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.reflect.construct': 197,
+ 'core-js/modules/es.regexp.to-string': 200
+ }
+ ],
+ 322: [
+ 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 the Perlin noise value at specified coordinates. Perlin noise is
+ * a random sequence generator producing a more naturally ordered, harmonic
+ * succession of numbers compared to the standard random() function.
+ * It was invented by Ken Perlin in the 1980s and been used since in
+ * graphical applications to produce procedural textures, natural motion,
+ * shapes, terrains etc.
The main difference to the
+ * random() function is that Perlin noise is defined in an infinite
+ * n-dimensional space where each pair of coordinates corresponds to a
+ * fixed semi-random value (fixed only for the lifespan of the program; see
+ * the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise,
+ * depending on the number of coordinates given. The resulting value will
+ * always be between 0.0 and 1.0. The noise value can be animated by moving
+ * through the noise space as demonstrated in the example above. The 2nd
+ * and 3rd dimensions can also be interpreted as time.
The actual
+ * noise is structured similar to an audio signal, in respect to the
+ * function's use of frequencies. Similar to the concept of harmonics in
+ * physics, Perlin noise is computed over several octaves which are added
+ * together for the final result.
Another way to adjust the
+ * character of the resulting sequence is the scale of the input
+ * coordinates. As the function works within an infinite space the value of
+ * the coordinates doesn't matter as such, only the distance between
+ * successive coordinates does (eg. when using noise() within a
+ * loop). As a general rule the smaller the difference between coordinates,
+ * the smoother the resulting noise sequence will be. Steps of 0.005-0.03
+ * work best for most applications, but this will differ depending on use.
+ *
+ * @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 (between 0 and 1) at specified
+ * coordinates
+ * @example
+ *
+ *
+ * let xoff = 0.0;
+ *
+ * function draw() {
+ * background(204);
+ * xoff = xoff + 0.01;
+ * let n = noise(xoff) * width;
+ * line(n, 0, n, height);
+ * describe(`vertical line moves left to right with updating
+ * noise values.`);
+ * }
+ *
+ *
+ */
+ _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 and level of detail produced by the Perlin noise
+ * function. Similar to harmonics in physics, noise is computed over
+ * several octaves. Lower octaves contribute more to the output signal and
+ * as such define the overall intensity of the noise, whereas higher octaves
+ * create finer-grained details in the noise sequence.
+ *
+ * By default, noise is computed over 4 octaves with each octave contributing
+ * exactly half as much as its predecessor, starting at 50% strength for the 1st
+ * octave. This falloff amount can be changed by adding an additional function
+ * parameter. Eg. a falloff factor of 0.75 means each octave will now have
+ * 75% impact (25% less) of the previous lower octave. Any value between
+ * 0.0 and 1.0 is valid, however, note that values greater than 0.5 might
+ * result in greater than 1.0 values returned by noise().
+ *
+ * By changing these parameters, the signal created by the noise()
+ * function can be adapted to fit very specific needs and characteristics.
+ *
+ * @method noiseDetail
+ * @param {Number} lod number of octaves to be used by the noise
+ * @param {Number} falloff falloff factor for each octave
+ * @example
+ *
+ */
+ _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 noise(). By default,
+ * noise() produces different results each time
+ * the program is run. Set the `seed` parameter to a constant to return
+ * the same pseudo-random numbers each time the software is run.
+ *
+ * @method noiseSeed
+ * @param {Number} seed the seed value
+ * @example
+ *
+ * let xoff = 0.0;
+ *
+ * function setup() {
+ * noiseSeed(99);
+ * stroke(0, 10);
+ * }
+ *
+ * function draw() {
+ * xoff = xoff + .01;
+ * let n = noise(xoff) * width;
+ * line(n, 0, n, height);
+ * describe(`vertical grey lines drawing in pattern affected by noise.`);
+ * }
+ *
+ *
+ */
+ _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': 290
+ }
+ ],
+ 323: [
+ 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.slice');
+ _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.regexp.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.slice');
+ _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.to-string');
+ _dereq_('core-js/modules/es.regexp.to-string');
+ _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
+ };
+ } /**
+ * @module Math
+ * @submodule Vector
+ * @requires constants
+ */
+ /**
+ * A class to describe a two or three-dimensional vector, specifically
+ * a Euclidean (also known as geometric) vector. A vector is an entity
+ * that has both magnitude and direction. The datatype, however, stores
+ * the components of the vector (`x`, `y` for 2D; or `x`, `y`, `z` for 3D). The magnitude
+ * and direction can be accessed via the methods p5.Vector.mag() and heading().
+ *
+ * In many of the p5.js examples, you will see p5.Vector used to describe a
+ * position, velocity, or acceleration. For example, if you consider a rectangle
+ * moving across the screen, at any given instant it has a position (a vector
+ * that points from the origin to its location), a velocity (the rate at which
+ * the object's position changes per time unit, expressed as a vector), and
+ * acceleration (the rate at which the object's velocity changes per time
+ * unit, expressed as a vector).
+ *
+ * Since vectors represent groupings of values, we cannot simply use
+ * traditional addition/multiplication/etc. Instead, we'll need to do some
+ * "vector" math, which is made easy by the methods inside the p5.Vector 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
+ *
+ *
+ * let v1 = createVector(40, 50);
+ * let v2 = createVector(40, 50);
+ *
+ * ellipse(v1.x, v1.y, 50, 50);
+ * ellipse(v2.x, v2.y, 50, 50);
+ * v1.add(v2);
+ * ellipse(v1.x, v1.y, 50, 50);
+ *
+ * describe(`2 white ellipses. One center-left the other
+ * bottom right and off canvas`);
+ *
+ *
+ */
+
+ _main.default.Vector = function Vector() {
+ var x,
+ y,
+ z; // This is how it comes in with createVector()
+ // This check if the first argument is a function
+ if ({
+ }.toString.call(arguments[0]) === '[object Function]') {
+ // In this case the vector have an associated p5 instance
+ this.isPInst = true;
+ this._fromRadians = arguments[0];
+ this._toRadians = arguments[1];
+ x = arguments[2] || 0;
+ y = arguments[3] || 0;
+ z = arguments[4] || 0; // This is what we'll get with new p5.Vector()
+ } else {
+ x = arguments[0] || 0;
+ y = arguments[1] || 0;
+ z = arguments[2] || 0;
+ } /**
+ * The x component of the vector
+ * @property x {Number}
+ */
+
+ this.x = x;
+ /**
+ * The y component of the vector
+ * @property y {Number}
+ */
+ this.y = y;
+ /**
+ * The z component of the vector
+ * @property z {Number}
+ */
+ this.z = z;
+ };
+ /**
+ * Returns a string representation of a vector `v` by calling `String(v)`
+ * or `v.toString()`. This method is useful for logging vectors in the
+ * console.
+ * @method toString
+ * @return {String}
+ * @example
+ *
+ *
+ * function setup() {
+ * let v = createVector(20, 30);
+ * print(String(v)); // prints "p5.Vector Object : [20, 30, 0]"
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'black');
+ *
+ * noStroke();
+ * text(v1.toString(), 10, 25, 90, 75);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.toString = function p5VectorToString() {
+ return 'p5.Vector Object : ['.concat(this.x, ', ').concat(this.y, ', ').concat(this.z, ']');
+ };
+ /**
+ * Sets the `x`, `y`, and `z` components of the vector using two or three separate
+ * variables, the data from a p5.Vector, or the values from a float array.
+ * @method set
+ * @param {Number} [x] The x component of the vector
+ * @param {Number} [y] The y component of the vector
+ * @param {Number} [z] The z component of the vector
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * let v = createVector(1, 2, 3);
+ * v.set(4, 5, 6); // Sets vector to [4, 5, 6]
+ *
+ * let v1 = createVector(0, 0, 0);
+ * let arr = [1, 2, 3];
+ * v1.set(arr); // Sets vector to [1, 2, 3]
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.copy = 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 `x`, `y`, and `z` components to a vector, adds one vector to another, or
+ * adds two independent vectors together. The version of the method that adds
+ * two vectors together is a static method and returns a p5.Vector, the others
+ * act directly on the vector. Additionally, you may provide arguments to this method as an array.
+ * See the examples for more context.
+ *
+ * @method add
+ * @param {Number} x The x component of the vector to be added
+ * @param {Number} [y] The y component of the vector to be added
+ * @param {Number} [z] The z component of the vector to be added
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(1, 2, 3);
+ * v.add(4, 5, 6);
+ * // v's components are set to [5, 7, 9]
+ *
+ *
+ *
+ *
+ *
+ * let v = createVector(1, 2, 3);
+ * // Provide arguments as an array
+ * let arr = [4, 5, 6];
+ * v.add(arr);
+ * // v's components are set to [5, 7, 9]
+ *
+ *
+ */
+ /**
+ * @method rem
+ * @param {p5.Vector | Number[]} value The divisor vector
+ * @chainable
+ */
+ _main.default.Vector.prototype.rem = function rem(x, y, z) {
+ if (x instanceof _main.default.Vector) {
+ if (Number.isFinite(x.x) && Number.isFinite(x.y) && Number.isFinite(x.z)) {
+ var xComponent = parseFloat(x.x);
+ var yComponent = parseFloat(x.y);
+ var zComponent = parseFloat(x.z);
+ return calculateRemainder3D.call(this, xComponent, yComponent, zComponent);
+ }
+ } else if (x instanceof Array) {
+ if (x.every(function (element) {
+ return Number.isFinite(element);
+ })) {
+ if (x.length === 2) {
+ return calculateRemainder2D.call(this, x[0], x[1]);
+ }
+ if (x.length === 3) {
+ return calculateRemainder3D.call(this, x[0], x[1], x[2]);
+ }
+ }
+ } else if (arguments.length === 1) {
+ if (Number.isFinite(arguments[0]) && arguments[0] !== 0) {
+ this.x = this.x % arguments[0];
+ this.y = this.y % arguments[0];
+ this.z = this.z % arguments[0];
+ return this;
+ }
+ } else if (arguments.length === 2) {
+ var vectorComponents = Array.prototype.slice.call(arguments);
+ if (vectorComponents.every(function (element) {
+ return Number.isFinite(element);
+ })) {
+ if (vectorComponents.length === 2) {
+ return calculateRemainder2D.call(this, vectorComponents[0], vectorComponents[1]);
+ }
+ }
+ } else if (arguments.length === 3) {
+ var _vectorComponents = Array.prototype.slice.call(arguments);
+ if (_vectorComponents.every(function (element) {
+ return Number.isFinite(element);
+ })) {
+ if (_vectorComponents.length === 3) {
+ return calculateRemainder3D.call(this, _vectorComponents[0], _vectorComponents[1], _vectorComponents[2]);
+ }
+ }
+ }
+ };
+ /**
+ * Subtracts `x`, `y`, and `z` components from a vector, subtracts one vector from
+ * another, or subtracts two independent vectors. The version of the method
+ * that subtracts two vectors is a static method and returns a p5.Vector, the
+ * others act directly on the vector. Additionally, you may provide arguments to this method as an array.
+ * See the examples for more context.
+ *
+ * @method sub
+ * @param {Number} x The x component of the vector to subtract
+ * @param {Number} [y] The y component of the vector to subtract
+ * @param {Number} [z] The z component of the vector to subtract
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(4, 5, 6);
+ * v.sub(1, 1, 1);
+ * // v's components are set to [3, 4, 5]
+ *
+ *
+ *
+ *
+ *
+ * let v = createVector(4, 5, 6);
+ * // Provide arguments as an array
+ * let arr = [1, 1, 1];
+ * v.sub(arr);
+ * // v's components are set to [3, 4, 5]
+ *
+ *
+ *
+ * // red vector - blue vector = purple vector
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(70, 50);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let v2 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * let v3 = p5.Vector.sub(v1, v2);
+ * drawArrow(v2, v3, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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
+ */
+ _main.default.Vector.prototype.sub = 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 (x instanceof Array) {
+ 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 the vector by a scalar, multiplies the `x`, `y`, and `z` components from a vector, or multiplies
+ * the `x`, `y`, and `z` components of two independent vectors. When multiplying a vector by a scalar, the `x`, `y`,
+ * and `z` components of the vector are all multiplied by the scalar. When multiplying a vector by a vector,
+ * the `x`, `y`, `z` components of both vectors are multiplied by each other
+ * (for example, with two vectors `a` and `b`: `a.x * b.x`, `a.y * b.y`, `a.z * b.z`). The static version of this method
+ * creates a new p5.Vector while the non-static version acts on the vector
+ * directly. Additionally, you may provide arguments to this function as an array.
+ * See the examples for more context.
+ *
+ * @method mult
+ * @param {Number} n The number to multiply with the vector
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(1, 2, 3);
+ * v.mult(2);
+ * // v's components are set to [2, 4, 6]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(1, 2, 3);
+ * let v1 = createVector(2, 3, 4);
+ * v0.mult(v1); // v0's components are set to [2, 6, 12]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(1, 2, 3);
+ * // Provide arguments as an array
+ * let arr = [2, 3, 4];
+ * v0.mult(arr); // v0's components are set to [2, 6, 12]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(1, 2, 3);
+ * let v1 = createVector(2, 3, 4);
+ * const result = p5.Vector.mult(v0, v1);
+ * print(result); // result's components are set to [2, 6, 12]
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = createVector(25, -25);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let num = map(mouseX, 0, width, -2, 2, true);
+ * let v2 = p5.Vector.mult(v1, num);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * noStroke();
+ * text('multiplied by ' + num.toFixed(2), 5, 90);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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 The number to multiply with the x component of the vector
+ * @param {Number} y The number to multiply with the y component of the vector
+ * @param {Number} [z] The number to multiply with the z component of the vector
+ * @chainable
+ */
+ /**
+ * @method mult
+ * @param {Number[]} arr The array to multiply with the components of the vector
+ * @chainable
+ */
+ /**
+ * @method mult
+ * @param {p5.Vector} v The vector to multiply with the components of the original vector
+ * @chainable
+ */
+ _main.default.Vector.prototype.mult = function mult(x, y, z) {
+ 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 (x instanceof Array) {
+ 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 = Array.prototype.slice.call(arguments);
+ if (vectorComponents.every(function (element) {
+ return Number.isFinite(element);
+ }) && vectorComponents.every(function (element) {
+ return typeof element === 'number';
+ })) {
+ if (arguments.length === 1) {
+ this.x *= x;
+ this.y *= x;
+ this.z *= x;
+ }
+ if (arguments.length === 2) {
+ this.x *= x;
+ this.y *= y;
+ }
+ if (arguments.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 the vector by a scalar, divides a vector by the `x`, `y`, and `z` arguments, or divides the `x`, `y`, and
+ * `z` components of two vectors against each other. When dividing a vector by a scalar, the `x`, `y`,
+ * and `z` components of the vector are all divided by the scalar. When dividing a vector by a vector,
+ * the `x`, `y`, `z` components of the source vector are treated as the dividend, and the `x`, `y`, `z` components
+ * of the argument is treated as the divisor. (For example, with two vectors
+ * `a` and `b`: `a.x / b.x`, `a.y / b.y`, `a.z / b.z`.) If any component of the second vector is 0, a division by 0
+ * error will be logged, unless both two vectors have 0 in their `z` components, in which case only the `x` and `y`
+ * components will be divided.
+ * The static version of this method creates a
+ * new p5.Vector while the non-static version acts on the vector directly.
+ * Additionally, you may provide arguments to this method as an array.
+ * See the examples for more context.
+ *
+ * @method div
+ * @param {number} n The number to divide the vector by
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(6, 4, 2);
+ * v.div(2); //v's components are set to [3, 2, 1]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(9, 4, 2);
+ * let v1 = createVector(3, 2, 4);
+ * v0.div(v1); // v0's components are set to [3, 2, 0.5]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(9, 4, 2);
+ * // Provide arguments as an array
+ * let arr = [3, 2, 4];
+ * v0.div(arr); // v0's components are set to [3, 2, 0.5]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(9, 4, 2);
+ * let v1 = createVector(3, 2, 4);
+ * let result = p5.Vector.div(v0, v1);
+ * print(result); // result's components are set to [3, 2, 0.5]
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 100);
+ * let v1 = createVector(50, -50);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let num = map(mouseX, 0, width, 10, 0.5, true);
+ * let v2 = p5.Vector.div(v1, num);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * noStroke();
+ * text('divided by ' + num.toFixed(2), 10, 90);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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 The number to divide with the x component of the vector
+ * @param {Number} y The number to divide with the y component of the vector
+ * @param {Number} [z] The number to divide with the z component of the vector
+ * @chainable
+ */
+ /**
+ * @method div
+ * @param {Number[]} arr The array to divide the components of the vector by
+ * @chainable
+ */
+ /**
+ * @method div
+ * @param {p5.Vector} v The vector to divide the components of the original vector by
+ * @chainable
+ */
+ _main.default.Vector.prototype.div = function div(x, y, z) {
+ 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 (x instanceof Array) {
+ if (x.every(function (element) {
+ return Number.isFinite(element);
+ }) && 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;
+ }
+ var vectorComponents = Array.prototype.slice.call(arguments);
+ if (vectorComponents.every(function (element) {
+ return Number.isFinite(element);
+ }) && vectorComponents.every(function (element) {
+ return typeof element === 'number';
+ })) {
+ if (vectorComponents.some(function (element) {
+ return element === 0;
+ })) {
+ console.warn('p5.Vector.prototype.div:', 'divide by 0');
+ return this;
+ }
+ if (arguments.length === 1) {
+ this.x /= x;
+ this.y /= x;
+ this.z /= x;
+ }
+ if (arguments.length === 2) {
+ this.x /= x;
+ this.y /= y;
+ }
+ if (arguments.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 and returns the result as
+ * a float. (This is simply the equation `sqrt(x*x + y*y + z*z)`.)
+ *
+ * @method mag
+ * @return {Number} The magnitude of the vector
+ * @example
+ *
+ *
+ * let v = createVector(20.0, 30.0, 40.0);
+ * let m = v.mag();
+ * print(m); // Prints "53.85164807134504"
+ *
+ *
+ */
+ _main.default.Vector.prototype.mag = function mag() {
+ return Math.sqrt(this.magSq());
+ };
+ /**
+ * 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
+ * @return {number} The squared magnitude of the vector
+ * @example
+ *
+ */
+ _main.default.Vector.prototype.magSq = 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 version of the method
+ * that computes the dot product of two independent vectors is a static
+ * method. See the examples for more context.
+ *
+ * @method dot
+ * @param {Number} x The x component of the vector
+ * @param {Number} [y] The y component of the vector
+ * @param {Number} [z] The z component of the vector
+ * @return {Number} The dot product
+ *
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = createVector(2, 3, 4);
+ *
+ * print(v1.dot(v2)); // Prints "20"
+ *
+ *
+ */
+ /**
+ * @method dot
+ * @param {p5.Vector} value value component of the vector or a p5.Vector
+ * @return {Number}
+ */
+ _main.default.Vector.prototype.dot = 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 and returns a vector composed of the cross product between
+ * two vectors. Both the static and non-static methods return a new p5.Vector.
+ * See the examples for more context.
+ *
+ * @method cross
+ * @param {p5.Vector} v p5.Vector to be crossed
+ * @return {p5.Vector} p5.Vector composed of cross product
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = createVector(1, 2, 3);
+ *
+ * let v = v1.cross(v2); // v's components are [0, 0, 0]
+ * print(v);
+ *
+ *
+ */
+ _main.default.Vector.prototype.cross = 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 Euclidean distance between two points (considering a
+ * point as a vector object).
+ * If you are looking to calculate distance between 2 points see dist()
+ *
+ * @method dist
+ * @param {p5.Vector} v The x, y, and z coordinates of a p5.Vector
+ * @return {Number} The distance
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 0, 0);
+ * let v2 = createVector(0, 1, 0);
+ *
+ * let distance = v1.dist(v2); // distance is 1.4142...
+ * print(distance);
+ *
+ *
+ */
+ _main.default.Vector.prototype.normalize = 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;
+ };
+ /**
+ * Limit the magnitude of this vector to the value used for the `max`
+ * parameter.
+ *
+ * @method limit
+ * @param {Number} max The maximum magnitude for the vector
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(10, 20, 2);
+ * // v has components [10.0, 20.0, 2.0]
+ * v.limit(5);
+ * // v's components are set to
+ * // [2.2271771, 4.4543543, 0.4454354]
+ *
+ *
+ */
+ _main.default.Vector.prototype.limit = function limit(max) {
+ var mSq = this.magSq();
+ if (mSq > max * max) {
+ this.div(Math.sqrt(mSq)) //normalize it
+ .mult(max);
+ }
+ return this;
+ };
+ /**
+ * Set the magnitude of this vector to the value used for the `len`
+ * parameter.
+ *
+ * @method setMag
+ * @param {number} len The new length for this vector
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(3, 4, 0);
+ * // v has components [3.0, 4.0, 0.0]
+ * v.setMag(10);
+ * // v's components are set to [6.0, 8.0, 0.0]
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(50, 50);
+ *
+ * drawArrow(v0, v1, 'red');
+ *
+ * let length = map(mouseX, 0, width, 0, 141, true);
+ * v1.setMag(length);
+ * drawArrow(v0, v1, 'blue');
+ *
+ * noStroke();
+ * text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.setMag = function setMag(n) {
+ return this.normalize().mult(n);
+ };
+ /**
+ * 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
+ * @return {Number} The angle of rotation
+ * @example
+ *
+ */
+ _main.default.Vector.prototype.heading = function heading() {
+ var h = Math.atan2(this.y, this.x);
+ if (this.isPInst) return this._fromRadians(h);
+ return h;
+ };
+ /**
+ * Rotate the vector to a specific angle (only 2D vectors); magnitude remains the
+ * same.
+ *
+ * @method setHeading
+ * @param {number} angle The angle of rotation
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(10.0, 20.0);
+ * // result of v.heading() is 1.1071487177940904
+ * v.setHeading(Math.PI);
+ * // result of v.heading() is now 3.141592653589793
+ *
+ *
+ */
+ _main.default.Vector.prototype.setHeading = 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;
+ };
+ /**
+ * Rotate the vector by an angle (only 2D vectors); magnitude remains the
+ * same.
+ *
+ * @method rotate
+ * @param {number} angle The angle of rotation
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(10.0, 20.0);
+ * // v has components [10.0, 20.0, 0.0]
+ * v.rotate(HALF_PI);
+ * // v's components are set to [-20.0, 9.999999, 0.0]
+ *
+ *
+ *
+ *
+ *
+ * // static function implementation
+ * let v = createVector(10.0, 20.0);
+ * // v has components [10.0, 20.0, 0.0]
+ * let rotated_v = p5.Vector.rotate(v, HALF_PI);
+ * console.log(rotated_v);
+ * // rotated_v's components are set to [-20.0, 9.999999, 0.0]
+ * console.log(v);
+ * // v's components remains the same (i.e, [10.0, 20.0, 0.0])
+ *
+ *
+ *
+ *
+ *
+ * let angle = 0;
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = createVector(50, 0);
+ *
+ * drawArrow(v0, v1.rotate(angle), 'black');
+ * angle += 0.01;
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.rotate = 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 and returns the angle between two vectors. This method will take
+ * the current angleMode into consideration, and
+ * give the angle in radians or degrees accordingly.
+ *
+ * @method angleBetween
+ * @param {p5.Vector} value The x, y, and z components of a p5.Vector
+ * @return {Number} The angle between
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 0, 0);
+ * let v2 = createVector(0, 1, 0);
+ *
+ * let angle = v1.angleBetween(v2);
+ * // angle is PI/2
+ * print(angle);
+ *
+ *
+ */
+ _main.default.Vector.prototype.angleBetween = function angleBetween(v) {
+ var dotmagmag = this.dot(v) / (this.mag() * v.mag()); // Mathematically speaking: the dotmagmag variable will be between -1 and 1
+ // inclusive. Practically though it could be slightly outside this range due
+ // to floating-point rounding issues. This can make Math.acos return NaN.
+ //
+ // Solution: we'll clamp the value to the -1,1 range
+ var angle;
+ angle = Math.acos(Math.min(1, Math.max( - 1, dotmagmag)));
+ angle = angle * Math.sign(this.cross(v).z || 1);
+ if (this.isPInst) {
+ angle = this._fromRadians(angle);
+ }
+ return angle;
+ };
+ /**
+ * Linear interpolate the vector to another vector.
+ *
+ * @method lerp
+ * @param {Number} x The x component
+ * @param {Number} y The y component
+ * @param {Number} z The z component
+ * @param {Number} amt The amount of interpolation; some value between 0.0
+ * (old vector) and 1.0 (new vector). 0.9 is very near
+ * the new vector. 0.5 is halfway in between.
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * let v = createVector(1, 1, 0);
+ *
+ * v.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]
+ *
+ *
+ */
+ /**
+ * @method lerp
+ * @param {p5.Vector} v The p5.Vector to lerp to
+ * @param {Number} amt
+ * @chainable
+ */
+ _main.default.Vector.prototype.lerp = 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;
+ };
+ /**
+ * Reflect a vector about a normal to a line in 2D, or about a normal to a
+ * plane in 3D.
+ *
+ * @method reflect
+ * @param {p5.Vector} surfaceNormal the p5.Vector
+ * to reflect about.
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(4, 6); // incoming vector, this example vector is heading to the right and downward
+ * let n = createVector(0, -1); // surface normal to a plane (this example normal points directly upwards)
+ * v.reflect(n); // v is reflected about the surface normal n. v's components are now set to [4, -6]
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let n = createVector(0, -30);
+ * drawArrow(v1, n, 'blue');
+ *
+ * let r = v1.copy();
+ * r.reflect(n);
+ * drawArrow(v1, r, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.reflect = function reflect(surfaceNormal) {
+ surfaceNormal.normalize();
+ return this.sub(surfaceNormal.mult(2 * this.dot(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
+ * @return {Number[]} An Array with the 3 values
+ * @example
+ *
+ *
+ * function setup() {
+ * let v = createVector(20, 30);
+ * print(v.array()); // Prints : Array [20, 30, 0]
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let v = createVector(10.0, 20.0, 30.0);
+ * let f = v.array();
+ * print(f[0]); // Prints "10.0"
+ * print(f[1]); // Prints "20.0"
+ * print(f[2]); // Prints "30.0"
+ *
+ *
+ */
+ _main.default.Vector.prototype.array = function array() {
+ return [this.x || 0,
+ this.y || 0,
+ this.z || 0];
+ };
+ /**
+ * Equality check against a p5.Vector.
+ *
+ * @method equals
+ * @param {Number} [x] The x component of the vector
+ * @param {Number} [y] The y component of the vector
+ * @param {Number} [z] The z component of the vector
+ * @return {Boolean} Whether the vectors are equal
+ * @example
+ *
+ */
+ /**
+ * @method equals
+ * @param {p5.Vector|Array} value The vector to compare
+ * @return {Boolean}
+ */
+ _main.default.Vector.prototype.equals = 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 (x instanceof Array) {
+ 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
+ /**
+ * Make a new 2D vector from an angle.
+ *
+ * @method fromAngle
+ * @static
+ * @param {Number} angle The desired angle, in radians (unaffected by angleMode)
+ * @param {Number} [length] The length of the new vector (defaults to 1)
+ * @return {p5.Vector} The new p5.Vector object
+ * @example
+ *
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // Create a variable, proportional to the mouseX,
+ * // varying from 0-360, to represent an angle in degrees.
+ * let myDegrees = map(mouseX, 0, width, 0, 360);
+ *
+ * // Display that variable in an onscreen text.
+ * // (Note the nfc() function to truncate additional decimal places,
+ * // and the "\xB0" character for the degree symbol.)
+ * let readout = 'angle = ' + nfc(myDegrees, 1) + '\xB0';
+ * noStroke();
+ * fill(0);
+ * text(readout, 5, 15);
+ *
+ * // Create a p5.Vector using the fromAngle function,
+ * // and extract its x and y components.
+ * let v = p5.Vector.fromAngle(radians(myDegrees), 30);
+ * let vx = v.x;
+ * let vy = v.y;
+ *
+ * push();
+ * translate(width / 2, height / 2);
+ * noFill();
+ * stroke(150);
+ * line(0, 0, 30, 0);
+ * stroke(0);
+ * line(0, 0, vx, vy);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.fromAngle = function fromAngle(angle, length) {
+ if (typeof length === 'undefined') {
+ length = 1;
+ }
+ return new _main.default.Vector(length * Math.cos(angle), length * Math.sin(angle), 0);
+ };
+ /**
+ * Make a new 3D vector from a pair of ISO spherical angles.
+ *
+ * @method fromAngles
+ * @static
+ * @param {Number} theta The polar angle, in radians (zero is up)
+ * @param {Number} phi The azimuthal angle, in radians
+ * (zero is out of the screen)
+ * @param {Number} [length] The length of the new vector (defaults to 1)
+ * @return {p5.Vector} A new p5.Vector object
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * fill(255);
+ * noStroke();
+ * }
+ * function draw() {
+ * background(255);
+ *
+ * let t = millis() / 1000;
+ *
+ * // add three point lights
+ * pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));
+ * pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));
+ * pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));
+ *
+ * sphere(35);
+ * }
+ *
+ *
+ */
+ _main.default.Vector.fromAngles = function (theta, phi, length) {
+ if (typeof length === 'undefined') {
+ length = 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);
+ };
+ /**
+ * Make a new 2D unit vector from a random angle.
+ *
+ * @method random2D
+ * @static
+ * @return {p5.Vector} A new p5.Vector object
+ * @example
+ *
+ *
+ * let v = p5.Vector.random2D();
+ * // May make v's attributes something like:
+ * // [0.61554617, -0.51195765, 0.0] or
+ * // [-0.4695841, -0.14366731, 0.0] or
+ * // [0.6091097, -0.22805278, 0.0]
+ * print(v);
+ *
+ *
+ *
+ *
+ *
+ * function setup() {
+ * frameRate(1);
+ * }
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = p5.Vector.random2D();
+ * drawArrow(v0, v1.mult(50), 'black');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.random2D = function random2D() {
+ return this.fromAngle(Math.random() * constants.TWO_PI);
+ };
+ /**
+ * Make a new random 3D unit vector.
+ *
+ * @method random3D
+ * @static
+ * @return {p5.Vector} A new p5.Vector object
+ * @example
+ *
+ *
+ * let v = p5.Vector.random3D();
+ * // May make v's attributes something like:
+ * // [0.61554617, -0.51195765, 0.599168] or
+ * // [-0.4695841, -0.14366731, -0.8711202] or
+ * // [0.6091097, -0.22805278, -0.7595902]
+ * print(v);
+ *
+ *
+ */
+ _main.default.Vector.random3D = 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
+ */
+ _main.default.Vector.copy = 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] The vector to receive the result
+ * @return {p5.Vector} The resulting p5.Vector
+ */
+ _main.default.Vector.add = function add(v1, v2, target) {
+ if (!target) {
+ target = v1.copy();
+ if (arguments.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
+ */
+ _main.default.Vector.rem = 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] The vector to receive the result
+ * @return {p5.Vector} The resulting p5.Vector
+ */
+ _main.default.Vector.sub = function sub(v1, v2, target) {
+ if (!target) {
+ target = v1.copy();
+ if (arguments.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} The resulting new p5.Vector
+ */
+ /**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v
+ * @param {Number} n
+ * @param {p5.Vector} [target] the vector to receive the result
+ */
+ /**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v0
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} [target]
+ */
+ /**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v0
+ * @param {Number[]} arr
+ * @param {p5.Vector} [target]
+ */
+ _main.default.Vector.mult = function mult(v, n, target) {
+ if (!target) {
+ target = v.copy();
+ if (arguments.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
+ */
+ _main.default.Vector.rotate = function rotate(v, a, target) {
+ if (arguments.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
+ */
+ /**
+ * @method div
+ * @static
+ * @param {p5.Vector} v0
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} [target]
+ */
+ /**
+ * @method div
+ * @static
+ * @param {p5.Vector} v0
+ * @param {Number[]} arr
+ * @param {p5.Vector} [target]
+ */
+ _main.default.Vector.div = function div(v, n, target) {
+ if (!target) {
+ target = v.copy();
+ if (arguments.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 The first p5.Vector
+ * @param {p5.Vector} v2 The second p5.Vector
+ * @return {Number} The dot product
+ */
+ _main.default.Vector.dot = function dot(v1, v2) {
+ return v1.dot(v2);
+ };
+ /**
+ * Calculates the cross product of two vectors.
+ */
+ /**
+ * @method cross
+ * @static
+ * @param {p5.Vector} v1 The first p5.Vector
+ * @param {p5.Vector} v2 The second p5.Vector
+ * @return {Number} The cross product
+ */
+ _main.default.Vector.cross = 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
+ */
+ _main.default.Vector.dist = 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
+ */
+ _main.default.Vector.lerp = function lerp(v1, v2, amt, target) {
+ if (!target) {
+ target = v1.copy();
+ if (arguments.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;
+ };
+ /**
+ * 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
+ */
+ _main.default.Vector.mag = 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
+ */
+ _main.default.Vector.magSq = 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
+ */
+ _main.default.Vector.normalize = function normalize(v, target) {
+ if (arguments.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
+ */
+ _main.default.Vector.limit = function limit(v, max, target) {
+ if (arguments.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
+ */
+ _main.default.Vector.setMag = function setMag(v, len, target) {
+ if (arguments.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
+ */
+ _main.default.Vector.heading = 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} the angle between the two vectors
+ */
+ _main.default.Vector.angleBetween = 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] the vector to receive the result (Optional)
+ * @return {p5.Vector} the reflected vector
+ */
+ _main.default.Vector.reflect = function reflect(incidentVector, surfaceNormal, target) {
+ if (arguments.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
+ */
+ _main.default.Vector.array = 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}
+ */
+ _main.default.Vector.equals = function equals(v1, v2) {
+ var v;
+ if (v1 instanceof _main.default.Vector) {
+ v = v1;
+ } else if (v1 instanceof Array) {
+ 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);
+ };
+ var _default = _main.default.Vector;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 278,
+ '../core/main': 290,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.every': 169,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.array.some': 181,
+ 'core-js/modules/es.math.sign': 186,
+ 'core-js/modules/es.number.constructor': 187,
+ 'core-js/modules/es.number.is-finite': 188,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.sub': 210,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 324: [
+ 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 random().
+ *
+ * By default, random() produces different results each time the program
+ * is run. Set the seed parameter to a constant to return the same
+ * pseudo-random numbers each time the software is run.
+ *
+ * @method randomSeed
+ * @param {Number} seed the seed value
+ * @example
+ *
+ *
+ * randomSeed(99);
+ * for (let i = 0; i < 100; i++) {
+ * let r = random(0, 255);
+ * stroke(r);
+ * line(i, 0, i, 100);
+ * }
+ * describe('many vertical lines drawn in white, black, or grey.');
+ *
+ *
+ */
+ _main.default.prototype.randomSeed = function (seed) {
+ this._lcgSetSeed(randomStateProp, seed);
+ this._gaussian_previous = false;
+ };
+ /**
+ * Return a random floating-point number.
+ *
+ * Takes either 0, 1 or 2 arguments.
+ *
+ * If no argument is given, returns a random number from 0
+ * up to (but not including) 1.
+ *
+ * If one argument is given and it is a number, returns a random number from 0
+ * up to (but not including) the number.
+ *
+ * If one argument is given and it is an array, returns a random element from
+ * that array.
+ *
+ * If two arguments are given, returns a random number from the
+ * first argument up to (but not including) the second argument.
+ *
+ * @method random
+ * @param {Number} [min] the lower bound (inclusive)
+ * @param {Number} [max] the upper bound (exclusive)
+ * @return {Number} the random number
+ * @example
+ *
+ *
+ * for (let i = 0; i < 100; i++) {
+ * let r = random(50);
+ * stroke(r * 5);
+ * line(50, i, 50 + r, i);
+ * }
+ * describe(`100 horizontal lines from center canvas to right.
+ * The size and fill change each time.`);
+ *
+ *
+ *
+ *
+ * for (let i = 0; i < 100; i++) {
+ * let r = random(-50, 50);
+ * line(50, i, 50 + r, i);
+ * }
+ * describe(`100 horizontal lines from center of canvas.
+ * The height & side change each render.`);
+ *
+ *
+ *
+ *
+ * // Get a random element from an array using the random(Array) syntax
+ * let words = ['apple', 'bear', 'cat', 'dog'];
+ * let word = random(words); // select random word
+ * text(word, 10, 50); // draw the word
+ * describe('word displayed at random. Either apple, bear, cat, or dog.');
+ *
+ *
+ */
+ /**
+ * @method random
+ * @param {Array} choices the array to choose from
+ * @return {*} the 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 (min instanceof Array) {
+ 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. There is theoretically no minimum or maximum
+ * value that randomGaussian() might return. Rather, there is
+ * just a very low probability that values far from the mean will be
+ * returned; and a higher probability that numbers near the mean will
+ * be returned.
+ *
+ * Takes either 0, 1 or 2 arguments.
+ * If no args, the mean is 0 and the standard deviation is 1.
+ * If one arg, that arg is the mean and the standard deviation is 1.
+ * If two args, the first arg is the mean and the second is the standard deviation.
+ *
+ * @method randomGaussian
+ * @param {Number} [mean] the mean
+ * @param {Number} [sd] the standard deviation
+ * @return {Number} the random number
+ * @example
+ *
+ *
+ * for (let y = 0; y < 100; y++) {
+ * let x = randomGaussian(50, 15);
+ * line(50, y, x, y);
+ * }
+ * describe(`100 horizontal lines from center of canvas.
+ * The height & side change each render.`);
+ *
+ *
+ *
+ *
+ * let distribution = new Array(360);
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * for (let i = 0; i < distribution.length; i++) {
+ * distribution[i] = floor(randomGaussian(0, 15));
+ * }
+ * }
+ *
+ * function draw() {
+ * background(204);
+ *
+ * translate(width / 2, width / 2);
+ *
+ * for (let i = 0; i < distribution.length; i++) {
+ * rotate(TWO_PI / distribution.length);
+ * stroke(0);
+ * let dist = abs(distribution[i]);
+ * line(0, 0, dist, 0);
+ * }
+ *
+ * describe(`black lines radiate from center of canvas.
+ * The size changes each render.`);
+ * }
+ *
+ *
+ */
+ _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': 290
+ }
+ ],
+ 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.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;
+ /**
+ * The inverse of cos(), returns the arc cosine of a value.
+ * This function expects the values in the range of -1 to 1 and values are returned in
+ * the range 0 to PI (3.1415927) if the angleMode() is RADIANS
+ * or 0 to 180 if the angleMode() is DEGREES.
+ *
+ * @method acos
+ * @param {Number} value the value whose arc cosine is to be returned
+ * @return {Number} the arc cosine of the given value
+ *
+ * @example
+ *
+ *
+ * let a = PI;
+ * let c = cos(a);
+ * let ac = acos(c);
+ * // Prints: "3.1415927 : -1.0 : 3.1415927"
+ * print(a + ' : ' + c + ' : ' + ac);
+ *
+ *
+ *
+ *
+ *
+ * let a = PI + PI / 4.0;
+ * let c = cos(a);
+ * let ac = acos(c);
+ * // Prints: "3.926991 : -0.70710665 : 2.3561943"
+ * print(a + ' : ' + c + ' : ' + ac);
+ *
+ *
+ */
+ _main.default.prototype.acos = function (ratio) {
+ return this._fromRadians(Math.acos(ratio));
+ };
+ /**
+ * The inverse of sin(), returns the arc sine of a value.
+ * This function expects the values in the range of -1 to 1 and values are returned
+ * in the range -PI/2 to PI/2 if the angleMode is RADIANS or -90 to 90 if the angle
+ * mode is DEGREES.
+ *
+ * @method asin
+ * @param {Number} value the value whose arc sine is to be returned
+ * @return {Number} the arc sine of the given value
+ *
+ * @example
+ *
+ *
+ * let a = PI / 3.0;
+ * let s = sin(a);
+ * let as = asin(s);
+ * // Prints: "1.0471975 : 0.86602540 : 1.0471975"
+ * print(a + ' : ' + s + ' : ' + as);
+ *
+ *
+ *
+ *
+ *
+ * let a = PI + PI / 3.0;
+ * let s = sin(a);
+ * let as = asin(s);
+ * // Prints: "4.1887902 : -0.86602540 : -1.0471975"
+ * print(a + ' : ' + s + ' : ' + as);
+ *
+ *
+ */
+ _main.default.prototype.asin = function (ratio) {
+ return this._fromRadians(Math.asin(ratio));
+ };
+ /**
+ * The inverse of tan(), returns the arc tangent of a value.
+ * This function expects the values in the range of -Infinity to Infinity (exclusive) and
+ * values are returned in the range -PI/2 to PI/2 if the angleMode is RADIANS or
+ * -90 to 90 if the angle mode is DEGREES.
+ *
+ * @method atan
+ * @param {Number} value the value whose arc tangent is to be returned
+ * @return {Number} the arc tangent of the given value
+ *
+ * @example
+ *
+ *
+ * let a = PI / 3.0;
+ * let t = tan(a);
+ * let at = atan(t);
+ * // Prints: "1.0471975 : 1.7320508 : 1.0471975"
+ * print(a + ' : ' + t + ' : ' + at);
+ *
+ *
+ *
+ *
+ *
+ * let a = PI + PI / 3.0;
+ * let t = tan(a);
+ * let at = atan(t);
+ * // Prints: "4.1887902 : 1.7320508 : 1.0471975"
+ * print(a + ' : ' + t + ' : ' + at);
+ *
+ *
+ */
+ _main.default.prototype.atan = function (ratio) {
+ return this._fromRadians(Math.atan(ratio));
+ };
+ /**
+ * Calculates the angle (in radians) from a specified point to the coordinate
+ * origin as measured from the positive x-axis. Values are returned as a
+ * float in the range from PI to -PI if the angleMode()
+ * is RADIANS or 180 to -180 if the angleMode() is DEGREES.
+ * The atan2() function is most often used for orienting geometry
+ * to the position of the cursor.
+ *
+ * Note: The y-coordinate of the point is the first parameter, and the
+ * x-coordinate is the second parameter, due to the structure of calculating
+ * the tangent.
+ *
+ * @method atan2
+ * @param {Number} y y-coordinate of the point
+ * @param {Number} x x-coordinate of the point
+ * @return {Number} the arc tangent of the given point
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(204);
+ * translate(width / 2, height / 2);
+ * let a = atan2(mouseY - height / 2, mouseX - width / 2);
+ * rotate(a);
+ * rect(-30, -5, 60, 10);
+ * describe('60×10 rect at center of canvas rotates with mouse movements');
+ * }
+ *
+ *
+ */
+ _main.default.prototype.atan2 = function (y, x) {
+ return this._fromRadians(Math.atan2(y, x));
+ };
+ /**
+ * Calculates the cosine of an angle. This function takes into account the
+ * current angleMode. Values are returned in the range -1 to 1.
+ *
+ * @method cos
+ * @param {Number} angle the angle
+ * @return {Number} the cosine of the angle
+ *
+ * @example
+ *
+ *
+ * let a = 0.0;
+ * let inc = TWO_PI / 25.0;
+ * for (let i = 0; i < 25; i++) {
+ * line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);
+ * a = a + inc;
+ * }
+ * describe(`vertical black lines form wave patterns, extend-down on
+ * left and right side`);
+ *
+ *
+ */
+ _main.default.prototype.cos = function (angle) {
+ return Math.cos(this._toRadians(angle));
+ };
+ /**
+ * Calculates the sine of an angle. This function takes into account the
+ * current angleMode. Values are returned in the range -1 to 1.
+ *
+ * @method sin
+ * @param {Number} angle the angle
+ * @return {Number} the sine of the angle
+ *
+ * @example
+ *
+ *
+ * let a = 0.0;
+ * let inc = TWO_PI / 25.0;
+ * for (let i = 0; i < 25; i++) {
+ * line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);
+ * a = a + inc;
+ * }
+ * describe(`vertical black lines extend down and up from center
+ * to form wave pattern.`);
+ *
+ *
+ */
+ _main.default.prototype.sin = function (angle) {
+ return Math.sin(this._toRadians(angle));
+ };
+ /**
+ * Calculates the tangent of an angle. This function takes into account
+ * the current angleMode. Values are returned in the range of all real numbers.
+ *
+ * @method tan
+ * @param {Number} angle the angle
+ * @return {Number} the tangent of the angle
+ *
+ * @example
+ *
+ *
+ * let a = 0.0;
+ * let inc = TWO_PI / 50.0;
+ * for (let i = 0; i < 100; i = i + 2) {
+ * line(i, 50, i, 50 + tan(a) * 2.0);
+ * a = a + inc;
+ * }
+ * describe(`vertical black lines end down and up from center to
+ * form spike pattern.`);
+ *
+ */
+ _main.default.prototype.tan = function (angle) {
+ return Math.tan(this._toRadians(angle));
+ };
+ /**
+ * Converts a radian measurement to its corresponding value in degrees.
+ * Radians and degrees are two ways of measuring the same thing. There are
+ * 360 degrees in a circle and 2*PI radians in a circle. For example,
+ * 90° = PI/2 = 1.5707964. This function does not take into account the
+ * current angleMode().
+ *
+ * @method degrees
+ * @param {Number} radians the radians value to convert to degrees
+ * @return {Number} the converted angle
+ *
+ * @example
+ *
+ *
+ * let rad = PI / 4;
+ * let deg = degrees(rad);
+ * print(rad + ' radians is ' + deg + ' degrees');
+ * // Prints: 0.7853981633974483 radians is 45 degrees
+ *
+ *
+ */
+ _main.default.prototype.degrees = function (angle) {
+ return angle * constants.RAD_TO_DEG;
+ };
+ /**
+ * Converts a degree measurement to its corresponding value in radians.
+ * Radians and degrees are two ways of measuring the same thing. There are
+ * 360 degrees in a circle and 2*PI radians in a circle. For example,
+ * 90° = PI/2 = 1.5707964. This function does not take into account the
+ * current angleMode.
+ *
+ * @method radians
+ * @param {Number} degrees the degree value to convert to radians
+ * @return {Number} the converted angle
+ *
+ * @example
+ *
+ *
+ * let deg = 45.0;
+ * let rad = radians(deg);
+ * print(deg + ' degrees is ' + rad + ' radians');
+ * // Prints: 45 degrees is 0.7853981633974483 radians
+ *
+ *
+ */
+ _main.default.prototype.radians = function (angle) {
+ return angle * constants.DEG_TO_RAD;
+ };
+ /**
+ * Sets the current mode of p5 to the given mode. Default mode is RADIANS.
+ *
+ * Calling angleMode() with no arguments returns current anglemode.
+ * @method angleMode
+ * @param {Constant} mode either RADIANS or DEGREES
+ * @example
+ *
+ *
+ * function draw() {
+ * background(204);
+ * angleMode(DEGREES); // Change the mode to DEGREES
+ * let a = atan2(mouseY - height / 2, mouseX - width / 2);
+ * translate(width / 2, height / 2);
+ * push();
+ * rotate(a);
+ * rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees
+ * pop();
+ * angleMode(RADIANS); // Change the mode to RADIANS
+ * rotate(a); // variable a stays the same
+ * rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians
+ * describe(`40×10 rect in center rotates with mouse moves.
+ * 20×10 rect moves faster.`);
+ * }
+ *
+ *
+ *
+ */
+ /**
+ * @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) {
+ 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;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 278,
+ '../core/main': 290,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 326: [
+ 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 Typography
+ * @submodule Attributes
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+ /**
+ * Sets the current alignment for drawing text. Accepts two
+ * arguments: horizAlign (LEFT, CENTER, or RIGHT) and
+ * vertAlign (TOP, BOTTOM, CENTER, or BASELINE).
+ *
+ * The horizAlign parameter is in reference to the x value
+ * of the text() function, while the vertAlign parameter
+ * is in reference to the y value.
+ *
+ * So if you write textAlign(LEFT), you are aligning the left
+ * edge of your text to the x value you give in text().
+ * If you write textAlign(RIGHT, TOP), you are aligning the right edge
+ * of your text to the x value and the top edge of the text
+ * to the y value.
+ *
+ * @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
+ *
+ *
+ * textSize(16);
+ * textAlign(RIGHT);
+ * text('ABCD', 50, 30);
+ * textAlign(CENTER);
+ * text('EFGH', 50, 50);
+ * textAlign(LEFT);
+ * text('IJKL', 50, 70);
+ * describe(`Letters ABCD displayed at top left, EFGH at center, and
+ * IJKL at bottom right.`);
+ *
+ *
+ */
+ /**
+ * @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/gets the spacing, in pixels, between lines of text. This setting will be
+ * used in all subsequent calls to the text() function.
+ *
+ * @method textLeading
+ * @param {Number} leading the size in pixels for spacing between lines
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * let lines = 'L1\nL2\nL3'; // "\n" is a "new line" character
+ * textSize(12);
+ *
+ * textLeading(10);
+ * text(lines, 10, 25);
+ *
+ * textLeading(20);
+ * text(lines, 40, 25);
+ *
+ * textLeading(30);
+ * text(lines, 70, 25);
+ *
+ * describe(`A set of L1, L2, and L3, displayed vertically 3 times.
+ * Spacing increases for each set.`);
+ *
+ *
+ */
+ /**
+ * @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/gets the current font size. This size will be used in all subsequent
+ * calls to the text() function. Font size is measured in pixels.
+ *
+ * @method textSize
+ * @param {Number} theSize the size of the letters in units of pixels
+ * @chainable
+ *
+ * @example
+ *
+ */
+ /**
+ * @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 and returns the width of any character or text string.
+ *
+ * @method textWidth
+ * @param {String} theText the String of characters to measure
+ * @return {Number} the calculated width
+ * @example
+ *
+ *
+ * textSize(28);
+ *
+ * let aChar = 'P';
+ * let cWidth = textWidth(aChar);
+ * text(aChar, 0, 40);
+ * line(cWidth, 0, cWidth, 50);
+ *
+ * let aString = 'p5.js';
+ * let sWidth = textWidth(aString);
+ * text(aString, 0, 85);
+ * line(sWidth, 50, sWidth, 100);
+ *
+ * describe('Letter P and p5.js are displayed with vertical lines at end.');
+ *
+ *
+ */
+ _main.default.prototype.textWidth = function () {
+ var _this$_renderer5;
+ 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;
+ }
+ return (_this$_renderer5 = this._renderer).textWidth.apply(_this$_renderer5, args);
+ };
+ /**
+ * Returns 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}
+ * @example
+ *
+ *
+ * let base = height * 0.75;
+ * let scalar = 0.8; // Different for each font
+ *
+ * textSize(32); // Set initial text size
+ * let asc = textAscent() * scalar; // Calc ascent
+ * line(0, base - asc, width, base - asc);
+ * text('dp', 0, base); // Draw text on baseline
+ *
+ * textSize(64); // Increase text size
+ * asc = textAscent() * scalar; // Recalc ascent
+ * line(40, base - asc, width, base - asc);
+ * text('dp', 40, base); // Draw text on baseline
+ *
+ *
+ */
+ _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();
+ };
+ /**
+ * Returns 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}
+ * @example
+ *
+ *
+ * let base = height * 0.75;
+ * let scalar = 0.8; // Different for each font
+ *
+ * textSize(32); // Set initial text size
+ * let desc = textDescent() * scalar; // Calc descent
+ * line(0, base + desc, width, base + desc);
+ * text('dp', 0, base); // Draw text on baseline
+ *
+ * textSize(64); // Increase text size
+ * desc = textDescent() * scalar; // Recalc descent
+ * line(40, base + desc, width, base + desc);
+ * text('dp', 40, base); // Draw text on baseline
+ *
+ *
+ */
+ _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();
+ };
+ /**
+ * Specifies how lines of text are wrapped within a text box. This requires a max-width set on the text area, specified in text() as parameter `x2`.
+ *
+ * WORD wrap style only breaks lines at spaces. A single string without spaces that exceeds the boundaries of the canvas or text area is not truncated, and will overflow the desired area, disappearing at the canvas edge.
+ *
+ * CHAR wrap style breaks lines wherever needed to stay within the text box.
+ *
+ * WORD is the default wrap style, and both styles will still break lines at any line breaks (`\n`) specified in the original text. The text area max-height parameter (`y2`) also still applies to wrapped text in both styles, lines of text that do not fit within the text area will not be drawn to the screen.
+ *
+ * @method textWrap
+ * @param {Constant} wrapStyle text wrapping style, either WORD or CHAR
+ * @return {String} wrapStyle
+ * @example
+ *
+ *
+ * @alt
+ * p5*js in p5's theme dark pink
+ * p5*js in p5's theme dark pink
+ */
+
+ _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 screen. Displays the information specified in the first
+ * parameter on the screen in the position specified by the additional
+ * parameters. A default font will be used unless a font is set with the
+ * textFont() function and a default size will be
+ * used unless a font is set with textSize(). Change
+ * the color of the text with the fill() function. Change
+ * the outline of the text with the stroke() and
+ * strokeWeight() functions.
+ *
+ * The text displays in relation to the textAlign()
+ * function, which gives the option to draw to the left, right, and center of the
+ * coordinates.
+ *
+ * The x2 and y2 parameters define a rectangular area to display within and
+ * may only be used with string data. When these parameters are specified,
+ * they are interpreted based on the current rectMode()
+ * setting. Text that does not fit completely within the rectangle specified will
+ * not be drawn to the screen. If x2 and y2 are not specified, the baseline
+ * alignment is the default, which means that the text will be drawn upwards
+ * from x and y.
+ *
+ * WEBGL: Only opentype/truetype fonts are supported. You must load a font
+ * using the loadFont() method (see the example above).
+ * stroke() currently has no effect in webgl mode.
+ * Learn more about working with text in webgl mode on the
+ * wiki.
+ *
+ * @method text
+ * @param {String|Object|Array|Number|Boolean} str the alphanumeric
+ * symbols to be displayed
+ * @param {Number} x x-coordinate of text
+ * @param {Number} y y-coordinate of text
+ * @param {Number} [x2] by default, the width of the text box,
+ * see rectMode() for more info
+ * @param {Number} [y2] by default, the height of the text box,
+ * see rectMode() for more info
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 'word' displayed 3 times going from black, blue to translucent blue
+ * The text 'The quick brown fox jumped over the lazy dog' displayed.
+ * The text 'p5.js' 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 current font that will be drawn with the text() function.
+ * If textFont() is called without any argument, it will return the current font if one has
+ * been set already. If not, it will return the name of the default font as a string.
+ * If textFont() is called with a font to use, it will return the p5 object.
+ *
+ * WEBGL: Only fonts loaded via loadFont() are supported.
+ *
+ * @method textFont
+ * @return {Object} the current font / p5 Object
+ *
+ * @example
+ *
+ */
+
+ _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
+ *
+ */
+ _main.default.prototype.shorten = function (list) {
+ list.pop();
+ return list;
+ };
+ /**
+ * Randomizes the order of the elements of an array. Implements
+ *
+ * Fisher-Yates Shuffle Algorithm.
+ *
+ * @method shuffle
+ * @param {Array} array Array to shuffle
+ * @param {Boolean} [bool] modify passed array
+ * @return {Array} shuffled Array
+ * @example
+ *
+ * function setup() {
+ * let regularArr = ['ABC', 'def', createVector(), TAU, Math.E];
+ * print(regularArr);
+ * shuffle(regularArr, true); // force modifications to passed array
+ * print(regularArr);
+ *
+ * // By default shuffle() returns a shuffled cloned array:
+ * let newArr = shuffle(regularArr);
+ * print(regularArr);
+ * print(newArr);
+ * }
+ *
+ */
+ _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
+ *
+ */
+ _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
+ *
+ *
+ * @alt
+ * 20 by 20 white ellipse in the center of the canvas
+ */
+
+ _main.default.prototype.float = function (str) {
+ if (str instanceof Array) {
+ return str.map(parseFloat);
+ }
+ return parseFloat(str);
+ };
+ /**
+ * Converts a boolean, string, or float to its integer representation.
+ * When an array of values is passed in, then an int array of the same length
+ * is returned.
+ *
+ * @method int
+ * @param {String|Boolean|Number} n value to parse
+ * @param {Integer} [radix] the radix to convert to (default: 10)
+ * @return {Number} integer representation of value
+ *
+ * @example
+ *
+ */
+ _main.default.prototype.str = function (n) {
+ if (n instanceof Array) {
+ return n.map(_main.default.prototype.str);
+ } else {
+ return String(n);
+ }
+ };
+ /**
+ * Converts a number or string to its boolean representation.
+ * For a number, any non-zero value (positive or negative) evaluates to true,
+ * while zero evaluates to false. For a string, the value "true" evaluates to
+ * true, while any other value evaluates to false. When an array of number or
+ * string values is passed in, then a array of booleans of the same length is
+ * returned.
+ *
+ * @method boolean
+ * @param {String|Boolean|Number|Array} n value to parse
+ * @return {Boolean} boolean representation of value
+ * @example
+ *
+ */
+ _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 number, string representation of a number, or boolean to its byte
+ * representation. A byte can be only a whole number between -128 and 127, so
+ * when a value outside of this range is converted, it wraps around to the
+ * corresponding byte representation. When an array of number, string or boolean
+ * values is passed in, then an array of bytes the same length is returned.
+ *
+ * @method byte
+ * @param {String|Boolean|Number} n value to parse
+ * @return {Number} byte representation of value
+ *
+ * @example
+ *
+ */
+ /**
+ * @method byte
+ * @param {Array} ns values to parse
+ * @return {Number[]} array of byte representation of 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 its corresponding single-character
+ * string representation. If a string parameter is provided, it is first
+ * parsed as an integer and then translated into a single-character string.
+ * When an array of number or string values is passed in, then an array of
+ * single-character strings of the same length is returned.
+ *
+ * @method char
+ * @param {String|Number} n value to parse
+ * @return {String} string representation of value
+ *
+ * @example
+ *
+ */
+ /**
+ * @method char
+ * @param {Array} ns values to parse
+ * @return {String[]} array of string representation of values
+ */
+ _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 its corresponding integer
+ * representation. When an array of single-character string values is passed
+ * in, then an array of integers of the same length is returned.
+ *
+ * @method unchar
+ * @param {String} n value to parse
+ * @return {Number} integer representation of value
+ *
+ * @example
+ *
+ */
+ /**
+ * @method unchar
+ * @param {Array} ns values to parse
+ * @return {Number[]} integer representation of values
+ */
+ _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 in its equivalent hexadecimal notation. If a
+ * second parameter is passed, it is used to set the number of characters to
+ * generate in the hexadecimal notation. When an array is passed in, an
+ * array of strings in hexadecimal notation of the same length is returned.
+ *
+ * @method hex
+ * @param {Number} n value to parse
+ * @param {Number} [digits]
+ * @return {String} hexadecimal string representation of value
+ *
+ * @example
+ *
+ *
+ * @alt
+ * "hello world!" displayed middle left of canvas.
+ */
+
+ _main.default.prototype.join = function (list, separator) {
+ _main.default._validateParameters('join', arguments);
+ return list.join(separator);
+ };
+ /**
+ * This function is used to apply a regular expression to a piece of text,
+ * and return matching groups (elements found inside parentheses) as a
+ * String array. If there are no matches, a null value will be returned.
+ * If no groups are specified in the regular expression, but the sequence
+ * matches, an array of length 1 (with the matched text as the first element
+ * of the array) will be returned.
+ *
+ * To use the function, first check to see if the result is null. If the
+ * result is null, then the sequence did not match at all. If the sequence
+ * did match, an array is returned.
+ *
+ * If there are groups (specified by sets of parentheses) in the regular
+ * expression, then the contents of each will be returned in the array.
+ * Element [0] of a regular expression match returns the entire matching
+ * string, and the match groups start at element [1] (the first group is [1],
+ * the second [2], and so on).
+ *
+ * @method match
+ * @param {String} str the String to be searched
+ * @param {String} regexp the regexp to be used for matching
+ * @return {String[]} Array of Strings found
+ * @example
+ *
+ *
+ * let string = 'Hello p5js*!';
+ * let regexp = 'p5js\\*';
+ * let m = match(string, regexp);
+ * text(m, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * "p5js*" displayed middle left of canvas.
+ */
+ _main.default.prototype.match = function (str, reg) {
+ _main.default._validateParameters('match', arguments);
+ return str.match(reg);
+ };
+ /**
+ * This function is used to apply a regular expression to a piece of text,
+ * and return a list of matching groups (elements found inside parentheses)
+ * as a two-dimensional String array. If there are no matches, a null value
+ * will be returned. If no groups are specified in the regular expression,
+ * but the sequence matches, a two dimensional array is still returned, but
+ * the second dimension is only of length one.
+ *
+ * To use the function, first check to see if the result is null. If the
+ * result is null, then the sequence did not match at all. If the sequence
+ * did match, a 2D array is returned.
+ *
+ * If there are groups (specified by sets of parentheses) in the regular
+ * expression, then the contents of each will be returned in the array.
+ * Assuming a loop with counter variable i, element [i][0] of a regular
+ * expression match returns the entire matching string, and the match groups
+ * start at element [i][1] (the first group is [i][1], the second [i][2],
+ * and so on).
+ *
+ * @method matchAll
+ * @param {String} str the String to be searched
+ * @param {String} regexp the regexp to be used for matching
+ * @return {String[]} 2d Array of Strings found
+ * @example
+ *
+ */
+ _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;
+ };
+ /**
+ * Utility function for formatting numbers into strings. There are two
+ * versions: one for formatting floats, and one for formatting ints.
+ *
+ * The values for the digits, left, and right parameters should always
+ * be positive integers.
+ *
+ * (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter
+ * if greater than the current length of the number.
+ *
+ * For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123
+ * (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than
+ * the result will be 123.200.
+ *
+ * @method nf
+ * @param {Number|String} num the Number to format
+ * @param {Integer|String} [left] number of digits to the left of the
+ * decimal point
+ * @param {Integer|String} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * @alt
+ * "11,253,106.115" top middle and "1.00,1.00,2.00" displayed bottom mid
+ */
+ /**
+ * @method nfc
+ * @param {Array} nums the 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;
+ } /**
+ * Utility function for formatting numbers into strings. Similar to nf() but
+ * puts a "+" in front of positive numbers and a "-" in front of negative
+ * numbers. There are two versions: one for formatting floats, and one for
+ * formatting ints. The values for left, and right parameters
+ * should always be positive integers.
+ *
+ * @method nfp
+ * @param {Number} num the Number to format
+ * @param {Integer} [left] number of digits to the left of the decimal
+ * point
+ * @param {Integer} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * @alt
+ * "+11253106.11" top middle and "-11253106.11" displayed bottom middle
+ */
+ /**
+ * @method nfp
+ * @param {Number[]} nums the 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();
+ } /**
+ * Utility function for formatting numbers into strings. Similar to nf() but
+ * puts an additional "_" (space) in front of positive numbers just in case to align it with negative
+ * numbers which includes "-" (minus) sign.
+ *
+ * The main usecase of nfs() can be seen when one wants to align the digits (place values) of a non-negative
+ * number with some negative number (See the example to get a clear picture).
+ * There are two versions: one for formatting float, and one for formatting int.
+ *
+ * The values for the digits, left, and right parameters should always be positive integers.
+ *
+ * (IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using.
+ *
+ * (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter
+ * if greater than the current length of the number.
+ *
+ * For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123
+ * (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than
+ * the result will be 123.200.
+ *
+ * @method nfs
+ * @param {Number} num the Number to format
+ * @param {Integer} [left] number of digits to the left of the decimal
+ * point
+ * @param {Integer} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * background(200);
+ * let num1 = 321;
+ * let num2 = -1321;
+ *
+ * noStroke();
+ * fill(0);
+ * textSize(16);
+ *
+ * // nfs() aligns num1 (positive number) with num2 (negative number) by
+ * // adding a blank space in front of the num1 (positive number)
+ * // [left = 4] in num1 add one 0 in front, to align the digits with num2
+ * // [right = 2] in num1 and num2 adds two 0's after both numbers
+ * // To see the differences check the example of nf() too.
+ * text(nfs(num1, 4, 2), 10, 30);
+ * text(nfs(num2, 4, 2), 10, 80);
+ * // Draw dividing line
+ * stroke(120);
+ * line(0, 50, width, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * "0321.00" top middle and "-1321.00" displayed bottom middle
+ */
+ /**
+ * @method nfs
+ * @param {Array} nums the 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();
+ } /**
+ * The split() function maps to String.split(), it breaks a String into
+ * pieces using a character or string as the delimiter. The delim parameter
+ * specifies the character or characters that mark the boundaries between
+ * each piece. A String[] array is returned that contains each of the pieces.
+ *
+ * The splitTokens() function works in a similar fashion, except that it
+ * splits using a range of characters instead of a specific character or
+ * sequence.
+ *
+ * @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
+ *
+ *
+ * @alt
+ * "pat" top left, "Xio" mid left and "Alex" displayed bottom left
+ */
+
+ _main.default.prototype.split = function (str, delim) {
+ _main.default._validateParameters('split', arguments);
+ return str.split(delim);
+ };
+ /**
+ * The splitTokens() function splits a String at one or many character
+ * delimiters or "tokens." The delim parameter specifies the character or
+ * characters to be used as a boundary.
+ *
+ * If no delim characters are specified, 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 the String to be split
+ * @param {String} [delim] list of individual Strings that will be used as
+ * separators
+ * @return {String[]} Array of Strings
+ * @example
+ *
+ *
+ * function setup() {
+ * let myStr = 'Mango, Banana, Lime';
+ * let myStrArr = splitTokens(myStr, ',');
+ *
+ * print(myStrArr); // prints : ["Mango"," Banana"," Lime"]
+ * }
+ *
+ *
+ */
+ _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 characters from the beginning and end of a String. In
+ * addition to standard whitespace characters such as space, carriage return,
+ * and tab, this function also removes the Unicode "nbsp" character.
+ *
+ * @method trim
+ * @param {String} str a String to be trimmed
+ * @return {String} a trimmed String
+ *
+ * @example
+ *
+ *
+ * let string = trim(' No new lines\n ');
+ * text(string + ' here', 2, 50);
+ *
+ *
+ *
+ * @alt
+ * "No new lines here" displayed center canvas
+ */
+ /**
+ * @method trim
+ * @param {Array} strs an Array of Strings to be trimmed
+ * @return {String[]} an Array of 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': 281,
+ '../core/friendly_errors/file_errors': 282,
+ '../core/friendly_errors/validate_params': 285,
+ '../core/main': 290,
+ 'core-js/modules/es.array.filter': 171,
+ 'core-js/modules/es.array.index-of': 175,
+ 'core-js/modules/es.array.join': 177,
+ 'core-js/modules/es.array.map': 179,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.constructor': 198,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.match': 205,
+ 'core-js/modules/es.string.replace': 207,
+ 'core-js/modules/es.string.split': 209,
+ 'core-js/modules/es.string.trim': 211
+ }
+ ],
+ 332: [
+ 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
+ */
+ /**
+ * p5.js communicates with the clock on your computer. The day() function
+ * returns the current day as a value from 1 - 31.
+ *
+ * @method day
+ * @return {Integer} the current day
+ * @example
+ *
+ *
+ * @alt
+ * Current day is displayed
+ */
+
+ _main.default.prototype.day = function () {
+ return new Date().getDate();
+ };
+ /**
+ * p5.js communicates with the clock on your computer. The hour() function
+ * returns the current hour as a value from 0 - 23.
+ *
+ * @method hour
+ * @return {Integer} the current hour
+ * @example
+ *
+ *
+ * let h = hour();
+ * text('Current hour:\n' + h, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current hour is displayed
+ */
+ _main.default.prototype.hour = function () {
+ return new Date().getHours();
+ };
+ /**
+ * p5.js communicates with the clock on your computer. The minute() function
+ * returns the current minute as a value from 0 - 59.
+ *
+ * @method minute
+ * @return {Integer} the current minute
+ * @example
+ *
+ *
+ * let m = minute();
+ * text('Current minute: \n' + m, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current minute is displayed
+ */
+ _main.default.prototype.minute = function () {
+ return new Date().getMinutes();
+ };
+ /**
+ * Returns the number of milliseconds (thousandths of a second) since
+ * starting the sketch (when `setup()` is called). This information is often
+ * used for timing events and animation sequences.
+ *
+ * @method millis
+ * @return {Number} the number of milliseconds since starting the sketch
+ * @example
+ *
+ *
+ * @alt
+ * number of milliseconds since sketch has started displayed
+ */
+ _main.default.prototype.millis = function () {
+ if (this._millisStart === - 1) {
+ // Sketch has not started
+ return 0;
+ } else {
+ return window.performance.now() - this._millisStart;
+ }
+ };
+ /**
+ * p5.js communicates with the clock on your computer. The month() function
+ * returns the current month as a value from 1 - 12.
+ *
+ * @method month
+ * @return {Integer} the current month
+ * @example
+ *
+ *
+ * let m = month();
+ * text('Current month: \n' + m, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current month is displayed
+ */
+ _main.default.prototype.month = function () {
+ //January is 0!
+ return new Date().getMonth() + 1;
+ };
+ /**
+ * p5.js communicates with the clock on your computer. The second() function
+ * returns the current second as a value from 0 - 59.
+ *
+ * @method second
+ * @return {Integer} the current second
+ * @example
+ *
+ *
+ * @alt
+ * Current second is displayed
+ */
+ _main.default.prototype.second = function () {
+ return new Date().getSeconds();
+ };
+ /**
+ * p5.js communicates with the clock on your computer. The year() function
+ * returns the current year as an integer (2014, 2015, 2016, etc).
+ *
+ * @method year
+ * @return {Integer} the current year
+ * @example
+ *
+ *
+ * let y = year();
+ * text('Current year: \n' + y, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current year is displayed
+ */
+ _main.default.prototype.year = function () {
+ return new Date().getFullYear();
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/main': 290
+ }
+ ],
+ 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.concat');
+ _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.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.iterator');
+ _dereq_('core-js/modules/es.array.slice');
+ _dereq_('core-js/modules/es.math.hypot');
+ _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
+ */
+ /**
+ * Draw a plane with given a width and height
+ * @method plane
+ * @param {Number} [width] width of the plane
+ * @param {Number} [height] height of the plane
+ * @param {Integer} [detailX] Optional number of triangle
+ * subdivisions in x-dimension
+ * @param {Integer} [detailY] Optional number of triangle
+ * subdivisions in y-dimension
+ * @chainable
+ * @example
+ *
+ *
+ * // draw a plane
+ * // with width 50 and height 50
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('a white plane with black wireframe lines');
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * plane(50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Nothing displayed on canvas
+ * Rotating interior view of a box with sides that change color.
+ * 3d red and green gradient.
+ * Rotating interior view of a cylinder with sides that change color.
+ * Rotating view of a cylinder with sides that change color.
+ * 3d red and green gradient.
+ * rotating view of a multi-colored cylinder with concave sides.
+ */
+
+ _main.default.prototype.plane = function (width, height, detailX, detailY) {
+ this._assert3d('plane');
+ _main.default._validateParameters('plane', arguments);
+ if (typeof width === 'undefined') {
+ width = 50;
+ }
+ if (typeof height === 'undefined') {
+ height = width;
+ }
+ if (typeof detailX === 'undefined') {
+ detailX = 1;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 1;
+ }
+ 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;
+ };
+ /**
+ * Draw a box with given width, height and depth
+ * @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] Optional number of triangle
+ * subdivisions in x-dimension
+ * @param {Integer} [detailY] Optional number of triangle
+ * subdivisions in y-dimension
+ * @chainable
+ * @example
+ *
+ *
+ * // draw a spinning box
+ * // with width, height and depth of 50
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('a white box rotating in 3D space');
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * box(50);
+ * }
+ *
+ *
+ */
+ _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 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 strokeIndices instead of faces for strokes
+ //to avoid diagonal stroke lines across face of box
+ this.strokeIndices = [
+ [0,
+ 1],
+ [
+ 1,
+ 3
+ ],
+ [
+ 3,
+ 2
+ ],
+ [
+ 6,
+ 7
+ ],
+ [
+ 8,
+ 9
+ ],
+ [
+ 9,
+ 11
+ ],
+ [
+ 14,
+ 15
+ ],
+ [
+ 16,
+ 17
+ ],
+ [
+ 17,
+ 19
+ ],
+ [
+ 18,
+ 19
+ ],
+ [
+ 20,
+ 21
+ ],
+ [
+ 22,
+ 23
+ ]
+ ];
+ for (var i = 0; i < cubeIndices.length; i++) {
+ var cubeIndex = cubeIndices[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._makeTriangleEdges()._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;
+ };
+ /**
+ * Draw a sphere with given radius.
+ *
+ * DetailX and detailY determines the number of subdivisions in the x-dimension
+ * and the y-dimension of a sphere. More subdivisions make the sphere seem
+ * smoother. The recommended maximum values are both 24. Using a value greater
+ * than 24 may cause a warning or slow down the browser.
+ * @method sphere
+ * @param {Number} [radius] radius of circle
+ * @param {Integer} [detailX] optional number of subdivisions in x-dimension
+ * @param {Integer} [detailY] optional number of subdivisions in y-dimension
+ *
+ * @chainable
+ * @example
+ *
+ *
+ * // draw a sphere with radius 40
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('a white sphere with black wireframe lines');
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * let detailX;
+ * // slide to see how detailX works
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(3, 24, 3);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * describe(
+ * 'a white sphere with low detail on the x-axis, including a slider to adjust detailX'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * sphere(40, detailX.value(), 16);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * let detailY;
+ * // slide to see how detailY works
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(3, 16, 3);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * describe(
+ * 'a white sphere with low detail on the y-axis, including a slider to adjust detailY'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * sphere(40, 16, detailY.value());
+ * }
+ *
+ *
+ */
+ _main.default.prototype.sphere = function (radius, detailX, detailY) {
+ this._assert3d('sphere');
+ _main.default._validateParameters('sphere', arguments);
+ if (typeof radius === 'undefined') {
+ radius = 50;
+ }
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 16;
+ }
+ 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]);
+ }
+ }
+ };
+ /**
+ * Draw a cylinder with given radius and height
+ *
+ * DetailX and detailY determines the number of subdivisions in the x-dimension
+ * and the y-dimension of a cylinder. More subdivisions make the cylinder seem smoother.
+ * The recommended maximum value for detailX is 24. Using a value greater than 24
+ * may cause a warning or slow down the browser.
+ *
+ * @method cylinder
+ * @param {Number} [radius] radius of the surface
+ * @param {Number} [height] height of the cylinder
+ * @param {Integer} [detailX] number of subdivisions in x-dimension;
+ * default is 24
+ * @param {Integer} [detailY] number of subdivisions in y-dimension;
+ * default is 1
+ * @param {Boolean} [bottomCap] whether to draw the bottom of the cylinder
+ * @param {Boolean} [topCap] whether to draw the top of the cylinder
+ * @chainable
+ * @example
+ *
+ *
+ * // slide to see how detailX works
+ * let detailX;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(3, 24, 3);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * describe(
+ * 'a rotating white cylinder with limited X detail, with a slider that adjusts detailX'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * cylinder(20, 75, detailX.value(), 1);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailY works
+ * let detailY;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(1, 16, 1);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * describe(
+ * 'a rotating white cylinder with limited Y detail, with a slider that adjusts detailY'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * cylinder(20, 75, 16, detailY.value());
+ * }
+ *
+ *
+ */
+ _main.default.prototype.cylinder = function (radius, height, detailX, detailY, bottomCap, topCap) {
+ this._assert3d('cylinder');
+ _main.default._validateParameters('cylinder', arguments);
+ if (typeof radius === 'undefined') {
+ radius = 50;
+ }
+ if (typeof height === 'undefined') {
+ height = radius;
+ }
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 1;
+ }
+ if (typeof topCap === 'undefined') {
+ topCap = true;
+ }
+ if (typeof bottomCap === 'undefined') {
+ bottomCap = true;
+ }
+ 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;
+ };
+ /**
+ * Draw a cone with given radius and height
+ *
+ * DetailX and detailY determine the number of subdivisions in the x-dimension and
+ * the y-dimension of a cone. More subdivisions make the cone seem smoother. The
+ * recommended maximum value for detailX is 24. Using a value greater than 24
+ * may cause a warning or slow down the browser.
+ * @method cone
+ * @param {Number} [radius] radius of the bottom surface
+ * @param {Number} [height] height of the cone
+ * @param {Integer} [detailX] number of segments,
+ * the more segments the smoother geometry
+ * default is 24
+ * @param {Integer} [detailY] number of segments,
+ * the more segments the smoother geometry
+ * default is 1
+ * @param {Boolean} [cap] whether to draw the base of the cone
+ * @chainable
+ * @example
+ *
+ *
+ * // slide to see how detailx works
+ * let detailX;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(3, 16, 3);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * describe(
+ * 'a rotating white cone with limited X detail, with a slider that adjusts detailX'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * rotateY(millis() / 1000);
+ * cone(30, 65, detailX.value(), 16);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailY works
+ * let detailY;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(3, 16, 3);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * describe(
+ * 'a rotating white cone with limited Y detail, with a slider that adjusts detailY'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * rotateY(millis() / 1000);
+ * cone(30, 65, 16, detailY.value());
+ * }
+ *
+ *
+ */
+ _main.default.prototype.cone = function (radius, height, detailX, detailY, cap) {
+ this._assert3d('cone');
+ _main.default._validateParameters('cone', arguments);
+ if (typeof radius === 'undefined') {
+ radius = 50;
+ }
+ if (typeof height === 'undefined') {
+ height = radius;
+ }
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 1;
+ }
+ if (typeof cap === 'undefined') {
+ cap = true;
+ }
+ 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;
+ };
+ /**
+ * Draw an ellipsoid with given radius
+ *
+ * DetailX and detailY determine the number of subdivisions in the x-dimension and
+ * the y-dimension of a cone. More subdivisions make the ellipsoid appear to be smoother.
+ * Avoid detail number above 150, it may crash the browser.
+ * @method ellipsoid
+ * @param {Number} [radiusx] x-radius of ellipsoid
+ * @param {Number} [radiusy] y-radius of ellipsoid
+ * @param {Number} [radiusz] z-radius of ellipsoid
+ * @param {Integer} [detailX] number of segments,
+ * the more segments the smoother geometry
+ * default is 24. Avoid detail number above
+ * 150, it may crash the browser.
+ * @param {Integer} [detailY] number of segments,
+ * the more segments the smoother geometry
+ * default is 16. Avoid detail number above
+ * 150, it may crash the browser.
+ * @chainable
+ * @example
+ *
+ *
+ * // draw an ellipsoid
+ * // with radius 30, 40 and 40.
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('a white 3d ellipsoid');
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * ellipsoid(30, 40, 40);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailX works
+ * let detailX;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(2, 24, 12);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * describe(
+ * 'a rotating white ellipsoid with limited X detail, with a slider that adjusts detailX'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 94);
+ * rotateY(millis() / 1000);
+ * ellipsoid(30, 40, 40, detailX.value(), 8);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailY works
+ * let detailY;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(2, 24, 6);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * describe(
+ * 'a rotating white ellipsoid with limited Y detail, with a slider that adjusts detailY'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 105, 9);
+ * rotateY(millis() / 1000);
+ * ellipsoid(30, 40, 40, 12, detailY.value());
+ * }
+ *
+ *
+ */
+ _main.default.prototype.ellipsoid = function (radiusX, radiusY, radiusZ, detailX, detailY) {
+ this._assert3d('ellipsoid');
+ _main.default._validateParameters('ellipsoid', arguments);
+ if (typeof radiusX === 'undefined') {
+ radiusX = 50;
+ }
+ if (typeof radiusY === 'undefined') {
+ radiusY = radiusX;
+ }
+ if (typeof radiusZ === 'undefined') {
+ radiusZ = radiusX;
+ }
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 16;
+ }
+ 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;
+ };
+ /**
+ * Draw a torus with given radius and tube radius
+ *
+ * DetailX and detailY determine the number of subdivisions in the x-dimension and
+ * the y-dimension of a torus. More subdivisions make the torus appear to be smoother.
+ * The default and maximum values for detailX and detailY are 24 and 16, respectively.
+ * Setting them to relatively small values like 4 and 6 allows you to create new
+ * shapes other than a torus.
+ * @method torus
+ * @param {Number} [radius] radius of the whole ring
+ * @param {Number} [tubeRadius] radius of the tube
+ * @param {Integer} [detailX] number of segments in x-dimension,
+ * the more segments the smoother geometry
+ * default is 24
+ * @param {Integer} [detailY] number of segments in y-dimension,
+ * the more segments the smoother geometry
+ * default is 16
+ * @chainable
+ * @example
+ *
+ *
+ * // slide to see how detailX works
+ * let detailX;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailX = createSlider(3, 24, 3);
+ * detailX.position(10, height + 5);
+ * detailX.style('width', '80px');
+ * describe(
+ * 'a rotating white torus with limited X detail, with a slider that adjusts detailX'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * rotateY(millis() / 1000);
+ * torus(30, 15, detailX.value(), 12);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * // slide to see how detailY works
+ * let detailY;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * detailY = createSlider(3, 16, 3);
+ * detailY.position(10, height + 5);
+ * detailY.style('width', '80px');
+ * describe(
+ * 'a rotating white torus with limited Y detail, with a slider that adjusts detailY'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(205, 102, 94);
+ * rotateY(millis() / 1000);
+ * torus(30, 15, 16, detailY.value());
+ * }
+ *
+ *
+ */
+ _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
+ /////////////////////////
+ /**
+ * 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
+ *
+ */
+ _main.default.RendererGL.prototype.point = function (x, y, z) {
+ if (typeof z === 'undefined') {
+ z = 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.strokeIndices = [
+ [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._makeTriangleEdges()._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 {
+ 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,
+ 1,
+ 0, // the resulting unit Z-axis (unchanged)
+ 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 (args) {
+ var x = arguments[0];
+ var y = arguments[1];
+ var width = arguments[2];
+ var height = arguments[3];
+ var start = arguments[4];
+ var stop = arguments[5];
+ var mode = arguments[6];
+ var detail = 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() {
+ this.strokeIndices = [
+ ]; // 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.strokeIndices.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.strokeIndices.push([0,
+ 1]);
+ this.strokeIndices.push([this.vertices.length - 2,
+ this.vertices.length - 1]);
+ this.strokeIndices.push([0,
+ this.vertices.length - 1]);
+ break;
+ case constants.CHORD:
+ this.strokeIndices.push([0,
+ 1]);
+ this.strokeIndices.push([0,
+ this.vertices.length - 1]);
+ break;
+ case constants.OPEN:
+ this.strokeIndices.push([0,
+ 1]);
+ break;
+ default:
+ this.faces.push([0,
+ this.vertices.length - 2,
+ this.vertices.length - 1]);
+ this.strokeIndices.push([this.vertices.length - 2,
+ this.vertices.length - 1]);
+ }
+ }
+ };
+ var arcGeom = new _main.default.Geometry(detail, 1, _arc);
+ arcGeom.computeNormals();
+ if (detail <= 50) {
+ arcGeom._makeTriangleEdges()._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.strokeIndices = [
+ [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()._makeTriangleEdges()._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, detailX, detailY) {
+ /* eslint-enable max-len */
+ if (typeof detailX === 'undefined') {
+ detailX = 2;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 2;
+ }
+ 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()._makeTriangleEdges()._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': 278,
+ '../core/main': 290,
+ './p5.Geometry': 339,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.math.hypot': 185,
+ 'core-js/modules/es.number.to-fixed': 189,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 334: [
+ 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.splice');
+ _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.splice');
+ _dereq_('core-js/modules/es.object.to-string');
+ _dereq_('core-js/modules/es.regexp.to-string');
+ 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 3D
+ * @submodule Interaction
+ * @for p5
+ * @requires core
+ */
+ /**
+ * Allows movement around a 3D sketch using a mouse or trackpad. Left-clicking
+ * and dragging will rotate the camera position about the center of the sketch,
+ * right-clicking and dragging will pan the camera position without rotation,
+ * and using the mouse wheel (scrolling) will move the camera closer or further
+ * from the center of the sketch. This function can be called with parameters
+ * dictating sensitivity to mouse movement along the X and Y axes. Calling
+ * this function without parameters is equivalent to calling orbitControl(1,1).
+ * To reverse direction of movement in either axis, enter a negative number
+ * for sensitivity.
+ * @method orbitControl
+ * @for p5
+ * @param {Number} [sensitivityX] sensitivity to mouse movement along X axis
+ * @param {Number} [sensitivityY] sensitivity to mouse movement along Y axis
+ * @param {Number} [sensitivityZ] sensitivity to scroll movement along Z axis
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * describe(
+ * 'Camera orbits around a box when mouse is hold-clicked & then moved.'
+ * );
+ * }
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * rotateY(0.5);
+ * box(30, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Camera orbits around a box when mouse is hold-clicked & then moved.
+ */
+ // implementation based on three.js 'orbitControls':
+ // https://github.com/mrdoob/three.js/blob/dev/examples/js/controls/OrbitControls.js
+
+ _main.default.prototype.orbitControl = function (sensitivityX, sensitivityY, sensitivityZ) {
+ this._assert3d('orbitControl');
+ _main.default._validateParameters('orbitControl', arguments); // If the mouse is not in bounds of the canvas, disable all behaviors:
+ var mouseInCanvas = this.mouseX < this.width && this.mouseX > 0 && this.mouseY < this.height && this.mouseY > 0;
+ if (!mouseInCanvas) return;
+ var cam = this._renderer._curCamera;
+ if (typeof sensitivityX === 'undefined') {
+ sensitivityX = 1;
+ }
+ if (typeof sensitivityY === 'undefined') {
+ sensitivityY = sensitivityX;
+ }
+ if (typeof sensitivityZ === 'undefined') {
+ sensitivityZ = 0.5;
+ } // 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
+ // 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);
+ }
+ var scaleFactor = this.height < this.width ? this.height : this.width; // ZOOM if there is a change in mouseWheelDelta
+ if (this._mouseWheelDeltaY !== this._pmouseWheelDeltaY) {
+ // zoom according to direction of mouseWheelDeltaY rather than value
+ if (this._mouseWheelDeltaY > 0) {
+ this._renderer._curCamera._orbit(0, 0, sensitivityZ * scaleFactor);
+ } else {
+ this._renderer._curCamera._orbit(0, 0, - sensitivityZ * scaleFactor);
+ }
+ }
+ if (this.mouseIsPressed) {
+ // ORBIT BEHAVIOR
+ if (this.mouseButton === this.LEFT) {
+ var deltaTheta = - sensitivityX * (this.mouseX - this.pmouseX) / scaleFactor;
+ var deltaPhi = sensitivityY * (this.mouseY - this.pmouseY) / scaleFactor;
+ this._renderer._curCamera._orbit(deltaTheta, deltaPhi, 0);
+ } else if (this.mouseButton === this.RIGHT) {
+ // PANNING BEHAVIOR along X/Z camera axes and restricted to X/Z plane
+ // in world space
+ var local = cam._getLocalAxes(); // normalize portions along X/Z axes
+ var xmag = Math.sqrt(local.x[0] * local.x[0] + local.x[2] * local.x[2]);
+ if (xmag !== 0) {
+ local.x[0] /= xmag;
+ local.x[2] /= xmag;
+ } // normalize portions along X/Z axes
+
+ var ymag = Math.sqrt(local.y[0] * local.y[0] + local.y[2] * local.y[2]);
+ if (ymag !== 0) {
+ local.y[0] /= ymag;
+ local.y[2] /= ymag;
+ } // move along those vectors by amount controlled by mouseX, pmouseY
+
+ var dx = - 1 * sensitivityX * (this.mouseX - this.pmouseX);
+ var dz = - 1 * sensitivityY * (this.mouseY - this.pmouseY); // restrict movement to XZ plane in world space
+ cam.setPosition(cam.eyeX + dx * local.x[0] + dz * local.z[0], cam.eyeY, cam.eyeZ + dx * local.x[2] + dz * local.z[2]);
+ }
+ }
+ return this;
+ };
+ /**
+ * debugMode() helps visualize 3D space by adding a grid to indicate where the
+ * ‘ground’ is in a sketch and an axes icon which indicates the +X, +Y, and +Z
+ * directions. This function can be called without parameters to create a
+ * default grid and axes icon, or it can be called according to the examples
+ * above to customize the size and position of the grid and/or axes icon. The
+ * grid is drawn using the most recently set stroke color and weight. To
+ * specify these parameters, add a call to stroke() and strokeWeight()
+ * just before the end of the draw() loop.
+ *
+ * By default, the grid will run through the origin (0,0,0) of the sketch
+ * along the XZ plane
+ * and the axes icon will be offset from the origin. Both the grid and axes
+ * icon will be sized according to the current canvas size. Note that because the
+ * grid runs parallel to the default camera view, it is often helpful to use
+ * debugMode along with orbitControl to allow full view of the grid.
+ * @method debugMode
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode();
+ * describe(
+ * 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z. the grid and icon disappear when the spacebar is pressed.'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * // Press the spacebar to turn debugMode off!
+ * if (keyIsDown(32)) {
+ * noDebugMode();
+ * }
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z. the grid and icon disappear when the
+ * spacebar is pressed.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode(GRID);
+ * describe('a 3D box is centered on a grid in a 3D sketch.');
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode(AXES);
+ * describe(
+ * 'a 3D box is centered in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z.'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode(GRID, 100, 10, 0, 0, 0);
+ * describe('a 3D box is centered on a grid in a 3D sketch');
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode(100, 10, 0, 0, 0, 20, 0, -40, 0);
+ * describe(
+ * 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z.'
+ * );
+ * }
+ *
+ * function draw() {
+ * noStroke();
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * // set the stroke color and weight for the grid!
+ * stroke(255, 0, 150);
+ * strokeWeight(0.8);
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z.
+ */
+ /**
+ * @method debugMode
+ * @param {Constant} mode either GRID or AXES
+ */
+ /**
+ * @method debugMode
+ * @param {Constant} mode
+ * @param {Number} [gridSize] size of one side of the grid
+ * @param {Number} [gridDivisions] number of divisions in the grid
+ * @param {Number} [xOff] X axis offset from origin (0,0,0)
+ * @param {Number} [yOff] Y axis offset from origin (0,0,0)
+ * @param {Number} [zOff] Z axis offset from origin (0,0,0)
+ */
+ /**
+ * @method debugMode
+ * @param {Constant} mode
+ * @param {Number} [axesSize] size of axes icon
+ * @param {Number} [xOff]
+ * @param {Number} [yOff]
+ * @param {Number} [zOff]
+ */
+ /**
+ * @method debugMode
+ * @param {Number} [gridSize]
+ * @param {Number} [gridDivisions]
+ * @param {Number} [gridXOff]
+ * @param {Number} [gridYOff]
+ * @param {Number} [gridZOff]
+ * @param {Number} [axesSize]
+ * @param {Number} [axesXOff]
+ * @param {Number} [axesYOff]
+ * @param {Number} [axesZOff]
+ */
+ _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.call(this, args[1], args[2], args[3], args[4], args[5]));
+ } else if (args[0] === constants.AXES) {
+ this.registerMethod('post', this._axesIcon.call(this, args[1], args[2], args[3], args[4]));
+ } else {
+ this.registerMethod('post', this._grid.call(this, args[0], args[1], args[2], args[3], args[4]));
+ this.registerMethod('post', this._axesIcon.call(this, args[5], args[6], args[7], args[8]));
+ }
+ };
+ /**
+ * Turns off debugMode() in a 3D sketch.
+ * @method noDebugMode
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * camera(0, -30, 100, 0, 0, 0, 0, 1, 0);
+ * normalMaterial();
+ * debugMode();
+ * describe(
+ * 'a 3D box is centered on a grid in a 3D sketch. an icon indicates the direction of each axis: a red line points +X, a green line +Y, and a blue line +Z. the grid and icon disappear when the spacebar is pressed.'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * orbitControl();
+ * box(15, 30);
+ * // Press the spacebar to turn debugMode off!
+ * if (keyIsDown(32)) {
+ * noDebugMode();
+ * }
+ * }
+ *
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z. the grid and icon disappear when the
+ * spacebar is pressed.
+ */
+ _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.mat4[0], this._renderer._curCamera.cameraMatrix.mat4[1], this._renderer._curCamera.cameraMatrix.mat4[2], this._renderer._curCamera.cameraMatrix.mat4[3], this._renderer._curCamera.cameraMatrix.mat4[4], this._renderer._curCamera.cameraMatrix.mat4[5], this._renderer._curCamera.cameraMatrix.mat4[6], this._renderer._curCamera.cameraMatrix.mat4[7], this._renderer._curCamera.cameraMatrix.mat4[8], this._renderer._curCamera.cameraMatrix.mat4[9], this._renderer._curCamera.cameraMatrix.mat4[10], this._renderer._curCamera.cameraMatrix.mat4[11], this._renderer._curCamera.cameraMatrix.mat4[12], this._renderer._curCamera.cameraMatrix.mat4[13], this._renderer._curCamera.cameraMatrix.mat4[14], this._renderer._curCamera.cameraMatrix.mat4[15]); // 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.mat4[0], this._renderer._curCamera.cameraMatrix.mat4[1], this._renderer._curCamera.cameraMatrix.mat4[2], this._renderer._curCamera.cameraMatrix.mat4[3], this._renderer._curCamera.cameraMatrix.mat4[4], this._renderer._curCamera.cameraMatrix.mat4[5], this._renderer._curCamera.cameraMatrix.mat4[6], this._renderer._curCamera.cameraMatrix.mat4[7], this._renderer._curCamera.cameraMatrix.mat4[8], this._renderer._curCamera.cameraMatrix.mat4[9], this._renderer._curCamera.cameraMatrix.mat4[10], this._renderer._curCamera.cameraMatrix.mat4[11], this._renderer._curCamera.cameraMatrix.mat4[12], this._renderer._curCamera.cameraMatrix.mat4[13], this._renderer._curCamera.cameraMatrix.mat4[14], this._renderer._curCamera.cameraMatrix.mat4[15]); // 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': 278,
+ '../core/main': 290,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.splice': 182,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 335: [
+ 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 3D
+ * @submodule Lights
+ * @for p5
+ * @requires core
+ */
+ /**
+ * Creates an ambient light with the given color.
+ *
+ * Ambient light does not come from a specific direction.
+ * Objects are evenly lit from all sides. Ambient lights are
+ * almost always used in combination with other types of lights.
+ *
+ * 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 ambientLight
+ * @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] alpha value relative to current
+ * color range (default is 0-255)
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noStroke();
+ * describe('sphere with coral color under black light');
+ * }
+ * function draw() {
+ * background(100);
+ * ambientLight(0); // black light (no light)
+ * ambientMaterial(255, 127, 80); // coral material
+ * sphere(40);
+ * }
+ *
+ *
+ * @alt
+ * sphere with coral color under black light
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noStroke();
+ * describe('sphere with coral color under white light');
+ * }
+ * function draw() {
+ * background(100);
+ * ambientLight(255); // white light
+ * ambientMaterial(255, 127, 80); // coral material
+ * sphere(40);
+ * }
+ *
+ *
+ * @alt
+ * sphere with coral color under white light
+ */
+ /**
+ * @method ambientLight
+ * @param {Number} gray number specifying value between
+ * white and black
+ * @param {Number} [alpha]
+ * @chainable
+ */
+ /**
+ * @method ambientLight
+ * @param {String} value a color string
+ * @chainable
+ */
+ /**
+ * @method ambientLight
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ * @chainable
+ */
+ /**
+ * @method ambientLight
+ * @param {p5.Color} color color as a p5.Color
+ * @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 color of the specular highlight of a non-ambient light
+ * (i.e. all lights except ambientLight()).
+ *
+ * specularColor() affects only the lights which are created after
+ * it in the code.
+ *
+ * This function is used in combination with
+ * specularMaterial().
+ * If a geometry does not use specularMaterial(), this function
+ * will have no effect.
+ *
+ * The default color is white (255, 255, 255), which is used if
+ * specularColor() is not explicitly called.
+ *
+ * Note: specularColor is equivalent to the Processing function
+ * lightSpecular.
+ *
+ * @method specularColor
+ * @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
+ * @chainable
+ * @example
+ *
+ *
+ * let setRedSpecularColor = true;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noStroke();
+ * describe(
+ * 'Sphere with specular highlight. Clicking the mouse toggles the specular highlight color between red and the default white.'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(0);
+ *
+ * ambientLight(60);
+ *
+ * // add a point light to showcase specular color
+ * // -- use mouse location to position the light
+ * let lightPosX = mouseX - width / 2;
+ * let lightPosY = mouseY - height / 2;
+ * // -- set the light's specular color
+ * if (setRedSpecularColor) {
+ * specularColor(255, 0, 0); // red specular highlight
+ * }
+ * // -- create the light
+ * pointLight(200, 200, 200, lightPosX, lightPosY, 50); // white light
+ *
+ * // use specular material with high shininess
+ * specularMaterial(150);
+ * shininess(50);
+ *
+ * sphere(30, 64, 64);
+ * }
+ *
+ * function mouseClicked() {
+ * setRedSpecularColor = !setRedSpecularColor;
+ * }
+ *
+ *
+ *
+ * @alt
+ * Sphere with specular highlight. Clicking the mouse toggles the
+ * specular highlight color between red and the default white.
+ */
+ /**
+ * @method specularColor
+ * @param {Number} gray number specifying value between
+ * white and black
+ * @chainable
+ */
+ /**
+ * @method specularColor
+ * @param {String} value color as a CSS string
+ * @chainable
+ */
+ /**
+ * @method specularColor
+ * @param {Number[]} values color as an array containing the
+ * red, green, and blue components
+ * @chainable
+ */
+ /**
+ * @method specularColor
+ * @param {p5.Color} color color as a p5.Color
+ * @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 directional light with the given color and direction.
+ *
+ * Directional light comes from one direction.
+ * The direction is specified as numbers inclusively between -1 and 1.
+ * For example, setting the direction as (0, -1, 0) will cause the
+ * geometry to be lit from below (since the light will be facing
+ * directly upwards). Similarly, setting the direction as (1, 0, 0)
+ * will cause the geometry to be lit from the left (since the light
+ * will be facing directly rightwards).
+ *
+ * Directional lights do not have a specific point of origin, and
+ * therefore cannot be positioned closer or farther away from a geometry.
+ *
+ * A maximum of **5** directional lights can be active at once.
+ *
+ * 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 directionalLight
+ * @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} x x component of direction (inclusive range of -1 to 1)
+ * @param {Number} y y component of direction (inclusive range of -1 to 1)
+ * @param {Number} z z component of direction (inclusive range of -1 to 1)
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe(
+ * 'scene with sphere and directional light. The direction of the light is controlled with the mouse position.'
+ * );
+ * }
+ * function draw() {
+ * background(0);
+ * //move your mouse to change light direction
+ * let dirX = (mouseX / width - 0.5) * 2;
+ * let dirY = (mouseY / height - 0.5) * 2;
+ * directionalLight(250, 250, 250, -dirX, -dirY, -1);
+ * noStroke();
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * scene with sphere and directional light. The direction of
+ * the light is controlled with the mouse position.
+ */
+ /**
+ * @method directionalLight
+ * @param {Number} v1
+ * @param {Number} v2
+ * @param {Number} v3
+ * @param {p5.Vector} direction direction of light as a
+ * p5.Vector
+ * @chainable
+ */
+ /**
+ * @method directionalLight
+ * @param {p5.Color|Number[]|String} color color as a p5.Color,
+ * as an array, 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 point light with the given color and position.
+ *
+ * A point light emits light from a single point in all directions.
+ * Because the light is emitted from a specific point (position),
+ * it has a different effect when it is positioned farther vs. nearer
+ * an object.
+ *
+ * A maximum of **5** point lights can be active at once.
+ *
+ * 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 pointLight
+ * @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} x x component of position
+ * @param {Number} y y component of position
+ * @param {Number} z z component of position
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe(
+ * 'scene with sphere and point light. The position of the light is controlled with the mouse position.'
+ * );
+ * }
+ * function draw() {
+ * background(0);
+ * // move your mouse to change light position
+ * let locX = mouseX - width / 2;
+ * let locY = mouseY - height / 2;
+ * // to set the light position,
+ * // think of the world's coordinate as:
+ * // -width/2,-height/2 ----------- width/2,-height/2
+ * // | |
+ * // | 0,0 |
+ * // | |
+ * // -width/2,height/2 ----------- width/2,height/2
+ * pointLight(250, 250, 250, locX, locY, 50);
+ * noStroke();
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * scene with sphere and point light. The position of
+ * the light is controlled with the mouse position.
+ */
+ /**
+ * @method pointLight
+ * @param {Number} v1
+ * @param {Number} v2
+ * @param {Number} v3
+ * @param {p5.Vector} position of light as a p5.Vector
+ * @chainable
+ */
+ /**
+ * @method pointLight
+ * @param {p5.Color|Number[]|String} color color as a p5.Color,
+ * as an array, or as 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;
+ };
+ /**
+ * 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
+ *
+ *
+ * @alt
+ * the light is partially ambient and partially directional
+ */
+ _main.default.prototype.lights = function () {
+ this._assert3d('lights'); // only restore the colorMode to default if it is not in default already
+ if (this._colorMode === constants.RGB) {
+ this.ambientLight(128, 128, 128);
+ this.directionalLight(128, 128, 128, 0, 0, - 1);
+ } else {
+ var maxBright = this._colorMaxes[this._colorMode][2];
+ this.ambientLight(0, 0, maxBright);
+ this.directionalLight(0, 0, maxBright, 0, 0, - 1);
+ }
+ return this;
+ };
+ /**
+ * Sets the falloff rate for pointLight()
+ * and spotLight().
+ *
+ * lightFalloff() affects only the lights which are created after it
+ * in the code.
+ *
+ * The `constant`, `linear`, an `quadratic` parameters are used to calculate falloff as follows:
+ *
+ * d = distance from light position to vertex position
+ *
+ * falloff = 1 / (CONSTANT + d \* LINEAR + (d \* d) \* QUADRATIC)
+ *
+ * @method lightFalloff
+ * @param {Number} constant CONSTANT value for determining falloff
+ * @param {Number} linear LINEAR value for determining falloff
+ * @param {Number} quadratic QUADRATIC value for determining falloff
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Two spheres with different falloff values show different intensity of light
+ */
+ _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 spot light with the given color, position,
+ * light direction, angle, and concentration.
+ *
+ * Like a pointLight(), a spotLight()
+ * emits light from a specific point (position). It has a different effect
+ * when it is positioned farther vs. nearer an object.
+ *
+ * However, unlike a pointLight(), the light is emitted in **one direction**
+ * along a conical shape. The shape of the cone can be controlled using
+ * the `angle` and `concentration` parameters.
+ *
+ * The `angle` parameter is used to
+ * determine the radius of the cone. And the `concentration`
+ * parameter is used to focus the light towards the center of
+ * the cone. Both parameters are optional, however if you want
+ * to specify `concentration`, you must also specify `angle`.
+ * The minimum concentration value is 1.
+ *
+ * A maximum of **5** spot lights can be active at once.
+ *
+ * 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 spotLight
+ * @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} x x component of position
+ * @param {Number} y y component of position
+ * @param {Number} z z component of position
+ * @param {Number} rx x component of light direction (inclusive range of -1 to 1)
+ * @param {Number} ry y component of light direction (inclusive range of -1 to 1)
+ * @param {Number} rz z component of light direction (inclusive range of -1 to 1)
+ * @param {Number} [angle] angle of cone. Defaults to PI/3
+ * @param {Number} [concentration] concentration of cone. Defaults to 100
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe(
+ * 'scene with sphere and spot light. The position of the light is controlled with the mouse position.'
+ * );
+ * }
+ * function draw() {
+ * background(0);
+ * // move your mouse to change light position
+ * let locX = mouseX - width / 2;
+ * let locY = mouseY - height / 2;
+ * // to set the light position,
+ * // think of the world's coordinate as:
+ * // -width/2,-height/2 ----------- width/2,-height/2
+ * // | |
+ * // | 0,0 |
+ * // | |
+ * // -width/2,height/2 ----------- width/2,height/2
+ * ambientLight(50);
+ * spotLight(0, 250, 0, locX, locY, 100, 0, 0, -1, Math.PI / 16);
+ * noStroke();
+ * sphere(40);
+ * }
+ *
+ *
+ *
+ * @alt
+ * scene with sphere and spot light. The position of
+ * the light is controlled with the mouse position.
+ */
+ /**
+ * @method spotLight
+ * @param {p5.Color|Number[]|String} color color as a p5.Color,
+ * as an array, or as a CSS string
+ * @param {p5.Vector} position position of light as a p5.Vector
+ * @param {p5.Vector} direction direction of light as a p5.Vector
+ * @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 present in a sketch.
+ *
+ * All subsequent geometry is rendered without lighting (until a new
+ * light is created with a call to one of the lighting functions
+ * (lights(),
+ * ambientLight(),
+ * directionalLight(),
+ * pointLight(),
+ * spotLight()).
+ *
+ * @method noLights
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Three white spheres. Each appears as a different
+ * color due to lighting.
+ */
+ _main.default.prototype.noLights = function () {
+ this._assert3d('noLights');
+ _main.default._validateParameters('noLights', arguments);
+ 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;
+ return this;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 278,
+ '../core/main': 290,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 336: [
+ 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.slice');
+ _dereq_('core-js/modules/es.array.splice');
+ _dereq_('core-js/modules/es.object.to-string');
+ _dereq_('core-js/modules/es.regexp.exec');
+ _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.array.concat');
+ _dereq_('core-js/modules/es.array.index-of');
+ _dereq_('core-js/modules/es.array.slice');
+ _dereq_('core-js/modules/es.array.splice');
+ _dereq_('core-js/modules/es.object.to-string');
+ _dereq_('core-js/modules/es.regexp.exec');
+ _dereq_('core-js/modules/es.string.match');
+ _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_('./p5.Geometry');
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : {
+ default:
+ obj
+ };
+ } /**
+ * @module Shape
+ * @submodule 3D Models
+ * @for p5
+ * @requires core
+ * @requires p5.Geometry
+ */
+ /**
+ * Load a 3d model from an OBJ or STL file.
+ *
+ * loadModel() should be placed inside of preload().
+ * This allows the model to load fully before the rest of your code is run.
+ *
+ * One of the limitations of the OBJ and STL format is that it doesn't have a built-in
+ * sense of scale. This means that models exported from different programs might
+ * be very different sizes. If your model isn't displaying, try calling
+ * loadModel() with the normalized parameter set to true. This will resize the
+ * model to a scale appropriate for p5. You can also make additional changes to
+ * the final size of your model with the scale() function.
+ *
+ * Also, the support for colored STL files is not present. STL files with color will be
+ * rendered without color properties.
+ *
+ * @method loadModel
+ * @param {String} path Path of the model to be loaded
+ * @param {Boolean} normalize If true, scale the model to a
+ * standardized size when loading
+ * @param {function(p5.Geometry)} [successCallback] Function to be called
+ * once the model is loaded. Will be passed
+ * the 3D model object.
+ * @param {function(Event)} [failureCallback] called with event error if
+ * the model fails to load.
+ * @param {String} [fileType] The file extension of the model
+ * (.stl, .obj).
+ * @return {p5.Geometry} the p5.Geometry object
+ *
+ * @example
+ *
+ *
+ * //draw a spinning teapot
+ * let teapot;
+ *
+ * function preload() {
+ * // Load model with normalise parameter set to true
+ * teapot = loadModel('assets/teapot.obj', true);
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('Vertically rotating 3-d teapot with red, green and blue gradient.');
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * scale(0.4); // Scaled to make model fit into canvas
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * normalMaterial(); // For effect
+ * model(teapot);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Vertically rotating 3-d teapot with red, green and blue gradient.
+ */
+ /**
+ * @method loadModel
+ * @param {String} path
+ * @param {function(p5.Geometry)} [successCallback]
+ * @param {function(Event)} [failureCallback]
+ * @param {String} [fileType]
+ * @return {p5.Geometry} the p5.Geometry object
+ */
+
+ _main.default.prototype.loadModel = function (path) {
+ _main.default._validateParameters('loadModel', arguments);
+ var normalize;
+ var successCallback;
+ var failureCallback;
+ var fileType = path.slice( - 4);
+ if (typeof arguments[1] === 'boolean') {
+ normalize = arguments[1];
+ successCallback = arguments[2];
+ failureCallback = arguments[3];
+ if (typeof arguments[4] !== 'undefined') {
+ fileType = arguments[4];
+ }
+ } else {
+ normalize = false;
+ successCallback = arguments[1];
+ 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;
+ if (fileType.match(/\.stl$/i)) {
+ this.httpDo(path, 'GET', 'arrayBuffer', function (arrayBuffer) {
+ parseSTL(model, arrayBuffer);
+ if (normalize) {
+ model.normalize();
+ }
+ self._decrementPreload();
+ if (typeof successCallback === 'function') {
+ successCallback(model);
+ }
+ }, failureCallback);
+ } else if (fileType.match(/\.obj$/i)) {
+ this.loadStrings(path, function (strings) {
+ parseObj(model, strings);
+ if (normalize) {
+ model.normalize();
+ }
+ self._decrementPreload();
+ if (typeof successCallback === 'function') {
+ successCallback(model);
+ }
+ }, failureCallback);
+ } else {
+ _main.default._friendlyFileLoadError(3, path);
+ if (failureCallback) {
+ failureCallback();
+ } else {
+ console.error('Sorry, the file type is invalid. Only OBJ and STL files are supported.');
+ }
+ }
+ return model;
+ };
+ /**
+ * 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) {
+ // 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: [
+ ]
+ };
+ var indexedVerts = {
+ };
+ 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] === '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 vertIndex = 0; // 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.
+ if (indexedVerts[vertString] !== undefined) {
+ vertIndex = indexedVerts[vertString];
+ } else {
+ var vertParts = vertString.split('/');
+ for (var i = 0; i < vertParts.length; i++) {
+ vertParts[i] = parseInt(vertParts[i]) - 1;
+ }
+ vertIndex = indexedVerts[vertString] = model.vertices.length;
+ model.vertices.push(loadedVerts.v[vertParts[0]].copy());
+ if (loadedVerts.vt[vertParts[1]]) {
+ model.uvs.push(loadedVerts.vt[vertParts[1]].slice());
+ } else {
+ model.uvs.push([0,
+ 0]);
+ }
+ if (loadedVerts.vn[vertParts[2]]) {
+ model.vertexNormals.push(loadedVerts.vn[vertParts[2]].copy());
+ }
+ }
+ face.push(vertIndex);
+ }
+ if (face[0] !== face[1] && face[0] !== face[2] && face[1] !== face[2]) {
+ model.faces.push(face);
+ }
+ }
+ }
+ }
+ } // If the model doesn't have normals, compute the normals
+
+ if (model.vertexNormals.length === 0) {
+ model.computeNormals();
+ }
+ 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;
+ } /**
+ * Render a 3d model to the screen.
+ *
+ * @method model
+ * @param {p5.Geometry} model Loaded 3d model to be rendered
+ * @example
+ *
+ *
+ * @alt
+ * zooming Mandelbrot set. a colorful, infinitely detailed fractal.
+ */
+
+ _main.default.prototype.loadShader = function (vertFilename, fragFilename, callback, errorCallback) {
+ _main.default._validateParameters('loadShader', arguments);
+ if (!errorCallback) {
+ errorCallback = console.error;
+ }
+ var loadedShader = new _main.default.Shader();
+ var self = this;
+ var loadedFrag = false;
+ var loadedVert = false;
+ var onLoad = function onLoad() {
+ self._decrementPreload();
+ if (callback) {
+ callback(loadedShader);
+ }
+ };
+ this.loadStrings(vertFilename, function (result) {
+ loadedShader._vertSrc = result.join('\n');
+ loadedVert = true;
+ if (loadedFrag) {
+ onLoad();
+ }
+ }, errorCallback);
+ this.loadStrings(fragFilename, function (result) {
+ loadedShader._fragSrc = result.join('\n');
+ loadedFrag = true;
+ if (loadedVert) {
+ onLoad();
+ }
+ }, errorCallback);
+ return loadedShader;
+ };
+ /**
+ * Creates a new p5.Shader object
+ * from the provided vertex and fragment shader code.
+ *
+ * Note, shaders can only 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} a shader object created from the provided
+ * vertex and fragment shaders.
+ *
+ * @example
+ *
+ *
+ * // the 'varying's are shared between both vertex & fragment shaders
+ * let varying = 'precision highp float; varying vec2 vPos;';
+ *
+ * // the vertex shader is called for each vertex
+ * let vs =
+ * varying +
+ * 'attribute vec3 aPosition;' +
+ * 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';
+ *
+ * // the fragment shader is called for each pixel
+ * let fs =
+ * varying +
+ * 'uniform vec2 p;' +
+ * 'uniform float r;' +
+ * 'const int I = 500;' +
+ * 'void main() {' +
+ * ' vec2 c = p + vPos * r, z = c;' +
+ * ' float n = 0.0;' +
+ * ' for (int i = I; i > 0; i --) {' +
+ * ' if(z.x*z.x+z.y*z.y > 4.0) {' +
+ * ' n = float(i)/float(I);' +
+ * ' 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 mandel;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ *
+ * // create and initialize the shader
+ * mandel = createShader(vs, fs);
+ * shader(mandel);
+ * noStroke();
+ *
+ * // 'p' is the center point of the Mandelbrot image
+ * mandel.setUniform('p', [-0.74364388703, 0.13182590421]);
+ * describe('zooming Mandelbrot set. a colorful, infinitely detailed fractal.');
+ * }
+ *
+ * function draw() {
+ * // 'r' is the size of the image in Mandelbrot-space
+ * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));
+ * quad(-1, -1, 1, -1, 1, 1, -1, 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * zooming Mandelbrot set. a colorful, infinitely detailed fractal.
+ */
+ _main.default.prototype.createShader = function (vertSrc, fragSrc) {
+ this._assert3d('createShader');
+ _main.default._validateParameters('createShader', arguments);
+ return new _main.default.Shader(this._renderer, vertSrc, fragSrc);
+ };
+ /**
+ * Sets the p5.Shader object to
+ * be used to render subsequent shapes.
+ *
+ * Custom shaders can be created using the
+ * createShader() and
+ * loadShader() functions.
+ *
+ * Use resetShader() to
+ * restore the default shaders.
+ *
+ * Note, shaders can only be used in WEBGL mode.
+ *
+ * @method shader
+ * @chainable
+ * @param {p5.Shader} s the p5.Shader object
+ * to use for rendering shapes.
+ *
+ * @example
+ *
+ *
+ * // Click within the image to toggle
+ * // the shader used by the quad shape
+ * // Note: for an alternative approach to the same example,
+ * // involving changing uniforms please refer to:
+ * // https://p5js.org/reference/#/p5.Shader/setUniform
+ *
+ * let redGreen;
+ * let orangeBlue;
+ * let showRedGreen = false;
+ *
+ * function preload() {
+ * // note that we are using two instances
+ * // of the same vertex and fragment shaders
+ * 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 colors for redGreen shader
+ * shader(redGreen);
+ * redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]);
+ * redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]);
+ *
+ * // initialize the colors for orangeBlue shader
+ * shader(orangeBlue);
+ * orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]);
+ * orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]);
+ *
+ * noStroke();
+ *
+ * describe(
+ * 'canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.'
+ * );
+ * }
+ *
+ * function draw() {
+ * // update the offset values for each shader,
+ * // moving orangeBlue in vertical and redGreen
+ * // in horizontal direction
+ * orangeBlue.setUniform('offset', [0, sin(millis() / 2000) + 1]);
+ * redGreen.setUniform('offset', [sin(millis() / 2000), 1]);
+ *
+ * if (showRedGreen === true) {
+ * shader(redGreen);
+ * } else {
+ * shader(orangeBlue);
+ * }
+ * quad(-1, -1, 1, -1, 1, 1, -1, 1);
+ * }
+ *
+ * function mouseClicked() {
+ * showRedGreen = !showRedGreen;
+ * }
+ *
+ *
+ *
+ * @alt
+ * canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.
+ */
+ _main.default.prototype.shader = function (s) {
+ this._assert3d('shader');
+ _main.default._validateParameters('shader', arguments);
+ if (s._renderer === undefined) {
+ s._renderer = this._renderer;
+ }
+ s.init();
+ if (s.isStrokeShader()) {
+ this._renderer.userStrokeShader = s;
+ } else {
+ this._renderer.userFillShader = s;
+ this._renderer._useNormalMaterial = false;
+ }
+ return this;
+ };
+ /**
+ * Restores the default shaders. Code that runs after resetShader()
+ * will not be affected by the shader previously set by
+ * shader()
+ *
+ * @method resetShader
+ * @chainable
+ * @example
+ *
+ *
+ * // This variable will hold our shader object
+ * let shaderProgram;
+ *
+ * // This variable will hold our vertex shader source code
+ * 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;
+ * }
+ * `;
+ *
+ * // This variable will hold our fragment shader source code
+ * 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);
+ * }
+ * `;
+ *
+ * function setup() {
+ * // Shaders require WEBGL mode to work
+ * createCanvas(100, 100, WEBGL);
+ *
+ * // Create our shader
+ * shaderProgram = createShader(vertSrc, fragSrc);
+ *
+ * describe(
+ * 'Two rotating cubes. The left one is painted using a custom (user-defined) shader, while the right one is painted using the default fill shader.'
+ * );
+ * }
+ *
+ * function draw() {
+ * // Clear the scene
+ * background(200);
+ *
+ * // Draw a box using our shader
+ * // shader() sets the active shader with our shader
+ * shader(shaderProgram);
+ * push();
+ * translate(-width / 4, 0, 0);
+ * rotateX(millis() * 0.00025);
+ * rotateY(millis() * 0.0005);
+ * 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(width / 4, 0, 0);
+ * rotateX(millis() * 0.00025);
+ * rotateY(millis() * 0.0005);
+ * box(width / 4);
+ * pop();
+ * }
+ *
+ *
+ * @alt
+ * Two rotating cubes. The left one is painted using a custom (user-defined) shader,
+ * while the right one is painted using the default fill shader.
+ */
+ _main.default.prototype.resetShader = function () {
+ this._renderer.userFillShader = this._renderer.userStrokeShader = null;
+ return this;
+ };
+ /**
+ * Sets the texture that will be used to render subsequent shapes.
+ *
+ * A texture is like a "skin" that wraps around a 3D geometry. Currently
+ * supported textures are images, video, and offscreen renders.
+ *
+ * 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.
+ *
+ * You can view more materials in this
+ * example.
+ *
+ * @method texture
+ * @param {p5.Image|p5.MediaElement|p5.Graphics|p5.Texture} tex image to use as texture
+ * @chainable
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('spinning cube with a texture from an image');
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * rotateZ(frameCount * 0.01);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * //pass image as texture
+ * texture(img);
+ * box(width / 2);
+ * }
+ *
+ *
+ * @alt
+ * spinning cube with a texture from an image
+ *
+ * @example
+ *
+ *
+ * let pg;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * pg = createGraphics(200, 200);
+ * pg.textSize(75);
+ * describe('plane with a texture from an image created by createGraphics()');
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * pg.background(255);
+ * pg.text('hello!', 0, 100);
+ * //pass image as texture
+ * texture(pg);
+ * rotateX(0.5);
+ * noStroke();
+ * plane(50);
+ * }
+ *
+ *
+ * @alt
+ * plane with a texture from an image created by createGraphics()
+ *
+ * @example
+ *
+ *
+ * let vid;
+ * function preload() {
+ * vid = createVideo('assets/fingers.mov');
+ * vid.hide();
+ * }
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('rectangle with video as texture');
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * //pass video frame as texture
+ * texture(vid);
+ * rect(-40, -40, 80, 80);
+ * }
+ *
+ * function mousePressed() {
+ * vid.loop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * rectangle with video as texture
+ *
+ * @example
+ *
+ * @alt
+ * quad with a texture, mapped using normalized coordinates
+ */
+ _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._useSpecularMaterial = false;
+ this._renderer._useEmissiveMaterial = false;
+ this._renderer._useNormalMaterial = false;
+ this._renderer._tex = tex;
+ this._renderer._setProperty('_doFill', true);
+ return this;
+ };
+ /**
+ * Sets the coordinate space for texture mapping. The default mode is IMAGE
+ * which refers to the actual coordinates of the image.
+ * NORMAL refers to a normalized space of values ranging from 0 to 1.
+ *
+ * With IMAGE, if an image is 100×200 pixels, mapping the image onto the entire
+ * size of a quad would require the points (0,0) (100, 0) (100,200) (0,200).
+ * The same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1).
+ * @method textureMode
+ * @param {Constant} mode either IMAGE or NORMAL
+ * @example
+ *
+ * @alt
+ * quad with a texture, mapped using image coordinates
+ */
+ _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;
+ }
+ };
+ /**
+ * Sets the global texture wrapping mode. This controls how textures behave
+ * when their uv's go outside of the 0 to 1 range. There are three options:
+ * CLAMP, REPEAT, and MIRROR.
+ *
+ * CLAMP causes the pixels at the edge of the texture to extend to the bounds.
+ * REPEAT causes the texture to tile repeatedly until reaching the bounds.
+ * MIRROR works similarly to REPEAT but it flips the texture with every new tile.
+ *
+ * REPEAT & MIRROR are only available if the texture
+ * is a power of two size (128, 256, 512, 1024, etc.).
+ *
+ * This method will affect all textures in your sketch until a subsequent
+ * textureWrap() call is made.
+ *
+ * If only one argument is provided, it will be applied to both the
+ * horizontal and vertical axes.
+ * @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);
+ * textureWrap(MIRROR);
+ * describe('an image of the rocky mountains repeated in mirrored tiles');
+ * }
+ *
+ * function draw() {
+ * background(0);
+ *
+ * let dX = mouseX;
+ * let dY = mouseY;
+ *
+ * let u = lerp(1.0, 2.0, dX);
+ * let v = lerp(1.0, 2.0, dY);
+ *
+ * scale(width / 2);
+ *
+ * texture(img);
+ *
+ * beginShape(TRIANGLES);
+ * vertex(-1, -1, 0, 0, 0);
+ * vertex(1, -1, 0, u, 0);
+ * vertex(1, 1, 0, u, v);
+ *
+ * vertex(1, 1, 0, u, v);
+ * vertex(-1, 1, 0, 0, v);
+ * vertex(-1, -1, 0, 0, 0);
+ * endShape();
+ * }
+ *
+ *
+ *
+ * @alt
+ * an image of the rocky mountains repeated in mirrored tiles
+ */
+ _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 textures = this._renderer.textures;
+ for (var i = 0; i < textures.length; i++) {
+ textures[i].setWrapMode(wrapX, wrapY);
+ }
+ };
+ /**
+ * Sets the current material as a normal material.
+ *
+ * A normal material is not affected by light. It is often used as
+ * a placeholder material when debugging.
+ *
+ * Surfaces facing the X-axis become red, those facing the Y-axis
+ * become green, and those facing the Z-axis become blue.
+ *
+ * You can view more materials in this
+ * example.
+ *
+ * @method normalMaterial
+ * @chainable
+ * @example
+ *
+ * @alt
+ * Sphere with normal material
+ */
+ _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 the material.
+ *
+ * The ambientMaterial() color is the color the object will reflect
+ * under **any** lighting.
+ *
+ * Consider an ambientMaterial() with the color yellow (255, 255, 0).
+ * If the light emits the color white (255, 255, 255), then the object
+ * will appear yellow as it will reflect the red and green components
+ * of the light. If the light emits the color red (255, 0, 0), then
+ * the object will appear red as it will reflect the red component
+ * of the light. If the light emits the color blue (0, 0, 255),
+ * then the object will appear black, as there is no component of
+ * the light that it can reflect.
+ *
+ * You can view more materials in this
+ * example.
+ *
+ * @method ambientMaterial
+ * @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
+ * @chainable
+ * @example
+ *
+ * @alt
+ * sphere reflecting red, blue, and green light
+ *
+ * @example
+ *
+ *
+ * // ambientLight is both red and blue (magenta),
+ * // so object only reflects it's red and blue components
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('box reflecting only red and blue light');
+ * }
+ * function draw() {
+ * background(70);
+ * ambientLight(255, 0, 255); // magenta light
+ * ambientMaterial(255); // white material
+ * box(30);
+ * }
+ *
+ *
+ * @alt
+ * box reflecting only red and blue light
+ *
+ * @example
+ *
+ *
+ * // ambientLight is green. Since object does not contain
+ * // green, it does not reflect any light
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('box reflecting no light');
+ * }
+ * function draw() {
+ * background(70);
+ * ambientLight(0, 255, 0); // green light
+ * ambientMaterial(255, 0, 255); // magenta material
+ * box(30);
+ * }
+ *
+ *
+ * @alt
+ * box reflecting no light
+ */
+ /**
+ * @method ambientMaterial
+ * @param {Number} gray number specifying value between
+ * white and black
+ * @chainable
+ */
+ /**
+ * @method ambientMaterial
+ * @param {p5.Color|Number[]|String} color
+ * color as a p5.Color,
+ * as an array, or as 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.curAmbientColor = color._array;
+ this._renderer._useNormalMaterial = false;
+ this._renderer._enableLighting = true;
+ this._renderer._tex = null;
+ this._renderer._setProperty('_doFill', true);
+ return this;
+ };
+ /**
+ * Sets the emissive color of the material.
+ *
+ * An emissive material will display the emissive color at
+ * full strength regardless of lighting. This can give the
+ * appearance that the object is glowing.
+ *
+ * Note, "emissive" is a misnomer in the sense that the material
+ * does not actually emit light that will affect surrounding objects.
+ *
+ * You can view more materials in this
+ * example.
+ *
+ * @method emissiveMaterial
+ * @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] alpha value relative to current color
+ * range (default is 0-255)
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * sphere with green emissive material
+ */
+ /**
+ * @method emissiveMaterial
+ * @param {Number} gray number specifying value between
+ * white and black
+ * @chainable
+ */
+ /**
+ * @method emissiveMaterial
+ * @param {p5.Color|Number[]|String} color
+ * color as a p5.Color,
+ * as an array, or as 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;
+ this._renderer._tex = null;
+ return this;
+ };
+ /**
+ * Sets the specular color of the material.
+ *
+ * A specular material is reflective (shiny). The shininess can be
+ * controlled by the shininess() function.
+ *
+ * Like ambientMaterial(),
+ * the specularMaterial() color is the color the object will reflect
+ * under ambientLight().
+ * However unlike ambientMaterial(), for all other types of lights
+ * (directionalLight(),
+ * pointLight(),
+ * spotLight()),
+ * a specular material will reflect the **color of the light source**.
+ * This is what gives it its "shiny" appearance.
+ *
+ * You can view more materials in this
+ * example.
+ *
+ * @method specularMaterial
+ * @param {Number} gray number specifying value between white and black.
+ * @param {Number} [alpha] alpha value relative to current color range
+ * (default is 0-255)
+ * @chainable
+ *
+ * @example
+ *
+ * @alt
+ * torus with specular material
+ */
+ /**
+ * @method specularMaterial
+ * @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]
+ * @chainable
+ */
+ /**
+ * @method specularMaterial
+ * @param {p5.Color|Number[]|String} color
+ * color as a p5.Color,
+ * as an array, or as 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;
+ this._renderer._tex = null;
+ return this;
+ };
+ /**
+ * Sets the amount of gloss ("shininess") of a
+ * specularMaterial().
+ *
+ * The default and minimum value is 1.
+ *
+ * @method shininess
+ * @param {Number} shine degree of shininess
+ * @chainable
+ * @example
+ *
+ * @alt
+ * two spheres, one more shiny than the other
+ */
+ _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;
+ };
+ /**
+ * @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 [description]
+ * @return {Number[]]} Normalized numbers array
+ */
+ _main.default.RendererGL.prototype._applyColorBlend = function (colors) {
+ var gl = this.GL;
+ var isTexture = this.drawMode === constants.TEXTURE;
+ var doBlend = 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_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_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': 278,
+ '../core/main': 290,
+ './p5.Texture': 346,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.join': 177,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 338: [
+ 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 3D
+ * @submodule Camera
+ * @requires core
+ */
+ ////////////////////////////////////////////////////////////////////////////////
+ // p5.Prototype Methods
+ ////////////////////////////////////////////////////////////////////////////////
+ /**
+ * Sets the position of the current camera in a 3D sketch.
+ * Parameters for this function define the camera's position,
+ * the center of the sketch (where the camera is pointing),
+ * and an up direction (the orientation of the camera).
+ *
+ * This function simulates the movements of the camera, allowing objects to be
+ * viewed from various angles. Remember, it does not move the objects themselves
+ * but the camera instead. For example when the centerX value is positive,
+ * and the camera is rotating to the right side of the sketch,
+ * the object will seem like it's moving to the left.
+ *
+ * See this example
+ * to view the position of your camera.
+ *
+ * If no parameters are given, the following default is used:
+ * camera(0, 0, (height/2) / tan(PI/6), 0, 0, 0, 0, 1, 0)
+ * @method camera
+ * @constructor
+ * @for p5
+ * @param {Number} [x] camera position value on x axis
+ * @param {Number} [y] camera position value on y axis
+ * @param {Number} [z] camera position value on z axis
+ * @param {Number} [centerX] x coordinate representing center of the sketch
+ * @param {Number} [centerY] y coordinate representing center of the sketch
+ * @param {Number} [centerZ] z coordinate representing center of the sketch
+ * @param {Number} [upX] x component of direction 'up' from camera
+ * @param {Number} [upY] y component of direction 'up' from camera
+ * @param {Number} [upZ] z component of direction 'up' from camera
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * describe('a square moving closer and then away from the camera.');
+ * }
+ * function draw() {
+ * background(204);
+ * //move the camera away from the plane by a sin wave
+ * camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0);
+ * plane(10, 10);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * //move slider to see changes!
+ * //sliders control the first 6 parameters of camera()
+ * let sliderGroup = [];
+ * let X;
+ * let Y;
+ * let Z;
+ * let centerX;
+ * let centerY;
+ * let centerZ;
+ * let h = 20;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * //create sliders
+ * for (var i = 0; i < 6; i++) {
+ * if (i === 2) {
+ * sliderGroup[i] = createSlider(10, 400, 200);
+ * } else {
+ * sliderGroup[i] = createSlider(-400, 400, 0);
+ * }
+ * h = map(i, 0, 6, 5, 85);
+ * sliderGroup[i].position(10, height + h);
+ * sliderGroup[i].style('width', '80px');
+ * }
+ * describe(
+ * 'White square repeatedly grows to fill canvas and then shrinks. An interactive example of a red cube with 3 sliders for moving it across x, y, z axis and 3 sliders for shifting its center.'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(60);
+ * // assigning sliders' value to each parameters
+ * X = sliderGroup[0].value();
+ * Y = sliderGroup[1].value();
+ * Z = sliderGroup[2].value();
+ * centerX = sliderGroup[3].value();
+ * centerY = sliderGroup[4].value();
+ * centerZ = sliderGroup[5].value();
+ * camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0);
+ * stroke(255);
+ * fill(255, 102, 94);
+ * box(85);
+ * }
+ *
+ *
+ * @alt
+ * White square repeatedly grows to fill canvas and then shrinks.
+ * An interactive example of a red cube with 3 sliders for moving it across x, y,
+ * z axis and 3 sliders for shifting its center.
+ */
+
+ _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.
+ * This projection represents depth through foreshortening: objects
+ * that are close to the camera appear their actual size while those
+ * that are further away from the camera appear smaller.
+ *
+ * The parameters to this function define the viewing frustum
+ * (the truncated pyramid within which objects are seen by the camera) through
+ * vertical field of view, aspect ratio (usually width/height), and near and far
+ * clipping planes.
+ *
+ * If no parameters are given, the following default is used:
+ * perspective(PI/3, width/height, eyeZ/10, eyeZ*10),
+ * where eyeZ is equal to ((height/2) / tan(PI/6)).
+ * @method perspective
+ * @for p5
+ * @param {Number} [fovy] camera frustum vertical field of view,
+ * from bottom to top of view, in angleMode units
+ * @param {Number} [aspect] camera frustum aspect ratio
+ * @param {Number} [near] frustum near plane length
+ * @param {Number} [far] frustum far plane length
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * two colored 3D boxes move back and forth, rotating as mouse is dragged.
+ */
+ _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;
+ };
+ /**
+ * Sets an orthographic projection for the current camera in a 3D sketch
+ * and defines a box-shaped viewing frustum within which objects are seen.
+ * In this projection, all objects with the same dimension appear the same
+ * size, regardless of whether they are near or far from the camera.
+ *
+ * The parameters to this function specify the viewing frustum where
+ * left and right are the minimum and maximum x values, top and bottom are
+ * the minimum and maximum y values, and near and far are the minimum and
+ * maximum z values.
+ *
+ * If no parameters are given, the following default is used:
+ * ortho(-width/2, width/2, -height/2, height/2).
+ * @method ortho
+ * @for p5
+ * @param {Number} [left] camera frustum left plane
+ * @param {Number} [right] camera frustum right plane
+ * @param {Number} [bottom] camera frustum bottom plane
+ * @param {Number} [top] camera frustum top plane
+ * @param {Number} [near] camera frustum near plane
+ * @param {Number} [far] camera frustum far plane
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * two 3D boxes move back and forth along same plane, rotating as mouse is dragged.
+ */
+ _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 as defined by
+ * the parameters.
+ *
+ * A frustum is a geometric form: a pyramid with its top
+ * cut off. With the viewer's eye at the imaginary top of
+ * the pyramid, the six planes of the frustum act as clipping
+ * planes when rendering a 3D view. Thus, any form inside the
+ * clipping planes is visible; anything outside
+ * those planes is not visible.
+ *
+ * Setting the frustum changes the perspective of the scene being rendered.
+ * This can be achieved more simply in many cases by using
+ * perspective().
+ *
+ * If no parameters are given, the following default is used:
+ * frustum(-width/2, width/2, -height/2, height/2, 0, max(width, height)).
+ * @method frustum
+ * @for p5
+ * @param {Number} [left] camera frustum left plane
+ * @param {Number} [right] camera frustum right plane
+ * @param {Number} [bottom] camera frustum bottom plane
+ * @param {Number} [top] camera frustum top plane
+ * @param {Number} [near] camera frustum near plane
+ * @param {Number} [far] camera frustum far plane
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * two 3D boxes move back and forth along same plane, rotating as mouse is dragged.
+ */
+ _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
+ * (see camera())
+ * and a default perspective projection
+ * (see perspective()).
+ * Its properties can be controlled with the p5.Camera
+ * methods.
+ *
+ * Note: Every 3D sketch starts with a default camera initialized.
+ * This camera can be controlled with the global methods
+ * camera(),
+ * perspective(), ortho(),
+ * and frustum() if it is the only camera
+ * in the scene.
+ * @method createCamera
+ * @return {p5.Camera} The newly created camera object.
+ * @for p5
+ * @example
+ *
+ * // Creates a camera object and animates it around a box.
+ * let camera;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(0);
+ * camera = createCamera();
+ * describe('An example that creates a camera and moves it around the box.');
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * // The camera will automatically
+ * // rotate to look at [0, 0, 0].
+ * camera.lookAt(0, 0, 0);
+ *
+ * // The camera will move on the
+ * // x axis.
+ * camera.setPosition(sin(frameCount / 60) * 200, 0, 100);
+ * box(20);
+ *
+ * // A 'ground' box to give the viewer
+ * // a better idea of where the camera
+ * // is looking.
+ * translate(0, 50, 0);
+ * rotateX(HALF_PI);
+ * box(150, 150, 20);
+ * }
+ *
+ *
+ * @alt
+ * An example that creates a camera and moves it around the box.
+ */
+ _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;
+ };
+ /**
+ * This class describes a camera for use in p5's
+ *
+ * WebGL mode. It contains camera position, orientation, and projection
+ * information necessary for rendering a 3D scene.
+ *
+ * New p5.Camera objects can be made through the
+ * createCamera() function and controlled through
+ * the methods described below. A camera created in this way will use a default
+ * position in the scene and a default perspective projection until these
+ * properties are changed through the various methods available. It is possible
+ * to create multiple cameras, in which case the current camera
+ * can be set through the setCamera() method.
+ *
+ * Note:
+ * The methods below operate in two coordinate systems: the 'world' coordinate
+ * system describe positions in terms of their relationship to the origin along
+ * the X, Y and Z axes whereas the camera's 'local' coordinate system
+ * describes positions from the camera's point of view: left-right, up-down,
+ * and forward-backward. The move() method,
+ * for instance, moves the camera along its own axes, whereas the
+ * setPosition()
+ * method sets the camera's position in world-space.
+ *
+ * The camera object propreties
+ * eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ
+ * which describes camera position, orientation, and projection
+ * are also accessible via the camera object generated using
+ * createCamera()
+ *
+ * @class p5.Camera
+ * @param {rendererGL} rendererGL instance of WebGL renderer
+ * @example
+ *
+ *
+ * let cam;
+ * let delta = 0.01;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * cam = createCamera();
+ * // set initial pan angle
+ * cam.pan(-0.8);
+ * describe(
+ * 'camera view pans left and right across a series of rotating 3D boxes.'
+ * );
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // pan camera according to angle 'delta'
+ * cam.pan(delta);
+ *
+ * // every 160 frames, switch direction
+ * if (frameCount % 160 === 0) {
+ * delta *= -1;
+ * }
+ *
+ * rotateX(frameCount * 0.01);
+ * translate(-100, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * translate(35, 0, 0);
+ * box(20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * camera view pans left and right across a series of rotating 3D boxes.
+ */
+ _main.default.Camera = function (renderer) {
+ this._renderer = renderer;
+ this.cameraType = 'default';
+ this.cameraMatrix = new _main.default.Matrix();
+ this.projMatrix = new _main.default.Matrix();
+ };
+ /**
+ * camera position value on x axis
+ * @property {Number} eyeX
+ * @readonly
+ * @example
+ *
+ *
+ * let cam, div;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(0);
+ * cam = createCamera();
+ * div = createDiv();
+ * div.position(0, 0);
+ * describe('An example showing the use of camera object properties');
+ * }
+ *
+ * function draw() {
+ * orbitControl();
+ * box(10);
+ * div.html('eyeX = ' + cam.eyeX);
+ * }
+ *
+ *
+ * @alt
+ * An example showing the use of camera object properties
+ *
+ */
+ /**
+ * camera position value on y axis
+ * @property {Number} eyeY
+ * @readonly
+ * @example
+ *
+ * let cam, div;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(0);
+ * cam = createCamera();
+ * div = createDiv();
+ * div.position(0, 0);
+ * describe('An example showing the use of camera object properties');
+ * }
+ *
+ * function draw() {
+ * orbitControl();
+ * box(10);
+ * div.html('eyeY = ' + cam.eyeY);
+ * }
+ *
+ *
+ * @alt
+ * An example showing the use of camera object properties
+ *
+ */
+ /**
+ * camera position value on z axis
+ * @property {Number} eyeZ
+ * @readonly
+ * @example
+ *
+ * let cam, div;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(0);
+ * cam = createCamera();
+ * div = createDiv();
+ * div.position(0, 0);
+ * describe('An example showing the use of camera object properties');
+ * }
+ *
+ * function draw() {
+ * orbitControl();
+ * box(10);
+ * div.html('eyeZ = ' + cam.eyeZ);
+ * }
+ *
+ *
+ * @alt
+ * An example showing the use of camera object properties
+ *
+ */
+ /**
+ * x coordinate representing center of the sketch
+ * @property {Number} centerX
+ * @readonly
+ * @example
+ *
+ * let cam, div;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(255);
+ * cam = createCamera();
+ * cam.lookAt(1, 0, 0);
+ * div = createDiv('centerX = ' + cam.centerX);
+ * div.position(0, 0);
+ * div.style('color', 'white');
+ * describe('An example showing the use of camera object properties');
+ * }
+ *
+ * function draw() {
+ * orbitControl();
+ * box(10);
+ * }
+ *
+ *
+ * @alt
+ * An example showing the use of camera object properties
+ *
+ */
+ /**
+ * y coordinate representing center of the sketch
+ * @property {Number} centerY
+ * @readonly
+ * @example
+ *
+ * let cam, div;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(255);
+ * cam = createCamera();
+ * cam.lookAt(0, 1, 0);
+ * div = createDiv('centerY = ' + cam.centerY);
+ * div.position(0, 0);
+ * div.style('color', 'white');
+ * describe('An example showing the use of camera object properties');
+ * }
+ *
+ * function draw() {
+ * orbitControl();
+ * box(10);
+ * }
+ *
+ *
+ * @alt
+ * An example showing the use of camera object properties
+ *
+ */
+ /**
+ * z coordinate representing center of the sketch
+ * @property {Number} centerZ
+ * @readonly
+ * @example
+ *
+ * let cam, div;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(255);
+ * cam = createCamera();
+ * cam.lookAt(0, 0, 1);
+ * div = createDiv('centerZ = ' + cam.centerZ);
+ * div.position(0, 0);
+ * div.style('color', 'white');
+ * describe('An example showing the use of camera object properties');
+ * }
+ *
+ * function draw() {
+ * orbitControl();
+ * box(10);
+ * }
+ *
+ *
+ * @alt
+ * An example showing the use of camera object properties
+ *
+ */
+ /**
+ * x component of direction 'up' from camera
+ * @property {Number} upX
+ * @readonly
+ * @example
+ *
+ * let cam, div;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(255);
+ * cam = createCamera();
+ * div = createDiv('upX = ' + cam.upX);
+ * div.position(0, 0);
+ * div.style('color', 'blue');
+ * div.style('font-size', '18px');
+ * describe('An example showing the use of camera object properties');
+ * }
+ *
+ *
+ * @alt
+ * An example showing the use of camera object properties
+ *
+ */
+ /**
+ * y component of direction 'up' from camera
+ * @property {Number} upY
+ * @readonly
+ * @example
+ *
+ * let cam, div;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(255);
+ * cam = createCamera();
+ * div = createDiv('upY = ' + cam.upY);
+ * div.position(0, 0);
+ * div.style('color', 'blue');
+ * div.style('font-size', '18px');
+ * describe('An example showing the use of camera object properties');
+ * }
+ *
+ *
+ * @alt
+ * An example showing the use of camera object properties
+ *
+ */
+ /**
+ * z component of direction 'up' from camera
+ * @property {Number} upZ
+ * @readonly
+ * @example
+ *
+ * let cam, div;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(255);
+ * cam = createCamera();
+ * div = createDiv('upZ = ' + cam.upZ);
+ * div.position(0, 0);
+ * div.style('color', 'blue');
+ * div.style('font-size', '18px');
+ * describe('An example showing the use of camera object properties');
+ * }
+ *
+ *
+ * @alt
+ * An example showing the use of camera object properties
+ *
+ */
+ ////////////////////////////////////////////////////////////////////////////////
+ // Camera Projection Methods
+ ////////////////////////////////////////////////////////////////////////////////
+ /**
+ * Sets a perspective projection.
+ * Accepts the same parameters as the global
+ * perspective().
+ * More information on this function can be found there.
+ * @method perspective
+ * @for p5.Camera
+ * @example
+ *
+ * @alt
+ * two 3D boxes move back and forth along same plane, rotating as mouse is dragged.
+ */
+ _main.default.Camera.prototype.ortho = function (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);
+ var w = right - left;
+ var h = top - bottom;
+ var d = far - near;
+ var x = + 2 / w;
+ var y = + 2 / h;
+ 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.mat4[0], this.projMatrix.mat4[1], this.projMatrix.mat4[2], this.projMatrix.mat4[3], this.projMatrix.mat4[4], this.projMatrix.mat4[5], this.projMatrix.mat4[6], this.projMatrix.mat4[7], this.projMatrix.mat4[8], this.projMatrix.mat4[9], this.projMatrix.mat4[10], this.projMatrix.mat4[11], this.projMatrix.mat4[12], this.projMatrix.mat4[13], this.projMatrix.mat4[14], this.projMatrix.mat4[15]);
+ }
+ this.cameraType = 'custom';
+ };
+ /**
+ * Sets the camera's frustum.
+ * Accepts the same parameters as the global
+ * frustum().
+ * More information on this function can be found there.
+ * @method frustum
+ * @for p5.Camera
+ * @example
+ *
+ *
+ * @alt
+ * camera view pans left and right across a series of rotating 3D boxes.
+ */
+ _main.default.Camera.prototype.pan = function (amount) {
+ var local = this._getLocalAxes();
+ this._rotateView(amount, local.y[0], local.y[1], local.y[2]);
+ };
+ /**
+ * Tilting rotates the camera view up and down.
+ * @method tilt
+ * @param {Number} angle amount to rotate camera in current
+ * angleMode units.
+ * Greater than 0 values rotate counterclockwise (to the left).
+ * @example
+ *
+ *
+ * @alt
+ * camera view tilts up and down across a series of rotating 3D boxes.
+ */
+ _main.default.Camera.prototype.tilt = function (amount) {
+ var local = this._getLocalAxes();
+ this._rotateView(amount, local.x[0], local.x[1], local.x[2]);
+ };
+ /**
+ * Reorients the camera to look at a position in world space.
+ * @method lookAt
+ * @for p5.Camera
+ * @param {Number} x x position of a point in world space
+ * @param {Number} y y position of a point in world space
+ * @param {Number} z z position of a point in world space
+ * @example
+ *
+ *
+ * @alt
+ * camera view of rotating 3D cubes changes to look at a new random
+ * point every second .
+ */
+ _main.default.Camera.prototype.lookAt = function (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 camera's position and orientation.
+ * Accepts the same parameters as the global
+ * camera().
+ * More information on this function can be found there.
+ * @method camera
+ * @for p5.Camera
+ * @example
+ *
+ *
+ * let cam;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * // Create a camera.
+ * // createCamera() sets the newly created camera as
+ * // the current (active) camera.
+ * cam = createCamera();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * // Move the camera away from the plane by a sin wave
+ * cam.camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0);
+ * plane(10, 10);
+ * }
+ *
+ *
+ * @alt
+ * White square repeatedly grows to fill canvas and then shrinks.
+ *
+ * @example
+ *
+ *
+ * // move slider to see changes!
+ * // sliders control the first 6 parameters of camera()
+ *
+ * let sliderGroup = [];
+ * let X;
+ * let Y;
+ * let Z;
+ * let centerX;
+ * let centerY;
+ * let centerZ;
+ * let h = 20;
+ * let cam;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * // create a camera
+ * cam = createCamera();
+ * // create sliders
+ * for (var i = 0; i < 6; i++) {
+ * if (i === 2) {
+ * sliderGroup[i] = createSlider(10, 400, 200);
+ * } else {
+ * sliderGroup[i] = createSlider(-400, 400, 0);
+ * }
+ * h = map(i, 0, 6, 5, 85);
+ * sliderGroup[i].position(10, height + h);
+ * sliderGroup[i].style('width', '80px');
+ * }
+ * }
+ *
+ * function draw() {
+ * background(60);
+ * // assigning sliders' value to each parameters
+ * X = sliderGroup[0].value();
+ * Y = sliderGroup[1].value();
+ * Z = sliderGroup[2].value();
+ * centerX = sliderGroup[3].value();
+ * centerY = sliderGroup[4].value();
+ * centerZ = sliderGroup[5].value();
+ * cam.camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0);
+ * stroke(255);
+ * fill(255, 102, 94);
+ * box(85);
+ * }
+ *
+ *
+ * @alt
+ * An interactive example of a red cube with 3 sliders for moving it across x, y,
+ * z axis and 3 sliders for shifting its center.
+ */
+ _main.default.Camera.prototype.camera = function (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.mat4[0], this.cameraMatrix.mat4[1], this.cameraMatrix.mat4[2], this.cameraMatrix.mat4[3], this.cameraMatrix.mat4[4], this.cameraMatrix.mat4[5], this.cameraMatrix.mat4[6], this.cameraMatrix.mat4[7], this.cameraMatrix.mat4[8], this.cameraMatrix.mat4[9], this.cameraMatrix.mat4[10], this.cameraMatrix.mat4[11], this.cameraMatrix.mat4[12], this.cameraMatrix.mat4[13], this.cameraMatrix.mat4[14], this.cameraMatrix.mat4[15]);
+ }
+ return this;
+ };
+ /**
+ * Move camera along its local axes while maintaining current camera orientation.
+ * @method move
+ * @param {Number} x amount to move along camera's left-right axis
+ * @param {Number} y amount to move along camera's up-down axis
+ * @param {Number} z amount to move along camera's forward-backward axis
+ * @example
+ *
+ *
+ * // see the camera move along its own axes while maintaining its orientation
+ * let cam;
+ * let delta = 0.5;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * cam = createCamera();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // move the camera along its local axes
+ * cam.move(delta, delta, 0);
+ *
+ * // every 100 frames, switch direction
+ * if (frameCount % 150 === 0) {
+ * delta *= -1;
+ * }
+ *
+ * translate(-10, -10, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * camera view moves along a series of 3D boxes, maintaining the same
+ * orientation throughout the move
+ */
+ _main.default.Camera.prototype.move = function (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);
+ };
+ /**
+ * Set camera position in world-space while maintaining current camera
+ * orientation.
+ * @method setPosition
+ * @param {Number} x x position of a point in world space
+ * @param {Number} y y position of a point in world space
+ * @param {Number} z z position of a point in world space
+ * @example
+ *
+ *
+ * @alt
+ * black canvas with purple cube spinning
+ */
+ _main.default.RendererGL.prototype.fill = function (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
+ *
+ *
+ * @alt
+ * black canvas with two purple rotating spheres with pink
+ * outlines the sphere on top has much heavier outlines,
+ */
+ _main.default.RendererGL.prototype.strokeWeight = function (w) {
+ if (this.curStrokeWeight !== w) {
+ this.pointSize = w;
+ this.curStrokeWeight = w;
+ }
+ }; // x,y are canvas-relative (pre-scaled by _pixelDensity)
+ _main.default.RendererGL.prototype._getPixel = function (x, y) {
+ var imageData,
+ index;
+ imageData = new Uint8Array(4);
+ this.drawingContext.readPixels(x, y, 1, 1, this.drawingContext.RGBA, this.drawingContext.UNSIGNED_BYTE, imageData);
+ index = 0;
+ return [imageData[index + 0],
+ imageData[index + 1],
+ imageData[index + 2],
+ imageData[index + 3]];
+ };
+ /**
+ * 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
+ */
+ _main.default.RendererGL.prototype.loadPixels = function () {
+ var pixelsState = this._pixelsState; //@todo_FES
+ if (this._pInst._glAttributes.preserveDrawingBuffer !== true) {
+ console.log('loadPixels only works in WebGL when preserveDrawingBuffer ' + 'is true.');
+ return;
+ } //if there isn't a renderer-level temporary pixels buffer
+ //make a new one
+
+ var pixels = pixelsState.pixels;
+ var len = this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4;
+ if (!(pixels instanceof Uint8Array) || pixels.length !== len) {
+ pixels = new Uint8Array(len);
+ this._pixelsState._setProperty('pixels', pixels);
+ }
+ var pd = this._pInst._pixelDensity;
+ this.GL.readPixels(0, 0, this.width * pd, this.height * pd, this.GL.RGBA, this.GL.UNSIGNED_BYTE, pixels);
+ }; //////////////////////////////////////////////
+ // HASH | for geometry
+ //////////////////////////////////////////////
+ _main.default.RendererGL.prototype.geometryInHash = function (gId) {
+ return this.retainedMode.geometry[gId] !== undefined;
+ };
+ /**
+ * [resize description]
+ * @private
+ * @param {Number} w [description]
+ * @param {Number} h [description]
+ */
+ _main.default.RendererGL.prototype.resize = function (w, h) {
+ _main.default.Renderer.prototype.resize.call(this, w, h);
+ this.GL.viewport(0, 0, this.GL.drawingBufferWidth, this.GL.drawingBufferHeight);
+ this._viewport = this.GL.getParameter(this.GL.VIEWPORT);
+ 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));
+ }
+ };
+ /**
+ * 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.
+ */
+ _main.default.RendererGL.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.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);
+ };
+ _main.default.RendererGL.prototype.applyMatrix = function (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
+ */
+ _main.default.RendererGL.prototype.translate = function (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
+ */
+ _main.default.RendererGL.prototype.scale = function (x, y, z) {
+ this.uMVMatrix.scale(x, y, z);
+ return this;
+ };
+ _main.default.RendererGL.prototype.rotate = function (rad, axis) {
+ if (typeof axis === 'undefined') {
+ return this.rotateZ(rad);
+ }
+ _main.default.Matrix.prototype.rotate.apply(this.uMVMatrix, arguments);
+ return this;
+ };
+ _main.default.RendererGL.prototype.rotateX = function (rad) {
+ this.rotate(rad, 1, 0, 0);
+ return this;
+ };
+ _main.default.RendererGL.prototype.rotateY = function (rad) {
+ this.rotate(rad, 0, 1, 0);
+ return this;
+ };
+ _main.default.RendererGL.prototype.rotateZ = function (rad) {
+ this.rotate(rad, 0, 0, 1);
+ return this;
+ };
+ _main.default.RendererGL.prototype.push = function () {
+ // 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._useSpecularMaterial = this._useSpecularMaterial;
+ properties._useEmissiveMaterial = this._useEmissiveMaterial;
+ properties._useShininess = this._useShininess;
+ 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;
+ return style;
+ };
+ _main.default.RendererGL.prototype.resetMatrix = function () {
+ this.uMVMatrix.set(this._curCamera.cameraMatrix.mat4[0], this._curCamera.cameraMatrix.mat4[1], this._curCamera.cameraMatrix.mat4[2], this._curCamera.cameraMatrix.mat4[3], this._curCamera.cameraMatrix.mat4[4], this._curCamera.cameraMatrix.mat4[5], this._curCamera.cameraMatrix.mat4[6], this._curCamera.cameraMatrix.mat4[7], this._curCamera.cameraMatrix.mat4[8], this._curCamera.cameraMatrix.mat4[9], this._curCamera.cameraMatrix.mat4[10], this._curCamera.cameraMatrix.mat4[11], this._curCamera.cameraMatrix.mat4[12], this._curCamera.cameraMatrix.mat4[13], this._curCamera.cameraMatrix.mat4[14], this._curCamera.cameraMatrix.mat4[15]);
+ 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.
+ */
+ _main.default.RendererGL.prototype._getImmediateStrokeShader = function () {
+ // select the stroke shader to use
+ var stroke = this.userStrokeShader;
+ if (!stroke || !stroke.isStrokeShader()) {
+ return this._getLineShader();
+ }
+ return stroke;
+ };
+ _main.default.RendererGL.prototype._getRetainedStrokeShader = _main.default.RendererGL.prototype._getImmediateStrokeShader;
+ /*
+ * selects which fill shader should be used based on renderer state,
+ * for use with begin/endShape and immediate vertex mode.
+ */
+ _main.default.RendererGL.prototype._getImmediateFillShader = function () {
+ 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.
+ */
+ _main.default.RendererGL.prototype._getRetainedFillShader = function () {
+ 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;
+ };
+ _main.default.RendererGL.prototype._getImmediatePointShader = function () {
+ // select the point shader to use
+ var point = this.userPointShader;
+ if (!point || !point.isPointShader()) {
+ return this._getPointShader();
+ }
+ return point;
+ };
+ _main.default.RendererGL.prototype._getRetainedLineShader = _main.default.RendererGL.prototype._getImmediateLineShader;
+ _main.default.RendererGL.prototype._getLightShader = function () {
+ if (!this._defaultLightShader) {
+ if (this._pInst._glAttributes.perPixelLighting) {
+ this._defaultLightShader = new _main.default.Shader(this, defaultShaders.phongVert, defaultShaders.phongFrag);
+ } else {
+ this._defaultLightShader = new _main.default.Shader(this, defaultShaders.lightVert, defaultShaders.lightTextureFrag);
+ }
+ }
+ return this._defaultLightShader;
+ };
+ _main.default.RendererGL.prototype._getImmediateModeShader = function () {
+ if (!this._defaultImmediateModeShader) {
+ this._defaultImmediateModeShader = new _main.default.Shader(this, defaultShaders.immediateVert, defaultShaders.vertexColorFrag);
+ }
+ return this._defaultImmediateModeShader;
+ };
+ _main.default.RendererGL.prototype._getNormalShader = function () {
+ if (!this._defaultNormalShader) {
+ this._defaultNormalShader = new _main.default.Shader(this, defaultShaders.normalVert, defaultShaders.normalFrag);
+ }
+ return this._defaultNormalShader;
+ };
+ _main.default.RendererGL.prototype._getColorShader = function () {
+ if (!this._defaultColorShader) {
+ this._defaultColorShader = new _main.default.Shader(this, defaultShaders.normalVert, defaultShaders.basicFrag);
+ }
+ return this._defaultColorShader;
+ };
+ _main.default.RendererGL.prototype._getPointShader = function () {
+ if (!this._defaultPointShader) {
+ this._defaultPointShader = new _main.default.Shader(this, defaultShaders.pointVert, defaultShaders.pointFrag);
+ }
+ return this._defaultPointShader;
+ };
+ _main.default.RendererGL.prototype._getLineShader = function () {
+ if (!this._defaultLineShader) {
+ this._defaultLineShader = new _main.default.Shader(this, defaultShaders.lineVert, defaultShaders.lineFrag);
+ }
+ return this._defaultLineShader;
+ };
+ _main.default.RendererGL.prototype._getFontShader = function () {
+ if (!this._defaultFontShader) {
+ this.GL.getExtension('OES_standard_derivatives');
+ this._defaultFontShader = new _main.default.Shader(this, defaultShaders.fontVert, defaultShaders.fontFrag);
+ }
+ return this._defaultFontShader;
+ };
+ _main.default.RendererGL.prototype._getEmptyTexture = function () {
+ 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;
+ };
+ _main.default.RendererGL.prototype.getTexture = function (img) {
+ var textures = this.textures;
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+ try {
+ for (var _iterator = textures[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var texture = _step.value;
+ if (texture.src === img) return texture;
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+ var tex = new _main.default.Texture(this, img);
+ textures.push(tex);
+ return tex;
+ };
+ _main.default.RendererGL.prototype._setStrokeUniforms = function (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]);
+ };
+ _main.default.RendererGL.prototype._setFillUniforms = function (fillShader) {
+ fillShader.bindShader(); // 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('uAmbientMatColor', this.curAmbientColor);
+ fillShader.setUniform('uSpecularMatColor', this.curSpecularColor);
+ fillShader.setUniform('uEmissiveMatColor', this.curEmissiveColor);
+ fillShader.setUniform('uSpecular', this._useSpecularMaterial);
+ fillShader.setUniform('uEmissive', this._useEmissiveMaterial);
+ fillShader.setUniform('uShininess', this._useShininess);
+ 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;
+ fillShader.setUniform('uAmbientLightCount', ambientLightCount);
+ fillShader.setUniform('uAmbientColor', this.ambientLightColors);
+ 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();
+ };
+ _main.default.RendererGL.prototype._setPointUniforms = function (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
+ */
+ _main.default.RendererGL.prototype._bindBuffer = function (buffer, target, values, type, usage) {
+ if (!target) target = this.GL.ARRAY_BUFFER;
+ this.GL.bindBuffer(target, buffer);
+ if (values !== undefined) {
+ var data = new (type || Float32Array) (values);
+ this.GL.bufferData(target, data, usage || this.GL.STATIC_DRAW);
+ }
+ }; ///////////////////////////////
+ //// UTILITY FUNCTIONS
+ //////////////////////////////
+ _main.default.RendererGL.prototype._arraysEqual = function (a, b) {
+ var aLength = a.length;
+ if (aLength !== b.length) return false;
+ for (var i = 0; i < aLength; i++) {
+ if (a[i] !== b[i]) return false;
+ }
+ return true;
+ };
+ _main.default.RendererGL.prototype._isTypedArray = function (arr) {
+ var res = false;
+ res = arr instanceof Float32Array;
+ res = arr instanceof Float64Array;
+ res = arr instanceof Int16Array;
+ res = arr instanceof Uint16Array;
+ res = arr instanceof Uint32Array;
+ return res;
+ };
+ /**
+ * 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]
+ */
+ _main.default.RendererGL.prototype._flatten = function (arr) {
+ //when empty, return empty
+ if (arr.length === 0) {
+ return [];
+ } else if (arr.length > 20000) {
+ //big models , load slower to avoid stack overflow
+ //faster non-recursive flatten via axelduch
+ //stackoverflow.com/questions/27266550/how-to-flatten-nested-array-in-javascript
+ var _toString = Object.prototype.toString;
+ var arrayTypeStr = '[object Array]';
+ var result = [
+ ];
+ var nodes = arr.slice();
+ var node;
+ node = nodes.pop();
+ do {
+ if (_toString.call(node) === arrayTypeStr) {
+ nodes.push.apply(nodes, _toConsumableArray(node));
+ } else {
+ result.push(node);
+ }
+ } while (nodes.length && (node = nodes.pop()) !== undefined);
+ result.reverse(); // we reverse result to restore the original order
+ return result;
+ } else {
+ var _ref; //otherwise if model within limits for browser
+ //use faster recursive loading
+ return (_ref = [
+ ]).concat.apply(_ref, _toConsumableArray(arr));
+ }
+ };
+ /**
+ * 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]
+ */
+ _main.default.RendererGL.prototype._vToNArray = function (arr) {
+ var ret = [
+ ];
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+ try {
+ for (var _iterator2 = arr[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
+ var item = _step2.value;
+ ret.push(item.x, item.y, item.z);
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+ return ret;
+ };
+ /**
+ * 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;
+ _main.default.RendererGL.prototype._initTessy = function initTesselator() {
+ // function called for each vertex of tesselator output
+ function vertexCallback(data, polyVertArray) {
+ for (var i = 0; i < data.length; i++) {
+ polyVertArray[polyVertArray.length] = data[i];
+ }
+ }
+ 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);
+ return tessy;
+ };
+ _main.default.RendererGL.prototype._triangulate = function (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);
+ for (var i = 0; i < contours.length; i++) {
+ this._tessy.gluTessBeginContour();
+ var contour = contours[i];
+ 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
+
+ this._tessy.gluTessEndPolygon();
+ return triangleVerts;
+ }; // function to calculate BezierVertex Coefficients
+ _main.default.RendererGL.prototype._bezierCoefficients = function (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
+ _main.default.RendererGL.prototype._quadraticCoefficients = function (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
+ _main.default.RendererGL.prototype._bezierToCatmull = function (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;
+ };
+ var _default = _main.default.RendererGL;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 278,
+ '../core/main': 290,
+ '../core/p5.Renderer': 293,
+ './p5.Camera': 338,
+ './p5.Matrix': 340,
+ './p5.Shader': 345,
+ 'core-js/modules/es.array.concat': 167,
+ 'core-js/modules/es.array.fill': 170,
+ 'core-js/modules/es.array.filter': 171,
+ 'core-js/modules/es.array.from': 173,
+ 'core-js/modules/es.array.includes': 174,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.object.assign': 190,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.to-string': 200,
+ 'core-js/modules/es.string.includes': 203,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.typed-array.copy-within': 215,
+ 'core-js/modules/es.typed-array.every': 216,
+ 'core-js/modules/es.typed-array.fill': 217,
+ 'core-js/modules/es.typed-array.filter': 218,
+ 'core-js/modules/es.typed-array.find': 220,
+ 'core-js/modules/es.typed-array.find-index': 219,
+ 'core-js/modules/es.typed-array.float32-array': 221,
+ 'core-js/modules/es.typed-array.float64-array': 222,
+ 'core-js/modules/es.typed-array.for-each': 223,
+ 'core-js/modules/es.typed-array.includes': 224,
+ 'core-js/modules/es.typed-array.index-of': 225,
+ 'core-js/modules/es.typed-array.int16-array': 226,
+ 'core-js/modules/es.typed-array.iterator': 228,
+ 'core-js/modules/es.typed-array.join': 229,
+ 'core-js/modules/es.typed-array.last-index-of': 230,
+ 'core-js/modules/es.typed-array.map': 231,
+ 'core-js/modules/es.typed-array.reduce': 233,
+ 'core-js/modules/es.typed-array.reduce-right': 232,
+ 'core-js/modules/es.typed-array.reverse': 234,
+ 'core-js/modules/es.typed-array.set': 235,
+ 'core-js/modules/es.typed-array.slice': 236,
+ 'core-js/modules/es.typed-array.some': 237,
+ 'core-js/modules/es.typed-array.sort': 238,
+ 'core-js/modules/es.typed-array.subarray': 239,
+ 'core-js/modules/es.typed-array.to-locale-string': 240,
+ 'core-js/modules/es.typed-array.to-string': 241,
+ 'core-js/modules/es.typed-array.uint16-array': 242,
+ 'core-js/modules/es.typed-array.uint32-array': 243,
+ 'core-js/modules/es.typed-array.uint8-array': 244,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248,
+ 'libtess': 261,
+ 'path': 264
+ }
+ ],
+ 345: [
+ 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.function.name');
+ _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.function.name');
+ _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
+ };
+ } /**
+ * This module defines the p5.Shader class
+ * @module 3D
+ * @submodule Material
+ * @for p5
+ * @requires core
+ */
+ /**
+ * Shader class for WEBGL Mode
+ * @class p5.Shader
+ * @constructor
+ * @param {p5.RendererGL} renderer an instance of p5.RendererGL that
+ * will provide the GL context for this new p5.Shader
+ * @param {String} vertSrc source code for the vertex shader (as a string)
+ * @param {String} fragSrc source code for the fragment shader (as a string)
+ */
+
+ _main.default.Shader = function (renderer, vertSrc, fragSrc) {
+ // 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
+ */
+ _main.default.Shader.prototype.init = function () {
+ 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)) {
+ console.error('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)) {
+ console.error('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)) {
+ console.error('Snap! Error linking shader program: '.concat(gl.getProgramInfoLog(this._glProgram)));
+ }
+ this._loadAttributes();
+ this._loadUniforms();
+ }
+ return this;
+ };
+ /**
+ * Queries the active attributes for this shader and loads
+ * their names and locations into the attributes array.
+ * @method _loadAttributes
+ * @private
+ */
+ _main.default.Shader.prototype._loadAttributes = function () {
+ 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
+ */
+ _main.default.Shader.prototype._loadUniforms = function () {
+ 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 thats 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;
+ };
+ _main.default.Shader.prototype.compile = function () { // TODO
+ };
+ /**
+ * initializes (if needed) and binds the shader program.
+ * @method bindShader
+ * @private
+ */
+ _main.default.Shader.prototype.bindShader = function () {
+ this.init();
+ if (!this._bound) {
+ this.useProgram();
+ this._bound = true;
+ this._setMatrixUniforms();
+ this.setUniform('uViewport', this._renderer._viewport);
+ }
+ };
+ /**
+ * @method unbindShader
+ * @chainable
+ * @private
+ */
+ _main.default.Shader.prototype.unbindShader = function () {
+ if (this._bound) {
+ this.unbindTextures(); //this._renderer.GL.useProgram(0); ??
+ this._bound = false;
+ }
+ return this;
+ };
+ _main.default.Shader.prototype.bindTextures = function () {
+ 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;
+ }
+ }
+ }
+ };
+ _main.default.Shader.prototype.updateTextures = function () {
+ 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;
+ }
+ }
+ }
+ };
+ _main.default.Shader.prototype.unbindTextures = function () {
+ 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;
+ }
+ }
+ }
+ };
+ _main.default.Shader.prototype._setMatrixUniforms = function () {
+ 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()) {
+ if (this._renderer._curCamera.cameraType === 'default') {
+ // strokes scale up as they approach camera, default
+ this.setUniform('uPerspective', 1);
+ } else {
+ // strokes have uniform scale regardless of distance from camera
+ this.setUniform('uPerspective', 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);
+ }
+ };
+ /**
+ * @method useProgram
+ * @chainable
+ * @private
+ */
+ _main.default.Shader.prototype.useProgram = function () {
+ var gl = this._renderer.GL;
+ if (this._renderer._curShader !== this) {
+ gl.useProgram(this._glProgram);
+ this._renderer._curShader = this;
+ }
+ return this;
+ };
+ /**
+ * Used to set the uniforms of a
+ * p5.Shader object.
+ *
+ * Uniforms are used as a way to provide shader programs
+ * (which run on the GPU) with values from a sketch
+ * (which runs on the CPU).
+ *
+ * @method setUniform
+ * @chainable
+ * @param {String} uniformName the name of the uniform.
+ * Must correspond to the name used in the vertex and fragment shaders
+ * @param {Boolean|Number|Number[]|p5.Image|p5.Graphics|p5.MediaElement|p5.Texture}
+ * data the data to associate with the uniform. The type can be
+ * a boolean (true/false), a number, an array of numbers, or
+ * an image (p5.Image, p5.Graphics, p5.MediaElement, p5.Texture)
+ *
+ * @example
+ *
+ *
+ * // Click within the image to toggle the value of uniforms
+ * // Note: for an alternative approach to the same example,
+ * // involving toggling between shaders please refer to:
+ * // https://p5js.org/reference/#/p5/shader
+ *
+ * let grad;
+ * let showRedGreen = false;
+ *
+ * function preload() {
+ * // note that we are using two instances
+ * // of the same vertex and fragment shaders
+ * grad = loadShader('assets/shader.vert', 'assets/shader-gradient.frag');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * shader(grad);
+ * noStroke();
+ *
+ * describe(
+ * 'canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.'
+ * );
+ * }
+ *
+ * function draw() {
+ * // update the offset values for each scenario,
+ * // moving the "grad" shader in either vertical or
+ * // horizontal direction each with differing colors
+ *
+ * if (showRedGreen === true) {
+ * grad.setUniform('colorCenter', [1, 0, 0]);
+ * grad.setUniform('colorBackground', [0, 1, 0]);
+ * grad.setUniform('offset', [sin(millis() / 2000), 1]);
+ * } else {
+ * grad.setUniform('colorCenter', [1, 0.5, 0]);
+ * grad.setUniform('colorBackground', [0.226, 0, 0.615]);
+ * grad.setUniform('offset', [0, sin(millis() / 2000) + 1]);
+ * }
+ * quad(-1, -1, 1, -1, 1, 1, -1, 1);
+ * }
+ *
+ * function mouseClicked() {
+ * showRedGreen = !showRedGreen;
+ * }
+ *
+ *
+ *
+ * @alt
+ * canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.
+ */
+ _main.default.Shader.prototype.setUniform = function (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?)
+ *
+ **/
+ _main.default.Shader.prototype.isLightShader = function () {
+ return this.attributes.aNormal !== undefined || this.uniforms.uUseLighting !== undefined || this.uniforms.uAmbientLightCount !== undefined || this.uniforms.uDirectionalLightCount !== undefined || this.uniforms.uPointLightCount !== undefined || this.uniforms.uAmbientColor !== undefined || this.uniforms.uDirectionalDiffuseColors !== undefined || this.uniforms.uDirectionalSpecularColors !== undefined || this.uniforms.uPointLightLocation !== undefined || this.uniforms.uPointLightDiffuseColors !== undefined || this.uniforms.uPointLightSpecularColors !== undefined || this.uniforms.uLightingDirection !== undefined || this.uniforms.uSpecular !== undefined;
+ };
+ _main.default.Shader.prototype.isNormalShader = function () {
+ return this.attributes.aNormal !== undefined;
+ };
+ _main.default.Shader.prototype.isTextureShader = function () {
+ return this.samplers.length > 0;
+ };
+ _main.default.Shader.prototype.isColorShader = function () {
+ return this.attributes.aVertexColor !== undefined || this.uniforms.uMaterialColor !== undefined;
+ };
+ _main.default.Shader.prototype.isTexLightShader = function () {
+ return this.isLightShader() && this.isTextureShader();
+ };
+ _main.default.Shader.prototype.isStrokeShader = function () {
+ return this.uniforms.uStrokeWeight !== undefined;
+ };
+ /**
+ * @method enableAttrib
+ * @chainable
+ * @private
+ */
+ _main.default.Shader.prototype.enableAttrib = function (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[loc]) {
+ gl.enableVertexAttribArray(loc); // Record register availability
+ this._renderer.registerEnabled[loc] = true;
+ }
+ this._renderer.GL.vertexAttribPointer(loc, size, type || gl.FLOAT, normalized || false, stride || 0, offset || 0);
+ }
+ }
+ return this;
+ };
+ var _default = _main.default.Shader;
+ exports.default = _default;
+ },
+ {
+ '../core/main': 290,
+ 'core-js/modules/es.array.index-of': 175,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.array.slice': 180,
+ 'core-js/modules/es.function.name': 183,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 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.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.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.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
+ };
+ } /**
+ * 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} [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 = function (renderer, obj, settings) {
+ this._renderer = renderer;
+ var gl = this._renderer.GL;
+ settings = settings || {
+ };
+ if (settings.dataType === gl.FLOAT) {
+ var ext = gl.getExtension('OES_texture_float');
+ if (!ext) {
+ console.log('Oh no, your device doesn\'t support floating point textures!');
+ }
+ var linear = gl.getExtension('OES_texture_float_linear');
+ if (!linear) {
+ console.log('Ack! Your device doesn\'t support linear filtering for floating point textures');
+ }
+ }
+ 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; // 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;
+ var textureData = this._getTextureDataFromSource();
+ this.width = textureData.width;
+ this.height = textureData.height;
+ this.init(textureData);
+ return this;
+ };
+ _main.default.Texture.prototype._getTextureDataFromSource = function () {
+ var textureData;
+ 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
+ */
+ _main.default.Texture.prototype.init = function (data) {
+ var gl = this._renderer.GL;
+ 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.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
+ */
+ _main.default.Texture.prototype.update = function () {
+ var data = this.src;
+ if (data.width === 0 || data.height === 0) {
+ return false; // nothing to do!
+ }
+ 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;
+ this.height = textureData.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
+ */
+ _main.default.Texture.prototype.bindTexture = function () {
+ // bind texture using gl context + glTarget and
+ // generated gl texture object
+ var gl = this._renderer.GL;
+ gl.bindTexture(this.glTarget, this.glTex);
+ return this;
+ };
+ /**
+ * Unbinds the texture from the appropriate GL target.
+ * @method unbindTexture
+ */
+ _main.default.Texture.prototype.unbindTexture = function () {
+ // unbind per above, disable texturing on glTarget
+ var gl = this._renderer.GL;
+ gl.bindTexture(this.glTarget, null);
+ };
+ /**
+ * 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
+ */
+ _main.default.Texture.prototype.setInterpolation = function (downScale, upScale) {
+ var gl = this._renderer.GL;
+ if (downScale === constants.NEAREST) {
+ this.glMinFilter = gl.NEAREST;
+ } else {
+ this.glMinFilter = gl.LINEAR;
+ }
+ if (upScale === constants.NEAREST) {
+ this.glMagFilter = gl.NEAREST;
+ } else {
+ this.glMagFilter = gl.LINEAR;
+ }
+ 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();
+ };
+ /**
+ * 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
+ */
+ _main.default.Texture.prototype.setWrapMode = function (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 (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 (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 (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 (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();
+ };
+ var _default = _main.default.Texture;
+ exports.default = _default;
+ },
+ {
+ '../core/constants': 278,
+ '../core/main': 290,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.typed-array.copy-within': 215,
+ 'core-js/modules/es.typed-array.every': 216,
+ 'core-js/modules/es.typed-array.fill': 217,
+ 'core-js/modules/es.typed-array.filter': 218,
+ 'core-js/modules/es.typed-array.find': 220,
+ 'core-js/modules/es.typed-array.find-index': 219,
+ 'core-js/modules/es.typed-array.for-each': 223,
+ 'core-js/modules/es.typed-array.includes': 224,
+ 'core-js/modules/es.typed-array.index-of': 225,
+ 'core-js/modules/es.typed-array.iterator': 228,
+ 'core-js/modules/es.typed-array.join': 229,
+ 'core-js/modules/es.typed-array.last-index-of': 230,
+ 'core-js/modules/es.typed-array.map': 231,
+ 'core-js/modules/es.typed-array.reduce': 233,
+ 'core-js/modules/es.typed-array.reduce-right': 232,
+ 'core-js/modules/es.typed-array.reverse': 234,
+ 'core-js/modules/es.typed-array.set': 235,
+ 'core-js/modules/es.typed-array.slice': 236,
+ 'core-js/modules/es.typed-array.some': 237,
+ 'core-js/modules/es.typed-array.sort': 238,
+ 'core-js/modules/es.typed-array.subarray': 239,
+ 'core-js/modules/es.typed-array.to-locale-string': 240,
+ 'core-js/modules/es.typed-array.to-string': 241,
+ 'core-js/modules/es.typed-array.uint8-array': 244,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 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.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
+ };
+ } // 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.
+ */
+ function ImageInfos(width, height) {
+ 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
+ */
+ this.findImage = function (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
+ };
+ };
+ } /**
+ * @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 = function FontInfo(font) {
+ 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.
+ */
+ this.getGlyphInfo = function (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
+ */
+
+ function Cubic(p0, c0, c1, p1) {
+ 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
+ */
+ this.toQuadratic = function () {
+ 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.
+ */
+ this.quadError = function () {
+ 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.
+ */
+ this.split = function (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.
+ */
+ this.splitInflections = function () {
+ 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;
+ };
+ } /**
+ * @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;
+ };
+ };
+ _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);
+ 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;
+ p.pop();
+ }
+ return p;
+ };
+ },
+ {
+ '../core/constants': 278,
+ '../core/main': 290,
+ './p5.RendererGL.Retained': 343,
+ './p5.Shader': 345,
+ 'core-js/modules/es.array.iterator': 176,
+ 'core-js/modules/es.object.get-own-property-descriptor': 191,
+ 'core-js/modules/es.object.to-string': 195,
+ 'core-js/modules/es.regexp.exec': 199,
+ 'core-js/modules/es.string.iterator': 204,
+ 'core-js/modules/es.string.split': 209,
+ 'core-js/modules/es.string.sub': 210,
+ 'core-js/modules/es.symbol': 214,
+ 'core-js/modules/es.symbol.description': 212,
+ 'core-js/modules/es.symbol.iterator': 213,
+ 'core-js/modules/es.weak-map': 246,
+ 'core-js/modules/web.dom-collections.iterator': 248
+ }
+ ],
+ 348: [
+ 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.'
+ }
+ }
+ },
+ {
+ }
+ ],
+ 349: [
+ 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'
+ ];
+ exports.languages = languages;
+ },
+ {
+ './en/translation': 348
+ }
+ ]
+ }, {
+ }, [
+ 273
+ ]) (273)
+});
diff --git a/switchboard/p5.sound.min-1.js b/switchboard/p5.sound.min-1.js
new file mode 100644
index 0000000..44f2523
--- /dev/null
+++ b/switchboard/p5.sound.min-1.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;np5.Color object, color components,\n or CSS color\n',
+ type: 'p5.Color|Number[]|String'
+ }
+ ],
+ class: 'p5',
+ module: 'Color'
+ },
+ blue: {
+ name: 'blue',
+ params: [
+ {
+ name: 'color',
+ description:
+ '
Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT\n Native CSS properties: 'grab', 'progress', 'cell' etc.\n External: path for cursor's images\n (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)\n For more information on Native CSS cursors and url visit:\n https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT
function to be fired when any user input is\n detected within the element.\n if false is passed instead, the previously\n firing function will no longer fire.
crossOrigin property of the img element; use either \'anonymous\' or \'use-credentials\' to retrieve the image with cross-origin access (for later use with canvas. if an empty string("") is passed, CORS is not used
callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content
callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content
A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension.
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).
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).
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.
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.
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.
function to be fired when mouse is\n double clicked over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
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.
sampleFactor - the ratio of path-length to number of samples\n(default=.1); higher values yield more points and are therefore\nmore precise
\n
simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear
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.
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
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.
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.
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.
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.
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.
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.
This callback function handles the sources when they\n have been enumerated. The callback function\n receives the deviceList array as its only argument
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.
+ *
+ * noStroke();
+ * let c = color(0, 126, 255, 102);
+ * fill(c);
+ * rect(15, 15, 35, 70);
+ * let value = alpha(c); // Sets 'value' to 102
+ * fill(value);
+ * rect(50, 15, 35, 70);
+ *
+ *
+ *
+ * @alt
+ * Left half of canvas light blue and right half light charcoal grey.
+ */ _main.default.prototype.alpha = function(c) {
+ _main.default._validateParameters('alpha', arguments);
+ return this.color(c)._getAlpha();
+ };
+
+ /**
+ * Extracts the blue value from a color or pixel array.
+ *
+ * @method blue
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the blue value
+ * @example
+ *
+ *
+ * let c = color(175, 100, 220);
+ * fill(c);
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ * let blueValue = blue(c);
+ * fill(0, 0, blueValue);
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ *
+ *
+ *
+ * @alt
+ * Left half of canvas light purple and right half a royal blue.
+ */
+ _main.default.prototype.blue = function(c) {
+ _main.default._validateParameters('blue', arguments);
+ return this.color(c)._getBlue();
+ };
+
+ /**
+ * Extracts the HSB brightness value from a color or pixel array.
+ *
+ * @method brightness
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the brightness value
+ *
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = brightness(c); // Sets 'value' to 255
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color('hsb(60, 100%, 50%)');
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = brightness(c); // A 'value' of 50% is 127.5
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ * @alt
+ * Left half of canvas salmon pink and the right half with it's brightness colored white.
+ * Left half of canvas olive colored and the right half with it's brightness color gray.
+ */
+ _main.default.prototype.brightness = function(c) {
+ _main.default._validateParameters('brightness', arguments);
+ return this.color(c)._getBrightness();
+ };
+
+ /**
+ * Creates colors for storing in variables of the color datatype. The
+ * parameters are interpreted as RGB or HSB values depending on the
+ * current colorMode(). The default mode is RGB values from 0 to 255
+ * and, therefore, the function call color(255, 204, 0) will return a
+ * bright yellow color.
+ *
+ * Note that if only one value is provided to color(), it will be interpreted
+ * as a grayscale value. Add a second value, and it will be used for alpha
+ * transparency. When three values are specified, they are interpreted as
+ * either RGB or HSB values. Adding a fourth value applies alpha
+ * transparency.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color
+ * strings and all named color strings are supported. In this case, an alpha
+ * number value as a second argument is not supported, the RGBA form should be
+ * used.
+ *
+ * @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
+ *
+ *
+ * let c = color(255, 204, 0);
+ * fill(c);
+ * noStroke();
+ * ellipse(25, 25, 80, 80); // Draw left circle
+ * // Using only one value generates a grayscale value.
+ * c = color(65);
+ * fill(c);
+ * ellipse(75, 75, 80, 80);
+ *
+ *
+ *
+ *
+ *
+ * // You can use named SVG & CSS colors
+ * let c = color('magenta');
+ * fill(c);
+ * noStroke();
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // Example of hex color codes
+ * noStroke();
+ * let c = color('#0f0');
+ * fill(c);
+ * rect(0, 10, 45, 80);
+ * c = color('#00ff00');
+ * fill(c);
+ * rect(55, 10, 45, 80);
+ *
+ *
+ *
+ *
+ *
+ * // RGB and RGBA color strings are also supported
+ * // these all set to the same color (solid blue)
+ * let c;
+ * noStroke();
+ * c = color('rgb(0,0,255)');
+ * fill(c);
+ * rect(10, 10, 35, 35); // Draw rectangle
+ * c = color('rgb(0%, 0%, 100%)');
+ * fill(c);
+ * rect(55, 10, 35, 35); // Draw rectangle
+ * c = color('rgba(0, 0, 255, 1)');
+ * fill(c);
+ * rect(10, 55, 35, 35); // Draw rectangle
+ * c = color('rgba(0%, 0%, 100%, 1)');
+ * fill(c);
+ * rect(55, 55, 35, 35); // Draw rectangle
+ *
+ *
+ *
+ *
+ *
+ * // HSL color can also be specified by value
+ * let c = color('hsl(160, 100%, 50%)');
+ * noStroke();
+ * fill(c);
+ * rect(0, 10, 45, 80); // Draw rectangle
+ * c = color('hsla(160, 100%, 50%, 0.5)');
+ * fill(c);
+ * rect(55, 10, 45, 80); // Draw rectangle
+ *
+ *
+ *
+ *
+ *
+ * // HSB color can also be specified
+ * let c = color('hsb(160, 100%, 50%)');
+ * noStroke();
+ * fill(c);
+ * rect(0, 10, 45, 80); // Draw rectangle
+ * c = color('hsba(160, 100%, 50%, 0.5)');
+ * fill(c);
+ * rect(55, 10, 45, 80); // Draw rectangle
+ *
+ *
+ *
+ *
+ *
+ * noStroke();
+ * let c = color(50, 55, 100);
+ * fill(c);
+ * rect(0, 10, 45, 80); // Draw left rect
+ * colorMode(HSB, 100);
+ * c = color(50, 55, 100);
+ * fill(c);
+ * rect(55, 10, 45, 80);
+ *
+ *
+ *
+ * @alt
+ * Yellow rect in middle right of canvas, with 55 pixel width and height.
+ * Yellow ellipse in top left of canvas, black ellipse in bottom right,both 80x80.
+ * Bright fuchsia rect in middle of canvas, 60 pixel width and height.
+ * Two bright green rects on opposite sides of the canvas, both 45x80.
+ * Four blue rects in each corner of the canvas, each are 35x35.
+ * Bright sea green rect on left and darker rect on right of canvas, both 45x80.
+ * Dark green rect on left and lighter green rect on right of canvas, both 45x80.
+ * Dark blue rect on left and light teal rect on right of canvas, both 45x80.
+ */
+
+ /**
+ * @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() {
+ _main.default._validateParameters('color', arguments);
+ if (arguments[0] instanceof _main.default.Color) {
+ return arguments[0]; // Do nothing if argument is already a color object.
+ }
+
+ var args = arguments[0] instanceof Array ? arguments[0] : arguments;
+ return new _main.default.Color(this, args);
+ };
+
+ /**
+ * Extracts the green value from a color or pixel array.
+ *
+ * @method green
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the green value
+ * @example
+ *
+ *
+ * let c = color(20, 75, 200); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * let greenValue = green(c); // Get green in 'c'
+ * print(greenValue); // Print "75.0"
+ * fill(0, greenValue, 0); // Use 'greenValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ *
+ *
+ *
+ * @alt
+ * blue rect on left and green on right, both with black outlines & 35x60.
+ */
+ _main.default.prototype.green = function(c) {
+ _main.default._validateParameters('green', arguments);
+ return this.color(c)._getGreen();
+ };
+
+ /**
+ * Extracts the hue value from a color or pixel array.
+ *
+ * Hue exists in both HSB and HSL. This function will return the
+ * HSB-normalized hue when supplied with an HSB color object (or when supplied
+ * with a pixel array while the color mode is HSB), but will default to the
+ * HSL-normalized hue otherwise. (The values will only be different if the
+ * maximum hue setting for each system is different.)
+ *
+ * @method hue
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the hue
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = hue(c); // Sets 'value' to "0"
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ * @alt
+ * salmon pink rect on left and black on right, both 35x60.
+ */
+ _main.default.prototype.hue = function(c) {
+ _main.default._validateParameters('hue', arguments);
+ return this.color(c)._getHue();
+ };
+
+ /**
+ * Blends two colors to find a third color somewhere between them. The amt
+ * parameter is the amount to interpolate between the two values where 0.0
+ * equal to the first color, 0.1 is very near the first color, 0.5 is halfway
+ * in between, etc. An amount below 0 will be treated as 0. Likewise, amounts
+ * above 1 will be capped at 1. This is different from the behavior of lerp(),
+ * but necessary because otherwise numbers outside the range will produce
+ * strange and unexpected colors.
+ *
+ * The way that colors are interpolated depends on the current color mode.
+ *
+ * @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
+ *
+ *
+ * @alt
+ * 4 rects one tan, brown, brownish purple, purple, with white outlines & 20x60
+ */
+
+ _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.
+ l0 = this.lerp(fromArray[0], toArray[0], amt);
+ 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);
+ };
+
+ /**
+ * Extracts the HSL lightness value from a color or pixel array.
+ *
+ * @method lightness
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the lightness
+ *
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSL);
+ * let c = color(156, 100, 50, 1);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = lightness(c); // Sets 'value' to 50
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ * @alt
+ * light pastel green rect on left and dark grey rect on right, both 35x60.
+ */
+ _main.default.prototype.lightness = function(c) {
+ _main.default._validateParameters('lightness', arguments);
+ return this.color(c)._getLightness();
+ };
+
+ /**
+ * Extracts the red value from a color or pixel array.
+ *
+ * @method red
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the red value
+ * @example
+ *
+ *
+ * let c = color(255, 204, 0); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * let redValue = red(c); // Get red in 'c'
+ * print(redValue); // Print "255.0"
+ * fill(redValue, 0, 0); // Use 'redValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ *
+ *
+ *
+ *
+ *
+ * colorMode(RGB, 255); // Sets the range for red, green, and blue to 255
+ * let c = color(127, 255, 0);
+ * colorMode(RGB, 1); // Sets the range for red, green, and blue to 1
+ * let myColor = red(c);
+ * print(myColor); // 0.4980392156862745
+ *
+ *
+ *
+ * @alt
+ * yellow rect on left and red rect on right, both with black outlines and 35x60.
+ * grey canvas
+ */
+ _main.default.prototype.red = function(c) {
+ _main.default._validateParameters('red', arguments);
+ return this.color(c)._getRed();
+ };
+
+ /**
+ * Extracts the saturation value from a color or pixel array.
+ *
+ * Saturation is scaled differently in HSB and HSL. This function will return
+ * the HSB saturation when supplied with an HSB color object (or when supplied
+ * with a pixel array while the color mode is HSB), but will default to the
+ * HSL saturation otherwise.
+ *
+ * @method saturation
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the saturation value
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * let c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * let value = saturation(c); // Sets 'value' to 126
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ * @alt
+ *deep pink rect on left and grey rect on right, both 35x60.
+ */
+ _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': 43,
+ '../core/friendly_errors/fes_core': 46,
+ '../core/friendly_errors/file_errors': 47,
+ '../core/friendly_errors/validate_params': 49,
+ '../core/main': 54,
+ './p5.Color': 41
+ }
+ ],
+ 41: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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 };
+ }
+ /**
+ * @module Color
+ * @submodule Creating & Reading
+ * @for p5
+ * @requires core
+ * @requires constants
+ * @requires color_conversion
+ */ /**
+ * Each color stores the color mode and level maxes that was applied at the
+ * time of its construction. These are used to interpret the input arguments
+ * (at construction and later for that instance of color) and to format the
+ * output e.g. when saturation() is requested.
+ *
+ * Internally, we store an array representing the ideal RGBA values in floating
+ * point form, normalized from 0 to 1. From this we calculate the closest
+ * screen color (RGBA levels from 0 to 255) and expose this to the renderer.
+ *
+ * We also cache normalized, floating point components of the color in various
+ * representations as they are calculated. This is done to prevent repeating a
+ * conversion that has already been performed.
+ *
+ * @class p5.Color
+ * @constructor
+ */ _main.default.Color = function(pInst, vals) {
+ // Record color mode and maxes at time of construction.
+ this._storeModeAndMaxes(pInst._colorMode, pInst._colorMaxes); // Calculate normalized RGBA values.
+ if (
+ this.mode !== constants.RGB &&
+ this.mode !== constants.HSL &&
+ this.mode !== constants.HSB
+ ) {
+ throw new Error(''.concat(this.mode, ' is an invalid colorMode.'));
+ } else {
+ this._array = _main.default.Color._parseInputs.apply(this, vals);
+ }
+
+ // Expose closest screen color.
+ this._calculateLevels();
+ return this;
+ };
+
+ /**
+ * This function returns the color formatted as a string. This can be useful
+ * for debugging, or for using p5.js with other libraries.
+ *
+ * @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
+ *
+ * @example
+ *
+ *
+ * @alt
+ * canvas with gradually changing background color
+ */
+ _main.default.Color.prototype.setRed = function(new_red) {
+ this._array[0] = new_red / this.maxes[constants.RGB][0];
+ this._calculateLevels();
+ };
+
+ /**
+ * The setGreen function sets the green component of a color.
+ * The range depends on your color mode, in the default RGB mode it's between 0 and 255.
+ * @method setGreen
+ * @param {Number} green the new green value
+ * @example
+ *
+ *
+ * @alt
+ * canvas with gradually changing background color
+ **/
+ _main.default.Color.prototype.setGreen = function(new_green) {
+ this._array[1] = new_green / this.maxes[constants.RGB][1];
+ this._calculateLevels();
+ };
+
+ /**
+ * The setBlue function sets the blue component of a color.
+ * The range depends on your color mode, in the default RGB mode it's between 0 and 255.
+ * @method setBlue
+ * @param {Number} blue the new blue value
+ * @example
+ *
+ *
+ * @alt
+ * canvas with gradually changing background color
+ **/
+ _main.default.Color.prototype.setBlue = function(new_blue) {
+ this._array[2] = new_blue / this.maxes[constants.RGB][2];
+ this._calculateLevels();
+ };
+
+ /**
+ * The setAlpha function sets the transparency (alpha) value of a color.
+ * The range depends on your color mode, in the default RGB mode it's between 0 and 255.
+ * @method setAlpha
+ * @param {Number} alpha the new alpha value
+ * @example
+ *
+ *
+ * @alt
+ * a square with gradually changing opacity on a gray background
+ **/
+ _main.default.Color.prototype.setAlpha = function(new_alpha) {
+ this._array[3] = new_alpha / this.maxes[this.mode][3];
+ this._calculateLevels();
+ };
+
+ // calculates and stores the closest screen levels
+ _main.default.Color.prototype._calculateLevels = function() {
+ 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);
+ }
+ };
+
+ _main.default.Color.prototype._getAlpha = function() {
+ 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())
+ _main.default.Color.prototype._storeModeAndMaxes = function(new_mode, new_maxes) {
+ this.mode = new_mode;
+ this.maxes = new_maxes;
+ };
+
+ _main.default.Color.prototype._getMode = function() {
+ return this.mode;
+ };
+
+ _main.default.Color.prototype._getMaxes = function() {
+ return this.maxes;
+ };
+
+ _main.default.Color.prototype._getBlue = function() {
+ return this._array[2] * this.maxes[constants.RGB][2];
+ };
+
+ _main.default.Color.prototype._getBrightness = function() {
+ if (!this.hsba) {
+ this.hsba = _color_conversion.default._rgbaToHSBA(this._array);
+ }
+ return this.hsba[2] * this.maxes[constants.HSB][2];
+ };
+
+ _main.default.Color.prototype._getGreen = function() {
+ 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.
+ */
+ _main.default.Color.prototype._getHue = function() {
+ 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];
+ }
+ };
+
+ _main.default.Color.prototype._getLightness = function() {
+ if (!this.hsla) {
+ this.hsla = _color_conversion.default._rgbaToHSLA(this._array);
+ }
+ return this.hsla[2] * this.maxes[constants.HSL][2];
+ };
+
+ _main.default.Color.prototype._getRed = function() {
+ 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.
+ */
+ _main.default.Color.prototype._getSaturation = function() {
+ 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];
+ }
+ };
+
+ /**
+ * 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'
+ )
+ };
+
+ /**
+ * 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
+ *
+ *
+ *
+ * @alt
+ * //todo
+ */
+ _main.default.Color._parseInputs = function(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 _main.default.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;
+ };
+ var _default = _main.default.Color;
+ exports.default = _default;
+ },
+ { '../core/constants': 43, '../core/main': 54, './color_conversion': 39 }
+ ],
+ 42: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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 };
+ } /**
+ * @method background
+ * @param {Number} gray specifies a value between white and black
+ * @param {Number} [a]
+ * @chainable
+ */ /**
+ * @module Color
+ * @submodule Setting
+ * @for p5
+ * @requires core
+ * @requires constants
+ */ /**
+ * The background() function sets the color used
+ * for the background of the p5.js canvas. The default background is transparent.
+ * This function is typically used within draw() to clear
+ * the display window at the beginning of each frame, but it can be used inside
+ * setup() to set the background on the first frame of
+ * animation or if the background need only be set once.
+ *
+ * The color is either specified in terms of the RGB, HSB, or HSL color depending
+ * on the current colorMode. (The default color space
+ * is RGB, with each value in the range from 0 to 255). The alpha range by default
+ * is also 0 to 255.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color strings
+ * and all named color strings are supported. In this case, an alpha number
+ * value as a second argument is not supported, the RGBA form should be used.
+ *
+ * A p5.Color object can also be provided to set the background color.
+ *
+ * A p5.Image can also be provided to set the background image.
+ *
+ * @method background
+ * @param {p5.Color} color any value created by the color() function
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * @alt
+ * canvas with darkest charcoal grey background.
+ * canvas with yellow background.
+ * canvas with royal blue background.
+ * canvas with red background.
+ * canvas with pink background.
+ * canvas with black background.
+ * canvas with bright green background.
+ * canvas with soft green background.
+ * canvas with red background.
+ * canvas with light purple background.
+ * canvas with 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} v1 red or hue value (depending on the current color
+ * mode)
+ * @param {Number} v2 green or saturation value (depending on the current
+ * color mode)
+ * @param {Number} v3 blue or brightness value (depending on the current
+ * color mode)
+ * @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 within a buffer. This function only clears the canvas.
+ * It will not clear objects created by createX() methods such as
+ * createVideo() or createDiv().
+ * Unlike the main graphics context, pixels in additional graphics areas created
+ * with createGraphics() can be entirely
+ * or partially transparent. This function clears everything to make all of
+ * the pixels 100% transparent.
+ *
+ * @method clear
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * small white ellipses are continually drawn at mouse's x and y coordinates.
+ */
+
+ _main.default.prototype.clear = function() {
+ this._renderer.clear();
+ return this;
+ };
+
+ /**
+ * colorMode() changes the way p5.js interprets
+ * color data. By default, the parameters for fill(),
+ * stroke(), background(),
+ * and color() are defined by values between 0 and 255
+ * using the RGB color model. This is equivalent to setting colorMode(RGB, 255).
+ * Setting colorMode(HSB) lets you use the HSB system instead. By default, this
+ * is colorMode(HSB, 360, 100, 100, 1). You can also use HSL.
+ *
+ * Note: existing color objects remember the mode that they were created in,
+ * so you can change modes as you like without affecting 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
+ *
+ *
+ * @alt
+ *Green to red gradient from bottom L to top R. shading originates from top left.
+ *Rainbow gradient from left to right. Brightness increasing to white at top.
+ *unknown image.
+ *50x50 ellipse at middle L & 40x40 ellipse at center. Translucent pink 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. For example, if you run fill(204, 102, 0),
+ * all shapes drawn after the fill command will be filled with the color orange.
+ * This color is either specified in terms of the RGB or HSB color depending on
+ * the current colorMode(). (The default color space
+ * is RGB, with each value in the range from 0 to 255). The alpha range by default
+ * is also 0 to 255.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color strings
+ * and all named color strings are supported. In this case, an alpha number
+ * value as a second argument is not supported, the RGBA form should be used.
+ *
+ * A p5 Color object can also be provided to set the fill color.
+ *
+ * @method fill
+ * @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]
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 60x60 dark charcoal grey rect with black outline in center of canvas.
+ * 60x60 yellow rect with black outline in center of canvas.
+ * 60x60 royal blue rect with black outline in center of canvas.
+ * 60x60 red rect with black outline in center of canvas.
+ * 60x60 pink rect with black outline in center of canvas.
+ * 60x60 black rect with black outline in center of canvas.
+ * 60x60 light green rect with black outline in center of canvas.
+ * 60x60 soft green rect with black outline in center of canvas.
+ * 60x60 red rect with black outline in center of canvas.
+ * 60x60 dark fuchsia rect with black outline in center of canvas.
+ * 60x60 blue rect with black outline in center of canvas.
+ */
+
+ /**
+ * @method fill
+ * @param {String} value a color string
+ * @chainable
+ */
+
+ /**
+ * @method fill
+ * @param {Number} gray a gray 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 filling geometry. If both noStroke() and noFill() are called,
+ * nothing will be drawn to the screen.
+ *
+ * @method noFill
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white rect top middle and noFill rect center. Both 60x60 with black outlines.
+ * black canvas with purple cube wireframe spinning
+ */
+ _main.default.prototype.noFill = function() {
+ this._renderer._setProperty('_doFill', false);
+ return this;
+ };
+
+ /**
+ * Disables drawing the stroke (outline). If both noStroke() and noFill()
+ * are called, nothing will be drawn to the screen.
+ *
+ * @method noStroke
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 60x60 white rect at center. no outline.
+ * black canvas with pink cube spinning
+ */
+ _main.default.prototype.noStroke = function() {
+ this._renderer._setProperty('_doStroke', false);
+ return this;
+ };
+
+ /**
+ * Sets the color used to draw lines and borders around shapes. This color
+ * is either specified in terms of the RGB or HSB color depending on the
+ * current colorMode() (the default color space
+ * is RGB, with each value in the range from 0 to 255). The alpha range by
+ * default is also 0 to 255.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color
+ * strings and all named color strings are supported. In this case, an alpha
+ * number value as a second argument is not supported, the RGBA form should be
+ * used.
+ *
+ * A p5 Color object can also be provided to set the stroke color.
+ *
+ * @method stroke
+ * @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]
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * @alt
+ * 60x60 white rect at center. Dark charcoal grey outline.
+ * 60x60 white rect at center. Yellow outline.
+ * 60x60 white rect at center. Royal blue outline.
+ * 60x60 white rect at center. Red outline.
+ * 60x60 white rect at center. Pink outline.
+ * 60x60 white rect at center. Black outline.
+ * 60x60 white rect at center. Bright green outline.
+ * 60x60 white rect at center. Soft green outline.
+ * 60x60 white rect at center. Red outline.
+ * 60x60 white rect at center. Dark fuchsia outline.
+ * 60x60 white rect at center. Blue outline.
+ */
+
+ /**
+ * @method stroke
+ * @param {String} value a color string
+ * @chainable
+ */
+
+ /**
+ * @method stroke
+ * @param {Number} gray a gray 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;
+ };
+
+ /**
+ * All drawing that follows erase() will subtract from
+ * the canvas.Erased areas will reveal the web page underneath the canvas.Erasing
+ * can be canceled with noErase().
+ *
+ * Drawing done with image() and
+ * background() in between erase() and
+ * noErase() will not erase the canvas but works as usual.
+ *
+ * @method erase
+ * @param {Number} [strengthFill] A number (0-255) for the strength of erasing for a shape's fill.
+ * This will default to 255 when no argument is given, which
+ * is full strength.
+ * @param {Number} [strengthStroke] A number (0-255) for the strength of erasing for a shape's stroke.
+ * This will default to 255 when no argument is given, which
+ * is full strength.
+ *
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 80x80 white quarter-circle with curve toward bottom right of canvas.
+ */ exports.WAIT = WAIT;
+ var HALF_PI = _PI / 2;
+ /**
+ * PI is a mathematical constant with the value
+ * 3.14159265358979323846. It is the ratio of the circumference
+ * of a circle to its diameter. It is useful in combination with
+ * the trigonometric functions sin() and cos().
+ *
+ * @property {Number} PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, PI);
+ *
+ *
+ * @alt
+ * white half-circle with curve toward bottom of canvas.
+ */ exports.HALF_PI = HALF_PI;
+ var PI = _PI;
+ /**
+ * QUARTER_PI is a mathematical constant with the value 0.7853982.
+ * It is one quarter the ratio of the circumference of a circle to
+ * its diameter. It is useful in combination with the trigonometric
+ * functions sin() and cos().
+ *
+ * @property {Number} QUARTER_PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, QUARTER_PI);
+ *
+ *
+ * @alt
+ * white eighth-circle rotated about 40 degrees with curve bottom right canvas.
+ */ exports.PI = PI;
+ var QUARTER_PI = _PI / 4;
+ /**
+ * TAU is an alias for TWO_PI, a mathematical constant with the
+ * value 6.28318530717958647693. It is twice the ratio of the
+ * circumference of a circle to its diameter. It is useful in
+ * combination with the trigonometric functions sin() and cos().
+ *
+ * @property {Number} TAU
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, TAU);
+ *
+ *
+ * @alt
+ * 80x80 white ellipse shape in center of canvas.
+ */ exports.QUARTER_PI = QUARTER_PI;
+ var TAU = _PI * 2;
+ /**
+ * TWO_PI is a mathematical constant with the value
+ * 6.28318530717958647693. It is twice the ratio of the
+ * circumference of a circle to its diameter. It is useful in
+ * combination with the trigonometric functions sin() and cos().
+ *
+ * @property {Number} TWO_PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, TWO_PI);
+ *
+ *
+ * @alt
+ * 80x80 white ellipse shape in center of canvas.
+ */ exports.TAU = TAU;
+ var TWO_PI = _PI * 2;
+ /**
+ * Constant to be used with angleMode() function, to set the mode which
+ * p5.js interprates and calculates angles (either DEGREES or RADIANS).
+ * @property {String} DEGREES
+ * @final
+ *
+ * @example
+ *
+ */ exports.TWO_PI = TWO_PI;
+ var DEGREES = 'degrees';
+ /**
+ * Constant to be used with angleMode() function, to set the mode which
+ * p5.js interprates and calculates angles (either RADIANS or DEGREES).
+ * @property {String} RADIANS
+ * @final
+ *
+ * @example
+ *
+ * let x = 10;
+ * print('The value of x is ' + x);
+ * // prints "The value of x is 10"
+ *
+ *
+ * @alt
+ * default grey canvas
+ */
+ _main.default.prototype.print = function() {
+ if (!arguments.length) {
+ _windowPrint();
+ } else {
+ var _console;
+ (_console = console).log.apply(_console, arguments);
+ }
+ };
+
+ /**
+ * The system variable frameCount contains the
+ * number of frames that have been displayed since the program started. Inside
+ * setup() the value is 0, after the first iteration
+ * of draw it is 1, etc.
+ *
+ * @property {Integer} frameCount
+ * @readOnly
+ * @example
+ *
+ *
+ * @alt
+ * numbers rapidly counting upward with frame count set to 30.
+ */
+ _main.default.prototype.frameCount = 0;
+
+ /**
+ * The system variable deltaTime contains the time
+ * difference between the beginning of the previous frame and the beginning
+ * of the current frame in milliseconds.
+ *
+ * This variable is useful for creating time sensitive animation or physics
+ * calculation that should stay constant regardless of frame rate.
+ *
+ * @property {Integer} deltaTime
+ * @readOnly
+ * @example
+ *
+ * let rectX = 0;
+ * let fr = 30; //starting FPS
+ * let clr;
+ *
+ * function setup() {
+ * background(200);
+ * frameRate(fr); // Attempt to refresh at starting FPS
+ * clr = color(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rectX = rectX + 1 * (deltaTime / 50); // Move Rectangle in relation to deltaTime
+ *
+ * if (rectX >= width) {
+ * // If you go off screen.
+ * if (fr === 30) {
+ * clr = color(0, 0, 255);
+ * fr = 10;
+ * frameRate(fr); // make frameRate 10 FPS
+ * } else {
+ * clr = color(255, 0, 0);
+ * fr = 30;
+ * frameRate(fr); // make frameRate 30 FPS
+ * }
+ * rectX = 0;
+ * }
+ * fill(clr);
+ * rect(rectX, 40, 20, 20);
+ * }
+ *
+ *
+ * @alt
+ * red rect moves left to right, followed by blue rect moving at the same speed
+ * with a lower frame rate. Loops.
+ */
+ _main.default.prototype.deltaTime = 0;
+
+ /**
+ * Confirms if the window a p5.js program is in is "focused," meaning that
+ * the sketch will accept mouse or keyboard input. This variable is
+ * "true" if the window is focused and "false" if not.
+ *
+ * @property {Boolean} focused
+ * @readOnly
+ * @example
+ *
+ * // To demonstrate, put two windows side by side.
+ * // Click on the window that the p5 sketch isn't in!
+ * function draw() {
+ * background(200);
+ * noStroke();
+ * fill(0, 200, 0);
+ * ellipse(25, 25, 50, 50);
+ *
+ * if (!focused) {
+ // or "if (focused === false)"
+ * stroke(200, 0, 0);
+ * line(0, 0, 100, 100);
+ * line(100, 0, 0, 100);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * green 50x50 ellipse at top left. Red X covers canvas when page focus changes
+ */
+ _main.default.prototype.focused = document.hasFocus();
+
+ /**
+ * Sets the cursor to a predefined symbol or an image, or makes it visible
+ * if already hidden. If you are trying to set an image as the cursor, the
+ * recommended size is 16x16 or 32x32 pixels. The values for parameters x and y
+ * must be less than the dimensions of the image.
+ *
+ * @method cursor
+ * @param {String|Constant} type Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT
+ * Native CSS properties: 'grab', 'progress', 'cell' etc.
+ * External: path for cursor's images
+ * (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)
+ * For more information on Native CSS cursors and url visit:
+ * https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
+ * @param {Number} [x] the horizontal active spot of the cursor (must be less than 32)
+ * @param {Number} [y] the vertical active spot of the cursor (must be less than 32)
+ * @example
+ *
+ *
+ * @alt
+ * canvas is divided into four quadrants. cursor on first is a cross, second is a progress,
+ * third is a custom cursor using path to the cursor and fourth is a grab.
+ */
+ _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;
+ };
+
+ /**
+ * 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 frame rate is
+ * based on the frame rate of the display (here also called "refresh rate"),
+ * which is set to 60 frames per second on most computers. A frame rate of 24
+ * frames per second (usual for movies) or above will be enough for smooth
+ * animations. This is the same as setFrameRate(val).
+ *
+ * Calling frameRate() with no arguments returns
+ * the current framerate. The draw function must run at least once before it will
+ * return a value. This is the same as getFrameRate().
+ *
+ * Calling frameRate() with arguments that are not
+ * of the type numbers or are non positive also returns current framerate.
+ *
+ * @method frameRate
+ * @param {Number} fps number of frames to be displayed every second
+ * @chainable
+ *
+ * @example
+ *
+ *
+ *
+ * @alt
+ * blue rect moves left to right, followed by red rect moving faster. Loops.
+ */
+ /**
+ * @method frameRate
+ * @return {Number} current frameRate
+ */
+ _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 framerate.
+ *
+ * @private
+ * @param {Number} [fps] number of frames to be displayed every second
+ */
+ _main.default.prototype.setFrameRate = function(fps) {
+ return this.frameRate(fps);
+ };
+
+ /**
+ * Hides the cursor from view.
+ *
+ * @method noCursor
+ * @example
+ *
+ *
+ * @alt
+ * cursor becomes 10x 10 white ellipse the moves with mouse x and y.
+ */
+ _main.default.prototype.noCursor = function() {
+ this._curElement.elt.style.cursor = 'none';
+ };
+
+ /**
+ * System variable that stores the width of the screen display according to The
+ * default pixelDensity. This is used to run a
+ * full-screen program on any display size. To return actual screen size,
+ * multiply this by pixelDensity.
+ *
+ * @property {Number} displayWidth
+ * @readOnly
+ * @example
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _main.default.prototype.displayWidth = screen.width;
+
+ /**
+ * System variable that stores the height of the screen display according to The
+ * default pixelDensity. This is used to run a
+ * full-screen program on any display size. To return actual screen size,
+ * multiply this by pixelDensity.
+ *
+ * @property {Number} displayHeight
+ * @readOnly
+ * @example
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _main.default.prototype.displayHeight = screen.height;
+
+ /**
+ * System variable that stores the width of the inner window, it maps to
+ * window.innerWidth.
+ *
+ * @property {Number} windowWidth
+ * @readOnly
+ * @example
+ *
+ * createCanvas(windowWidth, windowHeight);
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _main.default.prototype.windowWidth = getWindowWidth();
+ /**
+ * System variable that stores the height of the inner window, it maps to
+ * window.innerHeight.
+ *
+ * @property {Number} windowHeight
+ * @readOnly
+ * @example
+ *
+ * createCanvas(windowWidth, windowHeight);
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _main.default.prototype.windowHeight = getWindowHeight();
+
+ /**
+ * The windowResized() function is called once
+ * every time the browser window is resized. This is a good place to resize the
+ * canvas or do any other adjustments to accommodate the new window size.
+ *
+ * @method windowResized
+ * @example
+ *
+ * @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
+ );
+ }
+
+ /**
+ * System variable that stores the width of the drawing canvas. This value
+ * is set by the first parameter of the createCanvas() function.
+ * For example, the function call createCanvas(320, 240) sets the width
+ * variable to the value 320. The value of width defaults to 100 if
+ * createCanvas() is not used in a program.
+ *
+ * @property {Number} width
+ * @readOnly
+ */
+ _main.default.prototype.width = 0;
+
+ /**
+ * System variable that stores the height of the drawing canvas. This value
+ * is set by the second parameter of the createCanvas() function. For
+ * example, the function call createCanvas(320, 240) sets the height
+ * variable to the value 240. The value of height defaults to 100 if
+ * createCanvas() is not used in a program.
+ *
+ * @property {Number} height
+ * @readOnly
+ */
+ _main.default.prototype.height = 0;
+
+ /**
+ * If argument is given, sets the sketch to fullscreen or not based on the
+ * value of the argument. If no argument is given, returns the current
+ * fullscreen state. Note that due to browser restrictions this can only
+ * be called on user input, for example, on mouse press like the example
+ * below.
+ *
+ * @method fullscreen
+ * @param {Boolean} [val] whether the sketch should be in fullscreen mode
+ * or not
+ * @return {Boolean} current fullscreen state
+ * @example
+ *
+ *
+ * // Clicking in the box toggles fullscreen on and off.
+ * function setup() {
+ * background(200);
+ * }
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {
+ * let fs = fullscreen();
+ * fullscreen(!fs);
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * This example does not render anything.
+ */
+ _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 scaling for high pixel density displays. By default
+ * pixel density is set to match display density, call pixelDensity(1)
+ * to turn this off. Calling pixelDensity() with no arguments returns
+ * the current pixel density of the sketch.
+ *
+ * @method pixelDensity
+ * @param {Number} val whether or how much the sketch should scale
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * fuzzy 50x50 white ellipse with black outline in center of canvas.
+ * sharp 50x50 white ellipse with black outline in center of 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 = 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 pixel density of the current display the sketch is running on.
+ *
+ * @method displayDensity
+ * @returns {Number} current pixel density of the display
+ * @example
+ *
+ *
+ * @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': 43, './main': 54 }
+ ],
+ 45: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0; // Different browsers may use different error strings for the same error.
+ // Extracting info from them is much easier and cleaner if we have a predefined
+ // lookup against which we try and match the errors obtained from the browser,
+ // classify them into types and extract the required information. The contents
+ // of this file serve as that lookup. The FES can use this to give a simplified
+ // explanation for all kinds of errors.
+ var strings = {
+ ReferenceError: [
+ {
+ msg: '{{}} is not defined',
+ type: 'NOTDEFINED',
+ browser: 'all'
+ },
+
+ {
+ msg: "Can't find variable: {{}}",
+ type: 'NOTDEFINED',
+ browser: 'Safari'
+ }
+ ],
+
+ 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'
+ }
+ ],
+
+ TypeError: [
+ {
+ msg: '{{.}} is not a function',
+ type: 'NOTFUNC',
+ browser: 'all'
+ }
+ ]
+ };
+ var _default = strings;
+ exports.default = _default;
+ },
+ {}
+ ],
+ 46: [
+ 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 };
+ }
+ 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' && 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);
+ }
+
+ // 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
+ );
+ };
+
+ /**
+ * Prints out a fancy, colorful message to the console log
+ *
+ * @method report
+ * @private
+ * @param {String} message the words to be said
+ * @param {String} func the name of the function to link
+ * @param {Number|String} color CSS color string or error type
+ *
+ * @return console logs
+ */
+ var report = function report(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];
+ }
+
+ var prefixedMsg;
+ var style = [
+ 'color: '.concat(color),
+ 'font-family: Arial',
+ 'font-size: larger'
+ ];
+ if (func == null || func.substring(0, 4) === 'load') {
+ prefixedMsg = (0, _internationalization.translator)('fes.pre', {
+ message: 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('/');
+
+ prefixedMsg = (0, _internationalization.translator)('fes.pre', {
+ message: ''
+ .concat(message, ' (http://p5js.org/reference/#/')
+ .concat(referenceSection, '/')
+ .concat(funcName, ')')
+ });
+ }
+ 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 {Number} message message to be printed
+ * @param {String} method name of method
+ * @param {Number|String} [color] CSS color string or error type (Optional)
+ */
+ _main.default._friendlyError = function(message, method, color) {
+ report(message, method, color);
+ };
+
+ /**
+ * This is called internally if there is a error with autoplay.
+ *
+ * @method _friendlyAutoplayError
+ * @private
+ */
+ _main.default._friendlyAutoplayError = function(src) {
+ var message = (0, _internationalization.translator)('fes.autoplay', {
+ src: src,
+ link: 'https://developer.mozilla.org/docs/Web/Media/Autoplay_guide'
+ });
+
+ console.log(
+ (0, _internationalization.translator)('fes.pre', { message: message })
+ );
+ };
+
+ var computeEditDistance = function computeEditDistance(w1, w2) {
+ // An implementation of
+ // https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm to
+ // compute the Levenshtein distance. It gives a measure of how dissimilar
+ // two strings are. If the "distance" between them is small enough, it is
+ // reasonable to think that one is the misspelled version of the other.
+ 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 if the various functions such as setup, draw, preload have been
+ // defined with capitalization mistakes
+ 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 the symbol caught in the ReferenceErrror to everything
+ // in misusedAtTopLevel ( all public p5 properties ). The use of
+ // misusedAtTopLevel here is for convenience as it was an array that was
+ // already defined when spelling check was implemented. For this particular
+ // use-case, it's a misnomer.
+ var handleMisspelling = function handleMisspelling(errSym, error) {
+ if (!misusedAtTopLevelCode) {
+ defineMisusedAtTopLevelCode();
+ }
+
+ var min = 999999,
+ minIndex = 0;
+ // compute the levenshtein distance for the symbol against all known
+ // public p5 properties. Find the property with the minimum distance
+ misusedAtTopLevelCode.forEach(function(symbol, idx) {
+ var dist = computeEditDistance(errSym, symbol.name);
+ if (dist < min) {
+ min = dist;
+ minIndex = idx;
+ }
+ });
+
+ if (min > Math.min(EDIT_DIST_THRESHOLD, errSym.length)) return false;
+
+ var symbol = misusedAtTopLevelCode[minIndex];
+
+ // Show a message only if the caught symbol and the matched property name
+ // differ in their name ( either letter difference or difference of case )
+ if (errSym !== symbol.name) {
+ 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,
+ line: parsed[0].lineNumber
+ };
+ }
+ var msg = (0, _internationalization.translator)('fes.misspelling', {
+ name: errSym,
+ actualName: symbol.name,
+ type: symbol.type,
+ location: locationObj
+ ? (0, _internationalization.translator)('fes.location', locationObj)
+ : ''
+ });
+
+ _main.default._friendlyError(msg, symbol.name);
+ return true;
+ }
+ return false;
+ };
+
+ var processStack = function processStack(error, stacktrace) {
+ // Responsible for removing internal library calls from the stacktrace
+ // and also for detectiong if the error happened inside the library
+
+ // 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;
+ 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];
+ for (var j = 0; j < i; j++) {
+ // Due to the current build process, all p5 functions have
+ // _main.default in their names in the final build. This is the
+ // easiest way to check if a function is inside the p5 library
+ if (stacktrace[j].functionName.search('_main.default') !== -1) {
+ isInternal = true;
+ p5FileName = stacktrace[j].fileName;
+ 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
+ );
+ }
+ }
+ return [isInternal, friendlyStack];
+ };
+
+ // prints a friendly stacktrace which only includes user-written functions
+ // and is easier for newcomers to understand
+ 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);
+ }
+ };
+
+ 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. Show the friendlyStack and return
+ if (isInternal) {
+ if (friendlyStack) printFriendlyStack(friendlyStack);
+ 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': {
+ 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': {
+ 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;
+ }
+ }
+
+ break;
+ }
+ case 'ReferenceError': {
+ switch (matchedError.type) {
+ case 'NOTDEFINED': {
+ 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 url1 = 'https://p5js.org/examples/data-variable-scope.html';
+ var url2 =
+ 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Not_Defined#What_went_wrong';
+ _main.default._friendlyError(
+ (0, _internationalization.translator)(
+ 'fes.globalErrors.reference.notDefined',
+ {
+ url1: url1,
+ url2: url2,
+ symbol: errSym,
+ location: locationObj
+ ? (0, _internationalization.translator)(
+ 'fes.location',
+ locationObj
+ )
+ : ''
+ }
+ )
+ );
+
+ if (friendlyStack) printFriendlyStack(friendlyStack);
+ break;
+ }
+ }
+
+ break;
+ }
+
+ case 'TypeError': {
+ switch (matchedError.type) {
+ case 'NOTFUNC': {
+ var _errSym = matchedError.match[1];
+ var splitSym = _errSym.split('.');
+ var _url2 =
+ '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: _url2,
+ 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;
+ }
+ }
+ }
+ }
+ };
+
+ _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';
+ report(str, 'print', '#ED225D'); // p5.js magenta
+ report(str, 'print', '#2D7BB6'); // p5.js blue
+ report(str, 'print', '#EE9900'); // p5.js orange
+ report(str, 'print', '#A67F59'); // p5.js light brown
+ report(str, 'print', '#704F21'); // p5.js gold
+ report(str, 'print', '#1CC581'); // auto cyan
+ report(str, 'print', '#FF6625'); // auto orange
+ report(str, 'print', '#79EB22'); // auto green
+ report(str, 'print', '#B40033'); // p5.js darkened magenta
+ report(str, 'print', '#084B7F'); // p5.js darkened blue
+ report(str, 'print', '#945F00'); // p5.js darkened orange
+ report(str, 'print', '#6B441D'); // p5.js darkened brown
+ report(str, 'print', '#2E1B00'); // p5.js darkened gold
+ report(str, 'print', '#008851'); // auto dark cyan
+ report(str, 'print', '#C83C00'); // auto dark orange
+ report(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';
+
+ 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;
+ });
+ };
+
+ 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,
+ link: 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': 43,
+ '../internationalization': 52,
+ '../main': 54,
+ './browser_errors': 45
+ }
+ ],
+ 47: [
+ 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,
+ link: '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'
+ };
+ }
+ };
+
+ /**
+ * This is called internally if there is a error during file loading.
+ *
+ * @method _friendlyFileLoadError
+ * @private
+ * @param {Number} errorType
+ * @param {String} filePath
+ */
+ _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': 52, '../main': 54 }
+ ],
+ 48: [
+ 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 };
+ } /** // Borrow from stacktracejs https://github.com/stacktracejs/stacktrace.js with
+ * @for p5
+ * @requires core
+ */
+ // 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() {
+ 'use strict';
+
+ 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.
+ *
+ * @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': 54 }
+ ],
+ 49: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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 _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 _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 _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' && 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);
+ }
+
+ 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.
+
+ // These two functions would be called repeatedly over and over again,
+ // so they need to be as optimized for performance as possible
+
+ 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 is
+ obj = obj[type] || (obj[type] = {});
+ }
+
+ return obj;
+ };
+ 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;
+ };
+
+ // validateParameters() helper functions:
+ // lookupParamDoc() for querying data.json
+ var lookupParamDoc = function lookupParamDoc(func) {
+ // look for the docs in the `data.json` datastructure
+
+ var ichDot = func.lastIndexOf('.');
+ var funcName = func.substr(ichDot + 1);
+ var funcClass = func.substr(0, ichDot) || '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.substr(type.length - 2, 2) === '[]') {
+ return {
+ name: type,
+ array: ct(type.substr(0, type.length - 2))
+ };
+ }
+
+ var lowerType = type.toLowerCase();
+
+ // contant
+ 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.substr(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
+ };
+ };
+
+ var isNumber = function isNumber(param) {
+ switch (_typeof(param)) {
+ case 'number':
+ return true;
+ case 'string':
+ return !isNaN(param);
+ default:
+ return false;
+ }
+ };
+
+ 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;
+ };
+
+ // testType() for non-object type parameter validation
+ 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.
+ 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
+ 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
+ _main.default.ValidationError = (function(name) {
+ var err = /*#__PURE__*/ (function(_Error) {
+ _inherits(err, _Error);
+ function err(message, func, type) {
+ var _this;
+ _classCallCheck(this, err);
+ _this = _possibleConstructorReturn(this, _getPrototypeOf(err).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;
+ })(_wrapNativeSuper(Error));
+
+ err.prototype.name = name;
+ return err;
+ })('ValidationError');
+
+ // function for generating console.log() msg
+ _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()
+ }),
+
+ link: '[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.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);
+ }
+ };
+
+ // 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
+ _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;
+ };
+
+ /**
+ * Validates parameters
+ * param {String} func the name of the function
+ * param {Array} args user input arguments
+ *
+ * example:
+ * const a;
+ * ellipse(10,10,a,5);
+ * console ouput:
+ * "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': 43,
+ '../internationalization': 52,
+ '../main': 54
+ }
+ ],
+ 50: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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': 43 }
+ ],
+ 51: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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': 54, './internationalization': 52 }
+ ],
+ 52: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ 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 };
+ }
+
+ var resources;
+ // Do not include translations in the minified js
+ if (typeof IS_MINIFIED === 'undefined') {
+ resources = _dereq_('../../translations').default;
+ }
+
+ /**
+ * This is our translation function. Give it a key and
+ * it will retreive 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() {
+ console.debug('p5.js translator called before translations were loaded');
+ return '';
+ };
+ // (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() {
+ return new Promise(function(resolve, reject) {
+ _i18next.default
+ .use(_i18nextBrowserLanguagedetector.default)
+ .init({
+ fallbackLng: 'en',
+ nestingPrefix: '$tr(',
+ nestingSuffix: ')',
+ defaultNS: 'translation',
+ returnEmptyString: false,
+ interpolation: {
+ escapeValue: false
+ },
+
+ detection: {
+ checkWhitelist: false
+ },
+
+ resources: resources
+ })
+ .then(
+ function(translateFn) {
+ exports.translator = translator = translateFn;
+ resolve();
+ },
+ function(e) {
+ return reject('Translations failed to load ('.concat(e, ')'));
+ }
+ );
+ });
+ };
+ exports.initialize = initialize;
+ },
+ { '../../translations': 114, i18next: 30, 'i18next-browser-languagedetector': 27 }
+ ],
+ 53: [
+ 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': 54 }
+ ],
+ 54: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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;
+ }
+
+ /**
+ * 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} 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, sync) {
+ var _this = this;
+ _classCallCheck(this, p5);
+ //////////////////////////////////////////////
+ // PUBLIC p5 PROPERTIES AND METHODS
+ //////////////////////////////////////////////
+
+ /**
+ * Called directly before setup(), the preload() function is used to handle
+ * asynchronous loading of external files in a blocking way. If a preload
+ * function is defined, setup() will wait until any load calls within have
+ * finished. Nothing besides load calls (loadImage, loadJSON, loadFont,
+ * loadStrings, etc.) should be inside the preload function. If asynchronous
+ * loading is preferred, the load methods can instead be called in setup()
+ * or anywhere else with the use of a callback parameter.
+ *
+ * By default the text "loading..." will be displayed. To make your own
+ * loading page, include an HTML element with id "p5_loading" in your
+ * page. More information here.
+ *
+ * @method preload
+ * @example
+ *
+ * let img;
+ * let c;
+ * function preload() {
+ * // preload() runs once
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ *
+ * function setup() {
+ * // setup() waits until preload() is done
+ * img.loadPixels();
+ * // get color of middle pixel
+ * c = img.get(img.width / 2, img.height / 2);
+ * }
+ *
+ * function draw() {
+ * background(c);
+ * image(img, 25, 25, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+
+ /**
+ * The setup() function is called once when the program starts. It's used to
+ * define initial environment properties such as screen size and background
+ * color and to load media such as images and fonts as the program starts.
+ * There can only be one setup() function for each program and it shouldn't
+ * be called again after its initial execution.
+ *
+ * Note: Variables declared within setup() are not accessible within other
+ * functions, including draw().
+ *
+ * @method setup
+ * @example
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+
+ /**
+ * Called directly after setup(), the draw() function continuously executes
+ * the lines of code contained inside its block until the program is stopped
+ * or noLoop() is called. Note if noLoop() is called in setup(), draw() will
+ * still be executed once before stopping. draw() is called automatically and
+ * should never be called explicitly.
+ *
+ * It should always be controlled with noLoop(), redraw() and loop(). After
+ * noLoop() stops the code in draw() from executing, redraw() causes the
+ * code inside draw() to execute once, and loop() will cause the code
+ * inside draw() to resume executing continuously.
+ *
+ * The number of times draw() executes in each second may be controlled with
+ * the frameRate() function.
+ *
+ * There can only be one draw() function for each sketch, and draw() must
+ * exist if you want the code to run continuously, or to process events such
+ * as mousePressed(). Sometimes, you might have an empty call to draw() in
+ * your program, as shown in the above example.
+ *
+ * It is important to note that the drawing coordinate system will be reset
+ * at the beginning of each draw() call. If any transformations are performed
+ * within draw() (ex: scale, rotate, translate), their effects will be
+ * undone at the beginning of draw(), so transformations will not accumulate
+ * over time. On the other hand, styling applied (ex: fill, stroke, etc) will
+ * remain in effect.
+ *
+ * @method draw
+ * @example
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+ this.remove = function() {
+ 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 _iteratorNormalCompletion3 = true;
+ var _didIteratorError3 = false;
+ var _iteratorError3 = undefined;
+ try {
+ for (
+ var _iterator3 = _this._elements[Symbol.iterator](), _step3;
+ !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done);
+ _iteratorNormalCompletion3 = true
+ ) {
+ var e = _step3.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) {
+ _didIteratorError3 = true;
+ _iteratorError3 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
+ _iterator3.return();
+ }
+ } finally {
+ if (_didIteratorError3) {
+ throw _iteratorError3;
+ }
+ }
+ }
+ 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 {
+ window.addEventListener('load', this._start.bind(this), false);
+ }
+ }
+ _createClass(p5, [
+ {
+ key: '_initializeInstanceVariables',
+ value: function _initializeInstanceVariables() {
+ 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);
+ }
+
+ // 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) {
+ log(
+ '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.'
+ )
+ );
+
+ 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;
+
+ /**
+ * Allows for the friendly error system (FES) to be turned off when creating a sketch,
+ * which can give a significant boost to performance when needed.
+ * See
+ * disabling the friendly error system.
+ *
+ * @property {Boolean} disableFriendlyErrors
+ * @example
+ *
+ *
+ * @property elt
+ * @readOnly
+ */
+ this.elt = elt;
+ this._pInst = this._pixelsState = pInst;
+ this._events = {};
+ this.width = this.elt.offsetWidth;
+ this.height = this.elt.offsetHeight;
+ };
+
+ /**
+ *
+ * Attaches the element to the parent specified. A way of setting
+ * the container for the element. Accepts either a string ID, DOM
+ * node, or p5.Element. If no arguments given, parent node is returned.
+ * For more ways to position the canvas, see the
+ *
+ * positioning the canvas wiki page.
+ *
+ * @method parent
+ * @param {String|p5.Element|Object} parent the ID, DOM node, or p5.Element
+ * of desired parent element
+ * @chainable
+ *
+ * @example
+ *
+ * // Add the following comment to html file.
+ * // <div id="myContainer"></div>
+ *
+ * // The js code
+ * let cnv = createCanvas(100, 100);
+ * cnv.parent('myContainer');
+ *
+ *
+ *
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
+ * div1.parent(div0); // use p5.Element
+ *
+ *
+ *
+ * let div0 = createDiv('this is the parent');
+ * div0.id('apples');
+ * let div1 = createDiv('this is the child');
+ * div1.parent('apples'); // use id
+ *
+ *
+ *
+ * let elt = document.getElementById('myParentDiv');
+ * let div1 = createDiv('this is the child');
+ * div1.parent(elt); // use element from page
+ *
+ *
+ * @alt
+ * no display.
+ */
+ /**
+ * @method parent
+ * @return {p5.Element}
+ */
+ _main.default.Element.prototype.parent = function(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 ID of the element. If no ID argument is passed in, it instead
+ * returns the current ID of the element.
+ * Note that only one element can have a particular id in a page.
+ * The .class() function can be used
+ * to identify multiple elements with the same class name.
+ *
+ * @method id
+ * @param {String} id ID of the element
+ * @chainable
+ *
+ * @example
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // Assigns a CSS selector ID to
+ * // the canvas element.
+ * cnv.id('mycanvas');
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ /**
+ * @method id
+ * @return {String} the id of the element
+ */
+ _main.default.Element.prototype.id = function(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 given class to the element. If no class argument is passed in, it
+ * instead returns a string containing the current class(es) of the element.
+ *
+ * @method class
+ * @param {String} class class to add
+ * @chainable
+ *
+ * @example
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // Assigns a CSS selector class 'small'
+ * // to the canvas element.
+ * cnv.class('small');
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ /**
+ * @method class
+ * @return {String} the class of the element
+ */
+ _main.default.Element.prototype.class = function(c) {
+ if (typeof c === 'undefined') {
+ return this.elt.className;
+ }
+
+ this.elt.className = c;
+ return this;
+ };
+
+ /**
+ * The .mousePressed() function is called
+ * once after every time a mouse button is pressed over the element. Some mobile
+ * browsers may also trigger this event on a touch screen, if the user performs
+ * a quick tap. This can be used to attach element specific event listeners.
+ *
+ * @method mousePressed
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * pressed over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mousePressed(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any click anywhere
+ * function mousePressed() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mousePressed = function(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);
+ };
+ // Pass along the event-prepended form of the callback.
+ _main.default.Element._adjustListener('mousedown', eventPrependedFxn, this);
+ return this;
+ };
+
+ /**
+ * The .doubleClicked() function is called once after every time a
+ * mouse button is pressed twice over the element. This can be used to
+ * attach element and action specific event listeners.
+ *
+ * @method doubleClicked
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * double clicked over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @return {p5.Element}
+ * @example
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.doubleClicked(changeGray); // attach listener for
+ * // canvas double click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any double click anywhere
+ * function doubleClicked() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is double clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.doubleClicked = function(fxn) {
+ _main.default.Element._adjustListener('dblclick', fxn, this);
+ return this;
+ };
+
+ /**
+ * The mouseWheel() function is called
+ * once after every time a mouse wheel is scrolled over the element. This can
+ * be used to attach element specific event listeners.
+ *
+ * The function accepts a callback function as argument which will be executed
+ * when the `wheel` event is triggered on the element, the callback function is
+ * passed one argument `event`. The `event.deltaY` property returns negative
+ * values if the mouse wheel is rotated up or away from the user and positive
+ * in the other direction. The `event.deltaX` does the same as `event.deltaY`
+ * except it reads the horizontal wheel scroll of the mouse wheel.
+ *
+ * On OS X with "natural" scrolling enabled, the `event.deltaY` values are
+ * reversed.
+ *
+ * @method mouseWheel
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * scrolled over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseWheel(changeSize); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with mousewheel movement
+ * // anywhere on screen
+ * function mouseWheel() {
+ * g = g + 10;
+ * }
+ *
+ * // this function fires with mousewheel movement
+ * // over canvas only
+ * function changeSize(event) {
+ * if (event.deltaY > 0) {
+ * d = d + 10;
+ * } else {
+ * d = d - 10;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseWheel = function(fxn) {
+ _main.default.Element._adjustListener('wheel', fxn, this);
+ return this;
+ };
+
+ /**
+ * The mouseReleased() function is
+ * called once after every time a mouse button is released over the element.
+ * Some mobile browsers may also trigger this event on a touch screen, if the
+ * user performs a quick tap. This can be used to attach element specific event listeners.
+ *
+ * @method mouseReleased
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * released over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseReleased(changeGray); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // released
+ * function mouseReleased() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // released while on canvas
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseReleased = function(fxn) {
+ _main.default.Element._adjustListener('mouseup', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .mouseClicked() function is
+ * called once after a mouse button is pressed and released over the element.
+ * Some mobile browsers may also trigger this event on a touch screen, if the
+ * user performs a quick tap.This can be used to attach element specific event listeners.
+ *
+ * @method mouseClicked
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * clicked over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ *
+ * let cnv, d, g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseClicked(changeGray); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // clicked anywhere
+ * function mouseClicked() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // clicked on canvas
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseClicked = function(fxn) {
+ _main.default.Element._adjustListener('click', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .mouseMoved() function is called once every time a
+ * mouse moves over the element. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method mouseMoved
+ * @param {Function|Boolean} fxn function to be fired when a mouse moves
+ * over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d = 30;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseMoved(changeSize); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * fill(200);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires when mouse moves anywhere on
+ * // page
+ * function mouseMoved() {
+ * g = g + 5;
+ * if (g > 255) {
+ * g = 0;
+ * }
+ * }
+ *
+ * // this function fires when mouse moves over canvas
+ * function changeSize() {
+ * d = d + 2;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseMoved = function(fxn) {
+ _main.default.Element._adjustListener('mousemove', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .mouseOver() function is called once after every time a
+ * mouse moves onto the element. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method mouseOver
+ * @param {Function|Boolean} fxn function to be fired when a mouse moves
+ * onto the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseOver(changeGray);
+ * d = 10;
+ * }
+ *
+ * function draw() {
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * function changeGray() {
+ * d = d + 10;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseOver = function(fxn) {
+ _main.default.Element._adjustListener('mouseover', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .mouseOut() function is called once after every time a
+ * mouse moves off the element. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method mouseOut
+ * @param {Function|Boolean} fxn function to be fired when a mouse
+ * moves off of an element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseOut(changeGray);
+ * d = 10;
+ * }
+ *
+ * function draw() {
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * function changeGray() {
+ * d = d + 10;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.mouseOut = function(fxn) {
+ _main.default.Element._adjustListener('mouseout', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .touchStarted() function is called once after every time a touch is
+ * registered. This can be used to attach element specific event listeners.
+ *
+ * @method touchStarted
+ * @param {Function|Boolean} fxn function to be fired when a touch
+ * starts over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchStarted(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any touch anywhere
+ * function touchStarted() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.touchStarted = function(fxn) {
+ _main.default.Element._adjustListener('touchstart', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .touchMoved() function is called once after every time a touch move is
+ * registered. This can be used to attach element specific event listeners.
+ *
+ * @method touchMoved
+ * @param {Function|Boolean} fxn function to be fired when a touch moves over
+ * the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchMoved(changeGray); // attach listener for
+ * // canvas click only
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.touchMoved = function(fxn) {
+ _main.default.Element._adjustListener('touchmove', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .touchEnded() function is called once after every time a touch is
+ * registered. This can be used to attach element specific event listeners.
+ *
+ * @method touchEnded
+ * @param {Function|Boolean} fxn function to be fired when a touch ends
+ * over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * let cnv;
+ * let d;
+ * let g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchEnded(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any touch anywhere
+ * function touchEnded() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _main.default.Element.prototype.touchEnded = function(fxn) {
+ _main.default.Element._adjustListener('touchend', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .dragOver() function is called once after every time a
+ * file is dragged over the element. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method dragOver
+ * @param {Function|Boolean} fxn function to be fired when a file is
+ * dragged over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * // To test this sketch, simply drag a
+ * // file over the canvas
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('Drag file', width / 2, height / 2);
+ * c.dragOver(dragOverCallback);
+ * }
+ *
+ * // This function will be called whenever
+ * // a file is dragged over the canvas
+ * function dragOverCallback() {
+ * background(240);
+ * text('Dragged over', width / 2, height / 2);
+ * }
+ *
+ * @alt
+ * nothing displayed
+ */
+ _main.default.Element.prototype.dragOver = function(fxn) {
+ _main.default.Element._adjustListener('dragover', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .dragLeave() function is called once after every time a
+ * dragged file leaves the element area. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method dragLeave
+ * @param {Function|Boolean} fxn function to be fired when a file is
+ * dragged off the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * // To test this sketch, simply drag a file
+ * // over and then out of the canvas area
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('Drag file', width / 2, height / 2);
+ * c.dragLeave(dragLeaveCallback);
+ * }
+ *
+ * // This function will be called whenever
+ * // a file is dragged out of the canvas
+ * function dragLeaveCallback() {
+ * background(240);
+ * text('Dragged off', width / 2, height / 2);
+ * }
+ *
+ * @alt
+ * nothing displayed
+ */
+ _main.default.Element.prototype.dragLeave = function(fxn) {
+ _main.default.Element._adjustListener('dragleave', fxn, this);
+ return this;
+ };
+
+ // General handler for event attaching and detaching
+ _main.default.Element._adjustListener = function(ev, fxn, ctx) {
+ if (fxn === false) {
+ _main.default.Element._detachListener(ev, ctx);
+ } else {
+ _main.default.Element._attachListener(ev, fxn, ctx);
+ }
+ return this;
+ };
+
+ _main.default.Element._attachListener = function(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;
+ };
+
+ _main.default.Element._detachListener = function(ev, ctx) {
+ var f = ctx._events[ev];
+ ctx.elt.removeEventListener(ev, f, false);
+ ctx._events[ev] = null;
+ };
+
+ /**
+ * Helper fxn for sharing pixel methods
+ */
+ _main.default.Element.prototype._setProperty = function(prop, value) {
+ this[prop] = value;
+ };
+ var _default = _main.default.Element;
+ exports.default = _default;
+ },
+ { './main': 54 }
+ ],
+ 56: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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 Rendering
+ * @submodule Rendering
+ * @for p5
+ */ /**
+ * Thin wrapper around a renderer, to be used for creating a
+ * graphics buffer object. Use this class if you need
+ * to draw into an off-screen graphics buffer. The two parameters define the
+ * width and height in pixels. The fields and methods for this class are
+ * extensive, but mirror the normal drawing API for p5.
+ *
+ * @class p5.Graphics
+ * @constructor
+ * @extends p5.Element
+ * @param {Number} w width
+ * @param {Number} h height
+ * @param {Constant} renderer the renderer to use, either P2D or WEBGL
+ * @param {p5} [pInst] pointer to p5 instance
+ */ _main.default.Graphics = function(w, h, renderer, pInst) {
+ var r = renderer || constants.P2D;
+
+ this.canvas = document.createElement('canvas');
+ var node = pInst._userNode || document.body;
+ node.appendChild(this.canvas);
+
+ _main.default.Element.call(this, this.canvas, pInst);
+
+ // 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(this);
+ } else {
+ this[p] = _main.default.prototype[p];
+ }
+ }
+ }
+
+ _main.default.prototype._initializeInstanceVariables.apply(this);
+ this.width = w;
+ this.height = h;
+ this._pixelDensity = pInst._pixelDensity;
+
+ if (r === constants.WEBGL) {
+ this._renderer = new _main.default.RendererGL(this.canvas, this, false);
+ } else {
+ this._renderer = new _main.default.Renderer2D(this.canvas, this, false);
+ }
+ pInst._elements.push(this);
+
+ Object.defineProperty(this, 'deltaTime', {
+ get: function get() {
+ return this._pInst.deltaTime;
+ }
+ });
+
+ this._renderer.resize(w, h);
+ this._renderer._applyDefaults();
+ return this;
+ };
+
+ _main.default.Graphics.prototype = Object.create(_main.default.Element.prototype);
+
+ /**
+ * Resets certain values such as those modified by functions in the Transform category
+ * and in the Lights category that are not automatically reset
+ * with graphics buffer objects. Calling this in draw() will copy the behavior
+ * of the standard canvas.
+ *
+ * @method reset
+ * @example
+ *
+ *
+ * let pg;
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(0);
+ * pg = createGraphics(50, 100);
+ * pg.fill(0);
+ * frameRate(5);
+ * }
+ *
+ * function draw() {
+ * image(pg, width / 2, 0);
+ * pg.background(255);
+ * // p5.Graphics object behave a bit differently in some cases
+ * // The normal canvas on the left resets the translate
+ * // with every loop through draw()
+ * // the graphics object on the right doesn't automatically reset
+ * // so translate() is additive and it moves down the screen
+ * rect(0, 0, width / 2, 5);
+ * pg.rect(0, 0, width / 2, 5);
+ * translate(0, 5, 0);
+ * pg.translate(0, 5, 0);
+ * }
+ * function mouseClicked() {
+ * // if you click you will see that
+ * // reset() resets the translate back to the initial state
+ * // of the Graphics object
+ * pg.reset();
+ * }
+ *
+ *
+ * @alt
+ * A white line on a black background stays still on the top-left half.
+ * A black line animates from top to bottom on a white background on the right half.
+ * When clicked, the black line starts back over at the top.
+ */
+ _main.default.Graphics.prototype.reset = function() {
+ this._renderer.resetMatrix();
+ if (this._renderer.isP3D) {
+ this._renderer._update();
+ }
+ };
+
+ /**
+ * Removes a Graphics object from the page and frees any resources
+ * associated with it.
+ *
+ * @method remove
+ *
+ * @example
+ *
+ *
+ * @alt
+ * Black line extending from top-left of canvas to bottom right.
+ */
+ _main.default.prototype.createCanvas = function(w, h, renderer) {
+ _main.default._validateParameters('createCanvas', arguments);
+ //optional: renderer, otherwise defaults to p2d
+ var r = renderer || constants.P2D;
+ var c;
+
+ 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) {
+ 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);
+ } 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 given width and height. The canvas will be cleared
+ * and draw will be called immediately, allowing the sketch to re-render itself
+ * in the resized canvas.
+ * @method resizeCanvas
+ * @param {Number} w width of the canvas
+ * @param {Number} h height of the canvas
+ * @param {Boolean} [noRedraw] don't redraw the canvas immediately
+ * @example
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.prototype.noCanvas = function() {
+ if (this.canvas) {
+ this.canvas.parentNode.removeChild(this.canvas);
+ }
+ };
+
+ /**
+ * Creates and returns a new p5.Renderer object. Use this class if you need
+ * to draw into an off-screen graphics buffer. The two parameters define the
+ * width and height in pixels.
+ *
+ * @method createGraphics
+ * @param {Number} w width of the offscreen graphics buffer
+ * @param {Number} h height of the offscreen graphics buffer
+ * @param {Constant} [renderer] either P2D or WEBGL
+ * undefined defaults to p2d
+ * @return {p5.Graphics} offscreen graphics buffer
+ * @example
+ *
+ *
+ * @alt
+ * 4 grey squares alternating light and dark grey. White quarter circle mid-left.
+ */
+ _main.default.prototype.createGraphics = function(w, h, renderer) {
+ _main.default._validateParameters('createGraphics', arguments);
+ return new _main.default.Graphics(w, h, renderer, this);
+ };
+
+ /**
+ * Blends the pixels in the display window according to the defined mode.
+ * There is a choice of the following modes to blend the source pixels (A)
+ * with the ones of pixels already in the display window (B):
+ *
+ *
BLEND - linear interpolation of colours: C =
+ * A\*factor + B. This is the default blending mode.
+ *
ADD - sum of A and B
+ *
DARKEST - only the darkest colour succeeds: C =
+ * min(A\*factor, B).
+ *
LIGHTEST - only the lightest colour succeeds: C =
+ * max(A\*factor, B).
+ *
DIFFERENCE - subtract colors from underlying image.
+ *
EXCLUSION - similar to DIFFERENCE, but less
+ * extreme.
+ *
MULTIPLY - multiply the colors, result will always be
+ * darker.
+ *
SCREEN - opposite multiply, uses inverse values of the
+ * colors.
+ *
REPLACE - the pixels entirely replace the others and
+ * don't utilize alpha (transparency) values.
+ *
REMOVE - removes pixels from B with the alpha strength of A.
+ *
OVERLAY - mix of MULTIPLY and SCREEN
+ * . Multiplies dark values, and screens light values. (2D)
+ *
HARD_LIGHT - SCREEN when greater than 50%
+ * gray, MULTIPLY when lower. (2D)
+ *
SOFT_LIGHT - mix of DARKEST and
+ * LIGHTEST. Works like OVERLAY, but not as harsh. (2D)
+ *
BURN - darker areas are applied, increasing contrast,
+ * ignores lights. (2D)
+ *
SUBTRACT - remainder of A and B (3D)
+ *
+ *
+ * (2D) indicates that this blend mode only works in the 2D renderer.
+ * (3D) indicates that this blend mode only works in the WEBGL renderer.
+ *
+ * @method blendMode
+ * @param {Constant} mode blend mode to set for canvas.
+ * either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,
+ * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
+ * SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT
+ * @example
+ *
+ *
+ * @alt
+ * translucent image thick red & blue diagonal rounded lines intersecting center
+ * Thick red & blue diagonal rounded lines intersecting center. dark at overlap
+ */
+ _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);
+ };
+
+ /**
+ * The p5.js API provides a lot of functionality for creating graphics, but there is
+ * some native HTML5 Canvas functionality that is not exposed by p5. You can still call
+ * it directly using the variable `drawingContext`, as in the example shown. This is
+ * the equivalent of calling `canvas.getContext('2d');` or `canvas.getContext('webgl');`.
+ * See this
+ *
+ * reference for the native canvas API for possible drawing functions you can call.
+ *
+ * @property drawingContext
+ * @example
+ *
+ *
+ * @alt
+ * white ellipse with shadow blur effect around edges
+ */ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../webgl/p5.RendererGL': 108,
+ './constants': 43,
+ './main': 54,
+ './p5.Graphics': 56,
+ './p5.Renderer2D': 58
+ }
+ ],
+ 61: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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 };
+ }
+ /**
+ * @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
+ };
+ };
+
+ /**
+ * Draw an arc to the screen. If called with only x, y, w, h, start and stop,
+ * the arc will be drawn and filled as an open pie segment. If a mode parameter
+ * is provided, the arc will be filled like an open semi-circle (OPEN), a closed
+ * semi-circle (CHORD), or as a closed pie segment (PIE). The origin may be changed
+ * with the ellipseMode() function.
+ *
+ * The arc is always drawn clockwise from wherever start falls to wherever stop
+ * falls on the ellipse.Adding or subtracting TWO_PI to either angle does not
+ * change where they fall. If both start and stop fall at the same place, a full
+ * ellipse will be drawn. Be aware that the y-axis increases in the downward
+ * direction, therefore angles are measured clockwise from the positive
+ * x-direction ("3 o'clock").
+ *
+ * @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 {Number} [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.
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * @alt
+ *shattered outline of an ellipse with a quarter of a white circle bottom-right.
+ *white ellipse with top right quarter missing.
+ *white ellipse with black outline with top right missing.
+ *white ellipse with top right missing with black outline around shape.
+ *white ellipse with top right quarter missing with black outline around the shape.
+ */
+ _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
+ );
+ }
+
+ return this;
+ };
+
+ /**
+ * Draws an ellipse (oval) to the screen. By default, the first two parameters
+ * set the location of the center of the ellipse, and the third and fourth
+ * parameters set the shape's width and height. If no height is specified, 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.
+ *
+ * An ellipse with equal width and height is a circle.The origin may be changed
+ * with the ellipseMode() function.
+ *
+ * @method ellipse
+ * @param {Number} x x-coordinate of the center of ellipse.
+ * @param {Number} y y-coordinate of the center of ellipse.
+ * @param {Number} w width of the ellipse.
+ * @param {Number} [h] height of the ellipse.
+ * @chainable
+ * @example
+ *
+ *
+ * ellipse(56, 46, 55, 55);
+ *
+ *
+ *
+ * @alt
+ *white ellipse with black outline in middle-right of canvas that is 55x55
+ */
+
+ /**
+ * @method ellipse
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} w
+ * @param {Number} h
+ * @param {Integer} detail number of radial sectors to draw (for WebGL mode)
+ */
+ _main.default.prototype.ellipse = function(x, y, w, h, detailX) {
+ _main.default._validateParameters('ellipse', arguments);
+ return this._renderEllipse.apply(this, arguments);
+ };
+
+ /**
+ * Draws a circle to the screen. A circle is a simple closed shape.It is the set
+ * of all points in a plane that are at a given distance from a given point,
+ * the centre.This function is a special case of the ellipse() function, where
+ * the width and height of the ellipse are the same. Height and width of the
+ * ellipse correspond to the diameter of the circle. By default, the first two
+ * parameters set the location of the centre of the circle, the third sets the
+ * diameter of the circle.
+ *
+ * @method circle
+ * @param {Number} x x-coordinate of the centre of the circle.
+ * @param {Number} y y-coordinate of the centre of the circle.
+ * @param {Number} d diameter of the circle.
+ * @chainable
+ * @example
+ *
+ *
+ * // Draw a circle at location (30, 30) with a diameter of 20.
+ * circle(30, 30, 20);
+ *
+ *
+ *
+ * @alt
+ * white circle with black outline in mid of canvas that is 55x55.
+ */
+ _main.default.prototype.circle = function() {
+ _main.default._validateParameters('circle', arguments);
+ var args = Array.prototype.slice.call(arguments, 0, 2);
+ args.push(arguments[2]);
+ args.push(arguments[2]);
+ return this._renderEllipse.apply(this, args);
+ };
+
+ // 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]);
+
+ return this;
+ };
+
+ /**
+ * Draws a line (a direct path between two points) to the screen. If called with
+ * only 4 parameters, it will draw a line in 2D with a default width of 1 pixel.
+ * This width can be modified by using the
+ * strokeWeight() function. A line cannot be filled, therefore the fill() function will not affect the color of a line. So to
+ * color a line, use the stroke() function.
+ *
+ * @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
+ *
+ *
+ * @alt
+ * An example showing a line 78 pixels long running from mid-top to bottom-right of canvas.
+ * An example showing 3 lines of various stroke sizes. Form top, bottom and right sides of a square.
+ */
+
+ /**
+ * @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 _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default._validateParameters('line', args);
+
+ if (this._renderer._doStroke) {
+ var _this$_renderer;
+ (_this$_renderer = this._renderer).line.apply(_this$_renderer, args);
+ }
+
+ return this;
+ };
+
+ /**
+ * Draws a point, a coordinate in space at the dimension of one pixel.
+ * The first parameter is the horizontal value for the point, the second
+ * param is the vertical value for the point. The color of the point is
+ * changed with the stroke() function. The size of the point
+ * can be changed with the strokeWeight() function.
+ *
+ * @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
+ *
+ *
+ * point(30, 20);
+ * point(85, 20);
+ * stroke('purple'); // Change the color
+ * strokeWeight(10); // Make the points 10 pixels in size
+ * point(85, 75);
+ * point(30, 75);
+ *
+ *
+ *
+ *
+ *
+ * let a = createVector(10, 10);
+ * point(a);
+ * let b = createVector(10, 20);
+ * point(b);
+ * point(createVector(20, 10));
+ * point(createVector(20, 20));
+ *
+ *
+ *
+ * @alt
+ * 4 points centered in the middle-right of the canvas.
+ * 2 large points and 2 large purple points centered in the middle-right of the canvas.
+ * Vertices of a square of length 10 pixels towards the top-left of the canvas.
+ */
+
+ /**
+ * @method point
+ * @param {p5.Vector} coordinate_vector the coordinate vector
+ * @chainable
+ */
+ _main.default.prototype.point = function() {
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _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);
+ }
+ }
+
+ return this;
+ };
+
+ /**
+ * Draws a quad on the canvas. A quad is a quadrilateral, a four sided polygon. It is
+ * similar to a rectangle, but the angles between its edges are not
+ * constrained to ninety degrees. The first pair of parameters (x1,y1)
+ * sets the first vertex and the subsequent pairs should proceed
+ * clockwise or counter-clockwise around the defined shape.
+ * z-arguments only work when quad() is used in WEBGL mode.
+ *
+ * @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
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ *irregular white quadrilateral shape with black outline mid-right of canvas.
+ */
+ /**
+ * @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
+ * @chainable
+ */
+ _main.default.prototype.quad = function() {
+ for (
+ var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
+ _key3 < _len3;
+ _key3++
+ ) {
+ args[_key3] = arguments[_key3];
+ }
+ _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
+ // prettier-ignore
+ 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);
+ } else {
+ var _this$_renderer3;
+ (_this$_renderer3 = this._renderer).quad.apply(_this$_renderer3, args);
+ }
+ }
+
+ return this;
+ };
+
+ /**
+ * Draws a rectangle on the canvas. A rectangle is a four-sided closed shape with
+ * every angle at ninety degrees. By default, the first two parameters set
+ * the location of the upper-left corner, the third sets the width, and the
+ * fourth sets the height. The way these parameters are interpreted, may be
+ * changed with the rectMode() function.
+ *
+ * The fifth, sixth, seventh and eighth parameters, if specified,
+ * determine corner radius for the top-left, top-right, lower-right and
+ * lower-left corners, respectively. An omitted corner radius parameter is set
+ * to the value of the previously specified radius value in the parameter list.
+ *
+ * @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
+ *
+ *
+ * // Draw a rectangle at location (30, 20) with a width and height of 55.
+ * rect(30, 20, 55, 55);
+ *
+ *
+ *
+ *
+ *
+ * // Draw a rectangle with rounded corners, each having a radius of 20.
+ * rect(30, 20, 55, 55, 20);
+ *
+ *
+ *
+ *
+ *
+ * // Draw a rectangle with rounded corners having the following radii:
+ * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.
+ * rect(30, 20, 55, 55, 20, 15, 10, 5);
+ *
+ *
+ *
+ * @alt
+ * 55x55 white rect with black outline in mid-right of canvas.
+ * 55x55 white rect with black outline and rounded edges in mid-right of canvas.
+ * 55x55 white rect with black outline and rounded edges of different radii.
+ */
+
+ /**
+ * @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() {
+ _main.default._validateParameters('rect', arguments);
+ return this._renderRect.apply(this, arguments);
+ };
+
+ /**
+ * Draws a square to the screen. A square is a four-sided shape with every angle
+ * at ninety degrees, and equal side size. This function is a special case of the
+ * rect() function, where the width and height are the same, and the parameter
+ * is called "s" for side size. By default, the first two parameters set the
+ * location of the upper-left corner, the third sets the side size of the square.
+ * The way these parameters are interpreted, may be changed with the rectMode() function.
+ *
+ * The fourth, fifth, sixth and seventh parameters, if specified,
+ * determine corner radius for the top-left, top-right, lower-right and
+ * lower-left corners, respectively. An omitted corner radius parameter is set
+ * to the value of the previously specified radius value in the parameter list.
+ *
+ * @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
+ *
+ *
+ * // Draw a square at location (30, 20) with a side size of 55.
+ * square(30, 20, 55);
+ *
+ *
+ *
+ *
+ *
+ * // Draw a square with rounded corners, each having a radius of 20.
+ * square(30, 20, 55, 20);
+ *
+ *
+ *
+ *
+ *
+ * // Draw a square with rounded corners having the following radii:
+ * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.
+ * square(30, 20, 55, 20, 15, 10, 5);
+ *
+ *
+ *
+ * @alt
+ * 55x55 white square with black outline in mid-right of canvas.
+ * 55x55 white square with black outline and rounded edges in mid-right of canvas.
+ * 55x55 white square with black outline and rounded edges of different radii.
+ */
+ _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);
+ }
+
+ return this;
+ };
+
+ /**
+ * Draws a trangle to the canvas. A triangle is a plane created by connecting
+ * three points. The first two arguments specify the first point, the middle two
+ * arguments specify the second point, and the last two arguments specify the
+ * third point.
+ *
+ * @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
+ *
+ *
+ * triangle(30, 75, 58, 20, 86, 75);
+ *
+ *
+ *
+ *@alt
+ * white triangle with black outline in mid-right of canvas.
+ */
+ _main.default.prototype.triangle = function() {
+ for (
+ var _len4 = arguments.length, args = new Array(_len4), _key4 = 0;
+ _key4 < _len4;
+ _key4++
+ ) {
+ args[_key4] = arguments[_key4];
+ }
+ _main.default._validateParameters('triangle', args);
+
+ if (this._renderer._doStroke || this._renderer._doFill) {
+ this._renderer.triangle(args);
+ }
+
+ return this;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../constants': 43,
+ '../friendly_errors/fes_core': 46,
+ '../friendly_errors/file_errors': 47,
+ '../friendly_errors/validate_params': 49,
+ '../helpers': 50,
+ '../main': 54
+ }
+ ],
+ 62: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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
+ */ /**
+ * Modifies the location from which ellipses are drawn by changing the way in
+ * which parameters given to ellipse(),
+ * circle() and arc() are interpreted.
+ *
+ * The default mode is CENTER, in which the first two parameters are interpreted
+ * as the shape's center point's x and y coordinates respectively, while the third
+ * and fourth parameters are its width and height.
+ *
+ * ellipseMode(RADIUS) also uses the first two parameters as the shape's center
+ * point's x and y coordinates, but uses the third and fourth parameters to
+ * specify half of the shapes's width and height.
+ *
+ * ellipseMode(CORNER) interprets the first two parameters as the upper-left
+ * corner of the shape, while the third and fourth parameters are its width
+ * and height.
+ *
+ * ellipseMode(CORNERS) interprets the first two parameters as the location of
+ * one corner of the ellipse's bounding box, and the third and fourth parameters
+ * as the location of the opposite corner.
+ *
+ * The parameter to this method must be written in ALL CAPS because they are
+ * predefined as constants in ALL CAPS and Javascript is a case-sensitive language.
+ *
+ * @method ellipseMode
+ * @param {Constant} mode either CENTER, RADIUS, CORNER, or CORNERS
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 60x60 white ellipse and 30x30 grey ellipse with black outlines at center.
+ * 60x60 white ellipse and 30x30 grey ellipse top-right with 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 all geometry with jagged (aliased) edges. Note that smooth() is
+ * active by default in 2D mode, so it is necessary to call noSmooth() to disable
+ * smoothing of geometry, images, and fonts. In 3D mode, noSmooth() is enabled
+ * by default, so it is necessary to call smooth() if you would like
+ * smooth (antialiased) edges on your geometry.
+ *
+ * @method noSmooth
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 2 pixelated 36x36 white ellipses to left & right of center, black background
+ */
+ _main.default.prototype.noSmooth = function() {
+ this.setAttributes('antialias', false);
+ if (!this._renderer.isP3D) {
+ if ('imageSmoothingEnabled' in this.drawingContext) {
+ this.drawingContext.imageSmoothingEnabled = false;
+ }
+ }
+ return this;
+ };
+
+ /**
+ * Modifies the location from which rectangles are drawn by changing the way
+ * in which parameters given to rect() are interpreted.
+ *
+ * The default mode is CORNER, which interprets the first two parameters as the
+ * upper-left corner of the shape, while the third and fourth parameters are its
+ * width and height.
+ *
+ * rectMode(CORNERS) interprets the first two parameters as the location of
+ * one of the corner, and the third and fourth parameters as the location of
+ * the diagonally opposite corner. Note, the rectangle is drawn between the
+ * coordinates, so it is not neccesary that the first corner be the upper left
+ * corner.
+ *
+ * rectMode(CENTER) interprets the first two parameters as the shape's center
+ * point, while the third and fourth parameters are its width and height.
+ *
+ * rectMode(RADIUS) also uses the first two parameters as the shape's center
+ * point, but uses the third and fourth parameters to specify half of the shapes's
+ * width and height respectively.
+ *
+ * The parameter to this method must be written in ALL CAPS because they are
+ * predefined as constants in ALL CAPS and Javascript is a case-sensitive language.
+ *
+ * @method rectMode
+ * @param {Constant} mode either CORNER, CORNERS, CENTER, or RADIUS
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 50x50 white rect at center and 25x25 grey rect in the top left of the other.
+ * 50x50 white rect at center and 25x25 grey rect in the center of the other.
+ */
+ _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 all geometry with smooth (anti-aliased) edges. smooth() will also
+ * improve image quality of resized images. Note that smooth() is active by
+ * default in 2D mode; noSmooth() can be used to disable smoothing of geometry,
+ * images, and fonts. In 3D mode, noSmooth() is enabled
+ * by default, so it is necessary to call smooth() if you would like
+ * smooth (antialiased) edges on your geometry.
+ *
+ * @method smooth
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 2 pixelated 36x36 white ellipses one left one right of center. On black.
+ */
+ _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 line endings. These ends are either rounded,
+ * squared or extended, each of which specified with the corresponding
+ * parameters: ROUND, SQUARE and PROJECT. The default cap is ROUND.
+ *
+ * The parameter to this method must be written in ALL CAPS because they are
+ * predefined as constants in ALL CAPS and Javascript is a case-sensitive language.
+ *
+ * @method strokeCap
+ * @param {Constant} cap either ROUND, SQUARE or PROJECT
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3 lines. Top line: rounded ends, mid: squared, bottom: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 which connect line segments. These joints
+ * are either mitered, beveled or rounded and specified with the
+ * corresponding parameters MITER, BEVEL and ROUND. The default joint is
+ * MITER.
+ *
+ * The parameter to this method must be written in ALL CAPS because they are
+ * predefined as constants in ALL CAPS and Javascript is a case-sensitive language.
+ *
+ * @method strokeJoin
+ * @param {Constant} join either MITER, BEVEL, ROUND
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Right-facing arrowhead shape with pointed tip in center of canvas.
+ * Right-facing arrowhead shape with flat tip in center of canvas.
+ * Right-facing arrowhead shape with 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 lines, points and the border around
+ * shapes. All widths are set in units of pixels.
+ *
+ * @method strokeWeight
+ * @param {Number} weight the weight of the stroke (in pixels)
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3 horizontal black lines. Top line: thin, mid: medium, bottom:thick.
+ */
+ _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': 43, '../main': 54 }
+ ],
+ 63: [
+ 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 cubic Bezier curve on the screen. These curves are defined by a
+ * series of anchor and control points. The first two parameters specify
+ * the first anchor point and the last two parameters specify the other
+ * anchor point, which become the first and last points on the curve. The
+ * middle parameters specify the two control points which define the shape
+ * of the curve. Approximately speaking, control points "pull" the curve
+ * towards them.
+ *
+ * Bezier curves were developed by French automotive engineer Pierre Bezier,
+ * and are commonly used in computer graphics to define gently sloping curves.
+ * See also curve().
+ *
+ * @method bezier
+ * @param {Number} x1 x-coordinate for the first anchor point
+ * @param {Number} y1 y-coordinate for the first anchor point
+ * @param {Number} x2 x-coordinate for the first control point
+ * @param {Number} y2 y-coordinate for the first control point
+ * @param {Number} x3 x-coordinate for the second control point
+ * @param {Number} y3 y-coordinate for the second control point
+ * @param {Number} x4 x-coordinate for the second anchor point
+ * @param {Number} y4 y-coordinate for the second anchor point
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * stretched black s-shape in center with orange lines extending from end points.
+ * a white colored curve on black background from the upper-right corner to the lower right corner.
+ */ /**
+ * @method bezier
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1 z-coordinate for the first anchor point
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate for the first control point
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3 z-coordinate for the second control point
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4 z-coordinate for 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 resolution at which Bezier's curve is displayed. The default value is 20.
+ *
+ * Note, This function is only useful when using the WEBGL renderer
+ * as the default canvas renderer does not use this information.
+ *
+ * @method bezierDetail
+ * @param {Number} detail resolution of the curves
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * stretched black s-shape with a low level of bezier detail
+ */
+ _main.default.prototype.bezierDetail = function(d) {
+ _main.default._validateParameters('bezierDetail', arguments);
+ this._bezierDetail = d;
+ return this;
+ };
+
+ /**
+ * Given the x or y co-ordinate values of control and anchor points of a bezier
+ * curve, it evaluates the x or y coordinate of the bezier at position t. The
+ * parameters a and d are the x or y coordinates of first and last points on the
+ * curve while b and c are of the control points.The final parameter t is the
+ * position of the resultant point which is given between 0 and 1.
+ * This can be done once with the x coordinates and a second time
+ * with the y coordinates to get the location of a bezier curve at t.
+ *
+ * @method bezierPoint
+ * @param {Number} a coordinate of first point on the curve
+ * @param {Number} b coordinate of first control point
+ * @param {Number} c coordinate of second control point
+ * @param {Number} d coordinate of second point on the curve
+ * @param {Number} t value between 0 and 1
+ * @return {Number} the value of the Bezier at position t
+ * @example
+ *
+ *
+ * noFill();
+ * let x1 = 85,
+ x2 = 10,
+ x3 = 90,
+ x4 = 15;
+ * let y1 = 20,
+ y2 = 10,
+ y3 = 90,
+ y4 = 80;
+ * bezier(x1, y1, x2, y2, x3, y3, x4, y4);
+ * fill(255);
+ * let steps = 10;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = bezierPoint(x1, x2, x3, x4, t);
+ * let y = bezierPoint(y1, y2, y3, y4, t);
+ * circle(x, y, 5);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 10 points plotted on a given bezier at equal distances.
+ */
+ _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
+ );
+ };
+
+ /**
+ * Evaluates the tangent to the Bezier at position t for points a, b, c, d.
+ * The parameters a and d are the first and last points
+ * on the curve, and b and c are the control points.
+ * The final parameter t varies between 0 and 1.
+ *
+ * @method bezierTangent
+ * @param {Number} a coordinate of first point on the curve
+ * @param {Number} b coordinate of first control point
+ * @param {Number} c coordinate of second control point
+ * @param {Number} d coordinate of second point on the curve
+ * @param {Number} t value between 0 and 1
+ * @return {Number} the tangent at position t
+ * @example
+ *
+ *
+ * noFill();
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ * let steps = 6;
+ * fill(255);
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * // Get the location of the point
+ * let x = bezierPoint(85, 10, 90, 15, t);
+ * let y = bezierPoint(20, 10, 90, 80, t);
+ * // Get the tangent points
+ * let tx = bezierTangent(85, 10, 90, 15, t);
+ * let ty = bezierTangent(20, 10, 90, 80, t);
+ * // Calculate an angle from the tangent points
+ * let a = atan2(ty, tx);
+ * a += PI;
+ * stroke(255, 102, 0);
+ * line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);
+ * // The following line of code makes a line
+ * // inverse of the above line
+ * //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);
+ * stroke(0);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * noFill();
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ * stroke(255, 102, 0);
+ * let steps = 16;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = bezierPoint(85, 10, 90, 15, t);
+ * let y = bezierPoint(20, 10, 90, 80, t);
+ * let tx = bezierTangent(85, 10, 90, 15, t);
+ * let ty = bezierTangent(20, 10, 90, 80, t);
+ * let a = atan2(ty, tx);
+ * a -= HALF_PI;
+ * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
+ * }
+ *
+ *
+ *
+ * @alt
+ * s-shaped line with 6 short orange lines showing the tangents at those points.
+ * s-shaped line with 6 short orange lines showing lines coming out the underside of the bezier.
+ */
+ _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 curved line on the screen between two points, given as the
+ * middle four parameters. The first two parameters are a control point, as
+ * if the curve came from this point even though it's not drawn. The last
+ * two parameters similarly describe the other control point.
+ * Longer curves can be created by putting a series of curve() functions
+ * together or using curveVertex(). An additional function called
+ * curveTightness() provides control for the visual quality of the curve.
+ * The curve() function is an implementation of Catmull-Rom splines.
+ *
+ * @method curve
+ * @param {Number} x1 x-coordinate for the beginning control point
+ * @param {Number} y1 y-coordinate for the beginning control point
+ * @param {Number} x2 x-coordinate for the first point
+ * @param {Number} y2 y-coordinate for the first point
+ * @param {Number} x3 x-coordinate for the second point
+ * @param {Number} y3 y-coordinate for the second point
+ * @param {Number} x4 x-coordinate for the ending control point
+ * @param {Number} y4 y-coordinate for the ending control point
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * horseshoe shape with orange ends facing left and black curved center.
+ * horseshoe shape with orange ends facing left and black curved center.
+ * curving black and orange lines.
+ */
+
+ /**
+ * @method curve
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1 z-coordinate for the beginning control point
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate for the first point
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3 z-coordinate for the second point
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4 z-coordinate for the ending 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 resolution at which curves display. The default value is 20 while
+ * the minimum value is 3.
+ *
+ * This function is only useful when using the WEBGL renderer
+ * as the default canvas renderer does not use this
+ * information.
+ *
+ * @method curveDetail
+ * @param {Number} resolution resolution of the curves
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white arch shape with a low level of curve detail.
+ */
+ _main.default.prototype.curveDetail = function(d) {
+ _main.default._validateParameters('curveDetail', arguments);
+ if (d < 3) {
+ this._curveDetail = 3;
+ } else {
+ this._curveDetail = d;
+ }
+ return this;
+ };
+
+ /**
+ * Modifies the quality of forms created with curve()
+ * and curveVertex().The parameter tightness
+ * determines how the curve fits to the vertex points. The value 0.0 is the
+ * default value for tightness (this value defines the curves to be Catmull-Rom
+ * splines) and the value 1.0 connects all the points with straight lines.
+ * Values within the range -5.0 and 5.0 will deform the curves but will leave
+ * them recognizable and as values increase in magnitude, they will continue to deform.
+ *
+ * @method curveTightness
+ * @param {Number} amount amount of deformation from the original vertices
+ * @chainable
+ * @example
+ *
+ *
+ * // Move the mouse left and right to see the curve change
+ * function setup() {
+ * createCanvas(100, 100);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * let t = map(mouseX, 0, width, -5, 5);
+ * curveTightness(t);
+ * beginShape();
+ * curveVertex(10, 26);
+ * curveVertex(10, 26);
+ * curveVertex(83, 24);
+ * curveVertex(83, 61);
+ * curveVertex(25, 65);
+ * curveVertex(25, 65);
+ * endShape();
+ * }
+ *
+ *
+ *
+ * @alt
+ * Line shaped like right-facing arrow,points move with mouse-x and warp shape.
+ */
+ _main.default.prototype.curveTightness = function(t) {
+ _main.default._validateParameters('curveTightness', arguments);
+ this._renderer._curveTightness = t;
+ return this;
+ };
+
+ /**
+ * Evaluates the curve at position t for points a, b, c, d.
+ * The parameter t varies between 0 and 1, a and d are control points
+ * of the curve, and b and c are the start and end points of the curve.
+ * This can be done once with the x coordinates and a second time
+ * with the y coordinates to get the location of a curve at t.
+ *
+ * @method curvePoint
+ * @param {Number} a coordinate of first control point of the curve
+ * @param {Number} b coordinate of first point
+ * @param {Number} c coordinate of second point
+ * @param {Number} d coordinate of second control point
+ * @param {Number} t value between 0 and 1
+ * @return {Number} bezier value at position t
+ * @example
+ *
+ *
+ * noFill();
+ * curve(5, 26, 5, 26, 73, 24, 73, 61);
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * fill(255);
+ * ellipseMode(CENTER);
+ * let steps = 6;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = curvePoint(5, 5, 73, 73, t);
+ * let y = curvePoint(26, 26, 24, 61, t);
+ * ellipse(x, y, 5, 5);
+ * x = curvePoint(5, 73, 73, 15, t);
+ * y = curvePoint(26, 24, 61, 65, t);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ *
+ *line hooking down to right-bottom with 13 5x5 white ellipse points
+ */
+ _main.default.prototype.curvePoint = function(a, b, c, d, t) {
+ _main.default._validateParameters('curvePoint', arguments);
+
+ var t3 = t * t * t,
+ t2 = t * t,
+ f1 = -0.5 * t3 + t2 - 0.5 * t,
+ f2 = 1.5 * t3 - 2.5 * t2 + 1.0,
+ f3 = -1.5 * t3 + 2.0 * t2 + 0.5 * t,
+ f4 = 0.5 * t3 - 0.5 * t2;
+ return a * f1 + b * f2 + c * f3 + d * f4;
+ };
+
+ /**
+ * Evaluates the tangent to the curve at position t for points a, b, c, d.
+ * The parameter t varies between 0 and 1, a and d are points on the curve,
+ * and b and c are the control points.
+ *
+ * @method curveTangent
+ * @param {Number} a coordinate of first control point
+ * @param {Number} b coordinate of first point on the curve
+ * @param {Number} c coordinate of second point on the curve
+ * @param {Number} d coordinate of second conrol point
+ * @param {Number} t value between 0 and 1
+ * @return {Number} the tangent at position t
+ * @example
+ *
+ *
+ * noFill();
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * let steps = 6;
+ * for (let i = 0; i <= steps; i++) {
+ * let t = i / steps;
+ * let x = curvePoint(5, 73, 73, 15, t);
+ * let y = curvePoint(26, 24, 61, 65, t);
+ * //ellipse(x, y, 5, 5);
+ * let tx = curveTangent(5, 73, 73, 15, t);
+ * let ty = curveTangent(26, 24, 61, 65, t);
+ * let a = atan2(ty, tx);
+ * a -= PI / 2.0;
+ * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
+ * }
+ *
+ *
+ *
+ * @alt
+ * right curving line mid-right of canvas with 7 short lines radiating from it.
+ */
+ _main.default.prototype.curveTangent = function(a, b, c, d, t) {
+ _main.default._validateParameters('curveTangent', arguments);
+
+ var t2 = t * t,
+ f1 = -3 * t2 / 2 + 2 * t - 0.5,
+ f2 = 9 * t2 / 2 - 5 * t,
+ f3 = -9 * t2 / 2 + 4 * t + 0.5,
+ f4 = 3 * t2 / 2 - t;
+ return a * f1 + b * f2 + c * f3 + d * f4;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ {
+ '../friendly_errors/fes_core': 46,
+ '../friendly_errors/file_errors': 47,
+ '../friendly_errors/validate_params': 49,
+ '../main': 54
+ }
+ ],
+ 64: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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;
+
+ /**
+ * Use the beginContour() and
+ * endContour() functions to create negative shapes
+ * within shapes such as the center of the letter 'O'. beginContour()
+ * begins recording vertices for the shape and endContour() stops recording.
+ * The vertices that define a negative shape must "wind" in the opposite direction
+ * from the exterior shape. First draw vertices for the exterior clockwise order, then for internal shapes, draw vertices
+ * shape in counter-clockwise.
+ *
+ * These functions can only be used within a beginShape()/endShape() pair and
+ * transformations such as translate(), rotate(), and scale() do not work
+ * within a beginContour()/endContour() pair. It is also not possible to use
+ * other shapes, such as ellipse() or rect() within.
+ *
+ * @method beginContour
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white rect and smaller grey rect with red outlines in center of canvas.
+ */
+ _main.default.prototype.beginContour = function() {
+ contourVertices = [];
+ isContour = true;
+ return this;
+ };
+
+ /**
+ * Using the beginShape() and endShape() functions allow creating more
+ * complex forms. beginShape() begins recording vertices for a shape and
+ * endShape() stops recording. The value of the kind parameter tells it which
+ * types of shapes to create from the provided vertices. With no mode
+ * specified, the shape can be any irregular polygon.
+ *
+ * The parameters available for beginShape() are POINTS, LINES, TRIANGLES,
+ * TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP, and TESS (WebGL only). After calling the
+ * beginShape() function, a series of vertex() commands must follow. To stop
+ * drawing the shape, call endShape(). Each shape will be outlined with the
+ * current stroke color and filled with the fill color.
+ *
+ * Transformations such as translate(), rotate(), and scale() do not work
+ * within beginShape(). It is also not possible to use other shapes, such as
+ * ellipse() or rect() within beginShape().
+ *
+ * @method beginShape
+ * @param {Constant} [kind] either POINTS, LINES, TRIANGLES, TRIANGLE_FAN
+ * TRIANGLE_STRIP, QUADS, QUAD_STRIP or TESS
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white square-shape with black outline in middle-right of canvas.
+ * 4 black points in a square shape in middle-right of canvas.
+ * 2 horizontal black lines. In the top-right and bottom-right of canvas.
+ * 3 line shape with horizontal on top, vertical in middle and horizontal bottom.
+ * square line shape in middle-right of canvas.
+ * 2 white triangle shapes mid-right canvas. left one pointing up and right down.
+ * 5 horizontal interlocking and alternating white triangles in mid-right canvas.
+ * 4 interlocking white triangles in 45 degree rotated square-shape.
+ * 2 white rectangle shapes in mid-right canvas. Both 20x55.
+ * 3 side-by-side white rectangles center rect is smaller in mid-right canvas.
+ * Thick white l-shape with black outline mid-top-left of canvas.
+ */
+ _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;
+ };
+
+ /**
+ * Specifies vertex coordinates for Bezier curves. Each call to
+ * bezierVertex() defines the position of two control points and
+ * one anchor point of a Bezier curve, adding a new segment to a
+ * line or shape. For WebGL mode bezierVertex() can be used in 2D
+ * as well as 3D mode. 2D mode expects 6 parameters, while 3D mode
+ * expects 9 parameters (including z coordinates).
+ *
+ * The first time bezierVertex() is used within a beginShape()
+ * call, it must be prefaced with a call to vertex() to set the first anchor
+ * point. This function must be used between beginShape() and endShape()
+ * and only when there is no MODE or POINTS parameter specified to
+ * beginShape().
+ *
+ * @method bezierVertex
+ * @param {Number} x2 x-coordinate for the first control point
+ * @param {Number} y2 y-coordinate for the first control point
+ * @param {Number} x3 x-coordinate for the second control point
+ * @param {Number} y3 y-coordinate for the second control point
+ * @param {Number} x4 x-coordinate for the anchor point
+ * @param {Number} y4 y-coordinate for the anchor point
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * @alt
+ * crescent-shaped line in middle of canvas. Points facing left.
+ * white crescent shape in middle of canvas. Points facing left.
+ * crescent shape in middle of canvas with another crescent shape on positive z-axis.
+ */
+
+ /**
+ * @method bezierVertex
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate for the first control point (for WebGL mode)
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3 z-coordinate for the second control point (for WebGL mode)
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4 z-coordinate for the anchor point (for WebGL mode)
+ * @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;
+ };
+
+ /**
+ * Specifies vertex coordinates for curves. This function may only
+ * be used between beginShape() and endShape() and only when there
+ * is no MODE parameter specified to beginShape().
+ * For WebGL mode curveVertex() can be used in 2D as well as 3D mode.
+ * 2D mode expects 2 parameters, while 3D mode expects 3 parameters.
+ *
+ * The first and last points in a series of curveVertex() lines will be used to
+ * guide the beginning and end of a the curve. A minimum of four
+ * points is required to draw a tiny curve between the second and
+ * third points. Adding a fifth point with curveVertex() will draw
+ * the curve between the second, third, and fourth points. The
+ * curveVertex() function is an implementation of Catmull-Rom
+ * splines.
+ *
+ * @method curveVertex
+ * @param {Number} x x-coordinate of the vertex
+ * @param {Number} y y-coordinate of the vertex
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Upside-down u-shape line, mid canvas with the same shape in positive z-axis.
+ */
+ _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;
+ };
+
+ /**
+ * Use the beginContour() and endContour() functions to create negative
+ * shapes within shapes such as the center of the letter 'O'. beginContour()
+ * begins recording vertices for the shape and endContour() stops recording.
+ * The vertices that define a negative shape must "wind" in the opposite
+ * direction from the exterior shape. First draw vertices for the exterior
+ * clockwise order, then for internal shapes, draw vertices
+ * shape in counter-clockwise.
+ *
+ * These functions can only be used within a beginShape()/endShape() pair and
+ * transformations such as translate(), rotate(), and scale() do not work
+ * within a beginContour()/endContour() pair. It is also not possible to use
+ * other shapes, such as ellipse() or rect() within.
+ *
+ * @method endContour
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white rect and smaller grey rect with red outlines in center of canvas.
+ */
+ _main.default.prototype.endContour = function() {
+ 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;
+ };
+
+ /**
+ * The endShape() function is the companion to beginShape() and may only be
+ * called after beginShape(). When endShape() is called, all of image data
+ * defined since the previous call to beginShape() is written into the image
+ * buffer. The constant CLOSE as the value for the MODE parameter to close
+ * the shape (to connect the beginning and the end).
+ *
+ * @method endShape
+ * @param {Constant} [mode] use CLOSE to close the shape
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Triangle line shape with smallest interior angle on bottom and upside-down L.
+ */
+ _main.default.prototype.endShape = function(mode) {
+ _main.default._validateParameters('endShape', arguments);
+ if (this._renderer.isP3D) {
+ this._renderer.endShape(
+ mode,
+ isCurve,
+ isBezier,
+ isQuadratic,
+ isContour,
+ shapeKind
+ );
+ } else {
+ 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;
+ };
+
+ /**
+ * Specifies vertex coordinates for quadratic Bezier curves. Each call to
+ * quadraticVertex() defines the position of one control points and one
+ * anchor point of a Bezier curve, adding a new segment to a line or shape.
+ * The first time quadraticVertex() is used within a beginShape() call, it
+ * must be prefaced with a call to vertex() to set the first anchor point.
+ * For WebGL mode quadraticVertex() can be used in 2D as well as 3D mode.
+ * 2D mode expects 4 parameters, while 3D mode expects 6 parameters
+ * (including z coordinates).
+ *
+ * This function must be used between beginShape() and endShape()
+ * and only when there is no MODE or POINTS parameter specified to
+ * beginShape().
+ *
+ * @method quadraticVertex
+ * @param {Number} cx x-coordinate for the control point
+ * @param {Number} cy y-coordinate for the control point
+ * @param {Number} x3 x-coordinate for the anchor point
+ * @param {Number} y3 y-coordinate for the anchor point
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * // Click to change the number of sides.
+ * // In WebGL mode, custom shapes will only
+ * // display hollow fill sections when
+ * // all calls to vertex() use the same z-value.
+ *
+ * let sides = 3;
+ * let angle, px, py;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * setAttributes('antialias', true);
+ * fill(237, 34, 93);
+ * strokeWeight(3);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateX(frameCount * 0.01);
+ * rotateZ(frameCount * 0.01);
+ * ngon(sides, 0, 0, 80);
+ * }
+ *
+ * function mouseClicked() {
+ * if (sides > 6) {
+ * sides = 3;
+ * } else {
+ * sides++;
+ * }
+ * }
+ *
+ * function ngon(n, x, y, d) {
+ * beginShape(TESS);
+ * for (let i = 0; i < n + 1; i++) {
+ * angle = TWO_PI / n * i;
+ * px = x + sin(angle) * d / 2;
+ * py = y - cos(angle) * d / 2;
+ * vertex(px, py, 0);
+ * }
+ * for (let i = 0; i < n + 1; i++) {
+ * angle = TWO_PI / n * i;
+ * px = x + sin(angle) * d / 4;
+ * py = y - cos(angle) * d / 4;
+ * vertex(px, py, 0);
+ * }
+ * endShape();
+ * }
+ *
+ *
+ * @alt
+ * 4 black points in a square shape in middle-right of canvas.
+ * 4 points making a diamond shape.
+ * 8 points making a star.
+ * 8 points making 4 lines.
+ * A rotating 3D shape with a hollow section in the middle.
+ */
+ /**
+ * @method vertex
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} z z-coordinate of the vertex
+ * @param {Number} [u] the vertex's texture u-coordinate
+ * @param {Number} [v] the vertex's texture v-coordinate
+ * @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;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../constants': 43, '../main': 54 }
+ ],
+ 65: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ } // requestAnim shim layer by Paul Irish
+ // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
+ // http://my.opera.com/emoller/blog/2011/12/20/
+ // requestanimationframe-for-smart-er-animating
+ // requestAnimationFrame polyfill by Erik Möller
+ // fixes from Paul Irish and Tino Zijdel
+ window.requestAnimationFrame = (function() {
+ return (
+ window.requestAnimationFrame ||
+ window.webkitRequestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ window.oRequestAnimationFrame ||
+ window.msRequestAnimationFrame ||
+ function(callback, element) {
+ // should '60' here be framerate?
+ window.setTimeout(callback, 1000 / 60);
+ }
+ );
+ })();
+
+ /**
+ * shim for Uint8ClampedArray.slice
+ * (allows arrayCopy to work with pixels[])
+ * with thanks to http://halfpapstudios.com/blog/tag/html5-canvas/
+ * Enumerable set to false to protect for...in from
+ * Uint8ClampedArray.prototype pollution.
+ */
+ (function() {
+ if (
+ typeof Uint8ClampedArray !== 'undefined' &&
+ !Uint8ClampedArray.prototype.slice
+ ) {
+ Object.defineProperty(Uint8ClampedArray.prototype, 'slice', {
+ value: Array.prototype.slice,
+ writable: true,
+ configurable: true,
+ enumerable: false
+ });
+ }
+ })();
+
+ /**
+ * this is implementation of Object.assign() which is unavailable in
+ * IE11 and (non-Chrome) Android browsers.
+ * The assign() method is used to copy the values of all enumerable
+ * own properties from one or more source objects to a target object.
+ * It will return the target object.
+ * Modified from https://github.com/ljharb/object.assign
+ */
+ (function() {
+ if (!Object.assign) {
+ var keys = Object.keys;
+ var defineProperty = Object.defineProperty;
+ var canBeObject = function canBeObject(obj) {
+ return typeof obj !== 'undefined' && obj !== null;
+ };
+ var hasSymbols =
+ typeof Symbol === 'function' && _typeof(Symbol()) === 'symbol';
+ var propIsEnumerable = Object.prototype.propertyIsEnumerable;
+ var isEnumerableOn = function isEnumerableOn(obj) {
+ return function isEnumerable(prop) {
+ return propIsEnumerable.call(obj, prop);
+ };
+ };
+
+ // per ES6 spec, this function has to have a length of 2
+ var assignShim = function assign(target, source1) {
+ if (!canBeObject(target)) {
+ throw new TypeError('target must be an object');
+ }
+ var objTarget = Object(target);
+ var s, source, i, props;
+ for (s = 1; s < arguments.length; ++s) {
+ source = Object(arguments[s]);
+ props = keys(source);
+ if (hasSymbols && Object.getOwnPropertySymbols) {
+ props.push.apply(
+ props,
+ Object.getOwnPropertySymbols(source).filter(isEnumerableOn(source))
+ );
+ }
+ for (i = 0; i < props.length; ++i) {
+ objTarget[props[i]] = source[props[i]];
+ }
+ }
+ return objTarget;
+ };
+
+ defineProperty(Object, 'assign', {
+ value: assignShim,
+ configurable: true,
+ enumerable: false,
+ writable: true
+ });
+ }
+ })();
+ },
+ {}
+ ],
+ 66: [
+ 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 };
+ }
+ /**
+ * @module Structure
+ * @submodule Structure
+ * @for p5
+ * @requires core
+ */ /**
+ * Stops p5.js from continuously executing the code within draw().
+ * If loop() is called, the code in draw()
+ * begins to run continuously again. If using noLoop()
+ * in setup(), it should be the last line inside the block.
+ *
+ * When noLoop() is used, it's not possible to manipulate
+ * or access the screen inside event handling functions such as
+ * mousePressed() or
+ * keyPressed(). Instead, use those functions to
+ * call redraw() or loop(),
+ * which will run draw(), which can update the screen
+ * properly. This means that when noLoop() has been
+ * called, no drawing can happen, and functions like saveFrame()
+ * or loadPixels() may not be used.
+ *
+ * Note that if the sketch is resized, redraw() will
+ * be called to update the sketch, even after noLoop()
+ * has been specified. Otherwise, the sketch would enter an odd state until
+ * loop() was called.
+ *
+ * Use isLooping() to check current state of loop().
+ *
+ * @method noLoop
+ * @example
+ *
+ *
+ * let x = 0;
+ * function setup() {
+ * createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x = x + 0.1;
+ * if (x > width) {
+ * x = 0;
+ * }
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * noLoop();
+ * }
+ *
+ * function mouseReleased() {
+ * loop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * 113 pixel long line extending from top-left to bottom right of canvas.
+ * horizontal line moves slowly from left. Loops but stops on mouse press.
+ */ _main.default.prototype.noLoop = function() {
+ this._loop = false;
+ };
+
+ /**
+ * By default, p5.js loops through draw() continuously, executing the code within
+ * it. However, the draw() loop may be stopped by calling
+ * noLoop(). In that case, the draw()
+ * loop can be resumed with loop().
+ *
+ * Avoid calling loop() from inside setup().
+ *
+ * Use isLooping() to check current state of loop().
+ *
+ * @method loop
+ * @example
+ *
+ *
+ * let x = 0;
+ * function setup() {
+ * createCanvas(100, 100);
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x = x + 0.1;
+ * if (x > width) {
+ * x = 0;
+ * }
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * loop();
+ * }
+ *
+ * function mouseReleased() {
+ * noLoop();
+ * }
+ *
+ *
+ *
+ * @alt
+ * horizontal line moves slowly from left. Loops but stops on mouse press.
+ */
+ _main.default.prototype.loop = function() {
+ if (!this._loop) {
+ this._loop = true;
+ if (this._setupDone) {
+ this._draw();
+ }
+ }
+ };
+
+ /**
+ * By default, p5.js loops through draw() continuously,
+ * executing the code within it. If the sketch is stopped with
+ * noLoop() or resumed with loop(),
+ * isLooping() returns the current state for use within custom event handlers.
+ *
+ * @method isLooping
+ * @example
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * translate(50, 0);
+ * ellipse(0, 50, 33, 33); // Middle circle
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(33, 50, 33, 33); // Left-middle circle
+ *
+ * push(); // Start another new drawing state
+ * stroke(0, 102, 153);
+ * ellipse(66, 50, 33, 33); // Right-middle circle
+ * pop(); // Restore previous state
+ *
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ * @alt
+ * Gold ellipse + thick black outline @center 2 white ellipses on left and right.
+ * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.
+ */
+ _main.default.prototype.push = function() {
+ this._styles.push({
+ props: {
+ _colorMode: this._colorMode
+ },
+
+ renderer: this._renderer.push()
+ });
+ };
+
+ /**
+ * The push() function saves the current drawing style
+ * settings and transformations, while pop() restores
+ * these settings. Note that these functions are always used together. They allow
+ * you to change the style and transformation settings and later return to what
+ * you had. When a new state is started with push(), it
+ * builds on the current style and transform information. The push()
+ * and pop() functions can be embedded to provide more
+ * control. (See the second example for a demonstration.)
+ *
+ * push() stores information related to the current transformation state
+ * and style settings controlled by 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(),
+ * noiseSeed().
+ *
+ * In WEBGL mode additional style settings are stored. These are controlled by
+ * the following functions:
+ * setCamera(),
+ * ambientLight(),
+ * directionalLight(),
+ * pointLight(),
+ * texture(),
+ * specularMaterial(),
+ * shininess(),
+ * normalMaterial() and
+ * shader().
+ *
+ * @method pop
+ * @example
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * translate(50, 0);
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(0, 50, 33, 33); // Middle circle
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(33, 50, 33, 33); // Left-middle circle
+ *
+ * push(); // Start another new drawing state
+ * stroke(0, 102, 153);
+ * ellipse(66, 50, 33, 33); // Right-middle circle
+ * pop(); // Restore previous state
+ *
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ * @alt
+ * Gold ellipse + thick black outline @center 2 white ellipses on left and right.
+ * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.
+ */
+ _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()');
+ }
+ };
+
+ /**
+ * Executes the code within draw() one time. This
+ * function allows the program to update the display window only when necessary,
+ * for example when an event registered by mousePressed()
+ * or keyPressed() occurs.
+ *
+ * In structuring a program, it only makes sense to call redraw()
+ * within events such as mousePressed(). This
+ * is because redraw() does not run
+ * draw() immediately (it only sets a flag that indicates
+ * an update is needed).
+ *
+ * The redraw() function does not work properly when
+ * called inside draw().To enable/disable animations,
+ * use loop() and noLoop().
+ *
+ * In addition you can set the number of redraws per method call. Just
+ * add an integer as single parameter for the number of redraws.
+ *
+ * @method redraw
+ * @param {Integer} [n] Redraw for n-times. The default value is 1.
+ * @example
+ *
+ *
+ * @alt
+ * black line on far left of canvas
+ * black line on far left of canvas
+ */
+ _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;
+ var userSetup = context.setup;
+ var userDraw = context.draw;
+ if (typeof userDraw === 'function') {
+ if (typeof userSetup === 'undefined') {
+ context.scale(context._pixelDensity, context._pixelDensity);
+ }
+ var callMethod = function callMethod(f) {
+ f.call(context);
+ };
+ for (var idxRedraw = 0; idxRedraw < numberOfRedraws; idxRedraw++) {
+ context.resetMatrix();
+ if (context._renderer.isP3D) {
+ context._renderer._update();
+ }
+ context._setProperty('frameCount', context.frameCount + 1);
+ context._registeredMethods.pre.forEach(callMethod);
+ this._inUserDraw = true;
+ try {
+ userDraw();
+ } finally {
+ this._inUserDraw = false;
+ }
+ context._registeredMethods.post.forEach(callMethod);
+ }
+ }
+ };
+
+ /**
+ * The `p5()` constructor enables you to activate "instance mode" instead of normal
+ * "global mode". This is an advanced topic. A short description and example is
+ * included below. Please see
+ *
+ * Dan Shiffman's Coding Train video tutorial or this
+ * tutorial page
+ * for more info.
+ *
+ * By default, all p5.js functions are in the global namespace (i.e. bound to the window
+ * object), meaning you can call them simply `ellipse()`, `fill()`, etc. However, this
+ * might be inconvenient if you are mixing with other JS libraries (synchronously or
+ * asynchronously) or writing long programs of your own. p5.js currently supports a
+ * way around this problem called "instance mode". In instance mode, all p5 functions
+ * are bound up in a single variable instead of polluting your global namespace.
+ *
+ * Optionally, you can specify a default container for the canvas and any other elements
+ * to append to with a second argument. You can give the ID of an element in your html,
+ * or an html node itself.
+ *
+ * Note that creating instances like this also allows you to have more than one p5 sketch on
+ * a single web page, as they will each be wrapped up with their own set up variables. Of
+ * course, you could also use iframes to have multiple sketches in global mode.
+ *
+ * @method p5
+ * @param {Object} sketch a function containing a p5.js sketch
+ * @param {String|Object} node ID or pointer to HTML DOM node to contain sketch in
+ * @example
+ *
+ * const s = p => {
+ * let x = 100;
+ * let y = 100;
+ *
+ * p.setup = function() {
+ * p.createCanvas(700, 410);
+ * };
+ *
+ * p.draw = function() {
+ * p.background(0);
+ * p.fill(255);
+ * p.rect(x, y, 50, 50);
+ * };
+ * };
+ *
+ * new p5(s); // invoke p5
+ *
+ *
+ * @alt
+ * white rectangle on black background
+ */ var _default = _main.default;
+ exports.default = _default;
+ },
+ { './main': 54 }
+ ],
+ 67: [
+ 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 };
+ }
+ /**
+ * @module Transform
+ * @submodule Transform
+ * @for p5
+ * @requires core
+ * @requires constants
+ */ /**
+ * Multiplies the current matrix by the one specified through the parameters.
+ * This is a powerful operation that can perform the equivalent of translate,
+ * scale, shear and rotate all at once. You can learn more about transformation
+ * matrices on
+ * Wikipedia.
+ *
+ * The naming of the arguments here follows the naming of the
+ * WHATWG specification and corresponds to a
+ * transformation matrix of the
+ * form:
+ *
+ * >
+ *
+ * @method applyMatrix
+ * @param {Number} a numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} b numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} c numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} d numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} e numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} f numbers which define the 2x3 matrix to be multiplied
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateY(PI / 6);
+ * stroke(153);
+ * box(35);
+ * let rad = millis() / 1000;
+ * // Set rotation angles
+ * let ct = cos(rad);
+ * let st = sin(rad);
+ * // Matrix for rotation around the Y axis
+ * // prettier-ignore
+ * applyMatrix( ct, 0.0, st, 0.0,
+ * 0.0, 1.0, 0.0, 0.0,
+ * -st, 0.0, ct, 0.0,
+ * 0.0, 0.0, 0.0, 1.0);
+ * stroke(255);
+ * box(50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * A rectangle translating to the right
+ * A rectangle shrinking to the center
+ * A rectangle rotating clockwise about the center
+ * A rectangle shearing
+ */ _main.default.prototype.applyMatrix = function(a, b, c, d, e, f) {
+ var _this$_renderer;
+ (_this$_renderer = this._renderer).applyMatrix.apply(
+ _this$_renderer,
+ arguments
+ );
+ return this;
+ };
+
+ /**
+ * Replaces the current matrix with the identity matrix.
+ *
+ * @method resetMatrix
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * A rotated retangle in the center with another at the top left corner
+ */
+ _main.default.prototype.resetMatrix = function() {
+ this._renderer.resetMatrix();
+ return this;
+ };
+
+ /**
+ * Rotates a shape by the amount specified by the angle parameter. This
+ * function accounts for angleMode, so angles
+ * can be entered in either RADIANS or DEGREES.
+ *
+ * Objects are always rotated around their relative position to the
+ * origin and positive numbers rotate objects in a clockwise direction.
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).
+ * All tranformations are reset when draw() begins again.
+ *
+ * Technically, rotate() multiplies the current transformation matrix
+ * by a rotation matrix. This function can be further controlled by
+ * the push() and pop().
+ *
+ * @method rotate
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @param {p5.Vector|Number[]} [axis] (in 3d) the axis to rotate around
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white 52x52 rect with black outline at center rotated counter 45 degrees
+ */
+ _main.default.prototype.rotate = function(angle, axis) {
+ _main.default._validateParameters('rotate', arguments);
+ this._renderer.rotate(this._toRadians(angle), axis);
+ return this;
+ };
+
+ /**
+ * Rotates a shape around X axis by the amount specified in angle parameter.
+ * The angles can be entered in either RADIANS or DEGREES.
+ *
+ * Objects are always rotated around their relative position to the
+ * origin and positive numbers rotate objects in a clockwise direction.
+ * All tranformations are reset when draw() begins again.
+ *
+ * @method rotateX
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3d box rotating around the x axis.
+ */
+ _main.default.prototype.rotateX = function(angle) {
+ this._assert3d('rotateX');
+ _main.default._validateParameters('rotateX', arguments);
+ this._renderer.rotateX(this._toRadians(angle));
+ return this;
+ };
+
+ /**
+ * Rotates a shape around Y axis by the amount specified in angle parameter.
+ * The angles can be entered in either RADIANS or DEGREES.
+ *
+ * Objects are always rotated around their relative position to the
+ * origin and positive numbers rotate objects in a clockwise direction.
+ * All tranformations are reset when draw() begins again.
+ *
+ * @method rotateY
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3d box rotating around the y axis.
+ */
+ _main.default.prototype.rotateY = function(angle) {
+ this._assert3d('rotateY');
+ _main.default._validateParameters('rotateY', arguments);
+ this._renderer.rotateY(this._toRadians(angle));
+ return this;
+ };
+
+ /**
+ * Rotates a shape around Z axis by the amount specified in angle parameter.
+ * The angles can be entered in either RADIANS or DEGREES.
+ *
+ * This method works in WEBGL mode only.
+ *
+ * Objects are always rotated around their relative position to the
+ * origin and positive numbers rotate objects in a clockwise direction.
+ * All tranformations are reset when draw() begins again.
+ *
+ * @method rotateZ
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 3d box rotating around the z axis.
+ */
+ _main.default.prototype.rotateZ = function(angle) {
+ this._assert3d('rotateZ');
+ _main.default._validateParameters('rotateZ', arguments);
+ this._renderer.rotateZ(this._toRadians(angle));
+ return this;
+ };
+
+ /**
+ * Increases or decreases the size of a shape by expanding or contracting
+ * vertices. Objects always scale from their relative origin to the
+ * coordinate system. Scale values are specified as decimal percentages.
+ * For example, the function call scale(2.0) increases the dimension of a
+ * shape by 200%.
+ *
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function multiply the effect. For example, calling scale(2.0)
+ * and then scale(1.5) is the same as scale(3.0). If scale() is called
+ * within draw(), the transformation is reset when the loop begins again.
+ *
+ * Using this function with the z parameter is only available in WEBGL mode.
+ * This function can be further controlled with push() and pop().
+ *
+ * @method scale
+ * @param {Number|p5.Vector|Number[]} s
+ * percent to scale the object, or percentage to
+ * scale the object in the x-axis if multiple arguments
+ * are given
+ * @param {Number} [y] percent to scale the object in the y-axis
+ * @param {Number} [z] percent to scale the object in the z-axis (webgl only)
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white 52x52 rect with black outline at center rotated counter 45 degrees
+ * 2 white rects with black outline- 1 50x50 at center. other 25x65 bottom left
+ */
+ /**
+ * @method scale
+ * @param {p5.Vector|Number[]} scales per-axis percents to scale the object
+ * @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 (x instanceof Array) {
+ 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.call(this._renderer, x, y, z);
+
+ return this;
+ };
+
+ /**
+ * Shears a shape around the x-axis by the amount specified by the angle
+ * parameter. Angles should be specified in the current angleMode.
+ * Objects are always sheared around their relative position to the origin
+ * and positive numbers shear objects in a clockwise direction.
+ *
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * shearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).
+ * If shearX() is called within the draw(),
+ * the transformation is reset when the loop begins again.
+ *
+ * Technically, shearX() multiplies the current
+ * transformation matrix by a rotation matrix. This function can be further
+ * controlled by the push() and pop() functions.
+ *
+ * @method shearX
+ * @param {Number} angle angle of shear specified in radians or degrees,
+ * depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white irregular quadrilateral with black outline at top middle.
+ */
+ _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 a shape around the y-axis the amount specified by the angle
+ * parameter. Angles should be specified in the current angleMode. Objects
+ * are always sheared around their relative position to the origin and
+ * positive numbers shear objects in a clockwise direction.
+ *
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * shearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If
+ * shearY() is called within the draw(), the transformation is reset when
+ * the loop begins again.
+ *
+ * Technically, shearY() multiplies the current transformation matrix by a
+ * rotation matrix. This function can be further controlled by the
+ * push() and pop() functions.
+ *
+ * @method shearY
+ * @param {Number} angle angle of shear specified in radians or degrees,
+ * depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white irregular quadrilateral with black outline at middle bottom.
+ */
+ _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;
+ };
+
+ /**
+ * Specifies an amount to displace objects within the display window.
+ * The x parameter specifies left/right translation, the y parameter
+ * specifies up/down translation.
+ *
+ * Transformations are cumulative and apply to everything that happens after
+ * and subsequent calls to the function accumulates the effect. For example,
+ * calling translate(50, 0) and then translate(20, 0) is the same as
+ * translate(70, 0). If translate() is called within draw(), the
+ * transformation is reset when the loop begins again. This function can be
+ * further controlled by using push() and pop().
+ *
+ * @method translate
+ * @param {Number} x left/right translation
+ * @param {Number} y up/down translation
+ * @param {Number} [z] forward/backward translation (webgl only)
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * white 55x55 rect with black outline at center right.
+ * 3 white 55x55 rects with black outlines at top-l, center-r and bottom-r.
+ * a 20x20 white rect moving in a circle around the canvas
+ */
+ /**
+ * @method translate
+ * @param {p5.Vector} vector the vector to translate by
+ * @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': 54 }
+ ],
+ 68: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+
+ 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' && 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);
+ }
+ /**
+ *
+ * Stores a value in local storage under the key name.
+ * Local storage is saved in the browser and persists
+ * between browsing sessions and page reloads.
+ * The key can be the name of the variable but doesn't
+ * have to be. To retrieve stored items
+ * see getItem.
+ *
+ * Sensitive data such as passwords or personal information
+ * should not be stored in local storage.
+ *
+ * @method storeItem
+ * @for p5
+ * @param {String} key
+ * @param {String|Number|Object|Boolean|p5.Color|p5.Vector} value
+ *
+ * @example
+ *
+ * // Type to change the letter in the
+ * // center of the canvas.
+ * // If you reload the page, it will
+ * // still display the last key you entered
+ *
+ * let myText;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * myText = getItem('myText');
+ * if (myText === null) {
+ * myText = '';
+ * }
+ * }
+ *
+ * function draw() {
+ * textSize(40);
+ * background(255);
+ * text(myText, width / 2, height / 2);
+ * }
+ *
+ * function keyPressed() {
+ * myText = key;
+ * storeItem('myText', myText);
+ * }
+ *
+ *
+ * @alt
+ * When you type the key name is displayed as black text on white background.
+ * If you reload the page, the last letter typed is still displaying.
+ */
+ _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 the value of an item that was stored in local storage
+ * using storeItem()
+ *
+ * @method getItem
+ * @for p5
+ * @param {String} key name that you wish to use to store in local storage
+ * @return {Number|Object|String|Boolean|p5.Color|p5.Vector} Value of stored item
+ *
+ * @example
+ *
+ * // Click the mouse to change
+ * // the color of the background
+ * // Once you have changed the color
+ * // it will stay changed even when you
+ * // reload the page.
+ *
+ * let myColor;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * myColor = getItem('myColor');
+ * }
+ *
+ * function draw() {
+ * if (myColor !== null) {
+ * background(myColor);
+ * }
+ * }
+ *
+ * function mousePressed() {
+ * myColor = color(random(255), random(255), random(255));
+ * storeItem('myColor', myColor);
+ * }
+ *
+ *
+ * @alt
+ * If you click, the canvas changes to a random color.
+ * If you reload the page, the canvas is still the color it
+ * was when the page was previously loaded.
+ */
+ _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 = parseInt(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;
+ };
+
+ /**
+ *
+ * Clears all local storage items set with storeItem()
+ * for the current domain.
+ *
+ * @method clearStorage
+ * @for p5
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * let myNum = 10;
+ * let myBool = false;
+ * storeItem('myNum', myNum);
+ * storeItem('myBool', myBool);
+ * print(getItem('myNum')); // logs 10 to the console
+ * print(getItem('myBool')); // logs false to the console
+ * clearStorage();
+ * print(getItem('myNum')); // logs null to the console
+ * print(getItem('myBool')); // logs null to the console
+ * }
+ *
+ *
+ * function setup() {
+ * let myVar = 10;
+ * storeItem('myVar', myVar);
+ * print(getItem('myVar')); // logs 10 to the console
+ * removeItem('myVar');
+ * print(getItem('myVar')); // logs null to the console
+ * }
+ *
+ */
+ _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': 54 }
+ ],
+ 69: [
+ 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 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 = function(key, value) {
+ 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
+ * }
+ *
+ */
+ _main.default.TypedDict.prototype.size = function() {
+ 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
+ * }
+ *
+ */
+
+ _main.default.TypedDict.prototype.hasKey = function(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
+ * }
+ *
+ */
+
+ _main.default.TypedDict.prototype.get = function(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
+ *
+ */
+
+ _main.default.TypedDict.prototype.remove = function(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
+ *
+ *
+ */
+
+ _main.default.NumberDict.prototype.add = function(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
+ *
+ *
+ */
+
+ _main.default.NumberDict.prototype.sub = function(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
+ *
+ *
+ */
+
+ _main.default.NumberDict.prototype.mult = function(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
+ *
+ *
+ */
+
+ _main.default.NumberDict.prototype.div = function(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'
+ */
+
+ _main.default.NumberDict.prototype._valueTest = function(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);
+ * }
+ *
+ */
+
+ _main.default.NumberDict.prototype.minValue = function() {
+ 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);
+ * }
+ *
+ */
+
+ _main.default.NumberDict.prototype.maxValue = function() {
+ 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'
+ */
+
+ _main.default.NumberDict.prototype._keyTest = function(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);
+ * }
+ *
+ */
+
+ _main.default.NumberDict.prototype.minKey = function() {
+ 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);
+ * }
+ *
+ */
+
+ _main.default.NumberDict.prototype.maxKey = function() {
+ return this._keyTest(-1);
+ };
+ var _default = _main.default.TypedDict;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 70: [
+ 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 };
+ }
+ 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);
+ }
+
+ /**
+ * Searches the page for the first element that matches the given CSS selector string (can be an
+ * ID, class, tag name or a combination) and returns it as a p5.Element.
+ * The DOM node itself can be accessed with .elt.
+ * Returns null if none found. You can also specify a container to search within.
+ *
+ * @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
+ * HTML element to search within
+ * @return {p5.Element|null} p5.Element containing node found
+ * @example
+ *
+ * function setup() {
+ * createCanvas(50, 50);
+ * background(30);
+ * // move canvas down and right
+ * select('canvas').position(10, 30);
+ * }
+ *
+ *
+ *
+ * // select using ID
+ * let a = select('#container');
+ * let b = select('#beep', '#container');
+ * let c;
+ * if (a) {
+ * // select using class
+ * c = select('.boop', a);
+ * }
+ * // select using CSS selector string
+ * let d = select('#container #bleep');
+ * let e = select('#container p');
+ * [a, b, c, d, e]; // unused
+ *
+ */
+ _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 elements that match the given CSS selector string (can be an ID a class,
+ * tag name or a combination) and returns them as p5.Elements in
+ * an array.
+ * The DOM node itself can be accessed with .elt.
+ * Returns an empty array if none found.
+ * You can also specify a container to search within.
+ *
+ * @method selectAll
+ * @param {String} selectors CSS selector string of elements to search for
+ * @param {String|p5.Element|HTMLElement} [container] CSS selector string, p5.Element
+ * , or HTML element to search within
+ * @return {p5.Element[]} Array of p5.Elements containing nodes found
+ * @example
+ *
+ * function setup() {
+ * createButton('btn');
+ * createButton('2nd btn');
+ * createButton('3rd btn');
+ * let buttons = selectAll('button');
+ *
+ * for (let i = 0; i < buttons.length; i++) {
+ * buttons[i].size(100, 100);
+ * }
+ * }
+ *
+ *
+ * // these are all valid calls to selectAll()
+ * let a = selectAll('.beep');
+ * a = selectAll('div');
+ * a = selectAll('button', '#container');
+ *
+ * let b = createDiv();
+ * b.id('container');
+ * let c = select('#container');
+ * a = selectAll('p', c);
+ * a = selectAll('#container p');
+ *
+ * let d = document.getElementById('container');
+ * a = selectAll('.boop', d);
+ * a = selectAll('#container .boop');
+ * console.log(a);
+ *
+ */
+ _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[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, except any canvas / graphics
+ * elements created by createCanvas or createGraphics.
+ * Event handlers are removed, and element is removed from the DOM.
+ * @method removeElements
+ * @example
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * createDiv('this is some text');
+ * createP('this is a paragraph');
+ * }
+ * function mousePressed() {
+ * removeElements(); // this will remove the div and p, not canvas
+ * }
+ *
+ */
+ _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();
+ });
+ };
+
+ /**
+ * The .changed() function is called when the value of an
+ * element changes.
+ * This can be used to attach an element specific event listener.
+ *
+ * @method changed
+ * @param {Function|Boolean} fxn function to be fired when the value of
+ * an element changes.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * dropdown: pear, kiwi, grape. When selected text "its a" + selection shown.
+ */
+ _main.default.Element.prototype.changed = function(fxn) {
+ _main.default.Element._adjustListener('change', fxn, this);
+ return this;
+ };
+
+ /**
+ * The .input() function is called when any user input is
+ * detected with an element. The input event is often used
+ * to detect keystrokes in a input element, or changes on a
+ * slider element. This can be used to attach an element specific
+ * event listener.
+ *
+ * @method input
+ * @param {Function|Boolean} fxn function to be fired when any user input is
+ * detected within the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * // Open your console to see the output
+ * function setup() {
+ * let inp = createInput('');
+ * inp.input(myInputEvent);
+ * }
+ *
+ * function myInputEvent() {
+ * console.log('you are typing: ', this.value());
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+ _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 in the DOM with given inner HTML.
+ *
+ * @method createDiv
+ * @param {String} [html] inner HTML for element created
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * createDiv('this is some text');
+ *
+ */
+ _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 in the DOM with given inner HTML. Used
+ * for paragraph length text.
+ *
+ * @method createP
+ * @param {String} [html] inner HTML for element created
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * createP('this is some text');
+ *
+ */
+ _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 in the DOM with given inner HTML.
+ *
+ * @method createSpan
+ * @param {String} [html] inner HTML for element created
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * createSpan('this is some text');
+ *
+ */
+ _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 in the DOM with given src and
+ * alternate text.
+ *
+ * @method createImg
+ * @param {String} src src path or url for image
+ * @param {String} alt alternate text to be used if image does not load. You can use also an empty string (`""`) if that an image is not intended to be viewed.
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ */
+ /**
+ * @method createImg
+ * @param {String} src
+ * @param {String} alt
+ * @param {String} crossOrigin crossOrigin property of the `img` element; use either 'anonymous' or 'use-credentials' to retrieve the image with cross-origin access (for later use with `canvas`. if an empty string(`""`) is passed, CORS is not used
+ * @param {Function} [successCallback] callback to be called once image data is loaded with the p5.Element as argument
+ * @return {p5.Element} pointer to p5.Element holding created node
+ */
+ _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 in the DOM for including a hyperlink.
+ *
+ * @method createA
+ * @param {String} href url of page to link to
+ * @param {String} html inner html of link element to display
+ * @param {String} [target] target where new link should open,
+ * could be _blank, _self, _parent, _top.
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * createA('http://p5js.org/', 'this is a link');
+ *
+ */
+ _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 in the DOM.
+ * Use .size() to set the display length of the slider.
+ *
+ * @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] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value)
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * let slider;
+ * function setup() {
+ * slider = createSlider(0, 255, 100);
+ * slider.position(10, 10);
+ * slider.style('width', '80px');
+ * }
+ *
+ * function draw() {
+ * let val = slider.value();
+ * background(val);
+ * }
+ *
+ */
+ _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 in the DOM.
+ * Calling .checked() on a checkbox returns if it is checked or not
+ *
+ * @method createCheckbox
+ * @param {String} [label] label displayed after checkbox
+ * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ */
+ _main.default.prototype.createCheckbox = function() {
+ _main.default._validateParameters('createCheckbox', arguments);
+ var elt = document.createElement('div');
+ var checkbox = document.createElement('input');
+ checkbox.type = 'checkbox';
+ elt.appendChild(checkbox);
+ //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.getElementsByTagName('input')[0];
+ if (cb) {
+ if (arguments.length === 0) {
+ return cb.checked;
+ } else if (arguments[0]) {
+ cb.checked = true;
+ } else {
+ cb.checked = false;
+ }
+ }
+ return self;
+ };
+ this.value = function(val) {
+ self.value = val;
+ return this;
+ };
+ if (arguments[0]) {
+ var ran = Math.random()
+ .toString(36)
+ .slice(2);
+ var label = document.createElement('label');
+ checkbox.setAttribute('id', ran);
+ label.htmlFor = ran;
+ self.value(arguments[0]);
+ label.appendChild(document.createTextNode(arguments[0]));
+ elt.appendChild(label);
+ }
+ if (arguments[1]) {
+ checkbox.checked = true;
+ }
+ return self;
+ };
+
+ /**
+ * Creates a dropdown menu <select></select> element in the DOM.
+ * It also helps to assign select-box methods to p5.Element when selecting existing select box.
+ * - `.option(name, [value])` can be used to set options for the select after it is created.
+ * - `.value()` will return the currently selected option.
+ * - `.selected()` will return current dropdown element which is an instance of p5.Element
+ * - `.selected(value)` can be used to make given option selected by default when the page first loads.
+ * - `.disable()` marks whole of dropdown element as disabled.
+ * - `.disable(value)` marks given option as disabled
+ *
+ * @method createSelect
+ * @param {boolean} [multiple] true if dropdown should support multiple selections
+ * @return {p5.Element}
+ * @example
+ *
+ */
+ /**
+ * @method createSelect
+ * @param {Object} existing DOM select element
+ * @return {p5.Element}
+ */
+
+ _main.default.prototype.createSelect = function() {
+ _main.default._validateParameters('createSelect', arguments);
+ var self;
+ var arg = arguments[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].innerHTML === 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.innerHTML = 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;
+ };
+
+ return self;
+ };
+
+ /**
+ * Creates a radio button element in the DOM.It also helps existing radio buttons
+ * assign methods of p5.Element.
+ * - `.option(value, [label])` can be used to create a new option for the
+ * element. If an option with a value already exists, it will be returned.
+ * Optionally, a label can be provided as second argument for the option.
+ * - `.remove(value)` can be used to remove an option for the element.
+ * - `.value()` method will return the currently selected value.
+ * - `.selected()` method will return the currently selected input element.
+ * - `.selected(value)` method will select the option and return it.
+ * - `.disable(Boolean)` method will enable/disable the whole radio button element.
+ *
+ * @method createRadio
+ * @param {Object} containerElement An container HTML Element either a div
+ * or span inside which all existing radio inputs will be considered as options.
+ * @param {string} [name] A name parameter for each Input Element.
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * let inp1, inp2;
+ * function setup() {
+ * createCanvas(100, 100);
+ * background('grey');
+ * inp1 = createColorPicker('#ff0000');
+ * inp1.position(0, height + 5);
+ * inp1.input(setShade1);
+ * inp2 = createColorPicker(color('yellow'));
+ * inp2.position(0, height + 30);
+ * inp2.input(setShade2);
+ * setMidShade();
+ * }
+ *
+ * function setMidShade() {
+ * // Finding a shade between the two
+ * let commonShade = lerpColor(inp1.color(), inp2.color(), 0.5);
+ * fill(commonShade);
+ * rect(20, 20, 60, 60);
+ * }
+ *
+ * function setShade1() {
+ * setMidShade();
+ * console.log('You are choosing shade 1 to be : ', this.value());
+ * }
+ * function setShade2() {
+ * setMidShade();
+ * console.log('You are choosing shade 2 to be : ', this.value());
+ * }
+ *
+ */
+ _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 an <input></input> element in the DOM for text input.
+ * Use .size() to set the display length of the box.
+ *
+ * @method createInput
+ * @param {String} value default value of the input box
+ * @param {String} [type] type of text, ie text, password etc. Defaults to text.
+ * Needs a value to be specified first.
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * function setup() {
+ * let inp = createInput('');
+ * inp.input(myInputEvent);
+ * }
+ *
+ * function myInputEvent() {
+ * console.log('you are typing: ', this.value());
+ * }
+ *
+ */
+ /**
+ * @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 in the DOM of type 'file'.
+ * This allows users to select local files for use in a sketch.
+ *
+ * @method createFileInput
+ * @param {Function} callback callback function for when a file is loaded
+ * @param {Boolean} [multiple] optional, to allow multiple files to be selected
+ * @return {p5.Element} pointer to p5.Element holding created DOM element
+ * @example
+ *
+ */
+ _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 an HTML5 <video> element in the DOM for simple playback
+ * of audio/video. Shown by default, can be hidden with .hide()
+ * and drawn into canvas using image(). The first parameter
+ * can be either a single string path to a video file, or an array of string
+ * paths to different formats of the same video. This is useful for ensuring
+ * that your video can play across different browsers, as each supports
+ * different formats. See this
+ * page for further information about supported formats.
+ *
+ * @method createVideo
+ * @param {String|String[]} src path to a video file, or array of paths for
+ * supporting different browsers
+ * @param {Function} [callback] callback function to be called upon
+ * 'canplaythrough' event fire, that is, when the
+ * browser can play the media, and estimates that
+ * enough data has been loaded to play the media
+ * up to its end without having to stop for
+ * further buffering of content
+ * @return {p5.MediaElement} pointer to video p5.Element
+ * @example
+ *
+ * let vid;
+ * function setup() {
+ * noCanvas();
+ *
+ * vid = createVideo(
+ * ['assets/small.mp4', 'assets/small.ogv', 'assets/small.webm'],
+ * vidLoad
+ * );
+ *
+ * vid.size(100, 100);
+ * }
+ *
+ * // This function is called when the video loads
+ * function vidLoad() {
+ * vid.loop();
+ * vid.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 HTML5 <audio> element in the DOM for simple audio
+ * playback. The first parameter can be either a single string path to a
+ * audio file, or an array of string paths to different formats of the same
+ * audio. This is useful for ensuring that your audio can play across
+ * different browsers, as each supports different formats.
+ * See this
+ * page for further information about supported formats.
+ *
+ * @method createAudio
+ * @param {String|String[]} [src] path to an audio file, or array of paths
+ * for supporting different browsers
+ * @param {Function} [callback] callback function to be called upon
+ * 'canplaythrough' event fire, that is, when the
+ * browser can play the media, and estimates that
+ * enough data has been loaded to play the media
+ * up to its end without having to stop for
+ * further buffering of content
+ * @return {p5.MediaElement} pointer to audio p5.Element
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * // here we set the element to autoplay
+ * // The element will play as soon
+ * // as it is able to do so.
+ * ele.autoplay(true);
+ * }
+ *
+ */
+ _main.default.prototype.createAudio = function(src, callback) {
+ _main.default._validateParameters('createAudio', arguments);
+ return createMedia(this, 'audio', src, callback);
+ };
+
+ /** CAMERA STUFF **/
+
+ /**
+ * @property {String} VIDEO
+ * @final
+ * @category Constants
+ */
+ _main.default.prototype.VIDEO = 'video';
+ /**
+ * @property {String} AUDIO
+ * @final
+ * @category Constants
+ */
+ _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 new HTML5 <video> element that contains the audio/video feed
+ * from a webcam. The element is separate from the canvas and is displayed by
+ * default. The element can be hidden using .hide().
+ * The feed can be drawn onto the canvas using image().
+ * The loadedmetadata property can be used to detect when the element has fully
+ * loaded (see second example).
+ *
+ * More specific properties of the feed can be passing in a Constraints object.
+ * See the
+ * W3C spec for possible properties. Note that not all of these are supported
+ * by all browsers.
+ *
+ * Security note: A new browser security specification requires that
+ * getUserMedia, which is behind createCapture(),
+ * only works when you're running the code locally, or on HTTPS. Learn more
+ * here
+ * and here.
+ *
+ * @method createCapture
+ * @param {String|Constant|Object} type type of capture, either VIDEO or
+ * AUDIO if none specified, default both,
+ * or a Constraints object
+ * @param {Function} [callback] function to be called once
+ * stream has loaded
+ * @return {p5.Element} capture video p5.Element
+ * @example
+ *
+ */
+ _main.default.prototype.createCapture = function() {
+ _main.default._validateParameters('createCapture', arguments);
+
+ // return if getUserMedia is not supported by 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 _iteratorNormalCompletion10 = true;
+ var _didIteratorError10 = false;
+ var _iteratorError10 = undefined;
+ try {
+ for (
+ var _iterator10 = arguments[Symbol.iterator](), _step10;
+ !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done);
+ _iteratorNormalCompletion10 = true
+ ) {
+ var arg = _step10.value;
+ if (arg === _main.default.prototype.VIDEO) useAudio = false;
+ else if (arg === _main.default.prototype.AUDIO) useVideo = false;
+ else if (_typeof(arg) === 'object') constraints = arg;
+ else if (typeof arg === 'function') callback = arg;
+ }
+ } catch (err) {
+ _didIteratorError10 = true;
+ _iteratorError10 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
+ _iterator10.return();
+ }
+ } finally {
+ if (_didIteratorError10) {
+ throw _iteratorError10;
+ }
+ }
+ }
+ if (!constraints) constraints = { video: useVideo, audio: useAudio };
+
+ 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;
+ }
+ }, console.log);
+
+ 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;
+ } else {
+ videoEl.width = videoEl.elt.width = domElement.videoWidth;
+ videoEl.height = videoEl.elt.height = domElement.videoHeight;
+ }
+ videoEl.loadedmetadata = true;
+
+ if (callback) callback(domElement.srcObject);
+ });
+ return videoEl;
+ };
+
+ /**
+ * Creates element with given tag in the DOM with given content.
+ *
+ * @method createElement
+ * @param {String} tag tag for the new element
+ * @param {String} [content] html content to be inserted into the element
+ * @return {p5.Element} pointer to p5.Element holding created node
+ * @example
+ *
+ * createElement('h2', 'im an h2 p5.element!');
+ *
+ */
+ _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 specified class to the element.
+ *
+ * @for p5.Element
+ * @method addClass
+ * @param {String} class name of class to add
+ * @chainable
+ * @example
+ *
+ * let div = createDiv('div');
+ * div.addClass('myClass');
+ *
+ */
+ _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 specified 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() {
+ * div = createDiv('div');
+ * div.addClass('myClass');
+ * }
+ *
+ * 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 specified class already set to element
+ *
+ * @method hasClass
+ * @returns {boolean} a boolean value if element has specified class
+ * @param c {String} class name of class to check
+ * @example
+ *
+ */
+ _main.default.Element.prototype.hasClass = function(c) {
+ return this.elt.classList.contains(c);
+ };
+
+ /**
+ *
+ * Toggles element class
+ *
+ * @method toggleClass
+ * @param c {String} class name to toggle
+ * @chainable
+ * @example
+ *
+ * let div;
+ *
+ * function setup() {
+ * div = createDiv('div');
+ * div.addClass('show');
+ * }
+ *
+ * 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 to the parent specified.
+ * Accepts either a string ID, DOM node, or p5.Element.
+ * If no argument is specified, an array of children DOM nodes is returned.
+ *
+ * @method child
+ * @returns {Node[]} an array of child nodes
+ * @example
+ *
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
+ * div0.child(div1); // use p5.Element
+ *
+ *
+ * let div0 = createDiv('this is the parent');
+ * let div1 = createDiv('this is the child');
+ * div1.id('apples');
+ * div0.child('apples'); // use id
+ *
+ *
+ * // this example assumes there is a div already on the page
+ * // with id "myChildDiv"
+ * let div0 = createDiv('this is the parent');
+ * let elt = document.getElementById('myChildDiv');
+ * div0.child(elt); // use element from page
+ *
+ */
+ /**
+ * @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 a p5 Element either vertically, horizontally,
+ * or both, relative to its parent or according to
+ * the body if the Element has no parent. If no argument is passed
+ * the Element is aligned both vertically and horizontally.
+ *
+ * @method center
+ * @param {String} [align] passing 'vertical', 'horizontal' aligns element accordingly
+ * @chainable
+ *
+ * @example
+ *
+ * function setup() {
+ * let div = createDiv('').size(10, 10);
+ * div.style('background-color', 'orange');
+ * div.center();
+ * }
+ *
+ */
+ _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;
+ };
+
+ /**
+ *
+ * If an argument is given, sets the inner HTML of the element,
+ * replacing any existing html. If true is included as a second
+ * argument, html is appended instead of replacing existing html.
+ * If no arguments are given, returns
+ * the inner HTML of the element.
+ *
+ * @for p5.Element
+ * @method html
+ * @returns {String} the inner HTML of the element
+ * @example
+ *
+ * let div = createDiv('').size(100, 100);
+ * div.html('hi');
+ *
+ *
+ * let div = createDiv('Hello ').size(100, 100);
+ * div.html('World', true);
+ *
+ */
+ /**
+ * @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[1]) {
+ this.elt.insertAdjacentHTML('beforeend', arguments[0]);
+ return this;
+ } else {
+ this.elt.innerHTML = arguments[0];
+ return this;
+ }
+ };
+
+ /**
+ *
+ * Sets the position of the element. If no position type argument is given, the
+ * position will be relative to (0, 0) of the window.
+ * Essentially, this sets position:absolute and left and top
+ * properties of style. If an optional third argument specifying position type is given,
+ * the x and y coordinates will be interpreted based on the positioning scheme.
+ * If no arguments given, the function returns the x and y position of the element.
+ *
+ * found documentation on how to be more specific with object type
+ * https://stackoverflow.com/questions/14714314/how-do-i-comment-object-literals-in-yuidoc
+ *
+ * @method position
+ * @returns {Object} object of form { x: 0, y: 0 } containing the position of the element in an object
+ * @example
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // positions canvas 50px to the right and 100px
+ * // below upper left corner of the window
+ * cnv.position(50, 100);
+ * }
+ *
+ *
+ * function setup() {
+ * let cnv = createCanvas(100, 100);
+ * // positions canvas 50px to the right and 100px
+ * // below upper left corner of the window
+ * cnv.position(0, 0, 'fixed');
+ * }
+ *
+ */
+ /**
+ * @method position
+ * @param {Number} [x] x-position relative to upper left of window (optional)
+ * @param {Number} [y] y-position relative to upper 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[2] === 'static' ||
+ arguments[2] === 'fixed' ||
+ arguments[2] === 'relative' ||
+ arguments[2] === 'sticky' ||
+ arguments[2] === 'initial' ||
+ arguments[2] === 'inherit'
+ ) {
+ positionType = arguments[2];
+ }
+ this.elt.style.position = positionType;
+ this.elt.style.left = arguments[0] + 'px';
+ this.elt.style.top = arguments[1] + 'px';
+ this.x = arguments[0];
+ this.y = 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[0] + 'px, ' + arguments[1] + 'px)';
+ } else if (arguments.length > 2) {
+ this.elt.style.transform =
+ 'translate3d(' +
+ arguments[0] +
+ 'px,' +
+ arguments[1] +
+ 'px,' +
+ arguments[2] +
+ 'px)';
+ if (arguments.length === 3) {
+ this.elt.parentElement.style.perspective = '1000px';
+ } else {
+ this.elt.parentElement.style.perspective = 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[0] + 'deg)';
+ } else if (arguments.length === 2) {
+ this.elt.style.transform =
+ 'rotate(' + arguments[0] + 'deg, ' + arguments[1] + 'deg)';
+ } else if (arguments.length === 3) {
+ this.elt.style.transform = 'rotateX(' + arguments[0] + 'deg)';
+ this.elt.style.transform += 'rotateY(' + arguments[1] + 'deg)';
+ this.elt.style.transform += 'rotateZ(' + arguments[2] + 'deg)';
+ }
+ // add remaining transform back on
+ this.elt.style.transform += transform;
+ return this;
+ };
+
+ /**
+ * Sets the given style (css) property (1st arg) of the element with the
+ * given value (2nd arg). If a single argument is given, .style()
+ * returns the value of the given property; however, if the single argument
+ * is given in css syntax ('text-align:center'), .style() sets the css
+ * appropriately.
+ *
+ * @method style
+ * @param {String} property property to be set
+ * @returns {String} value of property
+ * @example
+ *
+ * let myDiv = createDiv('I like pandas.');
+ * myDiv.style('font-size', '18px');
+ * myDiv.style('color', '#ff0000');
+ *
+ *
+ * let col = color(25, 23, 200, 50);
+ * let button = createButton('button');
+ * button.style('background-color', col);
+ * button.position(10, 10);
+ *
+ */
+ /**
+ * @method style
+ * @param {String} property
+ * @param {String|p5.Color} value value to assign to property
+ * @return {String} current value of property, if no value is given as second argument
+ * @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] = parseInt(numVal, 10);
+ }
+ }
+ return this;
+ };
+
+ /**
+ *
+ * Adds a new attribute or changes the value of an existing attribute
+ * on the specified element. If no value is specified, returns the
+ * value of the given attribute, or null if attribute is not set.
+ *
+ * @method attribute
+ * @return {String} value of attribute
+ *
+ * @example
+ *
+ * let myDiv = createDiv('I like pandas.');
+ * myDiv.attribute('align', 'center');
+ *
+ */
+ /**
+ * @method attribute
+ * @param {String} attr attribute to set
+ * @param {String} value value to assign to 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 on the specified element.
+ *
+ * @method removeAttribute
+ * @param {String} attr attribute to remove
+ * @chainable
+ *
+ * @example
+ *
+ */
+ _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;
+ };
+
+ /**
+ * Either returns the value of the element if no arguments
+ * given, or sets the value of the element.
+ *
+ * @method value
+ * @return {String|Number} value of the element
+ * @example
+ *
+ * // gets the value
+ * let inp;
+ * function setup() {
+ * inp = createInput('');
+ * }
+ *
+ * function mousePressed() {
+ * print(inp.value());
+ * }
+ *
+ *
+ * // sets the value
+ * let inp;
+ * function setup() {
+ * inp = createInput('myValue');
+ * }
+ *
+ * function mousePressed() {
+ * inp.value('myValue');
+ * }
+ *
+ */
+ /**
+ * @method value
+ * @param {String|Number} value
+ * @chainable
+ */
+ _main.default.Element.prototype.value = function() {
+ if (arguments.length > 0) {
+ this.elt.value = arguments[0];
+ return this;
+ } else {
+ if (this.elt.type === 'range') {
+ return parseFloat(this.elt.value);
+ } else return this.elt.value;
+ }
+ };
+
+ /**
+ *
+ * Shows the current element. Essentially, setting display:block for the style.
+ *
+ * @method show
+ * @chainable
+ * @example
+ *
+ * let div = createDiv('div');
+ * div.style('display', 'none');
+ * div.show(); // turns display to block
+ *
+ * let div = createDiv('this is a div');
+ * div.hide();
+ *
+ */
+ _main.default.Element.prototype.hide = function() {
+ this.elt.style.display = 'none';
+ return this;
+ };
+
+ /**
+ *
+ * Sets the width and height of the element. AUTO can be used to
+ * only adjust one dimension at a time. If no arguments are given, it
+ * returns the width and height of the element in an object. In case of
+ * elements which need to be loaded, such as images, it is recommended
+ * to call the function after the element has finished loading.
+ *
+ * @method size
+ * @return {Object} the width and height of the element in an object
+ * @example
+ *
+ * let div = createDiv('this is a div');
+ * div.size(100, 100);
+ * let img = createImg(
+ * 'assets/rockies.jpg',
+ * 'A tall mountain with a small forest and field in front of it on a sunny day',
+ * '',
+ * () => {
+ * img.size(10, 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 = this.elt.offsetWidth;
+ this.height = this.elt.offsetHeight;
+
+ if (this._pInst && this._pInst._curElement) {
+ // main canvas associated with p5 instance
+ if (this._pInst._curElement.elt === this.elt) {
+ this._pInst._setProperty('width', this.elt.offsetWidth);
+ this._pInst._setProperty('height', this.elt.offsetHeight);
+ }
+ }
+ }
+ return this;
+ }
+ };
+
+ /**
+ * Removes the element, stops all media streams, and deregisters all listeners.
+ * @method remove
+ * @example
+ *
+ * let myDiv = createDiv('this is some text');
+ * myDiv.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) {
+ var tracks = this.elt.srcObject.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);
+ }
+ };
+
+ /**
+ * Registers a callback that gets called every time a file that is
+ * dropped on the element has been loaded.
+ * p5 will load every dropped file into memory and pass it as a p5.File object to the callback.
+ * Multiple files dropped at the same time will result in multiple calls to the callback.
+ *
+ * You can optionally pass a second callback which will be registered to the raw
+ * drop event.
+ * The callback will thus be provided the original
+ * DragEvent.
+ * Dropping multiple files at the same time will trigger the second callback once per drop,
+ * whereas the first callback will trigger for each loaded file.
+ *
+ * @method drop
+ * @param {Function} callback callback to receive loaded file, called for each file dropped.
+ * @param {Function} [fxn] callback triggered once when files are dropped with the drop event.
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Canvas turns into whatever image is dragged/dropped onto it.
+ */
+ _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
+ for (var i = 0; i < files.length; i++) {
+ var f = files[i];
+ _main.default.File._load(f, callback);
+ }
+ },
+ this
+ );
+ } else {
+ console.log('The File APIs are not fully supported in this browser.');
+ }
+
+ return this;
+ };
+
+ // =============================================================================
+ // p5.MediaElement additions
+ // =============================================================================
+
+ /**
+ * Extends p5.Element to handle audio and video. In addition to the methods
+ * of p5.Element, it also contains methods for controlling media. It is not
+ * called directly, but p5.MediaElements are created by calling createVideo,
+ * createAudio, and createCapture.
+ *
+ * @class p5.MediaElement
+ * @constructor
+ * @param {String} elt DOM node that is wrapped
+ */
+ _main.default.MediaElement = function(elt, pInst) {
+ _main.default.Element.call(this, elt, pInst);
+
+ var self = this;
+ this.elt.crossOrigin = 'anonymous';
+
+ this._prevTime = 0;
+ this._cueIDCounter = 0;
+ this._cues = [];
+ this._pixelsState = this;
+ this._pixelDensity = 1;
+ this._modified = false;
+
+ /**
+ * Path to the media element source.
+ *
+ * @property src
+ * @return {String} src
+ * @example
+ *
+ * let ele;
+ *
+ * function setup() {
+ * background(250);
+ *
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * //We'll set up our example so that
+ * //when you click on the text,
+ * //an alert box displays the MediaElement's
+ * //src field.
+ * textAlign(CENTER);
+ * text('Click Me!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * //Show our p5.MediaElement's src field
+ * alert(ele.src);
+ * }
+ * }
+ *
+ */
+ 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);
+ };
+ };
+ _main.default.MediaElement.prototype = Object.create(
+ _main.default.Element.prototype
+ );
+
+ /**
+ * Play an HTML5 media element.
+ *
+ * @method play
+ * @chainable
+ * @example
+ *
+ * let ele;
+ *
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/beat.mp3');
+ *
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to Play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * //Here we call the play() function on
+ * //the p5.MediaElement we created above.
+ * //This will start the audio sample.
+ * ele.play();
+ *
+ * background(200);
+ * text('You clicked Play!', width / 2, height / 2);
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.play = function() {
+ 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') {
+ _main.default._friendlyAutoplayError(this.src);
+ } else {
+ // any other kind of error
+ console.error('Media play method encountered an unexpected error', e);
+ }
+ });
+ }
+ return this;
+ };
+
+ /**
+ * Stops an HTML5 media element (sets current time to zero).
+ *
+ * @method stop
+ * @chainable
+ * @example
+ *
+ * //This example both starts
+ * //and stops a sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * //if the sample is currently playing
+ * //calling the stop() function on
+ * //our p5.MediaElement will stop
+ * //it and reset its current
+ * //time to 0 (i.e. it will start
+ * //at the beginning the next time
+ * //you play it)
+ * ele.stop();
+ *
+ * sampleIsPlaying = false;
+ * text('Click to play!', width / 2, height / 2);
+ * } else {
+ * //loop our sound element until we
+ * //call ele.stop() on it.
+ * ele.loop();
+ *
+ * sampleIsPlaying = true;
+ * text('Click to stop!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ * //This example both starts
+ * //and pauses a sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * //Calling pause() on our
+ * //p5.MediaElement will stop it
+ * //playing, but when we call the
+ * //loop() or play() functions
+ * //the sample will start from
+ * //where we paused it.
+ * ele.pause();
+ *
+ * sampleIsPlaying = false;
+ * text('Click to resume!', width / 2, height / 2);
+ * } else {
+ * //loop our sound element until we
+ * //call ele.pause() on it.
+ * ele.loop();
+ *
+ * sampleIsPlaying = true;
+ * text('Click to pause!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.pause = function() {
+ this.elt.pause();
+ return this;
+ };
+
+ /**
+ * Set 'loop' to true for an HTML5 media element, and starts playing.
+ *
+ * @method loop
+ * @chainable
+ * @example
+ *
+ * //Clicking the canvas will loop
+ * //the audio sample until the user
+ * //clicks again to stop it
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ *
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsLooping = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to loop!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (!sampleIsLooping) {
+ * //loop our sound element until we
+ * //call ele.stop() on it.
+ * ele.loop();
+ *
+ * sampleIsLooping = true;
+ * text('Click to stop!', width / 2, height / 2);
+ * } else {
+ * ele.stop();
+ *
+ * sampleIsLooping = false;
+ * text('Click to loop!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.loop = function() {
+ this.elt.setAttribute('loop', true);
+ this.play();
+ return this;
+ };
+ /**
+ * Set 'loop' to false for an HTML5 media element. Element will stop
+ * when it reaches the end.
+ *
+ * @method noLoop
+ * @chainable
+ * @example
+ *
+ * //This example both starts
+ * //and stops loop of sound sample
+ * //when the user clicks the canvas
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ * //while our audio is playing,
+ * //this will be set to true
+ * let sampleIsPlaying = false;
+ *
+ * function setup() {
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to play!', width / 2, height / 2);
+ * }
+ *
+ * function mouseClicked() {
+ * //here we test if the mouse is over the
+ * //canvas element when it's clicked
+ * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
+ * background(200);
+ *
+ * if (sampleIsPlaying) {
+ * ele.noLoop();
+ * sampleIsPlaying = false;
+ * text('No more Loops!', width / 2, height / 2);
+ * } else {
+ * ele.loop();
+ * sampleIsPlaying = true;
+ * text('Click to stop looping!', width / 2, height / 2);
+ * }
+ * }
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.noLoop = function() {
+ this.elt.removeAttribute('loop');
+ return this;
+ };
+
+ /**
+ * Sets up logic to check that autoplay succeeded.
+ *
+ * @method setupAutoplayFailDetection
+ * @private
+ */
+ _main.default.MediaElement.prototype._setupAutoplayFailDetection = function() {
+ var _this = this;
+ var timeout = setTimeout(function() {
+ return _main.default._friendlyAutoplayError(_this.src);
+ }, 500);
+ this.elt.addEventListener(
+ 'play',
+ function() {
+ return clearTimeout(timeout);
+ },
+ {
+ passive: true,
+ once: true
+ }
+ );
+ };
+
+ /**
+ * Set HTML5 media element to autoplay or not. If no argument is specified, by
+ * default it will autoplay.
+ *
+ * @method autoplay
+ * @param {Boolean} shouldAutoplay whether the element should autoplay
+ * @chainable
+ * @example
+ *
+ * let videoElement;
+ * function setup() {
+ * noCanvas();
+ * videoElement = createVideo(['assets/small.mp4'], onVideoLoad);
+ * }
+ * function onVideoLoad() {
+ * // The media will play as soon as it is loaded.
+ * videoElement.autoplay();
+ * videoElement.volume(0);
+ * videoElement.size(100, 100);
+ * }
+ *
+ *
+ *
+ * let videoElement;
+ * function setup() {
+ * noCanvas();
+ * videoElement = createVideo(['assets/small.mp4'], onVideoLoad);
+ * }
+ * function onVideoLoad() {
+ * // The media will not play untill some explicitly triggered.
+ * videoElement.autoplay(false);
+ * videoElement.volume(0);
+ * videoElement.size(100, 100);
+ * }
+ *
+ * function mouseClicked() {
+ * videoElement.play();
+ * }
+ *
+ *
+ * @alt
+ * An example of a video element which autoplays after it is loaded.
+ * An example of a video element which waits for a trigger for playing.
+ */
+
+ _main.default.MediaElement.prototype.autoplay = function(val) {
+ var _this2 = 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 _this2._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 volume for this HTML5 media element. If no argument is given,
+ * returns the current volume.
+ *
+ * @method volume
+ * @return {Number} current volume
+ *
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * // p5.MediaElement objects are usually created
+ * // by calling the createAudio(), createVideo(),
+ * // and createCapture() functions.
+ * // In this example we create
+ * // a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to Play!', width / 2, height / 2);
+ * }
+ * function mouseClicked() {
+ * // Here we call the volume() function
+ * // on the sound element to set its volume
+ * // Volume must be between 0.0 and 1.0
+ * ele.volume(0.2);
+ * ele.play();
+ * background(200);
+ * text('You clicked Play!', width / 2, height / 2);
+ * }
+ *
+ */
+ /**
+ * @method volume
+ * @param {Number} val volume between 0.0 and 1.0
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.volume = function(val) {
+ if (typeof val === 'undefined') {
+ return this.elt.volume;
+ } else {
+ this.elt.volume = val;
+ }
+ };
+
+ /**
+ * If no arguments are given, returns the current playback speed of the
+ * element. The speed parameter sets the speed where 2.0 will play the
+ * element twice as fast, 0.5 will play at half the speed, and -1 will play
+ * the element in normal speed in reverse.(Note that not all browsers support
+ * backward playback and even if they do, playback might not be smooth.)
+ *
+ * @method speed
+ * @return {Number} current playback speed of the element
+ *
+ * @example
+ *
+ * //Clicking the canvas will loop
+ * //the audio sample until the user
+ * //clicks again to stop it
+ *
+ * //We will store the p5.MediaElement
+ * //object in here
+ * let ele;
+ * let button;
+ *
+ * function setup() {
+ * createCanvas(710, 400);
+ * //Here we create a p5.MediaElement object
+ * //using the createAudio() function.
+ * ele = createAudio('assets/beat.mp3');
+ * ele.loop();
+ * background(200);
+ *
+ * button = createButton('2x speed');
+ * button.position(100, 68);
+ * button.mousePressed(twice_speed);
+ *
+ * button = createButton('half speed');
+ * button.position(200, 68);
+ * button.mousePressed(half_speed);
+ *
+ * button = createButton('reverse play');
+ * button.position(300, 68);
+ * button.mousePressed(reverse_speed);
+ *
+ * button = createButton('STOP');
+ * button.position(400, 68);
+ * button.mousePressed(stop_song);
+ *
+ * button = createButton('PLAY!');
+ * button.position(500, 68);
+ * button.mousePressed(play_speed);
+ * }
+ *
+ * function twice_speed() {
+ * ele.speed(2);
+ * }
+ *
+ * function half_speed() {
+ * ele.speed(0.5);
+ * }
+ *
+ * function reverse_speed() {
+ * ele.speed(-1);
+ * }
+ *
+ * function stop_song() {
+ * ele.stop();
+ * }
+ *
+ * function play_speed() {
+ * ele.play();
+ * }
+ *
+ */
+
+ /**
+ * @method speed
+ * @param {Number} speed speed multiplier for element playback
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.speed = function(val) {
+ if (typeof val === 'undefined') {
+ return this.presetPlaybackRate || this.elt.playbackRate;
+ } else {
+ if (this.loadedmetadata) {
+ this.elt.playbackRate = val;
+ } else {
+ this.presetPlaybackRate = val;
+ }
+ }
+ };
+
+ /**
+ * If no arguments are given, returns the current time of the element.
+ * If an argument is given the current time of the element is set to it.
+ *
+ * @method time
+ * @return {Number} current time (in seconds)
+ *
+ * @example
+ *
+ * let ele;
+ * let beginning = true;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ *
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('start at beginning', width / 2, height / 2);
+ * }
+ *
+ * // this function fires with click anywhere
+ * function mousePressed() {
+ * if (beginning === true) {
+ * // here we start the sound at the beginning
+ * // time(0) is not necessary here
+ * // as this produces the same result as
+ * // play()
+ * ele.play().time(0);
+ * background(200);
+ * text('jump 2 sec in', width / 2, height / 2);
+ * beginning = false;
+ * } else {
+ * // here we jump 2 seconds into the sound
+ * ele.play().time(2);
+ * background(250);
+ * text('start at beginning', width / 2, height / 2);
+ * beginning = true;
+ * }
+ * }
+ *
+ */
+ /**
+ * @method time
+ * @param {Number} time time to jump to (in seconds)
+ * @chainable
+ */
+ _main.default.MediaElement.prototype.time = function(val) {
+ if (typeof val === 'undefined') {
+ return this.elt.currentTime;
+ } else {
+ this.elt.currentTime = val;
+ return this;
+ }
+ };
+
+ /**
+ * Returns the duration of the HTML5 media element.
+ *
+ * @method duration
+ * @return {Number} duration
+ *
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio().
+ * ele = createAudio('assets/doorbell.mp3');
+ * background(250);
+ * textAlign(CENTER);
+ * text('Click to know the duration!', 10, 25, 70, 80);
+ * }
+ * function mouseClicked() {
+ * ele.play();
+ * background(200);
+ * //ele.duration dislpays the duration
+ * text(ele.duration() + ' seconds', width / 2, height / 2);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.duration = function() {
+ return this.elt.duration;
+ };
+ _main.default.MediaElement.prototype.pixels = [];
+ _main.default.MediaElement.prototype._ensureCanvas = function() {
+ if (!this.canvas) {
+ this.canvas = document.createElement('canvas');
+ this.drawingContext = this.canvas.getContext('2d');
+ this.setModified(true);
+ }
+ if (this.loadedmetadata) {
+ // 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.drawImage(
+ this.elt,
+ 0,
+ 0,
+ this.canvas.width,
+ this.canvas.height
+ );
+
+ this.setModified(true);
+ }
+ };
+ _main.default.MediaElement.prototype.loadPixels = function() {
+ this._ensureCanvas();
+ return _main.default.Renderer2D.prototype.loadPixels.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype.updatePixels = function(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;
+ };
+ _main.default.MediaElement.prototype.get = function() {
+ this._ensureCanvas();
+ return _main.default.Renderer2D.prototype.get.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype._getPixel = function() {
+ this.loadPixels();
+ return _main.default.Renderer2D.prototype._getPixel.apply(this, arguments);
+ };
+
+ _main.default.MediaElement.prototype.set = function(x, y, imgOrCol) {
+ if (this.loadedmetadata) {
+ // wait for metadata
+ this._ensureCanvas();
+ _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol);
+ this.setModified(true);
+ }
+ };
+ _main.default.MediaElement.prototype.copy = function() {
+ this._ensureCanvas();
+ _main.default.prototype.copy.apply(this, arguments);
+ };
+ _main.default.MediaElement.prototype.mask = function() {
+ this.loadPixels();
+ this.setModified(true);
+ _main.default.Image.prototype.mask.apply(this, arguments);
+ };
+ /**
+ * 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.
+ */
+ _main.default.MediaElement.prototype.isModified = function() {
+ 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
+ */
+ _main.default.MediaElement.prototype.setModified = function(value) {
+ this._modified = value;
+ };
+ /**
+ * Schedule an event to be called when the audio or video
+ * element reaches the end. If the element is looping,
+ * this will not be called. The element is passed in
+ * as the argument to the onended callback.
+ *
+ * @method onended
+ * @param {Function} callback function to call when the
+ * soundfile has ended. The
+ * media element will be passed
+ * in as the argument to the
+ * callback.
+ * @chainable
+ * @example
+ *
+ * function setup() {
+ * let audioEl = createAudio('assets/beat.mp3');
+ * audioEl.showControls();
+ * audioEl.onended(sayDone);
+ * }
+ *
+ * function sayDone(elt) {
+ * alert('done playing ' + elt.src);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.onended = function(callback) {
+ this._onended = callback;
+ return this;
+ };
+
+ /*** CONNECT TO WEB AUDIO API / p5.sound.js ***/
+
+ /**
+ * Send the audio output of this element to a specified audioNode or
+ * p5.sound object. If no element is provided, connects to p5's main
+ * output. That connection is established when this method is first called.
+ * All connections are removed by the .disconnect() method.
+ *
+ * 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
+ */
+ _main.default.MediaElement.prototype.connect = function(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 main output.
+ * This is useful if you want to re-route the output through
+ * audio effects, for example.
+ *
+ * @method disconnect
+ */
+ _main.default.MediaElement.prototype.disconnect = function() {
+ if (this.audioSourceNode) {
+ this.audioSourceNode.disconnect();
+ } else {
+ throw 'nothing to disconnect';
+ }
+ };
+
+ /*** SHOW / HIDE CONTROLS ***/
+
+ /**
+ * Show the default MediaElement controls, as determined by the web browser.
+ *
+ * @method showControls
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio()
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to Show Controls!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * ele.showControls();
+ * background(200);
+ * text('Controls Shown', width / 2, height / 2);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.showControls = function() {
+ // must set style for the element to show on the page
+ this.elt.style['text-align'] = 'inherit';
+ this.elt.controls = true;
+ };
+
+ /**
+ * Hide the default mediaElement controls.
+ * @method hideControls
+ * @example
+ *
+ * let ele;
+ * function setup() {
+ * //p5.MediaElement objects are usually created
+ * //by calling the createAudio(), createVideo(),
+ * //and createCapture() functions.
+ * //In this example we create
+ * //a new p5.MediaElement via createAudio()
+ * ele = createAudio('assets/lucky_dragons.mp3');
+ * ele.showControls();
+ * background(200);
+ * textAlign(CENTER);
+ * text('Click to hide Controls!', 10, 25, 70, 80);
+ * }
+ * function mousePressed() {
+ * ele.hideControls();
+ * background(200);
+ * text('Controls hidden', width / 2, height / 2);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.hideControls = function() {
+ this.elt.controls = false;
+ };
+
+ /*** SCHEDULE EVENTS ***/
+
+ // Cue inspired by JavaScript setTimeout, and the
+ // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org
+ var Cue = function Cue(callback, time, id, val) {
+ this.callback = callback;
+ this.time = time;
+ this.id = id;
+ this.val = val;
+ };
+
+ /**
+ * Schedule events to trigger every time a MediaElement
+ * (audio/video) reaches a playback cue point.
+ *
+ * Accepts a callback function, a time (in seconds) at which to trigger
+ * the callback, and an optional parameter for the callback.
+ *
+ * Time will be passed as the first parameter to the callback function,
+ * and param will be the second parameter.
+ *
+ * @method addCue
+ * @param {Number} time Time in seconds, relative to this media
+ * element's playback. For example, to trigger
+ * an event every time playback reaches two
+ * seconds, pass in the number 2. This will be
+ * passed as the first parameter to
+ * the callback function.
+ * @param {Function} callback Name of a function that will be
+ * called at the given time. The callback will
+ * receive time and (optionally) param as its
+ * two parameters.
+ * @param {Object} [value] An object to be passed as the
+ * second parameter to the
+ * callback function.
+ * @return {Number} id ID of this cue,
+ * useful for removeCue(id)
+ * @example
+ *
+ */
+ _main.default.MediaElement.prototype.addCue = function(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;
+ };
+
+ /**
+ * Remove a callback based on its ID. The ID is returned by the
+ * addCue method.
+ * @method removeCue
+ * @param {Number} id ID of the cue, as returned by addCue
+ * @example
+ *
+ */
+ _main.default.MediaElement.prototype.removeCue = function(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;
+ }
+ };
+
+ /**
+ * Remove all of the callbacks that had originally been scheduled
+ * via the addCue method.
+ * @method clearCues
+ * @param {Number} id ID of the cue, as returned by addCue
+ * @example
+ *
+ * let audioEl;
+ * function setup() {
+ * background(255, 255, 255);
+ * audioEl = createAudio('assets/beat.mp3');
+ * //Show the default MediaElement controls, as determined by the web browser
+ * audioEl.showControls();
+ * // schedule calls to changeBackground
+ * background(200);
+ * text('Click to change Cue!', 10, 25, 70, 80);
+ * audioEl.addCue(0.5, changeBackground, color(255, 0, 0));
+ * audioEl.addCue(1.0, changeBackground, color(0, 255, 0));
+ * audioEl.addCue(2.5, changeBackground, color(0, 0, 255));
+ * audioEl.addCue(3.0, changeBackground, color(0, 255, 255));
+ * audioEl.addCue(4.2, changeBackground, color(255, 255, 0));
+ * }
+ * function mousePressed() {
+ * // here we clear the scheduled callbacks
+ * audioEl.clearCues();
+ * // then we add some more callbacks
+ * audioEl.addCue(1, changeBackground, color(2, 2, 2));
+ * audioEl.addCue(3, changeBackground, color(255, 255, 0));
+ * }
+ * function changeBackground(val) {
+ * background(val);
+ * }
+ *
+ */
+ _main.default.MediaElement.prototype.clearCues = function() {
+ this._cues = [];
+ this.elt.ontimeupdate = null;
+ };
+
+ // private method that checks for cues to be fired if events
+ // have been scheduled using addCue(callback, time).
+ _main.default.MediaElement.prototype._onTimeUpdate = function() {
+ 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;
+ };
+
+ /**
+ * Base class for a file.
+ * Used for Element.drop and createFileInput.
+ *
+ * @class p5.File
+ * @constructor
+ * @param {File} file File that is wrapped
+ */
+ _main.default.File = function(file, pInst) {
+ /**
+ * Underlying File object. All normal File methods can be called on this.
+ *
+ * @property file
+ */
+ 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('/');
+ /**
+ * File type (image, text, etc.)
+ *
+ * @property type
+ */
+ this.type = typeList[0];
+ /**
+ * File subtype (usually the file extension jpg, png, xml, etc.)
+ *
+ * @property subtype
+ */
+ this.subtype = typeList[1];
+ /**
+ * File name
+ *
+ * @property name
+ */
+ this.name = file.name;
+ /**
+ * File size
+ *
+ * @property size
+ */
+ this.size = file.size;
+
+ /**
+ * URL string containing either image data, the text contents of the file or
+ * a parsed object if file is JSON and p5.XML if XML
+ *
+ * @property data
+ */
+ this.data = undefined;
+ };
+
+ _main.default.File._createLoader = function(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;
+ };
+
+ _main.default.File._load = function(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);
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 71: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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 Acceleration
+ * @for p5
+ * @requires core
+ */ /**
+ * 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.0 ? '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
+ *
+ * @alt
+ * 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
+ *
+ * @alt
+ * 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
+ *
+ *
+ * @alt
+ * 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
+ *
+ * @alt
+ * 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
+ *
+ * @alt
+ * 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
+ *
+ *
+ * @property {Number} rotationZ
+ * @readOnly
+ *
+ * @alt
+ * red horizontal line right, green vertical line bottom. black background.
+ */
+ _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);
+ *
+ *
+ *
+ * @alt
+ * 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);
+ *
+ *
+ *
+ * @alt
+ * 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);
+ *
+ *
+ *
+ * @alt
+ * 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);
+ * }
+ * function deviceTurned() {
+ * if (turnAxis === 'X') {
+ * if (value === 0) {
+ * value = 255;
+ * } else if (value === 255) {
+ * value = 0;
+ * }
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device turns
+ * 50x50 black rect in center of canvas. turns white on mobile when x-axis turns
+ */
+ _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);
+ * }
+ * function deviceMoved() {
+ * value = value + 5;
+ * threshold = threshold + 0.1;
+ * if (value > 255) {
+ * value = 0;
+ * threshold = 30;
+ * }
+ * setMoveThreshold(threshold);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device moves
+ */
+
+ _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);
+ * }
+ * function deviceMoved() {
+ * value = value + 5;
+ * threshold = threshold + 5;
+ * if (value > 255) {
+ * value = 0;
+ * threshold = 30;
+ * }
+ * setShakeThreshold(threshold);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device
+ * is being shaked
+ */
+
+ _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);
+ * }
+ * function deviceMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device moves
+ */
+
+ /**
+ * 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);
+ * }
+ * 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);
+ * }
+ * function deviceTurned() {
+ * if (turnAxis === 'X') {
+ * if (value === 0) {
+ * value = 255;
+ * } else if (value === 255) {
+ * value = 0;
+ * }
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device turns
+ * 50x50 black rect in center of canvas. turns white on mobile when x-axis turns
+ */
+
+ /**
+ * 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);
+ * }
+ * function deviceShaken() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device shakes
+ */
+
+ _main.default.prototype._ondeviceorientation = function(e) {
+ this._updatePRotations();
+ if (this._angleMode === constants.radians) {
+ e.beta = e.beta * (_PI / 180.0);
+ e.gamma = e.gamma * (_PI / 180.0);
+ e.alpha = e.alpha * (_PI / 180.0);
+ }
+ this._setProperty('rotationX', e.beta);
+ this._setProperty('rotationY', e.gamma);
+ this._setProperty('rotationZ', 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 deviceMoved = this.deviceMoved || window.deviceMoved;
+ if (typeof 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
+ ) {
+ deviceMoved();
+ }
+ }
+ var deviceTurned = this.deviceTurned || window.deviceTurned;
+ if (typeof 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.
+ var wRX = this.rotationX + 180;
+ var wPRX = 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');
+ deviceTurned();
+ }
+ this.pRotateDirectionX = rotateDirectionX;
+ startAngleX = wSAX - 180;
+
+ // Y-axis is identical to X-axis except for changing some names.
+ var wRY = this.rotationY + 180;
+ var wPRY = 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');
+ deviceTurned();
+ }
+ this.pRotateDirectionY = rotateDirectionY;
+ startAngleY = wSAY - 180;
+
+ // Z-axis is already in the range 0 to 360
+ // so no conversion is needed.
+ if (
+ (this.rotationZ - this.pRotationZ > 0 &&
+ this.rotationZ - this.pRotationZ < 270) ||
+ this.rotationZ - this.pRotationZ < -270
+ ) {
+ rotateDirectionZ = 'clockwise';
+ } else if (
+ this.rotationZ - this.pRotationZ < 0 ||
+ this.rotationZ - this.pRotationZ > 270
+ ) {
+ rotateDirectionZ = 'counter-clockwise';
+ }
+ if (rotateDirectionZ !== this.pRotateDirectionZ) {
+ startAngleZ = this.rotationZ;
+ }
+ if (
+ Math.abs(this.rotationZ - startAngleZ) > 90 &&
+ Math.abs(this.rotationZ - startAngleZ) < 270
+ ) {
+ startAngleZ = this.rotationZ;
+ this._setProperty('turnAxis', 'Z');
+ deviceTurned();
+ }
+ this.pRotateDirectionZ = rotateDirectionZ;
+ this._setProperty('turnAxis', undefined);
+ }
+ var deviceShaken = this.deviceShaken || window.deviceShaken;
+ if (typeof 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) {
+ deviceShaken();
+ }
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/constants': 43, '../core/main': 54 }
+ ],
+ 72: [
+ 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
+ */ /**
+ * The boolean system variable keyIsPressed is true if any key is pressed
+ * and false if no keys are pressed.
+ *
+ * @property {Boolean} keyIsPressed
+ * @readOnly
+ * @example
+ *
+ *
+ * @alt
+ * 50x50 white rect that turns black on keypress.
+ */ _main.default.prototype.isKeyPressed = false;
+ _main.default.prototype.keyIsPressed = false; // khan
+ /**
+ * The system variable key always contains the value of the most recent
+ * key on the keyboard that was typed. To get the proper capitalization, it
+ * is best to use it within keyTyped(). For non-ASCII keys, use the keyCode
+ * variable.
+ *
+ * @property {String} key
+ * @readOnly
+ * @example
+ *
+ * // Click any key to display it!
+ * // (Not Guaranteed to be Case Sensitive)
+ * function setup() {
+ * fill(245, 123, 158);
+ * textSize(50);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * text(key, 33, 65); // Display last key pressed.
+ * }
+ *
+ *
+ * @alt
+ * canvas displays any key value that is pressed in pink font.
+ */
+ _main.default.prototype.key = '';
+
+ /**
+ * The variable keyCode is used to detect special keys such as BACKSPACE,
+ * DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,
+ * DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
+ * You can also check for custom keys by looking up the keyCode of any key
+ * on a site like this: keycode.info.
+ *
+ * @property {Integer} keyCode
+ * @readOnly
+ * @example
+ *
+ * @alt
+ * Grey rect center. turns white when up arrow pressed and black when down
+ * Display key pressed and its keyCode in a yellow box
+ */
+ _main.default.prototype.keyCode = 0;
+
+ /**
+ * The keyPressed() function is called once every time a key is pressed. The
+ * keyCode for the key that was pressed is stored in the keyCode variable.
+ *
+ * For non-ASCII keys, use the keyCode variable. You can check if the keyCode
+ * equals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,
+ * OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
+ *
+ * For ASCII keys, the key that was pressed is stored in the key variable. However, it
+ * does not distinguish between uppercase and lowercase. For this reason, it
+ * is recommended to use keyTyped() to read the key variable, in which the
+ * case of the variable will be distinguished.
+ *
+ * Because of how operating systems handle key repeats, holding down a key
+ * may cause multiple calls to keyTyped() (and keyReleased() as well). The
+ * rate of repeat is set by the operating system and how each computer is
+ * configured.
+ * Browsers may have different default
+ * behaviors attached to various key events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method keyPressed
+ * @example
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyPressed() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyPressed() {
+ * if (keyCode === LEFT_ARROW) {
+ * value = 255;
+ * } else if (keyCode === RIGHT_ARROW) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * function keyPressed() {
+ * // Do something
+ * return false; // prevent any default behaviour
+ * }
+ *
+ *
+ *
+ * @alt
+ * black rect center. turns white when key pressed and black when released
+ * black rect center. turns white when left arrow pressed and black when right.
+ */
+ _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 keyPressed = this.keyPressed || window.keyPressed;
+ if (typeof keyPressed === 'function' && !e.charCode) {
+ var executeDefault = keyPressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+ /**
+ * The keyReleased() function is called once every time a key is released.
+ * See key and keyCode for more information.
+ * Browsers may have different default
+ * behaviors attached to various key events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method keyReleased
+ * @example
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyReleased() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * return false; // prevent any default behavior
+ * }
+ *
+ *
+ *
+ * @alt
+ * black rect center. turns white when key pressed and black when pressed again
+ */
+ _main.default.prototype._onkeyup = function(e) {
+ var keyReleased = this.keyReleased || window.keyReleased;
+ 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);
+ if (typeof keyReleased === 'function') {
+ var executeDefault = keyReleased(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * The keyTyped() function is called once every time a key is pressed, but
+ * action keys such as Backspace, Delete, Ctrl, Shift, and Alt are ignored. If you are trying to detect
+ * a keyCode for one of these keys, use the keyPressed() function instead.
+ * The most recent key typed will be stored in the key variable.
+ *
+ * Because of how operating systems handle key repeats, holding down a key
+ * will cause multiple calls to keyTyped() (and keyReleased() as well). The
+ * rate of repeat is set by the operating system and how each computer is
+ * configured.
+ * Browsers may have different default behaviors attached to various key
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method keyTyped
+ * @example
+ *
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyTyped() {
+ * if (key === 'a') {
+ * value = 255;
+ * } else if (key === 'b') {
+ * value = 0;
+ * }
+ * // uncomment to prevent any default behavior
+ * // return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black rect center. turns white when 'a' key typed and black when 'b' pressed
+ */
+ _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', String.fromCharCode(e.which));
+ var keyTyped = this.keyTyped || window.keyTyped;
+ if (typeof keyTyped === 'function') {
+ var executeDefault = 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 = {};
+ };
+
+ /**
+ * The keyIsDown() function checks if the key is currently down, i.e. pressed.
+ * It can be used if you have an object that moves, and you want several keys
+ * to be able to affect its behaviour simultaneously, such as moving a
+ * sprite diagonally. You can put in any number representing the keyCode of
+ * the key, or use any of the variable keyCode names listed
+ * here.
+ *
+ * @method keyIsDown
+ * @param {Number} code The key to check for.
+ * @return {Boolean} whether key is down or not
+ * @example
+ *
+ * let x = 100;
+ * let y = 100;
+ *
+ * function setup() {
+ * createCanvas(512, 512);
+ * fill(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * if (keyIsDown(LEFT_ARROW)) {
+ * x -= 5;
+ * }
+ *
+ * if (keyIsDown(RIGHT_ARROW)) {
+ * x += 5;
+ * }
+ *
+ * if (keyIsDown(UP_ARROW)) {
+ * y -= 5;
+ * }
+ *
+ * if (keyIsDown(DOWN_ARROW)) {
+ * y += 5;
+ * }
+ *
+ * clear();
+ * ellipse(x, y, 50, 50);
+ * }
+ *
+ *
+ *
+ * let diameter = 50;
+ *
+ * function setup() {
+ * createCanvas(512, 512);
+ * }
+ *
+ * function draw() {
+ * // 107 and 187 are keyCodes for "+"
+ * if (keyIsDown(107) || keyIsDown(187)) {
+ * diameter += 1;
+ * }
+ *
+ * // 109 and 189 are keyCodes for "-"
+ * if (keyIsDown(109) || keyIsDown(189)) {
+ * diameter -= 1;
+ * }
+ *
+ * clear();
+ * fill(255, 0, 0);
+ * ellipse(50, 50, diameter, diameter);
+ * }
+ *
+ *
+ * @alt
+ * 50x50 red ellipse moves left, right, up and down with arrow presses.
+ * 50x50 red ellipse gets bigger or smaller when + or - are pressed.
+ */
+ _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': 54 }
+ ],
+ 73: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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
+ */ /**
+ *
+ * The variable movedX contains the horizontal movement of the mouse since the last frame
+ * @property {Number} movedX
+ * @readOnly
+ * @example
+ *
+ *
+ * let x = 50;
+ * function setup() {
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * if (x > 48) {
+ * x -= 2;
+ * } else if (x < 48) {
+ * x += 2;
+ * }
+ * x += floor(movedX / 5);
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(x, 50, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * box moves left and right according to mouse movement then slowly back towards the center
+ */ _main.default.prototype.movedX = 0;
+ /**
+ * The variable movedY contains the vertical movement of the mouse since the last frame
+ * @property {Number} movedY
+ * @readOnly
+ * @example
+ *
+ *
+ * let y = 50;
+ * function setup() {
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * if (y > 48) {
+ * y -= 2;
+ * } else if (y < 48) {
+ * y += 2;
+ * }
+ * y += floor(movedY / 5);
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(y, 50, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * box moves up and down according to mouse movement then slowly back towards the center
+ */ _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;
+
+ /**
+ * The system variable mouseX always contains the current horizontal
+ * position of the mouse, relative to (0, 0) of the canvas. The value at
+ * the top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.
+ * If touch is used instead of mouse input, mouseX will hold the x value
+ * of the most recent touch point.
+ *
+ * @property {Number} mouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas
+ * function draw() {
+ * background(244, 248, 252);
+ * line(mouseX, 0, mouseX, 100);
+ * }
+ *
+ *
+ *
+ * @alt
+ * horizontal black line moves left and right with mouse x-position
+ */
+ _main.default.prototype.mouseX = 0;
+
+ /**
+ * The system variable mouseY always contains the current vertical
+ * position of the mouse, relative to (0, 0) of the canvas. The value at
+ * the top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL.
+ * If touch is used instead of mouse input, mouseY will hold the y value
+ * of the most recent touch point.
+ *
+ * @property {Number} mouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas
+ * function draw() {
+ * background(244, 248, 252);
+ * line(0, mouseY, 100, mouseY);
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black line moves up and down with mouse y-position
+ */
+ _main.default.prototype.mouseY = 0;
+
+ /**
+ * The system variable pmouseX always contains the horizontal position of
+ * the mouse or finger in the frame previous to the current frame, relative to
+ * (0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and
+ * (-width/2, -height/2) for WebGL. Note: pmouseX will be reset to the current mouseX
+ * value at the start of each touch event.
+ *
+ * @property {Number} pmouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas to leave a trail
+ * function setup() {
+ * //slow down the frameRate to make it more visible
+ * frameRate(10);
+ * }
+ *
+ * function draw() {
+ * background(244, 248, 252);
+ * line(mouseX, mouseY, pmouseX, pmouseY);
+ * print(pmouseX + ' -> ' + mouseX);
+ * }
+ *
+ *
+ *
+ * @alt
+ * line trail is created from cursor movements. faster movement make longer line.
+ */
+ _main.default.prototype.pmouseX = 0;
+
+ /**
+ * The system variable pmouseY always contains the vertical position of
+ * the mouse or finger in the frame previous to the current frame, relative to
+ * (0, 0) of the canvas. The value at the top-left corner is (0, 0) for 2-D and
+ * (-width/2, -height/2) for WebGL. Note: pmouseY will be reset to the current mouseY
+ * value at the start of each touch event.
+ *
+ * @property {Number} pmouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ * //draw a square only if the mouse is not moving
+ * if (mouseY === pmouseY && mouseX === pmouseX) {
+ * rect(20, 20, 60, 60);
+ * }
+ *
+ * print(pmouseY + ' -> ' + mouseY);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 black rect center, fuchsia background. rect flickers on mouse movement
+ */
+ _main.default.prototype.pmouseY = 0;
+
+ /**
+ * The system variable winMouseX always contains the current horizontal
+ * position of the mouse, relative to (0, 0) of the window.
+ *
+ * @property {Number} winMouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * let body = document.getElementsByTagName('body')[0];
+ * myCanvas.parent(body);
+ * }
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * //move the canvas to the horizontal mouse position
+ * //relative to the window
+ * myCanvas.position(winMouseX + 1, windowHeight / 2);
+ *
+ * //the y of the square is relative to the canvas
+ * rect(20, mouseY, 60, 60);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 black rect y moves with mouse y and fuchsia canvas moves with mouse x
+ */
+ _main.default.prototype.winMouseX = 0;
+
+ /**
+ * The system variable winMouseY always contains the current vertical
+ * position of the mouse, relative to (0, 0) of the window.
+ *
+ * @property {Number} winMouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * let body = document.getElementsByTagName('body')[0];
+ * myCanvas.parent(body);
+ * }
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * //move the canvas to the vertical mouse position
+ * //relative to the window
+ * myCanvas.position(windowWidth / 2, winMouseY + 1);
+ *
+ * //the x of the square is relative to the canvas
+ * rect(mouseX, 20, 60, 60);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 black rect x moves with mouse x and fuchsia canvas y moves with mouse y
+ */
+ _main.default.prototype.winMouseY = 0;
+
+ /**
+ * The system variable pwinMouseX always contains the horizontal position
+ * of the mouse in the frame previous to the current frame, relative to
+ * (0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX
+ * value at the start of each touch event.
+ *
+ * @property {Number} pwinMouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * noStroke();
+ * fill(237, 34, 93);
+ * }
+ *
+ * function draw() {
+ * clear();
+ * //the difference between previous and
+ * //current x position is the horizontal mouse speed
+ * let speed = abs(winMouseX - pwinMouseX);
+ * //change the size of the circle
+ * //according to the horizontal speed
+ * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
+ * //move the canvas to the mouse position
+ * myCanvas.position(winMouseX + 1, winMouseY + 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
+ */
+ _main.default.prototype.pwinMouseX = 0;
+
+ /**
+ * The system variable pwinMouseY always contains the vertical position of
+ * the mouse in the frame previous to the current frame, relative to (0, 0)
+ * of the window. Note: pwinMouseY will be reset to the current winMouseY
+ * value at the start of each touch event.
+ *
+ * @property {Number} pwinMouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * let myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * noStroke();
+ * fill(237, 34, 93);
+ * }
+ *
+ * function draw() {
+ * clear();
+ * //the difference between previous and
+ * //current y position is the vertical mouse speed
+ * let speed = abs(winMouseY - pwinMouseY);
+ * //change the size of the circle
+ * //according to the vertical speed
+ * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
+ * //move the canvas to the mouse position
+ * myCanvas.position(winMouseX + 1, winMouseY + 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * fuchsia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
+ */
+ _main.default.prototype.pwinMouseY = 0;
+
+ /**
+ * Processing automatically tracks if the mouse button is pressed and which
+ * button is pressed. The value of the system variable mouseButton is either
+ * LEFT, RIGHT, or CENTER depending on which button was pressed last.
+ * Warning: different browsers may track mouseButton differently.
+ *
+ * @property {Constant} mouseButton
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * @alt
+ * 50x50 black ellipse appears on center of fuchsia canvas on mouse click/press.
+ */
+ _main.default.prototype.mouseButton = 0;
+
+ /**
+ * The boolean system variable mouseIsPressed is true if the mouse is pressed
+ * and false if not.
+ *
+ * @property {Boolean} mouseIsPressed
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * @alt
+ * black 50x50 rect becomes ellipse with mouse click/press. fuchsia background.
+ */
+ _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);
+ }
+ };
+
+ /**
+ * The mouseMoved() function is called every time the mouse moves and a mouse
+ * button is not pressed.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseMoved
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Move the mouse across the page
+ * // to change its value
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mouseMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseMoved(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect becomes lighter with mouse movements until white then resets
+ * no image displayed
+ */
+
+ /**
+ * The mouseDragged() function is called once every time the mouse moves and
+ * a mouse button is pressed. If no mouseDragged() function is defined, the
+ * touchMoved() function will be called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseDragged
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Drag the mouse across the page
+ * // to change its value
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mouseDragged() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseDragged(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns lighter with mouse click and drag until white, resets
+ * no image displayed
+ */
+ _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();
+ }
+ }
+ }
+ };
+
+ /**
+ * The mousePressed() function is called once after every time a mouse button
+ * is pressed. The mouseButton variable (see the related reference entry)
+ * can be used to determine which button has been pressed. If no
+ * mousePressed() function is defined, the touchStarted() function will be
+ * called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mousePressed
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mousePressed() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mousePressed(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse click/press.
+ * no image displayed
+ */
+ _main.default.prototype._onmousedown = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', true);
+ this._setMouseButton(e);
+ this._updateNextMouseCoords(e);
+
+ if (typeof context.mousePressed === 'function') {
+ executeDefault = context.mousePressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ // only safari needs this manual fallback for consistency
+ } else if (
+ navigator.userAgent.toLowerCase().includes('safari') &&
+ typeof context.touchStarted === 'function'
+ ) {
+ executeDefault = context.touchStarted(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * The mouseReleased() function is called every time a mouse button is
+ * released. If no mouseReleased() function is defined, the touchEnded()
+ * function will be called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseReleased
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been clicked
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mouseReleased() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseReleased(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse click/press.
+ * no image displayed
+ */
+ _main.default.prototype._onmouseup = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', false);
+ 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();
+ }
+ }
+ };
+
+ _main.default.prototype._ondragend = _main.default.prototype._onmouseup;
+ _main.default.prototype._ondragover = _main.default.prototype._onmousemove;
+
+ /**
+ * The mouseClicked() function is called once after a mouse button has been
+ * pressed and then released.
+ * Browsers handle clicks differently, so this function is only guaranteed to be
+ * run when the left mouse button is clicked. To handle other mouse buttons
+ * being pressed or released, see mousePressed() or mouseReleased().
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseClicked
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been clicked
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * function mouseClicked() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function mouseClicked(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse click/press.
+ * no image displayed
+ */
+ _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();
+ }
+ }
+ };
+
+ /**
+ * The doubleClicked() function is executed every time a event
+ * listener has detected a dblclick event which is a part of the
+ * DOM L3 specification. The doubleClicked event is fired when a
+ * pointing device button (usually a mouse's primary button)
+ * is clicked twice on a single element. For more info on the
+ * dblclick event refer to mozilla's documentation here:
+ * https://developer.mozilla.org/en-US/docs/Web/Events/dblclick
+ *
+ * @method doubleClicked
+ * @param {Object} [event] optional MouseEvent callback argument.
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been double clicked
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * function doubleClicked() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a MouseEvent object
+ * // as a callback argument
+ * function doubleClicked(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse doubleClick/press.
+ * no image displayed
+ */
+
+ _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;
+
+ /**
+ * The function mouseWheel() is executed every time a vertical mouse wheel
+ * event is detected either triggered by an actual mouse wheel or by a
+ * touchpad.
+ * The event.delta property returns the amount the mouse wheel
+ * have scrolled. The values can be positive or negative depending on the
+ * scroll direction (on OS X with "natural" scrolling enabled, the signs
+ * are inverted).
+ * Browsers may have different default behaviors attached to various
+ * mouse events. To prevent any default behavior for this event, add
+ * "return false" to the end of the method.
+ * Due to the current support of the "wheel" event on Safari, the function
+ * may only work as expected if "return false" is included while using Safari.
+ *
+ * @method mouseWheel
+ * @param {Object} [event] optional WheelEvent callback argument.
+ *
+ * @example
+ *
+ *
+ * let pos = 25;
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(25, pos, 50, 50);
+ * }
+ *
+ * function mouseWheel(event) {
+ * print(event.delta);
+ * //move the square according to the vertical scroll amount
+ * pos += event.delta;
+ * //uncomment to block page scrolling
+ * //return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect moves up and down with vertical scroll. fuchsia background
+ */
+ _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();
+ }
+ }
+ };
+
+ /**
+ * The function requestPointerLock()
+ * locks the pointer to its current position and makes it invisible.
+ * Use movedX and movedY to get the difference the mouse was moved since
+ * the last call of draw.
+ * Note that not all browsers support this feature.
+ * This enables you to create experiences that aren't limited by the mouse moving out of the screen
+ * even if it is repeatedly moved into one direction.
+ * For example, a first person perspective experience.
+ *
+ * @method requestPointerLock
+ * @example
+ *
+ *
+ * @alt
+ * 3D scene moves according to mouse mouse movement in a first person perspective
+ */
+ _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;
+ };
+
+ /**
+ * The function exitPointerLock()
+ * exits a previously triggered pointer Lock
+ * for example to make ui elements usable etc
+ *
+ * @method exitPointerLock
+ * @example
+ *
+ *
+ * //click the canvas to lock the pointer
+ * //click again to exit (otherwise escape)
+ * let locked = false;
+ * function draw() {
+ * background(237, 34, 93);
+ * }
+ * function mouseClicked() {
+ * if (!locked) {
+ * locked = true;
+ * requestPointerLock();
+ * } else {
+ * exitPointerLock();
+ * locked = false;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * cursor gets locked / unlocked on mouse-click
+ */
+ _main.default.prototype.exitPointerLock = function() {
+ document.exitPointerLock();
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/constants': 43, '../core/main': 54 }
+ ],
+ 74: [
+ 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
+ */ /**
+ * The system variable touches[] contains an array of the positions of all
+ * current touch points, relative to (0, 0) of the canvas, and IDs identifying a
+ * unique touch as it moves. Each element in the array is an object with x, y,
+ * and id properties.
+ *
+ * The touches[] array is not supported on Safari and IE on touch-based
+ * desktops (laptops).
+ *
+ * @property {Object[]} touches
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // On a touchscreen device, touch
+ * // the canvas using one or more fingers
+ * // at the same time
+ * function draw() {
+ * clear();
+ * let display = touches.length + ' touches';
+ * text(display, 5, 10);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Number of touches currently registered are displayed on the canvas
+ */ _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
+ };
+ }
+
+ /**
+ * The touchStarted() function is called once after every time a touch is
+ * registered. If no touchStarted() function is defined, the mousePressed()
+ * function will be called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchStarted
+ * @param {Object} [event] optional TouchEvent callback argument.
+ * @example
+ *
+ *
+ * // Touch within the image to change
+ * // the value of the rectangle
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function touchStarted() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchStarted(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect turns white with touch event.
+ * no image displayed
+ */
+ _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();
+ }
+ // only safari needs this manual fallback for consistency
+ } else if (
+ navigator.userAgent.toLowerCase().includes('safari') &&
+ typeof context.mousePressed === 'function'
+ ) {
+ executeDefault = context.mousePressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * The touchMoved() function is called every time a touch move is registered.
+ * If no touchMoved() function is defined, the mouseDragged() function will
+ * be called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchMoved
+ * @param {Object} [event] optional TouchEvent callback argument.
+ * @example
+ *
+ *
+ * // Move your finger across the page
+ * // to change its value
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function touchMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * // returns a TouchEvent object
+ * // as a callback argument
+ * function touchMoved(event) {
+ * console.log(event);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect turns lighter with touch until white. resets
+ * no image displayed
+ */
+ _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();
+ }
+ }
+ };
+
+ /**
+ * The touchEnded() function is called every time a touch ends. If no
+ * touchEnded() function is defined, the mouseReleased() function will be
+ * called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchEnded
+ * @param {Object} [event] optional TouchEvent callback argument.
+ * @example
+ *
+ *
+ * // Release touch within the image to
+ * // change the value of the rectangle
+ *
+ * let value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function touchEnded() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 66x66 dark turquoise rect in center of canvas.
+ * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas
+ * no image displayed
+ */
+ _main.default.prototype.createImage = function(width, height) {
+ _main.default._validateParameters('createImage', arguments);
+ return new _main.default.Image(width, height);
+ };
+
+ /**
+ * Save the current canvas as an image. The browser will either save the
+ * file immediately, or prompt the user with a dialogue window.
+ *
+ * @method saveCanvas
+ * @param {p5.Element|HTMLCanvasElement} selectedCanvas a variable
+ * representing a specific html5 canvas (optional)
+ * @param {String} [filename]
+ * @param {String} [extension] 'jpg' or 'png'
+ *
+ * @example
+ *
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(255, 0, 0);
+ * saveCanvas(c, 'myCanvas', 'jpg');
+ * }
+ *
+ *
+ * // note that this example has the same result as above
+ * // if no canvas is specified, defaults to main canvas
+ * function setup() {
+ * let c = createCanvas(100, 100);
+ * background(255, 0, 0);
+ * saveCanvas('myCanvas', 'jpg');
+ *
+ * // all of the following are valid
+ * saveCanvas(c, 'myCanvas', 'jpg');
+ * saveCanvas(c, 'myCanvas.jpg');
+ * saveCanvas(c, 'myCanvas');
+ * saveCanvas(c);
+ * saveCanvas('myCanvas', 'png');
+ * saveCanvas('myCanvas');
+ * saveCanvas();
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ * no image displayed
+ * no image displayed
+ */
+ /**
+ * @method saveCanvas
+ * @param {String} [filename]
+ * @param {String} [extension]
+ */
+ _main.default.prototype.saveCanvas = function() {
+ _main.default._validateParameters('saveCanvas', arguments);
+
+ // copy arguments to array
+ var args = [].slice.call(arguments);
+ var htmlCanvas, filename, extension;
+
+ if (arguments[0] instanceof HTMLCanvasElement) {
+ htmlCanvas = arguments[0];
+ args.shift();
+ } else if (arguments[0] instanceof _main.default.Element) {
+ htmlCanvas = arguments[0].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);
+ }, mimeType);
+ };
+
+ _main.default.prototype.saveGif = 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 occurence
+ 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 occurence
+ 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 occurence 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();
+
+ for (var _k = 0; _k < allFramesPixelColors[_i3].length; _k++) {
+ var _color = allFramesPixelColors[_i3][_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 _k2 = 0; _k2 < allFramesPixelColors[_i3].length; _k2++) {
+ // If this pixel in this frame has the same color in previous frame
+ if (
+ allFramesPixelColors[_i3 - 1][_k2] === allFramesPixelColors[_i3][_k2]
+ ) {
+ pixelPaletteIndex[_k2] = 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);
+ };
+
+ /**
+ * Capture a sequence of frames that can be used to create a movie.
+ * Accepts a callback. For example, you may wish to send the frames
+ * to a server where they can be stored or converted into a movie.
+ * If no callback is provided, the browser will pop up save dialogues in an
+ * attempt to download all of the images that have just been created. With the
+ * callback provided the image data isn't saved by default but instead passed
+ * as an argument to the callback function as an array of objects, with the
+ * size of array equal to the total number of frames.
+ *
+ * Note that saveFrames() will only save the first 15 frames of an animation.
+ * To export longer animations, you might look into a library like
+ * ccapture.js.
+ *
+ * @method saveFrames
+ * @param {String} filename
+ * @param {String} extension 'jpg' or 'png'
+ * @param {Number} duration Duration in seconds to save the frames for.
+ * @param {Number} framerate Framerate to save the frames in.
+ * @param {function(Array)} [callback] A 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 - an
+ image/octet-stream, filename and extension.
+ * @example
+ *
+ *
+ * function setup() {
+ * // here we use a callback to display the image after loading
+ * loadImage('assets/laDefense.jpg', img => {
+ * image(img, 0, 0);
+ * });
+ * }
+ *
+ *
+ *
+ * @alt
+ * image of the underside of a white umbrella and grided ceililng above
+ * image of the underside of a white umbrella and grided ceililng above
+ */ _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);
+ } 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);
+ } 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;
+ });
+ return pImg;
+ };
+
+ /**
+ * 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);
+ if (numFrames > 1) {
+ 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);
+ // 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
+ // There are possible disposal codes but I didn't encounter any
+ if (gifReader.frameInfo(j).disposal === 1 && j > 0) {
+ pImg.drawingContext.putImageData(frames[j - 1].image, 0, 0);
+ } else {
+ pImg.drawingContext.clearRect(0, 0, pImg.width, pImg.height);
+ framePixels = new Uint8ClampedArray(pImg.width * pImg.height * 4);
+ }
+ loadGIFFrameIntoImage(j, gifReader);
+ var imageData = new ImageData(framePixels, pImg.width, pImg.height);
+ pImg.drawingContext.putImageData(imageData, 0, 0);
+ frames.push({
+ image: pImg.drawingContext.getImageData(0, 0, pImg.width, pImg.height),
+ delay: frameInfo.delay * 10 //GIF stores delay in one-hundredth of a second, shift to ms
+ });
+ }
+
+ //Uses Netscape block encoding
+ //to repeat forever, this will be 0
+ //to repeat just once, this will be null
+ //to repeat N times (1 0 && sVal < iVal) {
+ return sVal;
+ } else {
+ return iVal;
+ }
+ }
+
+ /**
+ * Draw an image to the p5.js canvas.
+ *
+ * This function can be used with different numbers of parameters. The
+ * simplest use requires only three parameters: img, x, and y—where (x, y) is
+ * the position of the image. Two more parameters can optionally be added to
+ * specify the width and height of the image.
+ *
+ * This function can also be used with all eight Number parameters. To
+ * differentiate between all these parameters, p5.js uses the language of
+ * "destination rectangle" (which corresponds to "dx", "dy", etc.) and "source
+ * image" (which corresponds to "sx", "sy", etc.) below. Specifying the
+ * "source image" dimensions can be useful when you want to display a
+ * subsection of the source image instead of the whole thing. Here's a diagram
+ * to explain further:
+ *
+ *
+ * @method image
+ * @param {p5.Image|p5.Element} img the image to display
+ * @param {Number} x the x-coordinate of the top-left corner of the image
+ * @param {Number} y the y-coordinate of the top-left corner of the image
+ * @param {Number} [width] the width to draw the image
+ * @param {Number} [height] the height to draw the image
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * // Top-left corner of the img is at (0, 0)
+ * // Width and height are the img's original width and height
+ * image(img, 0, 0);
+ * }
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * background(50);
+ * // Top-left corner of the img is at (10, 10)
+ * // Width and height are 50 x 50
+ * image(img, 10, 10, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * // Here, we use a callback to display the image after loading
+ * loadImage('assets/laDefense.jpg', img => {
+ * image(img, 0, 0);
+ * });
+ * }
+ *
+ *
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/gradient.png');
+ * }
+ * function setup() {
+ * // 1. Background image
+ * // Top-left corner of the img is at (0, 0)
+ * // Width and height are the img's original width and height, 100 x 100
+ * image(img, 0, 0);
+ * // 2. Top right image
+ * // Top-left corner of destination rectangle is at (50, 0)
+ * // Destination rectangle width and height are 40 x 20
+ * // The next parameters are relative to the source image:
+ * // - Starting at position (50, 50) on the source image, capture a 50 x 50
+ * // subsection
+ * // - Draw this subsection to fill the dimensions of the destination rectangle
+ * image(img, 50, 0, 40, 20, 50, 50, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * image of the underside of a white umbrella and gridded ceiling above
+ * image of the underside of a white umbrella and gridded ceiling above
+ */
+ /**
+ * @method image
+ * @param {p5.Image|p5.Element} 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
+ */
+ _main.default.prototype.image = function(
+ img,
+ dx,
+ dy,
+ dWidth,
+ dHeight,
+ sx,
+ sy,
+ sWidth,
+ sHeight
+ ) {
+ // set defaults per spec: https://goo.gl/3ykfOq
+
+ _main.default._validateParameters('image', arguments);
+
+ var defW = img.width;
+ var defH = img.height;
+
+ if (img.elt && img.elt.videoWidth && !img.canvas) {
+ // video no canvas
+ defW = img.elt.videoWidth;
+ 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 || defW;
+ var _sh = 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
+ );
+
+ // tint the image if there is a tint
+ this._renderer.image(img, _sx, _sy, _sw, _sh, vals.x, vals.y, vals.w, vals.h);
+ };
+
+ /**
+ * Sets the fill value for displaying images. Images can be tinted to
+ * specified colors or made transparent by including an alpha value.
+ *
+ * To apply transparency to an image without affecting its color, use
+ * white as the tint color and specify an alpha value. For instance,
+ * tint(255, 128) will make an image 50% transparent (assuming the default
+ * alpha range of 0-255, which can be changed with colorMode()).
+ *
+ * The value for the gray parameter must be less than or equal to the current
+ * maximum value as specified by colorMode(). The default maximum value is
+ * 255.
+ *
+ * @method tint
+ * @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]
+ *
+ * @example
+ *
+ *
+ * @alt
+ * 2 side by side images of umbrella and ceiling, one image with blue tint
+ * Images of umbrella and ceiling, one half of image with blue tint
+ * 2 side by side images of umbrella and ceiling, one image translucent
+ */
+
+ /**
+ * @method tint
+ * @param {String} value a color string
+ */
+
+ /**
+ * @method tint
+ * @param {Number} gray a gray value
+ * @param {Number} [alpha]
+ */
+
+ /**
+ * @method tint
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and 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 fill value for displaying images and reverts to
+ * displaying images with their original hues.
+ *
+ * @method noTint
+ * @example
+ *
+ *
+ * @alt
+ * 2 side by side images of bricks, left image with blue 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 = function(img) {
+ if (!img.canvas) {
+ return img;
+ }
+ var pixels = _filters.default._toPixels(img.canvas);
+ var tmpCanvas = document.createElement('canvas');
+ tmpCanvas.width = img.canvas.width;
+ tmpCanvas.height = img.canvas.height;
+ var tmpCtx = tmpCanvas.getContext('2d');
+ var id = tmpCtx.createImageData(img.canvas.width, img.canvas.height);
+ var newPixels = id.data;
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ var r = pixels[i];
+ var g = pixels[i + 1];
+ var b = pixels[i + 2];
+ var a = pixels[i + 3];
+
+ newPixels[i] = r * this._renderer._tint[0] / 255;
+ newPixels[i + 1] = g * this._renderer._tint[1] / 255;
+ newPixels[i + 2] = b * this._renderer._tint[2] / 255;
+ newPixels[i + 3] = a * this._renderer._tint[3] / 255;
+ }
+
+ tmpCtx.putImageData(id, 0, 0);
+ return tmpCanvas;
+ };
+
+ /**
+ * Set image mode. Modifies the location from which images are drawn by
+ * changing the way in which parameters given to image() are interpreted.
+ * The default mode is imageMode(CORNER), which interprets the second and
+ * third parameters of image() as the upper-left corner of the image. If
+ * two additional parameters are specified, they are used to set the image's
+ * width and height.
+ *
+ * imageMode(CORNERS) interprets the second and third parameters of image()
+ * as the location of one corner, and the fourth and fifth parameters as the
+ * opposite corner.
+ *
+ * imageMode(CENTER) interprets the second and third parameters of image()
+ * as the image's center point. If two additional parameters are specified,
+ * they are used to set the image's width and height.
+ *
+ * @method imageMode
+ * @param {Constant} mode either CORNER, CORNERS, or CENTER
+ * @example
+ *
+ *
+ *
+ * @alt
+ * small square image of bricks
+ * horizontal rectangle image of bricks
+ * large square image of bricks
+ */
+ _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': 43,
+ '../core/friendly_errors/fes_core': 46,
+ '../core/friendly_errors/file_errors': 47,
+ '../core/friendly_errors/validate_params': 49,
+ '../core/helpers': 50,
+ '../core/main': 54,
+ './filters': 75,
+ omggif: 33
+ }
+ ],
+ 78: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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 };
+ }
+ /**
+ * @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
+ */ /**
+ * Creates a new p5.Image. A p5.Image is a canvas backed representation of an
+ * image.
+ *
+ * p5 can display .gif, .jpg and .png images. Images may be displayed
+ * in 2D and 3D space. Before an image is used, it must be loaded with the
+ * loadImage() function. The p5.Image class contains fields for the width and
+ * height of the image, as well as an array called pixels[] that contains the
+ * values for every pixel in the image.
+ *
+ * The methods described below allow easy access to the image's pixels and
+ * alpha channel and simplify the process of compositing.
+ *
+ * Before using the pixels[] array, be sure to use the loadPixels() method on
+ * the image to make sure that the pixel data is properly loaded.
+ * @example
+ *
+ * function setup() {
+ * let img = createImage(100, 100); // same as new p5.Image(100, 100);
+ * img.loadPixels();
+ * createCanvas(100, 100);
+ * background(0);
+ *
+ * // helper for writing color to array
+ * function writeColor(image, x, y, red, green, blue, alpha) {
+ * let index = (x + y * width) * 4;
+ * image.pixels[index] = red;
+ * image.pixels[index + 1] = green;
+ * image.pixels[index + 2] = blue;
+ * image.pixels[index + 3] = alpha;
+ * }
+ *
+ * let x, y;
+ * // fill with random colors
+ * for (y = 0; y < img.height; y++) {
+ * for (x = 0; x < img.width; x++) {
+ * let red = random(255);
+ * let green = random(255);
+ * let blue = random(255);
+ * let alpha = 255;
+ * writeColor(img, x, y, red, green, blue, alpha);
+ * }
+ * }
+ *
+ * // draw a red line
+ * y = 0;
+ * for (x = 0; x < img.width; x++) {
+ * writeColor(img, x, y, 255, 0, 0, 255);
+ * }
+ *
+ * // draw a green line
+ * y = img.height - 1;
+ * for (x = 0; x < img.width; x++) {
+ * writeColor(img, x, y, 0, 255, 0, 255);
+ * }
+ *
+ * img.updatePixels();
+ * image(img, 0, 0);
+ * }
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * image(img, 0, 0);
+ * for (let i = 0; i < img.width; i++) {
+ * let c = img.get(i, img.height / 2);
+ * stroke(c);
+ * line(i, height / 2, i, height);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * rocky mountains in top and horizontal lines in corresponding colors in bottom.
+ *
+ */ this.width = width;
+ /**
+ * Image height.
+ * @property {Number} height
+ * @readOnly
+ * @example
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * image(img, 0, 0);
+ * for (let i = 0; i < img.height; i++) {
+ * let c = img.get(img.width / 2, i);
+ * stroke(c);
+ * line(0, i, width / 2, i);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * rocky mountains on right and vertical lines in corresponding colors on left.
+ *
+ */ 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;
+ /**
+ * Array containing the values for all the pixels in the display window.
+ * These values are numbers. This array is the size (include an appropriate
+ * factor for pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. Retina and other
+ * high density displays may have more pixels (by a factor of
+ * pixelDensity^2).
+ * For example, if the image is 100x100 pixels, there will be 40,000. With
+ * pixelDensity = 2, there will be 160,000. The first four values
+ * (indices 0-3) in the array will be the R, G, B, A values of the pixel at
+ * (0, 0). The second four values (indices 4-7) will contain the R, G, B, A
+ * values of the pixel at (1, 0). More generally, to set values for a pixel
+ * at (x, y):
+ * ```javascript
+ * let d = pixelDensity();
+ * for (let i = 0; i < d; i++) {
+ * for (let j = 0; j < d; j++) {
+ * // loop over
+ * index = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[index] = r;
+ * pixels[index+1] = g;
+ * pixels[index+2] = b;
+ * pixels[index+3] = a;
+ * }
+ * }
+ * ```
+ *
+ * Before accessing this array, the data must loaded with the loadPixels()
+ * function. After the array data has been modified, the updatePixels()
+ * function must be run to update the changes.
+ * @property {Number[]} pixels
+ * @example
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains vertically stacked
+ */
+ _main.default.Image.prototype.loadPixels = function() {
+ _main.default.Renderer2D.prototype.loadPixels.call(this);
+ this.setModified(true);
+ };
+
+ /**
+ * Updates the backing canvas for this image with the contents of
+ * the [pixels] array.
+ *
+ * If this image is an animated GIF then the pixels will be updated
+ * in the frame that is currently displayed.
+ *
+ * @method updatePixels
+ * @param {Integer} x x-offset of the target update area for the
+ * underlying canvas
+ * @param {Integer} y y-offset of the target update area for the
+ * underlying canvas
+ * @param {Integer} w height of the target update area for the
+ * underlying canvas
+ * @param {Integer} h height of the target update area for the
+ * underlying canvas
+ * @example
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains vertically stacked
+ */
+ /**
+ * @method updatePixels
+ */
+ _main.default.Image.prototype.updatePixels = function(x, y, w, h) {
+ _main.default.Renderer2D.prototype.updatePixels.call(this, x, y, w, h);
+ this.setModified(true);
+ };
+
+ /**
+ * Get a region of pixels from an image.
+ *
+ * If no params are passed, the whole image is returned.
+ * If x and y are the only params passed a single pixel is extracted.
+ * If all params are passed a rectangle region is extracted and a p5.Image
+ * is returned.
+ *
+ * @method get
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number} w width
+ * @param {Number} h height
+ * @return {p5.Image} the rectangle p5.Image
+ * @example
+ *
+ * let myImage;
+ * let c;
+ *
+ * function preload() {
+ * myImage = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * background(myImage);
+ * noStroke();
+ * c = myImage.get(60, 90);
+ * fill(c);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * //get() returns color here
+ *
+ *
+ * @alt
+ * image of rocky mountains with 50x50 green rect in front
+ */
+ /**
+ * @method get
+ * @return {p5.Image} the whole p5.Image
+ */
+ /**
+ * @method get
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number[]} color of pixel at x,y in array format [R, G, B, A]
+ */
+ _main.default.Image.prototype.get = function(x, y, w, h) {
+ _main.default._validateParameters('p5.Image.get', arguments);
+ return _main.default.Renderer2D.prototype.get.apply(this, arguments);
+ };
+
+ _main.default.Image.prototype._getPixel =
+ _main.default.Renderer2D.prototype._getPixel;
+
+ /**
+ * Set the color of a single pixel or write an image into
+ * this p5.Image.
+ *
+ * Note that for a large number of pixels this will
+ * be slower than directly manipulating the pixels array
+ * and then calling updatePixels().
+ *
+ * @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 |
+ * a p5.Color | image to copy
+ * @example
+ *
+ *
+ * @alt
+ * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas
+ */
+ _main.default.Image.prototype.set = function(x, y, imgOrCol) {
+ _main.default.Renderer2D.prototype.set.call(this, x, y, imgOrCol);
+ this.setModified(true);
+ };
+
+ /**
+ * Resize the image to a new width and height. To make the image scale
+ * proportionally, use 0 as the value for the wide or high parameter.
+ * For instance, to make the width of an image 150 pixels, and change
+ * the height using the same proportion, use resize(150, 0).
+ *
+ * @method resize
+ * @param {Number} width the resized image width
+ * @param {Number} height the resized image height
+ * @example
+ *
+ *
+ * @alt
+ * image of rocky mountains. zoomed in
+ */
+ _main.default.Image.prototype.resize = function(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;
+ }
+ }
+
+ // prettier-ignore
+ 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
+
+ // prettier-ignore
+ this.drawingContext.drawImage(
+ tempCanvas,
+ 0, 0, width, height,
+ 0, 0, width, height);
+
+ if (this.pixels.length > 0) {
+ this.loadPixels();
+ }
+
+ this.setModified(true);
+ };
+
+ /**
+ * Copies a region of pixels from one image to another. If no
+ * srcImage is specified this is used as the source. If the source
+ * and destination regions aren't the same size, it will
+ * automatically resize source pixels to fit the specified
+ * target 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 photo;
+ * let bricks;
+ * let x;
+ * let y;
+ *
+ * function preload() {
+ * photo = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks.jpg');
+ * }
+ *
+ * function setup() {
+ * x = bricks.width / 2;
+ * y = bricks.height / 2;
+ * photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);
+ * image(photo, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains and smaller image on top of bricks at top left
+ */
+ /**
+ * @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.Image.prototype.copy = function() {
+ for (
+ var _len = arguments.length, args = new Array(_len), _key = 0;
+ _key < _len;
+ _key++
+ ) {
+ args[_key] = arguments[_key];
+ }
+ _main.default.prototype.copy.apply(this, args);
+ };
+
+ /**
+ * Masks part of an image from displaying by loading another
+ * image and using its alpha channel as an alpha channel for
+ * this image.
+ *
+ * @method mask
+ * @param {p5.Image} srcImage source image
+ * @example
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ */
+ /**
+ * @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.Image.prototype.blend = function() {
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _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
+ */
+ _main.default.Image.prototype.setModified = function(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.
+ */
+ _main.default.Image.prototype.isModified = function() {
+ return this._modified;
+ };
+
+ /**
+ * Saves the image to a file and force the browser to download it.
+ * Accepts two strings for filename and file extension
+ * Supports png (default), jpg, and gif
+ *
+ * Note that the file will only be downloaded as an animated GIF
+ * if the p5.Image was loaded from a GIF file.
+ * @method save
+ * @param {String} filename give your file a name
+ * @param {String} extension 'png' or 'jpg'
+ * @example
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-wink-loop-once.gif');
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * // The GIF file that we loaded only loops once
+ * // so it freezes on the last frame after playing through
+ * image(gif, 0, 0);
+ * }
+ *
+ * function mousePressed() {
+ * // Click to reset the GIF and begin playback from start
+ * gif.reset();
+ * }
+ *
+ * @alt
+ * Animated image of a cartoon face that winks once and then freezes
+ * When you click it animates again, winks once and freezes
+ */
+ _main.default.Image.prototype.reset = function() {
+ if (this.gifProperties) {
+ var props = this.gifProperties;
+ props.playing = true;
+ props.timeSinceStart = 0;
+ props.timeDisplayed = 0;
+ props.loopCount = 0;
+ props.displayIndex = 0;
+ this.drawingContext.putImageData(props.frames[0].image, 0, 0);
+ }
+ };
+
+ /**
+ * Gets the index for the frame that is currently visible in an animated GIF.
+ *
+ * @method getCurrentFrame
+ * @return {Number} The index for the currently displaying frame in animated GIF
+ * @example
+ *
+ * @alt
+ * Animated image of a cartoon eye looking around and then
+ * looking outwards, in the lower-left hand corner a number counts
+ * up quickly to 124 and then starts back over at 0
+ */
+ _main.default.Image.prototype.getCurrentFrame = function() {
+ if (this.gifProperties) {
+ var props = this.gifProperties;
+ return props.displayIndex % props.numFrames;
+ }
+ };
+
+ /**
+ * Sets the index of the frame that is currently visible in an animated GIF
+ *
+ * @method setFrame
+ * @param {Number} index the index for the frame that should be displayed
+ * @example
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
+ * }
+ *
+ * // Move your mouse up and down over canvas to see the GIF
+ * // frames animate
+ * function draw() {
+ * gif.pause();
+ * image(gif, 0, 0);
+ * // Get the highest frame number which is the number of frames - 1
+ * let maxFrame = gif.numFrames() - 1;
+ * // Set the current frame that is mapped to be relative to mouse position
+ * let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));
+ * gif.setFrame(frameNumber);
+ * }
+ *
+ * @alt
+ * A still image of a cartoon eye that looks around when you move your mouse
+ * up and down over the canvas
+ */
+ _main.default.Image.prototype.setFrame = function(index) {
+ if (this.gifProperties) {
+ var props = this.gifProperties;
+ if (index < props.numFrames && index >= 0) {
+ props.timeDisplayed = 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}
+ * @example The number of frames in the animated GIF
+ *
+ * let gif;
+ *
+ * function preload() {
+ * gif = loadImage('assets/arnott-wallace-eye-loop-forever.gif');
+ * }
+ *
+ * // Move your mouse up and down over canvas to see the GIF
+ * // frames animate
+ * function draw() {
+ * gif.pause();
+ * image(gif, 0, 0);
+ * // Get the highest frame number which is the number of frames - 1
+ * let maxFrame = gif.numFrames() - 1;
+ * // Set the current frame that is mapped to be relative to mouse position
+ * let frameNumber = floor(map(mouseY, 0, height, 0, maxFrame, true));
+ * gif.setFrame(frameNumber);
+ * }
+ *
+ * @alt
+ * A still image of a cartoon eye that looks around when you move your mouse
+ * up and down over the canvas
+ */
+ _main.default.Image.prototype.numFrames = function() {
+ if (this.gifProperties) {
+ return this.gifProperties.numFrames;
+ }
+ };
+
+ /**
+ * Plays an animated GIF that was paused with
+ * pause()
+ *
+ * @method play
+ * @example
+ *
+ * @alt
+ * An animated GIF of a drawing of small child with
+ * hair blowing in the wind, when you click the image
+ * freezes when you release it animates again
+ */
+ _main.default.Image.prototype.play = function() {
+ if (this.gifProperties) {
+ this.gifProperties.playing = true;
+ }
+ };
+
+ /**
+ * Pauses an animated GIF.
+ *
+ * @method pause
+ * @example
+ *
+ * @alt
+ * An animated GIF of a drawing of small child with
+ * hair blowing in the wind, when you click the image
+ * freezes when you release it animates again
+ */
+ _main.default.Image.prototype.pause = function() {
+ if (this.gifProperties) {
+ this.gifProperties.playing = false;
+ }
+ };
+
+ /**
+ * Changes the delay between frames in an animated GIF. There is an optional second parameter that
+ * indicates an index for a specific frame that should have its delay modified. If no index is given, all frames
+ * will have the new delay.
+ *
+ * @method delay
+ * @param {Number} d the amount in milliseconds to delay between switching frames
+ * @param {Number} [index] the index of the frame that should have the new delay value {optional}
+ * @example
+ *
+ * @alt
+ * Two animated gifs of cartoon eyes looking around
+ * The gif on the left animates quickly, on the right
+ * the animation is much slower
+ */
+ _main.default.Image.prototype.delay = function(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;
+ }
+ }
+ }
+ }
+ }
+ };
+ var _default = _main.default.Image;
+ exports.default = _default;
+ },
+ { '../core/main': 54, './filters': 75 }
+ ],
+ 79: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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
+ */ /**
+ * Uint8ClampedArray
+ * containing the values for all the pixels in the display window.
+ * These values are numbers. This array is the size (include an appropriate
+ * factor for pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. Retina and other
+ * high density displays will have more pixels[] (by a factor of
+ * pixelDensity^2).
+ * For example, if the image is 100x100 pixels, there will be 40,000. On a
+ * retina display, there will be 160,000.
+ *
+ * The first four values (indices 0-3) in the array will be the R, G, B, A
+ * values of the pixel at (0, 0). The second four values (indices 4-7) will
+ * contain the R, G, B, A values of the pixel at (1, 0). More generally, to
+ * set values for a pixel at (x, y):
+ * ```javascript
+ * let d = pixelDensity();
+ * for (let i = 0; i < d; i++) {
+ * for (let j = 0; j < d; j++) {
+ * // loop over
+ * index = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[index] = r;
+ * pixels[index+1] = g;
+ * pixels[index+2] = b;
+ * pixels[index+3] = a;
+ * }
+ * }
+ * ```
+ * While the above method is complex, it is flexible enough to work with
+ * any pixelDensity. Note that set() will automatically take care of
+ * setting all the appropriate values in pixels[] for a given (x, y) at
+ * any pixelDensity, but the performance may not be as fast when lots of
+ * modifications are made to the pixel array.
+ *
+ * Before accessing this array, the data must loaded with the loadPixels()
+ * function. After the array data has been modified, the updatePixels()
+ * function must be run to update the changes.
+ *
+ * Note that this is not a standard javascript array. This means that
+ * standard javascript functions such as slice() or
+ * arrayCopy() do not
+ * work.
+ *
+ * @property {Number[]} pixels
+ * @example
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ *
+ */
+ /**
+ * @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 a region of the canvas to another region of the canvas
+ * and copies a region of pixels from an image used as the srcImg parameter
+ * into the canvas srcImage is specified this is used as the source. If
+ * the source and destination regions aren't the same size, it will
+ * automatically resize source pixels to fit the specified
+ * target 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
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ */
+ /**
+ * @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
+ ) {
+ srcImage.loadPixels();
+ 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) {
+ _main.default.RendererGL.prototype.image.call(
+ dstImage._renderer,
+ srcImage,
+ sx + sxMod,
+ sy + syMod,
+ sw,
+ sh,
+ dx,
+ dy,
+ dw,
+ dh
+ );
+ } else {
+ dstImage.drawingContext.drawImage(
+ srcImage.canvas,
+ s * (sx + sxMod),
+ s * (sy + syMod),
+ s * sw,
+ s * sh,
+ dx,
+ dy,
+ dw,
+ dh
+ );
+ }
+ };
+
+ /**
+ * Applies a filter to the canvas. The presets options are:
+ *
+ * THRESHOLD
+ * 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.
+ *
+ * GRAY
+ * Converts any colors in the image to grayscale equivalents. No parameter
+ * is used.
+ *
+ * OPAQUE
+ * Sets the alpha channel to entirely opaque. No parameter is used.
+ *
+ * INVERT
+ * Sets each pixel to its inverse value. No parameter is used.
+ *
+ * POSTERIZE
+ * 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.
+ *
+ * BLUR
+ * Executes a Gaussian blur with the level parameter specifying the extent
+ * of the blurring. If no parameter is used, the blur is equivalent to
+ * Gaussian blur of radius 1. Larger values increase the blur.
+ *
+ * ERODE
+ * Reduces the light areas. No parameter is used.
+ *
+ * DILATE
+ * Increases the light areas. No parameter is used.
+ *
+ * filter() does not work in WEBGL mode.
+ * A similar effect can be achieved in WEBGL mode using custom
+ * shaders. Adam Ferriss has written
+ * a selection of shader examples that contains many
+ * of the effects present in the filter examples.
+ *
+ * @method filter
+ * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT,
+ * POSTERIZE, BLUR, ERODE, DILATE or BLUR.
+ * See Filters.js for docs on
+ * each available filter
+ * @param {Number} [filterParam] an optional parameter unique
+ * to each filter, see above
+ *
+ * @example
+ *
+ *
+ * @alt
+ * black and white image of a brick wall.
+ * greyscale image of a brickwall
+ * image of a brickwall
+ * jade colored image of a brickwall
+ * red and pink image of a brickwall
+ * image of a brickwall
+ * blurry image of a brickwall
+ * image of a brickwall
+ * image of a brickwall with less detail
+ */
+ _main.default.prototype.filter = function(operation, value) {
+ _main.default._validateParameters('filter', arguments);
+ if (this.canvas !== undefined) {
+ _filters.default.apply(this.canvas, _filters.default[operation], value);
+ } else {
+ _filters.default.apply(this.elt, _filters.default[operation], value);
+ }
+ };
+
+ /**
+ * Get a region of pixels, or a single pixel, from the canvas.
+ *
+ * Returns an array of [R,G,B,A] values for any pixel or grabs a section of
+ * an image. If no parameters are specified, the entire image is returned.
+ * Use the x and y parameters to get the value of one pixel. Get a section of
+ * the display window by specifying additional w and h parameters. When
+ * getting an image, the x and y parameters define the coordinates for the
+ * upper-left corner of the image, regardless of the current imageMode().
+ *
+ * Getting the color of a single pixel with get(x, y) is easy, but not as fast
+ * as grabbing the data directly from pixels[]. The equivalent statement to
+ * get(x, y) using pixels[] with pixel density d is
+ * ```javascript
+ * let x, y, d; // set these to the coordinates
+ * let off = (y * width + x) * d * 4;
+ * let components = [
+ * pixels[off],
+ * pixels[off + 1],
+ * pixels[off + 2],
+ * pixels[off + 3]
+ * ];
+ * print(components);
+ * ```
+ * See the reference for pixels[] for more information.
+ *
+ * If you want to extract an array of colors or a subimage from an p5.Image object,
+ * take a look at p5.Image.get()
+ *
+ * @method get
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number} w width
+ * @param {Number} h height
+ * @return {p5.Image} the rectangle p5.Image
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * let c = get();
+ * image(c, width / 2, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 images of the rocky mountains, side-by-side
+ * Image of the rocky mountains with 50x50 green rect in center of canvas
+ */
+ /**
+ * @method get
+ * @return {p5.Image} the whole p5.Image
+ */
+ /**
+ * @method get
+ * @param {Number} x
+ * @param {Number} y
+ * @return {Number[]} color of 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 pixel data for the display window into the pixels[] array. This
+ * function must always be called before reading from or writing to pixels[].
+ * Note that only changes made with set() or direct manipulation of pixels[]
+ * will occur.
+ *
+ * @method loadPixels
+ * @example
+ *
+ *
+ * let img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * image(img, 0, 0, width, height);
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height * d / 2);
+ * loadPixels();
+ * for (let i = 0; i < halfImage; i++) {
+ * pixels[i + halfImage] = pixels[i];
+ * }
+ * updatePixels();
+ * }
+ *
+ *
+ *
+ * @alt
+ * two images of the rocky mountains. one on top, one on bottom of canvas.
+ */
+ _main.default.prototype.loadPixels = function() {
+ for (
+ var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
+ _key3 < _len3;
+ _key3++
+ ) {
+ args[_key3] = arguments[_key3];
+ }
+ _main.default._validateParameters('loadPixels', args);
+ this._renderer.loadPixels();
+ };
+
+ /**
+ * Changes the color of any pixel, or writes an image directly to the
+ * display window.
+ * The x and y parameters specify the pixel to change and the c parameter
+ * specifies the color value. This can be a p5.Color object, or [R, G, B, A]
+ * pixel array. It can also be a single grayscale value.
+ * When setting an image, the x and y parameters define the coordinates for
+ * the upper-left corner of the image, regardless of the current imageMode().
+ *
+ * After using set(), you must call updatePixels() for your changes to appear.
+ * This should be called once all pixels have been set, and must be called before
+ * calling .get() or drawing the image.
+ *
+ * Setting the color of a single pixel with set(x, y) is easy, but not as
+ * fast as putting the data directly into pixels[]. Setting the pixels[]
+ * values directly may be complicated when working with a retina display,
+ * but will perform better when lots of pixels need to be set directly on
+ * every loop. See the reference for pixels[] for more information.
+ *
+ * @method set
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number|Number[]|Object} c insert a grayscale value | a pixel array |
+ * a p5.Color object | a p5.Image to copy
+ * @example
+ *
+ *
+ * @alt
+ * 4 black points in the shape of a square middle-right of canvas.
+ * square with orangey-brown gradient lightening at bottom right.
+ * image of the rocky mountains. with lines like an 'x' through the center.
+ */
+ _main.default.prototype.set = function(x, y, imgOrCol) {
+ this._renderer.set(x, y, imgOrCol);
+ };
+ /**
+ * Updates the display window with the data in the pixels[] array.
+ * Use in conjunction with loadPixels(). If you're only reading pixels from
+ * the array, there's no need to call updatePixels() — updating is only
+ * necessary to apply changes. updatePixels() should be called anytime the
+ * pixels array is manipulated or set() is called, and only changes made with
+ * set() or direct changes to pixels[] will occur.
+ *
+ * @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;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * image(img, 0, 0, width, height);
+ * let d = pixelDensity();
+ * let halfImage = 4 * (width * d) * (height * d / 2);
+ * loadPixels();
+ * for (let i = 0; i < halfImage; i++) {
+ * pixels[i + halfImage] = pixels[i];
+ * }
+ * updatePixels();
+ * }
+ *
+ *
+ * @alt
+ * two images of the rocky mountains. one on top, one on bottom of canvas.
+ */
+ _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': 41, '../core/main': 54, './filters': 75 }
+ ],
+ 80: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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' && 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);
+ }
+
+ /**
+ * Loads a JSON file from a file or a URL, and returns an Object.
+ * Note that even if the JSON file contains an Array, an Object will be
+ * returned with index numbers as keys.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. JSONP is supported via a polyfill and you
+ * can pass in as the second argument an object with definitions of the json
+ * callback following the syntax specified here.
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadJSON
+ * @param {String} path name of the file or url to load
+ * @param {Object} [jsonpOptions] options object for jsonp related settings
+ * @param {String} [datatype] "json" or "jsonp"
+ * @param {function} [callback] function to be executed after
+ * loadJSON() 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 {Object|Array} JSON data
+ * @example
+ *
+ * Calling loadJSON() inside preload() guarantees to complete the
+ * operation before setup() and draw() are called.
+ *
+ *
+ * // 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/earthquakes/feed/v1.0/' +
+ * 'summary/all_day.geojson';
+ * earthquakes = loadJSON(url);
+ * }
+ *
+ * function setup() {
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * 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);
+ * }
+ *
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ * function setup() {
+ * noLoop();
+ * let url =
+ 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +
+ * 'summary/all_day.geojson';
+ * loadJSON(url, drawEarthquake);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * }
+ *
+ * function drawEarthquake(earthquakes) {
+ * // 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);
+ * }
+ *
+ *
+ * @alt
+ * 50x50 ellipse that changes from black to white depending on the current humidity
+ * 50x50 ellipse that changes from black to white depending on the current humidity
+ */
+ /**
+ * @method loadJSON
+ * @param {String} path
+ * @param {String} datatype
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ * @return {Object|Array}
+ */
+ /**
+ * @method loadJSON
+ * @param {String} path
+ * @param {function} callback
+ * @param {function} [errorCallback]
+ * @return {Object|Array}
+ */
+ _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;
+ };
+
+ /**
+ * Reads the contents of a file and creates a String array of its individual
+ * lines. If the name of the file is used as the parameter, as in the above
+ * example, the file must be located in the sketch directory/folder.
+ *
+ * Alternatively, the file maybe be loaded from anywhere on the local
+ * computer using an absolute path (something that starts with / on Unix and
+ * Linux, or a drive letter on Windows), or the filename parameter can be a
+ * URL for a file found on a network.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed.
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadStrings
+ * @param {String} filename name of the file or url to load
+ * @param {function} [callback] function to be executed after loadStrings()
+ * completes, Array 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 {String[]} Array of Strings
+ * @example
+ *
+ * Calling loadStrings() inside preload() guarantees to complete the
+ * operation before setup() and draw() are called.
+ *
+ *
+ * let result;
+ * function preload() {
+ * result = loadStrings('assets/test.txt');
+ * }
+
+ * function setup() {
+ * background(200);
+ * text(random(result), 10, 10, 80, 80);
+ * }
+ *
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ *
+ *
+ * @alt
+ * randomly generated text from a file, for example "i smell like butter"
+ * randomly generated text from a file, for example "i have three feet"
+ */
+ _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/);
+ Array.prototype.push.apply(ret, lines);
+
+ 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));
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * randomly generated text from a file, for example "i smell like butter"
+ * randomly generated text from a file, for example "i have three feet"
+ */
+ _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';
+ }
+ }
+ }
+
+ console.log('SEP IS ' + sep);
+
+ 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 _i = 0; _i < records[0].length; _i++) {
+ t.columns[_i] = 'null';
+ }
+ }
+ var row;
+ for (var _i2 = 0; _i2 < records.length; _i2++) {
+ //Handles row of 'undefined' at end of some CSVs
+ if (records[_i2].length === 1) {
+ if (records[_i2][0] === 'undefined' || records[_i2][0] === '') {
+ continue;
+ }
+ }
+ row = new _main.default.TableRow();
+ row.arr = records[_i2];
+ row.obj = makeObject(records[_i2], 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) {
+ var ret = {};
+ headers = headers || [];
+ if (typeof headers === 'undefined') {
+ for (var j = 0; j < row.length; j++) {
+ headers[j.toString()] = j;
+ }
+ }
+ for (var i = 0; i < headers.length; i++) {
+ var key = headers[i];
+ var val = row[i];
+ ret[key] = val;
+ }
+ return ret;
+ }
+
+ /**
+ * Reads the contents of a file and creates an XML object with its values.
+ * If the name of the file is used as the parameter, as in the above example,
+ * the file must be located in the sketch directory/folder.
+ *
+ * Alternatively, the file maybe be loaded from anywhere on the local
+ * computer using an absolute path (something that starts with / on Unix and
+ * Linux, or a drive letter on Windows), or the filename parameter can be a
+ * URL for a file found on a network.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. Calling loadXML() 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.
+ *
+ * This method is suitable for fetching files up to size of 64MB.
+ * @method loadXML
+ * @param {String} filename name of the file or URL to load
+ * @param {function} [callback] function to be executed after loadXML()
+ * completes, XML object 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 {Object} XML object containing data
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let children = xml.getChildren('animal');
+ *
+ * for (let i = 0; i < children.length; i++) {
+ * let id = children[i].getNum('id');
+ * let coloring = children[i].getString('species');
+ * let name = children[i].getContent();
+ * print(id + ', ' + coloring + ', ' + name);
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // 0, Capra hircus, Goat
+ * // 1, Panthera pardus, Leopard
+ * // 2, Equus zebra, Zebra
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _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));
+ * }
+ * }
+ *
+ *
+ * @alt
+ * 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() {
+ _main.default._validateParameters('httpGet', arguments);
+
+ var args = Array.prototype.slice.call(arguments);
+ 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 way cool.' };
+ *
+ * function setup() {
+ * createCanvas(800, 800);
+ * }
+ *
+ * function mousePressed() {
+ * // Pick new random color values
+ * let r = random(255);
+ * let g = random(255);
+ * let b = random(255);
+ *
+ * httpPost(url, 'json', postData, function(result) {
+ * strokeWeight(2);
+ * stroke(r, g, b);
+ * fill(r, g, b, 127);
+ * ellipse(mouseX, mouseY, 200, 200);
+ * 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 way cool.' };
+ *
+ * function setup() {
+ * createCanvas(800, 800);
+ * }
+ *
+ * function mousePressed() {
+ * // Pick new random color values
+ * let r = random(255);
+ * let g = random(255);
+ * let b = random(255);
+ *
+ * httpPost(
+ * url,
+ * 'json',
+ * postData,
+ * function(result) {
+ * // ... won't be called
+ * },
+ * function(error) {
+ * strokeWeight(2);
+ * stroke(r, g, b);
+ * fill(r, g, b, 127);
+ * 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() {
+ _main.default._validateParameters('httpPost', arguments);
+
+ var args = Array.prototype.slice.call(arguments);
+ 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 = [];
+
+ /**
+ * @method createWriter
+ * @param {String} name name of the file to be created
+ * @param {String} [extension]
+ * @return {p5.PrintWriter}
+ * @example
+ *
+ */
+ _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;
+ };
+
+ /**
+ * @class p5.PrintWriter
+ * @param {String} filename
+ * @param {String} [extension]
+ */
+ _main.default.PrintWriter = function(filename, extension) {
+ var self = this;
+ this.name = filename;
+ this.content = '';
+ //Changed to write because it was being overloaded by function below.
+ /**
+ * Writes data to the PrintWriter stream
+ * @method write
+ * @param {Array} data all data to be written by the PrintWriter
+ * @example
+ *
+ *
+ * // creates a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // write 'Hello world!'' to the file
+ * writer.write(['Hello world!']);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // creates a file called 'newFile2.txt'
+ * let writer = createWriter('newFile2.txt');
+ * // write 'apples,bananas,123' to the file
+ * writer.write(['apples', 'bananas', 123]);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // creates a file called 'newFile3.txt'
+ * let writer = createWriter('newFile3.txt');
+ * // write 'My name is: Teddy' to the file
+ * writer.write('My name is:');
+ * writer.write(' Teddy');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * button = createButton('SAVE FILE');
+ * button.position(21, 40);
+ * button.mousePressed(createFile);
+ * }
+ *
+ * function createFile() {
+ * // creates a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // write 'Hello world!'' to the file
+ * writer.write(['Hello world!']);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ * }
+ *
+ *
+ */
+ this.write = function(data) {
+ this.content += data;
+ };
+ /**
+ * Writes data to the PrintWriter stream, and adds a new line at the end
+ * @method print
+ * @param {Array} data all data to be printed by the PrintWriter
+ * @example
+ *
+ *
+ * // creates a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // creates a file containing
+ * // My name is:
+ * // Teddy
+ * writer.print('My name is:');
+ * writer.print('Teddy');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ * // create a file called 'newFile.txt'
+ * let writer = createWriter('newFile.txt');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // create a file called 'newFile2.txt'
+ * let writer = createWriter('newFile2.txt');
+ * // write some data to the file
+ * writer.write([100, 101, 102]);
+ * // close the PrintWriter and save the file
+ * writer.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');
+ *
+ *
+ *
+ * // Saves p5.Image as an image
+ * img = createImage(10, 10);
+ * save(img, 'myImage.png');
+ *
+ * // Saves array of strings to text file with line breaks after each item
+ * let arrayOfStrings = ['a', 'b'];
+ * save(arrayOfStrings, 'my.txt');
+ *
+ *
+ * @alt
+ * An example for saving a canvas as an image.
+ * An example for saving a p5.Image element as an image.
+ * An example for saving a p5.Renderer element.
+ * An example showing how to save a table in formats of HTML, CSV and TSV.
+ * An example for saving JSON to a txt file with some extra arguments.
+ * 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]);
+ }
+ }
+ }
+ };
+
+ /**
+ * Writes the contents of an Array or a JSON object to a .json file.
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveJSON
+ * @param {Array|Object} json
+ * @param {String} filename
+ * @param {Boolean} [optimize] If true, removes line breaks
+ * and spaces from the output
+ * file to optimize filesize
+ * (but not readability).
+ * @example
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _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;
+
+ /**
+ * Writes an array of Strings to a text file, one line per String.
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveStrings
+ * @param {String[]} list string array to be written
+ * @param {String} filename filename for output
+ * @param {String} [extension] the filename's extension
+ * @param {Boolean} [isCRLF] if true, change line-break to CRLF
+ * @example
+ *
+ * let words = 'apple bear cat dog';
+ *
+ * // .split() outputs an Array
+ * let list = split(words, ' ');
+ *
+ * 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) {
+ * saveStrings(list, 'nouns.txt');
+ * }
+ * }
+ *
+ * // Saves the following to a file called 'nouns.txt':
+ * //
+ * // apple
+ * // bear
+ * // cat
+ * // dog
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _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');
+ * }
+ *
+ * // Saves the following to a file called 'new.csv':
+ * // id,species,name
+ * // 0,Panthera leo,Lion
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _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) {
+ pWriter.write(table.rows[i].arr[j] + sep);
+ } else if (i < table.rows.length - 1) {
+ 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(str);
+ pWriter.print('');
+
+ 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('
');
+ for (var col = 0; col < table.columns.length; col++) {
+ var entry = table.rows[row].getString(col);
+ var htmlEntry = escapeHelper(entry);
+ pWriter.print('
'.concat(htmlEntry));
+ pWriter.print('
');
+ }
+ pWriter.print('
');
+ }
+ 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() {
+ var x = Object.prototype.toString.call(window.HTMLElement);
+ return x.indexOf('Constructor') > 0;
+ };
+
+ /**
+ * 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': 46,
+ '../core/friendly_errors/file_errors': 47,
+ '../core/friendly_errors/validate_params': 49,
+ '../core/main': 54,
+ 'es6-promise/auto': 23,
+ 'fetch-jsonp': 25,
+ 'file-saver': 26,
+ 'whatwg-fetch': 37
+ }
+ ],
+ 81: [
+ 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 };
+ } /**
+ * 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
+ */ /**
+ * @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
+ *
+ */
+ _main.default.Table = function(rows) {
+ /**
+ * An array containing the names of the columns in the table, if the "header" the table is
+ * loaded with the "header" parameter.
+ * @property columns {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() {
+ * //print the column names
+ * for (let c = 0; c < table.getColumnCount(); c++) {
+ * print('column ' + c + ' is named ' + table.columns[c]);
+ * }
+ * }
+ *
+ *
+ */
+ this.columns = [];
+
+ /**
+ * An array containing the p5.TableRow objects that make up the
+ * rows of the table. The same result as calling getRows()
+ * @property rows {p5.TableRow[]}
+ */
+ this.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));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.addRow = function(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));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.removeRow = function(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));
+ * }
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.getRow = function(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));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.getRows = function() {
+ 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'));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.findRow = function(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');
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.findRows = function(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"
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.matchRow = function(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
+ *
+ */
+ _main.default.Table.prototype.matchRows = function(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"]
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.getColumn = function(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');
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.clearRows = function() {
+ 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));
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.addColumn = function(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);
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getColumnCount = function() {
+ 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);
+ * }
+ *
+ *
+ */
+ _main.default.Table.prototype.getRowCount = function() {
+ 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
+ *
+ */
+ _main.default.Table.prototype.removeTokens = function(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
+ *
+ */
+ _main.default.Table.prototype.trim = function(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());
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.removeColumn = function(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));
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.set = function(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"]
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.setNum = function(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());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.setString = function(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
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.get = function(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
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.getNum = function(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
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+
+ _main.default.Table.prototype.getString = function(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
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.getObject = function(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]);
+ * }
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+ _main.default.Table.prototype.getArray = function() {
+ var tableArray = [];
+ for (var i = 0; i < this.rows.length; i++) {
+ tableArray.push(this.rows[i].arr);
+ }
+ return tableArray;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 82: [
+ 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 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 = function(str, separator) {
+ var arr = [];
+ var obj = {};
+ if (str) {
+ separator = separator || ',';
+ arr = str.split(separator);
+ }
+ for (var i = 0; i < arr.length; i++) {
+ var key = i;
+ var val = arr[i];
+ obj[key] = val;
+ }
+ this.arr = arr;
+ this.obj = obj;
+ 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());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.set = function(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());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.setNum = function(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());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.setString = function(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);
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.get = function(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);
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.getNum = function(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);
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+ _main.default.TableRow.prototype.getString = function(column) {
+ if (typeof column === 'string') {
+ return this.obj[column].toString();
+ } else {
+ return this.arr[column].toString();
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 83: [
+ 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 Input
+ * @requires core
+ */ /**
+ * XML is a representation of an XML object, able to parse XML code. Use
+ * loadXML() to load external XML files and create XML objects.
+ *
+ * @class p5.XML
+ * @constructor
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let children = xml.getChildren('animal');
+ *
+ * for (let i = 0; i < children.length; i++) {
+ * let id = children[i].getNum('id');
+ * let coloring = children[i].getString('species');
+ * let name = children[i].getContent();
+ * print(id + ', ' + coloring + ', ' + name);
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // 0, Capra hircus, Goat
+ * // 1, Panthera pardus, Leopard
+ * // 2, Equus zebra, Zebra
+ *
+ *
+ * @alt
+ * no image displayed
+ */ _main.default.XML = function(DOM) {
+ if (!DOM) {
+ var xmlDoc = document.implementation.createDocument(null, 'doc');
+ this.DOM = xmlDoc.createElement('root');
+ } else {
+ this.DOM = DOM;
+ }
+ };
+
+ /**
+ * Gets a copy of the element's parent. Returns the parent as another
+ * p5.XML object.
+ *
+ * @method getParent
+ * @return {p5.XML} element parent
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let children = xml.getChildren('animal');
+ * let parent = children[1].getParent();
+ * print(parent.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ *
+ */
+ _main.default.XML.prototype.getParent = function() {
+ return new _main.default.XML(this.DOM.parentElement);
+ };
+
+ /**
+ * Gets the element's full name, which is returned as a String.
+ *
+ * @method getName
+ * @return {String} the name of the node
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ *
+ */
+ _main.default.XML.prototype.getName = function() {
+ return this.DOM.tagName;
+ };
+
+ /**
+ * Sets the element's name, which is specified as a String.
+ *
+ * @method setName
+ * @param {String} the new name of the node
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.getName());
+ * xml.setName('fish');
+ * print(xml.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ * // fish
+ *
+ */
+ _main.default.XML.prototype.setName = function(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.nodeValue);
+ }
+ this.DOM = newDOM;
+ };
+
+ /**
+ * Checks whether or not the element has any children, and returns the result
+ * as a boolean.
+ *
+ * @method hasChildren
+ * @return {boolean}
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.hasChildren());
+ * }
+ *
+ * // Sketch prints:
+ * // true
+ *
+ */
+ _main.default.XML.prototype.hasChildren = function() {
+ return this.DOM.children.length > 0;
+ };
+
+ /**
+ * Get the names of all of the element's children, and returns the names as an
+ * array of Strings. This is the same as looping through and calling getName()
+ * on each child element individually.
+ *
+ * @method listChildren
+ * @return {String[]} names of the children of the element
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.listChildren());
+ * }
+ *
+ * // Sketch prints:
+ * // ["animal", "animal", "animal"]
+ *
+ */
+ _main.default.XML.prototype.listChildren = function() {
+ var arr = [];
+ for (var i = 0; i < this.DOM.childNodes.length; i++) {
+ arr.push(this.DOM.childNodes[i].nodeName);
+ }
+ return arr;
+ };
+
+ /**
+ * Returns all of the element's children as an array of p5.XML objects. When
+ * the name parameter is specified, then it will return all children that match
+ * that name.
+ *
+ * @method getChildren
+ * @param {String} [name] element name
+ * @return {p5.XML[]} children of the element
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let animals = xml.getChildren('animal');
+ *
+ * for (let i = 0; i < animals.length; i++) {
+ * print(animals[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Leopard"
+ * // "Zebra"
+ *
+ */
+ _main.default.XML.prototype.getChildren = function(param) {
+ if (param) {
+ return elementsToP5XML(this.DOM.getElementsByTagName(param));
+ } else {
+ return elementsToP5XML(this.DOM.children);
+ }
+ };
+
+ function elementsToP5XML(elements) {
+ var arr = [];
+ for (var i = 0; i < elements.length; i++) {
+ arr.push(new _main.default.XML(elements[i]));
+ }
+ return arr;
+ }
+
+ /**
+ * Returns the first of the element's children that matches the name parameter
+ * or the child of the given index.It returns undefined if no matching
+ * child is found.
+ *
+ * @method getChild
+ * @param {String|Integer} name element name or index
+ * @return {p5.XML}
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ *
+ */
+ _main.default.XML.prototype.getChild = function(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]);
+ }
+ };
+
+ /**
+ * Appends a new child to the element. The child can be specified with
+ * either a String, which will be used as the new tag's name, or as a
+ * reference to an existing p5.XML object.
+ * A reference to the newly created child is returned as an p5.XML object.
+ *
+ * @method addChild
+ * @param {p5.XML} node a p5.XML Object which will be the child to be added
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let child = new p5.XML();
+ * child.setName('animal');
+ * child.setAttribute('id', '3');
+ * child.setAttribute('species', 'Ornithorhynchus anatinus');
+ * child.setContent('Platypus');
+ * xml.addChild(child);
+ *
+ * let animals = xml.getChildren('animal');
+ * print(animals[animals.length - 1].getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Leopard"
+ * // "Zebra"
+ *
+ */
+ _main.default.XML.prototype.addChild = function(node) {
+ if (node instanceof _main.default.XML) {
+ this.DOM.appendChild(node.DOM);
+ } else {
+ // PEND
+ }
+ };
+
+ /**
+ * Removes the element specified by name or index.
+ *
+ * @method removeChild
+ * @param {String|Integer} name element name or index
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * xml.removeChild('animal');
+ * let children = xml.getChildren();
+ * for (let i = 0; i < children.length; i++) {
+ * print(children[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Leopard"
+ * // "Zebra"
+ *
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * xml.removeChild(1);
+ * let children = xml.getChildren();
+ * for (let i = 0; i < children.length; i++) {
+ * print(children[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Zebra"
+ *
+ */
+ _main.default.XML.prototype.removeChild = function(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]);
+ }
+ };
+
+ /**
+ * Counts the specified element's number of attributes, returned as an Number.
+ *
+ * @method getAttributeCount
+ * @return {Integer}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getAttributeCount());
+ * }
+ *
+ * // Sketch prints:
+ * // 2
+ *
+ */
+ _main.default.XML.prototype.getAttributeCount = function() {
+ return this.DOM.attributes.length;
+ };
+
+ /**
+ * Gets all of the specified element's attributes, and returns them as an
+ * array of Strings.
+ *
+ * @method listAttributes
+ * @return {String[]} an array of strings containing the names of attributes
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.listAttributes());
+ * }
+ *
+ * // Sketch prints:
+ * // ["id", "species"]
+ *
+ */
+ _main.default.XML.prototype.listAttributes = function() {
+ 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;
+ };
+
+ /**
+ * Checks whether or not an element has the specified attribute.
+ *
+ * @method hasAttribute
+ * @param {String} the attribute to be checked
+ * @return {boolean} true if attribute found else false
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.hasAttribute('species'));
+ * print(firstChild.hasAttribute('color'));
+ * }
+ *
+ * // Sketch prints:
+ * // true
+ * // false
+ *
+ */
+ _main.default.XML.prototype.hasAttribute = function(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;
+ };
+
+ /**
+ * Returns an attribute value of the element as an Number. If the defaultValue
+ * parameter is specified and the attribute doesn't exist, then defaultValue
+ * is returned. If no defaultValue is specified and the attribute doesn't
+ * exist, the value 0 is returned.
+ *
+ * @method getNum
+ * @param {String} name the non-null full name of the attribute
+ * @param {Number} [defaultValue] the default value of the attribute
+ * @return {Number}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getNum('id'));
+ * }
+ *
+ * // Sketch prints:
+ * // 0
+ *
+ */
+ _main.default.XML.prototype.getNum = function(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;
+ };
+
+ /**
+ * Returns an attribute value of the element as an String. If the defaultValue
+ * parameter is specified and the attribute doesn't exist, then defaultValue
+ * is returned. If no defaultValue is specified and the attribute doesn't
+ * exist, null is returned.
+ *
+ * @method getString
+ * @param {String} name the non-null full name of the attribute
+ * @param {Number} [defaultValue] the default value of the attribute
+ * @return {String}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getString('species'));
+ * }
+ *
+ * // Sketch prints:
+ * // "Capra hircus"
+ *
+ */
+ _main.default.XML.prototype.getString = function(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 the content of an element's attribute. The first parameter specifies
+ * the attribute name, while the second specifies the new content.
+ *
+ * @method setAttribute
+ * @param {String} name the full name of the attribute
+ * @param {Number|String|Boolean} value the value of the attribute
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getString('species'));
+ * firstChild.setAttribute('species', 'Jamides zebra');
+ * print(firstChild.getString('species'));
+ * }
+ *
+ * // Sketch prints:
+ * // "Capra hircus"
+ * // "Jamides zebra"
+ *
+ */
+ _main.default.XML.prototype.setAttribute = function(name, value) {
+ this.DOM.setAttribute(name, value);
+ };
+
+ /**
+ * Returns the content of an element. If there is no such content,
+ * defaultValue is returned if specified, otherwise null is returned.
+ *
+ * @method getContent
+ * @param {String} [defaultValue] value returned if no content is found
+ * @return {String}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * let xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * let firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * firstChild.setContent('Mountain Goat');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Mountain Goat"
+ *
+ */
+ _main.default.XML.prototype.setContent = function(content) {
+ if (!this.DOM.children.length) {
+ this.DOM.textContent = content;
+ }
+ };
+
+ /**
+ * Serializes the element into a string. This function is useful for preparing
+ * the content to be sent over a http request or saved to file.
+ *
+ * @method serialize
+ * @return {String} Serialized string of the element
+ * @example
+ *
+ */
+ _main.default.XML.prototype.serialize = function() {
+ var xmlSerializer = new XMLSerializer();
+ return xmlSerializer.serializeToString(this.DOM);
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 84: [
+ 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 Calculation
+ * @for p5
+ * @requires core
+ */ /**
+ * Calculates the absolute value (magnitude) of a number. Maps to Math.abs().
+ * 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() {
+ * let x = -3;
+ * let y = abs(x);
+ *
+ * print(x); // -3
+ * print(y); // 3
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */ _main.default.prototype.abs = Math.abs; /**
+ * Calculates the closest int value that is greater than or equal to the
+ * value of the parameter. Maps to Math.ceil(). For example, ceil(9.03)
+ * returns the value 10.
+ *
+ * @method ceil
+ * @param {Number} n number to round up
+ * @return {Integer} rounded up number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * // map, mouseX between 0 and 5.
+ * let ax = map(mouseX, 0, 100, 0, 5);
+ * let ay = 66;
+ *
+ * //Get the ceiling of the mapped number.
+ * let bx = ceil(map(mouseX, 0, 100, 0, 5));
+ * let by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ * }
+ *
+ *
+ * @alt
+ * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals
+ */
+ _main.default.prototype.ceil = Math.ceil;
+
+ /**
+ * Constrains a value 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 draw() {
+ * background(200);
+ *
+ * let leftWall = 25;
+ * let rightWall = 75;
+ *
+ * // xm is just the mouseX, while
+ * // xc is the mouseX, but constrained
+ * // between the leftWall and rightWall!
+ * let xm = mouseX;
+ * let xc = constrain(mouseX, leftWall, rightWall);
+ *
+ * // Draw the walls.
+ * stroke(150);
+ * line(leftWall, 0, leftWall, height);
+ * line(rightWall, 0, rightWall, height);
+ *
+ * // Draw xm and xc as circles.
+ * noStroke();
+ * fill(150);
+ * ellipse(xm, 33, 9, 9); // Not Constrained
+ * fill(0);
+ * ellipse(xc, 66, 9, 9); // Constrained
+ * }
+ *
+ *
+ * @alt
+ * 2 vertical lines. 2 ellipses move with mouse X 1 does not move passed lines
+ */
+ _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, in either two or three dimensions.
+ *
+ * @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
+ *
+ * // Move your mouse inside the canvas to see the
+ * // change in distance between two points!
+ * function draw() {
+ * background(200);
+ * fill(0);
+ *
+ * let x1 = 10;
+ * let y1 = 90;
+ * let x2 = mouseX;
+ * let y2 = mouseY;
+ *
+ * line(x1, y1, x2, y2);
+ * ellipse(x1, y1, 7, 7);
+ * ellipse(x2, y2, 7, 7);
+ *
+ * // d is the length of the line
+ * // the distance from point 1 to point 2.
+ * let d = int(dist(x1, y1, x2, y2));
+ *
+ * // Let's write d along the line we are drawing!
+ * push();
+ * translate((x1 + x2) / 2, (y1 + y2) / 2);
+ * rotate(atan2(y2 - y1, x2 - x1));
+ * text(nfc(d, 1), 0, -5);
+ * pop();
+ * // Fancy!
+ * }
+ *
+ *
+ * @alt
+ * 2 ellipses joined by line. 1 ellipse moves with mouse X&Y. Distance displayed.
+ */
+ /**
+ * @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 hypot(args[2] - args[0], args[3] - args[1]);
+ } else if (args.length === 6) {
+ //3D
+ return hypot(args[3] - args[0], args[4] - args[1], args[5] - args[2]);
+ }
+ };
+
+ /**
+ * Returns Euler's number e (2.71828...) raised to the power of the n
+ * parameter. Maps to Math.exp().
+ *
+ * @method exp
+ * @param {Number} n exponent to raise
+ * @return {Number} e^n
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // Compute the exp() function with a value between 0 and 2
+ * let xValue = map(mouseX, 0, width, 0, 2);
+ * let yValue = exp(xValue);
+ *
+ * let y = map(yValue, 0, 8, height, 0);
+ *
+ * let legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4);
+ * stroke(150);
+ * line(mouseX, y, mouseX, height);
+ * fill(0);
+ * text(legend, 5, 15);
+ * noStroke();
+ * ellipse(mouseX, y, 7, 7);
+ *
+ * // Draw the exp(x) curve,
+ * // over the domain of x from 0 to 2
+ * noFill();
+ * stroke(0);
+ * beginShape();
+ * for (let x = 0; x < width; x++) {
+ * xValue = map(x, 0, width, 0, 2);
+ * yValue = exp(xValue);
+ * y = map(yValue, 0, 8, height, 0);
+ * vertex(x, y);
+ * }
+ *
+ * endShape();
+ * line(0, 0, 0, height);
+ * line(0, height - 1, width, height - 1);
+ * }
+ *
+ *
+ * @alt
+ * ellipse moves along a curve with mouse x. e^n displayed.
+ */
+ _main.default.prototype.exp = Math.exp;
+
+ /**
+ * Calculates the closest int value that is less than or equal to the
+ * value of the parameter. Maps to Math.floor().
+ *
+ * @method floor
+ * @param {Number} n number to round down
+ * @return {Integer} rounded down number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * //map, mouseX between 0 and 5.
+ * let ax = map(mouseX, 0, 100, 0, 5);
+ * let ay = 66;
+ *
+ * //Get the floor of the mapped number.
+ * let bx = floor(map(mouseX, 0, 100, 0, 5));
+ * let by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ * }
+ *
+ *
+ * @alt
+ * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals
+ */
+ _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 values where 0.0
+ * equal to the first point, 0.1 is very near the first point, 0.5 is
+ * half-way in between, and 1.0 is equal to the second point. If the
+ * value of amt is more than 1.0 or less than 0.0, the number will be
+ * calculated accordingly in the ratio of the two given numbers. The lerp
+ * function is convenient for creating motion along a straight
+ * path and for drawing dotted lines.
+ *
+ * @method lerp
+ * @param {Number} start first value
+ * @param {Number} stop second value
+ * @param {Number} amt number
+ * @return {Number} lerped value
+ * @example
+ *
+ * function setup() {
+ * background(200);
+ * 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);
+ *
+ * let y = 50;
+ *
+ * strokeWeight(5);
+ * stroke(0); // Draw the original points in black
+ * point(a, y);
+ * point(b, y);
+ *
+ * stroke(100); // Draw the lerp points in gray
+ * point(c, y);
+ * point(d, y);
+ * point(e, y);
+ * }
+ *
+ *
+ * @alt
+ * 5 points horizontally staggered mid-canvas. mid 3 are grey, outer black
+ */
+ _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. This
+ * function expects the n parameter to be a value greater than 0.0. Maps to
+ * Math.log().
+ *
+ * @method log
+ * @param {Number} n number greater than 0
+ * @return {Number} natural logarithm of n
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * let maxX = 2.8;
+ * let maxY = 1.5;
+ *
+ * // Compute the natural log of a value between 0 and maxX
+ * let xValue = map(mouseX, 0, width, 0, maxX);
+ * let yValue, y;
+ * if (xValue > 0) {
+ // Cannot take the log of a negative number.
+ * yValue = log(xValue);
+ * y = map(yValue, -maxY, maxY, height, 0);
+ *
+ * // Display the calculation occurring.
+ * let legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3);
+ * stroke(150);
+ * line(mouseX, y, mouseX, height);
+ * fill(0);
+ * text(legend, 5, 15);
+ * noStroke();
+ * ellipse(mouseX, y, 7, 7);
+ * }
+ *
+ * // Draw the log(x) curve,
+ * // over the domain of x from 0 to maxX
+ * noFill();
+ * stroke(0);
+ * beginShape();
+ * for (let x = 0; x < width; x++) {
+ * xValue = map(x, 0, width, 0, maxX);
+ * yValue = log(xValue);
+ * y = map(yValue, -maxY, maxY, height, 0);
+ * vertex(x, y);
+ * }
+ * endShape();
+ * line(0, 0, 0, height);
+ * line(0, height / 2, width, height / 2);
+ * }
+ *
+ *
+ * @alt
+ * ellipse moves along a curve with mouse x. natural logarithm of n displayed.
+ */
+ _main.default.prototype.log = Math.log;
+
+ /**
+ * Calculates the magnitude (or length) of a vector. A vector is a direction
+ * in space commonly used in computer graphics and linear algebra. Because it
+ * has no "start" position, the magnitude of a vector can be thought of as
+ * the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is
+ * a shortcut for writing dist(0, 0, x, y).
+ *
+ * @method mag
+ * @param {Number} a first value
+ * @param {Number} b second value
+ * @return {Number} magnitude of vector from (0,0) to (a,b)
+ * @example
+ *
+ * function setup() {
+ * let x1 = 20;
+ * let x2 = 80;
+ * let y1 = 30;
+ * let y2 = 70;
+ *
+ * line(0, 0, x1, y1);
+ * print(mag(x1, y1)); // Prints "36.05551275463989"
+ * line(0, 0, x2, y1);
+ * print(mag(x2, y1)); // Prints "85.44003745317531"
+ * line(0, 0, x1, y2);
+ * print(mag(x1, y2)); // Prints "72.80109889280519"
+ * line(0, 0, x2, y2);
+ * print(mag(x2, y2)); // Prints "106.3014581273465"
+ * }
+ *
+ *
+ * @alt
+ * 4 lines of different length radiate from top left of canvas.
+ */
+ _main.default.prototype.mag = function(x, y) {
+ _main.default._validateParameters('mag', arguments);
+ return hypot(x, y);
+ };
+
+ /**
+ * Re-maps a number from one range to another.
+ *
+ * In the first example above, the number 25 is converted from a value in the
+ * range of 0 to 100 into a value that ranges from the left edge of the
+ * window (0) to the right edge (width).
+ *
+ * @method map
+ * @param {Number} value the incoming value to be converted
+ * @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
+ *
+ * let value = 25;
+ * let m = map(value, 0, 100, 0, width);
+ * ellipse(m, 50, 10, 10);
+
+ *
+ *
+ * function setup() {
+ * noStroke();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * let x1 = map(mouseX, 0, width, 25, 75);
+ * ellipse(x1, 25, 25, 25);
+ * //This ellipse is constrained to the 0-100 range
+ * //after setting withinBounds to true
+ * let x2 = map(mouseX, 0, width, 0, 100, true);
+ * ellipse(x2, 75, 25, 25);
+ * }
+
+ *
+ * @alt
+ * 10 by 10 white ellipse with in mid left canvas
+ * 2 25 by 25 white ellipses move with mouse x. Bottom has more range from X
+ */
+ _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);
+ }
+ };
+
+ /**
+ * Determines the largest value in a sequence of numbers, and then returns
+ * that value. max() accepts any number of Number parameters, or an Array
+ * of any length.
+ *
+ * @method max
+ * @param {Number} n0 Number to compare
+ * @param {Number} n1 Number to compare
+ * @return {Number} maximum Number
+ * @example
+ *
+ * function setup() {
+ * // Change the elements in the array and run the sketch
+ * // to show how max() works!
+ * let numArray = [2, 1, 5, 4, 8, 9];
+ * fill(0);
+ * noStroke();
+ * text('Array Elements', 0, 10);
+ * // Draw all numbers in the array
+ * let spacing = 15;
+ * let elemsY = 25;
+ * for (let i = 0; i < numArray.length; i++) {
+ * text(numArray[i], i * spacing, elemsY);
+ * }
+ * let maxX = 33;
+ * let maxY = 80;
+ * // Draw the Maximum value in the array.
+ * textSize(32);
+ * text(max(numArray), maxX, maxY);
+ * }
+ *
+ *
+ * @alt
+ * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 9
+ */
+ /**
+ * @method max
+ * @param {Number[]} nums Numbers to compare
+ * @return {Number}
+ */
+ _main.default.prototype.max = function() {
+ for (
+ var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
+ _key2 < _len2;
+ _key2++
+ ) {
+ args[_key2] = arguments[_key2];
+ }
+ _main.default._validateParameters('max', args);
+ if (args[0] instanceof Array) {
+ return Math.max.apply(null, args[0]);
+ } else {
+ return Math.max.apply(null, args);
+ }
+ };
+
+ /**
+ * Determines the smallest value in a sequence of numbers, and then returns
+ * that value. min() accepts any number of Number parameters, or an Array
+ * of any length.
+ *
+ * @method min
+ * @param {Number} n0 Number to compare
+ * @param {Number} n1 Number to compare
+ * @return {Number} minimum Number
+ * @example
+ *
+ * function setup() {
+ * // Change the elements in the array and run the sketch
+ * // to show how min() works!
+ * let numArray = [2, 1, 5, 4, 8, 9];
+ * fill(0);
+ * noStroke();
+ * text('Array Elements', 0, 10);
+ * // Draw all numbers in the array
+ * let spacing = 15;
+ * let elemsY = 25;
+ * for (let i = 0; i < numArray.length; i++) {
+ * text(numArray[i], i * spacing, elemsY);
+ * }
+ * let maxX = 33;
+ * let maxY = 80;
+ * // Draw the Minimum value in the array.
+ * textSize(32);
+ * text(min(numArray), maxX, maxY);
+ * }
+ *
+ *
+ * @alt
+ * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 1
+ */
+ /**
+ * @method min
+ * @param {Number[]} nums Numbers to compare
+ * @return {Number}
+ */
+ _main.default.prototype.min = function() {
+ for (
+ var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
+ _key3 < _len3;
+ _key3++
+ ) {
+ args[_key3] = arguments[_key3];
+ }
+ _main.default._validateParameters('min', args);
+ if (args[0] instanceof Array) {
+ return Math.min.apply(null, args[0]);
+ } else {
+ return Math.min.apply(null, args);
+ }
+ };
+
+ /**
+ * Normalizes a number from another range into a value between 0 and 1.
+ * Identical to map(value, low, high, 0, 1).
+ * Numbers outside of the range are not clamped to 0 and 1, because
+ * out-of-range values are often intentional and useful. (See the example above.)
+ *
+ * @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 draw() {
+ * background(200);
+ * let currentNum = mouseX;
+ * let lowerBound = 0;
+ * let upperBound = width; //100;
+ * let normalized = norm(currentNum, lowerBound, upperBound);
+ * let lineY = 70;
+ * stroke(3);
+ * line(0, lineY, width, lineY);
+ * //Draw an ellipse mapped to the non-normalized value.
+ * noStroke();
+ * fill(50);
+ * let s = 7; // ellipse size
+ * ellipse(currentNum, lineY, s, s);
+ *
+ * // Draw the guide
+ * let guideY = lineY + 15;
+ * text('0', 0, guideY);
+ * textAlign(RIGHT);
+ * text('100', width, guideY);
+ *
+ * // Draw the normalized value
+ * textAlign(LEFT);
+ * fill(0);
+ * textSize(32);
+ * let normalY = 40;
+ * let normalX = 20;
+ * text(normalized, normalX, normalY);
+ * }
+ *
+ *
+ * @alt
+ * ellipse moves with mouse. 0 shown left & 100 right and updating values center
+ */
+ _main.default.prototype.norm = function(n, start, stop) {
+ _main.default._validateParameters('norm', arguments);
+ return this.map(n, start, stop, 0, 1);
+ };
+
+ /**
+ * Facilitates exponential expressions. The pow() function is an efficient
+ * way of multiplying numbers by themselves (or their reciprocals) in large
+ * quantities. For example, pow(3, 5) is equivalent to the expression
+ * 3 × 3 × 3 × 3 × 3 and pow(3, -5) is equivalent to 1 /
+ * 3 × 3 × 3 × 3 × 3. Maps to
+ * Math.pow().
+ *
+ * @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
+ *
+ *
+ * @alt
+ * small to large ellipses radiating from top left of canvas
+ */
+ _main.default.prototype.pow = Math.pow;
+
+ /**
+ * Calculates the integer closest to the n parameter. For example,
+ * round(133.8) returns the value 134. Maps to Math.round().
+ *
+ * @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
+ *
+ * let x = round(3.7);
+ * text(x, width / 2, height / 2);
+ *
+ *
+ * let x = round(12.782383, 2);
+ * text(x, width / 2, height / 2);
+ *
+ *
+ * function draw() {
+ * background(200);
+ * //map, mouseX between 0 and 5.
+ * let ax = map(mouseX, 0, 100, 0, 5);
+ * let ay = 66;
+ *
+ * // Round the mapped number.
+ * let bx = round(map(mouseX, 0, 100, 0, 5));
+ * let by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ * }
+ *
+ *
+ * @alt
+ * "3" written in middle of canvas
+ * "12.78" written in middle of canvas
+ * horizontal center line squared values displayed on top and regular on bottom.
+ */
+ _main.default.prototype.round = function(n, decimals) {
+ if (!decimals) {
+ return Math.round(n);
+ }
+ return Number(Math.round(n + 'e' + decimals) + 'e-' + decimals);
+ };
+
+ /**
+ * Squares a number (multiplies a number by itself). The result is always a
+ * positive number, as multiplying two negative numbers always yields a
+ * positive result. For example, -1 * -1 = 1.
+ *
+ * @method sq
+ * @param {Number} n number to square
+ * @return {Number} squared number
+ * @example
+ *
+ *
+ * @alt
+ * horizontal center line squared values displayed on top and regular on bottom.
+ */
+ _main.default.prototype.sq = function(n) {
+ return n * n;
+ };
+
+ /**
+ * Calculates the square root of a number. The square root of a number is
+ * always positive, even though there may be a valid negative root. The
+ * square root s of number a is such that s*s = a. It is the opposite of
+ * squaring. Maps to Math.sqrt().
+ *
+ * @method sqrt
+ * @param {Number} n non-negative number to square root
+ * @return {Number} square root of number
+ * @example
+ *
+ *
+ * @alt
+ * horizontal center line squareroot values displayed on top and regular on bottom.
+ */
+ _main.default.prototype.sqrt = Math.sqrt;
+
+ // Calculate the length of the hypotenuse of a right triangle
+ // This won't under- or overflow in intermediate steps
+ // https://en.wikipedia.org/wiki/Hypot
+ function hypot(x, y, z) {
+ // Use the native implementation if it's available
+ if (typeof Math.hypot === 'function') {
+ return Math.hypot.apply(null, arguments);
+ }
+
+ // Otherwise use the V8 implementation
+ // https://github.com/v8/v8/blob/8cd3cf297287e581a49e487067f5cbd991b27123/src/js/math.js#L217
+ var length = arguments.length;
+ var args = [];
+ var max = 0;
+ for (var i = 0; i < length; i++) {
+ var n = arguments[i];
+ n = +n;
+ if (n === Infinity || n === -Infinity) {
+ return Infinity;
+ }
+ n = Math.abs(n);
+ if (n > max) {
+ max = n;
+ }
+ args[i] = n;
+ }
+
+ if (max === 0) {
+ max = 1;
+ }
+ var sum = 0;
+ var compensation = 0;
+ for (var j = 0; j < length; j++) {
+ var m = args[j] / max;
+ var summand = m * m - compensation;
+ var preliminary = sum + summand;
+ compensation = preliminary - sum - summand;
+ sum = preliminary;
+ }
+ return Math.sqrt(sum) * max;
+ }
+
+ /**
+ * Calculates the fractional part of a number.
+ *
+ * @method fract
+ * @param {Number} num Number whose fractional part needs to be found out
+ * @returns {Number} fractional part of x, i.e, {x}
+ * @example
+ *
+ *
+ * @alt
+ * draws a line from center of canvas to mouse pointer position.
+ */ _main.default.prototype.createVector = function(x, y, z) {
+ if (this instanceof _main.default) {
+ return new _main.default.Vector(this, arguments);
+ } else {
+ return new _main.default.Vector(x, y, z);
+ }
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 86: [
+ 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.0 - Math.cos(i * Math.PI));
+ };
+ var perlin; // will be initialized lazily by noise() or noiseSeed()
+ /**
+ * Returns the Perlin noise value at specified coordinates. Perlin noise is
+ * a random sequence generator producing a more naturally ordered, harmonic
+ * succession of numbers compared to the standard random() function.
+ * It was invented by Ken Perlin in the 1980s and been used since in
+ * graphical applications to produce procedural textures, natural motion,
+ * shapes, terrains etc.
The main difference to the
+ * random() function is that Perlin noise is defined in an infinite
+ * n-dimensional space where each pair of coordinates corresponds to a
+ * fixed semi-random value (fixed only for the lifespan of the program; see
+ * the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise,
+ * depending on the number of coordinates given. The resulting value will
+ * always be between 0.0 and 1.0. The noise value can be animated by moving
+ * through the noise space as demonstrated in the example above. The 2nd
+ * and 3rd dimension can also be interpreted as time.
The actual
+ * noise is structured similar to an audio signal, in respect to the
+ * function's use of frequencies. Similar to the concept of harmonics in
+ * physics, perlin noise is computed over several octaves which are added
+ * together for the final result.
Another way to adjust the
+ * character of the resulting sequence is the scale of the input
+ * coordinates. As the function works within an infinite space the value of
+ * the coordinates doesn't matter as such, only the distance between
+ * successive coordinates does (eg. when using noise() within a
+ * loop). As a general rule the smaller the difference between coordinates,
+ * the smoother the resulting noise sequence will be. Steps of 0.005-0.03
+ * work best for most applications, but this will differ depending on use.
+ *
+ * @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 (between 0 and 1) at specified
+ * coordinates
+ * @example
+ *
+ *
+ * let xoff = 0.0;
+ *
+ * function draw() {
+ * background(204);
+ * xoff = xoff + 0.01;
+ * let n = noise(xoff) * width;
+ * line(n, 0, n, height);
+ * }
+ *
+ *
+ *
+ * let noiseScale=0.02;
+ *
+ * function draw() {
+ * background(0);
+ * for (let x=0; x < width; x++) {
+ * let noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);
+ * stroke(noiseVal*255);
+ * line(x, mouseY+noiseVal*80, x, height);
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical line moves left to right with updating noise values.
+ * horizontal wave pattern effected by mouse x-position & updating noise values.
+ */ _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.0) {
+ xi++;
+ xf--;
+ }
+ if (yf >= 1.0) {
+ yi++;
+ yf--;
+ }
+ if (zf >= 1.0) {
+ zi++;
+ zf--;
+ }
+ }
+ return r;
+ };
+
+ /**
+ *
+ * Adjusts the character and level of detail produced by the Perlin noise
+ * function. Similar to harmonics in physics, noise is computed over
+ * several octaves. Lower octaves contribute more to the output signal and
+ * as such define the overall intensity of the noise, whereas higher octaves
+ * create finer grained details in the noise sequence.
+ *
+ * By default, noise is computed over 4 octaves with each octave contributing
+ * exactly half than its predecessor, starting at 50% strength for the 1st
+ * octave. This falloff amount can be changed by adding an additional function
+ * parameter. Eg. a falloff factor of 0.75 means each octave will now have
+ * 75% impact (25% less) of the previous lower octave. Any value between
+ * 0.0 and 1.0 is valid, however note that values greater than 0.5 might
+ * result in greater than 1.0 values returned by noise().
+ *
+ * By changing these parameters, the signal created by the noise()
+ * function can be adapted to fit very specific needs and characteristics.
+ *
+ * @method noiseDetail
+ * @param {Number} lod number of octaves to be used by the noise
+ * @param {Number} falloff falloff factor for each octave
+ * @example
+ *
+ *
+ * @alt
+ * 2 vertical grey smokey patterns affected my mouse x-position and noise.
+ */
+ _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 noise(). By default, noise()
+ * produces different results each time the program is run. Set the
+ * value parameter to a constant to return the same pseudo-random
+ * numbers each time the software is run.
+ *
+ * @method noiseSeed
+ * @param {Number} seed the seed value
+ * @example
+ *
+ * let xoff = 0.0;
+ *
+ * function setup() {
+ * noiseSeed(99);
+ * stroke(0, 10);
+ * }
+ *
+ * function draw() {
+ * xoff = xoff + .01;
+ * let n = noise(xoff) * width;
+ * line(n, 0, n, height);
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical grey lines drawing in pattern affected by noise.
+ */
+ _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': 54 }
+ ],
+ 87: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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 Vector
+ * @requires constants
+ */ /**
+ * A class to describe a two or three dimensional vector, specifically
+ * a Euclidean (also known as geometric) vector. A vector is an entity
+ * that has both magnitude and direction. The datatype, however, stores
+ * the components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude
+ * and direction can be accessed via the methods mag() and heading().
+ *
+ * In many of the p5.js examples, you will see p5.Vector used to describe a
+ * position, velocity, or acceleration. For example, if you consider a rectangle
+ * moving across the screen, at any given instant it has a position (a vector
+ * that points from the origin to its location), a velocity (the rate at which
+ * the object's position changes per time unit, expressed as a vector), and
+ * acceleration (the rate at which the object's velocity changes per time
+ * unit, expressed as a vector).
+ *
+ * Since vectors represent groupings of values, we cannot simply use
+ * traditional addition/multiplication/etc. Instead, we'll need to do some
+ * "vector" math, which is made easy by the methods inside the p5.Vector 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
+ *
+ *
+ * @alt
+ * 2 white ellipses. One center-left the other bottom right and off canvas
+ */ _main.default.Vector = function Vector() {
+ var x, y, z;
+ // This is how it comes in with createVector()
+ if (arguments[0] instanceof _main.default) {
+ // save reference to p5 if passed in
+ this.p5 = arguments[0];
+ x = arguments[1][0] || 0;
+ y = arguments[1][1] || 0;
+ z = arguments[1][2] || 0;
+ // This is what we'll get with new p5.Vector()
+ } else {
+ x = arguments[0] || 0;
+ y = arguments[1] || 0;
+ z = arguments[2] || 0;
+ }
+ /**
+ * The x component of the vector
+ * @property x {Number}
+ */
+ this.x = x;
+ /**
+ * The y component of the vector
+ * @property y {Number}
+ */
+ this.y = y;
+ /**
+ * The z component of the vector
+ * @property z {Number}
+ */
+ this.z = z;
+ };
+
+ /**
+ * Returns a string representation of a vector v by calling String(v)
+ * or v.toString(). This method is useful for logging vectors in the
+ * console.
+ * @method toString
+ * @return {String}
+ * @example
+ *
+ *
+ * function setup() {
+ * let v = createVector(20, 30);
+ * print(String(v)); // prints "p5.Vector Object : [20, 30, 0]"
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'black');
+ *
+ * noStroke();
+ * text(v1.toString(), 10, 25, 90, 75);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.toString = function p5VectorToString() {
+ return 'p5.Vector Object : ['
+ .concat(this.x, ', ')
+ .concat(this.y, ', ')
+ .concat(this.z, ']');
+ };
+
+ /**
+ * Sets the x, y, and z component of the vector using two or three separate
+ * variables, the data from a p5.Vector, or the values from a float array.
+ * @method set
+ * @param {Number} [x] the x component of the vector
+ * @param {Number} [y] the y component of the vector
+ * @param {Number} [z] the z component of the vector
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * let v = createVector(1, 2, 3);
+ * v.set(4, 5, 6); // Sets vector to [4, 5, 6]
+ *
+ * let v1 = createVector(0, 0, 0);
+ * let arr = [1, 2, 3];
+ * v1.set(arr); // Sets vector to [1, 2, 3]
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.copy = function copy() {
+ if (this.p5) {
+ return new _main.default.Vector(this.p5, [this.x, this.y, this.z]);
+ } else {
+ return new _main.default.Vector(this.x, this.y, this.z);
+ }
+ };
+
+ /**
+ * Adds x, y, and z components to a vector, adds one vector to another, or
+ * adds two independent vectors together. The version of the method that adds
+ * two vectors together is a static method and returns a p5.Vector, the others
+ * acts directly on the vector. Additionally, you may provide arguments to this function as an array.
+ * See the examples for more context.
+ *
+ * @method add
+ * @param {Number} x the x component of the vector to be added
+ * @param {Number} [y] the y component of the vector to be added
+ * @param {Number} [z] the z component of the vector to be added
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(1, 2, 3);
+ * v.add(4, 5, 6);
+ * // v's components are set to [5, 7, 9]
+ *
+ *
+ *
+ *
+ *
+ * let v = createVector(1, 2, 3);
+ * // Provide arguments as an array
+ * let arr = [4, 5, 6];
+ * v.add(arr);
+ * // v's components are set to [5, 7, 9]
+ *
+ *
+ */
+ /**
+ * @method rem
+ * @param {p5.Vector | Number[]} value divisor vector
+ * @chainable
+ */
+ _main.default.Vector.prototype.rem = function rem(x, y, z) {
+ if (x instanceof _main.default.Vector) {
+ if (Number.isFinite(x.x) && Number.isFinite(x.y) && Number.isFinite(x.z)) {
+ var xComponent = parseFloat(x.x);
+ var yComponent = parseFloat(x.y);
+ var zComponent = parseFloat(x.z);
+ calculateRemainder3D.call(this, xComponent, yComponent, zComponent);
+ }
+ } else if (x instanceof Array) {
+ if (
+ x.every(function(element) {
+ return Number.isFinite(element);
+ })
+ ) {
+ if (x.length === 2) {
+ calculateRemainder2D.call(this, x[0], x[1]);
+ }
+ if (x.length === 3) {
+ calculateRemainder3D.call(this, x[0], x[1], x[2]);
+ }
+ }
+ } else if (arguments.length === 1) {
+ if (Number.isFinite(arguments[0]) && arguments[0] !== 0) {
+ this.x = this.x % arguments[0];
+ this.y = this.y % arguments[0];
+ this.z = this.z % arguments[0];
+ return this;
+ }
+ } else if (arguments.length === 2) {
+ var vectorComponents = Array.prototype.slice.call(arguments);
+ if (
+ vectorComponents.every(function(element) {
+ return Number.isFinite(element);
+ })
+ ) {
+ if (vectorComponents.length === 2) {
+ calculateRemainder2D.call(this, vectorComponents[0], vectorComponents[1]);
+ }
+ }
+ } else if (arguments.length === 3) {
+ var _vectorComponents = Array.prototype.slice.call(arguments);
+ if (
+ _vectorComponents.every(function(element) {
+ return Number.isFinite(element);
+ })
+ ) {
+ if (_vectorComponents.length === 3) {
+ calculateRemainder3D.call(
+ this,
+ _vectorComponents[0],
+ _vectorComponents[1],
+ _vectorComponents[2]
+ );
+ }
+ }
+ }
+ };
+
+ /**
+ * Subtracts x, y, and z components from a vector, subtracts one vector from
+ * another, or subtracts two independent vectors. The version of the method
+ * that subtracts two vectors is a static method and returns a p5.Vector, the
+ * other acts directly on the vector. Additionally, you may provide arguments to this function as an array.
+ * See the examples for more context.
+ *
+ * @method sub
+ * @param {Number} x the x component of the vector to subtract
+ * @param {Number} [y] the y component of the vector to subtract
+ * @param {Number} [z] the z component of the vector to subtract
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(4, 5, 6);
+ * v.sub(1, 1, 1);
+ * // v's components are set to [3, 4, 5]
+ *
+ *
+ *
+ *
+ *
+ * let v = createVector(4, 5, 6);
+ * // Provide arguments as an array
+ * let arr = [1, 1, 1];
+ * v.sub(arr);
+ * // v's components are set to [3, 4, 5]
+ *
+ *
+ *
+ * // red vector - blue vector = purple vector
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(70, 50);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let v2 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * let v3 = p5.Vector.sub(v1, v2);
+ * drawArrow(v2, v3, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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
+ */
+ _main.default.Vector.prototype.sub = 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 (x instanceof Array) {
+ 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 the vector by a scalar, multiplies the x, y, and z components from a vector, or multiplies
+ * the x, y, and z components of two independent vectors. When multiplying a vector by a scalar, the x, y,
+ * and z components of the vector are all multiplied by the scalar. When multiplying a vector by a vector,
+ * the x, y, z components of both vectors are multiplied by each other
+ * (for example, with two vectors a and b: a.x * b.x, a.y * b.y, a.z * b.z). The static version of this method
+ * creates a new p5.Vector while the non static version acts on the vector
+ * directly. Additionally, you may provide arguments to this function as an array.
+ * See the examples for more context.
+ *
+ * @method mult
+ * @param {Number} n The number to multiply with the vector
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(1, 2, 3);
+ * v.mult(2);
+ * // v's components are set to [2, 4, 6]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(1, 2, 3);
+ * let v1 = createVector(2, 3, 4);
+ * v0.mult(v1); // v0's components are set to [2, 6, 12]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(1, 2, 3);
+ * // Provide arguments as an array
+ * let arr = [2, 3, 4];
+ * v0.mult(arr); // v0's components are set to [2, 6, 12]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(1, 2, 3);
+ * let v1 = createVector(2, 3, 4);
+ * const result = p5.Vector.mult(v0, v1);
+ * print(result); // result's components are set to [2, 6, 12]
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = createVector(25, -25);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let num = map(mouseX, 0, width, -2, 2, true);
+ * let v2 = p5.Vector.mult(v1, num);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * noStroke();
+ * text('multiplied by ' + num.toFixed(2), 5, 90);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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 The number to multiply with the x component of the vector
+ * @param {Number} y The number to multiply with the y component of the vector
+ * @param {Number} [z] The number to multiply with the z component of the vector
+ * @chainable
+ */
+
+ /**
+ * @method mult
+ * @param {Number[]} arr The array to multiply with the components of the vector
+ * @chainable
+ */
+
+ /**
+ * @method mult
+ * @param {p5.Vector} v The vector to multiply with the components of the original vector
+ * @chainable
+ */
+
+ _main.default.Vector.prototype.mult = function mult(x, y, z) {
+ 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 (x instanceof Array) {
+ 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 = Array.prototype.slice.call(arguments);
+ if (
+ vectorComponents.every(function(element) {
+ return Number.isFinite(element);
+ }) &&
+ vectorComponents.every(function(element) {
+ return typeof element === 'number';
+ })
+ ) {
+ if (arguments.length === 1) {
+ this.x *= x;
+ this.y *= x;
+ this.z *= x;
+ }
+ if (arguments.length === 2) {
+ this.x *= x;
+ this.y *= y;
+ }
+ if (arguments.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 the vector by a scalar, divides a vector by the x, y, and z arguments, or divides the x, y, and
+ * z components of two vectors against each other. When dividing a vector by a scalar, the x, y,
+ * and z components of the vector are all divided by the scalar. When dividing a vector by a vector,
+ * the x, y, z components of the source vector are treated as the dividend, and the x, y, z components
+ * of the argument is treated as the divisor (for example with two vectors a and b: a.x / b.x, a.y / b.y, a.z / b.z).
+ * The static version of this method creates a
+ * new p5.Vector while the non static version acts on the vector directly.
+ * Additionally, you may provide arguments to this function as an array.
+ * See the examples for more context.
+ *
+ * @method div
+ * @param {number} n The number to divide the vector by
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(6, 4, 2);
+ * v.div(2); //v's components are set to [3, 2, 1]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(9, 4, 2);
+ * let v1 = createVector(3, 2, 4);
+ * v0.div(v1); // v0's components are set to [3, 2, 0.5]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(9, 4, 2);
+ * // Provide arguments as an array
+ * let arr = [3, 2, 4];
+ * v0.div(arr); // v0's components are set to [3, 2, 0.5]
+ *
+ *
+ *
+ *
+ *
+ * let v0 = createVector(9, 4, 2);
+ * let v1 = createVector(3, 2, 4);
+ * let result = p5.Vector.div(v0, v1);
+ * print(result); // result's components are set to [3, 2, 0.5]
+ *
+ *
+ *
+ * let v = createVector(20.0, 30.0, 40.0);
+ * let m = v.mag();
+ * print(m); // Prints "53.85164807134504"
+ *
+ *
+ */
+ _main.default.Vector.prototype.mag = function mag() {
+ return Math.sqrt(this.magSq());
+ };
+
+ /**
+ * 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
+ * @return {number} squared magnitude of the vector
+ * @example
+ *
+ */
+ _main.default.Vector.prototype.magSq = 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 version of the method
+ * that computes the dot product of two independent vectors is a static
+ * method. See the examples for more context.
+ *
+ * @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} the dot product
+ *
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = createVector(2, 3, 4);
+ *
+ * print(v1.dot(v2)); // Prints "20"
+ *
+ *
+ */
+ /**
+ * @method dot
+ * @param {p5.Vector} value value component of the vector or a p5.Vector
+ * @return {Number}
+ */
+ _main.default.Vector.prototype.dot = 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 and returns a vector composed of the cross product between
+ * two vectors. Both the static and non static methods return a new p5.Vector.
+ * See the examples for more context.
+ *
+ * @method cross
+ * @param {p5.Vector} v p5.Vector to be crossed
+ * @return {p5.Vector} p5.Vector composed of cross product
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 2, 3);
+ * let v2 = createVector(1, 2, 3);
+ *
+ * let v = v1.cross(v2); // v's components are [0, 0, 0]
+ * print(v);
+ *
+ *
+ */
+ _main.default.Vector.prototype.cross = 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.p5) {
+ return new _main.default.Vector(this.p5, [x, y, z]);
+ } else {
+ return new _main.default.Vector(x, y, z);
+ }
+ };
+
+ /**
+ * Calculates the Euclidean distance between two points (considering a
+ * point as a vector object).
+ *
+ * @method dist
+ * @param {p5.Vector} v the x, y, and z coordinates of a p5.Vector
+ * @return {Number} the distance
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 0, 0);
+ * let v2 = createVector(0, 1, 0);
+ *
+ * let distance = v1.dist(v2); // distance is 1.4142...
+ * print(distance);
+ *
+ *
+ */
+ _main.default.Vector.prototype.normalize = 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;
+ };
+
+ /**
+ * Limit the magnitude of this vector to the value used for the max
+ * parameter.
+ *
+ * @method limit
+ * @param {Number} max the maximum magnitude for the vector
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(10, 20, 2);
+ * // v has components [10.0, 20.0, 2.0]
+ * v.limit(5);
+ * // v's components are set to
+ * // [2.2271771, 4.4543543, 0.4454354]
+ *
+ *
+ */
+ _main.default.Vector.prototype.limit = function limit(max) {
+ var mSq = this.magSq();
+ if (mSq > max * max) {
+ this.div(Math.sqrt(mSq)) //normalize it
+ .mult(max);
+ }
+ return this;
+ };
+
+ /**
+ * Set the magnitude of this vector to the value used for the len
+ * parameter.
+ *
+ * @method setMag
+ * @param {number} len the new length for this vector
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(10, 20, 2);
+ * // v has components [10.0, 20.0, 2.0]
+ * v.setMag(10);
+ * // v's components are set to [6.0, 8.0, 0.0]
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(50, 50);
+ *
+ * drawArrow(v0, v1, 'red');
+ *
+ * let length = map(mouseX, 0, width, 0, 141, true);
+ * v1.setMag(length);
+ * drawArrow(v0, v1, 'blue');
+ *
+ * noStroke();
+ * text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.setMag = function setMag(n) {
+ return this.normalize().mult(n);
+ };
+
+ /**
+ * 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 degree accordingly.
+ *
+ * @method heading
+ * @return {Number} the angle of rotation
+ * @example
+ *
+ */
+ _main.default.Vector.prototype.heading = function heading() {
+ var h = Math.atan2(this.y, this.x);
+ if (this.p5) return this.p5._fromRadians(h);
+ return h;
+ };
+
+ /**
+ * Rotate the vector by an angle (only 2D vectors), magnitude remains the
+ * same
+ *
+ * @method rotate
+ * @param {number} angle the angle of rotation
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(10.0, 20.0);
+ * // v has components [10.0, 20.0, 0.0]
+ * v.rotate(HALF_PI);
+ * // v's components are set to [-20.0, 9.999999, 0.0]
+ *
+ *
+ *
+ *
+ *
+ * let angle = 0;
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = createVector(50, 0);
+ *
+ * drawArrow(v0, v1.rotate(angle), 'black');
+ * angle += 0.01;
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.rotate = function rotate(a) {
+ var newHeading = this.heading() + a;
+ if (this.p5) newHeading = this.p5._toRadians(newHeading);
+ var mag = this.mag();
+ this.x = Math.cos(newHeading) * mag;
+ this.y = Math.sin(newHeading) * mag;
+ return this;
+ };
+
+ /**
+ * Calculates and returns the angle (in radians) between two vectors.
+ * @method angleBetween
+ * @param {p5.Vector} value the x, y, and z components of a p5.Vector
+ * @return {Number} the angle between (in radians)
+ * @example
+ *
+ *
+ * let v1 = createVector(1, 0, 0);
+ * let v2 = createVector(0, 1, 0);
+ *
+ * let angle = v1.angleBetween(v2);
+ * // angle is PI/2
+ * print(angle);
+ *
+ *
+ */
+
+ _main.default.Vector.prototype.angleBetween = function angleBetween(v) {
+ var dotmagmag = this.dot(v) / (this.mag() * v.mag());
+ // Mathematically speaking: the dotmagmag variable will be between -1 and 1
+ // inclusive. Practically though it could be slightly outside this range due
+ // to floating-point rounding issues. This can make Math.acos return NaN.
+ //
+ // Solution: we'll clamp the value to the -1,1 range
+ var angle;
+ angle = Math.acos(Math.min(1, Math.max(-1, dotmagmag)));
+ angle = angle * Math.sign(this.cross(v).z || 1);
+ if (this.p5) {
+ angle = this.p5._fromRadians(angle);
+ }
+ return angle;
+ };
+ /**
+ * Linear interpolate the vector to another vector
+ *
+ * @method lerp
+ * @param {Number} x the x component
+ * @param {Number} y the y component
+ * @param {Number} z the z component
+ * @param {Number} amt the amount of interpolation; some value between 0.0
+ * (old vector) and 1.0 (new vector). 0.9 is very near
+ * the new vector. 0.5 is halfway in between.
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * let v = createVector(1, 1, 0);
+ *
+ * v.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]
+ *
+ *
+ */
+ /**
+ * @method lerp
+ * @param {p5.Vector} v the p5.Vector to lerp to
+ * @param {Number} amt
+ * @chainable
+ */
+ _main.default.Vector.prototype.lerp = 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;
+ };
+
+ /**
+ * Reflect the incoming vector about a normal to a line in 2D, or about a normal to a plane in 3D
+ * This method acts on the vector directly
+ *
+ * @method reflect
+ * @param {p5.Vector} surfaceNormal the p5.Vector to reflect about, will be normalized by this method
+ * @chainable
+ * @example
+ *
+ *
+ * let v = createVector(4, 6); // incoming vector, this example vector is heading to the right and downward
+ * let n = createVector(0, -1); // surface normal to a plane (this example normal points directly upwards)
+ * v.reflect(n); // v is reflected about the surface normal n. v's components are now set to [4, -6]
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(0, 0);
+ * let v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'red');
+ *
+ * let n = createVector(0, -30);
+ * drawArrow(v1, n, 'blue');
+ *
+ * let r = v1.copy();
+ * r.reflect(n);
+ * drawArrow(v1, r, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.prototype.reflect = function reflect(surfaceNormal) {
+ surfaceNormal.normalize();
+ return this.sub(surfaceNormal.mult(2 * this.dot(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
+ * array.
+ *
+ * @method array
+ * @return {Number[]} an Array with the 3 values
+ * @example
+ *
+ *
+ * function setup() {
+ * let v = createVector(20, 30);
+ * print(v.array()); // Prints : Array [20, 30, 0]
+ * }
+ *
+ *
+ *
+ *
+ *
+ * let v = createVector(10.0, 20.0, 30.0);
+ * let f = v.array();
+ * print(f[0]); // Prints "10.0"
+ * print(f[1]); // Prints "20.0"
+ * print(f[2]); // Prints "30.0"
+ *
+ *
+ */
+ _main.default.Vector.prototype.array = function array() {
+ return [this.x || 0, this.y || 0, this.z || 0];
+ };
+
+ /**
+ * Equality check against a p5.Vector
+ *
+ * @method equals
+ * @param {Number} [x] the x component of the vector
+ * @param {Number} [y] the y component of the vector
+ * @param {Number} [z] the z component of the vector
+ * @return {Boolean} whether the vectors are equals
+ * @example
+ *
+ */
+ /**
+ * @method equals
+ * @param {p5.Vector|Array} value the vector to compare
+ * @return {Boolean}
+ */
+ _main.default.Vector.prototype.equals = 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 (x instanceof Array) {
+ 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
+
+ /**
+ * Make a new 2D vector from an angle
+ *
+ * @method fromAngle
+ * @static
+ * @param {Number} angle the desired angle, in radians (unaffected by angleMode)
+ * @param {Number} [length] the length of the new vector (defaults to 1)
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // Create a variable, proportional to the mouseX,
+ * // varying from 0-360, to represent an angle in degrees.
+ * let myDegrees = map(mouseX, 0, width, 0, 360);
+ *
+ * // Display that variable in an onscreen text.
+ * // (Note the nfc() function to truncate additional decimal places,
+ * // and the "\xB0" character for the degree symbol.)
+ * let readout = 'angle = ' + nfc(myDegrees, 1) + '\xB0';
+ * noStroke();
+ * fill(0);
+ * text(readout, 5, 15);
+ *
+ * // Create a p5.Vector using the fromAngle function,
+ * // and extract its x and y components.
+ * let v = p5.Vector.fromAngle(radians(myDegrees), 30);
+ * let vx = v.x;
+ * let vy = v.y;
+ *
+ * push();
+ * translate(width / 2, height / 2);
+ * noFill();
+ * stroke(150);
+ * line(0, 0, 30, 0);
+ * stroke(0);
+ * line(0, 0, vx, vy);
+ * pop();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.fromAngle = function fromAngle(angle, length) {
+ if (typeof length === 'undefined') {
+ length = 1;
+ }
+ return new _main.default.Vector(
+ length * Math.cos(angle),
+ length * Math.sin(angle),
+ 0
+ );
+ };
+
+ /**
+ * Make a new 3D vector from a pair of ISO spherical angles
+ *
+ * @method fromAngles
+ * @static
+ * @param {Number} theta the polar angle, in radians (zero is up)
+ * @param {Number} phi the azimuthal angle, in radians
+ * (zero is out of the screen)
+ * @param {Number} [length] the length of the new vector (defaults to 1)
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * fill(255);
+ * noStroke();
+ * }
+ * function draw() {
+ * background(255);
+ *
+ * let t = millis() / 1000;
+ *
+ * // add three point lights
+ * pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));
+ * pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));
+ * pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));
+ *
+ * sphere(35);
+ * }
+ *
+ *
+ */
+ _main.default.Vector.fromAngles = function(theta, phi, length) {
+ if (typeof length === 'undefined') {
+ length = 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
+ );
+ };
+
+ /**
+ * Make a new 2D unit vector from a random angle
+ *
+ * @method random2D
+ * @static
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * let v = p5.Vector.random2D();
+ * // May make v's attributes something like:
+ * // [0.61554617, -0.51195765, 0.0] or
+ * // [-0.4695841, -0.14366731, 0.0] or
+ * // [0.6091097, -0.22805278, 0.0]
+ * print(v);
+ *
+ *
+ *
+ *
+ *
+ * function setup() {
+ * frameRate(1);
+ * }
+ *
+ * function draw() {
+ * background(240);
+ *
+ * let v0 = createVector(50, 50);
+ * let v1 = p5.Vector.random2D();
+ * drawArrow(v0, v1.mult(50), 'black');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * 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();
+ * }
+ *
+ *
+ */
+ _main.default.Vector.random2D = function random2D() {
+ return this.fromAngle(Math.random() * constants.TWO_PI);
+ };
+
+ /**
+ * Make a new random 3D unit vector.
+ *
+ * @method random3D
+ * @static
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * let v = p5.Vector.random3D();
+ * // May make v's attributes something like:
+ * // [0.61554617, -0.51195765, 0.599168] or
+ * // [-0.4695841, -0.14366731, -0.8711202] or
+ * // [0.6091097, -0.22805278, -0.7595902]
+ * print(v);
+ *
+ *
+ */
+ _main.default.Vector.random3D = 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);
+ };
+
+ // 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] the vector to receive the result (Optional)
+ * @return {p5.Vector} the resulting p5.Vector
+ */
+
+ _main.default.Vector.add = function add(v1, v2, target) {
+ if (!target) {
+ target = v1.copy();
+ if (arguments.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 dividend p5.Vector
+ * @param {p5.Vector} v2 divisor p5.Vector
+ */
+ /**
+ * @method rem
+ * @static
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} v2
+ * @return {p5.Vector} the resulting p5.Vector
+ */
+ _main.default.Vector.rem = 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] the vector to receive the result (Optional)
+ * @return {p5.Vector} the resulting p5.Vector
+ */
+
+ _main.default.Vector.sub = function sub(v1, v2, target) {
+ if (!target) {
+ target = v1.copy();
+ if (arguments.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} The resulting new p5.Vector
+ */
+
+ /**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v
+ * @param {Number} n
+ * @param {p5.Vector} [target] the vector to receive the result (Optional)
+ */
+
+ /**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v0
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} [target]
+ */
+
+ /**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v0
+ * @param {Number[]} arr
+ * @param {p5.Vector} [target]
+ */
+ _main.default.Vector.mult = function mult(v, n, target) {
+ if (!target) {
+ target = v.copy();
+ if (arguments.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;
+ };
+
+ /**
+ * 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 (Optional)
+ */
+
+ /**
+ * @method div
+ * @static
+ * @param {p5.Vector} v0
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} [target]
+ */
+
+ /**
+ * @method div
+ * @static
+ * @param {p5.Vector} v0
+ * @param {Number[]} arr
+ * @param {p5.Vector} [target]
+ */
+ _main.default.Vector.div = function div(v, n, target) {
+ if (!target) {
+ target = v.copy();
+
+ if (arguments.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 the first p5.Vector
+ * @param {p5.Vector} v2 the second p5.Vector
+ * @return {Number} the dot product
+ */
+ _main.default.Vector.dot = function dot(v1, v2) {
+ return v1.dot(v2);
+ };
+
+ /**
+ * Calculates the cross product of two vectors.
+ */
+ /**
+ * @method cross
+ * @static
+ * @param {p5.Vector} v1 the first p5.Vector
+ * @param {p5.Vector} v2 the second p5.Vector
+ * @return {Number} the cross product
+ */
+ _main.default.Vector.cross = 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
+ */
+ _main.default.Vector.dist = 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 (Optional)
+ * @return {p5.Vector} the lerped value
+ */
+ _main.default.Vector.lerp = function lerp(v1, v2, amt, target) {
+ if (!target) {
+ target = v1.copy();
+ if (arguments.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;
+ };
+
+ /**
+ * @method mag
+ * @param {p5.Vector} vecT the vector to return the magnitude of
+ * @return {Number} the magnitude of vecT
+ * @static
+ */
+ _main.default.Vector.mag = function mag(vecT) {
+ var x = vecT.x,
+ y = vecT.y,
+ z = vecT.z;
+ var magSq = x * x + y * y + z * z;
+ return Math.sqrt(magSq);
+ };
+ var _default = _main.default.Vector;
+ exports.default = _default;
+ },
+ { '../core/constants': 43, '../core/main': 54 }
+ ],
+ 88: [
+ 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 };
+ } /** // variables used for random number generators
+ * @module Math
+ * @submodule Random
+ * @for p5
+ * @requires core
+ */
+ 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 random().
+ *
+ * By default, random() produces different results each time the program
+ * is run. Set the seed parameter to a constant to return the same
+ * pseudo-random numbers each time the software is run.
+ *
+ * @method randomSeed
+ * @param {Number} seed the seed value
+ * @example
+ *
+ *
+ * randomSeed(99);
+ * for (let i = 0; i < 100; i++) {
+ * let r = random(0, 255);
+ * stroke(r);
+ * line(i, 0, i, 100);
+ * }
+ *
+ *
+ *
+ * @alt
+ * many vertical lines drawn in white, black or grey.
+ */
+ _main.default.prototype.randomSeed = function(seed) {
+ this._lcgSetSeed(randomStateProp, seed);
+ this._gaussian_previous = false;
+ };
+
+ /**
+ * Return a random floating-point number.
+ *
+ * Takes either 0, 1 or 2 arguments.
+ *
+ * If no argument is given, returns a random number from 0
+ * up to (but not including) 1.
+ *
+ * If one argument is given and it is a number, returns a random number from 0
+ * up to (but not including) the number.
+ *
+ * If one argument is given and it is an array, returns a random element from
+ * that array.
+ *
+ * If two arguments are given, returns a random number from the
+ * first argument up to (but not including) the second argument.
+ *
+ * @method random
+ * @param {Number} [min] the lower bound (inclusive)
+ * @param {Number} [max] the upper bound (exclusive)
+ * @return {Number} the random number
+ * @example
+ *
+ *
+ * for (let i = 0; i < 100; i++) {
+ * let r = random(50);
+ * stroke(r * 5);
+ * line(50, i, 50 + r, i);
+ * }
+ *
+ *
+ *
+ *
+ * for (let i = 0; i < 100; i++) {
+ * let r = random(-50, 50);
+ * line(50, i, 50 + r, i);
+ * }
+ *
+ *
+ *
+ *
+ * // Get a random element from an array using the random(Array) syntax
+ * let words = ['apple', 'bear', 'cat', 'dog'];
+ * let word = random(words); // select random word
+ * text(word, 10, 50); // draw the word
+ *
+ *
+ *
+ * @alt
+ * 100 horizontal lines from center canvas to right. size+fill change each time
+ * 100 horizontal lines from center of canvas. height & side change each render
+ * word displayed at random. Either apple, bear, cat, or dog
+ */
+ /**
+ * @method random
+ * @param {Array} choices the array to choose from
+ * @return {*} the 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 (min instanceof Array) {
+ 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. There is theoretically no minimum or maximum
+ * value that randomGaussian() might return. Rather, there is
+ * just a very low probability that values far from the mean will be
+ * returned; and a higher probability that numbers near the mean will
+ * be returned.
+ *
+ * Takes either 0, 1 or 2 arguments.
+ * If no args, returns a mean of 0 and standard deviation of 1.
+ * If one arg, that arg is the mean (standard deviation is 1).
+ * If two args, first is mean, second is standard deviation.
+ *
+ * @method randomGaussian
+ * @param {Number} mean the mean
+ * @param {Number} sd the standard deviation
+ * @return {Number} the random number
+ * @example
+ *
+ *
+ * for (let y = 0; y < 100; y++) {
+ * let x = randomGaussian(50, 15);
+ * line(50, y, x, y);
+ * }
+ *
+ *
+ *
+ *
+ * let distribution = new Array(360);
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * for (let i = 0; i < distribution.length; i++) {
+ * distribution[i] = floor(randomGaussian(0, 15));
+ * }
+ * }
+ *
+ * function draw() {
+ * background(204);
+ *
+ * translate(width / 2, width / 2);
+ *
+ * for (let i = 0; i < distribution.length; i++) {
+ * rotate(TWO_PI / distribution.length);
+ * stroke(0);
+ * let dist = abs(distribution[i]);
+ * line(0, 0, dist, 0);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * 100 horizontal lines from center of canvas. height & side change each render
+ * black lines radiate from center of canvas. size determined each render
+ */
+ _main.default.prototype.randomGaussian = function(mean, sd) {
+ 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;
+ var s = sd || 1;
+ return y1 * s + m;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 89: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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;
+ /**
+ * The inverse of cos(), returns the arc cosine of a value.
+ * This function expects the values in the range of -1 to 1 and values are returned in
+ * the range 0 to PI (3.1415927) if the angleMode is RADIANS or 0 to 180 if the
+ * angle mode is DEGREES.
+ *
+ * @method acos
+ * @param {Number} value the value whose arc cosine is to be returned
+ * @return {Number} the arc cosine of the given value
+ *
+ * @example
+ *
+ *
+ * let a = PI;
+ * let c = cos(a);
+ * let ac = acos(c);
+ * // Prints: "3.1415927 : -1.0 : 3.1415927"
+ * print(a + ' : ' + c + ' : ' + ac);
+ *
+ *
+ *
+ *
+ *
+ * let a = PI + PI / 4.0;
+ * let c = cos(a);
+ * let ac = acos(c);
+ * // Prints: "3.926991 : -0.70710665 : 2.3561943"
+ * print(a + ' : ' + c + ' : ' + ac);
+ *
+ *
+ */ _main.default.prototype.acos = function(ratio) {
+ return this._fromRadians(Math.acos(ratio));
+ };
+
+ /**
+ * The inverse of sin(), returns the arc sine of a value.
+ * This function expects the values in the range of -1 to 1 and values are returned
+ * in the range -PI/2 to PI/2 if the angleMode is RADIANS or -90 to 90 if the angle
+ * mode is DEGREES.
+ *
+ * @method asin
+ * @param {Number} value the value whose arc sine is to be returned
+ * @return {Number} the arc sine of the given value
+ *
+ * @example
+ *
+ *
+ * let a = PI / 3.0;
+ * let s = sin(a);
+ * let as = asin(s);
+ * // Prints: "1.0471975 : 0.86602540 : 1.0471975"
+ * print(a + ' : ' + s + ' : ' + as);
+ *
+ *
+ *
+ *
+ *
+ * let a = PI + PI / 3.0;
+ * let s = sin(a);
+ * let as = asin(s);
+ * // Prints: "4.1887902 : -0.86602540 : -1.0471975"
+ * print(a + ' : ' + s + ' : ' + as);
+ *
+ *
+ */
+ _main.default.prototype.asin = function(ratio) {
+ return this._fromRadians(Math.asin(ratio));
+ };
+
+ /**
+ * The inverse of tan(), returns the arc tangent of a value.
+ * This function expects the values in the range of -Infinity to Infinity (exclusive) and
+ * values are returned in the range -PI/2 to PI/2 if the angleMode is RADIANS or
+ * -90 to 90 if the angle mode is DEGREES.
+ *
+ * @method atan
+ * @param {Number} value the value whose arc tangent is to be returned
+ * @return {Number} the arc tangent of the given value
+ *
+ * @example
+ *
+ *
+ * let a = PI / 3.0;
+ * let t = tan(a);
+ * let at = atan(t);
+ * // Prints: "1.0471975 : 1.7320508 : 1.0471975"
+ * print(a + ' : ' + t + ' : ' + at);
+ *
+ *
+ *
+ *
+ *
+ * let a = PI + PI / 3.0;
+ * let t = tan(a);
+ * let at = atan(t);
+ * // Prints: "4.1887902 : 1.7320508 : 1.0471975"
+ * print(a + ' : ' + t + ' : ' + at);
+ *
+ *
+ */
+ _main.default.prototype.atan = function(ratio) {
+ return this._fromRadians(Math.atan(ratio));
+ };
+
+ /**
+ * Calculates the angle (in radians) from a specified point to the coordinate
+ * origin as measured from the positive x-axis. Values are returned as a
+ * float in the range from PI to -PI if the angleMode is RADIANS or 180 to
+ * -180 if the angleMode is DEGREES. The atan2() function is
+ * most often used for orienting geometry to the position of the cursor.
+ *
+ * Note: The y-coordinate of the point is the first parameter, and the
+ * x-coordinate is the second parameter, due the the structure of calculating
+ * the tangent.
+ *
+ * @method atan2
+ * @param {Number} y y-coordinate of the point
+ * @param {Number} x x-coordinate of the point
+ * @return {Number} the arc tangent of the given point
+ *
+ * @example
+ *
+ *
+ * @alt
+ * 60 by 10 rect at center of canvas rotates with mouse movements
+ */
+ _main.default.prototype.atan2 = function(y, x) {
+ return this._fromRadians(Math.atan2(y, x));
+ };
+
+ /**
+ * Calculates the cosine of an angle. This function takes into account the
+ * current angleMode. Values are returned in the range -1 to 1.
+ *
+ * @method cos
+ * @param {Number} angle the angle
+ * @return {Number} the cosine of the angle
+ *
+ * @example
+ *
+ *
+ * let a = 0.0;
+ * let inc = TWO_PI / 25.0;
+ * for (let i = 0; i < 25; i++) {
+ * line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);
+ * a = a + inc;
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black lines form wave patterns, extend-down on left and right side
+ */
+ _main.default.prototype.cos = function(angle) {
+ return Math.cos(this._toRadians(angle));
+ };
+
+ /**
+ * Calculates the sine of an angle. This function takes into account the
+ * current angleMode. Values are returned in the range -1 to 1.
+ *
+ * @method sin
+ * @param {Number} angle the angle
+ * @return {Number} the sine of the angle
+ *
+ * @example
+ *
+ *
+ * let a = 0.0;
+ * let inc = TWO_PI / 25.0;
+ * for (let i = 0; i < 25; i++) {
+ * line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);
+ * a = a + inc;
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black lines extend down and up from center to form wave pattern
+ */
+ _main.default.prototype.sin = function(angle) {
+ return Math.sin(this._toRadians(angle));
+ };
+
+ /**
+ * Calculates the tangent of an angle. This function takes into account
+ * the current angleMode. Values are returned in the range of all real numbers.
+ *
+ * @method tan
+ * @param {Number} angle the angle
+ * @return {Number} the tangent of the angle
+ *
+ * @example
+ *
+ *
+ * let a = 0.0;
+ * let inc = TWO_PI / 50.0;
+ * for (let i = 0; i < 100; i = i + 2) {
+ * line(i, 50, i, 50 + tan(a) * 2.0);
+ * a = a + inc;
+ * }
+ *
+ *
+ * @alt
+ * vertical black lines end down and up from center to form spike pattern
+ */
+ _main.default.prototype.tan = function(angle) {
+ return Math.tan(this._toRadians(angle));
+ };
+
+ /**
+ * Converts a radian measurement to its corresponding value in degrees.
+ * Radians and degrees are two ways of measuring the same thing. There are
+ * 360 degrees in a circle and 2*PI radians in a circle. For example,
+ * 90° = PI/2 = 1.5707964. This function does not take into account the
+ * current angleMode.
+ *
+ * @method degrees
+ * @param {Number} radians the radians value to convert to degrees
+ * @return {Number} the converted angle
+ *
+ * @example
+ *
+ *
+ * let rad = PI / 4;
+ * let deg = degrees(rad);
+ * print(rad + ' radians is ' + deg + ' degrees');
+ * // Prints: 0.7853981633974483 radians is 45 degrees
+ *
+ *
+ */
+ _main.default.prototype.degrees = function(angle) {
+ return angle * constants.RAD_TO_DEG;
+ };
+
+ /**
+ * Converts a degree measurement to its corresponding value in radians.
+ * Radians and degrees are two ways of measuring the same thing. There are
+ * 360 degrees in a circle and 2*PI radians in a circle. For example,
+ * 90° = PI/2 = 1.5707964. This function does not take into account the
+ * current angleMode.
+ *
+ * @method radians
+ * @param {Number} degrees the degree value to convert to radians
+ * @return {Number} the converted angle
+ *
+ * @example
+ *
+ *
+ * let deg = 45.0;
+ * let rad = radians(deg);
+ * print(deg + ' degrees is ' + rad + ' radians');
+ * // Prints: 45 degrees is 0.7853981633974483 radians
+ *
+ *
+ */
+ _main.default.prototype.radians = function(angle) {
+ return angle * constants.DEG_TO_RAD;
+ };
+
+ /**
+ * Sets the current mode of p5 to given mode. Default mode is RADIANS.
+ *
+ * @method angleMode
+ * @param {Constant} mode either RADIANS or DEGREES
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(204);
+ * angleMode(DEGREES); // Change the mode to DEGREES
+ * let a = atan2(mouseY - height / 2, mouseX - width / 2);
+ * translate(width / 2, height / 2);
+ * push();
+ * rotate(a);
+ * rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees
+ * pop();
+ * angleMode(RADIANS); // Change the mode to RADIANS
+ * rotate(a); // variable a stays the same
+ * rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians
+ * }
+ *
+ *
+ *
+ * @alt
+ * 40 by 10 rect in center rotates with mouse moves. 20 by 10 rect moves faster.
+ *
+ */
+ _main.default.prototype.angleMode = function(mode) {
+ if (mode === constants.DEGREES || mode === constants.RADIANS) {
+ 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;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/constants': 43, '../core/main': 54 }
+ ],
+ 90: [
+ 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 Typography
+ * @submodule Attributes
+ * @for p5
+ * @requires core
+ * @requires constants
+ */ /**
+ * Sets the current alignment for drawing text. Accepts two
+ * arguments: horizAlign (LEFT, CENTER, or RIGHT) and
+ * vertAlign (TOP, BOTTOM, CENTER, or BASELINE).
+ *
+ * The horizAlign parameter is in reference to the x value
+ * of the text() function, while the vertAlign parameter
+ * is in reference to the y value.
+ *
+ * So if you write textAlign(LEFT), you are aligning the left
+ * edge of your text to the x value you give in text().
+ * If you write textAlign(RIGHT, TOP), you are aligning the right edge
+ * of your text to the x value and the top of edge of the text
+ * to the y value.
+ *
+ * @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
+ *
+ *
+ * @alt
+ * Letters ABCD displayed at top left, EFGH at center and IJKL at bottom right.
+ * The names of the four vertical alignments (TOP, CENTER, BASELINE & BOTTOM) rendered each showing that alignment's placement relative to a horizontal line.
+ */ /**
+ * @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/gets the spacing, in pixels, between lines of text. This setting will be
+ * used in all subsequent calls to the text() function.
+ *
+ * @method textLeading
+ * @param {Number} leading the size in pixels for spacing between lines
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * @alt
+ * A set of L1 L2 & L3 displayed vertically 3 times. spacing increases for each set
+ */
+ /**
+ * @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/gets the current font size. This size will be used in all subsequent
+ * calls to the text() function. Font size is measured in pixels.
+ *
+ * @method textSize
+ * @param {Number} theSize the size of the letters in units of pixels
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * @alt
+ * Letter P and p5.js are displayed with vertical lines at end.
+ */
+ _main.default.prototype.textWidth = function() {
+ var _this$_renderer5;
+ 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;
+ }
+ return (_this$_renderer5 = this._renderer).textWidth.apply(
+ _this$_renderer5,
+ args
+ );
+ };
+
+ /**
+ * Returns 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}
+ * @example
+ *
+ *
+ * let base = height * 0.75;
+ * let scalar = 0.8; // Different for each font
+ *
+ * textSize(32); // Set initial text size
+ * let asc = textAscent() * scalar; // Calc ascent
+ * line(0, base - asc, width, base - asc);
+ * text('dp', 0, base); // Draw text on baseline
+ *
+ * textSize(64); // Increase text size
+ * asc = textAscent() * scalar; // Recalc ascent
+ * line(40, base - asc, width, base - asc);
+ * text('dp', 40, base); // Draw text on baseline
+ *
+ *
+ */
+ _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();
+ };
+
+ /**
+ * Returns 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}
+ * @example
+ *
+ *
+ * let base = height * 0.75;
+ * let scalar = 0.8; // Different for each font
+ *
+ * textSize(32); // Set initial text size
+ * let desc = textDescent() * scalar; // Calc ascent
+ * line(0, base + desc, width, base + desc);
+ * text('dp', 0, base); // Draw text on baseline
+ *
+ * textSize(64); // Increase text size
+ * desc = textDescent() * scalar; // Recalc ascent
+ * line(40, base + desc, width, base + desc);
+ * text('dp', 40, base); // Draw text on baseline
+ *
+ *
+ */
+ _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();
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 91: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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 an opentype font file (.otf, .ttf) from a file or a URL,
+ * and returns a PFont Object. This method is asynchronous,
+ * meaning it may not finish before the next line in your sketch
+ * is executed.
+ *
+ * The path to the font should be relative to the HTML file
+ * that links in your sketch. Loading fonts from a URL or other
+ * remote location may be blocked due to your browser's built-in
+ * security.
+ *
+ * @method loadFont
+ * @param {String} path name of the file or url to load
+ * @param {Function} [callback] function to be executed after
+ * loadFont() completes
+ * @param {Function} [onError] function to be executed if
+ * an error occurs
+ * @return {p5.Font} p5.Font object
+ * @example
+ *
+ * Calling loadFont() inside preload() guarantees
+ * that the load operation will have completed before setup()
+ * and draw() are called.
+ *
+ *
+ *
+ * @alt
+ * p5*js in p5's theme dark pink
+ * p5*js in p5's theme dark pink
+ */ _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.substr(lastDotIdx + 1);
+
+ // if so, add it to the DOM (name-only) for use with DOM module
+ if (validFontTypes.includes(fileExt)) {
+ fontFamily = fileNoPath.substr(0, lastDotIdx);
+ 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 screen. Displays the information specified in the first
+ * parameter on the screen in the position specified by the additional
+ * parameters. A default font will be used unless a font is set with the
+ * textFont() function and a default size will be
+ * used unless a font is set with textSize(). Change
+ * the color of the text with the fill() function. Change
+ * the outline of the text with the stroke() and
+ * strokeWeight() functions.
+ *
+ * The text displays in relation to the textAlign()
+ * function, which gives the option to draw to the left, right, and center of the
+ * coordinates.
+ *
+ * The x2 and y2 parameters define a rectangular area to display within and
+ * may only be used with string data. When these parameters are specified,
+ * they are interpreted based on the current rectMode()
+ * setting. Text that does not fit completely within the rectangle specified will
+ * not be drawn to the screen. If x2 and y2 are not specified, the baseline
+ * alignment is the default, which means that the text will be drawn upwards
+ * from x and y.
+ *
+ * WEBGL: Only opentype/truetype fonts are supported. You must load a font
+ * using the loadFont() method (see the example above).
+ * stroke() currently has no effect in webgl mode.
+ *
+ * @method text
+ * @param {String|Object|Array|Number|Boolean} str the alphanumeric
+ * symbols to be displayed
+ * @param {Number} x x-coordinate of text
+ * @param {Number} y y-coordinate of text
+ * @param {Number} [x2] by default, the width of the text box,
+ * see rectMode() for more info
+ * @param {Number} [y2] by default, the height of the text box,
+ * see rectMode() for more info
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * 'word' displayed 3 times going from black, blue to translucent blue
+ * The text 'The quick brown fox jumped over the lazy dog' displayed.
+ * The text 'p5.js' 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 current font that will be drawn with the text() function.
+ *
+ * WEBGL: Only fonts loaded via loadFont() are supported.
+ *
+ * @method textFont
+ * @return {Object} the current font
+ *
+ * @example
+ *
+ */ _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
+ * @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
+ *
+ */
+ _main.default.prototype.shorten = function(list) {
+ list.pop();
+ return list;
+ };
+
+ /**
+ * Randomizes the order of the elements of an array. Implements
+ *
+ * Fisher-Yates Shuffle Algorithm.
+ *
+ * @method shuffle
+ * @param {Array} array Array to shuffle
+ * @param {Boolean} [bool] modify passed array
+ * @return {Array} shuffled Array
+ * @example
+ *
+ * function setup() {
+ * let regularArr = ['ABC', 'def', createVector(), TAU, Math.E];
+ * print(regularArr);
+ * shuffle(regularArr, true); // force modifications to passed array
+ * print(regularArr);
+ *
+ * // By default shuffle() returns a shuffled cloned array:
+ * let newArr = shuffle(regularArr);
+ * print(regularArr);
+ * print(newArr);
+ * }
+ *
+ */
+ _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
+ *
+ */
+ _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
+ *
+ *
+ * @alt
+ * 20 by 20 white ellipse in the center of the canvas
+ */ _main.default.prototype.float = function(str) {
+ if (str instanceof Array) {
+ return str.map(parseFloat);
+ }
+ return parseFloat(str);
+ };
+
+ /**
+ * Converts a boolean, string, or float to its integer representation.
+ * When an array of values is passed in, then an int array of the same length
+ * is returned.
+ *
+ * @method int
+ * @param {String|Boolean|Number} n value to parse
+ * @param {Integer} [radix] the radix to convert to (default: 10)
+ * @return {Number} integer representation of value
+ *
+ * @example
+ *
+ */
+ _main.default.prototype.str = function(n) {
+ if (n instanceof Array) {
+ return n.map(_main.default.prototype.str);
+ } else {
+ return String(n);
+ }
+ };
+
+ /**
+ * Converts a number or string to its boolean representation.
+ * For a number, any non-zero value (positive or negative) evaluates to true,
+ * while zero evaluates to false. For a string, the value "true" evaluates to
+ * true, while any other value evaluates to false. When an array of number or
+ * string values is passed in, then a array of booleans of the same length is
+ * returned.
+ *
+ * @method boolean
+ * @param {String|Boolean|Number|Array} n value to parse
+ * @return {Boolean} boolean representation of value
+ * @example
+ *
+ */
+ _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 number, string representation of a number, or boolean to its byte
+ * representation. A byte can be only a whole number between -128 and 127, so
+ * when a value outside of this range is converted, it wraps around to the
+ * corresponding byte representation. When an array of number, string or boolean
+ * values is passed in, then an array of bytes the same length is returned.
+ *
+ * @method byte
+ * @param {String|Boolean|Number} n value to parse
+ * @return {Number} byte representation of value
+ *
+ * @example
+ *
+ */
+ /**
+ * @method byte
+ * @param {Array} ns values to parse
+ * @return {Number[]} array of byte representation of 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 its corresponding single-character
+ * string representation. If a string parameter is provided, it is first
+ * parsed as an integer and then translated into a single-character string.
+ * When an array of number or string values is passed in, then an array of
+ * single-character strings of the same length is returned.
+ *
+ * @method char
+ * @param {String|Number} n value to parse
+ * @return {String} string representation of value
+ *
+ * @example
+ *
+ */
+ /**
+ * @method unchar
+ * @param {Array} ns values to parse
+ * @return {Number[]} integer representation of values
+ */
+ _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 in its equivalent hexadecimal notation. If a
+ * second parameter is passed, it is used to set the number of characters to
+ * generate in the hexadecimal notation. When an array is passed in, an
+ * array of strings in hexadecimal notation of the same length is returned.
+ *
+ * @method hex
+ * @param {Number} n value to parse
+ * @param {Number} [digits]
+ * @return {String} hexadecimal string representation of value
+ *
+ * @example
+ *
+ *
+ * @alt
+ * "hello world!" displayed middle left of canvas.
+ */ _main.default.prototype.join = function(list, separator) {
+ _main.default._validateParameters('join', arguments);
+ return list.join(separator);
+ };
+
+ /**
+ * This function is used to apply a regular expression to a piece of text,
+ * and return matching groups (elements found inside parentheses) as a
+ * String array. If there are no matches, a null value will be returned.
+ * If no groups are specified in the regular expression, but the sequence
+ * matches, an array of length 1 (with the matched text as the first element
+ * of the array) will be returned.
+ *
+ * To use the function, first check to see if the result is null. If the
+ * result is null, then the sequence did not match at all. If the sequence
+ * did match, an array is returned.
+ *
+ * If there are groups (specified by sets of parentheses) in the regular
+ * expression, then the contents of each will be returned in the array.
+ * Element [0] of a regular expression match returns the entire matching
+ * string, and the match groups start at element [1] (the first group is [1],
+ * the second [2], and so on).
+ *
+ * @method match
+ * @param {String} str the String to be searched
+ * @param {String} regexp the regexp to be used for matching
+ * @return {String[]} Array of Strings found
+ * @example
+ *
+ *
+ * let string = 'Hello p5js*!';
+ * let regexp = 'p5js\\*';
+ * let m = match(string, regexp);
+ * text(m, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * "p5js*" displayed middle left of canvas.
+ */
+ _main.default.prototype.match = function(str, reg) {
+ _main.default._validateParameters('match', arguments);
+ return str.match(reg);
+ };
+
+ /**
+ * This function is used to apply a regular expression to a piece of text,
+ * and return a list of matching groups (elements found inside parentheses)
+ * as a two-dimensional String array. If there are no matches, a null value
+ * will be returned. If no groups are specified in the regular expression,
+ * but the sequence matches, a two dimensional array is still returned, but
+ * the second dimension is only of length one.
+ *
+ * To use the function, first check to see if the result is null. If the
+ * result is null, then the sequence did not match at all. If the sequence
+ * did match, a 2D array is returned.
+ *
+ * If there are groups (specified by sets of parentheses) in the regular
+ * expression, then the contents of each will be returned in the array.
+ * Assuming a loop with counter variable i, element [i][0] of a regular
+ * expression match returns the entire matching string, and the match groups
+ * start at element [i][1] (the first group is [i][1], the second [i][2],
+ * and so on).
+ *
+ * @method matchAll
+ * @param {String} str the String to be searched
+ * @param {String} regexp the regexp to be used for matching
+ * @return {String[]} 2d Array of Strings found
+ * @example
+ *
+ */
+ _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;
+ };
+
+ /**
+ * Utility function for formatting numbers into strings. There are two
+ * versions: one for formatting floats, and one for formatting ints.
+ * The values for the digits, left, and right parameters should always
+ * be positive integers.
+ * (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter
+ * if greater than the current length of the number.
+ * For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123
+ * (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than
+ * the result will be 123.200.
+ *
+ * @method nf
+ * @param {Number|String} num the Number to format
+ * @param {Integer|String} [left] number of digits to the left of the
+ * decimal point
+ * @param {Integer|String} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * @alt
+ * "11,253,106.115" top middle and "1.00,1.00,2.00" displayed bottom mid
+ */
+ /**
+ * @method nfc
+ * @param {Array} nums the 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;
+ }
+
+ /**
+ * Utility function for formatting numbers into strings. Similar to nf() but
+ * puts a "+" in front of positive numbers and a "-" in front of negative
+ * numbers. There are two versions: one for formatting floats, and one for
+ * formatting ints. The values for left, and right parameters
+ * should always be positive integers.
+ *
+ * @method nfp
+ * @param {Number} num the Number to format
+ * @param {Integer} [left] number of digits to the left of the decimal
+ * point
+ * @param {Integer} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * @alt
+ * "+11253106.11" top middle and "-11253106.11" displayed bottom middle
+ */
+ /**
+ * @method nfp
+ * @param {Number[]} nums the 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();
+ }
+
+ /**
+ * Utility function for formatting numbers into strings. Similar to nf() but
+ * puts an additional "_" (space) in front of positive numbers just in case to align it with negative
+ * numbers which includes "-" (minus) sign.
+ * The main usecase of nfs() can be seen when one wants to align the digits (place values) of a non-negative
+ * number with some negative number (See the example to get a clear picture).
+ * There are two versions: one for formatting float, and one for formatting int.
+ * The values for the digits, left, and right parameters should always be positive integers.
+ * (IMP): The result on the canvas basically the expected alignment can vary based on the typeface you are using.
+ * (NOTE): Be cautious when using left and right parameters as it prepends numbers of 0's if the parameter
+ * if greater than the current length of the number.
+ * For example if number is 123.2 and left parameter passed is 4 which is greater than length of 123
+ * (integer part) i.e 3 than result will be 0123.2. Same case for right parameter i.e. if right is 3 than
+ * the result will be 123.200.
+ *
+ * @method nfs
+ * @param {Number} num the Number to format
+ * @param {Integer} [left] number of digits to the left of the decimal
+ * point
+ * @param {Integer} [right] number of digits to the right of the
+ * decimal point
+ * @return {String} formatted String
+ *
+ * @example
+ *
+ *
+ * let myFont;
+ * function preload() {
+ * myFont = loadFont('assets/fonts/inconsolata.ttf');
+ * }
+ * function setup() {
+ * background(200);
+ * let num1 = 321;
+ * let num2 = -1321;
+ *
+ * noStroke();
+ * fill(0);
+ * textFont(myFont);
+ * textSize(22);
+ *
+ * // nfs() aligns num1 (positive number) with num2 (negative number) by
+ * // adding a blank space in front of the num1 (positive number)
+ * // [left = 4] in num1 add one 0 in front, to align the digits with num2
+ * // [right = 2] in num1 and num2 adds two 0's after both numbers
+ * // To see the differences check the example of nf() too.
+ * text(nfs(num1, 4, 2), 10, 30);
+ * text(nfs(num2, 4, 2), 10, 80);
+ * // Draw dividing line
+ * stroke(120);
+ * line(0, 50, width, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * "0321.00" top middle and "-1321.00" displayed bottom middle
+ */
+ /**
+ * @method nfs
+ * @param {Array} nums the 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();
+ }
+
+ /**
+ * The split() function maps to String.split(), it breaks a String into
+ * pieces using a character or string as the delimiter. The delim parameter
+ * specifies the character or characters that mark the boundaries between
+ * each piece. A String[] array is returned that contains each of the pieces.
+ *
+ * The splitTokens() function works in a similar fashion, except that it
+ * splits using a range of characters instead of a specific character or
+ * sequence.
+ *
+ * @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
+ *
+ *
+ * @alt
+ * "pat" top left, "Xio" mid left and "Alex" displayed bottom left
+ */
+ _main.default.prototype.split = function(str, delim) {
+ _main.default._validateParameters('split', arguments);
+ return str.split(delim);
+ };
+
+ /**
+ * The splitTokens() function splits a String at one or many character
+ * delimiters or "tokens." The delim parameter specifies the character or
+ * characters to be used as a boundary.
+ *
+ * If no delim characters are specified, 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 the String to be split
+ * @param {String} [delim] list of individual Strings that will be used as
+ * separators
+ * @return {String[]} Array of Strings
+ * @example
+ *
+ *
+ * function setup() {
+ * let myStr = 'Mango, Banana, Lime';
+ * let myStrArr = splitTokens(myStr, ',');
+ *
+ * print(myStrArr); // prints : ["Mango"," Banana"," Lime"]
+ * }
+ *
+ *
+ */
+ _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 characters from the beginning and end of a String. In
+ * addition to standard whitespace characters such as space, carriage return,
+ * and tab, this function also removes the Unicode "nbsp" character.
+ *
+ * @method trim
+ * @param {String} str a String to be trimmed
+ * @return {String} a trimmed String
+ *
+ * @example
+ *
+ *
+ * let string = trim(' No new lines\n ');
+ * text(string + ' here', 2, 50);
+ *
+ *
+ *
+ * @alt
+ * "No new lines here" displayed center canvas
+ */
+ /**
+ * @method trim
+ * @param {Array} strs an Array of Strings to be trimmed
+ * @return {String[]} an Array of 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': 46,
+ '../core/friendly_errors/file_errors': 47,
+ '../core/friendly_errors/validate_params': 49,
+ '../core/main': 54
+ }
+ ],
+ 96: [
+ 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
+ */ /**
+ * p5.js communicates with the clock on your computer. The day() function
+ * returns the current day as a value from 1 - 31.
+ *
+ * @method day
+ * @return {Integer} the current day
+ * @example
+ *
+ *
+ * @alt
+ * Current day is displayed
+ */ _main.default.prototype.day = function() {
+ return new Date().getDate();
+ };
+
+ /**
+ * p5.js communicates with the clock on your computer. The hour() function
+ * returns the current hour as a value from 0 - 23.
+ *
+ * @method hour
+ * @return {Integer} the current hour
+ * @example
+ *
+ *
+ * let h = hour();
+ * text('Current hour:\n' + h, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current hour is displayed
+ */
+ _main.default.prototype.hour = function() {
+ return new Date().getHours();
+ };
+
+ /**
+ * p5.js communicates with the clock on your computer. The minute() function
+ * returns the current minute as a value from 0 - 59.
+ *
+ * @method minute
+ * @return {Integer} the current minute
+ * @example
+ *
+ *
+ * let m = minute();
+ * text('Current minute: \n' + m, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current minute is displayed
+ */
+ _main.default.prototype.minute = function() {
+ return new Date().getMinutes();
+ };
+
+ /**
+ * Returns the number of milliseconds (thousandths of a second) since
+ * starting the sketch (when `setup()` is called). This information is often
+ * used for timing events and animation sequences.
+ *
+ * @method millis
+ * @return {Number} the number of milliseconds since starting the sketch
+ * @example
+ *
+ *
+ * @alt
+ * number of milliseconds since sketch has started displayed
+ */
+ _main.default.prototype.millis = function() {
+ if (this._millisStart === -1) {
+ // Sketch has not started
+ return 0;
+ } else {
+ return window.performance.now() - this._millisStart;
+ }
+ };
+
+ /**
+ * p5.js communicates with the clock on your computer. The month() function
+ * returns the current month as a value from 1 - 12.
+ *
+ * @method month
+ * @return {Integer} the current month
+ * @example
+ *
+ *
+ * let m = month();
+ * text('Current month: \n' + m, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current month is displayed
+ */
+ _main.default.prototype.month = function() {
+ //January is 0!
+ return new Date().getMonth() + 1;
+ };
+
+ /**
+ * p5.js communicates with the clock on your computer. The second() function
+ * returns the current second as a value from 0 - 59.
+ *
+ * @method second
+ * @return {Integer} the current second
+ * @example
+ *
+ *
+ * @alt
+ * Current second is displayed
+ */
+ _main.default.prototype.second = function() {
+ return new Date().getSeconds();
+ };
+
+ /**
+ * p5.js communicates with the clock on your computer. The year() function
+ * returns the current year as an integer (2014, 2015, 2016, etc).
+ *
+ * @method year
+ * @return {Integer} the current year
+ * @example
+ *
+ *
+ * let y = year();
+ * text('Current year: \n' + y, 5, 50);
+ *
+ *
+ *
+ * @alt
+ * Current year is displayed
+ */
+ _main.default.prototype.year = function() {
+ return new Date().getFullYear();
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 97: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ 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);
+ }
+ 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
+ */ /**
+ * Draw a plane with given a width and height
+ * @method plane
+ * @param {Number} [width] width of the plane
+ * @param {Number} [height] height of the plane
+ * @param {Integer} [detailX] Optional number of triangle
+ * subdivisions in x-dimension
+ * @param {Integer} [detailY] Optional number of triangle
+ * subdivisions in y-dimension
+ * @chainable
+ * @example
+ *
+ */
+ _main.default.prototype.ellipsoid = function(
+ radiusX,
+ radiusY,
+ radiusZ,
+ detailX,
+ detailY
+ ) {
+ this._assert3d('ellipsoid');
+ _main.default._validateParameters('ellipsoid', arguments);
+ if (typeof radiusX === 'undefined') {
+ radiusX = 50;
+ }
+ if (typeof radiusY === 'undefined') {
+ radiusY = radiusX;
+ }
+ if (typeof radiusZ === 'undefined') {
+ radiusZ = radiusX;
+ }
+
+ if (typeof detailX === 'undefined') {
+ detailX = 24;
+ }
+ if (typeof detailY === 'undefined') {
+ detailY = 16;
+ }
+
+ 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;
+ };
+
+ /**
+ * Draw a torus with given radius and tube radius
+ *
+ * DetailX and detailY determine the number of subdivisions in the x-dimension and
+ * the y-dimension of a torus. More subdivisions make the torus appear to be smoother.
+ * The default and maximum values for detailX and detailY are 24 and 16, respectively.
+ * Setting them to relatively small values like 4 and 6 allows you to create new
+ * shapes other than a torus.
+ * @method torus
+ * @param {Number} [radius] radius of the whole ring
+ * @param {Number} [tubeRadius] radius of the tube
+ * @param {Integer} [detailX] number of segments in x-dimension,
+ * the more segments the smoother geometry
+ * default is 24
+ * @param {Integer} [detailY] number of segments in y-dimension,
+ * the more segments the smoother geometry
+ * default is 16
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Camera orbits around a box when mouse is hold-clicked & then moved.
+ */
+ // https://github.com/mrdoob/three.js/blob/dev/examples/js/controls/OrbitControls.js
+ _main.default.prototype.orbitControl = function(
+ sensitivityX,
+ sensitivityY,
+ sensitivityZ
+ ) {
+ this._assert3d('orbitControl');
+ _main.default._validateParameters('orbitControl', arguments);
+
+ // If the mouse is not in bounds of the canvas, disable all behaviors:
+ var mouseInCanvas =
+ this.mouseX < this.width &&
+ this.mouseX > 0 &&
+ this.mouseY < this.height &&
+ this.mouseY > 0;
+ if (!mouseInCanvas) return;
+
+ var cam = this._renderer._curCamera;
+
+ if (typeof sensitivityX === 'undefined') {
+ sensitivityX = 1;
+ }
+ if (typeof sensitivityY === 'undefined') {
+ sensitivityY = sensitivityX;
+ }
+ if (typeof sensitivityZ === 'undefined') {
+ sensitivityZ = 0.5;
+ }
+
+ // 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
+
+ // 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);
+ }
+
+ var scaleFactor = this.height < this.width ? this.height : this.width;
+
+ // ZOOM if there is a change in mouseWheelDelta
+ if (this._mouseWheelDeltaY !== this._pmouseWheelDeltaY) {
+ // zoom according to direction of mouseWheelDeltaY rather than value
+ if (this._mouseWheelDeltaY > 0) {
+ this._renderer._curCamera._orbit(0, 0, sensitivityZ * scaleFactor);
+ } else {
+ this._renderer._curCamera._orbit(0, 0, -sensitivityZ * scaleFactor);
+ }
+ }
+
+ if (this.mouseIsPressed) {
+ // ORBIT BEHAVIOR
+ if (this.mouseButton === this.LEFT) {
+ var deltaTheta = -sensitivityX * (this.mouseX - this.pmouseX) / scaleFactor;
+ var deltaPhi = sensitivityY * (this.mouseY - this.pmouseY) / scaleFactor;
+ this._renderer._curCamera._orbit(deltaTheta, deltaPhi, 0);
+ } else if (this.mouseButton === this.RIGHT) {
+ // PANNING BEHAVIOR along X/Z camera axes and restricted to X/Z plane
+ // in world space
+ var local = cam._getLocalAxes();
+
+ // normalize portions along X/Z axes
+ var xmag = Math.sqrt(local.x[0] * local.x[0] + local.x[2] * local.x[2]);
+ if (xmag !== 0) {
+ local.x[0] /= xmag;
+ local.x[2] /= xmag;
+ }
+
+ // normalize portions along X/Z axes
+ var ymag = Math.sqrt(local.y[0] * local.y[0] + local.y[2] * local.y[2]);
+ if (ymag !== 0) {
+ local.y[0] /= ymag;
+ local.y[2] /= ymag;
+ }
+
+ // move along those vectors by amount controlled by mouseX, pmouseY
+ var dx = -1 * sensitivityX * (this.mouseX - this.pmouseX);
+ var dz = -1 * sensitivityY * (this.mouseY - this.pmouseY);
+
+ // restrict movement to XZ plane in world space
+ cam.setPosition(
+ cam.eyeX + dx * local.x[0] + dz * local.z[0],
+ cam.eyeY,
+ cam.eyeZ + dx * local.x[2] + dz * local.z[2]
+ );
+ }
+ }
+ return this;
+ };
+
+ /**
+ * debugMode() helps visualize 3D space by adding a grid to indicate where the
+ * ‘ground’ is in a sketch and an axes icon which indicates the +X, +Y, and +Z
+ * directions. This function can be called without parameters to create a
+ * default grid and axes icon, or it can be called according to the examples
+ * above to customize the size and position of the grid and/or axes icon. The
+ * grid is drawn using the most recently set stroke color and weight. To
+ * specify these parameters, add a call to stroke() and strokeWeight()
+ * just before the end of the draw() loop.
+ *
+ * By default, the grid will run through the origin (0,0,0) of the sketch
+ * along the XZ plane
+ * and the axes icon will be offset from the origin. Both the grid and axes
+ * icon will be sized according to the current canvas size. Note that because the
+ * grid runs parallel to the default camera view, it is often helpful to use
+ * debugMode along with orbitControl to allow full view of the grid.
+ * @method debugMode
+ * @example
+ *
+ * @alt
+ * a 3D box is centered on a grid in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z. the grid and icon disappear when the
+ * spacebar is pressed.
+ *
+ * @example
+ *
+ * @alt
+ * a 3D box is centered in a 3D sketch. an icon
+ * indicates the direction of each axis: a red line points +X,
+ * a green line +Y, and a blue line +Z.
+ *
+ * @example
+ *
+ * @alt
+ * evenly distributed light across a sphere
+ * evenly distributed light across a rotating sphere
+ */
+ /**
+ * @method ambientLight
+ * @param {Number} gray a gray value
+ * @param {Number} [alpha]
+ * @chainable
+ */
+
+ /**
+ * @method ambientLight
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ * @chainable
+ */
+
+ /**
+ * @method ambientLight
+ * @param {p5.Color} color the ambient light color
+ * @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;
+ };
+
+ /**
+ * Set's the color of the specular highlight when using a specular material and
+ * specular light.
+ *
+ * This method can be combined with specularMaterial() and shininess()
+ * functions to set specular highlights. The default color is white, ie
+ * (255, 255, 255), which is used if this method is not called before
+ * specularMaterial(). If this method is called without specularMaterial(),
+ * There will be no effect.
+ *
+ * Note: specularColor is equivalent to the processing function
+ * lightSpecular.
+ *
+ * @method specularColor
+ * @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
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * different specular light sources from top and bottom of canvas
+ */
+
+ /**
+ * @method specularColor
+ * @param {String} value a color string
+ * @chainable
+ */
+
+ /**
+ * @method specularColor
+ * @param {Number} gray a gray value
+ * @chainable
+ */
+
+ /**
+ * @method specularColor
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ * @chainable
+ */
+
+ /**
+ * @method specularColor
+ * @param {p5.Color} color the ambient light color
+ * @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 directional light with a color and a direction
+ *
+ * A maximum of 5 directionalLight can be active at one time
+ * @method directionalLight
+ * @param {Number} v1 red or hue value (depending on the current
+ * color mode),
+ * @param {Number} v2 green or saturation value
+ * @param {Number} v3 blue or brightness value
+ * @param {p5.Vector} position the direction of the light
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * the light is partially ambient and partially directional
+ */
+ _main.default.prototype.lights = function() {
+ this._assert3d('lights');
+ this.ambientLight(128, 128, 128);
+ this.directionalLight(128, 128, 128, 0, 0, -1);
+ return this;
+ };
+
+ /**
+ * Sets the falloff rates for point lights. It affects only the elements which are created after it in the code.
+ * The default value is lightFalloff(1.0, 0.0, 0.0), and the parameters are used to calculate the falloff with the following equation:
+ *
+ * d = distance from light position to vertex position
+ *
+ * falloff = 1 / (CONSTANT + d \* LINEAR + ( d \* d ) \* QUADRATIC)
+ *
+ * @method lightFalloff
+ * @param {Number} constant constant value for determining falloff
+ * @param {Number} linear linear value for determining falloff
+ * @param {Number} quadratic quadratic value for determining falloff
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Two spheres with different falloff values show different intensity of light
+ */
+ _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 spotlight with a given color, position, direction of light,
+ * angle and concentration. Here, angle refers to the opening or aperture
+ * of the cone of the spotlight, and concentration is used to focus the
+ * light towards the center. Both angle and concentration are optional, but if
+ * you want to provide concentration, you will also have to specify the angle.
+ *
+ * A maximum of 5 spotLight can be active at one time
+ * @method spotLight
+ * @param {Number} v1 red or hue value (depending on the current
+ * color mode),
+ * @param {Number} v2 green or saturation value
+ * @param {Number} v3 blue or brightness value
+ * @param {Number} x x axis position
+ * @param {Number} y y axis position
+ * @param {Number} z z axis position
+ * @param {Number} rx x axis direction of light
+ * @param {Number} ry y axis direction of light
+ * @param {Number} rz z axis direction of light
+ * @param {Number} [angle] optional parameter for angle. Defaults to PI/3
+ * @param {Number} [conc] optional parameter for concentration. Defaults to 100
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * @alt
+ * Two spheres showing different colors
+ */
+ _main.default.prototype.noLights = function() {
+ this._assert3d('noLights');
+ _main.default._validateParameters('noLights', arguments);
+
+ 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;
+
+ return this;
+ };
+ var _default = _main.default;
+ exports.default = _default;
+ },
+ { '../core/main': 54 }
+ ],
+ 100: [
+ function(_dereq_, module, exports) {
+ 'use strict';
+ Object.defineProperty(exports, '__esModule', { value: true });
+ exports.default = void 0;
+
+ var _main = _interopRequireDefault(_dereq_('../core/main'));
+ _dereq_('./p5.Geometry');
+ function _interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : { default: obj };
+ }
+ /**
+ * @module Shape
+ * @submodule 3D Models
+ * @for p5
+ * @requires core
+ * @requires p5.Geometry
+ */ /**
+ * Load a 3d model from an OBJ or STL file.
+ *
+ * loadModel() should be placed inside of preload().
+ * This allows the model to load fully before the rest of your code is run.
+ *
+ * One of the limitations of the OBJ and STL format is that it doesn't have a built-in
+ * sense of scale. This means that models exported from different programs might
+ * be very different sizes. If your model isn't displaying, try calling
+ * loadModel() with the normalized parameter set to true. This will resize the
+ * model to a scale appropriate for p5. You can also make additional changes to
+ * the final size of your model with the scale() function.
+ *
+ * Also, the support for colored STL files is not present. STL files with color will be
+ * rendered without color properties.
+ *
+ * @method loadModel
+ * @param {String} path Path of the model to be loaded
+ * @param {Boolean} normalize If true, scale the model to a
+ * standardized size when loading
+ * @param {function(p5.Geometry)} [successCallback] Function to be called
+ * once the model is loaded. Will be passed
+ * the 3D model object.
+ * @param {function(Event)} [failureCallback] called with event error if
+ * the model fails to load.
+ * @param {String} [fileType] The file extension of the model
+ * (.stl, .obj).
+ * @return {p5.Geometry} the p5.Geometry object
+ *
+ * @example
+ *
+ *
+ * //draw a spinning teapot
+ * let teapot;
+ *
+ * function preload() {
+ * // Load model with normalise parameter set to true
+ * teapot = loadModel('assets/teapot.obj', true);
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * scale(0.4); // Scaled to make model fit into canvas
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * normalMaterial(); // For effect
+ * model(teapot);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Vertically rotating 3-d teapot with red, green and blue gradient.
+ */ /**
+ * @method loadModel
+ * @param {String} path
+ * @param {function(p5.Geometry)} [successCallback]
+ * @param {function(Event)} [failureCallback]
+ * @param {String} [fileType]
+ * @return {p5.Geometry} the p5.Geometry object
+ */ _main.default.prototype.loadModel = function(path) {
+ _main.default._validateParameters('loadModel', arguments);
+ var normalize;
+ var successCallback;
+ var failureCallback;
+ var fileType = path.slice(-4);
+ if (typeof arguments[1] === 'boolean') {
+ normalize = arguments[1];
+ successCallback = arguments[2];
+ failureCallback = arguments[3];
+ if (typeof arguments[4] !== 'undefined') {
+ fileType = arguments[4];
+ }
+ } else {
+ normalize = false;
+ successCallback = arguments[1];
+ 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;
+
+ if (fileType.match(/\.stl$/i)) {
+ this.httpDo(
+ path,
+ 'GET',
+ 'arrayBuffer',
+ function(arrayBuffer) {
+ parseSTL(model, arrayBuffer);
+
+ if (normalize) {
+ model.normalize();
+ }
+ self._decrementPreload();
+ if (typeof successCallback === 'function') {
+ successCallback(model);
+ }
+ },
+ failureCallback
+ );
+ } else if (fileType.match(/\.obj$/i)) {
+ this.loadStrings(
+ path,
+ function(strings) {
+ parseObj(model, strings);
+
+ if (normalize) {
+ model.normalize();
+ }
+
+ self._decrementPreload();
+ if (typeof successCallback === 'function') {
+ successCallback(model);
+ }
+ },
+ failureCallback
+ );
+ } else {
+ _main.default._friendlyFileLoadError(3, path);
+
+ if (failureCallback) {
+ failureCallback();
+ } else {
+ console.error(
+ 'Sorry, the file type is invalid. Only OBJ and STL files are supported.'
+ );
+ }
+ }
+ return model;
+ };
+
+ /**
+ * 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) {
+ // 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: []
+ };
+
+ var indexedVerts = {};
+
+ 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] === '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.
+ var texVertex = [parseFloat(tokens[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 vertIndex = 0;
+
+ // 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.
+
+ if (indexedVerts[vertString] !== undefined) {
+ vertIndex = indexedVerts[vertString];
+ } else {
+ var vertParts = vertString.split('/');
+ for (var i = 0; i < vertParts.length; i++) {
+ vertParts[i] = parseInt(vertParts[i]) - 1;
+ }
+
+ vertIndex = indexedVerts[vertString] = model.vertices.length;
+ model.vertices.push(loadedVerts.v[vertParts[0]].copy());
+ if (loadedVerts.vt[vertParts[1]]) {
+ model.uvs.push(loadedVerts.vt[vertParts[1]].slice());
+ } else {
+ model.uvs.push([0, 0]);
+ }
+
+ if (loadedVerts.vn[vertParts[2]]) {
+ model.vertexNormals.push(loadedVerts.vn[vertParts[2]].copy());
+ }
+ }
+
+ face.push(vertIndex);
+ }
+
+ if (face[0] !== face[1] && face[0] !== face[2] && face[1] !== face[2]) {
+ model.faces.push(face);
+ }
+ }
+ }
+ }
+ }
+ // If the model doesn't have normals, compute the normals
+ if (model.vertexNormals.length === 0) {
+ model.computeNormals();
+ }
+
+ 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) === 0x434f4c4f /*COLO*/ &&
+ reader.getUint8(index + 4) === 0x52 /*'R'*/ &&
+ reader.getUint8(index + 5) === 0x3d /*'='*/
+ ) {
+ 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 & 0x8000) === 0) {
+ // facet has its own unique color
+ r = (packedColor & 0x1f) / 31;
+ g = ((packedColor >> 5) & 0x1f) / 31;
+ b = ((packedColor >> 10) & 0x1f) / 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;
+ }
+
+ /**
+ * Render a 3d model to the screen.
+ *
+ * @method model
+ * @param {p5.Geometry} model Loaded 3d model to be rendered
+ * @example
+ *
+ *
+ * @alt
+ * zooming Mandelbrot set. a colorful, infinitely detailed fractal.
+ */ _main.default.prototype.loadShader = function(
+ vertFilename,
+ fragFilename,
+ callback,
+ errorCallback
+ ) {
+ _main.default._validateParameters('loadShader', arguments);
+ if (!errorCallback) {
+ errorCallback = console.error;
+ }
+
+ var loadedShader = new _main.default.Shader();
+
+ var self = this;
+ var loadedFrag = false;
+ var loadedVert = false;
+
+ var onLoad = function onLoad() {
+ self._decrementPreload();
+ if (callback) {
+ callback(loadedShader);
+ }
+ };
+
+ this.loadStrings(
+ vertFilename,
+ function(result) {
+ loadedShader._vertSrc = result.join('\n');
+ loadedVert = true;
+ if (loadedFrag) {
+ onLoad();
+ }
+ },
+ errorCallback
+ );
+
+ this.loadStrings(
+ fragFilename,
+ function(result) {
+ loadedShader._fragSrc = result.join('\n');
+ loadedFrag = true;
+ if (loadedVert) {
+ onLoad();
+ }
+ },
+ errorCallback
+ );
+
+ return loadedShader;
+ };
+
+ /**
+ * @method createShader
+ * @param {String} vertSrc source code for the vertex shader
+ * @param {String} fragSrc source code for the fragment shader
+ * @returns {p5.Shader} a shader object created from the provided
+ * vertex and fragment shaders.
+ *
+ * @example
+ *
+ *
+ * // the 'varying's are shared between both vertex & fragment shaders
+ * let varying = 'precision highp float; varying vec2 vPos;';
+ *
+ * // the vertex shader is called for each vertex
+ * let vs =
+ * varying +
+ * 'attribute vec3 aPosition;' +
+ * 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';
+ *
+ * // the fragment shader is called for each pixel
+ * let fs =
+ * varying +
+ * 'uniform vec2 p;' +
+ * 'uniform float r;' +
+ * 'const int I = 500;' +
+ * 'void main() {' +
+ * ' vec2 c = p + vPos * r, z = c;' +
+ * ' float n = 0.0;' +
+ * ' for (int i = I; i > 0; i --) {' +
+ * ' if(z.x*z.x+z.y*z.y > 4.0) {' +
+ * ' n = float(i)/float(I);' +
+ * ' 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 mandel;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ *
+ * // create and initialize the shader
+ * mandel = createShader(vs, fs);
+ * shader(mandel);
+ * noStroke();
+ *
+ * // 'p' is the center point of the Mandelbrot image
+ * mandel.setUniform('p', [-0.74364388703, 0.13182590421]);
+ * }
+ *
+ * function draw() {
+ * // 'r' is the size of the image in Mandelbrot-space
+ * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));
+ * quad(-1, -1, 1, -1, 1, 1, -1, 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * zooming Mandelbrot set. a colorful, infinitely detailed fractal.
+ */
+ _main.default.prototype.createShader = function(vertSrc, fragSrc) {
+ this._assert3d('createShader');
+ _main.default._validateParameters('createShader', arguments);
+ return new _main.default.Shader(this._renderer, vertSrc, fragSrc);
+ };
+
+ /**
+ * The shader() function lets the user provide a custom shader
+ * to fill in shapes in WEBGL mode. Users can create their
+ * own shaders by loading vertex and fragment shaders with
+ * loadShader().
+ *
+ * @method shader
+ * @chainable
+ * @param {p5.Shader} [s] the desired p5.Shader to use for rendering
+ * shapes.
+ *
+ * @example
+ *
+ *
+ * // Click within the image to toggle
+ * // the shader used by the quad shape
+ * // Note: for an alternative approach to the same example,
+ * // involving changing uniforms please refer to:
+ * // https://p5js.org/reference/#/p5.Shader/setUniform
+ *
+ * let redGreen;
+ * let orangeBlue;
+ * let showRedGreen = false;
+ *
+ * function preload() {
+ * // note that we are using two instances
+ * // of the same vertex and fragment shaders
+ * 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 colors for redGreen shader
+ * shader(redGreen);
+ * redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]);
+ * redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]);
+ *
+ * // initialize the colors for orangeBlue shader
+ * shader(orangeBlue);
+ * orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]);
+ * orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]);
+ *
+ * noStroke();
+ * }
+ *
+ * function draw() {
+ * // update the offset values for each shader,
+ * // moving orangeBlue in vertical and redGreen
+ * // in horizontal direction
+ * orangeBlue.setUniform('offset', [0, sin(millis() / 2000) + 1]);
+ * redGreen.setUniform('offset', [sin(millis() / 2000), 1]);
+ *
+ * if (showRedGreen === true) {
+ * shader(redGreen);
+ * } else {
+ * shader(orangeBlue);
+ * }
+ * quad(-1, -1, 1, -1, 1, 1, -1, 1);
+ * }
+ *
+ * function mouseClicked() {
+ * showRedGreen = !showRedGreen;
+ * }
+ *
+ *
+ *
+ * @alt
+ * canvas toggles between a circular gradient of orange and blue vertically. and a circular gradient of red and green moving horizontally when mouse is clicked/pressed.
+ */
+ _main.default.prototype.shader = function(s) {
+ this._assert3d('shader');
+ _main.default._validateParameters('shader', arguments);
+
+ if (s._renderer === undefined) {
+ s._renderer = this._renderer;
+ }
+
+ if (s.isStrokeShader()) {
+ this._renderer.userStrokeShader = s;
+ } else {
+ this._renderer.userFillShader = s;
+ this._renderer._useNormalMaterial = false;
+ }
+
+ s.init();
+
+ return this;
+ };
+
+ /**
+ * This function restores the default shaders in WEBGL mode. Code that runs
+ * after resetShader() will not be affected by previously defined
+ * shaders. Should be run after shader().
+ *
+ * @method resetShader
+ * @chainable
+ */
+ _main.default.prototype.resetShader = function() {
+ this._renderer.userFillShader = this._renderer.userStrokeShader = null;
+ return this;
+ };
+
+ /**
+ * Normal material for geometry is a material that is not affected by light.
+ * It is not reflective and is a placeholder material often used for debugging.
+ * Surfaces facing the X-axis, become red, those facing the Y-axis, become green and those facing the Z-axis, become blue.
+ * You can view all possible materials in this
+ * example.
+ * @method normalMaterial
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * Rotating view of many images umbrella and grid roof on a 3d plane
+ * black canvas
+ * black canvas
+ */
+ _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._useSpecularMaterial = false;
+ this._renderer._useEmissiveMaterial = false;
+ this._renderer._useNormalMaterial = false;
+ this._renderer._tex = tex;
+ this._renderer._setProperty('_doFill', true);
+
+ return this;
+ };
+
+ /**
+ * Sets the coordinate space for texture mapping. The default mode is IMAGE
+ * which refers to the actual coordinates of the image.
+ * NORMAL refers to a normalized space of values ranging from 0 to 1.
+ * This function only works in WEBGL mode.
+ *
+ * With IMAGE, if an image is 100 x 200 pixels, mapping the image onto the entire
+ * size of a quad would require the points (0,0) (100, 0) (100,200) (0,200).
+ * The same mapping in NORMAL is (0,0) (1,0) (1,1) (0,1).
+ * @method textureMode
+ * @param {Constant} mode either IMAGE or NORMAL
+ * @example
+ *
+ *
+ * @alt
+ * the underside of a white umbrella and gridded ceiling above
+ */
+ _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;
+ }
+ };
+
+ /**
+ * Sets the global 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.
+ *
+ * CLAMP causes the pixels at the edge of the texture to extend to the bounds
+ * REPEAT causes the texture to tile repeatedly until reaching the bounds
+ * MIRROR works similarly to REPEAT but it flips the texture with every new tile
+ *
+ * REPEAT & MIRROR are only available if the texture
+ * is a power of two size (128, 256, 512, 1024, etc.).
+ *
+ * This method will affect all textures in your sketch until a subsequent
+ * textureWrap call is made.
+ *
+ * If only one argument is provided, it will be applied to both the
+ * horizontal and vertical axes.
+ * @method textureWrap
+ * @param {Constant} wrapX either CLAMP, REPEAT, or MIRROR
+ * @param {Constant} [wrapY] either CLAMP, REPEAT, or MIRROR
+ * @example
+ *
+ *
+ * @alt
+ * an image of the rocky mountains repeated in mirrored tiles
+ */
+ _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 textures = this._renderer.textures;
+ for (var i = 0; i < textures.length; i++) {
+ textures[i].setWrapMode(wrapX, wrapY);
+ }
+ };
+
+ /**
+ * Ambient material for geometry with a given color. Ambient material defines the color the object reflects under any lighting.
+ * For example, if the ambient material of an object is pure red, but the ambient lighting only contains green, the object will not reflect any light.
+ * Here's an example containing all possible materials.
+ * @method ambientMaterial
+ * @param {Number} v1 gray value, red or hue value
+ * (depending on the current color mode),
+ * @param {Number} [v2] green or saturation value
+ * @param {Number} [v3] blue or brightness value
+ * @chainable
+ * @example
+ *
+ *
+ * // ambientLight is both red and blue (magenta),
+ * // so object only reflects it's red and blue components
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(70);
+ * ambientLight(100); // white light
+ * ambientMaterial(255, 0, 255); // pink material
+ * box(30);
+ * }
+ *
+ *
+ *
+ *
+ * // ambientLight is green. Since object does not contain
+ * // green, it does not reflect any light
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(70);
+ * ambientLight(0, 255, 0); // green light
+ * ambientMaterial(255, 0, 255); // pink material
+ * box(30);
+ * }
+ *
+ *
+ * @alt
+ * radiating light source from top right of canvas
+ * box reflecting only red and blue light
+ * box reflecting no light
+ */
+ /**
+ * @method ambientMaterial
+ * @param {Number[]|String|p5.Color} color color, color Array, or CSS color 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.curFillColor = color._array;
+ this._renderer._useSpecularMaterial = false;
+ this._renderer._useEmissiveMaterial = false;
+ this._renderer._useNormalMaterial = false;
+ this._renderer._enableLighting = true;
+ this._renderer._tex = null;
+
+ return this;
+ };
+
+ /**
+ * Sets the emissive color of the material used for geometry drawn to
+ * the screen. This is a misnomer in the sense that the material does not
+ * actually emit light that effects surrounding polygons. Instead,
+ * it gives the appearance that the object is glowing. An emissive material
+ * will display at full strength even if there is no light for it to reflect.
+ * @method emissiveMaterial
+ * @param {Number} v1 gray value, red or hue value
+ * (depending on the current color mode),
+ * @param {Number} [v2] green or saturation value
+ * @param {Number} [v3] blue or brightness value
+ * @param {Number} [a] opacity
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * radiating light source from top right of canvas
+ */
+ /**
+ * @method emissiveMaterial
+ * @param {Number[]|String|p5.Color} color color, color Array, or CSS color 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.curFillColor = color._array;
+ this._renderer._useSpecularMaterial = false;
+ this._renderer._useEmissiveMaterial = true;
+ this._renderer._useNormalMaterial = false;
+ this._renderer._enableLighting = true;
+ this._renderer._tex = null;
+
+ return this;
+ };
+
+ /**
+ * Specular material for geometry with a given color. Specular material is a shiny reflective material.
+ * Like ambient material it also defines the color the object reflects under ambient lighting.
+ * For example, if the specular material of an object is pure red, but the ambient lighting only contains green, the object will not reflect any light.
+ * For all other types of light like point and directional light, a specular material will reflect the color of the light source to the viewer.
+ * Here's an example containing all possible materials.
+ *
+ * @method specularMaterial
+ * @param {Number} gray number specifying value between white and black.
+ * @param {Number} [alpha] alpha value relative to current color range
+ * (default is 0-255)
+ * @chainable
+ */
+
+ /**
+ * @method specularMaterial
+ * @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]
+ * @chainable
+ *
+ * @example
+ *
+ * @alt
+ * Shininess on Camera changes position with mouse
+ */
+ _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;
+ };
+
+ /**
+ * @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 [description]
+ * @return {Number[]]} Normalized numbers array
+ */
+ _main.default.RendererGL.prototype._applyColorBlend = function(colors) {
+ var gl = this.GL;
+
+ var isTexture = this.drawMode === constants.TEXTURE;
+ var doBlend = isTexture || colors[colors.length - 1] < 1.0 || 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:
+ case constants.ADD:
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
+ break;
+ case constants.REMOVE:
+ gl.blendEquation(gl.FUNC_REVERSE_SUBTRACT);
+ gl.blendFunc(gl.SRC_ALPHA, gl.DST_ALPHA);
+ break;
+ case constants.MULTIPLY:
+ gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
+ gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ONE, gl.ONE);
+ break;
+ case constants.SCREEN:
+ gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
+ gl.blendFuncSeparate(gl.ONE_MINUS_DST_COLOR, gl.ONE, gl.ONE, gl.ONE);
+ 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.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE);
+ break;
+ case constants.DARKEST:
+ if (this.blendExt) {
+ gl.blendEquationSeparate(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_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': 43, '../core/main': 54, './p5.Texture': 110 }
+ ],
+ 102: [
+ 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 Lights, Camera
+ * @submodule Camera
+ * @requires core
+ */
+ // p5.Prototype Methods
+ ////////////////////////////////////////////////////////////////////////////////
+ /**
+ * Sets the camera position for a 3D sketch. Parameters for this function define
+ * the position for the camera, the center of the sketch (where the camera is
+ * pointing), and an up direction (the orientation of the camera).
+ *
+ * This function simulates the movements of the camera, allowing objects to be
+ * viewed from various angles. Remember, it does not move the objects themselves
+ * but the camera instead. For example when centerX value is positive, the camera
+ * is rotating to the right side of the sketch, so the object would seem like
+ * moving to the left.
+ *
+ * See this example
+ * to view the position of your camera.
+ *
+ * When called with no arguments, this function creates a default camera
+ * equivalent to
+ * camera(0, 0, (height/2.0) / tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0);
+ * @method camera
+ * @constructor
+ * @for p5
+ * @param {Number} [x] camera position value on x axis
+ * @param {Number} [y] camera position value on y axis
+ * @param {Number} [z] camera position value on z axis
+ * @param {Number} [centerX] x coordinate representing center of the sketch
+ * @param {Number} [centerY] y coordinate representing center of the sketch
+ * @param {Number} [centerZ] z coordinate representing center of the sketch
+ * @param {Number} [upX] x component of direction 'up' from camera
+ * @param {Number} [upY] y component of direction 'up' from camera
+ * @param {Number} [upZ] z component of direction 'up' from camera
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(204);
+ * //move the camera away from the plane by a sin wave
+ * camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0);
+ * plane(10, 10);
+ * }
+ *
+ *
+ *
+ * @example
+ *
+ *
+ * //move slider to see changes!
+ * //sliders control the first 6 parameters of camera()
+ * let sliderGroup = [];
+ * let X;
+ * let Y;
+ * let Z;
+ * let centerX;
+ * let centerY;
+ * let centerZ;
+ * let h = 20;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * //create sliders
+ * for (var i = 0; i < 6; i++) {
+ * if (i === 2) {
+ * sliderGroup[i] = createSlider(10, 400, 200);
+ * } else {
+ * sliderGroup[i] = createSlider(-400, 400, 0);
+ * }
+ * h = map(i, 0, 6, 5, 85);
+ * sliderGroup[i].position(10, height + h);
+ * sliderGroup[i].style('width', '80px');
+ * }
+ * }
+ *
+ * function draw() {
+ * background(60);
+ * // assigning sliders' value to each parameters
+ * X = sliderGroup[0].value();
+ * Y = sliderGroup[1].value();
+ * Z = sliderGroup[2].value();
+ * centerX = sliderGroup[3].value();
+ * centerY = sliderGroup[4].value();
+ * centerZ = sliderGroup[5].value();
+ * camera(X, Y, Z, centerX, centerY, centerZ, 0, 1, 0);
+ * stroke(255);
+ * fill(255, 102, 94);
+ * box(85);
+ * }
+ *
+ *
+ * @alt
+ * White square repeatedly grows to fill canvas and then shrinks.
+ * An interactive example of a red cube with 3 sliders for moving it across x, y,
+ * z axis and 3 sliders for shifting it's center.
+ */ _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 camera in a 3D sketch. This projection
+ * represents depth through foreshortening: objects that are close to the camera
+ * appear their actual size while those that are further away from the camera
+ * appear smaller. The parameters to this function define the viewing frustum
+ * (the truncated pyramid within which objects are seen by the camera) through
+ * vertical field of view, aspect ratio (usually width/height), and near and far
+ * clipping planes.
+ *
+ * When called with no arguments, the defaults
+ * provided are equivalent to
+ * perspective(PI/3.0, width/height, eyeZ/10.0, eyeZ*10.0), where eyeZ
+ * is equal to ((height/2.0) / tan(PI*60.0/360.0));
+ * @method perspective
+ * @for p5
+ * @param {Number} [fovy] camera frustum vertical field of view,
+ * from bottom to top of view, in angleMode units
+ * @param {Number} [aspect] camera frustum aspect ratio
+ * @param {Number} [near] frustum near plane length
+ * @param {Number} [far] frustum far plane length
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * two colored 3D boxes move back and forth, rotating as mouse is dragged.
+ */
+ _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;
+ };
+
+ /**
+ * Sets an orthographic projection for the camera in a 3D sketch and defines a
+ * box-shaped viewing frustum within which objects are seen. In this projection,
+ * all objects with the same dimension appear the same size, regardless of
+ * whether they are near or far from the camera. The parameters to this
+ * function specify the viewing frustum where left and right are the minimum and
+ * maximum x values, top and bottom are the minimum and maximum y values, and near
+ * and far are the minimum and maximum z values. If no parameters are given, the
+ * default is used: ortho(-width/2, width/2, -height/2, height/2).
+ * @method ortho
+ * @for p5
+ * @param {Number} [left] camera frustum left plane
+ * @param {Number} [right] camera frustum right plane
+ * @param {Number} [bottom] camera frustum bottom plane
+ * @param {Number} [top] camera frustum top plane
+ * @param {Number} [near] camera frustum near plane
+ * @param {Number} [far] camera frustum far plane
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * two 3D boxes move back and forth along same plane, rotating as mouse is dragged.
+ */
+ _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 a perspective matrix as defined by the parameters.
+ *
+ * A frustum is a geometric form: a pyramid with its top
+ * cut off. With the viewer's eye at the imaginary top of
+ * the pyramid, the six planes of the frustum act as clipping
+ * planes when rendering a 3D view. Thus, any form inside the
+ * clipping planes is visible; anything outside
+ * those planes is not visible.
+ *
+ * Setting the frustum changes the perspective of the scene being rendered.
+ * This can be achieved more simply in many cases by using
+ * perspective().
+ *
+ * @method frustum
+ * @for p5
+ * @param {Number} [left] camera frustum left plane
+ * @param {Number} [right] camera frustum right plane
+ * @param {Number} [bottom] camera frustum bottom plane
+ * @param {Number} [top] camera frustum top plane
+ * @param {Number} [near] camera frustum near plane
+ * @param {Number} [far] camera frustum far plane
+ * @chainable
+ * @example
+ *
+ *
+ * @alt
+ * two 3D boxes move back and forth along same plane, rotating as mouse is dragged.
+ */
+ _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 tells the
+ * renderer to use that camera.
+ * Returns the p5.Camera object.
+ * @method createCamera
+ * @return {p5.Camera} The newly created camera object.
+ * @for p5
+ * @example
+ *
+ * // Creates a camera object and animates it around a box.
+ * let camera;
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * background(0);
+ * camera = createCamera();
+ * setCamera(camera);
+ * }
+ *
+ * function draw() {
+ * camera.lookAt(0, 0, 0);
+ * camera.setPosition(sin(frameCount / 60) * 200, 0, 100);
+ * box(20);
+ * }
+ *
+ *
+ * @alt
+ * An example that creates a camera and moves it around the box.
+ */
+ _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;
+ };
+
+ /**
+ * This class describes a camera for use in p5's
+ *
+ * WebGL mode. It contains camera position, orientation, and projection
+ * information necessary for rendering a 3D scene.
+ *
+ * New p5.Camera objects can be made through the
+ * createCamera() function and controlled through
+ * the methods described below. A camera created in this way will use a default
+ * position in the scene and a default perspective projection until these
+ * properties are changed through the various methods available. It is possible
+ * to create multiple cameras, in which case the current camera
+ * can be set through the setCamera() method.
+ *
+ * Note:
+ * The methods below operate in two coordinate systems: the 'world' coordinate
+ * system describe positions in terms of their relationship to the origin along
+ * the X, Y and Z axes whereas the camera's 'local' coordinate system
+ * describes positions from the camera's point of view: left-right, up-down,
+ * and forward-backward. The move() method,
+ * for instance, moves the camera along its own axes, whereas the
+ * setPosition()
+ * method sets the camera's position in world-space.
+ *
+ * @class p5.Camera
+ * @param {rendererGL} rendererGL instance of WebGL renderer
+ * @example
+ *
+ *
+ * @alt
+ * camera view pans left and right across a series of rotating 3D boxes.
+ */
+ _main.default.Camera.prototype.pan = function(amount) {
+ var local = this._getLocalAxes();
+ this._rotateView(amount, local.y[0], local.y[1], local.y[2]);
+ };
+
+ /**
+ * Tilting rotates the camera view up and down.
+ * @method tilt
+ * @param {Number} angle amount to rotate camera in current
+ * angleMode units.
+ * Greater than 0 values rotate counterclockwise (to the left).
+ * @example
+ *
+ *
+ * @alt
+ * camera view tilts up and down across a series of rotating 3D boxes.
+ */
+ _main.default.Camera.prototype.tilt = function(amount) {
+ var local = this._getLocalAxes();
+ this._rotateView(amount, local.x[0], local.x[1], local.x[2]);
+ };
+
+ /**
+ * Reorients the camera to look at a position in world space.
+ * @method lookAt
+ * @for p5.Camera
+ * @param {Number} x x position of a point in world space
+ * @param {Number} y y position of a point in world space
+ * @param {Number} z z position of a point in world space
+ * @example
+ *
+ *
+ * @alt
+ * camera view of rotating 3D cubes changes to look at a new random
+ * point every second .
+ */
+ _main.default.Camera.prototype.lookAt = function(x, y, z) {
+ this.camera(
+ this.eyeX,
+ this.eyeY,
+ this.eyeZ,
+ x,
+ y,
+ z,
+ this.upX,
+ this.upY,
+ this.upZ
+ );
+ };
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Camera Position Methods
+ ////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Sets a camera's position and orientation. This is equivalent to calling
+ * camera() on a p5.Camera object.
+ * @method camera
+ * @for p5.Camera
+ */
+ _main.default.Camera.prototype.camera = function(
+ 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;
+
+ this.centerX = centerX;
+ this.centerY = centerY;
+ this.centerZ = centerZ;
+
+ 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.
+ // prettier-ignore
+ 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);
+
+ var tx = -eyeX;
+ var ty = -eyeY;
+ var tz = -eyeZ;
+
+ this.cameraMatrix.translate([tx, ty, tz]);
+
+ if (this._isActive()) {
+ this._renderer.uMVMatrix.set(
+ this.cameraMatrix.mat4[0],
+ this.cameraMatrix.mat4[1],
+ this.cameraMatrix.mat4[2],
+ this.cameraMatrix.mat4[3],
+ this.cameraMatrix.mat4[4],
+ this.cameraMatrix.mat4[5],
+ this.cameraMatrix.mat4[6],
+ this.cameraMatrix.mat4[7],
+ this.cameraMatrix.mat4[8],
+ this.cameraMatrix.mat4[9],
+ this.cameraMatrix.mat4[10],
+ this.cameraMatrix.mat4[11],
+ this.cameraMatrix.mat4[12],
+ this.cameraMatrix.mat4[13],
+ this.cameraMatrix.mat4[14],
+ this.cameraMatrix.mat4[15]
+ );
+ }
+ return this;
+ };
+
+ /**
+ * Move camera along its local axes while maintaining current camera orientation.
+ * @method move
+ * @param {Number} x amount to move along camera's left-right axis
+ * @param {Number} y amount to move along camera's up-down axis
+ * @param {Number} z amount to move along camera's forward-backward axis
+ * @example
+ *
+ *
+ * // see the camera move along its own axes while maintaining its orientation
+ * let cam;
+ * let delta = 0.5;
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * normalMaterial();
+ * cam = createCamera();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // move the camera along its local axes
+ * cam.move(delta, delta, 0);
+ *
+ * // every 100 frames, switch direction
+ * if (frameCount % 150 === 0) {
+ * delta *= -1;
+ * }
+ *
+ * translate(-10, -10, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * translate(15, 15, 0);
+ * box(50, 8, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * camera view moves along a series of 3D boxes, maintaining the same
+ * orientation throughout the move
+ */
+ _main.default.Camera.prototype.move = function(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],
+ 0,
+ 1,
+ 0
+ );
+ };
+
+ /**
+ * Set camera position in world-space while maintaining current camera
+ * orientation.
+ * @method setPosition
+ * @param {Number} x x position of a point in world space
+ * @param {Number} y y position of a point in world space
+ * @param {Number} z z position of a point in world space
+ * @example
+ *
+ *
+ * @alt
+ * black canvas with purple cube spinning
+ */
+ _main.default.RendererGL.prototype.fill = function(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
+ *